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

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

165 lines
5.1 KiB
Python

"""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}