"""NIP-77 Negentropy V1 (0x61) & Leaf Textile Envelope Primitives (`fleetmesh_core.textile.leaf_envelope`)."""
from __future__ import annotations
import bisect
import re
from typing import Any, Iterable, Optional
from ..storage import negentropy as _neg
from .bao import canonical_bao_hex
WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
KIND_FIBER = 30820
KIND_STRAND = 30821
KIND_FABRIC = 30822
KIND_QUILT = 30823
# The negentropy codec is the node's (fleetmesh_core.storage.negentropy): one
# implementation of the wire format. This module had its own copy, which
# trusted the counts and lengths in a message until audit 2026-11-18 (textile
# #14) and stayed a weaker duplicate of the stricter one; the names below are
# the ones textile callers already use.
NEG_VERSION = _neg.VERSION
NEG_INFINITY = _neg.INFINITY
NEG_SKIP, NEG_FINGERPRINT, NEG_ID_LIST = _neg.SKIP, _neg.FINGERPRINT, _neg.ID_LIST
NEG_BUCKETS = _neg.BUCKETS
NEG_LIST_THRESHOLD = _neg.LIST_THRESHOLD
_HEX64_RE = re.compile(r"^[0-9a-fA-F]{64}$")
def _is_hex64(s: Any) -> bool:
return isinstance(s, str) and bool(_HEX64_RE.match(s))
encode_varint = _neg.encode_varint
decode_varint = _neg.decode_varint
neg_fingerprint = _neg.fingerprint
NegBound = _neg.Bound
_minimal_bound = _neg.minimal_bound
encode_neg_message = _neg.encode_message
decode_neg_message = _neg.decode_message
[docs]class NegentropyServer:
"""Server-side NIP-77 Negentropy V1 reconciler."""
[docs] def __init__(self, items: Iterable[tuple[int, str]]) -> None:
dedup: dict[str, tuple[int, str]] = {}
for ts, hid in items:
if _is_hex64(hid):
dedup[hid.lower()] = (max(0, int(ts)), hid.lower())
self.items = sorted(dedup.values())
self._keys = [(ts, bytes.fromhex(i)) for ts, i in self.items]
def _slice(self, lower: NegBound, upper: NegBound) -> list[tuple[int, str]]:
lo = bisect.bisect_left(self._keys, lower.key())
hi = bisect.bisect_left(self._keys, upper.key())
return self.items[lo:hi]
def _split(self, lower: NegBound, upper: NegBound, out: list[tuple[NegBound, int, Any]]) -> None:
items = self._slice(lower, upper)
if len(items) < NEG_LIST_THRESHOLD:
out.append((upper, NEG_ID_LIST, [i[1] for i in items]))
return
per, extra = divmod(len(items), NEG_BUCKETS)
start = 0
for b in range(NEG_BUCKETS):
end = start + per + (1 if b < extra else 0)
chunk = items[start:end]
bd = upper if end >= len(items) else _minimal_bound(items[end - 1], items[end])
out.append((bd, NEG_FINGERPRINT, neg_fingerprint(chunk)))
start = end
[docs] def reconcile(self, message: bytes) -> Optional[bytes]:
if not message:
return None
if message[0] != NEG_VERSION:
return bytes([NEG_VERSION])
ranges = decode_neg_message(message)
out: list[tuple[NegBound, int, Any]] = []
lower = NegBound(0)
for upper, mode, payload in ranges:
mine = self._slice(lower, upper)
if mode == NEG_FINGERPRINT and neg_fingerprint(mine) != payload:
self._split(lower, upper, out)
elif mode == NEG_ID_LIST:
out.append((upper, NEG_ID_LIST, [i[1] for i in mine]))
else:
if out and out[-1][1] == NEG_SKIP:
out[-1] = (upper, NEG_SKIP, None)
else:
out.append((upper, NEG_SKIP, None))
lower = upper
while out and out[-1][1] == NEG_SKIP:
out.pop()
return encode_neg_message(out) if out else None
__all__ = [
"WS_GUID",
"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",
]