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