Source code for fleetmesh_protocols.textile.leaf_relay

"""Hosted Leaf Relay Inventory & RFC 6455 WebSocket Transport (`node.protocols.textile.leaf_relay`)."""
from __future__ import annotations

import base64
import hashlib
import json
import re
import struct
import threading
import time
from typing import Any, Callable, Mapping, MutableMapping

from fleetmesh_core.textile.bao import canonical_bao_hex
from fleetmesh_core.textile.leaf_envelope import (
    KIND_FABRIC,
    KIND_FIBER,
    KIND_QUILT,
    KIND_STRAND,
    NEG_BUCKETS,
    NEG_FINGERPRINT,
    NEG_ID_LIST,
    NEG_INFINITY,
    NEG_LIST_THRESHOLD,
    NEG_SKIP,
    NEG_VERSION,
    WS_GUID,
    NegBound,
    NegentropyServer,
    decode_neg_message,
    decode_varint,
    encode_neg_message,
    encode_varint,
    neg_fingerprint,
)

_HEX64_RE = re.compile(r"^[0-9a-fA-F]{64}$")


[docs]def det_hex(seed: str) -> str: """SHA-256 hex of `seed`: how hosted relays derive their keys and synthetic inventory ids. Not `canonical_bao_hex` (a Bao leaf hash, `sha256(0x00 || seed)`): deployed mediators derived their agreement, transport and operator keys with plain SHA-256, and leaves cache the descriptor carrying those keys, so a different derivation silently rotates every hosted mediator's keys. """ return hashlib.sha256(seed.encode("utf-8")).hexdigest()
def _is_hex64(s: Any) -> bool: return isinstance(s, str) and bool(_HEX64_RE.match(s))
[docs]def build_engine_textile_inventory( engine: Any, node_pk: str, descriptors_map: Mapping[str, MutableMapping[str, Any]], verify_event_fn: Callable[[Mapping[str, Any]], bool] = lambda d: bool(d.get("id") and d.get("sig")), ) -> MutableMapping[str, Any]: """Collect the 8-layer Textile inventory (Fibers, Strands, Fabrics, Quilts, Spools, Chunks, Suits, Fits).""" now = int(time.time()) base_ts = now - 1800 quilts: list[MutableMapping[str, Any]] = [] fabrics: list[MutableMapping[str, Any]] = [] strands: list[MutableMapping[str, Any]] = [] fibers: list[MutableMapping[str, Any]] = [] descriptors: list[MutableMapping[str, Any]] = [] qstore = getattr(engine, "quilt_store", None) if qstore is not None: raw_views = getattr(qstore, "_views", None) if isinstance(raw_views, Mapping): for (okey, aud), view in list(raw_views.items()): # Anyone may open a negentropy session, so only public views are listed: a `self` # or `circle` view's roots, owner and sealed shard fibers stay with its readers. if not isinstance(view, Mapping) or aud != "public": continue raw_q = view.get("quilt") q_obj: Mapping[str, Any] = raw_q if isinstance(raw_q, Mapping) else view qroot = str(q_obj.get("quilt_root") or det_hex(f"quilt:{okey}:{aud}")) ts = int(q_obj.get("updated_at") or view.get("updated_at") or base_ts) raw_f_list = view.get("fabrics") f_list: list[Any] = raw_f_list if isinstance(raw_f_list, list) else [] f_roots = [str((f.get("snapshot") or {}).get("fabric_root") or f.get("fabric_root") or "") for f in f_list if isinstance(f, Mapping)] quilts.append({ "id": det_hex(f"quilt-ev:{okey}:{aud}:{qroot}"), "quilt_root": qroot, "user_id": str(okey), "audience": str(aud), "version": int(q_obj.get("version") or 1), "fabric_roots": [r for r in f_roots if r], "strand_roots": [], "shard_fibers": {}, "timestamp": ts, "label": f"Quilt ({aud}) by {okey}", }) for sf in (q_obj.get("shard_fibers") or []): froot = str(sf.get("fiber_root") or "") if isinstance(sf, Mapping) else "" if _is_hex64(froot): fibers.append({ "id": froot.lower(), "fiber_root": froot.lower(), "media_type": "application/vnd.fleetmesh.shard+octet-stream", "total_bytes": int(sf.get("byte_length") or sf.get("total_bytes") or 0), "timestamp": ts, "label": f"Sealed Shard Fiber ({sf.get('shard_type') or 'shard'}) · {okey}", }) if not quilts: default_qroot = det_hex(f"anchor-public-quilt:{node_pk}") quilts.append({ "id": default_qroot, "quilt_root": default_qroot, "user_id": "anchor", "audience": "public", "version": 1, "fabric_roots": [], "strand_roots": [], "shard_fibers": {}, "timestamp": base_ts, "label": "FleetMesh Anchor Public Quilt (v1)", }) section_strands: dict[str, list[str]] = {"vod": [], "music": [], "social": [], "live": [], "scrobble": []} vod_raw = getattr(engine, "_vods", None) or getattr(engine, "vods", None) or [] vod_list = list(vod_raw.values()) if isinstance(vod_raw, Mapping) else list(vod_raw) for idx, v in enumerate(vod_list): if not isinstance(v, Mapping): continue vid = str(v.get("vod_id") or f"vod-{idx}") sroot = str(v.get("tree_root") or v.get("bao_root") or det_hex(f"strand:vod:{vid}")) hid = sroot.lower() if _is_hex64(sroot) else det_hex(f"strand:vod:{vid}:{sroot}") ts = int(v.get("published_at") or (base_ts - idx * 60)) sec = str(v.get("section") or "vod") strands.append({ "id": hid, "strand_id": vid, "strand_root": hid, "strand_kind": "media", "section": sec, "timestamp": ts, "label": f"Media Strand: {v.get('title', vid)} ({v.get('resolution', '1080p')})", }) section_strands.setdefault(sec, []).append(hid) f_hid = det_hex(f"fiber:vod:{hid}") fibers.append({ "id": f_hid, "fiber_root": f_hid, "media_type": "video/mp4", "total_bytes": int(v.get("size_bytes") or 4_194_304), "timestamp": ts, "label": f"Bao Video Fiber: {v.get('title', vid)}", }) for idx, m in enumerate(list(getattr(engine, "music_tracks", []) or [])): if not isinstance(m, Mapping): continue tid = str(m.get("track_id") or f"track-{idx}") hid = det_hex(f"strand:music:{tid}") ts = base_ts - idx * 45 strands.append({ "id": hid, "strand_id": tid, "strand_root": hid, "strand_kind": "music", "section": "music", "timestamp": ts, "label": f"Audio Strand: {m.get('title', tid)} — {m.get('artist', 'Artist')}", }) section_strands["music"].append(hid) sstore = getattr(engine, "social_strands_store", None) social_list = list(getattr(sstore, "_strands", {}).values()) if isinstance(getattr(sstore, "_strands", None), Mapping) else [] for idx, s in enumerate(social_list): if not isinstance(s, Mapping): continue sid = str(s.get("strand_id") or f"social-{idx}") hid = str(s.get("strand_root") or det_hex(f"strand:social:{sid}")).lower() ts = int(s.get("created_at_ts") or s.get("created_at") or (base_ts - idx * 30)) strands.append({ "id": hid, "strand_id": sid, "strand_root": hid, "strand_kind": "social", "section": "social", "timestamp": ts, "label": f"Social Strand by {s.get('author_handle', '@peer')}: {str(s.get('body') or s.get('title') or '')[:36]}", }) section_strands["social"].append(hid) if len(strands) < 2: for idx, (sid, sec, lbl) in enumerate((("anchor-welcome", "vod", "Anchor Genesis Media Strand"), ("anchor-social", "social", "Anchor Genesis Social Strand"))): hid = det_hex(f"strand:genesis:{node_pk}:{sid}") strands.append({"id": hid, "strand_id": sid, "strand_root": hid, "strand_kind": sec, "section": sec, "timestamp": base_ts - idx * 60, "label": lbl}) section_strands.setdefault(sec, []).append(hid) for sec_idx, (sec_name, sroots) in enumerate(section_strands.items()): if not sroots and sec_name not in ("vod", "music", "social"): continue froot = det_hex(f"fabric:{sec_name}:{','.join(sroots[:16])}") fabrics.append({ "id": froot, "fabric_root": froot, "fabric_kind": f"section:{sec_name}", "strand_roots": sroots, "timestamp": base_ts - sec_idx * 20, "label": f"Fabric ({sec_name.upper()}) · {len(sroots)} strand(s)", }) fstore = getattr(engine, "fiber_store", None) if fstore is not None: for froot, fentry in list(getattr(fstore, "_entries", {}).items()): if _is_hex64(froot): mtype = str(getattr(fentry, "media_type", "application/octet-stream")) fibers.append({ "id": froot.lower(), "fiber_root": froot.lower(), "media_type": mtype, "total_bytes": int(getattr(fentry, "total_bytes", 0)), "timestamp": int(getattr(fentry, "created_at", base_ts)), "label": f"Bao Fiber {froot[:14]}… ({mtype})", }) if len(fibers) < 2: for idx, s in enumerate(strands[:2]): fhid = det_hex(f"fiber:strand:{s['strand_root']}") fibers.append({"id": fhid, "fiber_root": fhid, "media_type": "application/vnd.fleetmesh.manifest+json", "total_bytes": 1024, "timestamp": int(s["timestamp"]), "label": f"Bao Manifest Fiber #{idx + 1}"}) for pk, d in descriptors_map.items(): if verify_event_fn(d): role = "anchor" if pk == node_pk else "leaf" descriptors.append({ "id": str(d["id"]), "pubkey": pk, "timestamp": int(d["created_at"]), "label": f"kind:11801 ({role}) did:nostr:{pk[:14]}…", "event": d, }) suits = [ { "id": det_hex(f"suit:{node_pk}:{slug}"), "suit_root": det_hex(f"suit:{node_pk}:{slug}"), "suit_id": slug, "quilt_roots": [str(q["quilt_root"]) for q in quilts[:3]], "fiber_count": len(fibers), "timestamp": base_ts - idx * 40, "label": f"{lbl} · {len(quilts)} quilt(s), {len(fibers)} fiber(s)", } for idx, (slug, lbl) in enumerate(( ("sovereign-personal-suit", "Sovereign Personal Suit (.fiberpack v2)"), ("circle-offline-suit", "Circle Offline Mission Suit (.fiberpack v2)"), ("creator-archive-suit", "Creator Master Archive Suit (.fiberpack v2)"), )) ] fits = [ { "id": det_hex(f"fit:{node_pk}:{fid}:{qmb}"), "fit_root": det_hex(f"fit:{node_pk}:{fid}:{qmb}"), "policy_id": fid, "quota_mb": qmb, "timestamp": base_ts - idx * 35, "label": lbl, } for idx, (fid, qmb, lbl) in enumerate(( ("fit-sovereign-default-v1", 2048, "Sovereign Desktop/PWA Leaf Fit (2 GB · Auto-Pin Shards & Circle)"), ("fit-mobile-saver-v1", 512, "Mobile Leaf Saver Fit (512 MB · Metadata & Audio Priority)"), ("fit-archival-node-v1", 8192, "Archival Steward Leaf Fit (8 GB · Whole-Fabric Pinning)"), )) ] spools = [ { "id": det_hex(f"spool:{node_pk}:{slug}"), "spool_id": det_hex(f"spool:{node_pk}:{slug}"), "spool_root": det_hex(f"spool:{node_pk}:{slug}"), "kind": kind, "timestamp": base_ts - idx * 45, "label": lbl, } for idx, (slug, kind, lbl) in enumerate(( ("anchor-live-channel-spool", "channel", "Anchor Live Broadcast Spool (MTF1 + Filament + Spool Cut)"), ("circle-dm-spool", "dm", "Circle Encrypted DM Spool (Append-Only BIP-340 Op Chain)"), ("mesh-telemetry-sensor-spool", "sensor", "Mesh Edge Telemetry Sensor Spool (Periodic Cut Compaction)"), )) ] chunks = [ { "id": det_hex(f"chunk-subtree:{str(fe.get('fiber_root') or fe.get('id') or '')}:0"), "chunk_root": det_hex(f"chunk-subtree:{str(fe.get('fiber_root') or fe.get('id') or '')}:0"), "fiber_root": str(fe.get("fiber_root") or fe.get("id") or ""), "chunk_index": 0, "byte_length": min(int(fe.get("total_bytes") or 1_048_576), 1_048_576), "timestamp": int(fe.get("timestamp") or (base_ts - idx * 25)), "label": f"1 MiB Height-10 Bao Subtree #0 · Fiber {str(fe.get('fiber_root') or fe.get('id') or '')[:12]}…", } for idx, fe in enumerate(fibers[:6]) ] return { "quilts": quilts, "fabrics": fabrics, "strands": strands, "fibers": fibers, "spools": spools, "chunks": chunks, "suits": suits, "fits": fits, "descriptors": descriptors, "counts": { "quilts": len(quilts), "fabrics": len(fabrics), "strands": len(strands), "fibers": len(fibers), "spools": len(spools), "chunks": len(chunks), "suits": len(suits), "fits": len(fits), "descriptors": len(descriptors), }, "summary": { "quilt_count": len(quilts), "fabric_count": len(fabrics), "strand_count": len(strands), "fiber_count": len(fibers), "spool_count": len(spools), "chunk_count": len(chunks), "suit_count": len(suits), "fit_count": len(fits), "descriptor_count": len(descriptors), }, }
# The largest frame a client may send. A leaf's gift wrap stays under about 90 KB (its JWE is # fragmented at 24,000 bytes), so 1 MiB leaves room without letting a frame's declared length # (up to 2^63) decide how much the relay buffers. WS_MAX_FRAME = 1024 * 1024 def _recv_exact(conn: Any, n: int) -> bytes: buf = bytearray() while len(buf) < n: chunk = conn.recv(n - len(buf)) if not chunk: return b"" buf.extend(chunk) return bytes(buf)
[docs]def serve_relay_websocket( handler: Any, ws_subs: dict[int, tuple[Callable[[list[Any]], None], dict[str, list[MutableMapping[str, Any]]]]], lock: threading.RLock, process_frame: Callable[[list[Any], dict[str, list[MutableMapping[str, Any]]]], list[list[Any]]], ) -> bool: """RFC 6455 WebSocket upgrade and frame loop for HostedLeafRelay.""" ws_key = (handler.headers.get("Sec-WebSocket-Key") or "").strip() if not ws_key: return False accept = base64.b64encode(hashlib.sha1((ws_key + WS_GUID).encode("ascii")).digest()).decode("ascii") handler.send_response(101, "Switching Protocols") handler.send_header("Upgrade", "websocket") handler.send_header("Connection", "Upgrade") handler.send_header("Sec-WebSocket-Accept", accept) handler.end_headers() handler.close_connection = True conn = handler.connection conn.settimeout(60.0) write_lock = threading.Lock() sub_map: dict[str, list[MutableMapping[str, Any]]] = {} conn_id = id(conn) def send_close(code: int) -> None: # A socket error here propagates to the frame loop's handler, which ends the connection. with write_lock: conn.sendall(bytes([0x88, 2]) + struct.pack(">H", code)) def send_ws_frame(frame_obj: list[Any]) -> None: payload = json.dumps(frame_obj, separators=(",", ":"), ensure_ascii=False).encode("utf-8") n = len(payload) header = bytearray([0x81]) if n < 126: header.append(n) elif n < 65536: header.append(126) header.extend(struct.pack(">H", n)) else: header.append(127) header.extend(struct.pack(">Q", n)) with write_lock: conn.sendall(bytes(header) + payload) with lock: ws_subs[conn_id] = (send_ws_frame, sub_map) try: while True: hdr = _recv_exact(conn, 2) if not hdr: break opcode, masked, length = hdr[0] & 0x0F, bool(hdr[1] & 0x80), hdr[1] & 0x7F if opcode == 0x8: break if length == 126: ext = _recv_exact(conn, 2) if not ext: break length = struct.unpack(">H", ext)[0] elif length == 127: ext = _recv_exact(conn, 8) if not ext: break length = struct.unpack(">Q", ext)[0] if length > WS_MAX_FRAME: send_close(1009) break if not masked or (opcode >= 0x8 and length > 125): send_close(1002) break mask_key = _recv_exact(conn, 4) if not mask_key: break data = _recv_exact(conn, length) if length > 0 else b"" data = bytes(b ^ mask_key[i % 4] for i, b in enumerate(data)) if opcode == 0x9: with write_lock: conn.sendall(bytes([0x8A, len(data)]) + data) continue if opcode != 0x1: continue try: msg = json.loads(data.decode("utf-8")) except Exception: continue for resp in process_frame(msg, sub_map): send_ws_frame(resp) except Exception as exc: _ = exc finally: with lock: ws_subs.pop(conn_id, None) return True
__all__ = [ "det_hex", "WS_GUID", "WS_MAX_FRAME", "KIND_FIBER", "KIND_STRAND", "KIND_FABRIC", "KIND_QUILT", "NEG_VERSION", "NEG_INFINITY", "NEG_SKIP", "NEG_FINGERPRINT", "NEG_ID_LIST", "NEG_BUCKETS", "NEG_LIST_THRESHOLD", "canonical_bao_hex", "encode_varint", "decode_varint", "neg_fingerprint", "NegBound", "encode_neg_message", "decode_neg_message", "NegentropyServer", "build_engine_textile_inventory", "serve_relay_websocket", ]