初始版本:基于 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
+17
@@ -0,0 +1,17 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.pyd
|
||||||
|
*.egg-info/
|
||||||
|
build/
|
||||||
|
dist/
|
||||||
|
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
env/
|
||||||
|
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
*.log
|
||||||
|
*.tmp
|
||||||
|
*.bak
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
# DHT 聊天(DHT Chat)
|
||||||
|
|
||||||
|
一个**完全去中心化**的 Windows 桌面聊天软件:没有服务器、没有账号系统,
|
||||||
|
节点之间通过 Kademlia DHT 互相发现、交换消息,聊天室历史也复制在 DHT 上。
|
||||||
|
|
||||||
|
- 纯 Python 3 标准库实现,**零第三方依赖**(唯一要求:安装 Python 时带上 tkinter)
|
||||||
|
- 图形界面基于 Tkinter,双击 `start.bat` 即可运行
|
||||||
|
- 支持**公共聊天室**(多人)与**一对一私聊**(X25519 + AEAD 端到端加密)
|
||||||
|
- 同一局域网内自动发现彼此;跨网段可手动交换引导地址
|
||||||
|
- 支持 UDP 分片,单条记录上限 1 MiB,长聊天记录也能同步
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、快速开始
|
||||||
|
|
||||||
|
### 1. 前置条件
|
||||||
|
|
||||||
|
- Windows 10 / 11
|
||||||
|
- Python 3.10 或更高版本(开发与测试使用 3.13)
|
||||||
|
|
||||||
|
安装 Python 时请勾选 **Add python.exe to PATH**(同时默认会装上 tkinter)。
|
||||||
|
检查是否可用:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
py -3 --version
|
||||||
|
py -3 -c "import tkinter"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 启动
|
||||||
|
|
||||||
|
**双击 `start.bat`** 即可(出错时会暂停窗口,方便看提示)。
|
||||||
|
也可以在命令行里运行:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
run.cmd
|
||||||
|
```
|
||||||
|
|
||||||
|
`run.cmd` 会自动优先使用 `py -3`,找不到时退回 `python`,所有参数原样透传:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
run.cmd --nick 小明
|
||||||
|
run.cmd -b 192.168.1.7:47800
|
||||||
|
run.cmd --no-gui
|
||||||
|
```
|
||||||
|
|
||||||
|
或者直接调用模块:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
py -3 -m dhtchat
|
||||||
|
```
|
||||||
|
|
||||||
|
首次启动会要求输入昵称,然后自动加入公共聊天室「大厅」。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、界面说明
|
||||||
|
|
||||||
|
| 区域 | 作用 |
|
||||||
|
| --- | --- |
|
||||||
|
| 顶部工具栏 | 修改昵称、填写「引导地址」并点「连接」、复制我的地址、查找用户 |
|
||||||
|
| 左侧「会话」 | 聊天室与私聊会话列表(「详情」列是消息条数),单击切换;下方「加入聊天室」「发起私聊」 |
|
||||||
|
| 左侧「已知节点」 | 已发现的节点及地址,**双击某人即可直接开私聊** |
|
||||||
|
| 中间窗口 | 聊天记录(自己的消息蓝色、他人黑色、系统提示橙色、错误红色) |
|
||||||
|
| 底部输入框 | 输入内容后回车发送;按 ↑ 可翻出历史输入 |
|
||||||
|
| 状态栏 | 我的地址、已知节点数、本地记录数、收发报文统计 |
|
||||||
|
|
||||||
|
菜单栏还提供:
|
||||||
|
|
||||||
|
- **文件**:复制我的地址 / 复制我的节点 ID / 改昵称 / 退出
|
||||||
|
- **聊天室**:加入聊天室 / 离开当前聊天室 / 重新从 DHT 拉取历史
|
||||||
|
- **网络**:添加引导节点 / 查找用户昵称 / 重新公布我的资料
|
||||||
|
- **帮助**:使用说明 / 关于(含状态目录路径)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、多台机器联机
|
||||||
|
|
||||||
|
### 情况 A:同一局域网(推荐)
|
||||||
|
|
||||||
|
两台机器在同一个网段时,程序会通过组播(`239.76.99.104:47654`)**自动发现**对方,
|
||||||
|
不需要任何配置。开窗后等几秒,左侧「已知节点」就会出现对方。
|
||||||
|
|
||||||
|
### 情况 B:不同网段 / 自动发现被防火墙拦截
|
||||||
|
|
||||||
|
1. 在 A 机上点 **「复制我的地址」**,得到形如 `192.168.1.7:47800` 的地址;
|
||||||
|
2. 在 B 机的「引导地址」输入框粘贴该地址,点 **「连接」**;
|
||||||
|
3. 连接成功后 B 机会把 A 机当作入口加入同一个 DHT,双方即可互相找到。
|
||||||
|
|
||||||
|
命令行等价写法:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
py -3 -m dhtchat -b 192.168.1.7:47800
|
||||||
|
```
|
||||||
|
|
||||||
|
`-b` 可以重复指定多个引导节点。只要网络里有**一个**可达节点,整张网就能联通。
|
||||||
|
|
||||||
|
> 提示:若开启了 Windows 防火墙,第一次运行时会弹窗询问是否允许网络访问,请选择**允许**;
|
||||||
|
> 也可以在「Windows Defender 防火墙 → 允许应用通过防火墙」里手动放行 UDP `47800` 与 `47654`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、聊天室与私聊
|
||||||
|
|
||||||
|
### 公共聊天室
|
||||||
|
|
||||||
|
1. 点「加入聊天室」输入房间名(默认「大厅」),房间名相同的人就会在同一个房间里;
|
||||||
|
2. 消息会同时通过点对点推送与 DHT 日志同步两条路径传播,**中途加入的人也能看到最近的聊天记录**;
|
||||||
|
3. 聊天区标题下方会显示当前在线成员昵称。
|
||||||
|
|
||||||
|
### 一对一私聊
|
||||||
|
|
||||||
|
1. 点「发起私聊」输入对方昵称,或直接在「已知节点」里双击对方;
|
||||||
|
2. 私聊使用 X25519 临时密钥协商 + AEAD 加密,**中继节点无法读取内容**;
|
||||||
|
3. 对方离线时会自动把消息写入 DHT 上的收件箱(`log/inbox/<节点 ID>`),
|
||||||
|
等他上线后再取出——所以先发消息、后开机也能收到。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、命令行参数
|
||||||
|
|
||||||
|
| 参数 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `-n, --nick <昵称>` | 显示昵称(默认沿用上次用过的昵称) |
|
||||||
|
| `-p, --port <端口>` | UDP 监听端口,`0` 表示随机端口(默认 `47800`) |
|
||||||
|
| `-b, --bootstrap <HOST:PORT>` | 引导节点地址,可重复指定 |
|
||||||
|
| `-r, --room <名称>` | 启动后自动加入的聊天室(默认「大厅」) |
|
||||||
|
| `--host <地址>` | 绑定的本地地址(默认 `0.0.0.0`,自动对外公布真实网卡地址) |
|
||||||
|
| `--state-dir <目录>` | 状态目录(默认 `%USERPROFILE%\.dhtchat`) |
|
||||||
|
| `--profile <名称>` | 身份配置名,可用于同一台机器同时开多个身份 |
|
||||||
|
| `--no-gui` | 使用命令行界面而不是图形界面 |
|
||||||
|
| `--no-discovery` | 关闭局域网自动发现,只用手动引导地址 |
|
||||||
|
| `-v, --verbose` | 输出调试日志 |
|
||||||
|
|
||||||
|
### 控制台模式
|
||||||
|
|
||||||
|
```bat
|
||||||
|
py -3 -m dhtchat --no-gui
|
||||||
|
```
|
||||||
|
|
||||||
|
可用命令:
|
||||||
|
|
||||||
|
```text
|
||||||
|
/join <聊天室> 加入或切换公共聊天室
|
||||||
|
/msg <昵称> <内容> 发送私聊消息
|
||||||
|
/who 列出当前聊天室成员
|
||||||
|
/peers 列出已知节点
|
||||||
|
/me 显示本机身份与地址
|
||||||
|
/help 显示本帮助
|
||||||
|
/quit 退出
|
||||||
|
```
|
||||||
|
|
||||||
|
直接输入文字即发送到当前聊天室。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、数据与状态目录
|
||||||
|
|
||||||
|
默认目录 `%USERPROFILE%\.dhtchat\default\`:
|
||||||
|
|
||||||
|
| 文件 | 内容 |
|
||||||
|
| --- | --- |
|
||||||
|
| `identity.json` | Ed25519 身份密钥(节点 ID = 公钥的 SHA-1) |
|
||||||
|
| `nickname.txt` | 上次使用的昵称 |
|
||||||
|
|
||||||
|
用 `--profile 名字` 可以并存多套身份,例如在同一台机器上开两个客户端对聊:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
run.cmd --profile a --port 47801
|
||||||
|
run.cmd --profile b --port 47802 -b 127.0.0.1:47801
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、工作原理
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
subgraph 本机
|
||||||
|
GUI[Tkinter 界面<br/>主线程] <-- 事件队列 --> APP[ChatApp<br/>后台 asyncio 线程]
|
||||||
|
APP --> CHAT[聊天层 ChatService]
|
||||||
|
CHAT --> NODE[Kademlia DHT 节点<br/>UDP + 分片]
|
||||||
|
CHAT --> CRYPTO[crypto<br/>Ed25519 / X25519 / AEAD]
|
||||||
|
end
|
||||||
|
NODE <-- UDP 报文 --> PEERS[(其它节点)]
|
||||||
|
CHAT -- 存放/读取 --> DHT[(DHT 上的<br/>聊天室日志 / 收件箱 / 用户档案)]
|
||||||
|
```
|
||||||
|
|
||||||
|
- **DHT 层**:Kademlia 路由表(160 位 ID、K=8)、`PING` / `FIND_NODE` / `FIND_VALUE` / `STORE`,
|
||||||
|
报文经 Ed25519 签名认证,超过 1200 字节自动分片重组。
|
||||||
|
- **键空间**:
|
||||||
|
- `log/room/<房间名>`:聊天室消息(grow-only 集合,按时间戳合并)
|
||||||
|
- `log/room/<房间名>/members`:成员列表
|
||||||
|
- `log/inbox/<节点 ID>`:离线私信
|
||||||
|
- `profile/<昵称>`:昵称 → 节点 ID/地址 的档案
|
||||||
|
- **聊天层**:负责房间加入/离开、消息广播与日志回放、私聊的加密与信箱降级。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、安全模型
|
||||||
|
|
||||||
|
| 项目 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| 身份 | Ed25519 密钥对;节点 ID 由公钥派生,无法伪造他人身份 |
|
||||||
|
| 报文完整性 | 每个 UDP 报文都由发送方私钥签名,接收方校验 `node_id == SHA1(pub)` |
|
||||||
|
| 私聊机密性 | X25519 密钥交换 + HKDF-SHA256 派生密钥 + AEAD 加密,附加数据绑定收发双方节点 ID |
|
||||||
|
| 聊天室 | **不加密**(房间内容需要复制到 DHT 供他人拉取),但每条消息都带发送者签名 |
|
||||||
|
|
||||||
|
也就是说:私聊是端到端加密的,聊天室消息是公开可读但不可篡改的。
|
||||||
|
请勿在公共聊天室里发送敏感信息。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 九、常见问题
|
||||||
|
|
||||||
|
**Q:双击 `start.bat` 一闪而过 / 提示找不到 Python**
|
||||||
|
安装 Python 3 并勾选「Add python.exe to PATH」,然后重新双击。`start.bat` 在出错时会暂停显示原因。
|
||||||
|
|
||||||
|
**Q:提示「当前 Python 没有安装 tkinter」**
|
||||||
|
改用 `run.cmd --no-gui` 运行命令行版,或安装官方 python.org 发行版(自带 tkinter)。
|
||||||
|
|
||||||
|
**Q:端口被占用**
|
||||||
|
关闭重复启动的客户端,或换端口:`run.cmd --port 47900`。
|
||||||
|
|
||||||
|
**Q:局域网里互相看不到**
|
||||||
|
1. 检查是不是同一个网段(`192.168.1.x` 与 `192.168.1.y` 才是);
|
||||||
|
2. 放行防火墙的 UDP `47800`、`47654`;
|
||||||
|
3. 实在不行就用手动引导:`run.cmd -b 对方IP:47800`。
|
||||||
|
|
||||||
|
**Q:房间消息发出去对方没立刻收到**
|
||||||
|
房间消息会先向已知成员点对点直推(基本实时);
|
||||||
|
如果对方还没成为你的已知节点,就要等 DHT 日志同步兜底(每 12 秒一次)。
|
||||||
|
先在「引导地址」里连一下对方,或让双方都等几秒自动发现,即可实时互通。
|
||||||
|
|
||||||
|
**Q:想清空聊天记录 / 重置身份**
|
||||||
|
删除 `%USERPROFILE%\.dhtchat` 目录即可(会同时删除身份密钥)。
|
||||||
|
|
||||||
|
**Q:消息太长发不出去**
|
||||||
|
单条记录上限 1 MiB(分片机制),单条消息建议不要超过几千字。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十、开发与测试
|
||||||
|
|
||||||
|
运行全部单元测试(48 个用例,覆盖密码学原语、DHT 路由与报文、聊天层逻辑):
|
||||||
|
|
||||||
|
```bat
|
||||||
|
py -3 -m unittest discover -s tests -v
|
||||||
|
```
|
||||||
|
|
||||||
|
项目结构:
|
||||||
|
|
||||||
|
```text
|
||||||
|
dhtchat/
|
||||||
|
__init__.py 版本与对外导出
|
||||||
|
__main__.py 命令行入口(GUI / 控制台分发)
|
||||||
|
gui.py Tkinter 图形界面
|
||||||
|
app.py 线程安全门面(GUI 与 asyncio 之间的桥)
|
||||||
|
chat.py 聊天业务层(房间、私聊、DHT 日志同步)
|
||||||
|
node.py Kademlia DHT 节点(UDP、分片、认证)
|
||||||
|
routing.py 路由表与 Contact
|
||||||
|
store.py 记录存储与合并策略
|
||||||
|
protocol.py 报文编码/解码与常量
|
||||||
|
crypto.py Ed25519 / X25519 / HKDF / AEAD
|
||||||
|
identity.py 身份密钥的加载与保存
|
||||||
|
util.py 本地地址探测等工具
|
||||||
|
tests/
|
||||||
|
test_crypto.py 密码学原语
|
||||||
|
test_dht.py DHT 节点与协议
|
||||||
|
test_chat.py 聊天层
|
||||||
|
run.cmd 启动脚本(自动寻找 Python)
|
||||||
|
start.bat 双击启动(出错会暂停)
|
||||||
|
```
|
||||||
|
|
||||||
|
> Windows 小贴士:系统 `PATH` 里可能有一个 0 字节的 `python.exe` 应用商店别名,
|
||||||
|
> 此时请使用 `py -3`,或者直接双击本仓库提供的 `run.cmd` / `start.bat`。
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""dhtchat -- a serverless chat client built on a Kademlia DHT.
|
||||||
|
|
||||||
|
The package is pure Python standard library: no third party dependency has to
|
||||||
|
be installed before ``python -m dhtchat`` works on Windows, Linux or macOS.
|
||||||
|
|
||||||
|
Layers
|
||||||
|
------
|
||||||
|
``crypto`` Ed25519/X25519/AEAD primitives (RFC 8032 / 7748 compliant)
|
||||||
|
``routing`` Kademlia routing table
|
||||||
|
``store`` replicated key/value store with merge semantics
|
||||||
|
``protocol`` UDP wire format, including transparent fragmentation
|
||||||
|
``node`` the DHT node itself (RPC, iterative lookups, relaying)
|
||||||
|
``chat`` rooms, private messages and DHT backed history
|
||||||
|
``app`` thread safe facade used by the GUI
|
||||||
|
``gui`` Tkinter desktop client
|
||||||
|
"""
|
||||||
|
|
||||||
|
from .chat import ChatService
|
||||||
|
from .identity import Identity
|
||||||
|
from .node import DhtNode
|
||||||
|
|
||||||
|
__version__ = "1.0.0"
|
||||||
|
__all__ = ["ChatService", "DhtNode", "Identity", "__version__"]
|
||||||
@@ -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())
|
||||||
+482
@@ -0,0 +1,482 @@
|
|||||||
|
"""Thread safe facade around the asyncio node.
|
||||||
|
|
||||||
|
Tkinter must own the main thread, so the DHT runs in a dedicated thread with
|
||||||
|
its own event loop. Calls in, and events out, are marshalled through
|
||||||
|
thread-safe primitives:
|
||||||
|
|
||||||
|
* commands use :meth:`asyncio.AbstractEventLoop.call_soon_threadsafe`
|
||||||
|
* events use a :class:`queue.Queue` drained by the GUI timer
|
||||||
|
|
||||||
|
A small UDP multicast beacon provides zero-configuration discovery of other
|
||||||
|
instances on the same LAN, and manual bootstrap addresses are always
|
||||||
|
supported for wide-area use.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import queue
|
||||||
|
import socket
|
||||||
|
import struct
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .chat import ChatService
|
||||||
|
from .identity import DEFAULT_STATE_DIR, Identity
|
||||||
|
from .node import DhtNode
|
||||||
|
from .routing import Contact
|
||||||
|
from .util import parse_host_port
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
MULTICAST_GROUP = "239.76.99.104"
|
||||||
|
DISCOVERY_PORT = 47654
|
||||||
|
DISCOVERY_MAGIC = "dhtchat-discovery-v1"
|
||||||
|
DISCOVERY_INTERVAL = 6.0
|
||||||
|
DEFAULT_PORT = 47800
|
||||||
|
|
||||||
|
|
||||||
|
class _DiscoveryProtocol(asyncio.DatagramProtocol):
|
||||||
|
def __init__(self, app: "ChatApp") -> None:
|
||||||
|
self.app = app
|
||||||
|
|
||||||
|
def datagram_received(self, data: bytes, addr) -> None:
|
||||||
|
try:
|
||||||
|
message = json.loads(data.decode("utf-8"))
|
||||||
|
except (ValueError, UnicodeDecodeError):
|
||||||
|
return
|
||||||
|
if not isinstance(message, dict) or message.get("m") != DISCOVERY_MAGIC:
|
||||||
|
return
|
||||||
|
self.app._handle_beacon(message, addr)
|
||||||
|
|
||||||
|
|
||||||
|
class ChatApp:
|
||||||
|
"""Owns the node, the chat service and their background event loop."""
|
||||||
|
|
||||||
|
def __init__(self, state_dir: Path | str | None = None, profile: str = "default") -> None:
|
||||||
|
self.root_dir = Path(state_dir) if state_dir else DEFAULT_STATE_DIR
|
||||||
|
self.profile = profile or "default"
|
||||||
|
self.profile_dir = self.root_dir / self.profile
|
||||||
|
self.events: queue.Queue[dict] = queue.Queue()
|
||||||
|
self.identity: Identity | None = None
|
||||||
|
self.node: DhtNode | None = None
|
||||||
|
self.chat: ChatService | None = None
|
||||||
|
|
||||||
|
self._loop: asyncio.AbstractEventLoop | None = None
|
||||||
|
self._thread: threading.Thread | None = None
|
||||||
|
self._stop_event: asyncio.Event | None = None
|
||||||
|
self._ready = threading.Event()
|
||||||
|
self._startup_error: Exception | None = None
|
||||||
|
self._discovery_transport: asyncio.DatagramTransport | None = None
|
||||||
|
self._discovery_tasks: list[asyncio.Task] = []
|
||||||
|
self._running = False
|
||||||
|
self.nickname = ""
|
||||||
|
self.last_error = ""
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# lifecycle
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@property
|
||||||
|
def running(self) -> bool:
|
||||||
|
return self._running
|
||||||
|
|
||||||
|
def start(
|
||||||
|
self,
|
||||||
|
nickname: str,
|
||||||
|
port: int = 0,
|
||||||
|
bootstrap: list[str] | tuple[str, ...] = (),
|
||||||
|
discovery: bool = True,
|
||||||
|
host: str = "0.0.0.0",
|
||||||
|
) -> bool:
|
||||||
|
"""Start the node in a background thread. Blocks until it is listening."""
|
||||||
|
if self._running:
|
||||||
|
return True
|
||||||
|
self.nickname = nickname or "匿名"
|
||||||
|
self._ready.clear()
|
||||||
|
self._startup_error = None
|
||||||
|
self._thread = threading.Thread(
|
||||||
|
target=self._thread_main,
|
||||||
|
args=(self.nickname, port, list(bootstrap), discovery, host),
|
||||||
|
name="dhtchat-loop",
|
||||||
|
daemon=True,
|
||||||
|
)
|
||||||
|
self._thread.start()
|
||||||
|
if not self._ready.wait(timeout=15):
|
||||||
|
self.last_error = "启动超时"
|
||||||
|
return False
|
||||||
|
return self._startup_error is None
|
||||||
|
|
||||||
|
def stop(self, timeout: float = 5.0) -> None:
|
||||||
|
loop = self._loop
|
||||||
|
stop_event = self._stop_event
|
||||||
|
if loop is None or stop_event is None or not self._running:
|
||||||
|
self._running = False
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
loop.call_soon_threadsafe(stop_event.set)
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
if self._thread is not None:
|
||||||
|
self._thread.join(timeout=timeout)
|
||||||
|
self._running = False
|
||||||
|
|
||||||
|
def _thread_main(
|
||||||
|
self,
|
||||||
|
nickname: str,
|
||||||
|
port: int,
|
||||||
|
bootstrap: list[str],
|
||||||
|
discovery: bool,
|
||||||
|
host: str,
|
||||||
|
) -> None:
|
||||||
|
loop = asyncio.new_event_loop()
|
||||||
|
self._loop = loop
|
||||||
|
asyncio.set_event_loop(loop)
|
||||||
|
try:
|
||||||
|
loop.run_until_complete(
|
||||||
|
self._main(nickname, port, bootstrap, discovery, host)
|
||||||
|
)
|
||||||
|
except Exception as exc: # pragma: no cover - defensive
|
||||||
|
log.exception("dhtchat event loop crashed")
|
||||||
|
self._startup_error = exc
|
||||||
|
self.last_error = str(exc)
|
||||||
|
self._emit({"type": "log", "level": "error", "text": f"运行错误: {exc}"})
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
loop.run_until_complete(loop.shutdown_asyncgens())
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
loop.close()
|
||||||
|
self._loop = None
|
||||||
|
self._running = False
|
||||||
|
|
||||||
|
async def _main(
|
||||||
|
self,
|
||||||
|
nickname: str,
|
||||||
|
port: int,
|
||||||
|
bootstrap: list[str],
|
||||||
|
discovery: bool,
|
||||||
|
host: str,
|
||||||
|
) -> None:
|
||||||
|
self._stop_event = asyncio.Event()
|
||||||
|
try:
|
||||||
|
identity = Identity.load_or_create(self.profile_dir / "identity.json")
|
||||||
|
node = DhtNode(identity, host=host, port=port)
|
||||||
|
await node.start()
|
||||||
|
except Exception as exc:
|
||||||
|
self._startup_error = exc
|
||||||
|
self.last_error = str(exc)
|
||||||
|
self._emit({"type": "log", "level": "error", "text": f"无法启动节点: {exc}"})
|
||||||
|
self._ready.set()
|
||||||
|
return
|
||||||
|
|
||||||
|
self.identity = identity
|
||||||
|
self.node = node
|
||||||
|
self.chat = ChatService(
|
||||||
|
node, identity, self.profile_dir, self._emit, nickname=nickname
|
||||||
|
)
|
||||||
|
self._running = True
|
||||||
|
self._ready.set()
|
||||||
|
|
||||||
|
self._emit(
|
||||||
|
{
|
||||||
|
"type": "started",
|
||||||
|
"nickname": nickname,
|
||||||
|
"node_id": identity.node_id_hex,
|
||||||
|
"fingerprint": identity.fingerprint,
|
||||||
|
"address": f"{node.address[0]}:{node.address[1]}",
|
||||||
|
"port": node.bound_port,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self._emit({"type": "log", "level": "info",
|
||||||
|
"text": f"节点已启动,监听 {node.host}:{node.bound_port}"})
|
||||||
|
|
||||||
|
if discovery:
|
||||||
|
await self._start_discovery()
|
||||||
|
|
||||||
|
seeds = []
|
||||||
|
for text in bootstrap:
|
||||||
|
try:
|
||||||
|
parsed = parse_host_port(text, DEFAULT_PORT)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if parsed[0] and parsed[1]:
|
||||||
|
seeds.append(parsed)
|
||||||
|
if seeds:
|
||||||
|
known = await node.bootstrap(seeds)
|
||||||
|
self._emit(
|
||||||
|
{
|
||||||
|
"type": "log",
|
||||||
|
"level": "info" if known else "warn",
|
||||||
|
"text": f"引导节点: 成功连接 {known}/{len(seeds)} 个",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
await self.chat.start()
|
||||||
|
self._emit_peers()
|
||||||
|
self._emit({"type": "ready"})
|
||||||
|
|
||||||
|
try:
|
||||||
|
await self._stop_event.wait()
|
||||||
|
finally:
|
||||||
|
for task in self._discovery_tasks:
|
||||||
|
task.cancel()
|
||||||
|
self._discovery_tasks = []
|
||||||
|
if self._discovery_transport is not None:
|
||||||
|
self._discovery_transport.close()
|
||||||
|
self._discovery_transport = None
|
||||||
|
try:
|
||||||
|
await self.chat.stop()
|
||||||
|
except Exception:
|
||||||
|
log.exception("chat shutdown failed")
|
||||||
|
try:
|
||||||
|
await node.stop()
|
||||||
|
except Exception:
|
||||||
|
log.exception("node shutdown failed")
|
||||||
|
self._emit({"type": "stopped"})
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# LAN discovery
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
async def _start_discovery(self) -> None:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
try:
|
||||||
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
sock.bind(("", DISCOVERY_PORT))
|
||||||
|
membership = struct.pack(
|
||||||
|
"4s4s", socket.inet_aton(MULTICAST_GROUP), socket.inet_aton("0.0.0.0")
|
||||||
|
)
|
||||||
|
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership)
|
||||||
|
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)
|
||||||
|
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
|
||||||
|
sock.setblocking(False)
|
||||||
|
except OSError as exc:
|
||||||
|
sock.close()
|
||||||
|
self._emit(
|
||||||
|
{"type": "log", "level": "warn",
|
||||||
|
"text": f"局域网自动发现不可用({exc}),请使用引导地址手动连接"}
|
||||||
|
)
|
||||||
|
return
|
||||||
|
transport, _ = await loop.create_datagram_endpoint(
|
||||||
|
lambda: _DiscoveryProtocol(self), sock=sock
|
||||||
|
)
|
||||||
|
self._discovery_transport = transport
|
||||||
|
self._discovery_tasks = [asyncio.create_task(self._beacon_loop())]
|
||||||
|
self._emit({"type": "log", "level": "info", "text": "局域网自动发现已启用"})
|
||||||
|
|
||||||
|
def _beacon(self, reply_to: tuple | None = None, just_started: bool = False) -> None:
|
||||||
|
if self._discovery_transport is None or self.node is None:
|
||||||
|
return
|
||||||
|
payload = {
|
||||||
|
"m": DISCOVERY_MAGIC,
|
||||||
|
"reply": reply_to is not None,
|
||||||
|
"node": self.identity.node_id_hex,
|
||||||
|
"pub": self.identity.public_hex,
|
||||||
|
"nick": self.nickname,
|
||||||
|
"host": self.node.advertised_host,
|
||||||
|
"port": self.node.bound_port,
|
||||||
|
"started": just_started,
|
||||||
|
}
|
||||||
|
data = json.dumps(payload).encode("utf-8")
|
||||||
|
try:
|
||||||
|
self._discovery_transport.sendto(data, (MULTICAST_GROUP, DISCOVERY_PORT))
|
||||||
|
except OSError:
|
||||||
|
log.debug("beacon send failed")
|
||||||
|
|
||||||
|
async def _beacon_loop(self) -> None:
|
||||||
|
self._beacon(just_started=True)
|
||||||
|
while True:
|
||||||
|
await asyncio.sleep(DISCOVERY_INTERVAL)
|
||||||
|
self._beacon()
|
||||||
|
|
||||||
|
def _handle_beacon(self, message: dict, addr: tuple) -> None:
|
||||||
|
if self.node is None or self.identity is None:
|
||||||
|
return
|
||||||
|
node_hex = str(message.get("node") or "")
|
||||||
|
if not node_hex or node_hex == self.identity.node_id_hex:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
node_id = bytes.fromhex(node_hex)
|
||||||
|
public = bytes.fromhex(str(message.get("pub") or ""))
|
||||||
|
port = int(message.get("port") or 0)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return
|
||||||
|
if len(node_id) != 20 or len(public) != 32 or not port:
|
||||||
|
return
|
||||||
|
host = str(message.get("host") or addr[0])
|
||||||
|
if host in ("0.0.0.0", "::"):
|
||||||
|
host = addr[0]
|
||||||
|
source = addr[0]
|
||||||
|
for candidate in (host, source):
|
||||||
|
if candidate:
|
||||||
|
self.node.routing.add(
|
||||||
|
Contact(node_id, candidate, port, public,
|
||||||
|
nickname=str(message.get("nick") or ""))
|
||||||
|
)
|
||||||
|
if not message.get("reply"):
|
||||||
|
self._beacon(reply_to=addr)
|
||||||
|
asyncio.ensure_future(self._introduce(host, port))
|
||||||
|
|
||||||
|
async def _introduce(self, host: str, port: int) -> None:
|
||||||
|
if self.node is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
await self.node.bootstrap([(host, port)])
|
||||||
|
except Exception:
|
||||||
|
log.exception("bootstrap from beacon failed")
|
||||||
|
self._emit_peers()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# event plumbing
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _emit(self, event: dict) -> None:
|
||||||
|
self.events.put(event)
|
||||||
|
|
||||||
|
def poll_events(self, limit: int = 200) -> list[dict]:
|
||||||
|
drained = []
|
||||||
|
for _ in range(limit):
|
||||||
|
try:
|
||||||
|
drained.append(self.events.get_nowait())
|
||||||
|
except queue.Empty:
|
||||||
|
break
|
||||||
|
return drained
|
||||||
|
|
||||||
|
def _emit_peers(self) -> None:
|
||||||
|
if self.node is None:
|
||||||
|
return
|
||||||
|
contacts = self.node.routing.snapshot()
|
||||||
|
self._emit(
|
||||||
|
{
|
||||||
|
"type": "peers",
|
||||||
|
"count": len(contacts),
|
||||||
|
"peers": contacts,
|
||||||
|
"info": self.node.describe(),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
def _submit(self, coroutine) -> None:
|
||||||
|
loop = self._loop
|
||||||
|
if loop is None or not self._running:
|
||||||
|
coroutine.close()
|
||||||
|
return
|
||||||
|
asyncio.run_coroutine_threadsafe(self._wrap(coroutine), loop)
|
||||||
|
|
||||||
|
async def _wrap(self, coroutine) -> None:
|
||||||
|
try:
|
||||||
|
await coroutine
|
||||||
|
except Exception as exc:
|
||||||
|
log.exception("command failed")
|
||||||
|
self._emit({"type": "log", "level": "error", "text": f"操作失败: {exc}"})
|
||||||
|
finally:
|
||||||
|
self._emit_peers()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# public, thread-safe commands
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def join_room(self, name: str) -> None:
|
||||||
|
if self.chat is not None:
|
||||||
|
self._submit(self._join(name))
|
||||||
|
|
||||||
|
async def _join(self, name: str) -> None:
|
||||||
|
assert self.chat is not None
|
||||||
|
self.chat.join_room(name)
|
||||||
|
|
||||||
|
def leave_room(self, name: str) -> None:
|
||||||
|
if self.chat is not None:
|
||||||
|
self.chat.leave_room(name)
|
||||||
|
self._emit_peers()
|
||||||
|
|
||||||
|
def send_room_message(self, room: str, text: str) -> None:
|
||||||
|
if self.chat is not None:
|
||||||
|
self._submit(self.chat.send_room_message(room, text))
|
||||||
|
|
||||||
|
def send_direct_message(self, target: str, text: str) -> None:
|
||||||
|
if self.chat is not None:
|
||||||
|
self._submit(self._send_direct(target, text))
|
||||||
|
|
||||||
|
async def _send_direct(self, target: str, text: str) -> None:
|
||||||
|
assert self.chat is not None
|
||||||
|
result = await self.chat.send_direct(target, text)
|
||||||
|
if not result.get("delivered"):
|
||||||
|
self._emit(
|
||||||
|
{
|
||||||
|
"type": "log",
|
||||||
|
"level": "warn",
|
||||||
|
"text": f"消息已写入 DHT 信箱,等待「{target}」上线:{result.get('reason', '对方暂不可达')}",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
def set_nickname(self, nickname: str) -> None:
|
||||||
|
"""Change the display name and republish the profile record."""
|
||||||
|
nickname = (nickname or "").strip()
|
||||||
|
if not nickname:
|
||||||
|
return
|
||||||
|
self.nickname = nickname
|
||||||
|
if self.chat is not None:
|
||||||
|
self._submit(self._set_nickname(nickname))
|
||||||
|
|
||||||
|
async def _set_nickname(self, nickname: str) -> None:
|
||||||
|
assert self.chat is not None and self.node is not None
|
||||||
|
self.chat.nickname = nickname
|
||||||
|
self.node.nickname = nickname
|
||||||
|
await self.chat.announce_profile()
|
||||||
|
self._emit({"type": "log", "level": "info", "text": f"昵称已更新为「{nickname}」"})
|
||||||
|
|
||||||
|
def snapshot(self) -> dict:
|
||||||
|
"""Best effort read-only view of the chat state (safe from any thread)."""
|
||||||
|
chat = self.chat
|
||||||
|
if chat is None:
|
||||||
|
return {"rooms": {}, "contacts": [], "delivered": 0}
|
||||||
|
try:
|
||||||
|
return chat.snapshot()
|
||||||
|
except Exception: # pragma: no cover - concurrent mutation
|
||||||
|
log.debug("snapshot failed", exc_info=True)
|
||||||
|
return {"rooms": {}, "contacts": [], "delivered": 0}
|
||||||
|
|
||||||
|
def add_bootstrap(self, address: str) -> None:
|
||||||
|
if self.node is None:
|
||||||
|
return
|
||||||
|
self._submit(self._add_bootstrap(address))
|
||||||
|
|
||||||
|
async def _add_bootstrap(self, address: str) -> None:
|
||||||
|
assert self.node is not None
|
||||||
|
try:
|
||||||
|
host, port = parse_host_port(address, DEFAULT_PORT)
|
||||||
|
except ValueError:
|
||||||
|
self._emit({"type": "log", "level": "warn", "text": f"地址格式无效: {address}"})
|
||||||
|
return
|
||||||
|
if not host:
|
||||||
|
return
|
||||||
|
known = await self.node.bootstrap([(host, port or DEFAULT_PORT)])
|
||||||
|
self._emit(
|
||||||
|
{
|
||||||
|
"type": "log",
|
||||||
|
"level": "info" if known else "warn",
|
||||||
|
"text": f"引导 {host}:{port}: {'成功' if known else '无响应'}",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
def refresh_profile(self) -> None:
|
||||||
|
if self.chat is not None:
|
||||||
|
self._submit(self.chat.announce_profile())
|
||||||
|
|
||||||
|
def lookup_nickname(self, nickname: str) -> None:
|
||||||
|
if self.chat is not None:
|
||||||
|
self._submit(self._lookup(nickname))
|
||||||
|
|
||||||
|
async def _lookup(self, nickname: str) -> None:
|
||||||
|
assert self.chat is not None
|
||||||
|
profile = await self.chat.resolve_nickname(nickname)
|
||||||
|
if profile is None:
|
||||||
|
self._emit(
|
||||||
|
{"type": "log", "level": "warn", "text": f"DHT 中找不到用户「{nickname}」"}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._emit({"type": "profile", **profile})
|
||||||
|
|
||||||
|
def describe(self) -> dict:
|
||||||
|
if self.node is None:
|
||||||
|
return {"running": False}
|
||||||
|
return {"running": self._running, **self.node.describe()}
|
||||||
+673
@@ -0,0 +1,673 @@
|
|||||||
|
"""Chat layer on top of the DHT.
|
||||||
|
|
||||||
|
Everything is derived from the distributed hash table -- there is no server:
|
||||||
|
|
||||||
|
``profile/<nick>``
|
||||||
|
Last-write-wins record publishing a user's public key, node id and
|
||||||
|
address. Used to resolve a nickname before starting a private chat.
|
||||||
|
|
||||||
|
``log/room/<name>``
|
||||||
|
Grow-only set holding recent room messages, so late joiners can replay
|
||||||
|
history and messages lost to packet loss can be recovered.
|
||||||
|
|
||||||
|
``log/room/<name>/members``
|
||||||
|
Grow-only set of room membership announcements refreshed every few
|
||||||
|
seconds (stale entries are pruned on read).
|
||||||
|
|
||||||
|
``log/inbox/<node_id>``
|
||||||
|
Encrypted offline mailbox used when a direct message cannot be delivered
|
||||||
|
through the overlay right away.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from . import crypto, protocol
|
||||||
|
from .identity import Identity
|
||||||
|
from .node import DhtNode
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
PROFILE_TTL = 24 * 3600.0
|
||||||
|
ROOM_LOG_TTL = 6 * 3600.0
|
||||||
|
MEMBER_TTL = 300.0
|
||||||
|
MEMBER_FRESH_SECONDS = 90.0
|
||||||
|
INBOX_TTL = 7 * 24 * 3600.0
|
||||||
|
MAX_TEXT = 1500
|
||||||
|
ROOM_TICK_SECONDS = 12.0
|
||||||
|
ROOM_REPLAY_LIMIT = 40
|
||||||
|
INBOX_TICK_SECONDS = 15.0
|
||||||
|
|
||||||
|
PROFILE_PREFIX = "profile/"
|
||||||
|
ROOM_LOG_PREFIX = "log/room/"
|
||||||
|
INBOX_PREFIX = "log/inbox/"
|
||||||
|
|
||||||
|
|
||||||
|
def _now() -> float:
|
||||||
|
return time.time()
|
||||||
|
|
||||||
|
|
||||||
|
def _canonical(record: dict) -> bytes:
|
||||||
|
payload = {k: v for k, v in record.items() if k != "sig"}
|
||||||
|
return json.dumps(
|
||||||
|
payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False
|
||||||
|
).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _sign_record(record: dict, identity: Identity) -> dict:
|
||||||
|
signed = dict(record)
|
||||||
|
signed["sig"] = identity.sign(_canonical(signed)).hex()
|
||||||
|
return signed
|
||||||
|
|
||||||
|
|
||||||
|
def verify_record(record: dict) -> bytes | None:
|
||||||
|
"""Return the signer's public key when ``record`` carries a valid signature."""
|
||||||
|
signature = record.get("sig")
|
||||||
|
public_hex = record.get("pub")
|
||||||
|
if not isinstance(signature, str) or not isinstance(public_hex, str):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
public = bytes.fromhex(public_hex)
|
||||||
|
raw_signature = bytes.fromhex(signature)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if len(public) != 32 or len(raw_signature) != 64:
|
||||||
|
return None
|
||||||
|
if not crypto.ed25519_verify(public, _canonical(record), raw_signature):
|
||||||
|
return None
|
||||||
|
return public
|
||||||
|
|
||||||
|
|
||||||
|
def encode_log_item(item: dict) -> bytes:
|
||||||
|
return json.dumps([item], separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def decode_log(blobs: list[bytes]) -> list[dict]:
|
||||||
|
items: list[dict] = []
|
||||||
|
for blob in blobs:
|
||||||
|
try:
|
||||||
|
parsed = json.loads(blob.decode("utf-8"))
|
||||||
|
except (ValueError, UnicodeDecodeError):
|
||||||
|
continue
|
||||||
|
if isinstance(parsed, list):
|
||||||
|
items.extend(item for item in parsed if isinstance(item, dict))
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RoomState:
|
||||||
|
name: str
|
||||||
|
messages: list[dict] = field(default_factory=list)
|
||||||
|
members: dict[str, dict] = field(default_factory=dict)
|
||||||
|
seen: set[str] = field(default_factory=set)
|
||||||
|
joined_at: float = field(default_factory=_now)
|
||||||
|
last_announce: float = 0.0
|
||||||
|
|
||||||
|
def member_list(self) -> list[dict]:
|
||||||
|
return sorted(self.members.values(), key=lambda m: m.get("nick") or "")
|
||||||
|
|
||||||
|
|
||||||
|
class ChatService:
|
||||||
|
"""Rooms, private messages and the related DHT bookkeeping."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
node: DhtNode,
|
||||||
|
identity: Identity,
|
||||||
|
state_dir: Path | str,
|
||||||
|
emit: Callable[[dict], None],
|
||||||
|
nickname: str = "",
|
||||||
|
) -> None:
|
||||||
|
self.node = node
|
||||||
|
self.identity = identity
|
||||||
|
self.state_dir = Path(state_dir)
|
||||||
|
self.state_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
self.emit = emit
|
||||||
|
self.nickname = nickname or f"用户{identity.fingerprint}"
|
||||||
|
|
||||||
|
self.rooms: dict[str, RoomState] = {}
|
||||||
|
self.contacts: dict[str, dict] = {} # nickname -> profile record
|
||||||
|
self.by_node: dict[str, dict] = {} # node id hex -> profile record
|
||||||
|
self.delivered: set[str] = set()
|
||||||
|
self._delivered_path = self.state_dir / "delivered.json"
|
||||||
|
self._tasks: list[asyncio.Task] = []
|
||||||
|
self._running = False
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# lifecycle
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
async def start(self) -> None:
|
||||||
|
self._load_delivered()
|
||||||
|
self.node.nickname = self.nickname
|
||||||
|
self.node.register_handler(protocol.ROOM_MSG, self._on_room_packet)
|
||||||
|
self.node.register_handler(protocol.DIRECT_MSG, self._on_direct_packet)
|
||||||
|
self.node.set_route_handler(self._on_routed_payload)
|
||||||
|
self._running = True
|
||||||
|
await self.announce_profile()
|
||||||
|
self._tasks = [
|
||||||
|
asyncio.create_task(self._room_loop()),
|
||||||
|
asyncio.create_task(self._inbox_loop()),
|
||||||
|
]
|
||||||
|
|
||||||
|
async def stop(self) -> None:
|
||||||
|
self._running = False
|
||||||
|
for task in self._tasks:
|
||||||
|
task.cancel()
|
||||||
|
for task in self._tasks:
|
||||||
|
try:
|
||||||
|
await task
|
||||||
|
except (asyncio.CancelledError, Exception):
|
||||||
|
pass
|
||||||
|
self._tasks = []
|
||||||
|
self._save_delivered()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def node_id_hex(self) -> str:
|
||||||
|
return self.identity.node_id_hex
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# identity / profile records
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _profile_record(self) -> dict:
|
||||||
|
host, port = self.node.address
|
||||||
|
record = {
|
||||||
|
"nick": self.nickname,
|
||||||
|
"pub": self.identity.public_hex,
|
||||||
|
"node": self.identity.node_id_hex,
|
||||||
|
"host": host,
|
||||||
|
"port": port,
|
||||||
|
"ts": _now(),
|
||||||
|
}
|
||||||
|
return _sign_record(record, self.identity)
|
||||||
|
|
||||||
|
async def announce_profile(self) -> int:
|
||||||
|
"""Publish (or refresh) our reachable profile in the DHT."""
|
||||||
|
blob = json.dumps(self._profile_record(), separators=(",", ":")).encode("utf-8")
|
||||||
|
try:
|
||||||
|
return await self.node.store(f"{PROFILE_PREFIX}{self.nickname}", blob, PROFILE_TTL)
|
||||||
|
except Exception:
|
||||||
|
log.exception("profile announcement failed")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def _remember_profile(self, record: dict) -> dict | None:
|
||||||
|
nick = str(record.get("nick") or "")
|
||||||
|
node_hex = str(record.get("node") or "")
|
||||||
|
if not nick or not node_hex:
|
||||||
|
return None
|
||||||
|
self.contacts[nick] = record
|
||||||
|
self.by_node[node_hex] = record
|
||||||
|
return record
|
||||||
|
|
||||||
|
async def resolve_nickname(self, nickname: str) -> dict | None:
|
||||||
|
"""Look up a nickname, verifying the signature on the profile record."""
|
||||||
|
cached = self.contacts.get(nickname)
|
||||||
|
if cached and _now() - float(cached.get("ts", 0)) < 120:
|
||||||
|
return cached
|
||||||
|
blobs = await self.node.find_value(f"{PROFILE_PREFIX}{nickname}")
|
||||||
|
for blob in blobs:
|
||||||
|
try:
|
||||||
|
record = json.loads(blob.decode("utf-8"))
|
||||||
|
except (ValueError, UnicodeDecodeError):
|
||||||
|
continue
|
||||||
|
if not isinstance(record, dict) or record.get("nick") != nickname:
|
||||||
|
continue
|
||||||
|
public = verify_record(record)
|
||||||
|
if public is None or public.hex() != record.get("pub"):
|
||||||
|
continue
|
||||||
|
return self._remember_profile(record)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# rooms
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def join_room(self, name: str) -> RoomState:
|
||||||
|
name = name.strip()
|
||||||
|
if not name:
|
||||||
|
raise ValueError("room name must not be empty")
|
||||||
|
room = self.rooms.get(name)
|
||||||
|
if room is None:
|
||||||
|
room = RoomState(name)
|
||||||
|
self.rooms[name] = room
|
||||||
|
self.emit({"type": "room_joined", "room": name})
|
||||||
|
self.emit({"type": "log", "level": "info", "text": f"已加入公共聊天室「{name}」"})
|
||||||
|
asyncio.ensure_future(self._sync_room(room, pull_history=True))
|
||||||
|
else:
|
||||||
|
asyncio.ensure_future(self._sync_room(room, pull_history=False))
|
||||||
|
return room
|
||||||
|
|
||||||
|
def leave_room(self, name: str) -> None:
|
||||||
|
if self.rooms.pop(name, None) is not None:
|
||||||
|
self.emit({"type": "room_left", "room": name})
|
||||||
|
self.emit({"type": "log", "level": "info", "text": f"已离开聊天室「{name}」"})
|
||||||
|
|
||||||
|
def _member_record(self, room: RoomState, ts: float | None = None) -> dict:
|
||||||
|
host, port = self.node.address
|
||||||
|
record = {
|
||||||
|
"id": self.identity.node_id_hex,
|
||||||
|
"nick": self.nickname,
|
||||||
|
"pub": self.identity.public_hex,
|
||||||
|
"host": host,
|
||||||
|
"port": port,
|
||||||
|
"room": room.name,
|
||||||
|
"ts": ts if ts is not None else _now(),
|
||||||
|
}
|
||||||
|
return _sign_record(record, self.identity)
|
||||||
|
|
||||||
|
def _merge_members(self, room: RoomState, items: list[dict]) -> bool:
|
||||||
|
changed = False
|
||||||
|
cutoff = _now() - MEMBER_FRESH_SECONDS
|
||||||
|
for item in items:
|
||||||
|
if not isinstance(item, dict) or item.get("room") not in (None, room.name):
|
||||||
|
continue
|
||||||
|
if verify_record(item) is None:
|
||||||
|
continue
|
||||||
|
node_hex = str(item.get("id") or "")
|
||||||
|
if not node_hex or node_hex == self.identity.node_id_hex:
|
||||||
|
continue
|
||||||
|
if float(item.get("ts", 0)) < cutoff:
|
||||||
|
continue
|
||||||
|
previous = room.members.get(node_hex)
|
||||||
|
if previous is None or float(item.get("ts", 0)) > float(previous.get("ts", 0)):
|
||||||
|
room.members[node_hex] = item
|
||||||
|
changed = True
|
||||||
|
# prune stale entries
|
||||||
|
for node_hex in [k for k, v in room.members.items()
|
||||||
|
if float(v.get("ts", 0)) < cutoff]:
|
||||||
|
del room.members[node_hex]
|
||||||
|
changed = True
|
||||||
|
return changed
|
||||||
|
|
||||||
|
async def _sync_room(self, room: RoomState, pull_history: bool = False) -> None:
|
||||||
|
"""Refresh membership and replay room log entries we have not seen yet.
|
||||||
|
|
||||||
|
The log is replayed on every sync (not just when joining) because a
|
||||||
|
message can be missed by the direct room broadcast: a member that only
|
||||||
|
just joined is not known to the sender yet. Already seen entries are
|
||||||
|
dropped by ``_accept_room_message``, so this stays cheap.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
member_blobs = await self.node.find_value(
|
||||||
|
f"{ROOM_LOG_PREFIX}{room.name}/members"
|
||||||
|
)
|
||||||
|
if self._merge_members(room, decode_log(member_blobs)):
|
||||||
|
self.emit({"type": "room_members", "room": room.name,
|
||||||
|
"members": room.member_list()})
|
||||||
|
history = decode_log(await self.node.find_value(f"{ROOM_LOG_PREFIX}{room.name}"))
|
||||||
|
history.sort(key=lambda m: float(m.get("ts", 0)))
|
||||||
|
if pull_history:
|
||||||
|
# Everything older than the replay window is ours to keep in
|
||||||
|
# sync, but must not show up later as if it were news.
|
||||||
|
backlog = history[:-ROOM_REPLAY_LIMIT] if len(history) > ROOM_REPLAY_LIMIT else []
|
||||||
|
room.seen.update(str(item.get("id")) for item in backlog if item.get("id"))
|
||||||
|
for item in history[len(backlog):]:
|
||||||
|
self._accept_room_message(room, item, history=True)
|
||||||
|
else:
|
||||||
|
for item in history[-ROOM_REPLAY_LIMIT:]:
|
||||||
|
self._accept_room_message(room, item)
|
||||||
|
except Exception:
|
||||||
|
log.exception("room sync failed for %s", room.name)
|
||||||
|
|
||||||
|
async def _room_loop(self) -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await asyncio.sleep(ROOM_TICK_SECONDS)
|
||||||
|
for room in list(self.rooms.values()):
|
||||||
|
await self._announce_membership(room)
|
||||||
|
await self._sync_room(room)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
log.exception("room tick failed")
|
||||||
|
|
||||||
|
async def _announce_membership(self, room: RoomState) -> None:
|
||||||
|
record = self._member_record(room)
|
||||||
|
room.last_announce = _now()
|
||||||
|
room.members[self.identity.node_id_hex] = record
|
||||||
|
try:
|
||||||
|
await self.node.store(
|
||||||
|
f"{ROOM_LOG_PREFIX}{room.name}/members",
|
||||||
|
encode_log_item(record),
|
||||||
|
MEMBER_TTL * 2,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
log.exception("membership announcement failed")
|
||||||
|
|
||||||
|
async def send_room_message(self, room_name: str, text: str) -> None:
|
||||||
|
room = self.rooms.get(room_name)
|
||||||
|
if room is None:
|
||||||
|
raise ValueError(f"未加入聊天室「{room_name}」")
|
||||||
|
text = text.strip()
|
||||||
|
if not text:
|
||||||
|
return
|
||||||
|
record = _sign_record(
|
||||||
|
{
|
||||||
|
"id": protocol.new_id(),
|
||||||
|
"room": room_name,
|
||||||
|
"nick": self.nickname,
|
||||||
|
"pub": self.identity.public_hex,
|
||||||
|
"node": self.identity.node_id_hex,
|
||||||
|
"text": text[:MAX_TEXT],
|
||||||
|
"ts": _now(),
|
||||||
|
},
|
||||||
|
self.identity,
|
||||||
|
)
|
||||||
|
self._accept_room_message(room, record, own=True)
|
||||||
|
self._broadcast_room(room, record)
|
||||||
|
try:
|
||||||
|
await self.node.store(
|
||||||
|
f"{ROOM_LOG_PREFIX}{room_name}", encode_log_item(record), ROOM_LOG_TTL
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
log.exception("storing room message failed")
|
||||||
|
|
||||||
|
def _broadcast_room(self, room: RoomState, record: dict) -> None:
|
||||||
|
payload = self.node._base(protocol.ROOM_MSG)
|
||||||
|
payload["room"] = room.name
|
||||||
|
payload["record"] = record
|
||||||
|
for node_hex, member in list(room.members.items()):
|
||||||
|
if node_hex == self.identity.node_id_hex:
|
||||||
|
continue
|
||||||
|
host, port = member.get("host"), member.get("port")
|
||||||
|
if not host or not port:
|
||||||
|
continue
|
||||||
|
self.node.send_raw(payload, (str(host), int(port)))
|
||||||
|
|
||||||
|
def _on_room_packet(self, message: dict, addr: tuple) -> None:
|
||||||
|
room_name = str(message.get("room") or "")
|
||||||
|
room = self.rooms.get(room_name)
|
||||||
|
if room is None:
|
||||||
|
return
|
||||||
|
record = message.get("record")
|
||||||
|
if not isinstance(record, dict):
|
||||||
|
return
|
||||||
|
self._accept_room_message(room, record)
|
||||||
|
|
||||||
|
def _accept_room_message(
|
||||||
|
self, room: RoomState, record: dict, own: bool = False, history: bool = False
|
||||||
|
) -> bool:
|
||||||
|
message_id = str(record.get("id") or "")
|
||||||
|
text = record.get("text")
|
||||||
|
if not message_id or not isinstance(text, str) or message_id in room.seen:
|
||||||
|
return False
|
||||||
|
public = verify_record(record)
|
||||||
|
if public is None:
|
||||||
|
return False
|
||||||
|
room.seen.add(message_id)
|
||||||
|
entry = {
|
||||||
|
"id": message_id,
|
||||||
|
"nick": str(record.get("nick") or "未知"),
|
||||||
|
"node": str(record.get("node") or ""),
|
||||||
|
"text": text,
|
||||||
|
"ts": float(record.get("ts", _now())),
|
||||||
|
"own": own or str(record.get("node")) == self.identity.node_id_hex,
|
||||||
|
"history": history,
|
||||||
|
}
|
||||||
|
room.messages.append(entry)
|
||||||
|
del room.messages[:-200]
|
||||||
|
self.emit({"type": "room_message", "room": room.name, **entry})
|
||||||
|
return True
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# direct messages
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _direct_aad(self, sender_node: bytes, recipient_node: bytes) -> bytes:
|
||||||
|
"""Bind a ciphertext to the exact pair of nodes it may travel between."""
|
||||||
|
return b"dhtchat-dm/v1" + sender_node + recipient_node
|
||||||
|
|
||||||
|
async def send_direct(self, target: str, text: str) -> dict:
|
||||||
|
"""Send an encrypted private message to a nickname or node id."""
|
||||||
|
text = text.strip()
|
||||||
|
if not text:
|
||||||
|
return {"delivered": False, "reason": "空消息"}
|
||||||
|
profile = await self.resolve_nickname(target)
|
||||||
|
if profile is None:
|
||||||
|
profile = self.by_node.get(target)
|
||||||
|
if profile is None:
|
||||||
|
# Maybe the user typed a raw node id.
|
||||||
|
node_id = self._parse_node_id(target)
|
||||||
|
if node_id is None:
|
||||||
|
return {"delivered": False, "reason": f"找不到用户「{target}」"}
|
||||||
|
profile = {"nick": target[:12], "node": node_id.hex(),
|
||||||
|
"pub": "", "host": "", "port": ""}
|
||||||
|
if not profile.get("pub"):
|
||||||
|
return {"delivered": False, "reason": f"「{target}」没有可用的公钥"}
|
||||||
|
|
||||||
|
peer_public = bytes.fromhex(profile["pub"])
|
||||||
|
peer_node = bytes.fromhex(profile["node"])
|
||||||
|
nickname = str(profile.get("nick") or target)
|
||||||
|
|
||||||
|
body = json.dumps(
|
||||||
|
{
|
||||||
|
"from_nick": self.nickname,
|
||||||
|
"from_node": self.identity.node_id_hex,
|
||||||
|
"to": peer_node.hex(),
|
||||||
|
"text": text[:MAX_TEXT],
|
||||||
|
"ts": _now(),
|
||||||
|
},
|
||||||
|
separators=(",", ":"),
|
||||||
|
ensure_ascii=False,
|
||||||
|
).encode("utf-8")
|
||||||
|
key = self.identity.shared_secret_with(peer_public)
|
||||||
|
blob = crypto.aead_encrypt(
|
||||||
|
key, body, self._direct_aad(self.identity.node_id, peer_node)
|
||||||
|
)
|
||||||
|
envelope = self._direct_envelope(peer_node, blob)
|
||||||
|
message_id = envelope["id"]
|
||||||
|
|
||||||
|
self.emit(
|
||||||
|
{
|
||||||
|
"type": "direct_message",
|
||||||
|
"peer": nickname,
|
||||||
|
"peer_node": peer_node.hex(),
|
||||||
|
"text": text[:MAX_TEXT],
|
||||||
|
"ts": _now(),
|
||||||
|
"own": True,
|
||||||
|
"delivered": None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
delivered = False
|
||||||
|
address = self._peer_address(profile, peer_node)
|
||||||
|
if address is not None:
|
||||||
|
delivered = self.node.send_raw(envelope, address)
|
||||||
|
if not delivered:
|
||||||
|
delivered = await self.node.send_routed(
|
||||||
|
peer_node, protocol.encode(envelope)
|
||||||
|
)
|
||||||
|
if not delivered:
|
||||||
|
# Store-and-forward: the peer picks it up from its DHT inbox.
|
||||||
|
try:
|
||||||
|
await self.node.store(
|
||||||
|
f"{INBOX_PREFIX}{peer_node.hex()}",
|
||||||
|
encode_log_item({"id": message_id, "ts": _now(), "blob": protocol.b64encode(protocol.encode(envelope))}),
|
||||||
|
INBOX_TTL,
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
log.exception("storing offline message failed")
|
||||||
|
self.emit(
|
||||||
|
{
|
||||||
|
"type": "direct_status",
|
||||||
|
"peer": nickname,
|
||||||
|
"message_id": message_id,
|
||||||
|
"delivered": delivered,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {"delivered": delivered, "peer": nickname, "peer_node": peer_node.hex()}
|
||||||
|
|
||||||
|
def _direct_envelope(self, peer_node: bytes, blob: bytes) -> dict:
|
||||||
|
envelope = self.node._base(protocol.DIRECT_MSG)
|
||||||
|
envelope["id"] = protocol.new_id()
|
||||||
|
envelope["dst"] = peer_node.hex()
|
||||||
|
envelope["blob"] = protocol.b64encode(blob)
|
||||||
|
return envelope
|
||||||
|
|
||||||
|
def _peer_address(self, profile: dict, peer_node: bytes):
|
||||||
|
contact = self.node.routing.get(peer_node)
|
||||||
|
if contact is not None:
|
||||||
|
return contact.address
|
||||||
|
if profile.get("host") and profile.get("port"):
|
||||||
|
return (str(profile["host"]), int(profile["port"]))
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _parse_node_id(self, text: str) -> bytes | None:
|
||||||
|
text = text.strip().lower()
|
||||||
|
if len(text) == 40:
|
||||||
|
try:
|
||||||
|
return bytes.fromhex(text)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
matches = [n for n in (self.routing_node_ids()) if n.startswith(text)]
|
||||||
|
if len(matches) == 1 and len(text) >= 6:
|
||||||
|
return bytes.fromhex(matches[0])
|
||||||
|
return None
|
||||||
|
|
||||||
|
def routing_node_ids(self) -> list[str]:
|
||||||
|
return [c.node_id_hex for c in self.node.routing.contacts()]
|
||||||
|
|
||||||
|
def _on_direct_packet(self, message: dict, addr: tuple) -> None:
|
||||||
|
self._handle_direct(message, addr)
|
||||||
|
|
||||||
|
def _on_routed_payload(self, destination: bytes, payload: bytes, addr: tuple) -> None:
|
||||||
|
message = protocol.decode(payload)
|
||||||
|
if message is None or message.get("t") != protocol.DIRECT_MSG:
|
||||||
|
return
|
||||||
|
node_id = self.node._authenticate(message)
|
||||||
|
if node_id is None:
|
||||||
|
return
|
||||||
|
message["_node_id"] = node_id
|
||||||
|
message["_addr"] = addr
|
||||||
|
self._handle_direct(message, addr)
|
||||||
|
|
||||||
|
def _handle_direct(self, message: dict, addr: tuple) -> None:
|
||||||
|
message_id = str(message.get("id") or "")
|
||||||
|
if not message_id or message_id in self.delivered:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
destination = bytes.fromhex(str(message["dst"]))
|
||||||
|
blob = protocol.b64decode(message["blob"])
|
||||||
|
except (KeyError, ValueError, TypeError):
|
||||||
|
return
|
||||||
|
if destination != self.identity.node_id:
|
||||||
|
return
|
||||||
|
sender_public = message.get("_public") or b""
|
||||||
|
if len(sender_public) != 32:
|
||||||
|
return
|
||||||
|
# The AAD must be built from the authenticated key, never from a field
|
||||||
|
# the sender could have forged.
|
||||||
|
sender_node = crypto.node_id_from_public(sender_public)
|
||||||
|
try:
|
||||||
|
key = self.identity.shared_secret_with(sender_public)
|
||||||
|
body = crypto.aead_decrypt(
|
||||||
|
key, blob, self._direct_aad(sender_node, self.identity.node_id)
|
||||||
|
)
|
||||||
|
payload = json.loads(body.decode("utf-8"))
|
||||||
|
except (ValueError, UnicodeDecodeError, json.JSONDecodeError):
|
||||||
|
self.emit({"type": "log", "level": "warn", "text": "收到一条无法解密的消息"})
|
||||||
|
return
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
return
|
||||||
|
|
||||||
|
self.delivered.add(message_id)
|
||||||
|
self._save_delivered()
|
||||||
|
from_nick = str(payload.get("from_nick") or "未知")
|
||||||
|
from_node = sender_node.hex()
|
||||||
|
profile = {
|
||||||
|
"nick": from_nick,
|
||||||
|
"node": from_node,
|
||||||
|
"pub": sender_public.hex(),
|
||||||
|
"host": addr[0],
|
||||||
|
"port": addr[1],
|
||||||
|
"ts": _now(),
|
||||||
|
}
|
||||||
|
self._remember_profile(profile)
|
||||||
|
self.emit(
|
||||||
|
{
|
||||||
|
"type": "direct_message",
|
||||||
|
"peer": from_nick,
|
||||||
|
"peer_node": from_node,
|
||||||
|
"text": str(payload.get("text") or ""),
|
||||||
|
"ts": float(payload.get("ts", _now())),
|
||||||
|
"own": False,
|
||||||
|
"delivered": True,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
self.emit({"type": "contact", **profile})
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# offline inbox
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
async def _inbox_loop(self) -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await asyncio.sleep(INBOX_TICK_SECONDS)
|
||||||
|
await self._poll_inbox()
|
||||||
|
await self.announce_profile()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
log.exception("inbox poll failed")
|
||||||
|
|
||||||
|
async def _poll_inbox(self) -> None:
|
||||||
|
key = f"{INBOX_PREFIX}{self.identity.node_id_hex}"
|
||||||
|
blobs = await self.node.find_value(key)
|
||||||
|
for item in decode_log(blobs):
|
||||||
|
message_id = str(item.get("id") or "")
|
||||||
|
if not message_id or message_id in self.delivered:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
raw = protocol.b64decode(str(item.get("blob") or ""))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
continue
|
||||||
|
message = protocol.decode(raw)
|
||||||
|
if message is None or message.get("t") != protocol.DIRECT_MSG:
|
||||||
|
continue
|
||||||
|
node_id = self.node._authenticate(message)
|
||||||
|
if node_id is None:
|
||||||
|
continue
|
||||||
|
message["_node_id"] = node_id
|
||||||
|
message["_addr"] = ("0.0.0.0", 0)
|
||||||
|
self._handle_direct(message, ("0.0.0.0", 0))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# persistence
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _load_delivered(self) -> None:
|
||||||
|
try:
|
||||||
|
data = json.loads(self._delivered_path.read_text(encoding="utf-8"))
|
||||||
|
if isinstance(data, list):
|
||||||
|
self.delivered = {str(x) for x in data}
|
||||||
|
except (OSError, ValueError):
|
||||||
|
self.delivered = set()
|
||||||
|
|
||||||
|
def _save_delivered(self) -> None:
|
||||||
|
try:
|
||||||
|
if len(self.delivered) > 4000:
|
||||||
|
self.delivered = set(list(self.delivered)[-4000:])
|
||||||
|
blob = json.dumps(sorted(self.delivered))
|
||||||
|
tmp = self._delivered_path.with_suffix(".tmp")
|
||||||
|
tmp.write_text(blob, encoding="utf-8")
|
||||||
|
os.replace(tmp, self._delivered_path)
|
||||||
|
except OSError:
|
||||||
|
log.debug("could not persist delivered ids")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def snapshot(self) -> dict:
|
||||||
|
return {
|
||||||
|
"rooms": {
|
||||||
|
name: {
|
||||||
|
"members": room.member_list(),
|
||||||
|
"messages": len(room.messages),
|
||||||
|
}
|
||||||
|
for name, room in self.rooms.items()
|
||||||
|
},
|
||||||
|
"contacts": list(self.contacts.values()),
|
||||||
|
"delivered": len(self.delivered),
|
||||||
|
}
|
||||||
@@ -0,0 +1,328 @@
|
|||||||
|
"""Pure-standard-library cryptography for dhtchat.
|
||||||
|
|
||||||
|
Implements Ed25519 (RFC 8032), X25519 (RFC 7748) and an AEAD built from
|
||||||
|
HKDF-SHA256 + HMAC-SHA256 + a SHA-256 counter keystream.
|
||||||
|
|
||||||
|
Only ``hashlib``/``hmac``/``os`` are used so the application runs on a stock
|
||||||
|
Windows Python installation with no third-party packages.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import os
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Curve constants
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
P = 2 ** 255 - 19
|
||||||
|
L = 2 ** 252 + 27742317777372353535851937790883648493
|
||||||
|
D = -121665 * pow(121666, P - 2, P) % P
|
||||||
|
I = pow(2, (P - 1) // 4, P)
|
||||||
|
|
||||||
|
PUBLIC_KEY_LEN = 32
|
||||||
|
PRIVATE_KEY_LEN = 32
|
||||||
|
SIGNATURE_LEN = 64
|
||||||
|
SHARED_SECRET_LEN = 32
|
||||||
|
|
||||||
|
AEAD_SALT_LEN = 16
|
||||||
|
AEAD_NONCE_LEN = 12
|
||||||
|
AEAD_TAG_LEN = 16
|
||||||
|
|
||||||
|
|
||||||
|
def _sha512(data: bytes) -> bytes:
|
||||||
|
return hashlib.sha512(data).digest()
|
||||||
|
|
||||||
|
|
||||||
|
def _inv(x: int) -> int:
|
||||||
|
return pow(x, P - 2, P)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Ed25519 group arithmetic (extended twisted Edwards coordinates)
|
||||||
|
# A point is the tuple (X, Y, Z, T) with x = X/Z, y = Y/Z and T = X*Y/Z.
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
IDENTITY = (0, 1, 1, 0)
|
||||||
|
|
||||||
|
_BY = 4 * _inv(5) % P
|
||||||
|
|
||||||
|
|
||||||
|
def _xrecover(y: int) -> int:
|
||||||
|
xx = (y * y - 1) * _inv(D * y * y + 1) % P
|
||||||
|
x = pow(xx, (P + 3) // 8, P)
|
||||||
|
if (x * x - xx) % P:
|
||||||
|
x = x * I % P
|
||||||
|
if x % 2:
|
||||||
|
x = P - x
|
||||||
|
return x
|
||||||
|
|
||||||
|
|
||||||
|
_BX = _xrecover(_BY)
|
||||||
|
BASE = (_BX, _BY, 1, _BX * _BY % P)
|
||||||
|
|
||||||
|
|
||||||
|
def _edwards(p1, p2):
|
||||||
|
"""Unified (also complete for Ed25519) addition for a = -1."""
|
||||||
|
x1, y1, z1, t1 = p1
|
||||||
|
x2, y2, z2, t2 = p2
|
||||||
|
a = (y1 - x1) * (y2 - x2) % P
|
||||||
|
b = (y1 + x1) * (y2 + x2) % P
|
||||||
|
c = t1 * 2 * D * t2 % P
|
||||||
|
d = z1 * 2 * z2 % P
|
||||||
|
e = b - a
|
||||||
|
f = d - c
|
||||||
|
g = d + c
|
||||||
|
h = b + a
|
||||||
|
return (e * f % P, g * h % P, f * g % P, e * h % P)
|
||||||
|
|
||||||
|
|
||||||
|
def _scalarmult(point, scalar: int):
|
||||||
|
if scalar == 0:
|
||||||
|
return IDENTITY
|
||||||
|
result = IDENTITY
|
||||||
|
addend = point
|
||||||
|
while scalar > 0:
|
||||||
|
if scalar & 1:
|
||||||
|
result = _edwards(result, addend)
|
||||||
|
addend = _edwards(addend, addend)
|
||||||
|
scalar >>= 1
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _is_identity(point) -> bool:
|
||||||
|
x, y, z, _ = point
|
||||||
|
return x % P == 0 and (y - z) % P == 0
|
||||||
|
|
||||||
|
|
||||||
|
def _points_equal(p1, p2) -> bool:
|
||||||
|
x1, y1, z1, _ = p1
|
||||||
|
x2, y2, z2, _ = p2
|
||||||
|
return (x1 * z2 - x2 * z1) % P == 0 and (y1 * z2 - y2 * z1) % P == 0
|
||||||
|
|
||||||
|
|
||||||
|
def _encode_point(point) -> bytes:
|
||||||
|
x, y, z, _ = point
|
||||||
|
zi = _inv(z)
|
||||||
|
x = x * zi % P
|
||||||
|
y = y * zi % P
|
||||||
|
return (y | ((x & 1) << 255)).to_bytes(32, "little")
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_point(encoded: bytes):
|
||||||
|
if len(encoded) != 32:
|
||||||
|
raise ValueError("point must be 32 bytes")
|
||||||
|
data = int.from_bytes(encoded, "little")
|
||||||
|
y = data & ((1 << 255) - 1)
|
||||||
|
if y >= P:
|
||||||
|
raise ValueError("non-canonical point encoding")
|
||||||
|
sign = encoded[31] >> 7
|
||||||
|
x = _xrecover(y)
|
||||||
|
if (x & 1) != sign:
|
||||||
|
x = P - x
|
||||||
|
if (-x * x + y * y - 1 - D * x * x * y * y) % P:
|
||||||
|
raise ValueError("point is not on the curve")
|
||||||
|
return (x, y, 1, x * y % P)
|
||||||
|
|
||||||
|
|
||||||
|
def _is_small_order(point) -> bool:
|
||||||
|
return _is_identity(_scalarmult(point, 8))
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Ed25519 public API
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
def generate_private_key() -> bytes:
|
||||||
|
"""Return a fresh random 32-byte Ed25519 seed."""
|
||||||
|
return os.urandom(PRIVATE_KEY_LEN)
|
||||||
|
|
||||||
|
|
||||||
|
def _expanded_private_key(seed: bytes):
|
||||||
|
if len(seed) != PRIVATE_KEY_LEN:
|
||||||
|
raise ValueError("private key must be 32 bytes")
|
||||||
|
digest = _sha512(seed)
|
||||||
|
scalar = bytearray(digest[:32])
|
||||||
|
scalar[0] &= 248
|
||||||
|
scalar[31] &= 127
|
||||||
|
scalar[31] |= 64
|
||||||
|
return int.from_bytes(bytes(scalar), "little"), digest[32:]
|
||||||
|
|
||||||
|
|
||||||
|
def ed25519_public_key(seed: bytes) -> bytes:
|
||||||
|
scalar, _ = _expanded_private_key(seed)
|
||||||
|
return _encode_point(_scalarmult(BASE, scalar))
|
||||||
|
|
||||||
|
|
||||||
|
def ed25519_sign(seed: bytes, message: bytes) -> bytes:
|
||||||
|
scalar, prefix = _expanded_private_key(seed)
|
||||||
|
public = _encode_point(_scalarmult(BASE, scalar))
|
||||||
|
r = int.from_bytes(_sha512(prefix + message), "little") % L
|
||||||
|
r_point = _encode_point(_scalarmult(BASE, r))
|
||||||
|
k = int.from_bytes(_sha512(r_point + public + message), "little") % L
|
||||||
|
s = (r + k * scalar) % L
|
||||||
|
return r_point + s.to_bytes(32, "little")
|
||||||
|
|
||||||
|
|
||||||
|
def ed25519_verify(public: bytes, message: bytes, signature: bytes) -> bool:
|
||||||
|
if len(public) != PUBLIC_KEY_LEN or len(signature) != SIGNATURE_LEN:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
a_point = _decode_point(public)
|
||||||
|
r_point = _decode_point(signature[:32])
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
if _is_small_order(a_point) or _is_small_order(r_point):
|
||||||
|
return False
|
||||||
|
s = int.from_bytes(signature[32:], "little")
|
||||||
|
if s >= L:
|
||||||
|
return False
|
||||||
|
k = int.from_bytes(_sha512(signature[:32] + public + message), "little") % L
|
||||||
|
left = _scalarmult(BASE, s)
|
||||||
|
right = _edwards(r_point, _scalarmult(a_point, k))
|
||||||
|
return _points_equal(left, right)
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# X25519 (RFC 7748)
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
def x25519(private_scalar: bytes, peer_public: bytes) -> bytes:
|
||||||
|
if len(private_scalar) != 32 or len(peer_public) != 32:
|
||||||
|
raise ValueError("x25519 inputs must be 32 bytes")
|
||||||
|
scalar = bytearray(private_scalar)
|
||||||
|
scalar[0] &= 248
|
||||||
|
scalar[31] &= 127
|
||||||
|
scalar[31] |= 64
|
||||||
|
k = int.from_bytes(bytes(scalar), "little")
|
||||||
|
x1 = int.from_bytes(peer_public, "little") & ((1 << 255) - 1)
|
||||||
|
|
||||||
|
x2, z2, x3, z3 = 1, 0, x1, 1
|
||||||
|
swap = 0
|
||||||
|
for bit in reversed(range(255)):
|
||||||
|
kt = (k >> bit) & 1
|
||||||
|
swap ^= kt
|
||||||
|
if swap:
|
||||||
|
x2, x3 = x3, x2
|
||||||
|
z2, z3 = z3, z2
|
||||||
|
swap = kt
|
||||||
|
a = (x2 + z2) % P
|
||||||
|
aa = a * a % P
|
||||||
|
b = (x2 - z2) % P
|
||||||
|
bb = b * b % P
|
||||||
|
e = (aa - bb) % P
|
||||||
|
c = (x3 + z3) % P
|
||||||
|
d = (x3 - z3) % P
|
||||||
|
da = d * a % P
|
||||||
|
cb = c * b % P
|
||||||
|
x3 = pow(da + cb, 2, P)
|
||||||
|
z3 = x1 * pow(da - cb, 2, P) % P
|
||||||
|
x2 = aa * bb % P
|
||||||
|
z2 = e * (aa + 121665 * e) % P
|
||||||
|
if swap:
|
||||||
|
x2, x3 = x3, x2
|
||||||
|
z2, z3 = z3, z2
|
||||||
|
if z2 % P == 0:
|
||||||
|
raise ValueError("x25519 produced the all-zero shared secret")
|
||||||
|
return (x2 * _inv(z2) % P).to_bytes(32, "little")
|
||||||
|
|
||||||
|
|
||||||
|
def ed25519_private_to_x25519(seed: bytes) -> bytes:
|
||||||
|
"""Convert an Ed25519 seed into an X25519 scalar."""
|
||||||
|
if len(seed) != PRIVATE_KEY_LEN:
|
||||||
|
raise ValueError("private key must be 32 bytes")
|
||||||
|
return hashlib.sha512(seed).digest()[:32]
|
||||||
|
|
||||||
|
|
||||||
|
def ed25519_public_to_x25519(public: bytes) -> bytes:
|
||||||
|
"""Convert an Ed25519 public key into an X25519 public key (u-coordinate)."""
|
||||||
|
if len(public) != PUBLIC_KEY_LEN:
|
||||||
|
raise ValueError("public key must be 32 bytes")
|
||||||
|
y = int.from_bytes(public, "little") & ((1 << 255) - 1)
|
||||||
|
if y >= P:
|
||||||
|
raise ValueError("non-canonical public key")
|
||||||
|
if (1 - y) % P == 0:
|
||||||
|
raise ValueError("public key has no X25519 counterpart")
|
||||||
|
return ((1 + y) * _inv((1 - y) % P) % P).to_bytes(32, "little")
|
||||||
|
|
||||||
|
|
||||||
|
def shared_secret(seed: bytes, peer_public: bytes) -> bytes:
|
||||||
|
"""X25519 ECDH between our Ed25519 seed and a peer's Ed25519 public key."""
|
||||||
|
return x25519(ed25519_private_to_x25519(seed), ed25519_public_to_x25519(peer_public))
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# HKDF-SHA256 and AEAD
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
def hkdf_sha256(secret: bytes, salt: bytes, info: bytes, length: int) -> bytes:
|
||||||
|
prk = hmac.new(salt or b"\x00" * 32, secret, hashlib.sha256).digest()
|
||||||
|
output = bytearray()
|
||||||
|
block = b""
|
||||||
|
counter = 1
|
||||||
|
while len(output) < length:
|
||||||
|
block = hmac.new(prk, block + info + bytes([counter]), hashlib.sha256).digest()
|
||||||
|
output += block
|
||||||
|
counter += 1
|
||||||
|
return bytes(output[:length])
|
||||||
|
|
||||||
|
|
||||||
|
def _keystream(key: bytes, nonce: bytes, length: int) -> bytes:
|
||||||
|
output = bytearray()
|
||||||
|
counter = 0
|
||||||
|
while len(output) < length:
|
||||||
|
output += hashlib.sha256(key + nonce + counter.to_bytes(8, "big")).digest()
|
||||||
|
counter += 1
|
||||||
|
return bytes(output[:length])
|
||||||
|
|
||||||
|
|
||||||
|
def _xor(data: bytes, other: bytes) -> bytes:
|
||||||
|
if not data:
|
||||||
|
return b""
|
||||||
|
return (
|
||||||
|
int.from_bytes(data, "big") ^ int.from_bytes(other, "big")
|
||||||
|
).to_bytes(len(data), "big")
|
||||||
|
|
||||||
|
|
||||||
|
def _derive_aead_keys(key: bytes, salt: bytes):
|
||||||
|
enc = hkdf_sha256(key, salt, b"dhtchat/v1 enc", 32)
|
||||||
|
mac = hkdf_sha256(key, salt, b"dhtchat/v1 mac", 32)
|
||||||
|
return enc, mac
|
||||||
|
|
||||||
|
|
||||||
|
def aead_encrypt(key: bytes, plaintext: bytes, aad: bytes = b"") -> bytes:
|
||||||
|
"""Encrypt with a random salt+nonce; returns salt || nonce || ciphertext || tag."""
|
||||||
|
salt = os.urandom(AEAD_SALT_LEN)
|
||||||
|
nonce = os.urandom(AEAD_NONCE_LEN)
|
||||||
|
enc_key, mac_key = _derive_aead_keys(key, salt)
|
||||||
|
stream = _keystream(enc_key, nonce, len(plaintext))
|
||||||
|
ciphertext = _xor(plaintext, stream)
|
||||||
|
tag = hmac.new(mac_key, salt + nonce + aad + ciphertext, hashlib.sha256).digest()
|
||||||
|
return salt + nonce + ciphertext + tag[:AEAD_TAG_LEN]
|
||||||
|
|
||||||
|
|
||||||
|
def aead_decrypt(key: bytes, blob: bytes, aad: bytes = b"") -> bytes:
|
||||||
|
minimum = AEAD_SALT_LEN + AEAD_NONCE_LEN + AEAD_TAG_LEN
|
||||||
|
if len(blob) < minimum:
|
||||||
|
raise ValueError("ciphertext is too short")
|
||||||
|
salt = blob[:AEAD_SALT_LEN]
|
||||||
|
nonce = blob[AEAD_SALT_LEN:AEAD_SALT_LEN + AEAD_NONCE_LEN]
|
||||||
|
ciphertext = blob[AEAD_SALT_LEN + AEAD_NONCE_LEN:-AEAD_TAG_LEN]
|
||||||
|
tag = blob[-AEAD_TAG_LEN:]
|
||||||
|
enc_key, mac_key = _derive_aead_keys(key, salt)
|
||||||
|
expected = hmac.new(
|
||||||
|
mac_key, salt + nonce + aad + ciphertext, hashlib.sha256
|
||||||
|
).digest()[:AEAD_TAG_LEN]
|
||||||
|
if not hmac.compare_digest(tag, expected):
|
||||||
|
raise ValueError("message authentication failed")
|
||||||
|
return _xor(ciphertext, _keystream(enc_key, nonce, len(ciphertext)))
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
# Helpers
|
||||||
|
# --------------------------------------------------------------------------
|
||||||
|
def fingerprint(public: bytes, length: int = 16) -> str:
|
||||||
|
"""Short human readable fingerprint of a public key (SHA-1 based)."""
|
||||||
|
return hashlib.sha1(public).hexdigest()[:length]
|
||||||
|
|
||||||
|
|
||||||
|
def node_id_from_public(public: bytes) -> bytes:
|
||||||
|
"""20-byte node id derived from the public key (SHA-1, Kademlia space)."""
|
||||||
|
return hashlib.sha1(public).digest()
|
||||||
+733
@@ -0,0 +1,733 @@
|
|||||||
|
"""Tkinter desktop client.
|
||||||
|
|
||||||
|
The DHT lives in a background thread (see :mod:`dhtchat.app`); Tkinter owns
|
||||||
|
the main thread. Events travel from the loop to the UI through
|
||||||
|
:attr:`ChatApp.events`, drained by a periodic ``after`` callback, so no widget
|
||||||
|
is ever touched from another thread.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import tkinter as tk
|
||||||
|
from pathlib import Path
|
||||||
|
from tkinter import messagebox, simpledialog, ttk
|
||||||
|
|
||||||
|
from . import __version__
|
||||||
|
from .app import ChatApp
|
||||||
|
|
||||||
|
POLL_MS = 120
|
||||||
|
MAX_LINES = 4000
|
||||||
|
MAX_HISTORY = 500
|
||||||
|
LOG_KEY = "__log__"
|
||||||
|
LOG_TITLE = "运行日志"
|
||||||
|
|
||||||
|
|
||||||
|
def load_nickname(profile_dir: Path) -> str:
|
||||||
|
try:
|
||||||
|
return (profile_dir / "nickname.txt").read_text(encoding="utf-8").strip()
|
||||||
|
except OSError:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def save_nickname(profile_dir: Path, nickname: str) -> None:
|
||||||
|
try:
|
||||||
|
profile_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
(profile_dir / "nickname.txt").write_text(nickname, encoding="utf-8")
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ChatWindow:
|
||||||
|
"""The whole user interface."""
|
||||||
|
|
||||||
|
def __init__(self, root: tk.Tk, app: ChatApp, args: argparse.Namespace) -> None:
|
||||||
|
self.root = root
|
||||||
|
self.app = app
|
||||||
|
self.args = args
|
||||||
|
self.default_room = args.room or "大厅"
|
||||||
|
self.nickname = (args.nick or load_nickname(app.profile_dir)).strip()
|
||||||
|
self.conversations: dict[str, dict] = {}
|
||||||
|
self.nodes: dict[str, dict] = {}
|
||||||
|
self.current: str | None = None
|
||||||
|
self.last_status = ""
|
||||||
|
self._closing = False
|
||||||
|
|
||||||
|
self._build_ui()
|
||||||
|
self.root.after(POLL_MS, self._pump)
|
||||||
|
self.root.after(80, self.boot)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# construction
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _build_ui(self) -> None:
|
||||||
|
self.root.title("DHT 聊天")
|
||||||
|
self.root.geometry("1000x660")
|
||||||
|
self.root.minsize(760, 460)
|
||||||
|
self.root.protocol("WM_DELETE_WINDOW", self.on_close)
|
||||||
|
self._apply_theme()
|
||||||
|
self._build_menu()
|
||||||
|
|
||||||
|
toolbar = ttk.Frame(self.root, padding=(8, 6))
|
||||||
|
toolbar.pack(side="top", fill="x")
|
||||||
|
self._build_toolbar(toolbar)
|
||||||
|
|
||||||
|
paned = ttk.PanedWindow(self.root, orient="horizontal")
|
||||||
|
paned.pack(side="top", fill="both", expand=True, padx=8, pady=(0, 4))
|
||||||
|
|
||||||
|
sidebar = ttk.Frame(paned)
|
||||||
|
paned.add(sidebar, weight=1)
|
||||||
|
self._build_sidebar(sidebar)
|
||||||
|
|
||||||
|
right = ttk.Frame(paned)
|
||||||
|
paned.add(right, weight=3)
|
||||||
|
self._build_chat_area(right)
|
||||||
|
|
||||||
|
status = ttk.Frame(self.root, padding=(8, 3))
|
||||||
|
status.pack(side="bottom", fill="x")
|
||||||
|
self.status_label = ttk.Label(status, text="正在启动…", anchor="w")
|
||||||
|
self.status_label.pack(side="left", fill="x", expand=True)
|
||||||
|
|
||||||
|
def _apply_theme(self) -> None:
|
||||||
|
style = ttk.Style()
|
||||||
|
for theme in ("vista", "winnative", "clam"):
|
||||||
|
if theme in style.theme_names():
|
||||||
|
try:
|
||||||
|
style.theme_use(theme)
|
||||||
|
except tk.TclError:
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
self.font_ui = ("Microsoft YaHei UI", 10) if self._has_cjk_font() else ("Segoe UI", 10)
|
||||||
|
self.font_mono = ("Consolas", 10)
|
||||||
|
style.configure("Treeview", font=self.font_ui, rowheight=22)
|
||||||
|
style.configure("TLabel", font=self.font_ui)
|
||||||
|
style.configure("TButton", font=self.font_ui)
|
||||||
|
style.configure("TLabelframe.Label", font=self.font_ui)
|
||||||
|
|
||||||
|
def _has_cjk_font(self) -> bool:
|
||||||
|
try:
|
||||||
|
return any(
|
||||||
|
"YaHei" in name
|
||||||
|
for name in self.root.tk.call("font", "families") # type: ignore[attr-defined]
|
||||||
|
)
|
||||||
|
except tk.TclError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _build_menu(self) -> None:
|
||||||
|
menubar = tk.Menu(self.root)
|
||||||
|
|
||||||
|
file_menu = tk.Menu(menubar, tearoff=0)
|
||||||
|
file_menu.add_command(label="复制我的地址", command=self.copy_my_address)
|
||||||
|
file_menu.add_command(label="复制我的节点 ID", command=self.copy_my_node_id)
|
||||||
|
file_menu.add_command(label="改昵称…", command=self.change_nickname)
|
||||||
|
file_menu.add_separator()
|
||||||
|
file_menu.add_command(label="退出", command=self.on_close)
|
||||||
|
menubar.add_cascade(label="文件", menu=file_menu)
|
||||||
|
|
||||||
|
room_menu = tk.Menu(menubar, tearoff=0)
|
||||||
|
room_menu.add_command(label="加入聊天室…", command=self.prompt_join_room)
|
||||||
|
room_menu.add_command(label="离开当前聊天室", command=self.leave_current_room)
|
||||||
|
room_menu.add_command(label="重新从 DHT 拉取历史", command=self.reload_room)
|
||||||
|
menubar.add_cascade(label="聊天室", menu=room_menu)
|
||||||
|
|
||||||
|
net_menu = tk.Menu(menubar, tearoff=0)
|
||||||
|
net_menu.add_command(label="添加引导节点…", command=self.prompt_bootstrap)
|
||||||
|
net_menu.add_command(label="查找用户昵称…", command=self.prompt_lookup)
|
||||||
|
net_menu.add_command(label="重新公布我的资料", command=self.app.refresh_profile)
|
||||||
|
menubar.add_cascade(label="网络", menu=net_menu)
|
||||||
|
|
||||||
|
help_menu = tk.Menu(menubar, tearoff=0)
|
||||||
|
help_menu.add_command(label="使用说明", command=self.show_help)
|
||||||
|
help_menu.add_command(label="关于", command=self.show_about)
|
||||||
|
menubar.add_cascade(label="帮助", menu=help_menu)
|
||||||
|
|
||||||
|
self.root.config(menu=menubar)
|
||||||
|
|
||||||
|
def _build_toolbar(self, parent: ttk.Frame) -> None:
|
||||||
|
ttk.Label(parent, text="昵称").pack(side="left")
|
||||||
|
self.nick_var = tk.StringVar(value=self.nickname)
|
||||||
|
self.nick_entry = ttk.Entry(parent, textvariable=self.nick_var, width=14)
|
||||||
|
self.nick_entry.pack(side="left", padx=(4, 2))
|
||||||
|
self.nick_entry.bind("<Return>", lambda _event: self.change_nickname())
|
||||||
|
ttk.Button(parent, text="应用", width=6, command=self.change_nickname).pack(side="left", padx=(0, 12))
|
||||||
|
|
||||||
|
ttk.Label(parent, text="引导地址").pack(side="left")
|
||||||
|
self.bootstrap_var = tk.StringVar()
|
||||||
|
entry = ttk.Entry(parent, textvariable=self.bootstrap_var, width=22)
|
||||||
|
entry.pack(side="left", padx=(4, 2))
|
||||||
|
entry.bind("<Return>", lambda _event: self.prompt_bootstrap())
|
||||||
|
ttk.Button(parent, text="连接", width=6, command=self.prompt_bootstrap).pack(side="left", padx=(0, 12))
|
||||||
|
|
||||||
|
ttk.Button(parent, text="复制我的地址", command=self.copy_my_address).pack(side="left")
|
||||||
|
ttk.Button(parent, text="找用户", width=8, command=self.prompt_lookup).pack(side="left", padx=6)
|
||||||
|
|
||||||
|
def _build_sidebar(self, parent: ttk.Frame) -> None:
|
||||||
|
rooms = ttk.Labelframe(parent, text="会话", padding=4)
|
||||||
|
rooms.pack(side="top", fill="both", expand=True)
|
||||||
|
|
||||||
|
self.tree = ttk.Treeview(rooms, columns=("detail",), show="tree headings", selectmode="browse")
|
||||||
|
self.tree.heading("#0", text="名称")
|
||||||
|
self.tree.column("#0", width=160, stretch=True)
|
||||||
|
self.tree.heading("detail", text="详情")
|
||||||
|
self.tree.column("detail", width=70, anchor="e", stretch=False)
|
||||||
|
self.tree.pack(side="top", fill="both", expand=True)
|
||||||
|
self.tree.bind("<<TreeviewSelect>>", self._on_select_conversation)
|
||||||
|
|
||||||
|
buttons = ttk.Frame(rooms)
|
||||||
|
buttons.pack(side="bottom", fill="x", pady=(4, 0))
|
||||||
|
ttk.Button(buttons, text="加入聊天室", width=11, command=self.prompt_join_room).pack(side="left")
|
||||||
|
ttk.Button(buttons, text="发起私聊", width=10, command=self.prompt_direct).pack(side="right")
|
||||||
|
|
||||||
|
peers = ttk.Labelframe(parent, text="已知节点", padding=4)
|
||||||
|
peers.pack(side="bottom", fill="both", expand=False, pady=(6, 0))
|
||||||
|
self.peer_tree = ttk.Treeview(
|
||||||
|
peers, columns=("nick", "address"), show="headings", selectmode="browse", height=6
|
||||||
|
)
|
||||||
|
self.peer_tree.heading("nick", text="昵称")
|
||||||
|
self.peer_tree.heading("address", text="地址")
|
||||||
|
self.peer_tree.column("nick", width=110, stretch=True)
|
||||||
|
self.peer_tree.column("address", width=130, stretch=True)
|
||||||
|
self.peer_tree.pack(side="top", fill="both", expand=True)
|
||||||
|
self.peer_tree.bind("<Double-1>", self._on_peer_activate)
|
||||||
|
|
||||||
|
def _build_chat_area(self, parent: ttk.Frame) -> None:
|
||||||
|
header = ttk.Frame(parent, padding=(0, 2))
|
||||||
|
header.pack(side="top", fill="x")
|
||||||
|
self.title_label = ttk.Label(header, text="未选择会话", font=("Microsoft YaHei UI", 11, "bold"))
|
||||||
|
self.title_label.pack(side="left")
|
||||||
|
self.subtitle_label = ttk.Label(header, text="", foreground="#666666")
|
||||||
|
self.subtitle_label.pack(side="left", padx=8)
|
||||||
|
|
||||||
|
body = ttk.Frame(parent)
|
||||||
|
body.pack(side="top", fill="both", expand=True)
|
||||||
|
self.transcript = tk.Text(
|
||||||
|
body, wrap="word", state="disabled", font=self.font_ui,
|
||||||
|
background="#fbfbfb", relief="flat", padx=8, pady=6,
|
||||||
|
)
|
||||||
|
scroll = ttk.Scrollbar(body, orient="vertical", command=self.transcript.yview)
|
||||||
|
self.transcript.configure(yscrollcommand=scroll.set)
|
||||||
|
scroll.pack(side="right", fill="y")
|
||||||
|
self.transcript.pack(side="left", fill="both", expand=True)
|
||||||
|
|
||||||
|
self.transcript.tag_configure("meta", foreground="#8a8a8a", font=self.font_ui)
|
||||||
|
self.transcript.tag_configure("own", foreground="#0b5394", font=self.font_ui)
|
||||||
|
self.transcript.tag_configure("other", foreground="#222222", font=self.font_ui)
|
||||||
|
self.transcript.tag_configure("system", foreground="#9a6a00", font=self.font_ui)
|
||||||
|
self.transcript.tag_configure("error", foreground="#a31515", font=self.font_ui)
|
||||||
|
self.transcript.tag_configure("nick", font=("Microsoft YaHei UI", 10, "bold"))
|
||||||
|
self.transcript.configure(state="disabled")
|
||||||
|
|
||||||
|
composer = ttk.Frame(parent, padding=(0, 6, 0, 0))
|
||||||
|
composer.pack(side="bottom", fill="x")
|
||||||
|
self.input_var = tk.StringVar()
|
||||||
|
self.entry = ttk.Entry(composer, textvariable=self.input_var, font=self.font_ui)
|
||||||
|
self.entry.pack(side="left", fill="x", expand=True)
|
||||||
|
self.entry.bind("<Return>", lambda _event: self.send_current())
|
||||||
|
self.entry.bind("<Up>", self._recall_history)
|
||||||
|
self.send_button = ttk.Button(composer, text="发送", width=8, command=self.send_current)
|
||||||
|
self.send_button.pack(side="left", padx=(6, 0))
|
||||||
|
self.input_history: list[str] = []
|
||||||
|
self.history_pos = 0
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# startup / shutdown
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def boot(self) -> None:
|
||||||
|
if not self.nickname:
|
||||||
|
self.nickname = simpledialog.askstring(
|
||||||
|
"取个名字", "请输入你的昵称(其它人靠它找到你):", parent=self.root
|
||||||
|
) or ""
|
||||||
|
self.nickname = self.nickname.strip() or f"用户{int(time.time()) % 10000}"
|
||||||
|
self.nick_var.set(self.nickname)
|
||||||
|
save_nickname(self.app.profile_dir, self.nickname)
|
||||||
|
self.log(f"正在启动节点,端口 {self.args.port or '自动'}…")
|
||||||
|
threading.Thread(target=self._start_backend, name="dhtchat-boot", daemon=True).start()
|
||||||
|
|
||||||
|
def _start_backend(self) -> None:
|
||||||
|
ok = self.app.start(
|
||||||
|
self.nickname,
|
||||||
|
port=self.args.port,
|
||||||
|
bootstrap=list(self.args.bootstrap),
|
||||||
|
discovery=not self.args.no_discovery,
|
||||||
|
host=self.args.host,
|
||||||
|
)
|
||||||
|
if not ok:
|
||||||
|
self.root.after(0, self._startup_failed)
|
||||||
|
|
||||||
|
def _startup_failed(self) -> None:
|
||||||
|
messagebox.showerror(
|
||||||
|
"启动失败",
|
||||||
|
self.app.last_error or "无法启动 DHT 节点,请检查端口是否被占用。",
|
||||||
|
parent=self.root,
|
||||||
|
)
|
||||||
|
self.log(f"启动失败: {self.app.last_error}", level="error")
|
||||||
|
|
||||||
|
def on_close(self) -> None:
|
||||||
|
if self._closing:
|
||||||
|
return
|
||||||
|
self._closing = True
|
||||||
|
try:
|
||||||
|
self.root.config(cursor="watch")
|
||||||
|
self.root.update_idletasks()
|
||||||
|
except tk.TclError:
|
||||||
|
pass
|
||||||
|
self.app.stop(timeout=3.0)
|
||||||
|
self.root.destroy()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# event pump
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _pump(self) -> None:
|
||||||
|
if self._closing:
|
||||||
|
return
|
||||||
|
for event in self.app.poll_events():
|
||||||
|
try:
|
||||||
|
self._handle_event(event)
|
||||||
|
except Exception as exc: # pragma: no cover - keep the UI alive
|
||||||
|
self.log(f"界面错误: {exc}", level="error")
|
||||||
|
self.root.after(POLL_MS, self._pump)
|
||||||
|
|
||||||
|
def _handle_event(self, event: dict) -> None:
|
||||||
|
kind = event.get("type")
|
||||||
|
if kind == "log":
|
||||||
|
self.log(str(event.get("text") or ""), level=str(event.get("level") or "info"))
|
||||||
|
elif kind == "started":
|
||||||
|
self._on_started(event)
|
||||||
|
elif kind == "ready":
|
||||||
|
self.log("已就绪,可以开始聊天了")
|
||||||
|
self.join_room(self.default_room, announce=True)
|
||||||
|
elif kind == "peers":
|
||||||
|
self._on_peers(event)
|
||||||
|
elif kind == "room_joined":
|
||||||
|
self.ensure_conversation("room", str(event.get("room") or ""), announce=False)
|
||||||
|
elif kind == "room_left":
|
||||||
|
self.remove_conversation(f"room:{event.get('room')}")
|
||||||
|
elif kind == "room_members":
|
||||||
|
self._on_members(event)
|
||||||
|
elif kind == "room_message":
|
||||||
|
self.ensure_conversation("room", str(event.get("room") or ""), announce=False)
|
||||||
|
key = f"room:{event.get('room')}"
|
||||||
|
self.append_entry(key, {
|
||||||
|
"nick": str(event.get("nick") or "?"),
|
||||||
|
"text": str(event.get("text") or ""),
|
||||||
|
"own": bool(event.get("own")),
|
||||||
|
"history": bool(event.get("history")),
|
||||||
|
"ts": float(event.get("ts") or time.time()),
|
||||||
|
"system": False,
|
||||||
|
})
|
||||||
|
elif kind == "direct_message":
|
||||||
|
peer = str(event.get("peer") or "?")
|
||||||
|
key = self.ensure_conversation("direct", peer, announce=False)
|
||||||
|
self.append_entry(key, {
|
||||||
|
"nick": "我" if event.get("own") else peer,
|
||||||
|
"text": str(event.get("text") or ""),
|
||||||
|
"own": bool(event.get("own")),
|
||||||
|
"history": False,
|
||||||
|
"ts": float(event.get("ts") or time.time()),
|
||||||
|
"system": False,
|
||||||
|
})
|
||||||
|
if not event.get("own"):
|
||||||
|
self.add_node(event.get("peer_node") or "", peer, "")
|
||||||
|
elif kind == "direct_status":
|
||||||
|
key = self.ensure_conversation("direct", str(event.get("peer") or "?"), announce=False)
|
||||||
|
delivered = bool(event.get("delivered"))
|
||||||
|
self.append_entry(key, {
|
||||||
|
"nick": "系统",
|
||||||
|
"text": "已直接送达" if delivered else "对方不在线,消息已存入 DHT 信箱,等待对方上线",
|
||||||
|
"own": False, "history": False, "ts": time.time(), "system": True,
|
||||||
|
})
|
||||||
|
elif kind == "contact":
|
||||||
|
self._on_contact(event)
|
||||||
|
elif kind == "profile":
|
||||||
|
self.log(
|
||||||
|
f"{event.get('nick')} 节点 {str(event.get('node'))[:12]}… "
|
||||||
|
f"地址 {event.get('host')}:{event.get('port')}"
|
||||||
|
)
|
||||||
|
elif kind == "stopped":
|
||||||
|
self.log("节点已停止")
|
||||||
|
|
||||||
|
def _on_started(self, event: dict) -> None:
|
||||||
|
self.node_id = str(event.get("node_id") or "")
|
||||||
|
self.fingerprint = str(event.get("fingerprint") or "")
|
||||||
|
address = str(event.get("address") or "")
|
||||||
|
self.root.title(f"DHT 聊天 - {event.get('nickname')}")
|
||||||
|
self.log(f"我的地址 {address}(把它告诉别人作为引导地址)")
|
||||||
|
self.log(f"节点 ID {self.node_id}")
|
||||||
|
self._refresh_status()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# conversations
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
@staticmethod
|
||||||
|
def _key(kind: str, name: str) -> str:
|
||||||
|
return f"{kind}:{name}"
|
||||||
|
|
||||||
|
def ensure_conversation(self, kind: str, name: str, announce: bool = True) -> str:
|
||||||
|
key = LOG_KEY if kind == "log" else self._key(kind, name)
|
||||||
|
if key not in self.conversations:
|
||||||
|
title = LOG_TITLE if kind == "log" else (
|
||||||
|
f"[房间] {name}" if kind == "room" else f"[私聊] {name}"
|
||||||
|
)
|
||||||
|
self.conversations[key] = {
|
||||||
|
"kind": kind, "name": name, "title": title, "entries": [],
|
||||||
|
"members": [], "node": "",
|
||||||
|
}
|
||||||
|
self.tree.insert("", "end", iid=key, text=title, values=("",))
|
||||||
|
if self.current is None:
|
||||||
|
self.select(key)
|
||||||
|
if kind == "room" and announce:
|
||||||
|
self.app.join_room(name)
|
||||||
|
return key
|
||||||
|
|
||||||
|
def remove_conversation(self, key: str) -> None:
|
||||||
|
self.conversations.pop(key, None)
|
||||||
|
try:
|
||||||
|
self.tree.delete(key)
|
||||||
|
except tk.TclError:
|
||||||
|
pass
|
||||||
|
if self.current == key:
|
||||||
|
self.current = None
|
||||||
|
remaining = list(self.conversations)
|
||||||
|
if remaining:
|
||||||
|
self.select(remaining[0])
|
||||||
|
else:
|
||||||
|
self._render()
|
||||||
|
|
||||||
|
def select(self, key: str) -> None:
|
||||||
|
if key not in self.conversations:
|
||||||
|
return
|
||||||
|
self.current = key
|
||||||
|
if self.tree.exists(key):
|
||||||
|
self.tree.selection_set(key)
|
||||||
|
self._render()
|
||||||
|
|
||||||
|
def _on_select_conversation(self, _event=None) -> None:
|
||||||
|
selection = self.tree.selection()
|
||||||
|
if selection and selection[0] != self.current:
|
||||||
|
self.current = selection[0]
|
||||||
|
self._render()
|
||||||
|
|
||||||
|
def _room_of_current(self) -> str:
|
||||||
|
conversation = self.conversations.get(self.current or "")
|
||||||
|
if conversation and conversation["kind"] == "room":
|
||||||
|
return str(conversation["name"])
|
||||||
|
return self.default_room
|
||||||
|
|
||||||
|
def append_entry(self, key: str, entry: dict) -> None:
|
||||||
|
conversation = self.conversations.get(key)
|
||||||
|
if conversation is None:
|
||||||
|
return
|
||||||
|
conversation["entries"].append(entry)
|
||||||
|
if len(conversation["entries"]) > MAX_HISTORY:
|
||||||
|
del conversation["entries"][:-MAX_HISTORY]
|
||||||
|
if key == self.current:
|
||||||
|
self._write_entry(entry)
|
||||||
|
if entry.get("system") is not True:
|
||||||
|
self._bump_detail(key)
|
||||||
|
|
||||||
|
def _bump_detail(self, key: str) -> None:
|
||||||
|
conversation = self.conversations.get(key)
|
||||||
|
if conversation is None or not self.tree.exists(key):
|
||||||
|
return
|
||||||
|
count = sum(1 for e in conversation["entries"] if not e.get("system"))
|
||||||
|
self.tree.set(key, "detail", str(count))
|
||||||
|
|
||||||
|
def _render(self) -> None:
|
||||||
|
self.transcript.configure(state="normal")
|
||||||
|
self.transcript.delete("1.0", "end")
|
||||||
|
conversation = self.conversations.get(self.current or "")
|
||||||
|
if conversation is None:
|
||||||
|
self.title_label.config(text="未选择会话")
|
||||||
|
self.subtitle_label.config(text="")
|
||||||
|
self.transcript.configure(state="disabled")
|
||||||
|
return
|
||||||
|
self.title_label.config(text=conversation["title"])
|
||||||
|
self._update_subtitle(conversation)
|
||||||
|
for entry in conversation["entries"][-MAX_LINES:]:
|
||||||
|
self._write_entry(entry)
|
||||||
|
self.transcript.configure(state="disabled")
|
||||||
|
self.transcript.see("end")
|
||||||
|
|
||||||
|
def _update_subtitle(self, conversation: dict) -> None:
|
||||||
|
if conversation["kind"] == "room":
|
||||||
|
names = [str(m.get("nick") or "?") for m in conversation["members"]]
|
||||||
|
self.subtitle_label.config(
|
||||||
|
text=f"在线成员 {len(names)}:" + (", ".join(names) if names else "暂无")
|
||||||
|
)
|
||||||
|
elif conversation["kind"] == "direct":
|
||||||
|
node = str(conversation.get("node") or "")
|
||||||
|
self.subtitle_label.config(
|
||||||
|
text=f"端到端加密 · 节点 {node[:12]}…" if node else "端到端加密"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.subtitle_label.config(text="网络与系统事件")
|
||||||
|
|
||||||
|
def _write_entry(self, entry: dict) -> None:
|
||||||
|
self.transcript.configure(state="normal")
|
||||||
|
stamp = time.strftime("%H:%M:%S", time.localtime(float(entry.get("ts") or time.time())))
|
||||||
|
self.transcript.insert("end", f"[{stamp}] ", ("meta",))
|
||||||
|
nick = str(entry.get("nick") or "?")
|
||||||
|
if entry.get("system"):
|
||||||
|
self.transcript.insert("end", f"{nick}: ", ("system",))
|
||||||
|
self.transcript.insert("end", f"{entry.get('text')}\n", ("system",))
|
||||||
|
else:
|
||||||
|
tag = "own" if entry.get("own") else "other"
|
||||||
|
self.transcript.insert("end", f"{nick}", ("nick", tag))
|
||||||
|
if entry.get("history"):
|
||||||
|
self.transcript.insert("end", "(历史)", ("meta",))
|
||||||
|
self.transcript.insert("end", f" {entry.get('text')}\n", (tag,))
|
||||||
|
self.transcript.configure(state="disabled")
|
||||||
|
self.transcript.see("end")
|
||||||
|
|
||||||
|
def log(self, text: str, level: str = "info") -> None:
|
||||||
|
if not text:
|
||||||
|
return
|
||||||
|
key = self.ensure_conversation("log", LOG_TITLE, announce=False)
|
||||||
|
entry = {
|
||||||
|
"nick": {"error": "错误", "warn": "提示"}.get(level, "信息"),
|
||||||
|
"text": text, "own": False, "history": False,
|
||||||
|
"ts": time.time(), "system": True,
|
||||||
|
}
|
||||||
|
self.conversations[key]["entries"].append(entry)
|
||||||
|
if len(self.conversations[key]["entries"]) > MAX_HISTORY:
|
||||||
|
del self.conversations[key]["entries"][:-MAX_HISTORY]
|
||||||
|
if key == self.current:
|
||||||
|
self._write_entry(entry)
|
||||||
|
self.last_status = text
|
||||||
|
self.status_label.config(text=text)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# nodes
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _on_peers(self, event: dict) -> None:
|
||||||
|
rows = event.get("peers") or []
|
||||||
|
self.peer_tree.delete(*self.peer_tree.get_children())
|
||||||
|
self.nodes.clear()
|
||||||
|
for row in rows:
|
||||||
|
node = str(row.get("node_id") or "")
|
||||||
|
nickname = str(row.get("nickname") or "") or "(未知)"
|
||||||
|
self.nodes[node] = {"nick": nickname, "address": str(row.get("address") or "")}
|
||||||
|
self.peer_tree.insert("", "end", iid=node, values=(nickname, row.get("address") or ""))
|
||||||
|
info = event.get("info") or {}
|
||||||
|
stats = info.get("stats") or {}
|
||||||
|
self._refresh_status(
|
||||||
|
peers=int(event.get("count") or len(rows)),
|
||||||
|
records=int(info.get("records") or 0),
|
||||||
|
stats=stats,
|
||||||
|
)
|
||||||
|
|
||||||
|
def add_node(self, node_id: str, nickname: str, address: str) -> None:
|
||||||
|
node_id = str(node_id or "")
|
||||||
|
if not node_id:
|
||||||
|
return
|
||||||
|
row = self.nodes.setdefault(node_id, {"nick": "", "address": ""})
|
||||||
|
row["nick"] = nickname or row["nick"] or "(未知)"
|
||||||
|
row["address"] = address or row["address"]
|
||||||
|
if not self.peer_tree.exists(node_id):
|
||||||
|
self.peer_tree.insert("", "end", iid=node_id, values=(row["nick"], row["address"]))
|
||||||
|
|
||||||
|
def _on_contact(self, event: dict) -> None:
|
||||||
|
node = str(event.get("node") or "")
|
||||||
|
nick = str(event.get("nick") or "")
|
||||||
|
self.add_node(node, nick, str(event.get("host") or ""))
|
||||||
|
key = self._key("direct", nick)
|
||||||
|
if key in self.conversations:
|
||||||
|
self.conversations[key]["node"] = node
|
||||||
|
self.conversations[key]["nick"] = nick
|
||||||
|
|
||||||
|
def _on_peer_activate(self, _event=None) -> None:
|
||||||
|
selection = self.peer_tree.selection()
|
||||||
|
if not selection:
|
||||||
|
return
|
||||||
|
row = self.nodes.get(selection[0]) or {}
|
||||||
|
nickname = str(row.get("nick") or "")
|
||||||
|
if nickname and nickname != "(未知)":
|
||||||
|
self.open_direct(nickname)
|
||||||
|
|
||||||
|
def _refresh_status(self, peers: int | None = None, records: int | None = None,
|
||||||
|
stats: dict | None = None) -> None:
|
||||||
|
info = self.app.describe()
|
||||||
|
peers = info.get("contacts", 0) if peers is None else peers
|
||||||
|
records = info.get("records", 0) if records is None else records
|
||||||
|
stats = info.get("stats", {}) if stats is None else stats
|
||||||
|
address = info.get("address") or f"{self.args.host}:{self.args.port or '随机'}"
|
||||||
|
text = (
|
||||||
|
f"我的地址 {address} | 已知节点 {peers} | 本地记录 {records} | "
|
||||||
|
f"收 {stats.get('received', 0)} / 发 {stats.get('sent', 0)}"
|
||||||
|
)
|
||||||
|
if self.last_status:
|
||||||
|
text = f"{text} | {self.last_status}"
|
||||||
|
self.status_label.config(text=text)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# actions
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def send_current(self) -> None:
|
||||||
|
text = self.input_var.get().strip()
|
||||||
|
if not text or self.current is None:
|
||||||
|
return
|
||||||
|
conversation = self.conversations.get(self.current)
|
||||||
|
if conversation is None:
|
||||||
|
return
|
||||||
|
self.input_var.set("")
|
||||||
|
self.input_history.append(text)
|
||||||
|
self.history_pos = len(self.input_history)
|
||||||
|
if conversation["kind"] == "room":
|
||||||
|
self.app.send_room_message(str(conversation["name"]), text)
|
||||||
|
elif conversation["kind"] == "direct":
|
||||||
|
self.app.send_direct_message(str(conversation["name"]), text)
|
||||||
|
else:
|
||||||
|
self.log("请先选择一个聊天室或私聊会话")
|
||||||
|
|
||||||
|
def _recall_history(self, _event=None) -> None:
|
||||||
|
if not self.input_history:
|
||||||
|
return
|
||||||
|
self.history_pos = max(0, self.history_pos - 1)
|
||||||
|
self.input_var.set(self.input_history[self.history_pos])
|
||||||
|
self.entry.icursor("end")
|
||||||
|
|
||||||
|
def join_room(self, name: str, announce: bool = True) -> None:
|
||||||
|
name = (name or "").strip()
|
||||||
|
if not name:
|
||||||
|
return
|
||||||
|
key = self.ensure_conversation("room", name, announce=announce)
|
||||||
|
self.select(key)
|
||||||
|
members = self.app.snapshot().get("rooms", {}).get(name, {}).get("members", [])
|
||||||
|
self._apply_members(name, members)
|
||||||
|
|
||||||
|
def prompt_join_room(self) -> None:
|
||||||
|
name = simpledialog.askstring("加入聊天室", "聊天室名称:", parent=self.root,
|
||||||
|
initialvalue=self.default_room)
|
||||||
|
if name:
|
||||||
|
self.default_room = name.strip()
|
||||||
|
self.join_room(self.default_room)
|
||||||
|
|
||||||
|
def leave_current_room(self) -> None:
|
||||||
|
conversation = self.conversations.get(self.current or "")
|
||||||
|
if not conversation or conversation["kind"] != "room":
|
||||||
|
messagebox.showinfo("提示", "当前不在聊天室里", parent=self.root)
|
||||||
|
return
|
||||||
|
name = str(conversation["name"])
|
||||||
|
self.app.leave_room(name)
|
||||||
|
self.remove_conversation(self._key("room", name))
|
||||||
|
|
||||||
|
def reload_room(self) -> None:
|
||||||
|
conversation = self.conversations.get(self.current or "")
|
||||||
|
if not conversation or conversation["kind"] != "room":
|
||||||
|
return
|
||||||
|
name = str(conversation["name"])
|
||||||
|
conversation["entries"].clear()
|
||||||
|
self._render()
|
||||||
|
self.app.leave_room(name)
|
||||||
|
self.app.join_room(name)
|
||||||
|
self.log(f"正在从 DHT 重新拉取「{name}」的历史记录…")
|
||||||
|
|
||||||
|
def prompt_direct(self) -> None:
|
||||||
|
nickname = simpledialog.askstring(
|
||||||
|
"发起私聊", "对方昵称(也可以直接粘贴对方的节点 ID):", parent=self.root
|
||||||
|
)
|
||||||
|
if nickname:
|
||||||
|
self.open_direct(nickname.strip())
|
||||||
|
|
||||||
|
def open_direct(self, nickname: str) -> None:
|
||||||
|
key = self.ensure_conversation("direct", nickname, announce=False)
|
||||||
|
self.select(key)
|
||||||
|
self.app.lookup_nickname(nickname)
|
||||||
|
|
||||||
|
def prompt_bootstrap(self) -> None:
|
||||||
|
address = self.bootstrap_var.get().strip()
|
||||||
|
if not address:
|
||||||
|
address = simpledialog.askstring(
|
||||||
|
"添加引导节点", "对方地址(例如 192.168.1.7:47800):", parent=self.root
|
||||||
|
) or ""
|
||||||
|
if not address:
|
||||||
|
return
|
||||||
|
self.bootstrap_var.set(address)
|
||||||
|
self.log(f"正在连接 {address}…")
|
||||||
|
self.app.add_bootstrap(address)
|
||||||
|
|
||||||
|
def prompt_lookup(self) -> None:
|
||||||
|
nickname = simpledialog.askstring("查找用户", "要查找的昵称:", parent=self.root)
|
||||||
|
if nickname:
|
||||||
|
self.app.lookup_nickname(nickname.strip())
|
||||||
|
|
||||||
|
def change_nickname(self) -> None:
|
||||||
|
nickname = self.nick_var.get().strip()
|
||||||
|
if not nickname or nickname == self.nickname:
|
||||||
|
return
|
||||||
|
self.nickname = nickname
|
||||||
|
save_nickname(self.app.profile_dir, nickname)
|
||||||
|
self.app.set_nickname(nickname)
|
||||||
|
self.root.title(f"DHT 聊天 - {nickname}")
|
||||||
|
|
||||||
|
def copy_my_address(self) -> None:
|
||||||
|
info = self.app.describe()
|
||||||
|
address = str(info.get("address") or "")
|
||||||
|
if not address:
|
||||||
|
return
|
||||||
|
self.root.clipboard_clear()
|
||||||
|
self.root.clipboard_append(address)
|
||||||
|
self.log(f"已复制我的地址: {address}")
|
||||||
|
|
||||||
|
def copy_my_node_id(self) -> None:
|
||||||
|
node_id = str(self.app.describe().get("node_id") or "")
|
||||||
|
if not node_id:
|
||||||
|
return
|
||||||
|
self.root.clipboard_clear()
|
||||||
|
self.root.clipboard_append(node_id)
|
||||||
|
self.log(f"已复制我的节点 ID: {node_id}")
|
||||||
|
|
||||||
|
def show_help(self) -> None:
|
||||||
|
messagebox.showinfo(
|
||||||
|
"使用说明",
|
||||||
|
"1. 两台机器在同一局域网时通常会自动发现彼此。\n"
|
||||||
|
"2. 不在同一网段时:在其中一台点「复制我的地址」,\n"
|
||||||
|
" 在另一台的「引导地址」里粘贴并点「连接」。\n"
|
||||||
|
"3. 想聊天就加入同一个聊天室名称(默认「大厅」)。\n"
|
||||||
|
"4. 私聊:点「发起私聊」输入对方昵称,消息会端到端加密;\n"
|
||||||
|
" 对方离线时会自动存入 DHT 信箱,等他上线后送达。",
|
||||||
|
parent=self.root,
|
||||||
|
)
|
||||||
|
|
||||||
|
def show_about(self) -> None:
|
||||||
|
state = str(self.app.profile_dir)
|
||||||
|
messagebox.showinfo(
|
||||||
|
"关于",
|
||||||
|
f"DHT 聊天 {__version__}\n\n"
|
||||||
|
"一个完全去中心化的聊天客户端:没有服务器,节点通过\n"
|
||||||
|
"Kademlia DHT 互相发现并交换消息,历史记录复制在 DHT 上。\n\n"
|
||||||
|
"私聊使用 X25519 + AEAD 端到端加密,身份为 Ed25519 密钥对。\n\n"
|
||||||
|
f"身份与状态目录:\n{state}",
|
||||||
|
parent=self.root,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _on_members(self, event: dict) -> None:
|
||||||
|
self._apply_members(str(event.get("room") or ""), event.get("members") or [])
|
||||||
|
|
||||||
|
def _apply_members(self, room: str, members: list) -> None:
|
||||||
|
key = self._key("room", room)
|
||||||
|
conversation = self.conversations.get(key)
|
||||||
|
if conversation is None:
|
||||||
|
return
|
||||||
|
conversation["members"] = list(members)
|
||||||
|
if key == self.current:
|
||||||
|
self._update_subtitle(conversation)
|
||||||
|
|
||||||
|
|
||||||
|
def run_gui(args: argparse.Namespace) -> int:
|
||||||
|
"""Create the window, start the backend and run the Tk main loop."""
|
||||||
|
from .__main__ import state_root
|
||||||
|
|
||||||
|
app = ChatApp(state_root(args), profile=args.profile)
|
||||||
|
root = tk.Tk()
|
||||||
|
window = ChatWindow(root, app, args)
|
||||||
|
try:
|
||||||
|
root.mainloop()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
window.on_close()
|
||||||
|
finally:
|
||||||
|
if not window._closing:
|
||||||
|
app.stop(timeout=3.0)
|
||||||
|
return 0
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
"""Local node identity: persistent Ed25519 key pair plus derived node id."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from . import crypto
|
||||||
|
|
||||||
|
DEFAULT_STATE_DIR = Path.home() / ".dhtchat"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Identity:
|
||||||
|
"""A local identity. ``node_id`` is SHA1 of the public key."""
|
||||||
|
|
||||||
|
seed: bytes
|
||||||
|
public: bytes
|
||||||
|
|
||||||
|
@property
|
||||||
|
def node_id(self) -> bytes:
|
||||||
|
return crypto.node_id_from_public(self.public)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def node_id_hex(self) -> str:
|
||||||
|
return self.node_id.hex()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def public_hex(self) -> str:
|
||||||
|
return self.public.hex()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def fingerprint(self) -> str:
|
||||||
|
return crypto.fingerprint(self.public)
|
||||||
|
|
||||||
|
def sign(self, message: bytes) -> bytes:
|
||||||
|
return crypto.ed25519_sign(self.seed, message)
|
||||||
|
|
||||||
|
def verify(self, public: bytes, message: bytes, signature: bytes) -> bool:
|
||||||
|
return crypto.ed25519_verify(public, message, signature)
|
||||||
|
|
||||||
|
def shared_secret_with(self, peer_public: bytes) -> bytes:
|
||||||
|
return crypto.shared_secret(self.seed, peer_public)
|
||||||
|
|
||||||
|
# -- persistence -----------------------------------------------------
|
||||||
|
@classmethod
|
||||||
|
def generate(cls) -> "Identity":
|
||||||
|
seed = crypto.generate_private_key()
|
||||||
|
return cls(seed=seed, public=crypto.ed25519_public_key(seed))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def load_or_create(cls, path: Path | str) -> "Identity":
|
||||||
|
path = Path(path)
|
||||||
|
if path.exists():
|
||||||
|
try:
|
||||||
|
data = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
seed = bytes.fromhex(data["seed"])
|
||||||
|
if len(seed) != crypto.PRIVATE_KEY_LEN:
|
||||||
|
raise ValueError("bad seed length")
|
||||||
|
return cls(seed=seed, public=crypto.ed25519_public_key(seed))
|
||||||
|
except (ValueError, KeyError, OSError):
|
||||||
|
pass
|
||||||
|
identity = cls.generate()
|
||||||
|
identity.save(path)
|
||||||
|
return identity
|
||||||
|
|
||||||
|
def save(self, path: Path | str) -> None:
|
||||||
|
path = Path(path)
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
payload = json.dumps({"seed": self.seed.hex()}, indent=2)
|
||||||
|
tmp = path.with_suffix(path.suffix + ".tmp")
|
||||||
|
tmp.write_text(payload, encoding="utf-8")
|
||||||
|
os.replace(tmp, path)
|
||||||
|
try:
|
||||||
|
os.chmod(path, 0o600)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
+751
@@ -0,0 +1,751 @@
|
|||||||
|
"""Kademlia DHT node: UDP transport, RPC layer, iterative lookups and
|
||||||
|
store-and-forward routing of chat payloads across the overlay.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import hashlib
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import time
|
||||||
|
from collections import OrderedDict
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from . import crypto, protocol
|
||||||
|
from .identity import Identity
|
||||||
|
from .routing import K, Contact, RoutingTable, distance
|
||||||
|
from .store import ValueStore, merge_records
|
||||||
|
from .util import local_ip
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
RPC_TIMEOUT = 3.0
|
||||||
|
LOOKUP_ROUNDS = 12
|
||||||
|
RELAY_TTL_SECONDS = 180.0
|
||||||
|
RELAY_CACHE_SIZE = 4096
|
||||||
|
FRAGMENT_TTL = 20.0
|
||||||
|
FRAGMENT_GROUPS = 128
|
||||||
|
|
||||||
|
|
||||||
|
WILDCARD_HOSTS = {"", "0.0.0.0", "::", "::0", "*"}
|
||||||
|
|
||||||
|
|
||||||
|
def _advertised_host(host: str) -> str:
|
||||||
|
"""Address other peers should use to reach us.
|
||||||
|
|
||||||
|
A wildcard bind address is useless to remote peers, so fall back to the
|
||||||
|
LAN address of this machine instead.
|
||||||
|
"""
|
||||||
|
if host.strip() in WILDCARD_HOSTS:
|
||||||
|
return local_ip()
|
||||||
|
return host
|
||||||
|
|
||||||
|
|
||||||
|
def key_to_target(key: str) -> bytes:
|
||||||
|
"""Map a human readable key onto the 160 bit id space."""
|
||||||
|
return hashlib.sha1(key.encode("utf-8")).digest()
|
||||||
|
|
||||||
|
|
||||||
|
class _DatagramProtocol(asyncio.DatagramProtocol):
|
||||||
|
def __init__(self, node: "DhtNode") -> None:
|
||||||
|
self.node = node
|
||||||
|
|
||||||
|
def datagram_received(self, data: bytes, addr) -> None:
|
||||||
|
try:
|
||||||
|
self.node.handle_datagram(data, addr)
|
||||||
|
except Exception: # never let a bad packet kill the loop
|
||||||
|
log.exception("error handling datagram from %s", addr)
|
||||||
|
|
||||||
|
def error_received(self, exc: Exception) -> None:
|
||||||
|
log.debug("udp error: %s", exc)
|
||||||
|
|
||||||
|
|
||||||
|
class DhtNode:
|
||||||
|
"""A Kademlia node speaking the dhtchat UDP protocol."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
identity: Identity,
|
||||||
|
host: str = "0.0.0.0",
|
||||||
|
port: int = 0,
|
||||||
|
k: int = K,
|
||||||
|
alpha: int = 3,
|
||||||
|
advertised_host: str = "",
|
||||||
|
) -> None:
|
||||||
|
self.identity = identity
|
||||||
|
self.host = host
|
||||||
|
self.requested_port = port
|
||||||
|
self.advertised_host = advertised_host or _advertised_host(host)
|
||||||
|
self.k = k
|
||||||
|
self.alpha = alpha
|
||||||
|
|
||||||
|
self.routing = RoutingTable(identity.node_id, k=k)
|
||||||
|
self.storage = ValueStore()
|
||||||
|
self.nickname = ""
|
||||||
|
self.stats = {"sent": 0, "received": 0, "stored": 0, "relayed": 0, "dropped": 0}
|
||||||
|
|
||||||
|
self._loop: asyncio.AbstractEventLoop | None = None
|
||||||
|
self.transport: asyncio.DatagramTransport | None = None
|
||||||
|
self.bound_port: int = 0
|
||||||
|
self._pending: dict[str, tuple] = {}
|
||||||
|
self._relay_prev: OrderedDict[str, tuple] = OrderedDict()
|
||||||
|
self._relay_pending: dict[str, asyncio.Future] = {}
|
||||||
|
self._handlers: dict[str, Callable[[dict, tuple], None]] = {}
|
||||||
|
self._fragments: dict[tuple[bytes, str], list] = {}
|
||||||
|
self._route_handler: Callable[[bytes, bytes, tuple], None] | None = None
|
||||||
|
self._tasks: list[asyncio.Task] = []
|
||||||
|
self._running = False
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# lifecycle
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
async def start(self) -> int:
|
||||||
|
self._loop = asyncio.get_running_loop()
|
||||||
|
self.transport, _ = await self._loop.create_datagram_endpoint(
|
||||||
|
lambda: _DatagramProtocol(self),
|
||||||
|
local_addr=(self.host, self.requested_port),
|
||||||
|
)
|
||||||
|
self.bound_port = self.transport.get_extra_info("sockname")[1]
|
||||||
|
self._running = True
|
||||||
|
self._tasks = [
|
||||||
|
asyncio.create_task(self._maintenance_loop()),
|
||||||
|
asyncio.create_task(self._cleanup_loop()),
|
||||||
|
]
|
||||||
|
log.info("dht node %s listening on %s:%s", self.identity.fingerprint,
|
||||||
|
self.host, self.bound_port)
|
||||||
|
return self.bound_port
|
||||||
|
|
||||||
|
async def stop(self) -> None:
|
||||||
|
self._running = False
|
||||||
|
for task in self._tasks:
|
||||||
|
task.cancel()
|
||||||
|
for task in self._tasks:
|
||||||
|
try:
|
||||||
|
await task
|
||||||
|
except (asyncio.CancelledError, Exception):
|
||||||
|
pass
|
||||||
|
self._tasks = []
|
||||||
|
for future in self._relay_pending.values():
|
||||||
|
if not future.done():
|
||||||
|
future.cancel()
|
||||||
|
self._relay_pending.clear()
|
||||||
|
self._fragments.clear()
|
||||||
|
if self.transport is not None:
|
||||||
|
self.transport.close()
|
||||||
|
self.transport = None
|
||||||
|
self._loop = None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def address(self) -> tuple[str, int]:
|
||||||
|
return (self.advertised_host, self.bound_port)
|
||||||
|
|
||||||
|
def register_handler(self, message_type: str, handler: Callable[[dict, tuple], None]) -> None:
|
||||||
|
"""Register a handler for an unsolicited chat message type."""
|
||||||
|
self._handlers[message_type] = handler
|
||||||
|
|
||||||
|
def set_route_handler(self, handler: Callable[[bytes, bytes, tuple], None]) -> None:
|
||||||
|
"""Handler invoked when a routed payload finally reaches this node."""
|
||||||
|
self._route_handler = handler
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# outbound helpers
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _base(self, message_type: str) -> dict:
|
||||||
|
message = {
|
||||||
|
"v": protocol.PROTOCOL_VERSION,
|
||||||
|
"t": message_type,
|
||||||
|
"src": self.identity.node_id_hex,
|
||||||
|
"pub": self.identity.public_hex,
|
||||||
|
}
|
||||||
|
if self.nickname:
|
||||||
|
message["nick"] = self.nickname
|
||||||
|
return message
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _message_nick(message: dict) -> str:
|
||||||
|
nick = message.get("nick")
|
||||||
|
return nick[:40] if isinstance(nick, str) else ""
|
||||||
|
|
||||||
|
def _remember_sender(self, message: dict, addr: tuple | None = None) -> None:
|
||||||
|
"""Add or refresh the sender of ``message`` in the routing table."""
|
||||||
|
node_id = message["_node_id"]
|
||||||
|
public = message["_public"]
|
||||||
|
nickname = self._message_nick(message)
|
||||||
|
if addr is None:
|
||||||
|
contact = self.routing.get(node_id)
|
||||||
|
if contact is None:
|
||||||
|
return
|
||||||
|
if nickname:
|
||||||
|
contact.nickname = nickname
|
||||||
|
return
|
||||||
|
self.routing.add(Contact(node_id, addr[0], addr[1], public, nickname=nickname))
|
||||||
|
|
||||||
|
def send_raw(self, message: dict, addr: tuple) -> bool:
|
||||||
|
"""Send ``message`` to ``addr``.
|
||||||
|
|
||||||
|
Payloads above :data:`protocol.MAX_DATAGRAM` are transparently split
|
||||||
|
into ``chunk`` datagrams, so callers never have to care about the MTU.
|
||||||
|
"""
|
||||||
|
if self.transport is None:
|
||||||
|
return False
|
||||||
|
payload = protocol.encode(message)
|
||||||
|
if len(payload) > protocol.MAX_DATAGRAM:
|
||||||
|
if not self._send_fragments(payload, addr):
|
||||||
|
self.stats["dropped"] += 1
|
||||||
|
log.warning("dropping oversized %s message (%d bytes)",
|
||||||
|
message.get("t"), len(payload))
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
return self._send_datagram(payload, addr)
|
||||||
|
|
||||||
|
def _send_datagram(self, payload: bytes, addr: tuple) -> bool:
|
||||||
|
try:
|
||||||
|
self.transport.sendto(payload, addr)
|
||||||
|
except OSError as exc:
|
||||||
|
log.debug("send to %s failed: %s", addr, exc)
|
||||||
|
return False
|
||||||
|
self.stats["sent"] += 1
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _send_fragments(self, payload: bytes, addr: tuple) -> bool:
|
||||||
|
if len(payload) > protocol.CHUNK_SIZE * protocol.MAX_CHUNKS:
|
||||||
|
log.warning("message of %d bytes exceeds the fragment budget", len(payload))
|
||||||
|
return False
|
||||||
|
chunks = [
|
||||||
|
payload[offset:offset + protocol.CHUNK_SIZE]
|
||||||
|
for offset in range(0, len(payload), protocol.CHUNK_SIZE)
|
||||||
|
]
|
||||||
|
group = protocol.new_id()
|
||||||
|
total = len(chunks)
|
||||||
|
delivered = False
|
||||||
|
for index, chunk in enumerate(chunks):
|
||||||
|
fragment = self._base(protocol.CHUNK)
|
||||||
|
fragment["id"] = group
|
||||||
|
fragment["n"] = index
|
||||||
|
fragment["c"] = total
|
||||||
|
fragment["d"] = protocol.b64encode(chunk)
|
||||||
|
delivered |= self._send_datagram(protocol.encode(fragment), addr)
|
||||||
|
return delivered
|
||||||
|
|
||||||
|
async def _rpc(
|
||||||
|
self, addr: tuple, message: dict, timeout: float = RPC_TIMEOUT,
|
||||||
|
expect_node: bytes | None = None,
|
||||||
|
) -> dict | None:
|
||||||
|
if self._loop is None:
|
||||||
|
return None
|
||||||
|
request_id = message["id"]
|
||||||
|
future = self._loop.create_future()
|
||||||
|
self._pending[request_id] = (future, addr, expect_node)
|
||||||
|
if not self.send_raw(message, addr):
|
||||||
|
self._pending.pop(request_id, None)
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return await asyncio.wait_for(future, timeout)
|
||||||
|
except (asyncio.TimeoutError, ConnectionError):
|
||||||
|
return None
|
||||||
|
finally:
|
||||||
|
self._pending.pop(request_id, None)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# inbound dispatch
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def handle_datagram(self, data: bytes, addr: tuple, reassembled: bool = False) -> None:
|
||||||
|
message = protocol.decode(data)
|
||||||
|
if message is None:
|
||||||
|
return
|
||||||
|
node_id = self._authenticate(message)
|
||||||
|
if node_id is None:
|
||||||
|
return
|
||||||
|
self.stats["received"] += 1
|
||||||
|
message["_addr"] = addr
|
||||||
|
message["_node_id"] = node_id
|
||||||
|
|
||||||
|
message_type = message["t"]
|
||||||
|
if message_type == protocol.CHUNK:
|
||||||
|
if not reassembled:
|
||||||
|
self._handle_fragment(message, addr)
|
||||||
|
elif message_type in protocol.RESPONSES:
|
||||||
|
if message_type in (protocol.ROUTE_ACK, protocol.ROUTE_FAIL):
|
||||||
|
self._handle_relay_receipt(message)
|
||||||
|
else:
|
||||||
|
self._handle_response(message)
|
||||||
|
elif message_type == protocol.ROUTE:
|
||||||
|
self._handle_route(message, addr)
|
||||||
|
elif message_type in protocol.REQUESTS:
|
||||||
|
reply = self._handle_request(message, addr)
|
||||||
|
if reply is not None:
|
||||||
|
self.send_raw(reply, addr)
|
||||||
|
else:
|
||||||
|
handler = self._handlers.get(message_type)
|
||||||
|
if handler is not None:
|
||||||
|
handler(message, addr)
|
||||||
|
|
||||||
|
def _authenticate(self, message: dict) -> bytes | None:
|
||||||
|
src = message.get("src")
|
||||||
|
pub = message.get("pub")
|
||||||
|
if not isinstance(src, str) or not isinstance(pub, str):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
node_id = bytes.fromhex(src)
|
||||||
|
public = bytes.fromhex(pub)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
if len(node_id) != 20 or len(public) != 32:
|
||||||
|
return None
|
||||||
|
if crypto.node_id_from_public(public) != node_id:
|
||||||
|
return None
|
||||||
|
message["_public"] = public
|
||||||
|
return node_id
|
||||||
|
|
||||||
|
def _handle_fragment(self, message: dict, addr: tuple) -> None:
|
||||||
|
"""Collect one ``chunk`` datagram, dispatching once the group is whole."""
|
||||||
|
group = message.get("id")
|
||||||
|
index = message.get("n")
|
||||||
|
count = message.get("c")
|
||||||
|
data = message.get("d")
|
||||||
|
if not isinstance(group, str) or not isinstance(data, str):
|
||||||
|
return
|
||||||
|
if not isinstance(index, int) or not isinstance(count, int):
|
||||||
|
return
|
||||||
|
if isinstance(index, bool) or isinstance(count, bool):
|
||||||
|
return
|
||||||
|
if count < 1 or count > protocol.MAX_CHUNKS or not 0 <= index < count:
|
||||||
|
return
|
||||||
|
key = (message["_node_id"], group)
|
||||||
|
entry = self._fragments.get(key)
|
||||||
|
if entry is None:
|
||||||
|
if len(self._fragments) >= FRAGMENT_GROUPS:
|
||||||
|
self._expire_fragments(force=True)
|
||||||
|
entry = [time.time() + FRAGMENT_TTL, count, [None] * count]
|
||||||
|
self._fragments[key] = entry
|
||||||
|
if entry[1] != count:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
entry[2][index] = protocol.b64decode(data)
|
||||||
|
except ValueError:
|
||||||
|
self._fragments.pop(key, None)
|
||||||
|
return
|
||||||
|
if any(part is None for part in entry[2]):
|
||||||
|
return
|
||||||
|
self._fragments.pop(key, None)
|
||||||
|
assembled = b"".join(entry[2])
|
||||||
|
if len(assembled) > protocol.MAX_ACCEPT:
|
||||||
|
return
|
||||||
|
self.handle_datagram(assembled, addr, reassembled=True)
|
||||||
|
|
||||||
|
def _expire_fragments(self, force: bool = False) -> None:
|
||||||
|
now = time.time()
|
||||||
|
for key, entry in list(self._fragments.items()):
|
||||||
|
if force or entry[0] < now:
|
||||||
|
self._fragments.pop(key, None)
|
||||||
|
|
||||||
|
def _handle_response(self, message: dict) -> None:
|
||||||
|
entry = self._pending.get(message.get("id"))
|
||||||
|
if entry is None:
|
||||||
|
return
|
||||||
|
future, addr, expect_node = entry
|
||||||
|
if expect_node is not None and message["_node_id"] != expect_node:
|
||||||
|
return
|
||||||
|
self._remember_sender(message, addr)
|
||||||
|
if not future.done():
|
||||||
|
future.set_result(message)
|
||||||
|
|
||||||
|
def _handle_request(self, message: dict, addr: tuple) -> dict | None:
|
||||||
|
self._remember_sender(message, addr)
|
||||||
|
message_type = message["t"]
|
||||||
|
if message_type == protocol.PING:
|
||||||
|
return self._reply(message, protocol.PONG)
|
||||||
|
if message_type == protocol.FIND_NODE:
|
||||||
|
return self._reply(message, protocol.NODES, nodes=self._closest_nodes(message))
|
||||||
|
if message_type == protocol.FIND_VALUE:
|
||||||
|
key = str(message.get("key", ""))
|
||||||
|
record = self.storage.get(key)
|
||||||
|
if record is not None:
|
||||||
|
return self._reply(
|
||||||
|
message,
|
||||||
|
protocol.VALUE,
|
||||||
|
value=protocol.b64encode(record.value),
|
||||||
|
ts=record.timestamp,
|
||||||
|
publisher=record.publisher.hex(),
|
||||||
|
)
|
||||||
|
return self._reply(message, protocol.NODES, nodes=self._closest_nodes(message))
|
||||||
|
if message_type == protocol.STORE:
|
||||||
|
try:
|
||||||
|
key = str(message["key"])
|
||||||
|
value = protocol.b64decode(message["value"])
|
||||||
|
ttl = float(message.get("ttl", 3600))
|
||||||
|
timestamp = float(message.get("ts", time.time()))
|
||||||
|
except (KeyError, ValueError, TypeError):
|
||||||
|
return None
|
||||||
|
accepted = self.storage.store(
|
||||||
|
key, value, message["_node_id"], min(max(ttl, 1.0), 86400.0), timestamp
|
||||||
|
)
|
||||||
|
if accepted:
|
||||||
|
self.stats["stored"] += 1
|
||||||
|
return self._reply(message, protocol.STORE_ACK, ok=accepted)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _reply(self, request: dict, message_type: str, **fields) -> dict:
|
||||||
|
reply = self._base(message_type)
|
||||||
|
reply["id"] = request.get("id", "")
|
||||||
|
reply.update(fields)
|
||||||
|
return reply
|
||||||
|
|
||||||
|
def _closest_nodes(self, message: dict) -> list[dict]:
|
||||||
|
try:
|
||||||
|
target = bytes.fromhex(str(message.get("target", "")))
|
||||||
|
except ValueError:
|
||||||
|
target = self.identity.node_id
|
||||||
|
return [c.to_dict() for c in self.routing.closest(target, self.k)]
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# store-and-forward routing
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _handle_route(self, message: dict, addr: tuple) -> None:
|
||||||
|
message_id = str(message.get("id", ""))
|
||||||
|
if not message_id:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
destination = bytes.fromhex(str(message["dst"]))
|
||||||
|
payload = protocol.b64decode(message["payload"])
|
||||||
|
hops = int(message.get("hops", 0))
|
||||||
|
except (KeyError, ValueError, TypeError):
|
||||||
|
return
|
||||||
|
|
||||||
|
if message_id in self._relay_prev:
|
||||||
|
return # loop guard
|
||||||
|
self._relay_prev[message_id] = (time.time(), addr)
|
||||||
|
self._trim_relay()
|
||||||
|
|
||||||
|
if destination == self.identity.node_id:
|
||||||
|
self._deliver_routed(message_id, payload, addr)
|
||||||
|
return
|
||||||
|
|
||||||
|
if hops <= 0:
|
||||||
|
self._send_receipt(protocol.ROUTE_FAIL, message_id, addr)
|
||||||
|
return
|
||||||
|
|
||||||
|
next_hop = self._next_hop(destination, exclude=addr)
|
||||||
|
if next_hop is None:
|
||||||
|
self._send_receipt(protocol.ROUTE_FAIL, message_id, addr)
|
||||||
|
return
|
||||||
|
forwarded = dict(message)
|
||||||
|
forwarded["hops"] = hops - 1
|
||||||
|
self.stats["relayed"] += 1
|
||||||
|
self.send_raw(forwarded, next_hop.address)
|
||||||
|
|
||||||
|
def _next_hop(self, destination: bytes, exclude: tuple) -> Contact | None:
|
||||||
|
own_distance = distance(self.identity.node_id, destination)
|
||||||
|
best: Contact | None = None
|
||||||
|
best_distance = own_distance
|
||||||
|
for contact in self.routing.contacts():
|
||||||
|
if contact.address == exclude:
|
||||||
|
continue
|
||||||
|
candidate = distance(contact.node_id, destination)
|
||||||
|
if candidate < best_distance:
|
||||||
|
best_distance = candidate
|
||||||
|
best = contact
|
||||||
|
return best
|
||||||
|
|
||||||
|
def _deliver_routed(self, message_id: str, payload: bytes, previous: tuple) -> None:
|
||||||
|
try:
|
||||||
|
if self._route_handler is not None:
|
||||||
|
self._route_handler(self.identity.node_id, payload, previous)
|
||||||
|
finally:
|
||||||
|
if previous and previous[1]:
|
||||||
|
self._send_receipt(protocol.ROUTE_ACK, message_id, previous)
|
||||||
|
|
||||||
|
def _send_receipt(self, message_type: str, message_id: str, addr: tuple) -> None:
|
||||||
|
receipt = self._base(message_type)
|
||||||
|
receipt["id"] = message_id
|
||||||
|
self.send_raw(receipt, addr)
|
||||||
|
|
||||||
|
def _handle_relay_receipt(self, message: dict) -> None:
|
||||||
|
message_id = str(message.get("id", ""))
|
||||||
|
if not message_id:
|
||||||
|
return
|
||||||
|
future = self._relay_pending.get(message_id)
|
||||||
|
if future is not None and not future.done():
|
||||||
|
future.set_result(message["t"] == protocol.ROUTE_ACK)
|
||||||
|
return
|
||||||
|
entry = self._relay_prev.get(message_id)
|
||||||
|
if entry is not None:
|
||||||
|
self.send_raw(message, entry[1])
|
||||||
|
|
||||||
|
def _trim_relay(self) -> None:
|
||||||
|
now = time.time()
|
||||||
|
while self._relay_prev:
|
||||||
|
message_id, (stamp, _) = next(iter(self._relay_prev.items()))
|
||||||
|
if now - stamp < RELAY_TTL_SECONDS and len(self._relay_prev) < RELAY_CACHE_SIZE:
|
||||||
|
break
|
||||||
|
self._relay_prev.pop(message_id, None)
|
||||||
|
|
||||||
|
async def send_routed(
|
||||||
|
self, destination: bytes, payload: bytes, hops: int = 6, timeout: float = 8.0
|
||||||
|
) -> bool:
|
||||||
|
"""Deliver ``payload`` to ``destination`` through the overlay.
|
||||||
|
|
||||||
|
Returns True when a ``route_ack`` came back, i.e. the target node
|
||||||
|
really accepted the payload.
|
||||||
|
"""
|
||||||
|
if self._loop is None:
|
||||||
|
return False
|
||||||
|
if destination == self.identity.node_id:
|
||||||
|
if self._route_handler is not None:
|
||||||
|
self._route_handler(destination, payload, ("0.0.0.0", 0))
|
||||||
|
return True
|
||||||
|
message_id = protocol.new_id()
|
||||||
|
envelope = self._base(protocol.ROUTE)
|
||||||
|
envelope["id"] = message_id
|
||||||
|
envelope["dst"] = destination.hex()
|
||||||
|
envelope["hops"] = hops
|
||||||
|
envelope["payload"] = protocol.b64encode(payload)
|
||||||
|
|
||||||
|
future = self._loop.create_future()
|
||||||
|
self._relay_pending[message_id] = future
|
||||||
|
try:
|
||||||
|
candidates = self.routing.closest(destination, self.alpha)
|
||||||
|
if not candidates:
|
||||||
|
return False
|
||||||
|
for contact in candidates:
|
||||||
|
self.send_raw(envelope, contact.address)
|
||||||
|
try:
|
||||||
|
return await asyncio.wait_for(future, timeout)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
self._relay_pending.pop(message_id, None)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# iterative lookups / storage
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
async def _find_rpc(self, contact: Contact, target: bytes, key: str | None):
|
||||||
|
message_type = protocol.FIND_VALUE if key else protocol.FIND_NODE
|
||||||
|
message = self._base(message_type)
|
||||||
|
message["id"] = protocol.new_id()
|
||||||
|
message["target"] = target.hex()
|
||||||
|
if key is not None:
|
||||||
|
message["key"] = key
|
||||||
|
reply = await self._rpc(contact.address, message, expect_node=contact.node_id)
|
||||||
|
if reply is None:
|
||||||
|
self.routing.mark_failed(contact.node_id)
|
||||||
|
return contact, None
|
||||||
|
self.routing.touch(contact.node_id)
|
||||||
|
message_type = reply["t"]
|
||||||
|
if message_type == protocol.VALUE:
|
||||||
|
try:
|
||||||
|
return contact, {
|
||||||
|
"contacts": [],
|
||||||
|
"value": protocol.b64decode(reply["value"]),
|
||||||
|
}
|
||||||
|
except (KeyError, ValueError):
|
||||||
|
return contact, {"contacts": [], "value": None}
|
||||||
|
if message_type == protocol.NODES:
|
||||||
|
return contact, {"contacts": self._parse_contacts(reply), "value": None}
|
||||||
|
return contact, None
|
||||||
|
|
||||||
|
def _parse_contacts(self, message: dict) -> list[Contact]:
|
||||||
|
contacts = []
|
||||||
|
for raw in message.get("nodes", []) or []:
|
||||||
|
if not isinstance(raw, dict):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
contact = Contact.from_dict(raw)
|
||||||
|
except (KeyError, ValueError, TypeError):
|
||||||
|
continue
|
||||||
|
if len(contact.node_id) != 20 or not contact.host:
|
||||||
|
continue
|
||||||
|
if contact.node_id == self.identity.node_id:
|
||||||
|
continue
|
||||||
|
contacts.append(contact)
|
||||||
|
return contacts
|
||||||
|
|
||||||
|
async def _lookup(self, target: bytes, key: str | None = None):
|
||||||
|
shortlist: dict[bytes, Contact] = {
|
||||||
|
c.node_id: c for c in self.routing.closest(target, self.k)
|
||||||
|
}
|
||||||
|
queried: set[bytes] = set()
|
||||||
|
values: list[bytes] = []
|
||||||
|
|
||||||
|
for _ in range(LOOKUP_ROUNDS):
|
||||||
|
candidates = sorted(
|
||||||
|
(c for c in shortlist.values() if c.node_id not in queried),
|
||||||
|
key=lambda c: distance(c.node_id, target),
|
||||||
|
)[: self.alpha]
|
||||||
|
if not candidates:
|
||||||
|
break
|
||||||
|
if len(queried) >= self.k:
|
||||||
|
furthest = max(distance(node_id, target) for node_id in queried)
|
||||||
|
if all(distance(c.node_id, target) >= furthest for c in candidates):
|
||||||
|
break
|
||||||
|
for contact in candidates:
|
||||||
|
queried.add(contact.node_id)
|
||||||
|
results = await asyncio.gather(
|
||||||
|
*[self._find_rpc(c, target, key) for c in candidates]
|
||||||
|
)
|
||||||
|
for _, payload in results:
|
||||||
|
if payload is None:
|
||||||
|
continue
|
||||||
|
for contact in payload["contacts"]:
|
||||||
|
shortlist.setdefault(contact.node_id, contact)
|
||||||
|
self.routing.add(contact)
|
||||||
|
if payload["value"] is not None:
|
||||||
|
values.append(payload["value"])
|
||||||
|
if key is not None and values:
|
||||||
|
break
|
||||||
|
|
||||||
|
nodes = sorted(shortlist.values(), key=lambda c: distance(c.node_id, target))
|
||||||
|
return nodes[: self.k], values
|
||||||
|
|
||||||
|
async def find_node(self, target: bytes) -> list[Contact]:
|
||||||
|
nodes, _ = await self._lookup(target)
|
||||||
|
return nodes
|
||||||
|
|
||||||
|
async def find_peer(self, node_id: bytes) -> Contact | None:
|
||||||
|
contact = self.routing.get(node_id)
|
||||||
|
if contact is not None:
|
||||||
|
return contact
|
||||||
|
nodes, _ = await self._lookup(node_id)
|
||||||
|
for candidate in nodes:
|
||||||
|
if candidate.node_id == node_id:
|
||||||
|
return candidate
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def find_value(self, key: str) -> list[bytes]:
|
||||||
|
"""Look up ``key``, merging the copies returned by all replicas."""
|
||||||
|
target = key_to_target(key)
|
||||||
|
_, values = await self._lookup(target, key)
|
||||||
|
record = self.storage.get(key)
|
||||||
|
if record is not None:
|
||||||
|
values.append(record.value)
|
||||||
|
return merge_records(key, values)
|
||||||
|
|
||||||
|
async def store(self, key: str, value: bytes, ttl: float = 3600.0) -> int:
|
||||||
|
"""Publish ``key``/``value`` to the k closest nodes (plus ourselves)."""
|
||||||
|
target = key_to_target(key)
|
||||||
|
nodes, _ = await self._lookup(target)
|
||||||
|
self.storage.store(key, value, self.identity.node_id, ttl)
|
||||||
|
stored = 1
|
||||||
|
contacts = [c for c in nodes if c.node_id != self.identity.node_id][: self.k]
|
||||||
|
if contacts:
|
||||||
|
results = await asyncio.gather(
|
||||||
|
*[self._store_rpc(c, key, value, ttl) for c in contacts]
|
||||||
|
)
|
||||||
|
stored += sum(1 for ok in results if ok)
|
||||||
|
return stored
|
||||||
|
|
||||||
|
async def _store_rpc(self, contact: Contact, key: str, value: bytes, ttl: float) -> bool:
|
||||||
|
message = self._base(protocol.STORE)
|
||||||
|
message["id"] = protocol.new_id()
|
||||||
|
message["key"] = key
|
||||||
|
message["value"] = protocol.b64encode(value)
|
||||||
|
message["ttl"] = ttl
|
||||||
|
message["ts"] = time.time()
|
||||||
|
reply = await self._rpc(contact.address, message, expect_node=contact.node_id)
|
||||||
|
if reply is None:
|
||||||
|
self.routing.mark_failed(contact.node_id)
|
||||||
|
return False
|
||||||
|
self.routing.touch(contact.node_id)
|
||||||
|
return bool(reply.get("ok"))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# bootstrap and maintenance
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
async def bootstrap(self, addresses: list[tuple]) -> int:
|
||||||
|
"""Ping the given seed addresses and seed our routing table."""
|
||||||
|
known = 0
|
||||||
|
for addr in addresses:
|
||||||
|
message = self._base(protocol.PING)
|
||||||
|
message["id"] = protocol.new_id()
|
||||||
|
reply = await self._rpc(addr, message, timeout=2.5)
|
||||||
|
if reply is None:
|
||||||
|
continue
|
||||||
|
contact = Contact(
|
||||||
|
reply["_node_id"], addr[0], addr[1], reply["_public"]
|
||||||
|
)
|
||||||
|
# Reply address is authoritative for reachability.
|
||||||
|
contact.host, contact.port = addr[0], addr[1]
|
||||||
|
self.routing.add(contact)
|
||||||
|
known += 1
|
||||||
|
for discovered in await self.find_node(self.identity.node_id):
|
||||||
|
self.routing.add(discovered)
|
||||||
|
if known:
|
||||||
|
log.info("bootstrap: %d seed(s) reachable, %d contact(s) known",
|
||||||
|
known, len(self.routing))
|
||||||
|
return known
|
||||||
|
|
||||||
|
def add_contact_from_dict(self, data: dict) -> Contact | None:
|
||||||
|
try:
|
||||||
|
contact = Contact.from_dict(data)
|
||||||
|
except (KeyError, ValueError, TypeError):
|
||||||
|
return None
|
||||||
|
self.routing.add(contact)
|
||||||
|
return contact
|
||||||
|
|
||||||
|
async def _maintenance_loop(self) -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await asyncio.sleep(25)
|
||||||
|
await self._refresh()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
log.exception("maintenance iteration failed")
|
||||||
|
|
||||||
|
async def _refresh(self) -> None:
|
||||||
|
contacts = self.routing.contacts()
|
||||||
|
if not contacts:
|
||||||
|
return
|
||||||
|
sample = random.sample(contacts, min(4, len(contacts)))
|
||||||
|
await asyncio.gather(*[self.ping_contact(c) for c in sample])
|
||||||
|
|
||||||
|
bucket = random.randrange(len(self.routing.buckets))
|
||||||
|
if self.routing.buckets[bucket]:
|
||||||
|
await self._lookup(self._random_id_in_bucket(bucket))
|
||||||
|
|
||||||
|
def _random_id_in_bucket(self, index: int) -> bytes:
|
||||||
|
own = int.from_bytes(self.identity.node_id, "big")
|
||||||
|
value = own ^ (1 << index)
|
||||||
|
value ^= random.getrandbits(index)
|
||||||
|
return value.to_bytes(20, "big")
|
||||||
|
|
||||||
|
async def ping_contact(self, contact: Contact) -> bool:
|
||||||
|
message = self._base(protocol.PING)
|
||||||
|
message["id"] = protocol.new_id()
|
||||||
|
reply = await self._rpc(contact.address, message, timeout=2.5,
|
||||||
|
expect_node=contact.node_id)
|
||||||
|
if reply is None:
|
||||||
|
self.routing.mark_failed(contact.node_id)
|
||||||
|
return False
|
||||||
|
self.routing.touch(contact.node_id)
|
||||||
|
return True
|
||||||
|
|
||||||
|
async def _cleanup_loop(self) -> None:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
await asyncio.sleep(60)
|
||||||
|
self.storage.cleanup()
|
||||||
|
self._trim_relay()
|
||||||
|
self._expire_fragments()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
log.exception("cleanup iteration failed")
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def describe(self) -> dict:
|
||||||
|
return {
|
||||||
|
"node_id": self.identity.node_id_hex,
|
||||||
|
"fingerprint": self.identity.fingerprint,
|
||||||
|
"address": f"{self.address[0]}:{self.address[1]}",
|
||||||
|
"contacts": len(self.routing),
|
||||||
|
"buckets": self.routing.bucket_sizes(),
|
||||||
|
"records": len(self.storage),
|
||||||
|
"stats": dict(self.stats),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def random_node_id() -> bytes:
|
||||||
|
return os.urandom(20)
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
"""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
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
"""Kademlia routing table and XOR distance helpers.
|
||||||
|
|
||||||
|
The identifier space is 160 bits (SHA-1), matching the classic Kademlia
|
||||||
|
paper: k = 8 contacts per bucket and one bucket per bit of shared prefix.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Iterable
|
||||||
|
|
||||||
|
ID_BITS = 160
|
||||||
|
ID_LEN = 20
|
||||||
|
K = 8
|
||||||
|
|
||||||
|
#: Contacts are considered stale (and therefore replaceable) after this many
|
||||||
|
#: seconds without a successful exchange.
|
||||||
|
STALE_SECONDS = 90.0
|
||||||
|
|
||||||
|
|
||||||
|
def distance(a: bytes, b: bytes) -> int:
|
||||||
|
"""XOR distance between two node ids."""
|
||||||
|
return int.from_bytes(a, "big") ^ int.from_bytes(b, "big")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Contact:
|
||||||
|
"""A known peer in the DHT overlay."""
|
||||||
|
|
||||||
|
node_id: bytes
|
||||||
|
host: str
|
||||||
|
port: int
|
||||||
|
public_key: bytes = b""
|
||||||
|
nickname: str = ""
|
||||||
|
last_seen: float = field(default_factory=time.time)
|
||||||
|
failed: int = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def address(self) -> tuple[str, int]:
|
||||||
|
return (self.host, self.port)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def node_id_hex(self) -> str:
|
||||||
|
return self.node_id.hex()
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"node": self.node_id.hex(),
|
||||||
|
"host": self.host,
|
||||||
|
"port": self.port,
|
||||||
|
"pub": self.public_key.hex(),
|
||||||
|
"nick": self.nickname,
|
||||||
|
}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_dict(cls, data: dict) -> "Contact":
|
||||||
|
return cls(
|
||||||
|
node_id=bytes.fromhex(data["node"]),
|
||||||
|
host=data["host"],
|
||||||
|
port=int(data["port"]),
|
||||||
|
public_key=bytes.fromhex(data.get("pub", "") or ""),
|
||||||
|
nickname=data.get("nick", "") or "",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RoutingTable:
|
||||||
|
"""Bucket based routing table for a single local node."""
|
||||||
|
|
||||||
|
def __init__(self, own_id: bytes, k: int = K) -> None:
|
||||||
|
self.own_id = own_id
|
||||||
|
self.k = k
|
||||||
|
self.buckets: list[list[Contact]] = [[] for _ in range(ID_BITS)]
|
||||||
|
self.replacements: list[list[Contact]] = [[] for _ in range(ID_BITS)]
|
||||||
|
|
||||||
|
# -- helpers ---------------------------------------------------------
|
||||||
|
def bucket_index(self, node_id: bytes) -> int | None:
|
||||||
|
d = distance(self.own_id, node_id)
|
||||||
|
if d == 0:
|
||||||
|
return None
|
||||||
|
return d.bit_length() - 1
|
||||||
|
|
||||||
|
def __len__(self) -> int:
|
||||||
|
return sum(len(b) for b in self.buckets)
|
||||||
|
|
||||||
|
def contacts(self) -> list[Contact]:
|
||||||
|
return [c for bucket in self.buckets for c in bucket]
|
||||||
|
|
||||||
|
# -- mutation --------------------------------------------------------
|
||||||
|
def add(self, contact: Contact) -> bool:
|
||||||
|
"""Insert or refresh ``contact``. Returns True if it is now stored."""
|
||||||
|
if contact.node_id == self.own_id:
|
||||||
|
return False
|
||||||
|
index = self.bucket_index(contact.node_id)
|
||||||
|
if index is None:
|
||||||
|
return False
|
||||||
|
bucket = self.buckets[index]
|
||||||
|
for existing in bucket:
|
||||||
|
if existing.node_id == contact.node_id:
|
||||||
|
if contact.host:
|
||||||
|
existing.host, existing.port = contact.host, contact.port
|
||||||
|
if contact.public_key:
|
||||||
|
existing.public_key = contact.public_key
|
||||||
|
if contact.nickname:
|
||||||
|
existing.nickname = contact.nickname
|
||||||
|
existing.last_seen = time.time()
|
||||||
|
existing.failed = 0
|
||||||
|
self._promote(bucket, existing)
|
||||||
|
return True
|
||||||
|
if len(bucket) < self.k:
|
||||||
|
bucket.append(contact)
|
||||||
|
return True
|
||||||
|
stale = min(bucket, key=lambda c: c.last_seen)
|
||||||
|
if time.time() - stale.last_seen > STALE_SECONDS:
|
||||||
|
bucket.remove(stale)
|
||||||
|
bucket.append(contact)
|
||||||
|
self._add_replacement(index, stale)
|
||||||
|
return True
|
||||||
|
self._add_replacement(index, contact)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _promote(self, bucket: list[Contact], contact: Contact) -> None:
|
||||||
|
bucket.remove(contact)
|
||||||
|
bucket.append(contact)
|
||||||
|
|
||||||
|
def _add_replacement(self, index: int, contact: Contact) -> None:
|
||||||
|
cache = self.replacements[index]
|
||||||
|
cache[:] = [c for c in cache if c.node_id != contact.node_id]
|
||||||
|
cache.append(contact)
|
||||||
|
del cache[:-self.k]
|
||||||
|
|
||||||
|
def mark_failed(self, node_id: bytes, threshold: int = 3) -> None:
|
||||||
|
for bucket in self.buckets:
|
||||||
|
for contact in bucket:
|
||||||
|
if contact.node_id == node_id:
|
||||||
|
contact.failed += 1
|
||||||
|
if contact.failed >= threshold:
|
||||||
|
bucket.remove(contact)
|
||||||
|
self._refill(bucket, node_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
def _refill(self, bucket: list[Contact], node_id: bytes) -> None:
|
||||||
|
index = self.bucket_index(node_id)
|
||||||
|
if index is None:
|
||||||
|
return
|
||||||
|
cache = self.replacements[index]
|
||||||
|
while cache and len(bucket) < self.k:
|
||||||
|
candidate = cache.pop(0)
|
||||||
|
if all(c.node_id != candidate.node_id for c in bucket):
|
||||||
|
bucket.append(candidate)
|
||||||
|
|
||||||
|
def remove(self, node_id: bytes) -> None:
|
||||||
|
for bucket in self.buckets:
|
||||||
|
for contact in list(bucket):
|
||||||
|
if contact.node_id == node_id:
|
||||||
|
bucket.remove(contact)
|
||||||
|
self._refill(bucket, node_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
def touch(self, node_id: bytes) -> None:
|
||||||
|
for bucket in self.buckets:
|
||||||
|
for contact in bucket:
|
||||||
|
if contact.node_id == node_id:
|
||||||
|
contact.last_seen = time.time()
|
||||||
|
contact.failed = 0
|
||||||
|
return
|
||||||
|
|
||||||
|
# -- lookup ----------------------------------------------------------
|
||||||
|
def closest(self, target: bytes, count: int = K) -> list[Contact]:
|
||||||
|
candidates = sorted(
|
||||||
|
self.contacts(), key=lambda c: distance(c.node_id, target)
|
||||||
|
)
|
||||||
|
return candidates[:count]
|
||||||
|
|
||||||
|
def get(self, node_id: bytes) -> Contact | None:
|
||||||
|
index = self.bucket_index(node_id)
|
||||||
|
if index is None:
|
||||||
|
return None
|
||||||
|
for contact in self.buckets[index]:
|
||||||
|
if contact.node_id == node_id:
|
||||||
|
return contact
|
||||||
|
return None
|
||||||
|
|
||||||
|
def snapshot(self) -> list[dict]:
|
||||||
|
now = time.time()
|
||||||
|
rows = []
|
||||||
|
for contact in sorted(
|
||||||
|
self.contacts(), key=lambda c: distance(c.node_id, self.own_id)
|
||||||
|
):
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"node_id": contact.node_id.hex(),
|
||||||
|
"address": f"{contact.host}:{contact.port}",
|
||||||
|
"nickname": contact.nickname,
|
||||||
|
"public_key": contact.public_key.hex(),
|
||||||
|
"age": round(now - contact.last_seen, 1),
|
||||||
|
"failed": contact.failed,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
def bucket_sizes(self) -> list[int]:
|
||||||
|
return [len(b) for b in self.buckets if b]
|
||||||
|
|
||||||
|
def extend(self, contacts: Iterable[Contact]) -> int:
|
||||||
|
added = 0
|
||||||
|
for contact in contacts:
|
||||||
|
if self.add(contact):
|
||||||
|
added += 1
|
||||||
|
return added
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
"""Replicated DHT value store.
|
||||||
|
|
||||||
|
Two merge strategies are supported:
|
||||||
|
|
||||||
|
``lww`` (last write wins)
|
||||||
|
Used for single valued keys such as ``profile/<nickname>``. The newest
|
||||||
|
record (by timestamp) replaces the previous one.
|
||||||
|
|
||||||
|
``grow`` (grow-only set)
|
||||||
|
Used for keys below ``log/`` such as ``log/room/<name>``. Values are JSON
|
||||||
|
arrays of items carrying an ``id``; replicated copies are merged by union
|
||||||
|
so that concurrent writers never lose each other's messages. This is what
|
||||||
|
gives the chat log store-and-forward behaviour without a central server.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
MAX_VALUE_BYTES = 48 * 1024
|
||||||
|
MAX_GROW_ITEMS = 200
|
||||||
|
|
||||||
|
|
||||||
|
def merge_mode(key: str) -> str:
|
||||||
|
return "grow" if key.startswith("log/") else "lww"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Record:
|
||||||
|
key: str
|
||||||
|
value: bytes
|
||||||
|
publisher: bytes
|
||||||
|
timestamp: float
|
||||||
|
expires_at: float
|
||||||
|
|
||||||
|
@property
|
||||||
|
def expired(self) -> bool:
|
||||||
|
return time.time() > self.expires_at
|
||||||
|
|
||||||
|
|
||||||
|
def merge_grow(existing: bytes, incoming: bytes) -> bytes:
|
||||||
|
"""Union two JSON encoded item lists, keeping the newest ``MAX_GROW_ITEMS``."""
|
||||||
|
items: dict[str, dict] = {}
|
||||||
|
for blob in (existing, incoming):
|
||||||
|
if not blob:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
parsed = json.loads(blob.decode("utf-8"))
|
||||||
|
except (ValueError, UnicodeDecodeError):
|
||||||
|
continue
|
||||||
|
if not isinstance(parsed, list):
|
||||||
|
continue
|
||||||
|
for item in parsed:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
item_id = str(item.get("id") or "")
|
||||||
|
if not item_id:
|
||||||
|
continue
|
||||||
|
previous = items.get(item_id)
|
||||||
|
if previous is None or float(item.get("ts", 0)) > float(
|
||||||
|
previous.get("ts", 0)
|
||||||
|
):
|
||||||
|
items[item_id] = item
|
||||||
|
ordered = sorted(items.values(), key=lambda i: float(i.get("ts", 0)))
|
||||||
|
return json.dumps(ordered[-MAX_GROW_ITEMS:], separators=(",", ":")).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def merge_records(key: str, blobs: list[bytes]) -> list[bytes]:
|
||||||
|
"""Combine records read back from several replicas into one value."""
|
||||||
|
blobs = [blob for blob in blobs if blob]
|
||||||
|
if not blobs:
|
||||||
|
return []
|
||||||
|
if merge_mode(key) == "grow":
|
||||||
|
merged = b""
|
||||||
|
for blob in blobs:
|
||||||
|
merged = merge_grow(merged, blob)
|
||||||
|
return [merged] if merged else []
|
||||||
|
best = blobs[-1]
|
||||||
|
best_ts = float("-inf")
|
||||||
|
for blob in blobs:
|
||||||
|
try:
|
||||||
|
ts = float(json.loads(blob.decode("utf-8")).get("ts", 0))
|
||||||
|
except (ValueError, UnicodeDecodeError, AttributeError):
|
||||||
|
ts = float("-inf")
|
||||||
|
if ts >= best_ts:
|
||||||
|
best_ts, best = ts, blob
|
||||||
|
return [best]
|
||||||
|
|
||||||
|
|
||||||
|
class ValueStore:
|
||||||
|
"""In-memory, TTL based value store hosted by every DHT node."""
|
||||||
|
|
||||||
|
def __init__(self, capacity: int = 4000) -> None:
|
||||||
|
self.capacity = capacity
|
||||||
|
self._records: dict[str, Record] = {}
|
||||||
|
|
||||||
|
def __len__(self) -> int:
|
||||||
|
return len(self._records)
|
||||||
|
|
||||||
|
def store(
|
||||||
|
self,
|
||||||
|
key: str,
|
||||||
|
value: bytes,
|
||||||
|
publisher: bytes,
|
||||||
|
ttl: float,
|
||||||
|
timestamp: float | None = None,
|
||||||
|
) -> bool:
|
||||||
|
"""Store ``value``; returns True when the incoming copy was accepted."""
|
||||||
|
if len(value) > MAX_VALUE_BYTES:
|
||||||
|
return False
|
||||||
|
now = time.time()
|
||||||
|
timestamp = now if timestamp is None else timestamp
|
||||||
|
|
||||||
|
current = self._records.get(key)
|
||||||
|
if current is not None and current.expired:
|
||||||
|
current = None
|
||||||
|
|
||||||
|
if merge_mode(key) == "grow":
|
||||||
|
merged = merge_grow(current.value if current else b"", value)
|
||||||
|
if current is not None and merged == current.value:
|
||||||
|
return False
|
||||||
|
record = Record(key, merged, publisher, timestamp, now + ttl)
|
||||||
|
else:
|
||||||
|
if current is not None:
|
||||||
|
if current.publisher == publisher and current.timestamp > timestamp:
|
||||||
|
return False
|
||||||
|
if current.timestamp > timestamp:
|
||||||
|
return False
|
||||||
|
record = Record(key, value, publisher, timestamp, now + ttl)
|
||||||
|
|
||||||
|
self._records[key] = record
|
||||||
|
if len(self._records) > self.capacity:
|
||||||
|
self._evict()
|
||||||
|
return True
|
||||||
|
|
||||||
|
def get(self, key: str) -> Record | None:
|
||||||
|
record = self._records.get(key)
|
||||||
|
if record is None:
|
||||||
|
return None
|
||||||
|
if record.expired:
|
||||||
|
del self._records[key]
|
||||||
|
return None
|
||||||
|
return record
|
||||||
|
|
||||||
|
def cleanup(self) -> int:
|
||||||
|
expired = [k for k, r in self._records.items() if r.expired]
|
||||||
|
for key in expired:
|
||||||
|
del self._records[key]
|
||||||
|
return len(expired)
|
||||||
|
|
||||||
|
def _evict(self) -> None:
|
||||||
|
# Drop expired entries first, then the oldest ones.
|
||||||
|
self.cleanup()
|
||||||
|
overflow = len(self._records) - self.capacity
|
||||||
|
if overflow <= 0:
|
||||||
|
return
|
||||||
|
ordered = sorted(self._records.items(), key=lambda kv: kv[1].timestamp)
|
||||||
|
for key, _ in ordered[:overflow]:
|
||||||
|
del self._records[key]
|
||||||
|
|
||||||
|
def stats(self) -> dict:
|
||||||
|
return {"records": len(self._records), "capacity": self.capacity}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""Small shared helpers."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
|
||||||
|
_CACHED_IP: tuple[float, str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def local_ip() -> str:
|
||||||
|
"""Best guess of the LAN address of this machine (cached for 60s)."""
|
||||||
|
global _CACHED_IP
|
||||||
|
now = time.monotonic()
|
||||||
|
if _CACHED_IP and now - _CACHED_IP[0] < 60:
|
||||||
|
return _CACHED_IP[1]
|
||||||
|
address = "127.0.0.1"
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
try:
|
||||||
|
sock.connect(("8.8.8.8", 80))
|
||||||
|
address = sock.getsockname()[0]
|
||||||
|
except OSError:
|
||||||
|
try:
|
||||||
|
address = socket.gethostbyname(socket.gethostname())
|
||||||
|
except OSError:
|
||||||
|
address = "127.0.0.1"
|
||||||
|
finally:
|
||||||
|
sock.close()
|
||||||
|
_CACHED_IP = (now, address)
|
||||||
|
return address
|
||||||
|
|
||||||
|
|
||||||
|
def parse_host_port(text: str, default_port: int = 0) -> tuple[str, int]:
|
||||||
|
"""Parse ``host``, ``host:port`` or ``[v6]:port`` into a (host, port) pair."""
|
||||||
|
text = (text or "").strip()
|
||||||
|
if not text:
|
||||||
|
raise ValueError("empty address")
|
||||||
|
if text.startswith("["):
|
||||||
|
host, _, rest = text[1:].partition("]")
|
||||||
|
port = rest.lstrip(":")
|
||||||
|
return host, int(port) if port else default_port
|
||||||
|
if text.count(":") == 1:
|
||||||
|
host, _, port = text.partition(":")
|
||||||
|
return host, int(port) if port else default_port
|
||||||
|
if ":" in text:
|
||||||
|
return text, default_port
|
||||||
|
return text, default_port
|
||||||
|
|
||||||
|
|
||||||
|
def format_duration(seconds: float) -> str:
|
||||||
|
seconds = max(0, int(seconds))
|
||||||
|
if seconds < 60:
|
||||||
|
return f"{seconds}s"
|
||||||
|
if seconds < 3600:
|
||||||
|
return f"{seconds // 60}m{seconds % 60:02d}s"
|
||||||
|
return f"{seconds // 3600}h{(seconds % 3600) // 60:02d}m"
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
@echo off
|
||||||
|
rem ---------------------------------------------------------------------------
|
||||||
|
rem DHT 聊天客户端启动脚本(所有参数都会透传给 python -m dhtchat)
|
||||||
|
rem 用法示例:
|
||||||
|
rem run.cmd 启动图形界面
|
||||||
|
rem run.cmd --nick 小明 指定昵称
|
||||||
|
rem run.cmd -b 192.168.1.7:47800 手动指定引导节点
|
||||||
|
rem run.cmd --no-gui 使用命令行界面
|
||||||
|
rem ---------------------------------------------------------------------------
|
||||||
|
setlocal
|
||||||
|
cd /d "%~dp0"
|
||||||
|
|
||||||
|
set "DHTCHAT_PY="
|
||||||
|
where py >nul 2>nul && py -3 -c "import sys" >nul 2>nul && set "DHTCHAT_PY=py -3"
|
||||||
|
if not defined DHTCHAT_PY (
|
||||||
|
where python >nul 2>nul && python -c "import sys" >nul 2>nul && set "DHTCHAT_PY=python"
|
||||||
|
)
|
||||||
|
|
||||||
|
if not defined DHTCHAT_PY (
|
||||||
|
echo [错误] 没有找到可用的 Python 3。
|
||||||
|
echo 请到 https://www.python.org/downloads/windows/ 安装,
|
||||||
|
echo 安装时勾选 "Add python.exe to PATH"。
|
||||||
|
exit /b 9009
|
||||||
|
)
|
||||||
|
|
||||||
|
%DHTCHAT_PY% -c "import tkinter" >nul 2>nul
|
||||||
|
if errorlevel 1 (
|
||||||
|
echo [提示] 当前 Python 缺少 tkinter,将改用命令行界面。
|
||||||
|
%DHTCHAT_PY% -m dhtchat --no-gui %*
|
||||||
|
exit /b %errorlevel%
|
||||||
|
)
|
||||||
|
|
||||||
|
%DHTCHAT_PY% -m dhtchat %*
|
||||||
|
exit /b %errorlevel%
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
@echo off
|
||||||
|
rem 双击本文件即可启动聊天客户端;出错时会暂停,方便查看提示信息。
|
||||||
|
call "%~dp0run.cmd" %*
|
||||||
|
set "DHTCHAT_RC=%errorlevel%"
|
||||||
|
if not "%DHTCHAT_RC%"=="0" (
|
||||||
|
echo.
|
||||||
|
echo 启动失败(退出码 %DHTCHAT_RC%)。常见原因见 README.md 的“常见问题”一节。
|
||||||
|
pause
|
||||||
|
)
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
"""Integration tests for the chat layer: rooms, profiles and private messages."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
from dhtchat import crypto, protocol # noqa: E402
|
||||||
|
from dhtchat.chat import ( # noqa: E402
|
||||||
|
ChatService,
|
||||||
|
_sign_record,
|
||||||
|
decode_log,
|
||||||
|
verify_record,
|
||||||
|
)
|
||||||
|
from dhtchat.identity import Identity # noqa: E402
|
||||||
|
from dhtchat.node import DhtNode # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
class Peer:
|
||||||
|
"""A node plus its chat service and the events both produced."""
|
||||||
|
|
||||||
|
def __init__(self, node: DhtNode, chat: ChatService, events: list[dict]) -> None:
|
||||||
|
self.node = node
|
||||||
|
self.chat = chat
|
||||||
|
self.events = events
|
||||||
|
|
||||||
|
@property
|
||||||
|
def nickname(self) -> str:
|
||||||
|
return self.chat.nickname
|
||||||
|
|
||||||
|
def of_type(self, kind: str) -> list[dict]:
|
||||||
|
return [event for event in self.events if event.get("type") == kind]
|
||||||
|
|
||||||
|
def texts(self, kind: str = "direct_message") -> list[str]:
|
||||||
|
return [event["text"] for event in self.of_type(kind)]
|
||||||
|
|
||||||
|
|
||||||
|
class ChatServiceTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self) -> None:
|
||||||
|
self._tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.tmp = Path(self._tmp.name)
|
||||||
|
self.peers: list[Peer] = []
|
||||||
|
|
||||||
|
async def asyncTearDown(self) -> None:
|
||||||
|
for peer in self.peers:
|
||||||
|
try:
|
||||||
|
await peer.chat.stop()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
await peer.node.stop()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._tmp.cleanup()
|
||||||
|
|
||||||
|
async def make_peer(self, nickname: str, start_chat: bool = True) -> Peer:
|
||||||
|
node = DhtNode(Identity.generate(), host="127.0.0.1", port=0)
|
||||||
|
await node.start()
|
||||||
|
events: list[dict] = []
|
||||||
|
chat = ChatService(
|
||||||
|
node, node.identity, self.tmp / nickname, events.append, nickname=nickname
|
||||||
|
)
|
||||||
|
peer = Peer(node, chat, events)
|
||||||
|
self.peers.append(peer)
|
||||||
|
if start_chat:
|
||||||
|
await chat.start()
|
||||||
|
return peer
|
||||||
|
|
||||||
|
async def link(self, follower: Peer, anchor: Peer) -> None:
|
||||||
|
self.assertEqual(await follower.node.bootstrap([anchor.node.address]), 1)
|
||||||
|
await follower.chat.announce_profile()
|
||||||
|
await anchor.chat.announce_profile()
|
||||||
|
|
||||||
|
async def join_and_sync(self, *peers: Peer, room: str) -> None:
|
||||||
|
for peer in peers:
|
||||||
|
peer.chat.join_room(room)
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
for peer in peers:
|
||||||
|
await peer.chat._announce_membership(peer.chat.rooms[room])
|
||||||
|
for peer in peers:
|
||||||
|
await peer.chat._sync_room(peer.chat.rooms[room])
|
||||||
|
|
||||||
|
# -- profiles ------------------------------------------------------
|
||||||
|
async def test_profile_is_published_and_verified(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
|
||||||
|
profile = await bob.chat.resolve_nickname("alice")
|
||||||
|
|
||||||
|
self.assertIsNotNone(profile)
|
||||||
|
self.assertEqual(profile["node"], alice.node.identity.node_id_hex)
|
||||||
|
self.assertEqual(profile["pub"], alice.node.identity.public_hex)
|
||||||
|
self.assertEqual(profile["port"], alice.node.bound_port)
|
||||||
|
|
||||||
|
async def test_resolve_nickname_returns_none_for_stranger(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
self.assertIsNone(await alice.chat.resolve_nickname("nobody"))
|
||||||
|
|
||||||
|
async def test_tampered_profile_is_rejected(self) -> None:
|
||||||
|
signer = Identity.generate()
|
||||||
|
record = {
|
||||||
|
"nick": "mallory",
|
||||||
|
"pub": signer.public_hex,
|
||||||
|
"node": signer.node_id_hex,
|
||||||
|
"host": "1.2.3.4",
|
||||||
|
"port": 1234,
|
||||||
|
"ts": 1.0,
|
||||||
|
}
|
||||||
|
signed = _sign_record(record, signer)
|
||||||
|
self.assertIsNotNone(verify_record(signed))
|
||||||
|
signed["port"] = 9999
|
||||||
|
self.assertIsNone(verify_record(signed))
|
||||||
|
|
||||||
|
# -- rooms ---------------------------------------------------------
|
||||||
|
async def test_room_message_reaches_member(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
await self.join_and_sync(alice, bob, room="大厅")
|
||||||
|
|
||||||
|
self.assertIn(bob.nickname, [m["nick"] for m in alice.chat.rooms["大厅"].member_list()])
|
||||||
|
await alice.chat.send_room_message("大厅", "大家好")
|
||||||
|
await asyncio.sleep(0.3)
|
||||||
|
|
||||||
|
self.assertEqual(bob.texts("room_message"), ["大家好"])
|
||||||
|
self.assertFalse(bob.of_type("room_message")[0]["own"])
|
||||||
|
|
||||||
|
async def test_late_joiner_replays_history_from_dht(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
await self.join_and_sync(alice, bob, room="大厅")
|
||||||
|
await alice.chat.send_room_message("大厅", "历史上的第一条")
|
||||||
|
|
||||||
|
carol = await self.make_peer("carol")
|
||||||
|
await self.link(carol, alice)
|
||||||
|
carol.chat.join_room("大厅")
|
||||||
|
await carol.chat._sync_room(carol.chat.rooms["大厅"], pull_history=True)
|
||||||
|
|
||||||
|
self.assertEqual(carol.texts("room_message"), ["历史上的第一条"])
|
||||||
|
self.assertTrue(carol.of_type("room_message")[0]["history"])
|
||||||
|
|
||||||
|
async def test_room_rejects_forged_record(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
await self.join_and_sync(alice, bob, room="大厅")
|
||||||
|
|
||||||
|
forged = {
|
||||||
|
"id": protocol.new_id(),
|
||||||
|
"room": "大厅",
|
||||||
|
"nick": "alice",
|
||||||
|
"pub": alice.node.identity.public_hex,
|
||||||
|
"node": alice.node.identity.node_id_hex,
|
||||||
|
"text": "假的",
|
||||||
|
"ts": 1.0,
|
||||||
|
"sig": "00" * 64,
|
||||||
|
}
|
||||||
|
packet = bob.node._base(protocol.ROOM_MSG)
|
||||||
|
packet["room"] = "大厅"
|
||||||
|
packet["record"] = forged
|
||||||
|
bob.node.send_raw(packet, alice.node.address)
|
||||||
|
await asyncio.sleep(0.3)
|
||||||
|
|
||||||
|
self.assertEqual(alice.texts("room_message"), [])
|
||||||
|
|
||||||
|
async def test_room_log_is_merged_across_replicas(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
await self.join_and_sync(alice, bob, room="大厅")
|
||||||
|
|
||||||
|
await alice.chat.send_room_message("大厅", "A")
|
||||||
|
await bob.chat.send_room_message("大厅", "B")
|
||||||
|
await asyncio.sleep(0.2)
|
||||||
|
|
||||||
|
blobs = await alice.node.find_value("log/room/大厅")
|
||||||
|
texts = {item.get("text") for item in decode_log(blobs)}
|
||||||
|
self.assertEqual(texts, {"A", "B"})
|
||||||
|
|
||||||
|
async def test_room_sync_picks_up_messages_missed_by_broadcast(self) -> None:
|
||||||
|
"""A member the sender did not know yet still gets the message."""
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
await self.join_and_sync(alice, bob, room="大厅")
|
||||||
|
|
||||||
|
await alice.chat.send_room_message("大厅", "广播丢了")
|
||||||
|
room = bob.chat.rooms["大厅"]
|
||||||
|
room.seen.clear()
|
||||||
|
room.messages.clear()
|
||||||
|
bob.events.clear()
|
||||||
|
|
||||||
|
await bob.chat._sync_room(room)
|
||||||
|
|
||||||
|
self.assertEqual(bob.texts("room_message"), ["广播丢了"])
|
||||||
|
self.assertFalse(bob.of_type("room_message")[0]["history"])
|
||||||
|
|
||||||
|
async def test_room_history_backlog_is_not_replayed_again(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
await self.join_and_sync(alice, bob, room="大厅")
|
||||||
|
for index in range(45):
|
||||||
|
await alice.chat.send_room_message("大厅", f"消息{index}")
|
||||||
|
|
||||||
|
carol = await self.make_peer("carol")
|
||||||
|
await self.link(carol, alice)
|
||||||
|
carol.chat.join_room("大厅")
|
||||||
|
await carol.chat._sync_room(carol.chat.rooms["大厅"], pull_history=True)
|
||||||
|
|
||||||
|
replayed = carol.of_type("room_message")
|
||||||
|
self.assertEqual(len(replayed), 40)
|
||||||
|
self.assertTrue(all(event["history"] for event in replayed))
|
||||||
|
|
||||||
|
carol.events.clear()
|
||||||
|
await carol.chat._sync_room(carol.chat.rooms["大厅"])
|
||||||
|
|
||||||
|
self.assertEqual(carol.of_type("room_message"), [])
|
||||||
|
|
||||||
|
# -- private messages ---------------------------------------------
|
||||||
|
async def test_private_message_over_direct_connection(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
|
||||||
|
result = await alice.chat.send_direct("bob", "悄悄话")
|
||||||
|
await asyncio.sleep(0.2)
|
||||||
|
|
||||||
|
self.assertTrue(result["delivered"])
|
||||||
|
self.assertEqual(bob.texts("direct_message"), ["悄悄话"])
|
||||||
|
self.assertEqual(alice.texts("direct_message"), ["悄悄话"])
|
||||||
|
self.assertTrue(alice.of_type("direct_message")[0]["own"])
|
||||||
|
self.assertFalse(bob.of_type("direct_message")[0]["own"])
|
||||||
|
|
||||||
|
async def test_private_message_falls_back_to_overlay_routing(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
|
||||||
|
# Pretend the profile has no usable address: only the DHT can help.
|
||||||
|
alice.chat._peer_address = lambda profile, node: None
|
||||||
|
|
||||||
|
result = await alice.chat.send_direct("bob", "走路由")
|
||||||
|
await asyncio.sleep(0.3)
|
||||||
|
|
||||||
|
self.assertTrue(result["delivered"])
|
||||||
|
self.assertEqual(bob.texts("direct_message"), ["走路由"])
|
||||||
|
|
||||||
|
async def test_ciphertext_for_another_recipient_is_rejected(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
|
||||||
|
shared = alice.node.identity.shared_secret_with(bob.node.identity.public)
|
||||||
|
body = json.dumps({"text": "给别人的"}).encode()
|
||||||
|
wrong_aad = (
|
||||||
|
b"dhtchat-dm/v1" + Identity.generate().node_id + bob.node.identity.node_id
|
||||||
|
)
|
||||||
|
blob = crypto.aead_encrypt(shared, body, wrong_aad)
|
||||||
|
|
||||||
|
envelope = alice.node._base(protocol.DIRECT_MSG)
|
||||||
|
envelope["id"] = protocol.new_id()
|
||||||
|
envelope["dst"] = bob.node.identity.node_id_hex
|
||||||
|
envelope["blob"] = protocol.b64encode(blob)
|
||||||
|
alice.node.send_raw(envelope, bob.node.address)
|
||||||
|
await asyncio.sleep(0.3)
|
||||||
|
|
||||||
|
self.assertEqual(bob.texts("direct_message"), [])
|
||||||
|
self.assertTrue(
|
||||||
|
any("无法解密" in event.get("text", "") for event in bob.of_type("log"))
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_duplicate_private_message_is_ignored(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
bob = await self.make_peer("bob")
|
||||||
|
await self.link(bob, alice)
|
||||||
|
|
||||||
|
shared = alice.node.identity.shared_secret_with(bob.node.identity.public)
|
||||||
|
aad = (
|
||||||
|
b"dhtchat-dm/v1" + alice.node.identity.node_id + bob.node.identity.node_id
|
||||||
|
)
|
||||||
|
body = json.dumps({"from_nick": "alice", "text": "只此一次"}, ensure_ascii=False).encode()
|
||||||
|
envelope = alice.node._base(protocol.DIRECT_MSG)
|
||||||
|
envelope["id"] = protocol.new_id()
|
||||||
|
envelope["dst"] = bob.node.identity.node_id_hex
|
||||||
|
envelope["blob"] = protocol.b64encode(crypto.aead_encrypt(shared, body, aad))
|
||||||
|
|
||||||
|
self.assertTrue(alice.node.send_raw(envelope, bob.node.address))
|
||||||
|
await asyncio.sleep(0.25)
|
||||||
|
self.assertTrue(alice.node.send_raw(envelope, bob.node.address))
|
||||||
|
await asyncio.sleep(0.25)
|
||||||
|
|
||||||
|
self.assertEqual(bob.texts("direct_message"), ["只此一次"])
|
||||||
|
|
||||||
|
async def test_private_message_reaches_offline_peer_through_inbox(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
proxy = await self.make_peer("proxy")
|
||||||
|
await self.link(proxy, alice)
|
||||||
|
|
||||||
|
bob_identity = Identity.generate()
|
||||||
|
alice.chat._remember_profile(
|
||||||
|
{
|
||||||
|
"nick": "bob",
|
||||||
|
"node": bob_identity.node_id_hex,
|
||||||
|
"pub": bob_identity.public_hex,
|
||||||
|
"host": "",
|
||||||
|
"port": "",
|
||||||
|
"ts": 1e12,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
alice.chat._peer_address = lambda profile, node: None
|
||||||
|
|
||||||
|
result = await alice.chat.send_direct("bob", "离线留言")
|
||||||
|
|
||||||
|
self.assertFalse(result["delivered"])
|
||||||
|
inbox = await proxy.node.find_value(f"log/inbox/{bob_identity.node_id_hex}")
|
||||||
|
self.assertEqual(len(inbox), 1)
|
||||||
|
self.assertEqual(len(decode_log(inbox)), 1)
|
||||||
|
|
||||||
|
# Now bob comes online and drains his inbox.
|
||||||
|
bob_node = DhtNode(bob_identity, host="127.0.0.1", port=0)
|
||||||
|
await bob_node.start()
|
||||||
|
events: list[dict] = []
|
||||||
|
bob_chat = ChatService(
|
||||||
|
bob_node, bob_identity, self.tmp / "bob", events.append, nickname="bob"
|
||||||
|
)
|
||||||
|
bob = Peer(bob_node, bob_chat, events)
|
||||||
|
self.peers.append(bob)
|
||||||
|
await bob_chat.start()
|
||||||
|
self.assertIn(await bob_node.bootstrap([proxy.node.address]), (0, 1))
|
||||||
|
|
||||||
|
await bob_chat._poll_inbox()
|
||||||
|
|
||||||
|
self.assertEqual(bob.texts("direct_message"), ["离线留言"])
|
||||||
|
self.assertEqual(bob.of_type("direct_message")[0]["peer"], "alice")
|
||||||
|
|
||||||
|
async def test_sending_to_unknown_nickname_reports_failure(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
result = await alice.chat.send_direct("nobody", "在吗")
|
||||||
|
self.assertFalse(result["delivered"])
|
||||||
|
self.assertIn("找不到", result["reason"])
|
||||||
|
|
||||||
|
async def test_room_history_is_capped_and_deduplicated(self) -> None:
|
||||||
|
alice = await self.make_peer("alice")
|
||||||
|
alice.chat.join_room("大厅")
|
||||||
|
room = alice.chat.rooms["大厅"]
|
||||||
|
|
||||||
|
for index in range(5):
|
||||||
|
await alice.chat.send_room_message("大厅", f"消息{index}")
|
||||||
|
|
||||||
|
self.assertEqual(len(room.messages), 5)
|
||||||
|
self.assertEqual(len(room.seen), 5)
|
||||||
|
record = alice.chat._member_record(room)
|
||||||
|
self.assertIsNotNone(verify_record(record))
|
||||||
|
self.assertEqual(record["room"], "大厅")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
"""Test vectors for :mod:`dhtchat.crypto`.
|
||||||
|
|
||||||
|
Ed25519 vectors come from RFC 8032 section 7.1, X25519 vectors from
|
||||||
|
RFC 7748 sections 5.2 and 6.1.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
from dhtchat import crypto # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
class Ed25519Tests(unittest.TestCase):
|
||||||
|
VECTORS = [
|
||||||
|
(
|
||||||
|
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
|
||||||
|
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
|
||||||
|
"",
|
||||||
|
"e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821"
|
||||||
|
"590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
|
||||||
|
"3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",
|
||||||
|
"72",
|
||||||
|
"92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e4"
|
||||||
|
"3e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
|
||||||
|
"fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",
|
||||||
|
"af82",
|
||||||
|
"6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b53"
|
||||||
|
"8d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_public_key_derivation(self):
|
||||||
|
for seed_hex, public_hex, _, _ in self.VECTORS:
|
||||||
|
seed = bytes.fromhex(seed_hex)
|
||||||
|
self.assertEqual(
|
||||||
|
crypto.ed25519_public_key(seed).hex(), public_hex
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_signature_vectors(self):
|
||||||
|
for seed_hex, public_hex, message_hex, signature_hex in self.VECTORS:
|
||||||
|
seed = bytes.fromhex(seed_hex)
|
||||||
|
message = bytes.fromhex(message_hex)
|
||||||
|
signature = crypto.ed25519_sign(seed, message)
|
||||||
|
self.assertEqual(
|
||||||
|
crypto.ed25519_public_key(seed).hex(), public_hex
|
||||||
|
)
|
||||||
|
self.assertEqual(signature.hex(), signature_hex)
|
||||||
|
self.assertTrue(
|
||||||
|
crypto.ed25519_verify(bytes.fromhex(public_hex), message, signature)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_roundtrip_and_tamper(self):
|
||||||
|
seed = crypto.generate_private_key()
|
||||||
|
public = crypto.ed25519_public_key(seed)
|
||||||
|
message = b"hello dht chat"
|
||||||
|
signature = crypto.ed25519_sign(seed, message)
|
||||||
|
self.assertTrue(crypto.ed25519_verify(public, message, signature))
|
||||||
|
self.assertFalse(crypto.ed25519_verify(public, message + b"!", signature))
|
||||||
|
|
||||||
|
broken = bytearray(signature)
|
||||||
|
broken[10] ^= 0x01
|
||||||
|
self.assertFalse(crypto.ed25519_verify(public, message, bytes(broken)))
|
||||||
|
|
||||||
|
other_seed = crypto.generate_private_key()
|
||||||
|
self.assertFalse(
|
||||||
|
crypto.ed25519_verify(
|
||||||
|
crypto.ed25519_public_key(other_seed), message, signature
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_rejects_malformed_inputs(self):
|
||||||
|
seed = crypto.generate_private_key()
|
||||||
|
public = crypto.ed25519_public_key(seed)
|
||||||
|
signature = crypto.ed25519_sign(seed, b"x")
|
||||||
|
self.assertFalse(crypto.ed25519_verify(public, b"x", signature[:-1]))
|
||||||
|
self.assertFalse(crypto.ed25519_verify(public[:-1], b"x", signature))
|
||||||
|
self.assertFalse(crypto.ed25519_verify(public, b"x", b"\x00" * 64))
|
||||||
|
self.assertFalse(crypto.ed25519_verify(b"\x00" * 32, b"x", signature))
|
||||||
|
|
||||||
|
|
||||||
|
class X25519Tests(unittest.TestCase):
|
||||||
|
def test_rfc7748_scalar_mult(self):
|
||||||
|
scalar = bytes.fromhex(
|
||||||
|
"a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4"
|
||||||
|
)
|
||||||
|
point = bytes.fromhex(
|
||||||
|
"e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c"
|
||||||
|
)
|
||||||
|
expected = bytes.fromhex(
|
||||||
|
"c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552"
|
||||||
|
)
|
||||||
|
self.assertEqual(crypto.x25519(scalar, point), expected)
|
||||||
|
|
||||||
|
def test_rfc7748_diffie_hellman(self):
|
||||||
|
alice_private = bytes.fromhex(
|
||||||
|
"77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"
|
||||||
|
)
|
||||||
|
alice_public = bytes.fromhex(
|
||||||
|
"8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"
|
||||||
|
)
|
||||||
|
bob_private = bytes.fromhex(
|
||||||
|
"5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb"
|
||||||
|
)
|
||||||
|
bob_public = bytes.fromhex(
|
||||||
|
"de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"
|
||||||
|
)
|
||||||
|
shared = bytes.fromhex(
|
||||||
|
"4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"
|
||||||
|
)
|
||||||
|
self.assertEqual(crypto.x25519(alice_private, bob_public), shared)
|
||||||
|
self.assertEqual(crypto.x25519(bob_private, alice_public), shared)
|
||||||
|
|
||||||
|
def test_ed25519_conversion_agrees_with_ecdh(self):
|
||||||
|
seed_a = crypto.generate_private_key()
|
||||||
|
seed_b = crypto.generate_private_key()
|
||||||
|
pub_a = crypto.ed25519_public_key(seed_a)
|
||||||
|
pub_b = crypto.ed25519_public_key(seed_b)
|
||||||
|
|
||||||
|
secret_ab = crypto.shared_secret(seed_a, pub_b)
|
||||||
|
secret_ba = crypto.shared_secret(seed_b, pub_a)
|
||||||
|
self.assertEqual(secret_ab, secret_ba)
|
||||||
|
self.assertEqual(len(secret_ab), crypto.SHARED_SECRET_LEN)
|
||||||
|
|
||||||
|
|
||||||
|
class AeadTests(unittest.TestCase):
|
||||||
|
def test_roundtrip(self):
|
||||||
|
key = crypto.shared_secret(
|
||||||
|
crypto.generate_private_key(), crypto.ed25519_public_key(crypto.generate_private_key())
|
||||||
|
)
|
||||||
|
for payload in (b"", b"a", b"x" * 1000):
|
||||||
|
blob = crypto.aead_encrypt(key, payload, b"aad")
|
||||||
|
self.assertEqual(crypto.aead_decrypt(key, blob, b"aad"), payload)
|
||||||
|
if len(payload) > 16:
|
||||||
|
self.assertNotIn(payload, blob)
|
||||||
|
|
||||||
|
def test_authentication(self):
|
||||||
|
key = b"\x11" * 32
|
||||||
|
other = b"\x22" * 32
|
||||||
|
blob = bytearray(crypto.aead_encrypt(key, b"secret", b"aad"))
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
crypto.aead_decrypt(other, bytes(blob), b"aad")
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
crypto.aead_decrypt(key, bytes(blob), b"other-aad")
|
||||||
|
|
||||||
|
blob[-1] ^= 0x01
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
crypto.aead_decrypt(key, bytes(blob), b"aad")
|
||||||
|
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
crypto.aead_decrypt(key, b"short", b"aad")
|
||||||
|
|
||||||
|
def test_hkdf_matches_rfc5869_case1(self):
|
||||||
|
ikm = bytes.fromhex("0b" * 22)
|
||||||
|
salt = bytes.fromhex("000102030405060708090a0b0c")
|
||||||
|
info = bytes.fromhex("f0f1f2f3f4f5f6f7f8f9")
|
||||||
|
expected = bytes.fromhex(
|
||||||
|
"3cb25f25faacd57a90434f64d0362f2a"
|
||||||
|
"2d2d0a90cf1a5a4c5db02d56ecc4c5bf"
|
||||||
|
"34007208d5b887185865"
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
crypto.hkdf_sha256(ikm, salt, info, 42), expected
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main(verbosity=2)
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
"""Integration tests for the DHT layer: RPC, lookups, storage and routing."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
|
||||||
|
from dhtchat import protocol # noqa: E402
|
||||||
|
from dhtchat.identity import Identity # noqa: E402
|
||||||
|
from dhtchat.node import DhtNode # noqa: E402
|
||||||
|
from dhtchat.routing import distance # noqa: E402
|
||||||
|
from dhtchat.store import ValueStore, merge_grow, merge_records # noqa: E402
|
||||||
|
from dhtchat.util import local_ip # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
class Collector(asyncio.DatagramProtocol):
|
||||||
|
"""Captures UDP datagrams so tests can assert that nothing was sent."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.messages: list[bytes] = []
|
||||||
|
|
||||||
|
def datagram_received(self, data: bytes, addr) -> None:
|
||||||
|
self.messages.append(data)
|
||||||
|
|
||||||
|
def error_received(self, exc: Exception) -> None: # pragma: no cover
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class StoreMergeTests(unittest.TestCase):
|
||||||
|
def test_grow_union_is_order_independent(self) -> None:
|
||||||
|
a = json.dumps([{"id": "1", "ts": 1}, {"id": "2", "ts": 2}]).encode()
|
||||||
|
b = json.dumps([{"id": "2", "ts": 3}, {"id": "3", "ts": 4}]).encode()
|
||||||
|
merged = json.loads(merge_grow(a, b).decode())
|
||||||
|
self.assertEqual({item["id"] for item in merged}, {"1", "2", "3"})
|
||||||
|
self.assertEqual(merge_grow(b, a), merge_grow(a, b))
|
||||||
|
newest = next(item for item in merged if item["id"] == "2")
|
||||||
|
self.assertEqual(newest["ts"], 3)
|
||||||
|
|
||||||
|
def test_grow_merge_is_idempotent(self) -> None:
|
||||||
|
a = json.dumps([{"id": "1", "ts": 1}]).encode()
|
||||||
|
once = merge_grow(b"", a)
|
||||||
|
self.assertEqual(merge_grow(once, a), once)
|
||||||
|
|
||||||
|
def test_merge_records_picks_newest_lww(self) -> None:
|
||||||
|
older = json.dumps({"nick": "a", "ts": 10}).encode()
|
||||||
|
newer = json.dumps({"nick": "a", "ts": 20}).encode()
|
||||||
|
self.assertEqual(merge_records("profile/a", [older, newer]), [newer])
|
||||||
|
self.assertEqual(merge_records("profile/a", [newer, older]), [newer])
|
||||||
|
|
||||||
|
def test_merge_records_ignores_empty_blobs(self) -> None:
|
||||||
|
self.assertEqual(merge_records("profile/a", [b"", b""]), [])
|
||||||
|
|
||||||
|
def test_value_store_keeps_grow_keys_immortal_until_ttl(self) -> None:
|
||||||
|
store = ValueStore()
|
||||||
|
item_one = json.dumps([{"id": "1", "ts": 1}]).encode()
|
||||||
|
item_two = json.dumps([{"id": "2", "ts": 2}]).encode()
|
||||||
|
self.assertTrue(store.store("log/room/x", item_one, b"p", 60))
|
||||||
|
self.assertTrue(store.store("log/room/x", item_two, b"p", 60))
|
||||||
|
self.assertFalse(store.store("log/room/x", item_one, b"p", 60))
|
||||||
|
merged = json.loads(store.get("log/room/x").value.decode())
|
||||||
|
self.assertEqual(len(merged), 2)
|
||||||
|
|
||||||
|
def test_value_store_rejects_stale_lww_write(self) -> None:
|
||||||
|
store = ValueStore()
|
||||||
|
self.assertTrue(store.store("profile/a", b"new", b"p", 60, timestamp=100))
|
||||||
|
self.assertFalse(store.store("profile/a", b"old", b"p", 60, timestamp=50))
|
||||||
|
|
||||||
|
def test_value_store_rejects_oversized_value(self) -> None:
|
||||||
|
store = ValueStore()
|
||||||
|
self.assertFalse(store.store("profile/a", b"x" * (48 * 1024 + 1), b"p", 60))
|
||||||
|
|
||||||
|
|
||||||
|
class DhtNodeTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def asyncSetUp(self) -> None:
|
||||||
|
self.nodes: list[DhtNode] = []
|
||||||
|
|
||||||
|
async def asyncTearDown(self) -> None:
|
||||||
|
for node in self.nodes:
|
||||||
|
await node.stop()
|
||||||
|
|
||||||
|
async def make_node(self) -> DhtNode:
|
||||||
|
node = DhtNode(Identity.generate(), host="127.0.0.1", port=0)
|
||||||
|
await node.start()
|
||||||
|
self.nodes.append(node)
|
||||||
|
return node
|
||||||
|
|
||||||
|
async def raw_send(self, payload: bytes, addr: tuple) -> None:
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
sock.setblocking(False)
|
||||||
|
try:
|
||||||
|
await asyncio.get_running_loop().sock_sendto(sock, payload, addr)
|
||||||
|
finally:
|
||||||
|
sock.close()
|
||||||
|
|
||||||
|
async def start_collector(self) -> tuple[asyncio.DatagramTransport, Collector]:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
protocol_obj = Collector()
|
||||||
|
transport, _ = await loop.create_datagram_endpoint(
|
||||||
|
lambda: protocol_obj, local_addr=("127.0.0.1", 0)
|
||||||
|
)
|
||||||
|
self.addAsyncCleanup(_close_transport, transport)
|
||||||
|
return transport, protocol_obj
|
||||||
|
|
||||||
|
# -- tests ---------------------------------------------------------
|
||||||
|
async def test_ping_and_bootstrap_populate_both_tables(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
node_b = await self.make_node()
|
||||||
|
|
||||||
|
known = await node_b.bootstrap([node_a.address])
|
||||||
|
|
||||||
|
self.assertEqual(known, 1)
|
||||||
|
self.assertIsNotNone(node_a.routing.get(node_b.identity.node_id))
|
||||||
|
self.assertIsNotNone(node_b.routing.get(node_a.identity.node_id))
|
||||||
|
contact = node_a.routing.get(node_b.identity.node_id)
|
||||||
|
self.assertEqual(contact.address, ("127.0.0.1", node_b.bound_port))
|
||||||
|
|
||||||
|
async def test_pong_carries_nickname_and_updates_contact(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
node_b = await self.make_node()
|
||||||
|
node_b.nickname = "小北"
|
||||||
|
|
||||||
|
await node_a.bootstrap([node_b.address])
|
||||||
|
|
||||||
|
contact = node_a.routing.get(node_b.identity.node_id)
|
||||||
|
self.assertIsNotNone(contact)
|
||||||
|
self.assertEqual(contact.nickname, "小北")
|
||||||
|
|
||||||
|
async def test_wildcard_bind_host_advertises_a_reachable_address(self) -> None:
|
||||||
|
"""Peers cannot connect to 0.0.0.0, so a LAN address must be advertised."""
|
||||||
|
wildcard = DhtNode(Identity.generate(), host="0.0.0.0", port=0)
|
||||||
|
self.nodes.append(wildcard)
|
||||||
|
await wildcard.start()
|
||||||
|
await asyncio.sleep(0)
|
||||||
|
|
||||||
|
self.assertEqual(wildcard.address[1], wildcard.bound_port)
|
||||||
|
self.assertNotIn(wildcard.address[0], ("0.0.0.0", "", "::"))
|
||||||
|
self.assertEqual(wildcard.address[0], local_ip())
|
||||||
|
|
||||||
|
explicit = DhtNode(Identity.generate(), host="127.0.0.1", port=0)
|
||||||
|
self.nodes.append(explicit)
|
||||||
|
self.assertEqual(explicit.address[0], "127.0.0.1")
|
||||||
|
|
||||||
|
async def test_store_then_find_value_on_third_node(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
node_b = await self.make_node()
|
||||||
|
node_c = await self.make_node()
|
||||||
|
await node_b.bootstrap([node_a.address])
|
||||||
|
await node_c.bootstrap([node_b.address])
|
||||||
|
|
||||||
|
blob = json.dumps({"nick": "alice", "ts": time.time()}).encode()
|
||||||
|
stored = await node_a.store("profile/alice", blob, ttl=300)
|
||||||
|
|
||||||
|
self.assertGreaterEqual(stored, 1)
|
||||||
|
self.assertEqual(await node_c.find_value("profile/alice"), [blob])
|
||||||
|
self.assertEqual(await node_b.find_value("profile/alice"), [blob])
|
||||||
|
|
||||||
|
async def test_grow_key_merges_concurrent_writers(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
node_b = await self.make_node()
|
||||||
|
await node_b.bootstrap([node_a.address])
|
||||||
|
|
||||||
|
item_a = json.dumps([{"id": "aa", "ts": 1}]).encode()
|
||||||
|
item_b = json.dumps([{"id": "bb", "ts": 2}]).encode()
|
||||||
|
await node_a.store("log/room/test", item_a, ttl=300)
|
||||||
|
await node_b.store("log/room/test", item_b, ttl=300)
|
||||||
|
|
||||||
|
merged = await node_a.find_value("log/room/test")
|
||||||
|
self.assertEqual(len(merged), 1)
|
||||||
|
ids = {item["id"] for item in json.loads(merged[0].decode())}
|
||||||
|
self.assertEqual(ids, {"aa", "bb"})
|
||||||
|
|
||||||
|
async def test_find_peer_locates_unknown_node(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
node_b = await self.make_node()
|
||||||
|
await node_a.bootstrap([node_b.address])
|
||||||
|
|
||||||
|
found = await node_a.find_peer(node_b.identity.node_id)
|
||||||
|
|
||||||
|
self.assertIsNotNone(found)
|
||||||
|
self.assertEqual(found.node_id, node_b.identity.node_id)
|
||||||
|
|
||||||
|
async def test_find_peer_returns_none_for_stranger(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
node_b = await self.make_node()
|
||||||
|
await node_a.bootstrap([node_b.address])
|
||||||
|
|
||||||
|
self.assertIsNone(await node_a.find_peer(Identity.generate().node_id))
|
||||||
|
|
||||||
|
async def test_send_routed_delivers_through_relay(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
node_b = await self.make_node()
|
||||||
|
node_c = await self.make_node()
|
||||||
|
await node_a.bootstrap([node_b.address])
|
||||||
|
await node_b.bootstrap([node_c.address])
|
||||||
|
|
||||||
|
# node_a must know nothing about node_c, forcing a relay through node_b.
|
||||||
|
node_a.routing.remove(node_c.identity.node_id)
|
||||||
|
self.assertIsNone(node_a.routing.get(node_c.identity.node_id))
|
||||||
|
self.assertIsNotNone(node_b.routing.get(node_c.identity.node_id))
|
||||||
|
|
||||||
|
received: list[bytes] = []
|
||||||
|
node_c.set_route_handler(lambda dst, payload, addr: received.append(payload))
|
||||||
|
|
||||||
|
delivered = await node_a.send_routed(
|
||||||
|
node_c.identity.node_id, b"hello-relay", timeout=5.0
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertTrue(delivered)
|
||||||
|
self.assertEqual(received, [b"hello-relay"])
|
||||||
|
self.assertGreaterEqual(node_b.stats["relayed"], 1)
|
||||||
|
self.assertGreaterEqual(node_c.stats["received"], 1)
|
||||||
|
|
||||||
|
async def test_send_routed_to_self_invokes_handler(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
received: list[bytes] = []
|
||||||
|
node_a.set_route_handler(lambda dst, payload, addr: received.append(payload))
|
||||||
|
|
||||||
|
self.assertTrue(await node_a.send_routed(node_a.identity.node_id, b"self"))
|
||||||
|
self.assertEqual(received, [b"self"])
|
||||||
|
|
||||||
|
async def test_send_routed_reports_failure_for_unreachable_id(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
node_b = await self.make_node()
|
||||||
|
await node_a.bootstrap([node_b.address])
|
||||||
|
|
||||||
|
delivered = await node_a.send_routed(
|
||||||
|
Identity.generate().node_id, b"nowhere", timeout=3.0
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertFalse(delivered)
|
||||||
|
|
||||||
|
async def test_oversized_request_is_fragmented_across_datagrams(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
node_b = await self.make_node()
|
||||||
|
received: list[dict] = []
|
||||||
|
node_b.register_handler(protocol.NOTIFY, lambda message, addr: received.append(message))
|
||||||
|
|
||||||
|
message = node_a._base(protocol.NOTIFY)
|
||||||
|
message["id"] = protocol.new_id()
|
||||||
|
message["padding"] = "x" * 4000
|
||||||
|
|
||||||
|
self.assertTrue(node_a.send_raw(message, node_b.address))
|
||||||
|
self.assertGreater(node_a.stats["sent"], 1)
|
||||||
|
await asyncio.sleep(0.4)
|
||||||
|
self.assertEqual(len(received), 1)
|
||||||
|
self.assertEqual(received[0]["padding"], "x" * 4000)
|
||||||
|
|
||||||
|
async def test_request_beyond_the_fragment_budget_is_dropped(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
message = node_a._base(protocol.PING)
|
||||||
|
message["id"] = protocol.new_id()
|
||||||
|
message["padding"] = "x" * (protocol.CHUNK_SIZE * protocol.MAX_CHUNKS)
|
||||||
|
|
||||||
|
before = node_a.stats["dropped"]
|
||||||
|
self.assertFalse(node_a.send_raw(message, ("127.0.0.1", 9)))
|
||||||
|
self.assertEqual(node_a.stats["dropped"], before + 1)
|
||||||
|
|
||||||
|
async def test_malformed_datagrams_do_not_kill_the_node(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
for payload in (b"", b"not json", b"\x00" * 2000, b"[1,2,3]", b'{"v":99,"t":"ping"}'):
|
||||||
|
await self.raw_send(payload, node_a.address)
|
||||||
|
|
||||||
|
node_b = await self.make_node()
|
||||||
|
self.assertEqual(await node_b.bootstrap([node_a.address]), 1)
|
||||||
|
self.assertIsNotNone(node_b.routing.get(node_a.identity.node_id))
|
||||||
|
|
||||||
|
async def test_node_id_must_match_public_key(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
_, collector = await self.start_collector()
|
||||||
|
|
||||||
|
impostor = Identity.generate()
|
||||||
|
message = {
|
||||||
|
"v": protocol.PROTOCOL_VERSION,
|
||||||
|
"t": protocol.PING,
|
||||||
|
"id": protocol.new_id(),
|
||||||
|
"src": Identity.generate().node_id_hex,
|
||||||
|
"pub": impostor.public_hex,
|
||||||
|
}
|
||||||
|
await self.raw_send(protocol.encode(message), node_a.address)
|
||||||
|
await asyncio.sleep(0.5)
|
||||||
|
|
||||||
|
self.assertEqual(collector.messages, [])
|
||||||
|
self.assertEqual(node_a.stats["received"], 0)
|
||||||
|
|
||||||
|
async def test_unsigned_route_message_is_rejected(self) -> None:
|
||||||
|
node_a = await self.make_node()
|
||||||
|
received: list[bytes] = []
|
||||||
|
node_a.set_route_handler(lambda dst, payload, addr: received.append(payload))
|
||||||
|
|
||||||
|
message = {
|
||||||
|
"v": protocol.PROTOCOL_VERSION,
|
||||||
|
"t": protocol.ROUTE,
|
||||||
|
"id": protocol.new_id(),
|
||||||
|
"src": "00" * 20,
|
||||||
|
"pub": "00" * 32,
|
||||||
|
"dst": node_a.identity.node_id_hex,
|
||||||
|
"hops": 3,
|
||||||
|
"payload": protocol.b64encode(b"spoofed"),
|
||||||
|
}
|
||||||
|
await self.raw_send(protocol.encode(message), node_a.address)
|
||||||
|
await asyncio.sleep(0.3)
|
||||||
|
|
||||||
|
self.assertEqual(received, [])
|
||||||
|
|
||||||
|
|
||||||
|
async def _close_transport(transport: asyncio.DatagramTransport) -> None:
|
||||||
|
transport.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user