初始版本:基于 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

+368
View File
@@ -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()
+178
View File
@@ -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)
+318
View File
@@ -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()