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