初始版本:基于 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:
MrhongxingandCopilot committed 2026-09-18 17:38:36 +08:00
commit e002ba9f62
19 files changed
+5064

No files matched your search

+751
View File
@@ -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)