Compare commits

...
103 Commits
Author SHA1 Message Date
Mark Qvist ea98db4f53 Prepare release 2026-08-29 04:16:13 +02:00
Mark Qvist ad3c06636b Adjusted logging 2026-08-29 04:10:50 +02:00
Mark Qvist 9ce4502961 Updated changelog 2026-08-29 01:36:31 +02:00
Mark Qvist a3cd84111f Updated default config with null_ident blocking example 2026-08-29 01:31:05 +02:00
Mark Qvist d5b2fc5609 Updated changelog 2026-08-29 00:16:42 +02:00
Mark Qvist 83a30b187a Tuned dataplane control defaults 2026-08-28 23:57:31 +02:00
Mark Qvist 943771a3f9 Updated version 2026-08-28 23:41:20 +02:00
Mark Qvist 5b4117dadc Skip local shared instance interfaces in ingress/egress control 2026-08-28 23:41:00 +02:00
Mark Qvist 6bc0481cdf Always remember to flush 2026-08-28 23:33:32 +02:00
Mark Qvist 4eebf0b685 Guard empty keepalive frames 2026-08-28 21:47:24 +02:00
Mark Qvist 149e415109 Prepare release 2026-08-28 16:03:16 +02:00
Mark Qvist 53ed9c1ed3 Updated version 2026-08-28 15:28:48 +02:00
Mark Qvist ccc5468bcc Updated changelog 2026-08-28 15:21:02 +02:00
Mark Qvist c1d7c12b52 Fixed stream-based resource initialized transfer failing when total sized happened to not fall withing MAX_EFFICIENT_SIZE 2026-08-28 14:43:39 +02:00
Mark Qvist 9878b18377 Added transmit buffer, TX drops and stalled status output to rnstatus 2026-08-28 13:44:14 +02:00
Mark Qvist 6e8c976421 Worker spawn prep 2026-08-28 12:44:59 +02:00
Mark Qvist b28f5ebf7a Allow inbound queue utilization in drainer benchmarks 2026-08-28 11:11:42 +02:00
Mark Qvist 77c8256a1a Fixed invalid prefix stripping in rngit page server 2026-08-28 01:50:46 +02:00
Mark Qvist dc9cf0c2f4 Updated setup.py 2026-08-28 00:09:16 +02:00
Mark Qvist fa07c8c87c Updated setup.py 2026-08-27 23:56:19 +02:00
Mark Qvist b7fe01237d Updated setup.py 2026-08-27 23:38:29 +02:00
Mark Qvist 3543dc9802 Load module compilation status from buildinfo if available 2026-08-27 23:37:43 +02:00
Mark Qvist 5b04a88026 Updated makefile 2026-08-27 23:36:34 +02:00
Mark Qvist 5fdd661081 Updated makefile 2026-08-27 22:53:15 +02:00
Mark Qvist ae0191578f Updated Cython dev shim 2026-08-27 22:37:51 +02:00
Mark Qvist e714c559cc Updated tests init 2026-08-27 22:17:38 +02:00
Mark Qvist 75cbc73f64 Removed dead Python 2 code from umsgpack 2026-08-27 21:05:27 +02:00
Mark Qvist d32ba8c1a1 Fixed inconsistency against advertised return type 2026-08-27 21:04:40 +02:00
Mark Qvist ff3a72209e Avoid rebind of exception reference 2026-08-27 18:32:41 +02:00
Mark Qvist 803b548951 Allow loading compiled modules 2026-08-27 14:56:47 +02:00
Mark Qvist 67a45ac5e9 Fixed nav init order 2026-08-27 14:55:20 +02:00
Mark Qvist e71c01959f Fixed stray non-imported variable 2026-08-27 14:49:32 +02:00
Mark Qvist 0a1b9453b2 Fixed non-epoll backend keepalive 2026-08-27 14:47:05 +02:00
Mark Qvist 79cad39e78 Fixed missing import 2026-08-27 14:43:21 +02:00
Mark Qvist de0dac695b Fixed missing exception reference 2026-08-27 13:12:53 +02:00
Mark Qvist 281c47f3e0 Fixed invalid reference in exception description 2026-08-27 13:12:04 +02:00
Mark Qvist 99c428a9f5 Added dataplane egress control 2026-08-27 02:22:55 +02:00
Mark Qvist cb9071b478 Added HWM limit option to TransmitBuffer 2026-08-27 01:56:43 +02:00
Mark Qvist 10848b7cff Added egress control HWM limiter test 2026-08-27 01:55:28 +02:00
Mark Qvist 89e73db94a Wired coalescing transmit buffer and optimized HDLC deframer into Backbone and Local interfaces 2026-08-26 22:18:37 +02:00
Mark Qvist 0ec84c7491 Added coalescing transmit buffer 2026-08-26 21:58:51 +02:00
Mark Qvist ac9130f01f Added coalesced transmit test 2026-08-26 21:38:15 +02:00
Mark Qvist 54a919f045 Added optimized HDLC implementation 2026-08-26 20:59:38 +02:00
Mark Qvist bafc09d3a6 Cleanup 2026-08-26 14:26:34 +02:00
Mark Qvist 419956bada Over-optimization is the root of all evil 2026-08-26 13:25:14 +02:00
Mark Qvist 1a16fdb727 Fixed inbound queue high-water mark initialization order 2026-08-26 01:05:01 +02:00
Mark Qvist 3b7cfc0666 Cleanup 2026-08-26 00:15:44 +02:00
Mark Qvist de76b8939f Added dataplane ingress control 2026-08-25 23:30:59 +02:00
Mark Qvist d80245b62c Traffic class and violation handling 2026-08-25 14:02:08 +02:00
Mark Qvist dcbc7638d0 Fixed RSSI/SNR reporting regression 2026-08-25 13:22:46 +02:00
Mark Qvist 0536b972d7 Tuned QUEUED_ANNOUNCES. Logging. 2026-08-25 12:08:43 +02:00
Mark Qvist 47add6381d Increase queues for throughput tests 2026-08-25 11:14:38 +02:00
Mark Qvist be2ba7c2f3 Tuned auto MTU configurration 2026-08-25 11:08:01 +02:00
Mark Qvist dd204e11ce Added 32k throughput run 2026-08-25 11:07:38 +02:00
Mark Qvist be4ee32908 Tuned queuelen defaults 2026-08-25 10:58:08 +02:00
Mark Qvist 9f66b5a6a3 Merge branch 'optimize' 2026-08-25 02:51:54 +02:00
Mark Qvist d38a8de571 Fixed f-strings for old snakes 2026-08-25 02:18:23 +02:00
Mark Qvist dea0124c57 Reduced lock acquisition 2026-08-25 02:06:34 +02:00
Mark Qvist aba8d606dd Cleanup 2026-08-25 01:52:53 +02:00
Mark Qvist 8221f82dc0 Cleanup 2026-08-25 01:52:05 +02:00
Mark Qvist 38e9d1cdd4 Cleanup 2026-08-25 01:45:34 +02:00
Mark Qvist 17e980ff79 Cleanup 2026-08-25 01:44:50 +02:00
Mark Qvist f111709902 Updated througput benchmarker 2026-08-25 01:41:31 +02:00
Mark Qvist 2d2167140d FP cache experiment 2026-08-25 01:41:02 +02:00
Mark Qvist d044db2931 Cache announce signature validation 2026-08-24 22:12:04 +02:00
Mark Qvist 516cb106c1 Updated througput benchmarker 2026-08-24 21:54:11 +02:00
Mark Qvist 7e197542e5 Updated througput bench 2026-08-24 21:54:11 +02:00
Mark Qvist 77f7632584 Avoid extra epoll modifies when EPOLLOUT already set 2026-08-24 21:54:11 +02:00
Mark Qvist 5e013464da Added throughput benchmarker 2026-08-24 21:54:11 +02:00
Mark Qvist b9278ce352 Added throughput benchmarker 2026-08-24 20:42:57 +02:00
Mark Qvist d81421dad3 Avoid additional packet hashing under lock in inbound 2026-08-24 17:58:29 +02:00
Mark Qvist 629e4fde2d Added hash map lookups for pending and active links 2026-08-24 17:45:29 +02:00
Mark Qvist 7311dc8544 Reduced path table lock acquisitions in inbound processing 2026-08-24 17:03:48 +02:00
Mark Qvist 0e070aacf6 Ah well, of course. 2026-08-24 11:29:01 +02:00
Mark Qvist 39899651ee Merge adjustments 2026-08-24 10:56:26 +02:00
Mark Qvist 1034d78828 Merge adjustments 2026-08-24 10:52:47 +02:00
Mark Qvist 9c2f424aaa Merge branch 'live_profiling' into live_profiler_merge 2026-08-24 10:31:13 +02:00
K8 dca5b9639e Limit total profiler captures per tag, not per thread; handle reentrant profilers; make stats time windows be non-overlapping. 2026-08-23 22:39:32 -06:00
K8 40281f91da Decorator for profiling functions. 2026-08-23 21:53:33 -06:00
K8 cf5d6a796e Rework profilers for running indefinitely. 2026-08-23 21:53:33 -06:00
K8 9302415f9e Add live profiling results output to rnstatus. 2026-08-23 21:53:33 -06:00
K8 9da6664976 Move log writing to a dedicated thread. 2026-08-23 21:53:33 -06:00
K8 1694a17a75 Full and configurable logfile rotation. 2026-08-23 21:53:33 -06:00
Mark Qvist 3fdfe93ec7 Don't loop on attached interface packets 2026-08-24 01:26:24 +02:00
Mark Qvist a9538e9fd1 Loglevel 2026-08-24 00:53:35 +02:00
Mark Qvist 956d688e10 Check before cancel incoming 2026-08-24 00:14:54 +02:00
Mark Qvist 1c83e732ad Use optimized IFAC handlers 2026-08-23 23:54:45 +02:00
Mark Qvist 5da0870e2a Optimized HKDF 2026-08-23 23:54:17 +02:00
Mark Qvist 171868c6cb Added IFAC and HKDF tests to test runner 2026-08-23 23:49:59 +02:00
Mark Qvist cfddb9abe6 Added HKDF tests 2026-08-23 23:48:48 +02:00
Mark Qvist 929aba0282 Added IFAC tests 2026-08-23 23:47:34 +02:00
Mark Qvist 7347034f9a Optimized outbound IFAC handling 2026-08-23 22:27:53 +02:00
Mark Qvist aef9e5b416 Extract outbound IFAC handling 2026-08-23 22:05:36 +02:00
Mark Qvist e806ae5837 Optimized inbound IFAC handling 2026-08-23 21:57:22 +02:00
Mark Qvist 602085a1cd Extract inbound IFAC handler 2026-08-23 20:11:29 +02:00
Mark Qvist 84597f3186 Added MTU output to rnstatus 2026-08-23 18:01:24 +02:00
Mark Qvist 88c629e3ad Logging and MTU adjustments 2026-08-23 18:01:13 +02:00
Mark Qvist 2058596dd1 Check before cancel outgoing 2026-08-23 15:32:04 +02:00
Mark Qvist b123a756b0 Added transport implementation name and version to discovery information requirements 2026-08-23 11:56:27 +02:00
Mark Qvist bfab2964b6 Fixed rnstatus including not-yet-blocked IPs in blocked IP list output 2026-08-23 11:30:43 +02:00
Mark Qvist 1bad7f5807 Remove from previous hashlist under transport edge case handling 2026-08-23 11:14:47 +02:00
Mark Qvist 26e3ca4f2b Added shared medium hints to interfaces 2026-08-23 10:46:21 +02:00
Mark Qvist d25ea38c84 Added PPS stats to rnstatus. Don't count local shared instance in traffic totals. 2026-08-22 22:41:03 +02:00
79 changed files with 4386 additions and 948 deletions

No files matched your search

+271 -5
View File
@@ -1,12 +1,278 @@
compiling = False
noticed = False
notice_delay = 0.3
import time
import os
import sys
import time
import threading
from importlib.util import find_spec
if find_spec("pyximport") and find_spec("cython"):
import pyximport; pyxloader = pyximport.install(pyimport=True, language_level=3)[1]
import json
import shutil
import subprocess
from importlib.abc import MetaPathFinder
from importlib.machinery import ExtensionFileLoader, SourceFileLoader
from importlib.machinery import EXTENSION_SUFFIXES
from importlib.util import spec_from_file_location
from distutils.extension import Extension
from pyximport import pyxbuild
COMPILE_DIRECTIVES = { "annotation_typing": False }
_WORKER_SCRIPT = r"""
import sys, os, json
from distutils.extension import Extension
from pyximport import pyxbuild
def main():
tasks_path = sys.argv[1]
with open(tasks_path, "r") as fh: tasks = json.load(fh)
results = []
for task in tasks:
try:
os.makedirs(task["scratch"], exist_ok=True)
extension = Extension(name=task["basename"], sources=[task["source"]])
extension.cython_directives = task["directives"]
so_path = pyxbuild.pyx_to_dll(task["source"], ext=extension, build_in_temp=True, pyxbuild_dir=task["scratch"])
os.makedirs(os.path.dirname(task["target"]), exist_ok=True)
os.replace(so_path, task["target"])
results.append({"fullname": task["fullname"], "ok": True, "error": None})
except Exception as e:
results.append({"fullname": task["fullname"], "ok": False,
"error": "{}: {}".format(type(e).__name__, e)})
with open(tasks_path + ".results", "w") as fh: json.dump(results, fh)
if __name__ == "__main__": main()
"""
def _compile_jobs():
jobs = os.environ.get("CRNS_JOBS")
if jobs: return max(1, int(jobs))
return max(1, min(os.cpu_count() or 1, 16))
class _ImportFinder(MetaPathFinder):
def __init__(self):
self.build_dir = os.path.join(os.path.expanduser("~"), ".pyxbld")
self.mirror_root = os.path.join(self.build_dir, "rnslib")
self.source_root = self._find_source_root()
self.abi_suffix = EXTENSION_SUFFIXES[0]
self.unbuildable = {}
self.unbuildable_path = os.path.join(self.build_dir, "unbuildable.json")
self._verify_mirror_directives()
try:
with open(self.unbuildable_path, "r") as fh: self.unbuildable = json.load(fh)
except Exception: self.unbuildable = {}
def _verify_mirror_directives(self):
# If the compiler directives have changed since the mirror was
# built, the entire mirror is invalidated and rebuilt.
stamp_path = os.path.join(self.build_dir, "rnslib.stamp")
directives = json.dumps(COMPILE_DIRECTIVES, sort_keys=True)
stamp = directives + "\n" + self.abi_suffix
previous = None
try:
with open(stamp_path, "r") as fh: previous = fh.read()
except Exception: pass
if previous != stamp:
shutil.rmtree(self.mirror_root, ignore_errors=True)
os.makedirs(self.mirror_root, exist_ok=True)
try:
os.makedirs(self.build_dir, exist_ok=True)
with open(stamp_path, "w") as fh: fh.write(stamp)
except Exception: pass
def _save_unbuildable(self):
try:
os.makedirs(os.path.dirname(self.unbuildable_path), exist_ok=True)
with open(self.unbuildable_path, "w") as fh: json.dump(self.unbuildable, fh, indent=1)
except Exception: pass
def _mark_unbuildable(self, fullname, source):
try:
self.unbuildable[fullname] = int(os.path.getmtime(source))
self._save_unbuildable()
except Exception: pass
def _unmark_buildable(self, fullname):
if fullname in self.unbuildable:
del self.unbuildable[fullname]
self._save_unbuildable()
def _is_unbuildable(self, fullname, source):
if fullname not in self.unbuildable: return False
try:
if int(os.path.getmtime(source)) == self.unbuildable[fullname]: return True
except Exception: pass
self.unbuildable.pop(fullname, None)
return False
def _find_source_root(self):
here = os.path.dirname(os.path.abspath(__file__))
candidate = os.path.abspath(os.path.join(here, "..", "RNS", "__init__.py"))
if os.path.exists(candidate): return os.path.dirname(os.path.dirname(candidate))
for entry in [os.getcwd()] + list(sys.path):
if not entry: continue
candidate = os.path.join(entry, "RNS", "__init__.py")
if os.path.exists(candidate): return os.path.dirname(candidate)
raise RuntimeError("CRNS could not locate the RNS source tree")
def _all_source_modules(self):
rns_root = os.path.join(self.source_root, "RNS")
for root, dirs, files in os.walk(rns_root):
dirs[:] = [d for d in dirs if d not in ("__pycache__", "i2plib")]
rel = os.path.relpath(root, self.source_root).replace(os.sep, ".")
for fn in sorted(files):
if not fn.endswith(".py"): continue
if fn == "__init__.py": fullname = rel
else: fullname = rel + "." + fn[:-3]
yield fullname
def _mirror_target(self, fullname, is_package):
rel = fullname.split(".")
basename = rel[-1]
if is_package: return os.path.join(self.mirror_root, *rel, "__init__" + self.abi_suffix)
return os.path.join(self.mirror_root, *rel[:-1], basename + self.abi_suffix)
def _source(self, fullname):
rel = fullname.split(".")
package_source = os.path.join(self.source_root, *rel, "__init__.py")
if os.path.exists(package_source): return package_source, True
module_source = os.path.join(self.source_root, *rel) + ".py"
if os.path.exists(module_source): return module_source, False
return None, None
def _compile(self, fullname, source):
basename = fullname.rsplit(".", 1)[-1]
extension = Extension(name=basename, sources=[source])
extension.cython_directives = COMPILE_DIRECTIVES
so_path = pyxbuild.pyx_to_dll(source, ext=extension, build_in_temp=True, pyxbuild_dir=self.build_dir)
abi_suffix = os.path.basename(so_path)[len(basename):]
return so_path, abi_suffix
def _is_current(self, fullname, source, is_package):
target = self._mirror_target(fullname, is_package)
if not os.path.exists(target): return False
try: return os.path.getmtime(target) >= os.path.getmtime(source)
except Exception: return False
def _ensure_compiled(self, fullname, source, is_package):
target = self._mirror_target(fullname, is_package)
if os.path.exists(target) and os.path.getmtime(target) >= os.path.getmtime(source): return target
so_path, abi_suffix = self._compile(fullname, source)
os.makedirs(os.path.dirname(target), exist_ok=True)
os.replace(so_path, target)
return target
def precompile(self):
if not os.path.isdir(self.mirror_root):
os.makedirs(self.mirror_root, exist_ok=True)
pending = []
for fullname in self._all_source_modules():
source, is_package = self._source(fullname)
if source is None:
continue
if self._is_current(fullname, source, is_package):
self._unmark_buildable(fullname)
continue
if self._is_unbuildable(fullname, source):
continue
pending.append((fullname, source, is_package))
if not pending: return
jobs = min(_compile_jobs(), len(pending))
if jobs > 1:
# Round-robin assignment spreads the large modules evenly
# across workers.
chunks = [[] for _ in range(jobs)]
for i, item in enumerate(pending): chunks[i % jobs].append(item)
workers_dir = os.path.join(self.build_dir, "workers")
os.makedirs(workers_dir, exist_ok=True)
procs = []
for w in range(jobs):
tasks = []
for fullname, source, is_package in chunks[w]:
tasks.append({ "fullname": fullname,
"basename": fullname.rsplit(".", 1)[-1],
"source": source,
"target": self._mirror_target(fullname, is_package),
"scratch": os.path.join(workers_dir, "w{}".format(w)),
"directives": COMPILE_DIRECTIVES })
task_path = os.path.join(workers_dir, "tasks{}.json".format(w))
with open(task_path, "w") as fh: json.dump(tasks, fh)
procs.append((w, task_path, subprocess.Popen([sys.executable, "-c", _WORKER_SCRIPT, task_path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)))
for w, task_path, proc in procs:
stdout, stderr = proc.communicate()
if proc.returncode != 0:
for fullname, _, _ in chunks[w]:
source, _ = self._source(fullname)
self._mark_unbuildable(fullname, source)
print(f"CRNS: compile worker failed for {fullname}, using interpreted module", file=sys.stderr)
if stderr:
tail = stderr.decode(errors="replace").strip().splitlines()[-5:]
print("CRNS: worker output:\n" + "\n".join(tail), file=sys.stderr)
continue
results = {}
try:
with open(task_path + ".results", "r") as fh:
for entry in json.load(fh): results[entry["fullname"]] = entry
except Exception: results = {}
for fullname, _, _ in chunks[w]:
entry = results.get(fullname)
if entry is not None and entry.get("ok"): self._unmark_buildable(fullname)
else:
error = "" if entry is None else entry.get("error", "")
source, _ = self._source(fullname)
self._mark_unbuildable(fullname, source)
print(f"Could not compile {fullname}, using interpreted module: {error}", file=sys.stderr)
else:
for fullname, source, is_package in pending:
try:
self._ensure_compiled(fullname, source, is_package)
self._unmark_buildable(fullname)
except Exception as e:
self._mark_unbuildable(fullname, source)
print(f"Could not compile {fullname}, using interpreted module: {e}", file=sys.stderr)
def _spec(self, fullname, source, is_package, compile_attempted):
if fullname == "RNS.vendor.i2plib" or fullname.startswith("RNS.vendor.i2plib."):
rel = fullname.split(".")
locations = [os.path.join(self.source_root, *rel)] if is_package else None
return spec_from_file_location(fullname, source, loader=SourceFileLoader(fullname, source), submodule_search_locations=locations)
if compile_attempted:
try:
target = self._ensure_compiled(fullname, source, is_package)
self._unmark_buildable(fullname)
if is_package: locations = [os.path.dirname(target)]
else: locations = None
return spec_from_file_location(fullname, target, loader=ExtensionFileLoader(fullname, target),
submodule_search_locations=locations)
except Exception as e:
self._mark_unbuildable(fullname, source)
print(f"Could not compile {fullname}, using interpreted module: {e}", file=sys.stderr)
rel = fullname.split(".")
locations = [os.path.join(self.source_root, *rel)] if is_package else None
return spec_from_file_location(fullname, source,loader=SourceFileLoader(fullname, source),submodule_search_locations=locations)
def find_spec(self, fullname, path, target=None):
if not isinstance(fullname, str): return None
if not (fullname == "RNS" or fullname.startswith("RNS.")): return None
source, is_package = self._source(fullname)
if source is None: return None
return self._spec(fullname, source, is_package, compile_attempted=not self._is_unbuildable(fullname, source))
_importfinder = _ImportFinder()
sys.meta_path.insert(0, _importfinder)
def notice_job():
global noticed
@@ -14,13 +280,13 @@ def notice_job():
while compiling:
if time.time() > started+notice_delay and compiling:
noticed = True
print("Compiling RNS object code... ", end="")
print("Compiling RNS object code...")
sys.stdout.flush()
break
time.sleep(0.1)
compiling = True
threading.Thread(target=notice_job, daemon=True).start()
_importfinder.precompile()
import RNS; compiling = False
if noticed: print("Done."); sys.stdout.flush()
if noticed: print("Compilation done"); sys.stdout.flush()
+84 -28
View File
@@ -1,3 +1,87 @@
### 2026-08-28: RNS 1.5.2
This maintenance release fixes a regression in resource transfers that was introduced in 1.5.1, an `I2PInterface` bug, and sets dataplane control parameters to default values that are actually sensible. If you installed `1.5.1`, it's update time again, baby.
**Changes**
- Tuned dataplane control parameters
- Added example for blocking unidentified page node peers to `rngit` default config
- Fixed regression in resource transfers causing some `rngit` file downloads to fail
- Fixed keepalive frames being passed to transport core on `I2PInterface`
**Verified Retrieval**
You can retrieve and verify this release over Reticulum using the built-in `rngit release` utility. To retrieve only the installation `.whl` package, and the release manifest for future updates, you can use:
```sh
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/reticulum fetch "latest:rns-*.whl" --signer bc7291552be7a58f361522990465165c
```
To download all artifacts, including the documentation and source archive, you can use the following command:
```sh
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/reticulum fetch latest:all --signer bc7291552be7a58f361522990465165c
```
**Release Signatures**
Release artifacts include a signed `rsm` release manifest and `rsg` signature files that can be validated against the RNS release signing identity `<bc7291552be7a58f361522990465165c>` using `rngit` or `rnid`. To perform an offline verification of all release artifacts using a manifest:
```sh
rngit release rns_*.rsm verify --signer bc7291552be7a58f361522990465165c
```
To verify release artifacts using individual `rsg` files, while also verifying the manifest itself, download the `rsm` and `rsg` signatures, make sure they are in the same folder as the release artifact, and run `rnid` signature verification with the release identity as the required signer:
```sh
rnid -i bc7291552be7a58f361522990465165c -V rns_*.rsm *.rsg
```
The `rnid` utility will then verify the signatures, and display whether they are valid. If the signature cannot be verified, the release has been tampered with and should be discarded.
### 2026-08-28: RNS 1.5.1
This release focuses on dataplane control, memory bounding and transport throughput, with adaptive ingress and egress control for interfaces, a new (and very efficient) zero-copy coalescing transmit buffer, an optimized HDLC deframer, and a range of other improvements to the inbound packet processing paths. It also introduces support for live profiling, and various new diagnostics output in `rnstatus`, along with a number of bug fixes and general improvements.
**Changes**
- Added adaptive dataplane egress control
- Added adaptive dataplane ingress control
- Added zero-copy coalescing transmit buffers to interfaces using the `BackboneInterface` backend
- Added early protocol violation checks for invalid frames
- Added transport implementation name and version to discovery information requirements
- Added full live profiling to the built-in `Profiler` primitive, by **K8**
- Added the `@RNS.Profiler.profile` decorator, by **K8**
- Added support for indefinitely running, reentrant profilers with bounded capture, by **K8**
- Added live profiling results output to `rnstatus`, by **K8**
- Added PPS statistics to `rnstatus`
- Added interface MTU display to `rnstatus`
- Added interface TX drop statistics to `rnstatus`
- Added interface TX buffer size output to `rnstatus`
- Added throughput benchmarker to the test suite
- Added support for natively compiled module builds, and the ability to load compiled modules when available
- Added module compilation status reporting from in-wheel build information
- Added parity tests for HDLC, IFAC and HKDF against the legacy implementations
- Added shared medium hints to interfaces
- Improved memory and CPU consumption under high traffic loads
- Improved traffic class handling
- Optimized HKDF to ~5.7x performance, if this worries you, **good**; then see the full parity and standard vector test suite and read the code
- Optimized inbound and outbound IFAC handling to ~90x performance on large frames
- Optimized inbound packet processing by reducing lock acquisitions and path table contention
- Optimized lookups for pending and active links using hash maps for lookup operations
- Optimized announce validation by caching signature validation results, significantly lowering announce storm CPU load
- Optimized the HDLC deframer
- Reduced redundant packet hashing in inbound processing
- Tuned default inbound queue lengths and announce queuing
- Tuned automatic interface MTU configuration
- Fixed `Resource` transfers failing when initialized from stream-based data sources that fell outside `MAX_EFFICIENT_SIZE`
- Fixed an invalid prefix stripping bug in the `rngit` page server (`.something` files not viewable)
- Fixed RSSI/SNR reporting regression
- Fixed keepalive handling on non-epoll backends
- Fixed a bug in `rngit` page navigation content initialization order
- Fixed the `rngit` page node not being able to serve in-tree downloads for large files
- Fixed `rnstatus` blocked IP listing including IPs that were actually not yet blocked
- Fixed `rnstatus` traffic totals counting the local shared instance inter-app transit in totals
- Fixed various minor bugs in `rnsh`, `rnir`, identity handling
- Fixed a latent bug in the AES module, where an exception would not resolve it's exception description correctly, and instead raise another exception.
- Removed dead Python 2 code from `umsgpack`
### 2026-08-22: RNS 1.5.0
This release significantly improves the core Transport handling of RNS, with a priority-based ingress queue backend, substantially improved efficiency of both data and management traffic handling, more efficient ingress/egress limiting, and a long list of other improvements and bugfixes.
@@ -45,34 +129,6 @@ This release significantly improves the core Transport handling of RNS, with a p
- Fixed speedtest example aborting transfers on stale link status
- Updated documentation, including manual sections on queue tuning and interface discovery options
**Verified Retrieval**
You can retrieve and verify this release over Reticulum using the built-in `rngit release` utility. To retrieve only the installation `.whl` package, and the release manifest for future updates, you can use:
```sh
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/reticulum fetch "latest:rns-*.whl" --signer bc7291552be7a58f361522990465165c
```
To download all artifacts, including the documentation and source archive, you can use the following command:
```sh
rngit release rns://7649a50d84610232d1416b41d2896aff/reticulum/reticulum fetch latest:all --signer bc7291552be7a58f361522990465165c
```
**Release Signatures**
Release artifacts include a signed `rsm` release manifest and `rsg` signature files that can be validated against the RNS release signing identity `<bc7291552be7a58f361522990465165c>` using `rngit` or `rnid`. To perform an offline verification of all release artifacts using a manifest:
```sh
rngit release rns_*.rsm verify --signer bc7291552be7a58f361522990465165c
```
To verify release artifacts using individual `rsg` files, while also verifying the manifest itself, download the `rsm` and `rsg` signatures, make sure they are in the same folder as the release artifact, and run `rnid` signature verification with the release identity as the required signer:
```sh
rnid -i bc7291552be7a58f361522990465165c -V rns_*.rsm *.rsg
```
The `rnid` utility will then verify the signatures, and display whether they are valid. If the signature cannot be verified, the release has been tampered with and should be discarded.
### 2026-07-26: RNS 1.4.2
This maintenance release fixes bugs in blackholed identity filtering and recursive path request handling for RNode interfaces.
+18
View File
@@ -21,6 +21,19 @@ clean:
@-rm -rf ./tests/__pycache__
@-rm -rf ./tests/rnsconfig/storage
@-rm -rf ./*.egg-info
@-rm -rf ./RNS/*.c
@-rm -rf ./RNS/Cryptography/*.c
@-rm -rf ./RNS/Cryptography/aes/*.c
@-rm -rf ./RNS/Cryptography/pure25519/*.c
@-rm -rf ./RNS/Interfaces/*.c
@-rm -rf ./RNS/Interfaces/util/*.c
@-rm -rf ./RNS/Interfaces/Android/*.c
@-rm -rf ./RNS/Utilities/*.c
@-rm -rf ./RNS/Utilities/rngit/*.c
@-rm -rf ./RNS/Utilities/rnsh/*.c
@-rm -rf ./RNS/vendor/*.c
@-rm -rf ./RNS/vendor/i2plib/*.c
@-rm -rf
@make -C docs clean
@echo Done
@@ -50,6 +63,9 @@ build_wheel:
build_pure_wheel:
python3 setup.py bdist_wheel --pure
build_native:
python3 setup.py bdist_wheel --native
documentation:
make -C docs html markdown
@@ -65,6 +81,8 @@ release: test remove_symlinks build_sdist build_wheel build_pure_wheel documenta
debug: remove_symlinks build_wheel build_pure_wheel create_symlinks
native: remove_symlinks build_native create_symlinks
local: release sign
sign:
+4 -4
View File
@@ -43,7 +43,7 @@ elif cp.PROVIDER == cp.PROVIDER_PYCA:
class AES_128_CBC:
@staticmethod
def encrypt(plaintext, key, iv):
if len(key) != 16: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if len(key) != 16: raise ValueError(f"Invalid key length {len(key)*8} for AES_128_CBC")
if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES128(key)
return cipher.encrypt(plaintext, iv)
@@ -60,7 +60,7 @@ class AES_128_CBC:
@staticmethod
def decrypt(ciphertext, key, iv):
if len(key) != 16: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if len(key) != 16: raise ValueError(f"Invalid key length {len(key)*8} for AES_128_CBC")
if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES128(key)
return cipher.decrypt(ciphertext, iv)
@@ -78,7 +78,7 @@ class AES_128_CBC:
class AES_256_CBC:
@staticmethod
def encrypt(plaintext, key, iv):
if len(key) != 32: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if len(key) != 32: raise ValueError(f"Invalid key length {len(key)*8} for AES_256_CBC")
if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES256(key)
return cipher.encrypt_cbc(plaintext, iv)
@@ -95,7 +95,7 @@ class AES_256_CBC:
@staticmethod
def decrypt(ciphertext, key, iv):
if len(key) != 32: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if len(key) != 32: raise ValueError(f"Invalid key length {len(key)*8} for AES_256_CBC")
if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES256(key)
return cipher.decrypt_cbc(ciphertext, iv)
+51
View File
@@ -32,8 +32,59 @@ import hashlib
from math import ceil
from RNS.Cryptography import HMAC
# Precomputed byte-permutation tables used to key the inner
# and outer hashing states of the HMAC construction
trans_5C = bytes((x ^ 0x5C) for x in range(256))
trans_36 = bytes((x ^ 0x36) for x in range(256))
# Precomputed HKDF counter bytes
_counters = [bytes([(i + 1) % 0x100]) for i in range(0x100)]
def hkdf(length=None, derive_from=None, salt=None, context=None):
hash_len = 32
hash_block_size = 64
if length == None or length < 1: raise ValueError("Invalid output key length")
if derive_from == None or derive_from == "": raise ValueError("Cannot derive key from empty input material")
if salt == None or len(salt) == 0: salt = bytes([0] * hash_len)
if context == None: context = b""
pseudorandom_key = HMAC.new(salt, derive_from).digest()
# The pseudorandom key is always a 32-byte SHA-256 digest, so the
# HMAC key schedule below never needs the long-key hashing branch.
key = pseudorandom_key.ljust(hash_block_size, b"\x00")
# Precompute the keyed inner and outer hashing states of the
# HMAC construction once. Each expansion block then only requires
# two cheap hash-object copies instead of constructing a complete
# HMAC object per 32 bytes of output. This is possible since the
# PRK is **always** 32-byte SHA-256 HMAC output.
inner_state = hashlib.sha256(key.translate(trans_36))
outer_state = hashlib.sha256(key.translate(trans_5C))
# Expand
has_context = len(context) > 0
block = b""
derived = bytearray()
for i in range(ceil(length / hash_len)):
inner = inner_state.copy()
inner.update(block)
if has_context: inner.update(context)
inner.update(_counters[i & 0xFF])
outer = outer_state.copy()
outer.update(inner.digest())
block = outer.digest()
derived += block
return bytes(derived[:length])
def hkdf_legacy(length=None, derive_from=None, salt=None, context=None):
hash_len = 32
def hmac_sha256(key, data):
return HMAC.new(key, data).digest()
+4 -2
View File
@@ -52,5 +52,7 @@ elif cp.PROVIDER == cp.PROVIDER_PYCA:
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules
__all__ = list(set([os.path.basename(f).replace(".pyc", "").replace(".py", "") for f in modules if not (f.endswith("__init__.py") or f.endswith("__init__.pyc"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+10
View File
@@ -10,8 +10,16 @@ from threading import Lock
from .vendor import umsgpack as msgpack
from collections import deque
# Discoverable interfaces must include a short,
# unique implementation-specific identifier and
# version tag in announced discovery information.
IMPLEMENTATION_NAME = "RNS"
from RNS._version import __version__ as RNS_VERSION
NAME = 0xFF
TRANSPORT_ID = 0xFE
TRANSPORT_IMPL = 0xFD
TRANSPORT_VERS = 0xFC
INTERFACE_TYPE = 0x00
TRANSPORT = 0x01
REACHABLE_ON = 0x02
@@ -132,6 +140,8 @@ class InterfaceAnnouncer():
info = {INTERFACE_TYPE: interface_type,
TRANSPORT: RNS.Reticulum.transport_enabled(),
TRANSPORT_ID: RNS.Transport.identity.hash,
TRANSPORT_IMPL: IMPLEMENTATION_NAME,
TRANSPORT_VERS: RNS_VERSION,
NAME: self.sanitize(interface.discovery_name),
LATITUDE: interface.discovery_latitude,
LONGITUDE: interface.discovery_longitude,
+9 -6
View File
@@ -201,7 +201,7 @@ class Identity:
except Exception as e:
RNS.log(f"Error while serializing and writing known destinations: {e}", RNS.LOG_ERROR)
try: os.unlink(temp_file)
except Exception as e: RNS.log(f"Could not clean up temporary file {temp_file}: {e}", RNS.LOG_WARNING)
except Exception as exc: RNS.log(f"Could not clean up temporary file {temp_file}: {exc}", RNS.LOG_WARNING)
raise e
RNS.log(f"Saved known destinations to storage in {RNS.prettyshorttime(time.time()-save_start)}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
@@ -556,7 +556,8 @@ class Identity:
if signal_blackholed: return "blackholed"
else: return False
if announced_identity.pub != None and announced_identity.validate(signature, signed_data):
if announced_identity.pub != None and (packet.announce_signature_validated or announced_identity.validate(signature, signed_data)):
packet.announce_signature_validated = True
if only_validate_signature:
del announced_identity
return True
@@ -758,9 +759,7 @@ class Identity:
return True
except Exception as e:
raise e
RNS.log("Failed to load identity key", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Failed to load identity key, the contained exception was: {e}", RNS.LOG_ERROR)
return False
def load_public_key(self, pub_bytes):
@@ -778,8 +777,12 @@ class Identity:
self.sig_pub = Ed25519PublicKey.from_public_bytes(self.sig_pub_bytes)
self.update_hashes()
return True
except Exception as e:
RNS.log("Error while loading public key, the contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while loading public key, the contained exception was: {e}", RNS.LOG_ERROR)
return False
def update_hashes(self):
self.hash = Identity.truncated_hash(self.get_public_key())
+1
View File
@@ -128,6 +128,7 @@ class AX25KISSInterface(Interface):
self.packet_queue = []
self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False
self.flow_control_timeout = 5
self.flow_control_locked = time.time()
+1
View File
@@ -131,6 +131,7 @@ class KISSInterface(Interface):
self.packet_queue = []
self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False
self.flow_control_timeout = 5
self.flow_control_locked = time.time()
+4 -6
View File
@@ -282,12 +282,9 @@ class RNodeInterface(Interface):
if (port != None or device_serial != None) and (enable_bluetooth or disable_bluetooth or pairing_mode):
serial = None
bluetooth_state = None
if pairing_mode:
bluetooth_state = 0x01
elif enable_bluetooth:
bluetooth_state = 0x01
elif disable_bluetooth:
bluetooth_state = 0x00
if pairing_mode: bluetooth_state = 0x01
elif enable_bluetooth: bluetooth_state = 0x01
elif disable_bluetooth: bluetooth_state = 0x00
if port != None:
RNS.log("Opening serial port "+port+"...")
@@ -518,6 +515,7 @@ class RNodeInterface(Interface):
self.packet_queue = []
self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False
self.announce_rate_target = None
self.last_port_io = 0
@@ -95,6 +95,7 @@ class SerialInterface(Interface):
raise ValueError("No port specified for serial interface")
self.HW_MTU = 564
self.shared_medium = True
self.pyserial = serial
self.serial = None
+4 -2
View File
@@ -33,5 +33,7 @@ import glob
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules
__all__ = list(set([os.path.basename(f).replace(".pyc", "").replace(".py", "") for f in modules if not (f.endswith("__init__.py") or f.endswith("__init__.pyc"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+274 -66
View File
@@ -29,6 +29,8 @@
# SOFTWARE.
from RNS.Interfaces.Interface import Interface
from RNS.Interfaces.util.TransmitBuffer import TransmitBuffer
from RNS.Interfaces.util.HDLC import HDLC, ReceiveBuffer
import threading
import socket
import select
@@ -37,22 +39,11 @@ import sys
import os
import RNS
class HDLC():
FLAG = 0x7E
ESC = 0x7D
ESC_MASK = 0x20
@staticmethod
def escape(data):
data = data.replace(bytes([HDLC.ESC]), bytes([HDLC.ESC, HDLC.ESC^HDLC.ESC_MASK]))
data = data.replace(bytes([HDLC.FLAG]), bytes([HDLC.ESC, HDLC.FLAG^HDLC.ESC_MASK]))
return data
class BackboneInterface(Interface):
HW_MTU = 1048576
BITRATE_GUESS = 1_000_000_000
DEFAULT_IFAC_SIZE = 16
AUTOCONFIGURE_MTU = True
HW_MTU = 1048576
BITRATE_GUESS = 100_000_000
DEFAULT_IFAC_SIZE = 16
AUTOCONFIGURE_MTU = True
BLOCK_FAST_FLAPPING = True
FAST_FLAP_THRESHOLD = 20
@@ -61,12 +52,34 @@ class BackboneInterface(Interface):
fast_flapping_lock = threading.Lock()
fast_flapping = {}
DP_IC_HIGH_WM_PCT = 90
DP_IC_MID_WM_PCT = 68
DP_IC_LOW_WM_PCT = 10
DP_IC_INTERVAL = 0.250
DP_IC_TRIGGER = 1.5
DP_IC_RCVBUF = 32768
DP_IC_IF_HEADROOM = 32
DP_IC_PENALTY = 1.5
DP_EC_INTERVAL = 1.0
DP_EC_MID_WM = 128*1024
DP_EC_HIGH_WM = 4*1024*1024
DP_EC_STALL_TICKS = 3
DP_EC_MAX_ETA = 10.0
DP_EC_RELEASE_ETA = 5.0 # Gate release hysterisis
DP_EC_DEAD_TIME = 12.0
epoll = None
listener_filenos = {}
spawned_interface_filenos = {}
epoll = None
_job_active = False
_job_lock = threading.Lock()
_job_active = False
_ic_job_active = False
_ec_job_active = False
_job_lock = threading.Lock()
_ec_job_lock = threading.Lock()
_ic_job_lock = threading.Lock()
_dp_ic_lock = threading.Lock()
_dp_ic_snapshot = 0
@staticmethod
def get_address_for_if(name, bind_port, prefer_ipv6=False):
@@ -247,7 +260,9 @@ class BackboneInterface(Interface):
@staticmethod
def start():
if not BackboneInterface._job_active: threading.Thread(target=BackboneInterface.__job, daemon=True).start()
if not BackboneInterface._job_active: threading.Thread(target=BackboneInterface.__job, daemon=True).start()
if not BackboneInterface._ic_job_active: threading.Thread(target=BackboneInterface.__dp_ic_job, daemon=True).start()
if not BackboneInterface._ec_job_active: threading.Thread(target=BackboneInterface.__dp_ec_job, daemon=True).start()
@staticmethod
def ensure_epoll():
@@ -288,7 +303,7 @@ class BackboneInterface(Interface):
RNS.log(f"Attempt to register invalid file descriptor {fileno}", RNS.LOG_WARNING)
return
try: BackboneInterface.epoll.register(fileno, select.EPOLLIN)
try: BackboneInterface.epoll.register(fileno, select.EPOLLIN | select.EPOLLHUP)
except Exception as e:
RNS.log(f"An error occurred while registering EPOLLIN for file descriptor {fileno}: {e}", RNS.LOG_WARNING)
@@ -319,13 +334,223 @@ class BackboneInterface(Interface):
if interface.socket:
fileno = interface.socket.fileno()
if fileno in BackboneInterface.spawned_interface_filenos:
try: BackboneInterface.epoll.modify(fileno, select.EPOLLIN | select.EPOLLOUT)
try:
events = select.EPOLLOUT | select.EPOLLHUP
if not interface.dp_ingress_gated: events |= select.EPOLLIN
BackboneInterface.epoll.modify(fileno, events)
except Exception as e:
if str(e).endswith("No such file or directory"): pass
elif str(e).endswith("Bad file descriptor"): pass
else: RNS.log(f"Error occurred on {interface} while modifying socket EPOLL state: {e}", RNS.LOG_WARNING)
raise e
@staticmethod
def __throttle_ingress(interface, hold=None):
if interface.dp_ingress_gated: return False
try:
fileno = interface.socket.fileno()
if fileno in BackboneInterface.spawned_interface_filenos:
interface.dp_ingress_gated = True
interface.dp_ingress_tcount += 1
events = select.EPOLLHUP
if interface.transmit_buffer.sendable > 0: events |= select.EPOLLOUT
BackboneInterface.epoll.modify(fileno, events)
if hold: interface.dp_ingress_hold = time.time() + hold
RNS.log(f"Ingress throttled on {interface}", RNS.LOG_NOTICE) if RNS.sl(RNS.LOG_NOTICE) else None
return True
except Exception as e: RNS.log(f"Error throttling {interface}: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return False
@staticmethod
def __release_ingress(interface):
if not interface.dp_ingress_gated: return False
try:
fileno = interface.socket.fileno()
if fileno in BackboneInterface.spawned_interface_filenos:
events = select.EPOLLIN | select.EPOLLHUP
if interface.transmit_buffer.sendable > 0: events |= select.EPOLLOUT
BackboneInterface.epoll.modify(fileno, events)
interface.dp_ingress_gated = False
RNS.log(f"Released ingress throttle on {interface}", RNS.LOG_NOTICE) if RNS.sl(RNS.LOG_NOTICE) else None
return True
except Exception as e: RNS.log(f"Error releasing throttle on {interface}: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return False
@staticmethod
def _throttle_immediate(q_depth):
with BackboneInterface._dp_ic_lock:
st = time.time()
interfaces = list(BackboneInterface.spawned_interface_filenos.values())
producers = [iface for iface in interfaces if iface.dp_ingress_packets > 0]
if producers:
producers.sort(key=lambda p: p.dp_ingress_packets, reverse=True)
selected = producers[0]
now = time.time()
span = now - BackboneInterface._dp_ic_snapshot
total = sum(iface.dp_ingress_packets for iface in producers)
avail = sum(iface.dp_ingress_bytes for iface in interfaces) / span
share = selected.dp_ingress_packets / total
rate = selected.dp_ingress_packets / span
speed = selected.dp_ingress_bytes / span
data = selected.dp_ingress_bytes
pkts = selected.dp_ingress_packets
alloc = 1/((max(len(interfaces), BackboneInterface.DP_IC_IF_HEADROOM))*BackboneInterface.DP_IC_PENALTY)
hold = (avail/(avail*alloc))*span
if BackboneInterface.__throttle_ingress(selected, hold=hold):
taken = time.time()-st
if RNS.sl(RNS.LOG_DEBUG):
RNS.log(f"Throttled producer with {pkts} packets at {RNS.prettysize(rate, suffix='pps')} / {RNS.prettyspeed(speed*8)}, {round(share*100.0, 2)}% ingress share", RNS.LOG_DEBUG)
RNS.log(f"Available ingress budget {RNS.prettyspeed(avail*8)}, hard-allocated {round(alloc*100.0, 2)}% ({RNS.prettyspeed(avail*alloc*8)}), handled in {RNS.prettyshorttime(taken, compact=True, tight=True)}", RNS.LOG_DEBUG)
RNS.log(f"Holding for {RNS.prettyshorttime(hold, compact=True, tight=True)}, throttling handled in {RNS.prettyshorttime(taken, compact=True, tight=True)} at depth {q_depth}", RNS.LOG_DEBUG)
@staticmethod
def _dp_ec_evaluate(interface, now):
tb = interface.transmit_buffer
drained = tb._tx_sent - interface._dp_ec_prev_sent
interface._dp_ec_prev_sent = tb._tx_sent
sendable = tb.sendable
buffered = len(tb)
if buffered == 0 or sendable == 0:
interface._dp_ec_zero_ticks = 0
interface._dp_ec_last_drain = now
interface.tx_stalled = False
return False
if now - interface._dp_ec_last_drain >= BackboneInterface.DP_EC_DEAD_TIME:
RNS.log(f"No egress control drain progress for {RNS.prettyshorttime(BackboneInterface.DP_EC_DEAD_TIME, compact=True)} on {interface}, tearing down", RNS.LOG_NOTICE)
try:
if hasattr(interface, "socket") and interface.socket:
fileno = interface.socket.fileno()
BackboneInterface.deregister_fileno(fileno)
if fileno in BackboneInterface.spawned_interface_filenos: BackboneInterface.spawned_interface_filenos.pop(fileno)
try: interface.socket.close()
except Exception as e: RNS.log(f"Egress control could not close socket for {interface}: {e}", RNS.LOG_ERROR)
except Exception as e: RNS.log(f"Egress control cleanup error for {interface}: {e}", RNS.LOG_ERROR)
interface.receive(b"")
return True
if drained > 0:
interface._dp_ec_last_drain = now
interface._dp_ec_zero_ticks = 0
drain_rate = drained / BackboneInterface.DP_EC_INTERVAL
clear_eta = buffered / drain_rate if drain_rate > 0 else float("inf")
if buffered > BackboneInterface.DP_EC_MID_WM and clear_eta > BackboneInterface.DP_EC_MAX_ETA:
if not interface.tx_stalled: RNS.log(f"Egress control drain ETA of {RNS.prettyshorttime(clear_eta, compact=True)} exceeds maximum on {interface}, gating outbound", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
interface.tx_stalled = True
elif clear_eta < BackboneInterface.DP_EC_RELEASE_ETA or buffered <= BackboneInterface.DP_EC_MID_WM:
if interface.tx_stalled: RNS.log(f"Egress control drain recovered on {interface}, resuming outbound", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
interface.tx_stalled = False
else:
# No drain progress on this tick
if buffered > BackboneInterface.DP_EC_MID_WM:
interface._dp_ec_zero_ticks += 1
if interface._dp_ec_zero_ticks >= BackboneInterface.DP_EC_STALL_TICKS:
if not interface.tx_stalled: RNS.log(f"No egress control drain progress on {interface}, gating outbound", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
interface.tx_stalled = True
else:
interface._dp_ec_zero_ticks = 0
interface.tx_stalled = False
return False
@staticmethod
def __dp_ec_job():
with BackboneInterface._ec_job_lock:
if BackboneInterface._ec_job_active: return
else:
BackboneInterface._ec_job_active = True
RNS.log(f"Started dataplane egress control", RNS.LOG_DEBUG)
try:
while True:
time.sleep(BackboneInterface.DP_EC_INTERVAL)
now = time.time()
try: interfaces = list(BackboneInterface.spawned_interface_filenos.values())
except RuntimeError as e:
RNS.log(f"Deferring egress control evaluation due to error: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
continue
for interface in interfaces:
if interface.detached: continue
if isinstance(interface, RNS.Interfaces.LocalInterface.LocalClientInterface): continue
BackboneInterface._dp_ec_evaluate(interface, now)
except Exception as e:
RNS.log(f"BackboneInterface egress control error: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
@staticmethod
def __dp_ic_job():
with BackboneInterface._ic_job_lock:
if BackboneInterface._ic_job_active: return
else:
BackboneInterface._ic_job_active = True
RNS.log(f"Started dataplane ingress control: High/mid/low water marks are {BackboneInterface.DP_IC_HIGH_WM}/{BackboneInterface.DP_IC_MID_WM}/{BackboneInterface.DP_IC_LOW_WM} packets", RNS.LOG_DEBUG)
try:
while True:
time.sleep(BackboneInterface.DP_IC_INTERVAL)
try:
if RNS.Transport.inbound_queues != None: q_depth = RNS.Transport.inbound_queues.qsize(RNS.Transport.TC_DATA)
else: continue
except Exception: continue
with BackboneInterface._dp_ic_lock:
st = time.time()
interfaces = list(BackboneInterface.spawned_interface_filenos.values())
if q_depth > BackboneInterface.DP_IC_MID_WM:
producers = [iface for iface in interfaces if iface.dp_ingress_packets > 0 and not isinstance(interface, RNS.Interfaces.LocalInterface.LocalClientInterface)]
if producers:
producers.sort(key=lambda p: p.dp_ingress_packets, reverse=True)
selected = producers[0]
now = time.time()
span = max(now - BackboneInterface._dp_ic_snapshot, 0.001)
total = sum(iface.dp_ingress_packets for iface in producers)
avail = sum(iface.dp_ingress_bytes for iface in interfaces) / span
mean = total / max(len(producers), 2)
share = selected.dp_ingress_packets / total
rate = selected.dp_ingress_packets / span
speed = selected.dp_ingress_bytes / span
data = selected.dp_ingress_bytes
pkts = selected.dp_ingress_packets
alloc = 1/((max(len(interfaces), BackboneInterface.DP_IC_IF_HEADROOM))*BackboneInterface.DP_IC_PENALTY)
hold = (avail/max(avail*alloc, 1))*span
if BackboneInterface.__throttle_ingress(selected, hold=hold):
taken = time.time()-st
if RNS.sl(RNS.LOG_DEBUG):
RNS.log(f"Throttled producer with {pkts} packets at {RNS.prettysize(rate, suffix='pps')} / {RNS.prettyspeed(speed*8)}, {round(share*100.0, 2)}% ingress share", RNS.LOG_DEBUG)
RNS.log(f"Available ingress budget {RNS.prettyspeed(avail*8)}, hard-allocated {round(alloc*100.0, 2)}% ({RNS.prettyspeed(avail*alloc*8)}), handled in {RNS.prettyshorttime(taken, compact=True, tight=True)}", RNS.LOG_DEBUG)
RNS.log(f"Holding for {RNS.prettyshorttime(hold, compact=True, tight=True)}, throttling handled in {RNS.prettyshorttime(taken, compact=True, tight=True)}", RNS.LOG_DEBUG)
elif q_depth < BackboneInterface.DP_IC_LOW_WM:
now = time.time()
for iface in interfaces:
if iface.dp_ingress_gated:
if iface.dp_ingress_hold and now < iface.dp_ingress_hold: continue
BackboneInterface.__release_ingress(iface)
break
BackboneInterface._dp_ic_snapshot = time.time()
for iface in interfaces:
iface.dp_ingress_bytes = 0
iface.dp_ingress_packets = 0
except Exception as e:
RNS.log(f"BackboneInterface ingress control error: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
@staticmethod
def __job():
with BackboneInterface._job_lock:
@@ -340,13 +565,16 @@ class BackboneInterface(Interface):
spawned_interface = BackboneInterface.spawned_interface_filenos[fileno]
client_socket = spawned_interface.socket
socket_valid = client_socket and fileno == client_socket.fileno()
if socket_valid and (event & select.EPOLLIN):
if socket_valid and (event & select.EPOLLIN) and not spawned_interface.dp_ingress_gated:
if spawned_interface.dp_ingress_gated: continue
try: received_bytes = client_socket.recv(spawned_interface.HW_MTU)
except Exception as e:
RNS.log(f"Error while reading from {spawned_interface}: {e}", RNS.LOG_PATHING) if RNS.sl(RNS.LOG_PATHING) else None
received_bytes = b""
if len(received_bytes): spawned_interface.receive(received_bytes)
if len(received_bytes):
spawned_interface.dp_ingress_bytes += len(received_bytes)
spawned_interface.receive(received_bytes)
else:
BackboneInterface.deregister_fileno(fileno); client_socket.close()
try:
@@ -364,7 +592,7 @@ class BackboneInterface(Interface):
socket_valid_after_read = socket_valid and fileno in BackboneInterface.spawned_interface_filenos
if socket_valid_after_read and (event & select.EPOLLOUT):
try: written = client_socket.send(spawned_interface.transmit_buffer)
try: written = spawned_interface.transmit_buffer.drain_to(client_socket)
except Exception as e:
written = 0
if not spawned_interface.detached:
@@ -391,11 +619,12 @@ class BackboneInterface(Interface):
except Exception as e: RNS.log(f"Error while closing socket for {spawned_interface}: {e}", RNS.LOG_WARNING)
spawned_interface.receive(b"")
spawned_interface.transmit_buffer = spawned_interface.transmit_buffer[written:]
try:
if len(spawned_interface.transmit_buffer) == 0: BackboneInterface.epoll.modify(fileno, select.EPOLLIN)
except Exception as e:
RNS.log(f"Error while setting EPOLLIN on {spawned_interface}: {e}", RNS.LOG_ERROR)
if spawned_interface.transmit_buffer.sendable == 0:
events = select.EPOLLHUP
if not spawned_interface.dp_ingress_gated: events |= select.EPOLLIN
BackboneInterface.epoll.modify(fileno, events)
except Exception as e: RNS.log(f"Error while setting EPOLLIN on {spawned_interface}: {e}", RNS.LOG_ERROR)
spawned_interface.txb += written
if spawned_interface.parent_interface: spawned_interface.parent_interface.txb += written
@@ -423,6 +652,7 @@ class BackboneInterface(Interface):
try:
client_socket, address = server_socket.accept()
client_socket.setblocking(0)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, BackboneInterface.DP_IC_RCVBUF)
if not owner_interface.incoming_connection(client_socket):
try: client_socket.close()
except Exception as e: RNS.log(f"Error while closing socket for failed incoming connection: {e}", RNS.LOG_WARNING)
@@ -564,7 +794,7 @@ class BackboneInterface(Interface):
@property
def blocked_ip_list(self):
if not self.block_fast_flapping: return []
else: return list(self.fast_flapping.keys())
else: return [ip for ip in self.fast_flapping if self.fast_flapping[ip][2] > self.fast_flap_grace]
@property
def blocked_ip_count(self):
@@ -642,8 +872,10 @@ class BackboneClientInterface(Interface):
self.i2p_tunneled = i2p_tunneled
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
self.bitrate = BackboneClientInterface.BITRATE_GUESS
self.frame_buffer = b""
self.transmit_buffer = b""
self.transmit_buffer = TransmitBuffer()
self.receive_buffer = ReceiveBuffer(mtu=lambda: self.HW_MTU, min_frame_len=RNS.Reticulum.HEADER_MINSIZE,
max_frame_len=lambda: self.HW_MTU+(getattr(self, "ifac_size", None) or 0),
on_frame=self.process_incoming, on_invalid=self.invalid_frame)
if max_reconnect_tries == None:
self.max_reconnect_tries = BackboneClientInterface.RECONNECT_MAX_TRIES
@@ -732,6 +964,7 @@ class BackboneClientInterface(Interface):
self.socket.settimeout(BackboneClientInterface.INITIAL_CONNECT_TIMEOUT)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.socket.connect(target_address)
# TODO: Check missing setblocking(0)
self.socket.settimeout(None)
BackboneInterface.add_client_socket(self.socket, self)
@@ -791,55 +1024,31 @@ class BackboneClientInterface(Interface):
self.rxb += len(data)
if hasattr(self, "parent_interface") and self.parent_interface != None:
self.parent_interface.rxb += len(data)
self.dp_ingress_packets += 1
self.owner.inbound(data, self)
def process_outgoing(self, data):
if self.online and not self.detached:
try:
self.transmit_buffer += bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
BackboneInterface.tx_ready(self)
frame = bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
if self.tx_stalled or not self.transmit_buffer.append(frame, self.tx_hwm):
self.tx_drops += 1
self.tx_dropped_bytes += len(frame)
RNS.log(f"Egress control dropping outbound frame of {RNS.prettysize(len(frame))} on {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
else: BackboneInterface.tx_ready(self)
except Exception as e:
RNS.log("Exception occurred while transmitting via "+str(self)+", tearing down interface", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
self.teardown()
def check_frame_len(self, frame_len):
if frame_len <= RNS.Reticulum.HEADER_MINSIZE: return False
elif frame_len > self.HW_MTU + (self.ifac_size or 0): return False
else: return True
def invalid_frame(self, frame_len):
RNS.log(f"Invalid HDLC frame of {RNS.prettysize(frame_len)} received on {self}, dropping frame", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
def receive(self, data_in):
try:
if len(data_in) > 0:
self.frame_buffer += data_in
flags_remaining = True
while flags_remaining:
frame_start = self.frame_buffer.find(HDLC.FLAG)
if frame_start != -1:
frame_end = self.frame_buffer.find(HDLC.FLAG, frame_start+1)
if frame_end != -1:
frame = self.frame_buffer[frame_start+1:frame_end]
frame = frame.replace(bytes([HDLC.ESC, HDLC.FLAG ^ HDLC.ESC_MASK]), bytes([HDLC.FLAG]))
frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
frame_len = len(frame)
if frame_len != 0:
if self.check_frame_len(frame_len): self.process_incoming(frame)
else: self.invalid_frame(len(frame))
self.frame_buffer = self.frame_buffer[frame_end:]
else:
if len(self.frame_buffer) > self.HW_MTU*2: self.frame_buffer = b""
flags_remaining = False
else:
self.frame_buffer = b""
flags_remaining = False
if len(data_in) > 0: self.receive_buffer.feed(data_in)
else:
self.online = False
if self.initiator and not self.detached:
@@ -858,8 +1067,7 @@ class BackboneClientInterface(Interface):
RNS.log("Attempting to reconnect...", RNS.LOG_WARNING)
def job(): self.reconnect()
threading.Thread(target=job, daemon=True).start()
else:
self.teardown()
else: self.teardown()
def teardown(self):
if self.initiator and not self.detached:
+1
View File
@@ -537,6 +537,7 @@ class I2PInterfacePeer(Interface):
raise IOError("Attempt to reconnect on a non-initiator I2P interface")
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
if hasattr(self, "parent_interface") and self.parent_interface != None and self.parent_count:
self.parent_interface.rxb += len(data)
+30 -10
View File
@@ -126,6 +126,7 @@ class Interface:
self.tunnel_id = None
self.ingress_control = True
self.phy_keepalive = False
self.shared_medium = False
self.ic_burst_active = False
self.ic_burst_activated = 0
@@ -147,6 +148,7 @@ class Interface:
self.ec_pr_freq = RNS.Reticulum.get_instance()._default_ec_pr_freq()
self.egress_control = RNS.Reticulum.get_instance()._default_egress_control()
self.held_announces = {}
self.transmit_buffer = None
self.ia_freq_deque = deque(maxlen=Interface.IA_FREQ_SAMPLES)
self.oa_freq_deque = deque(maxlen=Interface.OA_FREQ_SAMPLES)
@@ -156,6 +158,24 @@ class Interface:
self.protocol_violations = 0
self.ifac_violations = 0
self.packet_filter_hits = 0
self.dp_ingress_tcount = 0
self.dp_ingress_bytes = 0
self.dp_ingress_packets = 0
self.dp_ingress_hold = None
self.dp_ingress_gated = False
self.tx_hwm = 4*1024*1024
self.tx_stalled = False
self.tx_drops = 0
self.tx_dropped_bytes = 0
self._dp_ec_prev_sent = 0
self._dp_ec_zero_ticks = 0
self._dp_ec_last_drain = time.time()
self.reports_phy_stats = False
self.r_stat_rssi = None
self.r_stat_snr = None
self.r_stat_q = None
def get_hash(self):
if not self.__hash: self.__hash = RNS.Identity.full_hash(str(self).encode("utf-8"))
@@ -230,18 +250,18 @@ class Interface:
def optimise_mtu(self):
if self.AUTOCONFIGURE_MTU:
if self.bitrate >= 1_000_000_000: self.HW_MTU = 524288
elif self.bitrate > 750_000_000: self.HW_MTU = 262144
elif self.bitrate > 400_000_000: self.HW_MTU = 131072
elif self.bitrate > 200_000_000: self.HW_MTU = 65536
elif self.bitrate > 100_000_000: self.HW_MTU = 32768
elif self.bitrate > 10_000_000: self.HW_MTU = 16384
elif self.bitrate > 5_000_000: self.HW_MTU = 8192
elif self.bitrate > 2_000_000: self.HW_MTU = 4096
elif self.bitrate > 1_000_000: self.HW_MTU = 2048
elif self.bitrate > 62_500: self.HW_MTU = 1024
elif self.bitrate >= 750_000_000: self.HW_MTU = 262144
elif self.bitrate >= 400_000_000: self.HW_MTU = 131072
elif self.bitrate >= 200_000_000: self.HW_MTU = 65536
elif self.bitrate >= 100_000_000: self.HW_MTU = 32768
elif self.bitrate >= 10_000_000: self.HW_MTU = 16384
elif self.bitrate >= 5_000_000: self.HW_MTU = 8192
elif self.bitrate >= 2_000_000: self.HW_MTU = 4096
elif self.bitrate >= 1_000_000: self.HW_MTU = 2048
elif self.bitrate >= 62_500: self.HW_MTU = 1024
else: self.HW_MTU = None
RNS.log(f"{self} hardware MTU set to {self.HW_MTU}", RNS.LOG_PATHING)
RNS.log(f"{self} hardware MTU set to {self.HW_MTU}", RNS.LOG_EXTREME)
def age(self):
return time.time()-self.created
+2
View File
@@ -122,6 +122,7 @@ class KISSInterface(Interface):
self.packet_queue = []
self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False
self.flow_control_timeout = 5
self.flow_control_locked = time.time()
@@ -245,6 +246,7 @@ class KISSInterface(Interface):
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
+21 -43
View File
@@ -30,6 +30,8 @@
from RNS.Interfaces.Interface import Interface
from RNS.Interfaces.BackboneInterface import BackboneInterface
from RNS.Interfaces.util.TransmitBuffer import TransmitBuffer
from RNS.Interfaces.util.HDLC import HDLC, ReceiveBuffer
import socketserver
import threading
import socket
@@ -39,17 +41,6 @@ import os
import RNS
from threading import Lock
class HDLC():
FLAG = 0x7E
ESC = 0x7D
ESC_MASK = 0x20
@staticmethod
def escape(data):
data = data.replace(bytes([HDLC.ESC]), bytes([HDLC.ESC, HDLC.ESC^HDLC.ESC_MASK]))
data = data.replace(bytes([HDLC.FLAG]), bytes([HDLC.ESC, HDLC.FLAG^HDLC.ESC_MASK]))
return data
class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
def server_bind(self):
if RNS.vendor.platformutils.is_windows():
@@ -84,8 +75,9 @@ class LocalClientInterface(Interface):
self.detached = False
self.name = name
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
self.frame_buffer = b""
self.transmit_buffer = b""
self.transmit_buffer = TransmitBuffer()
self.receive_buffer = ReceiveBuffer(mtu=lambda: self.HW_MTU, min_frame_len=RNS.Reticulum.HEADER_MINSIZE,
max_frame_len=lambda: self.HW_MTU, on_frame=self.process_incoming)
if RNS.vendor.platformutils.use_epoll(): self.epoll_backend = True
@@ -195,15 +187,15 @@ class LocalClientInterface(Interface):
def send_keepalive(self):
if self.online:
RNS.log(f"Sending keepalive on {self}", RNS.LOG_DEBUG) # TODO: Remove
RNS.log(f"Sending keepalive on {self}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
try:
if self.epoll_backend:
self.transmit_buffer += bytes([HDLC.FLAG])+bytes([HDLC.FLAG])
self.transmit_buffer.append(bytes([HDLC.FLAG])+bytes([HDLC.FLAG]))
BackboneInterface.tx_ready(self)
else:
self.writing = True
data = bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
data = bytes([HDLC.FLAG])+bytes([HDLC.FLAG])
self.socket.sendall(data)
self.writing = False
@@ -220,22 +212,24 @@ class LocalClientInterface(Interface):
def process_outgoing(self, data):
if self.pause_on_client_sleep and time.time() > self.pause_timeout:
RNS.log(f"TX paused for LocalInterface client, dropping outbound packet", RNS.LOG_DEBUG) # TODO: Remove
RNS.log(f"TX paused for LocalInterface client, dropping outbound packet", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None # TODO: Remove
return
if self.online:
try:
if self.epoll_backend:
self.transmit_buffer += bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
BackboneInterface.tx_ready(self)
frame = bytes([HDLC.FLAG])+HDLC.escape(data)+bytes([HDLC.FLAG])
if self.tx_stalled or not self.transmit_buffer.append(frame, self.tx_hwm):
self.tx_drops += 1
self.tx_dropped_bytes += len(frame)
RNS.log(f"Egress control dropping outbound frame of {RNS.prettysize(len(frame))} on {self}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
else: BackboneInterface.tx_ready(self)
else:
self.writing = True
if self._force_bitrate:
if not hasattr(self, "send_lock"):
self.send_lock = Lock()
if not hasattr(self, "send_lock"): self.send_lock = Lock()
with self.send_lock:
# RNS.log(f"Simulating latency of {RNS.prettytime(s)} for {len(data)} bytes", RNS.LOG_EXTREME)
s = len(data) / self.bitrate * 8
@@ -255,22 +249,7 @@ class LocalClientInterface(Interface):
self.teardown()
def handle_hdlc(self, data_in):
self.frame_buffer += data_in
flags_remaining = True
while flags_remaining:
frame_start = self.frame_buffer.find(HDLC.FLAG)
if frame_start != -1:
frame_end = self.frame_buffer.find(HDLC.FLAG, frame_start+1)
if frame_end != -1:
frame = self.frame_buffer[frame_start+1:frame_end]
frame = frame.replace(bytes([HDLC.ESC, HDLC.FLAG ^ HDLC.ESC_MASK]), bytes([HDLC.FLAG]))
frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
if len(frame) > RNS.Reticulum.HEADER_MINSIZE: self.process_incoming(frame)
self.frame_buffer = self.frame_buffer[frame_end:]
else: flags_remaining = False
else: flags_remaining = False
self.receive_buffer.feed(data_in)
def receive(self, data_in):
try:
@@ -284,8 +263,7 @@ class LocalClientInterface(Interface):
# there's no other connectivity left to block anyway, it might be
# unnecessary.
self.reconnect()
else:
self.teardown(nowarning=True)
else: self.teardown(nowarning=True)
except Exception as e:
self.online = False
@@ -297,7 +275,7 @@ class LocalClientInterface(Interface):
def read_loop(self):
try:
self.frame_buffer = b""
self.receive_buffer.reset()
data_in = b""
while True:
data_in = self.socket.recv(4096)
@@ -431,6 +409,7 @@ class LocalServerInterface(Interface):
self.announce_rate_grace = None
self.announce_rate_penalty = None
self.HW_MTU = 262144
self.bitrate = 1000*1000*1000
self.online = True
@@ -512,5 +491,4 @@ class LocalInterfaceHandler(socketserver.BaseRequestHandler):
self.callback = callback
socketserver.BaseRequestHandler.__init__(self, *args, **keys)
def handle(self):
self.callback(handler=self)
def handle(self): self.callback(handler=self)
+2
View File
@@ -84,6 +84,7 @@ class PipeInterface(Interface):
self.pipe_is_open = False
self.bitrate = PipeInterface.BITRATE_GUESS
self.respawn_delay = respawn_delay
self.shared_medium = True
try:
self.open_pipe()
@@ -119,6 +120,7 @@ class PipeInterface(Interface):
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
+4 -3
View File
@@ -258,6 +258,7 @@ class RNodeInterface(Interface):
self.r_stat_tx = None
self.r_stat_rssi = None
self.r_stat_snr = None
self.r_stat_q = None
self.r_st_alock = None
self.r_lt_alock = None
self.r_random = None
@@ -278,6 +279,7 @@ class RNodeInterface(Interface):
self.r_noise_floor = None
self.r_interference = None
self.r_interference_l = None
self.reports_phy_stats = True
self.r_battery_state = RNodeInterface.BATTERY_STATE_UNKNOWN
self.r_battery_percent = 0
@@ -294,6 +296,7 @@ class RNodeInterface(Interface):
self.packet_queue = []
self.flow_control = flow_control
self.shared_medium = True
self.interface_ready = False
self.announce_rate_target = None
self.supports_discovery = True
@@ -699,11 +702,9 @@ class RNodeInterface(Interface):
self.bitrate = 0
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
self.r_stat_rssi = None
self.r_stat_snr = None
def process_outgoing(self,data):
datalen = len(data)
+5 -2
View File
@@ -269,6 +269,7 @@ class RNodeMultiInterface(Interface):
self.r_stat_tx = None
self.r_stat_rssi = None
self.r_stat_snr = None
self.r_stat_q = None
self.r_st_alock = None
self.r_lt_alock = None
self.r_random = None
@@ -276,6 +277,8 @@ class RNodeMultiInterface(Interface):
self.packet_queue = []
self.interface_ready = False
self.announce_rate_target = None
self.reports_phy_stats = True
self.validcfg = True
if id_interval != None and id_callsign != None:
@@ -1001,6 +1004,7 @@ class RNodeSubInterface(Interface):
self.r_premable_time_ms = None
self.packet_queue = []
self.shared_medium = True
self.interface_ready = False
self.parent_interface = parent_interface
self.announce_rate_target = None
@@ -1124,10 +1128,9 @@ class RNodeSubInterface(Interface):
self.bitrate = 0
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
self.r_stat_rssi = None
self.r_stat_snr = None
def process_outgoing(self,data):
if self.online:
+2
View File
@@ -83,6 +83,7 @@ class SerialInterface(Interface):
raise ValueError("No port specified for serial interface")
self.HW_MTU = 564
self.shared_medium = True
self.pyserial = serial
self.serial = None
@@ -142,6 +143,7 @@ class SerialInterface(Interface):
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
+1
View File
@@ -302,6 +302,7 @@ class TCPClientInterface(Interface):
raise IOError("Attempt to reconnect on a non-initiator TCP interface")
def process_incoming(self, data):
if not data: return
if self.online and not self.detached:
self.rxb += len(data)
if hasattr(self, "parent_interface") and self.parent_interface != None:
+2
View File
@@ -78,6 +78,7 @@ class UDPInterface(Interface):
self.name = name
self.online = False
self.bitrate = UDPInterface.BITRATE_GUESS
self.shared_medium = True
if device != None:
if bindip == None:
@@ -114,6 +115,7 @@ class UDPInterface(Interface):
def process_incoming(self, data):
if not data: return
self.rxb += len(data)
self.owner.inbound(data, self)
+4 -2
View File
@@ -36,5 +36,7 @@ import RNS.Interfaces.util.netinfo as netinfo
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules
__all__ = list(set([os.path.basename(f).replace(".pyc", "").replace(".py", "") for f in modules if not (f.endswith("__init__.py") or f.endswith("__init__.pyc"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+106
View File
@@ -0,0 +1,106 @@
# Reticulum License
#
# Copyright (c) 2026 Mark Qvist
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# - The Software shall not be used in any kind of system which includes amongst
# its functions the ability to purposefully do harm to human beings.
#
# - The Software shall not be used, directly or indirectly, in the creation of
# an artificial intelligence, machine learning or language model training
# dataset, including but not limited to any use that contributes to the
# training or development of such a model or algorithm.
#
# - The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
class HDLC():
FLAG = 0x7E
ESC = 0x7D
ESC_MASK = 0x20
FLAG_B = bytes([FLAG])
ESC_B = bytes([ESC])
ESCPD_FLAG = bytes([ESC, FLAG ^ ESC_MASK])
ESCPD_ESC = bytes([ESC, ESC ^ ESC_MASK])
@staticmethod
def escape(data):
data = data.replace(HDLC.ESC_B, HDLC.ESCPD_ESC)
data = data.replace(HDLC.FLAG_B, HDLC.ESCPD_FLAG)
return data
@staticmethod
def unescape(frame):
frame = frame.replace(HDLC.ESCPD_FLAG, HDLC.FLAG_B)
frame = frame.replace(HDLC.ESCPD_ESC, HDLC.ESC_B)
return frame
class ReceiveBuffer():
def __init__(self, mtu, min_frame_len, max_frame_len=None, on_frame=None, on_invalid=None):
self._mtu = mtu
self._min_frame_len = min_frame_len
self._max_frame_len = max_frame_len
self._on_frame = on_frame
self._on_invalid = on_invalid
self._buf = bytearray()
self._off = 0
def mtu(self):
return self._mtu() if callable(self._mtu) else self._mtu
def max(self):
m = self._max_frame_len
return m() if callable(m) else m
def feed(self, data):
if not data: return
self._buf.extend(data)
buf = self._buf
while True:
frame_start = buf.find(HDLC.FLAG, self._off)
if frame_start == -1:
self.reset()
return
frame_end = buf.find(HDLC.FLAG, frame_start+1)
if frame_end == -1:
if len(buf)-self._off > self.mtu()*2: self.reset()
return
frame = HDLC.unescape(bytes(buf[frame_start+1:frame_end]))
frame_len = len(frame)
if frame_len > 0:
max_len = self.max()
if frame_len > self._min_frame_len and (max_len is None or frame_len <= max_len):
if self._on_frame is not None: self._on_frame(frame)
elif self._on_invalid is not None: self._on_invalid(frame_len)
self._off = frame_end
if self._off > 0 and self._off >= len(buf) // 2:
del buf[:self._off]
self._off = 0
# Drops any partial frames from the buffer and
# resets assembly offset
def reset(self):
self._buf.clear()
self._off = 0
# Buffered bytes currently unconsumed
def __len__(self): return len(self._buf)-self._off
+171
View File
@@ -0,0 +1,171 @@
# Reticulum License
#
# Copyright (c) 2026 Mark Qvist
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# - The Software shall not be used in any kind of system which includes amongst
# its functions the ability to purposefully do harm to human beings.
#
# - The Software shall not be used, directly or indirectly, in the creation of
# an artificial intelligence, machine learning or language model training
# dataset, including but not limited to any use that contributes to the
# training or development of such a model or algorithm.
#
# - The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from collections import deque
import threading
# Zero-copy coalesced transmit buffer for arbitrary
# frame sizes. It's even almost 100% lock-free.
class TransmitBuffer:
COALESCE_TARGET = 65536
def __init__(self):
self._tail_lock = threading.Lock()
# Producer-owned state
self._cur = None
self._cur_frames = 0
# Consumer-owned state
self._head_offset = 0
# Shared chunk queue. Producer appends right, consumer
# pops from left. Appended chunks are immutable.
self._chunks = deque()
# Accounting counters
# Producer-owned
self._tx_total = 0 # Total bytes appended
self._tx_visible = 0 # Total bytes pushed to the chunk queue
self._tx_frames = 0 # Total frames appended
# Consumer-owned
self._tx_sent = 0 # Total bytes sent to the kernel
self._tx_frames_sent = 0 # Total frames fully sent
# Queue a finalized and complete on-wire frame.
# Executed by producer side only.
def append(self, frame, limit=None):
with self._tail_lock:
if limit is not None and (self._tx_total - self._tx_sent) + len(frame) > limit: return False
# Allocate separate chunks to frames
# larger than the coalescing target.
if len(frame) >= self.COALESCE_TARGET:
self._flush()
self._chunks.append((frame, 1))
self._tx_visible += len(frame)
self._tx_total += len(frame)
self._tx_frames += 1
else:
if self._cur is not None and len(self._cur) + len(frame) > self.COALESCE_TARGET: self._flush()
if self._cur is None:
self._cur = bytearray()
self._cur_frames = 0
self._cur.extend(frame)
self._cur_frames += 1
self._tx_total += len(frame)
self._tx_frames += 1
if not self._chunks:
# Queue is idle. Make the frame visible immediately so
# sparse traffic does not incur coalescing latency.
self._flush()
return True
def _flush(self):
if self._cur is not None and len(self._cur) > 0:
self._chunks.append((self._cur, self._cur_frames))
self._tx_visible += len(self._cur)
self._cur = None
self._cur_frames = 0
# Make producer-side coalescing tail visible to the consumer.
# Called by producer when it has finished producing a burst,
# and wants to make the remaining bytes transmittable. Safe to
# call after every append.
def flush(self):
with self._tail_lock: self._flush()
# Drain buffered frames to a socket. Called by consumer. If the
# chunk queue is drained completely, any potential producer-side
# coalescing tail is released under the tail lock, and drained in
# the same cycle. If you possess wizardry for doing this without
# the lock, I am all ears.
def drain_to(self, socket):
# TODO: At *some* point (no, not now), replace with a
# mechanism for send_msg to immediately drain all
# chunks directly to the kernel.
total = 0
whole = True
while whole:
if not self._chunks:
with self._tail_lock: self._flush()
if not self._chunks: break
chunk, _ = self._chunks[0]
remaining = len(chunk) - self._head_offset
if remaining <= 0:
self._pop_head()
continue
try: written = socket.send(memoryview(chunk)[self._head_offset:])
except BlockingIOError: break
except InterruptedError: continue
if written <= 0: break
total += written
self._head_offset += written
self._tx_sent += written
if self._head_offset >= len(chunk): self._pop_head()
else: whole = False
return total
def _pop_head(self):
chunk, frames = self._chunks.popleft()
self._tx_frames_sent += frames
self._head_offset = 0
# Total number of bytes currently buffered, including the
# producer's in-progress coalescing chunk.
def __len__(self): return self._tx_total-self._tx_sent
# The number of bytes actually ready to send, and will be
# visible to the consumer, that is, what can be drained.
@property
def sendable(self): return self._tx_visible-self._tx_sent
# The number of complete frames currently buffere, including
# ones contained in a potential in-progress coalescing chunk.
@property
def frames_buffered(self): return self._tx_frames-self._tx_frames_sent
# Number of chunks currently queued and visible to the consumer
@property
def chunks_buffered(self): return len(self._chunks)
def __repr__(self): return f"<TransmitBuffer buffered={len(self)} sendable={self.sendable} frames={self.frames_buffered} chunks={self.chunks_buffered}>"
+4 -2
View File
@@ -3,5 +3,7 @@ import glob
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules
__all__ = list(set([os.path.basename(f).replace(".pyc", "").replace(".py", "") for f in modules if not (f.endswith("__init__.py") or f.endswith("__init__.pyc"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+13 -5
View File
@@ -117,7 +117,8 @@ class Packet:
__slots__ = "hops", "header", "header_type", "packet_type", "transport_type", "context", "context_flag", "destination"
__slots__ += "transport_id", "data", "flags", "raw", "packed", "sent", "create_receipt", "receipt", "fromPacked", "MTU"
__slots__ += "sent_at", "packet_hash", "ratchet_id", "attached_interface", "receiving_interface", "rssi", "snr", "q"
__slots__ += "ciphertext", "plaintext", "destination_hash", "destination_type", "link", "map_hash", "is_outbound_pr", "traffic_class"
__slots__ += "ciphertext", "plaintext", "destination_hash", "destination_type", "link", "map_hash", "is_outbound_pr"
__slots__ += "traffic_class", "announce_signature_validated"
def __init__(self, destination, data, packet_type = DATA, context = NONE, transport_type = RNS.Transport.BROADCAST,
header_type = HEADER_1, transport_id = None, attached_interface = None, create_receipt = True, context_flag=FLAG_UNSET):
@@ -160,6 +161,7 @@ class Packet:
self.ratchet_id = None
self.traffic_class = None
self.announce_signature_validated = None
self.attached_interface = attached_interface
self.receiving_interface = None
self.is_outbound_pr = False
@@ -270,12 +272,14 @@ class Packet:
self.data = self.raw[DST_LEN+3:]
if len(self.destination_hash) != DST_LEN: raise ValueError("Malformed destination hash field")
if len(self.data) == 0: raise ValueError("Zero-length data field")
self.packed = False
self.update_hash()
return True
except Exception as e:
RNS.log(f"Received malformed packet, dropping it. The contained exception was: {e}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
RNS.log(f"Received malformed packet, dropping it. The contained exception was: {e}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
return False
def send(self):
@@ -350,6 +354,10 @@ class Packet:
def getTruncatedHash(self): return RNS.Identity.truncated_hash(self.get_hashable_part())
@property
def truncated_packet_hash(self):
return self.packet_hash[:RNS.Reticulum.TRUNCATED_HASHLENGTH//8]
def get_hashable_part(self):
hashable_part = bytes([self.raw[0] & 0b00001111])
if self.header_type == Packet.HEADER_2: hashable_part += self.raw[(RNS.Identity.TRUNCATED_HASHLENGTH//8)+2:]
@@ -380,7 +388,7 @@ class Packet:
class ProofDestination:
def __init__(self, packet):
self.hash = packet.get_hash()[:RNS.Reticulum.TRUNCATED_HASHLENGTH//8];
self.hash = packet.truncated_packet_hash;
self.type = RNS.Destination.SINGLE
def encrypt(self, plaintext): return plaintext
@@ -405,8 +413,8 @@ class PacketReceipt:
# Creates a new packet receipt from a sent packet
def __init__(self, packet):
self.hash = packet.get_hash()
self.truncated_hash = packet.getTruncatedHash()
self.hash = packet.packet_hash
self.truncated_hash = packet.truncated_packet_hash
self.sent = True
self.sent_at = time.time()
self.proved = False
+33 -22
View File
@@ -30,6 +30,7 @@
import RNS
import os
import io
import bz2
import math
import time
@@ -280,6 +281,19 @@ class Resource:
if hasattr(data, "read"):
if data_size == None: data_size = os.stat(data.name).st_size
if data_size == 0:
if isinstance(data, io.BufferedReader):
RNS.log(f"Attempting to proxy stream data...", RNS.LOG_DEBUG)
stream_proxy = tempfile.TemporaryFile()
stream_proxy.write(data.read())
stream_proxy.flush(); stream_proxy.seek(0)
data_size = os.stat(stream_proxy.name).st_size
if data_size: RNS.log(f"Stream proxy succeeded, final data size is {RNS.prettysize(data_size)}", RNS.LOG_DEBUG)
else: RNS.log(f"Resource initialisation received an invalid readable input, or stream data that could not be proxied, the transfer will likely fail.", RNS.LOG_WARNING)
data = stream_proxy
else: RNS.log(f"Got zero-sized readable at resource initialisation, the transfer will likely.", RNS.LOG_WARNING)
self.total_size = data_size + self.metadata_size
if self.total_size <= Resource.MAX_EFFICIENT_SIZE:
@@ -290,12 +304,6 @@ class Resource:
data.close()
else:
# self.total_segments = ((data_size-1)//Resource.MAX_EFFICIENT_SIZE)+1
# self.segment_index = segment_index
# self.split = True
# seek_index = segment_index-1
# seek_position = seek_index*Resource.MAX_EFFICIENT_SIZE
self.total_segments = ((self.total_size-1)//Resource.MAX_EFFICIENT_SIZE)+1
self.segment_index = segment_index
self.split = True
@@ -372,10 +380,8 @@ class Resource:
self.req_hashlist = []
self.receiver_min_consecutive_height = 0
if timeout != None:
self.timeout = timeout
else:
self.timeout = self.link.rtt * self.link.traffic_timeout_factor
if timeout != None: self.timeout = timeout
else: self.timeout = self.link.rtt * self.link.traffic_timeout_factor
if data != None:
self.initiator = True
@@ -384,18 +390,21 @@ class Resource:
compression_began = time.time()
if self.auto_compress and data_size <= self.auto_compress_limit:
RNS.log("Compressing resource data...", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
self.compressed_data = bz2.compress(self.uncompressed_data)
RNS.log("Compression completed in "+str(round(time.time()-compression_began, 3))+" seconds", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
else:
self.compressed_data = self.uncompressed_data
RNS.log("Compressing resource data...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
try:
self.compressed_data = bz2.compress(self.uncompressed_data)
RNS.log("Compression completed in "+str(round(time.time()-compression_began, 3))+" seconds", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
except Exception as e:
RNS.log(f"Could not auto-compress resource data, falling back to uncompressed transfer: {e}", RNS.LOG_DEBUG)
self.compressed_data = self.uncompressed_data
else: self.compressed_data = self.uncompressed_data
self.uncompressed_size = len(self.uncompressed_data)
self.compressed_size = len(self.compressed_data)
if (self.compressed_size < self.uncompressed_size and auto_compress):
saved_bytes = len(self.uncompressed_data) - len(self.compressed_data)
RNS.log("Compression saved "+str(saved_bytes)+" bytes, sending compressed", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
RNS.log("Compression saved "+str(saved_bytes)+" bytes, sending compressed", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
self.data = b""
self.data += RNS.Identity.get_random_hash()[:Resource.RANDOM_HASH_SIZE]
@@ -1085,7 +1094,7 @@ class Resource:
if self.next_segment: self.next_segment.cancel()
if self.status == Resource.CORRUPT:
self.link.cancel_incoming_resource(self)
if self in self.link.incoming_resources: self.link.cancel_incoming_resource(self)
self.reject(self.advertisement_packet)
self.link.teardown()
@@ -1097,14 +1106,14 @@ class Resource:
cancel_packet = RNS.Packet(self.link, self.hash, context=RNS.Packet.RESOURCE_ICL)
cancel_packet.send()
except Exception as e: RNS.log("Could not send resource cancel packet, the contained exception was: "+str(e), RNS.LOG_ERROR)
self.link.cancel_outgoing_resource(self)
if self in self.link.outgoing_resources: self.link.cancel_outgoing_resource(self)
else:
if self.link.status == RNS.Link.ACTIVE:
try:
cancel_packet = RNS.Packet(self.link, self.hash, context=RNS.Packet.RESOURCE_RCL)
cancel_packet.send()
except Exception as e: RNS.log("Could not send resource cancel packet, the contained exception was: "+str(e), RNS.LOG_ERROR)
self.link.cancel_incoming_resource(self)
if self in self.link.incoming_resources: self.link.cancel_incoming_resource(self)
if self.callback != None:
try:
@@ -1117,7 +1126,7 @@ class Resource:
if self.status < Resource.COMPLETE:
if self.initiator:
self.status = Resource.REJECTED
self.link.cancel_outgoing_resource(self)
if self in self.link.outgoing_resources: self.link.cancel_outgoing_resource(self)
if self.callback != None:
try:
self.link.resource_concluded(self)
@@ -1238,7 +1247,9 @@ class Resource:
return self.compressed
def __str__(self):
return "<"+RNS.hexrep(self.hash,delimit=False)+"/"+RNS.hexrep(self.link.link_id,delimit=False)+">"
if hasattr(self, "hash") and self.hash and hasattr(self, "link") and self.link:
return "<"+RNS.hexrep(self.hash,delimit=False)+"/"+RNS.hexrep(self.link.link_id,delimit=False)+">"
else: return "<initializing_resource/unknown>"
class ResourceAdvertisement:
@@ -1362,4 +1373,4 @@ class ResourceAdvertisement:
if adv.t > Resource.MAX_EFFICIENT_SIZE*3: raise ValueError("Invalid transfer size")
return adv
return adv
+26 -4
View File
@@ -108,8 +108,8 @@ class Reticulum:
discovery significantly increases throughput over fast links.
"""
MAX_QUEUED_ANNOUNCES = 16384
QUEUED_ANNOUNCE_LIFE = 60*60*24
MAX_QUEUED_ANNOUNCES = 4096
QUEUED_ANNOUNCE_LIFE = 60*60*3
ANNOUNCE_CAP = 2
"""
@@ -190,8 +190,6 @@ class Reticulum:
RNS.Transport.exit_handler()
RNS.Identity.exit_handler()
if RNS.Profiler.ran(): RNS.Profiler.results()
RNS.loglevel = RNS.LOG_NONE
RNS._detach_stdout()
@@ -737,6 +735,11 @@ class Reticulum:
if self.local_socket_path == None and self.use_af_unix:
self.local_socket_path = "default"
dql = RNS.Reticulum.default_data_queue_length() or RNS.Transport.INBOUND_DA_QUEUE_LENGTH
BackboneInterface.BackboneInterface.DP_IC_HIGH_WM = max(4, int((BackboneInterface.BackboneInterface.DP_IC_HIGH_WM_PCT/100.0) * dql))
BackboneInterface.BackboneInterface.DP_IC_MID_WM = max(2, int((BackboneInterface.BackboneInterface.DP_IC_MID_WM_PCT/100.0) * dql))
BackboneInterface.BackboneInterface.DP_IC_LOW_WM = max(0, int((BackboneInterface.BackboneInterface.DP_IC_LOW_WM_PCT/100.0) * dql))
self.__start_local_interface()
if self.is_shared_instance or self.is_standalone_instance:
@@ -1293,6 +1296,7 @@ class Reticulum:
if path == "packet_rssi": self.rpc_return(conn, self.get_packet_rssi(call["packet_hash"]))
if path == "packet_snr": self.rpc_return(conn, self.get_packet_snr(call["packet_hash"]))
if path == "packet_q": self.rpc_return(conn, self.get_packet_q(call["packet_hash"]))
if path == "profiling_results": self.rpc_return(conn, self.get_profiling_results())
if path == "blackholed_identities": self.rpc_return(conn, self.get_blackholed_identities())
if path == "is_blackholed": self.rpc_return(conn, self.is_blackholed(call["identity_hash"]))
@@ -1524,6 +1528,7 @@ class Reticulum:
ifstats["short_name"] = str(interface.name)
ifstats["hash"] = interface.get_hash()
ifstats["type"] = str(type(interface).__name__)
ifstats["mtu"] = interface.HW_MTU
ifstats["rxb"] = interface.rxb
ifstats["txb"] = interface.txb
ifstats["arxb"] = interface.arxb
@@ -1534,6 +1539,10 @@ class Reticulum:
ifstats["ptxb"] = interface.ptxb
ifstats["prxc"] = interface.prxc
ifstats["ptxc"] = interface.ptxc
ifstats["txdrp"] = interface.tx_drops
ifstats["txdrb"] = interface.tx_dropped_bytes
ifstats["txstalled"] = interface.tx_stalled
ifstats["txbuffered"] = len(interface.transmit_buffer) if interface.transmit_buffer else 0
ifstats["incoming_announce_frequency"] = interface.incoming_announce_frequency()
ifstats["outgoing_announce_frequency"] = interface.outgoing_announce_frequency()
ifstats["incoming_pr_frequency"] = interface.incoming_pr_frequency()
@@ -1583,6 +1592,8 @@ class Reticulum:
stats["ptxs"] = RNS.Transport.pr_speed_tx
stats["prxf"] = RNS.Transport.pr_freq_rx
stats["ptxf"] = RNS.Transport.pr_freq_tx
stats["rxpps"] = RNS.Transport.rx_pps
stats["txpps"] = RNS.Transport.tx_pps
stats["rxqt"] = qsnapshot[0]
stats["rxqd"] = qsnapshot[1][0]
stats["rxqa"] = qsnapshot[1][1]
@@ -1845,6 +1856,17 @@ class Reticulum:
return None
def get_profiling_results(self):
if self.is_connected_to_shared_instance:
rpc_connection = self.get_rpc_client()
rpc_connection.send_bytes(mp.packb({"get": "profiling_results"}))
response = mp.unpackb(rpc_connection.recv_bytes())
return response
else:
if RNS.Profiler.ran(): return RNS.Profiler.results()
else: return None
def halt_interface(self, interface):
pass
+277 -202
View File
@@ -44,18 +44,21 @@ from .vendor import umsgpack as umsgpack
from RNS.Interfaces.BackboneInterface import BackboneInterface
class InboundQueues:
__slots__ = ("_cond", "_queues", "_sizes", "_dropped")
__slots__ = ("_cond", "_queues", "_sizes", "_dropped", "_hw_mark")
def __init__(self, sizes):
def __init__(self, sizes, hw_mark=None):
self._cond = Condition()
self._queues = [deque() for _ in sizes]
self._sizes = sizes
self._dropped = [0 for _ in sizes]
self._hw_mark = hw_mark or max(128, BackboneInterface.DP_IC_HIGH_WM)
def put(self, traffic_class, item, block=False, timeout=None):
with self._cond:
q = self._queues[traffic_class]
if len(q) >= self._sizes[traffic_class]:
q = self._queues[traffic_class]; ql = len(q)
if traffic_class == Transport.TC_DATA and ql >= self._hw_mark:
BackboneInterface._throttle_immediate(ql)
if ql >= self._sizes[traffic_class]:
self._dropped[traffic_class] += 1
raise Full
q.append(item)
@@ -134,13 +137,13 @@ class Transport:
PATH_REQUEST_RG = 1.5 # Extra grace time for roaming-mode interfaces to allow more suitable peers to respond first
PATH_REQUEST_MI = 20 # Minimum interval in seconds for automated path requests
TRANSPORT_WORKERS = 1
USE_INBOUND_QUEUE = True
USE_OUTBOUND_QUEUE = False
INBOUND_DA_QUEUE_LENGTH = 4096
INBOUND_AN_QUEUE_LENGTH = 256
INBOUND_PR_QUEUE_LENGTH = 256
INBOUND_IL_QUEUE_LENGTH = 128
OUTBOUND_QUEUE_LENGTH = 4096
INBOUND_DA_QUEUE_LENGTH = 1024
INBOUND_AN_QUEUE_LENGTH = 128
INBOUND_PR_QUEUE_LENGTH = 128
INBOUND_IL_QUEUE_LENGTH = 8
STATE_UNKNOWN = 0x00
STATE_UNRESPONSIVE = 0x01
@@ -164,6 +167,8 @@ class Transport:
destinations_map = {} # Destination hash map of active destinations
pending_links = [] # Links that are being established
active_links = [] # Links that are active
pending_links_map = {} # Link ID hash map of pending links
active_links_map = {} # Link ID hash map of active links
packet_hashlist = set() # A list of packet hashes for duplicate detection
packet_hashlist_prev = set()
receipts = [] # Receipts of all outgoing packets for proof processing
@@ -281,6 +286,10 @@ class Transport:
pr_speed_tx = 0
pr_freq_rx = 0
pr_freq_tx = 0
rx_packets = 0
tx_packets = 0
rx_pps = 0
tx_pps = 0
traffic_captured = None
lowest_interface_bitrate = None
highest_interface_bitrate = None
@@ -509,14 +518,16 @@ class Transport:
Transport.probe_destination = None
RNS.log("Transport instance "+str(Transport.identity)+" started", RNS.LOG_VERBOSE) if RNS.sl(RNS.LOG_VERBOSE) else None
Transport.start_time = time.time()
Transport.start_time = time.time()
# Sort interfaces according to bitrate
Transport.prioritize_interfaces()
# Spawn queue workers
if Transport.USE_INBOUND_QUEUE: threading.Thread(target=Transport.inbound_job, daemon=True).start()
if Transport.USE_OUTBOUND_QUEUE: threading.Thread(target=Transport.outbound_job, daemon=True).start()
for n in range(Transport.TRANSPORT_WORKERS):
if Transport.USE_INBOUND_QUEUE: threading.Thread(target=Transport.inbound_job, daemon=True).start()
if Transport.USE_OUTBOUND_QUEUE: threading.Thread(target=Transport.outbound_job, daemon=True).start()
Transport.ready = True
# Synthesize tunnels for any interfaces wanting it
@@ -578,6 +589,8 @@ class Transport:
@staticmethod
def count_traffic_loop():
rxp = 0; txp = 0; cts = None
while True:
time.sleep(1)
try:
@@ -588,6 +601,7 @@ class Transport:
for interface in Transport.interfaces:
if not hasattr(interface, "parent_interface") or interface.parent_interface == None:
if hasattr(interface, "is_local_shared_instance"): continue
if hasattr(interface, "transport_traffic_counter"):
now = time.time()
@@ -630,7 +644,18 @@ class Transport:
interface.transport_traffic_counter = { "ts": time.time(), "rxb": interface.rxb, "txb": interface.txb,
"arxb": interface.arxb, "atxb": interface.atxb,
"prxb": interface.prxb, "ptxb": interface.ptxb }
if not Transport.start_time: rpps = 0; tpps = 0
else:
if not cts: ts = Transport.start_time
else: ts = cts
cts = time.time(); td = cts - ts
rpps = (Transport.rx_packets - rxp) / td
tpps = (Transport.tx_packets - txp) / td
rxp = Transport.rx_packets
txp = Transport.tx_packets
Transport.rx_pps = int(round(rpps))
Transport.tx_pps = int(round(tpps))
Transport.traffic_rxb += rxb
Transport.traffic_txb += txb
Transport.speed_rx = rxs
@@ -696,14 +721,18 @@ class Transport:
closed_pending_links.append(link)
for closed_link in closed_pending_links: Transport.pending_links.remove(closed_link)
for closed_link in closed_pending_links:
Transport.pending_links.remove(closed_link)
Transport.pending_links_map.pop(closed_link.link_id, None)
with Transport.active_links_lock:
closed_links = []
for link in Transport.active_links:
if link.status == RNS.Link.CLOSED: closed_links.append(link)
for closed_link in closed_links: Transport.active_links.remove(closed_link)
for closed_link in closed_links:
Transport.active_links.remove(closed_link)
Transport.active_links_map.pop(closed_link.link_id, None)
Transport.links_last_checked = time.time()
@@ -1239,43 +1268,65 @@ class Transport:
def handle_outgoing_announces(outgoing):
for packet in sorted(outgoing, key=lambda p: p.hops): packet.send()
@staticmethod
def handle_outgoing_ifac(interface, raw):
# Calculate packet access code
ifac_size = interface.ifac_size
ifac = interface.ifac_identity.sign(raw)[-ifac_size:]
# Generate mask
mask = RNS.Cryptography.hkdf(length=len(raw) + ifac_size, derive_from=ifac,
salt=interface.ifac_key, context=None)
# Set IFAC flag and assemble new payload with IFAC
new_raw = bytes([raw[0] | 0x80, raw[1]]) + ifac + raw[2:]
# Mask header bytes and payload with a single bignum XOR, leaving
# the IFAC itself untouched, then ensure the IFAC flag is set.
n = len(new_raw)
x = int.from_bytes(new_raw, "big") ^ int.from_bytes(mask, "big")
if ifac_size: x ^= int.from_bytes(mask[2:2 + ifac_size], "big") << (8 * (n - 2 - ifac_size))
x |= 1 << (8 * n - 1)
return x.to_bytes(n, "big")
@staticmethod
def handle_outgoing_ifac_legacy(interface, raw):
# Calculate packet access code
ifac = interface.ifac_identity.sign(raw)[-interface.ifac_size:]
# Generate mask
mask = RNS.Cryptography.hkdf(length=len(raw)+interface.ifac_size, derive_from=ifac,
salt=interface.ifac_key, context=None)
# Set IFAC flag
new_header = bytes([raw[0] | 0x80, raw[1]])
# Assemble new payload with IFAC
new_raw = new_header+ifac+raw[2:]
# Mask payload
i = 0; masked_raw = b""
for byte in new_raw:
# Mask first header byte, but make sure the
# IFAC flag is still set
if i == 0: masked_raw += bytes([byte ^ mask[i] | 0x80])
# Mask second header byte and payload
elif i == 1 or i > interface.ifac_size+1: masked_raw += bytes([byte ^ mask[i]])
# Don't mask the IFAC itself
else: masked_raw += bytes([byte])
i += 1
return masked_raw
@staticmethod
def transmit(interface, raw):
try:
if hasattr(interface, "ifac_identity") and interface.ifac_identity != None:
# Calculate packet access code
ifac = interface.ifac_identity.sign(raw)[-interface.ifac_size:]
# Generate mask
mask = RNS.Cryptography.hkdf(length=len(raw)+interface.ifac_size,
derive_from=ifac,
salt=interface.ifac_key,
context=None)
# Set IFAC flag
new_header = bytes([raw[0] | 0x80, raw[1]])
# Assemble new payload with IFAC
new_raw = new_header+ifac+raw[2:]
# Mask payload
i = 0; masked_raw = b""
for byte in new_raw:
# Mask first header byte, but make sure the
# IFAC flag is still set
if i == 0: masked_raw += bytes([byte ^ mask[i] | 0x80])
# Mask second header byte and payload
elif i == 1 or i > interface.ifac_size+1: masked_raw += bytes([byte ^ mask[i]])
# Don't mask the IFAC itself
else: masked_raw += bytes([byte])
i += 1
# Send it
interface.process_outgoing(masked_raw)
interface.process_outgoing(Transport.handle_outgoing_ifac(interface, raw))
else: interface.process_outgoing(raw)
Transport.tx_packets += 1
except Exception as e: RNS.log("Error while transmitting on "+str(interface)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
@@ -1391,8 +1442,11 @@ class Transport:
# interface, or belongs to a link.
else:
stored_hash = False
for interface in Transport.interfaces:
if interface.OUT:
if packet.attached_interface: potential_interfaces = [packet.attached_interface]
else: potential_interfaces = Transport.interfaces
for interface in potential_interfaces:
if interface.OUT and interface.online:
should_transmit = True
if packet.destination.type == RNS.Destination.LINK:
@@ -1514,20 +1568,19 @@ class Transport:
timer = threading.Timer(wait_time, interface.process_announce_queue)
timer.start()
if wait_time < 1: wait_time_str = str(round(wait_time*1000,2))+"ms"
else: wait_time_str = str(round(wait_time*1,2))+"s"
ql_str = str(len(interface.announce_queue))
RNS.log("Added announce to queue (height "+ql_str+") on "+str(interface)+" for processing in "+wait_time_str, RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
if RNS.sl(RNS.LOG_EXTREME):
if wait_time < 1: wait_time_str = str(round(wait_time*1000,2))+"ms"
else: wait_time_str = str(round(wait_time*1,2))+"s"
ql_str = str(len(interface.announce_queue))
RNS.log("Added announce to queue (height "+ql_str+") on "+str(interface)+" for processing in "+wait_time_str, RNS.LOG_EXTREME)
else:
wait_time = max(interface.announce_allowed_at - time.time(), 0)
if wait_time < 1: wait_time_str = str(round(wait_time*1000,2))+"ms"
else: wait_time_str = str(round(wait_time*1,2))+"s"
ql_str = str(len(interface.announce_queue))
RNS.log("Added announce to queue (height "+ql_str+") on "+str(interface)+" for processing in "+wait_time_str, RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
if RNS.sl(RNS.LOG_EXTREME):
wait_time = max(interface.announce_allowed_at - time.time(), 0)
if wait_time < 1: wait_time_str = str(round(wait_time*1000,2))+"ms"
else: wait_time_str = str(round(wait_time*1,2))+"s"
ql_str = str(len(interface.announce_queue))
RNS.log("Added announce to queue (height "+ql_str+") on "+str(interface)+" for processing in "+wait_time_str, RNS.LOG_EXTREME)
else: pass
@@ -1632,6 +1685,70 @@ class Transport:
RNS.log(f"Error while processing inbound on {interface}: {e}", RNS.LOG_ERROR)
RNS.trace_exception(e)
@staticmethod
def handle_ifac(raw, interface):
# Extract IFAC
ifac_size = interface.ifac_size
ifac = raw[2:2 + ifac_size]
# Generate mask
mask = RNS.Cryptography.hkdf(length=len(raw), derive_from=ifac,
salt=interface.ifac_key, context=None)
# Unmask header bytes and payload with a single bignum XOR,
# leaving the IFAC tag itself untouched, then drop the IFAC
# flag and strip to actual frame payload.
n = len(raw)
x = int.from_bytes(raw, "big") ^ int.from_bytes(mask, "big")
if ifac_size: x ^= int.from_bytes(mask[2:2 + ifac_size], "big") << (8 * (n - 2 - ifac_size))
unmasked = x.to_bytes(n, "big")
# Unset IFAC flag and re-assemble packet
new_raw = bytes([unmasked[0] & 0x7f, unmasked[1]]) + unmasked[2 + ifac_size:]
# Calculate expected IFAC
expected_ifac = interface.ifac_identity.sign(new_raw)[-ifac_size:]
# Check it
if ifac == expected_ifac: return True, new_raw
else:
interface.ifac_violation("Invalid IFAC on packet")
return False, None
@staticmethod
def handle_ifac_legacy(raw, interface):
# Extract IFAC
ifac = raw[2:2+interface.ifac_size]
# Generate mask
mask = RNS.Cryptography.hkdf(length=len(raw), derive_from=ifac,
salt=interface.ifac_key, context=None)
# Unmask payload
i = 0; unmasked_raw = b""
for byte in raw:
# Unmask header bytes and payload
if i <= 1 or i > interface.ifac_size+1: unmasked_raw += bytes([byte ^ mask[i]])
# Don't unmask IFAC itself
else: unmasked_raw += bytes([byte])
i += 1
raw = unmasked_raw
# Unset IFAC flag
new_header = bytes([raw[0] & 0x7f, raw[1]])
# Re-assemble packet
new_raw = new_header+raw[2+interface.ifac_size:]
# Calculate expected IFAC
expected_ifac = interface.ifac_identity.sign(new_raw)[-interface.ifac_size:]
# Check it
if ifac == expected_ifac: return True, new_raw
else:
interface.ifac_violation("Invalid IFAC on packet")
return False, None
@staticmethod
def preprocess_inbound(raw, interface=None, tc=None, ifac_handled=False):
if not Transport.ready:
@@ -1650,35 +1767,8 @@ class Transport:
# Check that IFAC flag is set
if raw[0] & 0x80 == 0x80:
if len(raw) > 2+interface.ifac_size:
# Extract IFAC
ifac = raw[2:2+interface.ifac_size]
# Generate mask
mask = RNS.Cryptography.hkdf(length=len(raw), derive_from=ifac,
salt=interface.ifac_key, context=None)
# Unmask payload
i = 0; unmasked_raw = b""
for byte in raw:
# Unmask header bytes and payload
if i <= 1 or i > interface.ifac_size+1: unmasked_raw += bytes([byte ^ mask[i]])
# Don't unmask IFAC itself
else: unmasked_raw += bytes([byte])
i += 1
raw = unmasked_raw
# Unset IFAC flag
new_header = bytes([raw[0] & 0x7f, raw[1]])
# Re-assemble packet
new_raw = new_header+raw[2+interface.ifac_size:]
# Calculate expected IFAC
expected_ifac = interface.ifac_identity.sign(new_raw)[-interface.ifac_size:]
# Check it
if ifac == expected_ifac: raw = new_raw
else: return interface.ifac_violation("Invalid IFAC on packet")
ifac_valid, raw = Transport.handle_ifac(raw, interface)
if not ifac_valid: return
else: return interface.ifac_violation("Insufficient packet size for IFAC packet")
@@ -1705,12 +1795,14 @@ class Transport:
if not Transport.packet_filter(packet): return interface.packet_filter_hit()
traffic_class = tc or Transport.TC_DATA
Transport.rx_packets += 1
packet.receiving_interface = interface
packet.hops += 1
# Ingress limit announces early
if packet.packet_type == RNS.Packet.ANNOUNCE:
if not tc: traffic_class = Transport.TC_ANNOUNCE
if len(raw) > RNS.Reticulum.MTU: return packet.receiving_interface.protocol_violation(f"Excessive announce packet frame size of {len(raw)} bytes") if packet.receiving_interface else None
if traffic_class < Transport.TC_ANNOUNCE: traffic_class = Transport.TC_ANNOUNCE
announce_signature_valid = RNS.Identity.validate_announce(packet, only_validate_signature=True, signal_blackholed=True)
if announce_signature_valid == "blackholed": return None
elif not announce_signature_valid:
@@ -1734,7 +1826,7 @@ class Transport:
# Ingress limit path requests early
elif packet.destination_hash == Transport.pr_destination_hash:
traffic_class = Transport.TC_PATH_REQUEST
if traffic_class < Transport.TC_PATH_REQUEST: traffic_class = Transport.TC_PATH_REQUEST
if not len(packet.data) >= RNS.Identity.TRUNCATED_HASHLENGTH//8: return
else:
tag_bytes = None
@@ -1823,21 +1915,19 @@ class Transport:
if packet.receiving_interface != None:
if not packet.receiving_interface.online: return
if hasattr(packet.receiving_interface, "r_stat_rssi"):
if packet.receiving_interface.reports_phy_stats:
if packet.receiving_interface.r_stat_rssi != None:
packet.rssi = packet.receiving_interface.r_stat_rssi
Transport.local_client_rssi_cache.append([packet.packet_hash, packet.rssi])
while len(Transport.local_client_rssi_cache) > Transport.LOCAL_CLIENT_CACHE_MAXSIZE:
Transport.local_client_rssi_cache.pop(0)
if hasattr(packet.receiving_interface, "r_stat_snr"):
if packet.receiving_interface.r_stat_snr != None:
packet.snr = packet.receiving_interface.r_stat_snr
Transport.local_client_snr_cache.append([packet.packet_hash, packet.snr])
while len(Transport.local_client_snr_cache) > Transport.LOCAL_CLIENT_CACHE_MAXSIZE:
Transport.local_client_snr_cache.pop(0)
if hasattr(packet.receiving_interface, "r_stat_q"):
if packet.receiving_interface.r_stat_q != None:
packet.q = packet.receiving_interface.r_stat_q
Transport.local_client_q_cache.append([packet.packet_hash, packet.q])
@@ -1928,9 +2018,10 @@ class Transport:
if packet.transport_id != None and packet.packet_type != RNS.Packet.ANNOUNCE:
if not packet.transport_id == Transport.identity.hash: return
else:
if packet.destination_hash in Transport.path_table:
next_hop = Transport.path_table[packet.destination_hash][IDX_PT_NEXT_HOP]
remaining_hops = Transport.path_table[packet.destination_hash][IDX_PT_HOPS]
path_entry = Transport.path_table.get(packet.destination_hash)
if path_entry != None:
next_hop = path_entry[IDX_PT_NEXT_HOP]
remaining_hops = path_entry[IDX_PT_HOPS]
if remaining_hops > 1:
# Just increase hop count and transmit
@@ -1963,7 +2054,7 @@ class Transport:
new_raw += struct.pack("!B", packet.hops)
new_raw += packet.raw[2:]
outbound_interface = Transport.path_table[packet.destination_hash][IDX_PT_RVCD_IF]
outbound_interface = path_entry[IDX_PT_RVCD_IF]
if packet.packet_type == RNS.Packet.LINKREQUEST:
now = time.time()
@@ -2015,11 +2106,11 @@ class Transport:
outbound_interface, # 1: Outbound interface
time.time() ] # 2: Timestamp
with Transport.reverse_table_lock: Transport.reverse_table[packet.getTruncatedHash()] = reverse_entry
with Transport.reverse_table_lock: Transport.reverse_table[packet.truncated_packet_hash] = reverse_entry
if Transport.local_hops_delta != 0 and from_local_client and not to_local_client: new_raw = Transport.mangle_hops(new_raw, Transport.local_hops_delta)
Transport.transmit(outbound_interface, new_raw)
with Transport.path_table_lock: Transport.path_table[packet.destination_hash][IDX_PT_TIMESTAMP] = time.time()
path_entry[IDX_PT_TIMESTAMP] = time.time()
else:
# TODO: There should probably be some kind of REJECT
@@ -2070,25 +2161,18 @@ class Transport:
Transport.transmit(outbound_interface, new_raw)
Transport.link_table[packet.destination_hash][IDX_LT_TIMESTAMP] = time.time()
else:
RNS.log(f"No-outbound return on link packet from {packet.receiving_interface}", RNS.LOG_WARNING) # TODO: Remove
# TODO: Can we return safely here? Test and possibly enable this at some point.
return
else: RNS.log(f"No-outbound return on link packet from {packet.receiving_interface}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
return
# Announce handling. Handles logic related to incoming
# announces, queueing rebroadcasts of these, and removal
# of queued announce rebroadcasts once handed to the next node.
if packet.packet_type == RNS.Packet.ANNOUNCE:
local_destination = None
with Transport.destinations_map_lock:
if packet.destination_hash in Transport.destinations_map:
local_destination = Transport.destinations_map[packet.destination_hash]
announce_valid = RNS.Identity.validate_announce(packet)
if not announce_valid: return packet.receiving_interface.protocol_violation("Invalid announce") if packet.receiving_interface else None
local_destination = Transport.destinations_map.get(packet.destination_hash)
if local_destination == None and announce_valid:
if packet.transport_id != None:
received_from = packet.transport_id
@@ -2455,11 +2539,7 @@ class Transport:
# Handling for link requests to local destinations
elif packet.packet_type == RNS.Packet.LINKREQUEST and not link_request_handled:
if packet.transport_id == None or packet.transport_id == Transport.identity.hash:
destination = None
with Transport.destinations_map_lock:
if packet.destination_hash in Transport.destinations_map:
destination = Transport.destinations_map[packet.destination_hash]
destination = Transport.destinations_map.get(packet.destination_hash)
if destination and destination.type == packet.destination_type:
path_mtu = RNS.Link.mtu_from_lr_packet(packet)
mode = RNS.Link.mode_from_lr_packet(packet)
@@ -2489,37 +2569,31 @@ class Transport:
# Handling for local data packets
elif packet.packet_type == RNS.Packet.DATA:
if packet.destination_type == RNS.Destination.LINK:
with Transport.active_links_lock:
for link in Transport.active_links:
if link.link_id == packet.destination_hash:
if link.attached_interface == packet.receiving_interface:
packet.link = link
if packet.context == RNS.Packet.CACHE_REQUEST:
cached_packet = Transport.get_cached_packet(packet.data)
if cached_packet != None:
if not cached_packet.unpack(): return
RNS.Packet(destination=link, data=cached_packet.data,
packet_type=cached_packet.packet_type, context=cached_packet.context).send()
else: link.receive(packet)
break
else:
# In the strange and rare case that an interface
# is partly malfunctioning, and a link-associated
# packet is being received on an interface that
# has failed sending, and transport has failed over
# to another path, we remove this packet hash from
# the filter hashlist so the link can receive the
# packet when it finally arrives over another path.
while packet.packet_hash in Transport.packet_hashlist:
Transport.packet_hashlist.remove(packet.packet_hash)
else:
destination = None
with Transport.destinations_map_lock:
if packet.destination_hash in Transport.destinations_map:
destination = Transport.destinations_map[packet.destination_hash]
link = Transport.active_links_map.get(packet.destination_hash)
if link != None:
if link.attached_interface == packet.receiving_interface:
packet.link = link
if packet.context == RNS.Packet.CACHE_REQUEST:
cached_packet = Transport.get_cached_packet(packet.data)
if cached_packet != None:
if not cached_packet.unpack(): return
RNS.Packet(destination=link, data=cached_packet.data,
packet_type=cached_packet.packet_type, context=cached_packet.context).send()
else: link.receive(packet)
else:
# In the strange and rare case that an interface
# is partly malfunctioning, and a link-associated
# packet is being received on an interface that
# has failed sending, and transport has failed over
# to another path, we remove this packet hash from
# the filter hashlist so the link can receive the
# packet when it finally arrives over another path.
while packet.packet_hash in Transport.packet_hashlist: Transport.packet_hashlist.remove(packet.packet_hash)
while packet.packet_hash in Transport.packet_hashlist_prev: Transport.packet_hashlist_prev.remove(packet.packet_hash)
else:
destination = Transport.destinations_map.get(packet.destination_hash)
if destination and destination.type == packet.destination_type:
packet.destination = destination
if destination.receive(packet):
@@ -2556,10 +2630,8 @@ class Transport:
if peer_identity.validate(signature, signed_data) and not link_entry[IDX_LT_VALIDATED]:
RNS.log(f"Re-balancing path to {RNS.prettyhexrep(link_destination)} from link-request proof ({link_entry[IDX_LT_REM_HOPS]}->{packet.hops})", REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
link_entry[IDX_LT_REM_HOPS] = packet.hops
with Transport.path_table_lock:
if link_destination in Transport.path_table:
path_entry = Transport.path_table[link_destination]
path_entry[IDX_PT_HOPS] = packet.hops
path_entry = Transport.path_table.get(link_destination)
if path_entry: path_entry[IDX_PT_HOPS] = packet.hops
elif not link_entry[IDX_LT_VALIDATED]: RNS.log(f"Aborting link request proof path re-balancing for {RNS.prettyhexrep(link_destination)} on link {RNS.prettyhexrep(packet.destination_hash)} due to invalid signature", REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
else: pass
@@ -2603,65 +2675,57 @@ class Transport:
# Check if we can deliver it to a local pending link
pending_link = None
with Transport.pending_links_lock:
for link in Transport.pending_links:
if link.link_id == packet.destination_hash:
if packet.hops != link.expected_hops and link.status == RNS.Link.PENDING and Transport.ALLOW_LINK_PATH_REBALANCE:
RNS.log(f"Unbalanced link path ({packet.hops}/{link.expected_hops}) detected on link {link}, validating signature for re-balancing...", REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
try:
if len(packet.data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2 or len(packet.data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2+RNS.Link.LINK_MTU_SIZE:
packet_data = packet.data
signalling_bytes = b""
confirmed_mtu = None
mode = RNS.Link.mode_from_lp_packet(packet)
if mode != link.mode: raise TypeError(f"Invalid link mode {mode} in link request proof")
if len(packet_data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2+RNS.Link.LINK_MTU_SIZE:
confirmed_mtu = RNS.Link.mtu_from_lp_packet(packet)
signalling_bytes = RNS.Link.signalling_bytes(confirmed_mtu, mode)
packet_data = packet_data[:RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2]
link = Transport.pending_links_map.get(packet.destination_hash)
if link != None:
if packet.hops != link.expected_hops and link.status == RNS.Link.PENDING and Transport.ALLOW_LINK_PATH_REBALANCE:
RNS.log(f"Unbalanced link path ({packet.hops}/{link.expected_hops}) detected on link {link}, validating signature for re-balancing...", REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
try:
if len(packet.data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2 or len(packet.data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2+RNS.Link.LINK_MTU_SIZE:
packet_data = packet.data
signalling_bytes = b""
confirmed_mtu = None
mode = RNS.Link.mode_from_lp_packet(packet)
if mode != link.mode: raise TypeError(f"Invalid link mode {mode} in link request proof")
if len(packet_data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2+RNS.Link.LINK_MTU_SIZE:
confirmed_mtu = RNS.Link.mtu_from_lp_packet(packet)
signalling_bytes = RNS.Link.signalling_bytes(confirmed_mtu, mode)
packet_data = packet_data[:RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2]
peer_pub_bytes = packet_data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2]
peer_sig_pub_bytes = link.destination.identity.get_public_key()[RNS.Link.ECPUBSIZE//2:RNS.Link.ECPUBSIZE]
peer_pub_bytes = packet_data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2]
peer_sig_pub_bytes = link.destination.identity.get_public_key()[RNS.Link.ECPUBSIZE//2:RNS.Link.ECPUBSIZE]
signed_data = link.link_id+peer_pub_bytes+peer_sig_pub_bytes+signalling_bytes
signature = packet_data[:RNS.Identity.SIGLENGTH//8]
signed_data = link.link_id+peer_pub_bytes+peer_sig_pub_bytes+signalling_bytes
signature = packet_data[:RNS.Identity.SIGLENGTH//8]
if link.destination.identity.validate(signature, signed_data):
with Transport.path_table_lock:
if not link.rebalanced:
RNS.log(f"Re-balancing path to {RNS.prettyhexrep(link.destination.hash)} at link terminus ({link.expected_hops}->{packet.hops})", REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
link.rebalanced = time.time()
link.expected_hops = packet.hops
if link.destination.hash in Transport.path_table:
path_entry = Transport.path_table[link.destination.hash]
path_entry[IDX_PT_HOPS] = packet.hops
RNS.log(f"Path table re-balanced for {RNS.prettyhexrep(link.destination.hash)}", REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
if link.destination.identity.validate(signature, signed_data):
if not link.rebalanced:
RNS.log(f"Re-balancing path to {RNS.prettyhexrep(link.destination.hash)} at link terminus ({link.expected_hops}->{packet.hops})", REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
link.rebalanced = time.time()
link.expected_hops = packet.hops
path_entry = Transport.path_table.get(link.destination.hash)
if path_entry:
path_entry[IDX_PT_HOPS] = packet.hops
RNS.log(f"Path table re-balanced for {RNS.prettyhexrep(link.destination.hash)}", REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
else: RNS.log(f"Aborting path re-balancing at link terminus for {RNS.prettyhexrep(link.destination.hash)} on link {link} due to invalid signature", REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
except Exception as e: RNS.log("Error while validating link request proof for path re-balancing at link terminus. The contained exception was: "+str(e), REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
else: RNS.log(f"Aborting path re-balancing at link terminus for {RNS.prettyhexrep(link.destination.hash)} on link {link} due to invalid signature", REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
except Exception as e: RNS.log("Error while validating link request proof for path re-balancing at link terminus. The contained exception was: "+str(e), REBALANCE_LOGLEVEL) if RNS.sl(REBALANCE_LOGLEVEL) else None
if packet.hops == link.expected_hops:
# Add this packet to the filter hashlist if we
# have determined that it's actually destined
# for this system, and then validate the proof
Transport.add_packet_hash(packet.packet_hash)
pending_link = link
break
if packet.hops == link.expected_hops:
# Add this packet to the filter hashlist if we
# have determined that it's actually destined
# for this system, and then validate the proof
Transport.add_packet_hash(packet.packet_hash)
pending_link = link
if pending_link: pending_link.validate_proof(packet)
elif packet.context == RNS.Packet.RESOURCE_PRF:
with Transport.active_links_lock:
for link in Transport.active_links:
if link.link_id == packet.destination_hash:
link.receive(packet)
break
link = Transport.active_links_map.get(packet.destination_hash)
if link != None: link.receive(packet)
else:
if packet.destination_type == RNS.Destination.LINK:
with Transport.active_links_lock:
for link in Transport.active_links:
if link.link_id == packet.destination_hash:
packet.link = link
break
link = Transport.active_links_map.get(packet.destination_hash)
if link != None: packet.link = link
if len(packet.data) == RNS.PacketReceipt.EXPL_LENGTH: proof_hash = packet.data[:RNS.Identity.HASHLENGTH//8]
else: proof_hash = None
@@ -2864,9 +2928,13 @@ class Transport:
def register_link(link):
RNS.log("Registering link "+str(link), RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
if link.initiator:
with Transport.pending_links_lock: Transport.pending_links.append(link)
with Transport.pending_links_lock:
Transport.pending_links.append(link)
Transport.pending_links_map[link.link_id] = link
else:
with Transport.active_links_lock: Transport.active_links.append(link)
with Transport.active_links_lock:
Transport.active_links.append(link)
Transport.active_links_map[link.link_id] = link
@staticmethod
def activate_link(link):
@@ -2875,10 +2943,14 @@ class Transport:
if link in Transport.pending_links:
if link.status != RNS.Link.ACTIVE: raise IOError("Invalid link state for link activation: "+str(link.status))
Transport.pending_links.remove(link)
with Transport.active_links_lock: Transport.active_links.append(link)
Transport.pending_links_map.pop(link.link_id, None)
with Transport.active_links_lock:
Transport.active_links.append(link)
Transport.active_links_map[link.link_id] = link
link.status = RNS.Link.ACTIVE
else:
RNS.log("Attempted to activate a link that was not in the pending table", RNS.LOG_ERROR)
else: RNS.log("Attempted to activate a link that was not in the pending table", RNS.LOG_ERROR)
@staticmethod
def register_announce_handler(handler):
@@ -3259,6 +3331,9 @@ class Transport:
response.append(Transport.owner.get_interface_stats())
if data[0] == True: response.append(Transport.owner.get_link_count())
if len(data) >= 2:
if data[1] == True: response.append(Transport.owner.get_profiling_results())
return response
except Exception as e:
+4 -2
View File
@@ -33,5 +33,7 @@ import glob
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules
__all__ = list(set([os.path.basename(f).replace(".pyc", "").replace(".py", "") for f in modules if not (f.endswith("__init__.py") or f.endswith("__init__.pyc"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+4 -2
View File
@@ -35,5 +35,7 @@ import glob
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules
__all__ = list(set([os.path.basename(f).replace(".pyc", "").replace(".py", "") for f in modules if not (f.endswith("__init__.py") or f.endswith("__init__.pyc"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+12 -12
View File
@@ -709,7 +709,7 @@ class NomadNetworkNode():
content = self.m_heading("Invalid Path", 1) + "\n\nNo file path specified.\n"
return self.render_template(content, st=st)
file_path = file_path.lstrip("./").replace("/./", "/")
file_path = file_path.removeprefix("./").replace("/./", "/")
file_ext = os.path.splitext(file_path)[1].lower()
renderable = file_ext in self.RENDERABLE_EXTS
if not renderable: raw = True; render = False
@@ -1325,6 +1325,14 @@ class NomadNetworkNode():
content = self.m_heading("Error", 2) + "\nThe requested repository was not found.\n"
return self.render_template(content, st=st)
content_parts = []
nav_parts = []
# Breadcrumb navigation
breadcrumb = f">>\n{self.m_link('Node', self.PATH_INDEX)} / {self.m_link(group_name, self.PATH_GROUP, g=group_name)} / {self.m_link(repo_name, self.PATH_REPO, g=group_name, r=repo_name)} / {self.m_link('releases', self.PATH_RELEASES, g=group_name, r=repo_name)} / {tag}"
nav_parts.append(breadcrumb + "\n")
nav_content = "".join(nav_parts)
releases_path = f"{repo['path']}.releases"
if tag == "latest":
releases, latest_release = self.owner.releases_list_data(releases_path)
@@ -1338,14 +1346,6 @@ class NomadNetworkNode():
else: tag = latest_release
content_parts = []
nav_parts = []
# Breadcrumb navigation
breadcrumb = f">>\n{self.m_link('Node', self.PATH_INDEX)} / {self.m_link(group_name, self.PATH_GROUP, g=group_name)} / {self.m_link(repo_name, self.PATH_REPO, g=group_name, r=repo_name)} / {self.m_link('releases', self.PATH_RELEASES, g=group_name, r=repo_name)} / {tag}"
nav_parts.append(breadcrumb + "\n")
nav_content = "".join(nav_parts)
release_dir = os.path.join(releases_path, tag)
if not os.path.isdir(release_dir):
@@ -1671,7 +1671,7 @@ class NomadNetworkNode():
repo = self.get_accessible_repository(remote_identity, group_name, repo_name)
if not repo:
RNS.log(f"Repository not found or no access for artifact request {group_name}/{repo_name}/{tag}/{artifact}", RNS.LOG_WARNING)
RNS.log(f"Repository not found or no access for artifact request {group_name}/{repo_name}/{tag}/{artifact}", RNS.LOG_DEBUG)
return None
releases_path = f"{repo['path']}.releases"
@@ -1729,7 +1729,7 @@ class NomadNetworkNode():
repo = self.get_accessible_repository(remote_identity, group_name, repo_name)
if not repo:
RNS.log(f"Repository not found or no access for download request {group_name}/{repo_name}/{ref}/{file_path}", RNS.LOG_WARNING)
RNS.log(f"Repository not found or no access for download request {group_name}/{repo_name}/{ref}/{file_path}", RNS.LOG_DEBUG)
return None
repo_path = repo["path"]
@@ -1783,7 +1783,7 @@ class NomadNetworkNode():
repo = self.get_accessible_repository(remote_identity, group_name, repo_name)
if not repo:
RNS.log(f"Repository not found or no access for workdoc download request {group_name[:128]}/{repo_name[:128]}/{doc_id}", RNS.LOG_WARNING)
RNS.log(f"Repository not found or no access for workdoc download request {group_name[:128]}/{repo_name[:128]}/{doc_id}", RNS.LOG_DEBUG)
return None
doc_access = self.resolve_doc_permission(remote_identity, group_name, repo_name, doc_id, self.owner.PERM_READ)
+5
View File
@@ -4897,6 +4897,11 @@ announce_interval = 360
# blocked_identities = d31aeea49873006f13b3415520666a4e
# To make it easier to handle scrapers, crawlers, slopware
# and other annoyances, you can block unidentified peers by
# adding the null_ident hash to to blocked identities.
# blocked_identities = d7db22f63b453c23bb0688dde565b7c1
[repositories]
+2 -9
View File
@@ -55,19 +55,12 @@ def main():
parser.add_argument("--config", action="store", default=None, help="path to alternative Reticulum config directory", type=str)
parser.add_argument('-v', '--verbose', action='count', default=0)
parser.add_argument('-q', '--quiet', action='count', default=0)
parser.add_argument("--exampleconfig", action='store_true', default=False, help="print verbose configuration example to stdout and exit")
parser.add_argument("--version", action="version", version="rnir {version}".format(version=__version__))
args = parser.parse_args()
if args.exampleconfig:
print(__example_rns_config__)
exit()
if args.config:
configarg = args.config
else:
configarg = None
if args.config: configarg = args.config
else: configarg = None
program_setup(configdir = configarg, verbosity=args.verbose, quietness=args.quiet)
+4 -2
View File
@@ -41,7 +41,9 @@ module_dir = os.path.dirname(module_abs_filename)
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules
__all__ = list(set([os.path.basename(f).replace(".pyc", "").replace(".py", "") for f in modules if not (f.endswith("__init__.py") or f.endswith("__init__.pyc"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
def _get_version(): return __version__
+1
View File
@@ -32,6 +32,7 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import RNS
import asyncio
import threading
import time
+61 -50
View File
@@ -63,9 +63,10 @@ request_concluded = False
first_remote_req = True
remote_destination = None
remote_link = None
def get_remote_status(destination_hash, include_lstats, identity, no_output=False, timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
def get_remote_status(destination_hash, include_lstats, include_profiling, identity, no_output=False, timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
global request_result, request_concluded, first_remote_req, remote_destination, remote_link
link_count = None
profiling_results = None
if not RNS.Transport.has_path(destination_hash):
if not no_output:
@@ -114,7 +115,10 @@ def get_remote_status(destination_hash, include_lstats, identity, no_output=Fals
if len(response) > 1: link_count = response[1]
else: link_count = None
request_result = (status, link_count)
if len(response) > 2: profiling_results = response[2]
else: profiling_results = None
request_result = (status, link_count, profiling_results)
request_concluded = True
@@ -125,7 +129,7 @@ def get_remote_status(destination_hash, include_lstats, identity, no_output=Fals
print("Sending request...", end=" ")
sys.stdout.flush()
link.identify(identity)
link.request("/status", data = [include_lstats], response_callback = got_response, failed_callback = request_failed)
link.request("/status", data = [include_lstats, include_profiling], response_callback = got_response, failed_callback = request_failed)
first_remote_req = False
if not remote_link and not no_output:
@@ -155,7 +159,7 @@ def get_remote_status(destination_hash, include_lstats, identity, no_output=Fals
def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=False, astats=False, pstats=False, lstats=False,
sorting=None, sort_reverse=False, remote=None, management_identity=None, must_exit=True, rns_instance=None,
traffic_totals=False, discovered_interfaces=False, config_entries=False, burst_filter=False, blocked_ips=False,
queue_stats=False, remote_timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
queue_stats=False, pps=False, profiling=False, remote_timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
if remote: require_shared = False
else: require_shared = True
@@ -175,6 +179,7 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
link_count = None
active_link_count = None
stats = None
profiling_results = None
details = False
if config_entries:
@@ -327,8 +332,8 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
if identity == None: raise ValueError("Could not load management identity from "+str(management_identity))
try:
remote_status = get_remote_status(destination_hash, lstats, identity, no_output=json, timeout=remote_timeout)
if remote_status != None: stats, link_count = remote_status
remote_status = get_remote_status(destination_hash, lstats, profiling, identity, no_output=json, timeout=remote_timeout)
if remote_status != None: stats, link_count, profiling_results = remote_status
except Exception as e: raise e
except Exception as e:
@@ -343,6 +348,10 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
try: active_link_count = reticulum.get_active_link_count()
except Exception as e: pass
if profiling:
try: profiling_results = reticulum.get_profiling_results()
except Exception as e: pass
try: stats = reticulum.get_interface_stats()
except Exception as e: pass
@@ -367,46 +376,29 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
interfaces = stats["interfaces"]
if sorting != None and isinstance(sorting, str):
sorting = sorting.lower()
if sorting == "rate" or sorting == "bitrate":
interfaces.sort(key=lambda i: i["bitrate"], reverse=not sort_reverse)
if sorting == "rx":
interfaces.sort(key=lambda i: i["rxb"], reverse=not sort_reverse)
if sorting == "tx":
interfaces.sort(key=lambda i: i["txb"], reverse=not sort_reverse)
if sorting == "rxs":
interfaces.sort(key=lambda i: i["rxs"], reverse=not sort_reverse)
if sorting == "txs":
interfaces.sort(key=lambda i: i["txs"], reverse=not sort_reverse)
if sorting == "traffic":
interfaces.sort(key=lambda i: i["rxb"]+i["txb"], reverse=not sort_reverse)
if sorting == "announces" or sorting == "announce":
interfaces.sort(key=lambda i: i["incoming_announce_frequency"]+i["outgoing_announce_frequency"], reverse=not sort_reverse)
if sorting == "arx":
interfaces.sort(key=lambda i: i["incoming_announce_frequency"], reverse=not sort_reverse)
if sorting == "atx":
interfaces.sort(key=lambda i: i["outgoing_announce_frequency"], reverse=not sort_reverse)
if sorting == "arxc":
interfaces.sort(key=lambda i: i["arxc"], reverse=not sort_reverse)
if sorting == "atxc":
interfaces.sort(key=lambda i: i["atxc"], reverse=not sort_reverse)
if sorting == "prx":
interfaces.sort(key=lambda i: i["incoming_pr_frequency"], reverse=not sort_reverse)
if sorting == "ptx":
interfaces.sort(key=lambda i: i["outgoing_pr_frequency"], reverse=not sort_reverse)
if sorting == "prxc":
interfaces.sort(key=lambda i: i["prxc"], reverse=not sort_reverse)
if sorting == "ptxc":
interfaces.sort(key=lambda i: i["ptxc"], reverse=not sort_reverse)
if sorting == "held":
interfaces.sort(key=lambda i: i["held_announces"], reverse=not sort_reverse)
if sorting == "pvs":
interfaces.sort(key=lambda i: i["protocol_violations"], reverse=not sort_reverse)
if sorting == "ivs":
interfaces.sort(key=lambda i: i["ifac_violations"], reverse=not sort_reverse)
if sorting == "flt":
interfaces.sort(key=lambda i: i["packet_filter_hits"], reverse=not sort_reverse)
if sorting == "gravity" or sorting == "g":
interfaces.sort(key=lambda i: i["gravity"], reverse=not sort_reverse)
if sorting == "rate" or sorting == "bitrate": interfaces.sort(key=lambda i: i["bitrate"], reverse=not sort_reverse)
if sorting == "rx": interfaces.sort(key=lambda i: i["rxb"], reverse=not sort_reverse)
if sorting == "tx": interfaces.sort(key=lambda i: i["txb"], reverse=not sort_reverse)
if sorting == "rxs": interfaces.sort(key=lambda i: i["rxs"], reverse=not sort_reverse)
if sorting == "txs": interfaces.sort(key=lambda i: i["txs"], reverse=not sort_reverse)
if sorting == "traffic": interfaces.sort(key=lambda i: i["rxb"]+i["txb"], reverse=not sort_reverse)
if sorting == "anns" or sorting == "announces": interfaces.sort(key=lambda i: i["incoming_announce_frequency"]+i["outgoing_announce_frequency"], reverse=not sort_reverse)
if sorting == "arx": interfaces.sort(key=lambda i: i["incoming_announce_frequency"], reverse=not sort_reverse)
if sorting == "atx": interfaces.sort(key=lambda i: i["outgoing_announce_frequency"], reverse=not sort_reverse)
if sorting == "arxc": interfaces.sort(key=lambda i: i["arxc"], reverse=not sort_reverse)
if sorting == "atxc": interfaces.sort(key=lambda i: i["atxc"], reverse=not sort_reverse)
if sorting == "prx": interfaces.sort(key=lambda i: i["incoming_pr_frequency"], reverse=not sort_reverse)
if sorting == "ptx": interfaces.sort(key=lambda i: i["outgoing_pr_frequency"], reverse=not sort_reverse)
if sorting == "prxc": interfaces.sort(key=lambda i: i["prxc"], reverse=not sort_reverse)
if sorting == "ptxc": interfaces.sort(key=lambda i: i["ptxc"], reverse=not sort_reverse)
if sorting == "held": interfaces.sort(key=lambda i: i["held_announces"], reverse=not sort_reverse)
if sorting == "pvs": interfaces.sort(key=lambda i: i["protocol_violations"], reverse=not sort_reverse)
if sorting == "ivs": interfaces.sort(key=lambda i: i["ifac_violations"], reverse=not sort_reverse)
if sorting == "flt": interfaces.sort(key=lambda i: i["packet_filter_hits"], reverse=not sort_reverse)
if sorting == "gravity" or sorting == "g": interfaces.sort(key=lambda i: i["gravity"], reverse=not sort_reverse)
if sorting == "txdrp": interfaces.sort(key=lambda i: i["txdrp"], reverse=not sort_reverse)
if sorting == "txdrb": interfaces.sort(key=lambda i: i["txdrb"], reverse=not sort_reverse)
if sorting == "txbuf": interfaces.sort(key=lambda i: i["txbuffered"], reverse=not sort_reverse)
for ifstat in interfaces:
@@ -500,8 +492,11 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
if not (name.startswith("Shared Instance[") or name.startswith("TCPInterface[Client") or name.startswith("LocalInterface[")):
print(f" Mode : {modestr}")
if ifstat["txdrp"]:
print(f" TX Drops : {ifstat['txdrp']} ({RNS.prettysize(ifstat['txdrb'])})")
if "bitrate" in ifstat and ifstat["bitrate"] != None:
print(" Rate : {ss}".format(ss=speed_str(ifstat["bitrate"])))
print(f" Rate : {speed_str(ifstat['bitrate'])}, MTU {ifstat['mtu']}")
if "noise_floor" in ifstat:
if not "interference" in ifstat: nstr = ""
@@ -701,6 +696,11 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
if "rxs" in ifstat and "txs" in ifstat:
rxstat += " "+RNS.prettyspeed(ifstat["rxs"])
txstat += " "+RNS.prettyspeed(ifstat["txs"])
if ifstat["txbuffered"]:
if ifstat["txstalled"]: stlstr = ", stalled"
else: stlstr = ""
txstat += f" ({RNS.prettysize(ifstat['txbuffered'])} waiting{stlstr})"
print(f" Traffic : {txstat}\n {rxstat}")
@@ -736,6 +736,12 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
if stats["rxs"] > 0: rxstat = f"{rxstat}, {int(drxpct)}% data ({RNS.prettyspeed(drxs)})"
if stats["txs"] > 0: txstat = f"{txstat}, {int(dtxpct)}% data ({RNS.prettyspeed(dtxs)})"
if pps:
rpps = RNS.prettysize(stats['rxpps'], suffix="pps")
tpps = RNS.prettysize(stats['txpps'], suffix="pps")
rxstat = f"{rxstat}, {rpps}"
txstat = f"{txstat}, {tpps}"
print(f"\n Totals : {txstat}\n {rxstat}")
if pstats:
@@ -793,6 +799,9 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
print(f" {pqpress}")
print(f" {ilpress}")
if profiling_results:
print(f"\n Profiling :\n{RNS.Profiler.format_results(profiling_results)}")
if "transport_id" in stats and stats["transport_id"] != None:
print("\n Transport Instance "+RNS.prettyhexrep(stats["transport_id"])+" running")
if "network_id" in stats and stats["network_id"] != None:
@@ -830,8 +839,10 @@ def main(must_exit=True, rns_instance=None):
parser.add_argument("-B", "--burst", action="store_true", help="only show interfaces with active bursts", default=False)
parser.add_argument("-b", "--blocked-ips", action="store_true", help="show blocked IPs per interface", default=False)
parser.add_argument("-t", "--totals", action="store_true", help="display traffic totals", default=False)
parser.add_argument("-p", "--pps", action="store_true", help="display packets per second in totals", default=False)
parser.add_argument("-q", "--queues", action="store_true", help="display queue stats", default=False)
parser.add_argument("-s", "--sort", action="store", help="sort interfaces by [rate, traffic, rx, tx, rxs, txs, announces, arx, atx, arxc, atxc, held, prx, ptx, prxc, ptxc, pvs, ivs, flt]", default=None, type=str)
parser.add_argument("-z", "--profiling", action="store_true", help="display live profiling results", default=False)
parser.add_argument("-s", "--sort", action="store", help="sort interfaces by [rate, traffic, rx, tx, rxs, txs, anns, arx, atx, arxc, atxc, held, prx, ptx, prxc, ptxc, pvs, ivs, flt, txdrp, txdrb, txbuf]", default=None, type=str)
parser.add_argument("-r", "--reverse", action="store_true", help="reverse sorting", default=False)
parser.add_argument("-j", "--json", action="store_true", help="output in JSON format", default=False)
parser.add_argument("-R", action="store", metavar="hash", help="transport identity hash of remote instance to get status from", default=None, type=str)
@@ -869,7 +880,7 @@ def main(must_exit=True, rns_instance=None):
astats=args.announce_stats, pstats=args.pr_stats, lstats=args.link_stats, sorting=args.sort, sort_reverse=args.reverse,
remote=args.R, management_identity=args.i, remote_timeout=args.w, must_exit=False, rns_instance=reticulum,
traffic_totals=args.totals, discovered_interfaces=args.discovered, config_entries=args.D, burst_filter=args.burst,
blocked_ips=args.blocked_ips, queue_stats=args.queues)
blocked_ips=args.blocked_ips, queue_stats=args.queues, pps=args.pps, profiling=args.profiling)
finally:
sys.stdout = old_stdout
@@ -887,7 +898,7 @@ def main(must_exit=True, rns_instance=None):
astats=args.announce_stats, pstats=args.pr_stats, lstats=args.link_stats, sorting=args.sort, sort_reverse=args.reverse,
remote=args.R, management_identity=args.i, remote_timeout=args.w, must_exit=must_exit, rns_instance=rns_instance,
traffic_totals=args.totals, discovered_interfaces=args.discovered, config_entries=args.D, burst_filter=args.burst,
blocked_ips=args.blocked_ips, queue_stats=args.queues)
blocked_ips=args.blocked_ips, queue_stats=args.queues, pps=args.pps, profiling=args.profiling)
except KeyboardInterrupt:
print("")
+209 -88
View File
@@ -35,32 +35,25 @@ import time
import datetime
import random
import threading
import math
import bisect
from ._version import __version__
from .Reticulum import Reticulum
from .Identity import Identity
from .Link import Link, RequestReceipt
from .Channel import MessageBase
from .Buffer import Buffer, RawChannelReader, RawChannelWriter
from .Transport import Transport
from .Discovery import InterfaceAnnouncer
from .Destination import Destination
from .Packet import Packet
from .Packet import PacketReceipt
from .Resolver import Resolver
from .Resource import Resource, ResourceAdvertisement
from .Cryptography import HKDF
from .Cryptography import Hashes
from collections import deque
from functools import partial, wraps
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules
__all__ = list(set([os.path.basename(f).replace(".pyc", "").replace(".py", "") for f in modules if not (f.endswith("__init__.py") or f.endswith("__init__.pyc"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
import importlib.util
if importlib.util.find_spec("cython"): import cython; compiled = cython.compiled
else: compiled = False
try: from ._buildinfo import compiled
except ImportError:
if importlib.util.find_spec("cython"): import cython; compiled = cython.compiled
else: compiled = False
LOG_NONE = -1
LOG_CRITICAL = 0
@@ -161,7 +154,6 @@ def log(msg, level=3, _override_destination = False, pt=False):
log("Exception occurred while calling external log handler: "+str(e), LOG_CRITICAL)
log("Dumping future log events to console!", LOG_CRITICAL)
log(msg, level)
def rand():
result = instance_random.random()
@@ -291,7 +283,7 @@ def prettytime(time, verbose=False, compact=False):
if not neg: return tstr
else: return f"-{tstr}"
def prettyshorttime(time, verbose=False, compact=False):
def prettyshorttime(time, verbose=False, compact=False, tight=False):
neg = False
time = time*1e6
if time < 0:
@@ -327,8 +319,8 @@ def prettyshorttime(time, verbose=False, compact=False):
for c in components:
i += 1
if i == 1: pass
elif i < len(components): tstr += ", "
elif i == len(components): tstr += " and "
elif i < len(components): tstr += ", " if not tight else " "
elif i == len(components): tstr += " and " if not tight else " "
tstr += c
@@ -365,20 +357,50 @@ class Profiler:
profilers = {}
tags = {}
# Samples per tag
MAX_CAPTURES = 10000
@staticmethod
def get_profiler(tag=None, super_tag=None):
def get_profiler(tag=None, super_tag=None, max_captures=None):
if tag in Profiler.profilers: return Profiler.profilers[tag]
else:
profiler = Profiler(tag, super_tag)
if max_captures is None: max_captures = Profiler.MAX_CAPTURES
profiler = Profiler(tag, super_tag, max_captures)
Profiler.profilers[tag] = profiler
return profiler
def __init__(self, tag=None, super_tag=None):
@staticmethod
def profile(func=None, *, tag=None, max_captures=None):
"""
Decorator to profile a function. With no arguments, it can be
used as `@RNS.Profiler.profile`, in which case it will use the
qualified name of the function as the profiler tag. It can
also be used as `@RNS.Profiler.profile(tag="prof_tag")` to use
a specific profiler tag.
:param tag: Either a profiler tag as passed to `Profiler.get_profiler(...)` or a `Profiler` object.
:param max_captures: Maximum samples to capture for the specified profiler tag.
"""
if func is None:
return partial(Profiler.profile, tag=tag, max_captures=max_captures)
tag = func.__qualname__ if tag is None else tag
if isinstance(tag, Profiler): profiler = tag
else: profiler = Profiler.get_profiler(tag=tag, max_captures=max_captures)
@wraps(func)
def wrapper(*args, **kwargs):
with profiler:
return func(*args, **kwargs)
return wrapper
def __init__(self, tag=None, super_tag=None, max_captures=None):
self.paused = False
self.pause_time = 0
self.pause_started = None
self.tag = tag
self.super_tag = super_tag
self.max_captures = max_captures if max_captures is not None else Profiler.MAX_CAPTURES
if self.super_tag in Profiler.profilers:
self.super_profiler = Profiler.profilers[self.super_tag]
@@ -396,11 +418,18 @@ class Profiler:
tag = self.tag
super_tag = self.super_tag
thread_ident = threading.get_ident()
if not tag in Profiler.tags: Profiler.tags[tag] = {"threads": {}, "super": super_tag}
if not tag in Profiler.tags: Profiler.tags[tag] = {"threads": {}, "super": super_tag, "captures": deque(maxlen=self.max_captures)}
if not thread_ident in Profiler.tags[tag]["threads"]:
Profiler.tags[tag]["threads"][thread_ident] = {"current_start": None, "captures": []}
Profiler.tags[tag]["threads"][thread_ident] = {"running": deque()}
Profiler.tags[tag]["threads"][thread_ident]["current_start"] = time.perf_counter()
# The tag deque stores a shared reference to the capture, and the end
# time isn't updated until the context manager exits. This leaves the
# deque sorted by start time, except for cases where the thread is
# preemted between getting the current time and appending. We also store
# a stack of start times per thread to support reentrancy.
capture = {"start": time.perf_counter(), "end": None, "thread_ident": thread_ident}
Profiler.tags[tag]["captures"].append(capture)
Profiler.tags[tag]["threads"][thread_ident]["running"].append(capture)
self.resume_super()
def __exit__(self, exc_type, exc_value, traceback):
@@ -410,14 +439,15 @@ class Profiler:
end = time.perf_counter() - self.pause_time
self.pause_time = 0
thread_ident = threading.get_ident()
if tag in Profiler.tags and thread_ident in Profiler.tags[tag]["threads"]:
if Profiler.tags[tag]["threads"][thread_ident]["current_start"] != None:
begin = Profiler.tags[tag]["threads"][thread_ident]["current_start"]
Profiler.tags[tag]["threads"][thread_ident]["current_start"] = None
Profiler.tags[tag]["threads"][thread_ident]["captures"].append(end-begin)
try:
if tag in Profiler.tags and thread_ident in Profiler.tags[tag]["threads"]:
try: capture = Profiler.tags[tag]["threads"][thread_ident]["running"].pop()
except IndexError as e: return
capture["end"] = end
if not Profiler._ran:
Profiler._ran = True
self.resume_super()
finally:
self.resume_super()
def pause(self, pause_started=None):
if not self.paused:
@@ -436,78 +466,153 @@ class Profiler:
@staticmethod
def results():
from statistics import mean, median, stdev
def find_window_start(captures, start_time, hi=None):
hi = len(captures) if hi is None else hi
idx = bisect.bisect_left(captures, start_time, hi=hi, key=lambda c: c["start"])
return idx if len(captures) - idx > 1 else None
# Fast one-pass calculation of summary statistics
def calc_stats(captures, start=0, end=None, key=lambda c: c, threads_key=None):
if end is None: end = len(captures)
while start > 0 and start < len(captures) and start < end and key(captures[start]) is None: start += 1
while end > 0 and end <= len(captures) and start < end and key(captures[end-1]) is None: end -= 1
count = end - start
if count <= 0: return None
elif count == 1:
capture = key(captures[start])
return { "count": 1,
"mean": capture,
"median": capture,
"min": capture,
"max": capture,
"stdev": None,
"sum": capture,
"threads": 1 if threads_key else None}
# Median is approximate if there are any incomplete captures in the
# middle of the range.
med_even = count % 2 == 0
med_idx = start + (count // 2 if med_even else (count - 1) // 2)
while key(captures[med_idx]) is None and med_idx < end: med_idx += 1
if med_idx == end: c_median = None
elif med_even: c_median = key(captures[med_idx])
else:
med_idx2 = med_idx + 1
while key(captures[med_idx2]) is None and med_idx2 < end: med_idx2 += 1
if med_idx2 == end: c_median = None
else:
med_cap1 = key(captures[med_idx])
med_cap2 = key(captures[med_idx+1])
if med_cap1 is None or med_cap2 is None: c_median = None
else: c_median = (med_cap1 + med_cap2) / 2
c_count = 0; c_sum = 0; c_min = key(captures[start]); c_max = key(captures[start]); ck = 0; ck2 = 0
uniq_threads = set()
for idx in range(start, end):
c = key(captures[idx])
if c is None: continue
else: c_count += 1
c_sum += c
if c < c_min: c_min = c
if c > c_max: c_max = c
ck += c - c_median
ck2 += (c - c_median) ** 2
if threads_key: uniq_threads.add(threads_key(captures[idx]))
c_mean = c_sum / c_count if c_count > 0 else None
c_std = math.sqrt((ck2 - (ck ** 2)/c_count) / (c_count - 1)) if c_count > 1 else None
return { "count": c_count,
"mean": c_mean,
"median": c_median,
"min": c_min,
"max": c_max,
"stdev": c_std,
"sum": c_sum,
"threads": len(uniq_threads) if threads_key else None }
def stats_key(capture):
end = capture["end"]
if end is None: return None
else: return end - capture["start"]
results = {}
for tag in Profiler.tags:
tag_captures = []
now = time.perf_counter()
for tag in sorted(Profiler.tags):
tag_entry = Profiler.tags[tag]
for thread_ident in tag_entry["threads"]:
thread_entry = tag_entry["threads"][thread_ident]
thread_captures = thread_entry["captures"]
sample_count = len(thread_captures)
if sample_count > 1:
thread_results = { "count": sample_count,
"mean": mean(thread_captures),
"median": median(thread_captures),
"stdev": stdev(thread_captures) }
elif sample_count == 1:
thread_results = { "count": sample_count,
"mean": mean(thread_captures),
"median": median(thread_captures),
"stdev": None }
tag_captures = sorted(tag_entry["captures"], key=lambda c: c["start"])
tag_captures.extend(thread_captures)
if len(tag_captures):
captures_1m = None; captures_5m = None; captures_30m = None; captures_60m = None
stats_1m = None; stats_5m = None; stats_30m = None; stats_60m = None
sample_count = len(tag_captures)
if sample_count > 1:
tag_results = { "name": tag,
"super": tag_entry["super"],
"count": len(tag_captures),
"mean": mean(tag_captures),
"median": median(tag_captures),
"stdev": stdev(tag_captures) }
elif sample_count == 1:
tag_results = { "name": tag,
"super": tag_entry["super"],
"count": len(tag_captures),
"mean": mean(tag_captures),
"median": median(tag_captures),
"stdev": None }
captures_1m = find_window_start(tag_captures, now - 1*60)
if captures_1m: captures_5m = find_window_start(tag_captures, now - 5*60, hi=captures_1m)
if captures_5m: captures_30m = find_window_start(tag_captures, now - 30*60, hi=captures_5m)
if captures_30m: captures_60m = find_window_start(tag_captures, now - 60*60, hi=captures_30m)
results[tag] = tag_results
stats_all = calc_stats(tag_captures, 0, None, key=stats_key, threads_key=lambda c: c["thread_ident"])
if captures_1m: stats_1m = calc_stats(tag_captures, captures_1m, None, key=stats_key)
if captures_5m: stats_5m = calc_stats(tag_captures, captures_5m, captures_1m, key=stats_key)
if captures_30m: stats_30m = calc_stats(tag_captures, captures_30m, captures_5m, key=stats_key)
if captures_60m: stats_60m = calc_stats(tag_captures, captures_60m, captures_30m, key=stats_key)
if stats_all["count"]:
results[tag] = { "name": tag,
"super": tag_entry["super"],
"stats_all": stats_all,
"stats_1m": stats_1m,
"stats_5m": stats_5m,
"stats_30m": stats_30m,
"stats_60m": stats_60m }
# Yield to avoid bogging down the instance
time.sleep(0.001)
return results
@staticmethod
def format_results(results):
def pst(time):
if time is not None: return prettyshorttime(time, tight=True)
else: return "-----"
def print_results_recursive(tag, results, level=0):
print_tag_results(tag, level+1)
results_str = print_tag_results(tag, level+1) + "\n"
for tag_name in results:
sub_tag = results[tag_name]
if sub_tag["super"] == tag["name"]:
print_results_recursive(sub_tag, results, level=level+1)
results_str += print_results_recursive(sub_tag, results, level=level+1)
return results_str
def print_tag_results(tag, level):
ind = " "*level
name = tag["name"]; count = tag["count"]
mean = tag["mean"]; median = tag["median"]; stdev = tag["stdev"]
print( f"{ind}{name}")
print( f"{ind} Samples : {count}")
if stdev != None:
print(f"{ind} Mean : {prettyshorttime(mean)}")
print(f"{ind} Median : {prettyshorttime(median)}")
print(f"{ind} St.dev. : {prettyshorttime(stdev)}")
print( f"{ind} Total : {prettyshorttime(mean*count)}")
print("")
name = tag["name"]
stats_all = tag["stats_all"]; stats_1m = tag["stats_1m"]; stats_5m = tag["stats_5m"]; stats_30m = tag["stats_30m"]; stats_60m = tag["stats_60m"]
results_str = f" {ind}{name}\n"
results_str += f" {ind} Samples : {stats_all['count']} from {stats_all['threads']} thread{'s' if stats_all['threads'] > 1 else ''}\n"
if stats_all != None:
results_str += f" {ind} {'Mean':^15} | {'Median':^15} | {'Min':^15} | {'Max':^15} | {'St. dev':^15} | {'Total':^15}\n"
results_str += f" {ind} Stats : ({pst(stats_all['mean']):^15} | {pst(stats_all['median']):^15} | {pst(stats_all['min']):^15} | {pst(stats_all['max']):^15} | {pst(stats_all['stdev']):^15} | {pst(stats_all['sum']):^15})\n"
if stats_1m != None:
results_str += f" {ind} 0-1m : ({pst(stats_1m['mean']):^15} | {pst(stats_1m['median']):^15} | {pst(stats_1m['min']):^15} | {pst(stats_1m['max']):^15} | {pst(stats_1m['stdev']):^15} | {pst(stats_1m['sum']):^15})\n"
if stats_5m != None:
results_str += f" {ind} 1-5m : ({pst(stats_5m['mean']):^15} | {pst(stats_5m['median']):^15} | {pst(stats_5m['min']):^15} | {pst(stats_5m['max']):^15} | {pst(stats_5m['stdev']):^15} | {pst(stats_5m['sum']):^15})\n"
if stats_30m != None:
results_str += f" {ind} 5-30m : ({pst(stats_30m['mean']):^15} | {pst(stats_30m['median']):^15} | {pst(stats_30m['min']):^15} | {pst(stats_30m['max']):^15} | {pst(stats_30m['stdev']):^15} | {pst(stats_30m['sum']):^15})\n"
if stats_60m != None:
results_str += f" {ind} 30-60m : ({pst(stats_60m['mean']):^15} | {pst(stats_60m['median']):^15} | {pst(stats_60m['min']):^15} | {pst(stats_60m['max']):^15} | {pst(stats_60m['stdev']):^15} | {pst(stats_60m['sum']):^15})\n"
return results_str
print("\nProfiler results:\n")
results_str = ""
for tag_name in results:
tag = results[tag_name]
if tag["super"] == None:
print_results_recursive(tag, results)
results_str += print_results_recursive(tag, results)
return results_str
profile = Profiler.get_profiler
@@ -557,3 +662,19 @@ def bytes_to_b256(data):
if not type(data) == bytes: raise TypeError("Invalid input data for base256 encode")
try: return [byte_to_b256(c) for c in data]
except Exception as e: raise TypeError(f"Could not encode to base256: {e}")
from .Reticulum import Reticulum
from .Identity import Identity
from .Link import Link, RequestReceipt
from .Channel import MessageBase
from .Buffer import Buffer, RawChannelReader, RawChannelWriter
from .Transport import Transport
from .Discovery import InterfaceAnnouncer
from .Destination import Destination
from .Packet import Packet
from .Packet import PacketReceipt
from .Resolver import Resolver
from .Resource import Resource, ResourceAdvertisement
from .Cryptography import HKDF
from .Cryptography import Hashes
+1 -1
View File
@@ -1 +1 @@
__version__ = "1.5.0"
__version__ = "1.5.2"
+4 -2
View File
@@ -3,5 +3,7 @@ import glob
py_modules = glob.glob(os.path.dirname(__file__)+"/*.py")
pyc_modules = glob.glob(os.path.dirname(__file__)+"/*.pyc")
modules = py_modules+pyc_modules
__all__ = list(set([os.path.basename(f).replace(".pyc", "").replace(".py", "") for f in modules if not (f.endswith("__init__.py") or f.endswith("__init__.pyc"))]))
so_modules = glob.glob(os.path.dirname(__file__)+"/*.so")
pyd_modules = glob.glob(os.path.dirname(__file__)+"/*.pyd")
modules = py_modules+pyc_modules+so_modules+pyd_modules
__all__ = list(set([os.path.basename(f).split(".")[0] for f in modules if not os.path.basename(f).split(".")[0] == "__init__"]))
+16 -217
View File
@@ -2,7 +2,7 @@
# https://github.com/vsergeev/u-msgpack-python
#
# u-msgpack-python is a lightweight MessagePack serializer and deserializer
# module, compatible with both Python 2 and 3, as well CPython and PyPy
# module, compatible with Python 3, as well CPython and PyPy
# implementations of Python. u-msgpack-python is fully compliant with the
# latest MessagePack specification.com/msgpack/msgpack/blob/master/spec.md). In
# particular, it supports the new binary, UTF-8 string, and application ext
@@ -35,7 +35,7 @@ u-msgpack-python v2.7.1 - v at sergeev.io
https://github.com/vsergeev/u-msgpack-python
u-msgpack-python is a lightweight MessagePack serializer and deserializer
module, compatible with both Python 2 and 3, as well CPython and PyPy
module, compatible with Python 3, as well CPython and PyPy
implementations of Python. u-msgpack-python is fully compliant with the
latest MessagePack specification.com/msgpack/msgpack/blob/master/spec.md). In
particular, it supports the new binary, UTF-8 string, and application ext
@@ -49,10 +49,7 @@ import datetime
import sys
import io
if sys.version_info[0:2] >= (3, 3):
from collections.abc import Hashable
else:
from collections import Hashable
from collections.abc import Hashable
__version__ = "2.7.1"
"Module version string"
@@ -104,8 +101,6 @@ class Ext(object):
# Check data is type bytes or str
elif sys.version_info[0] == 3 and not isinstance(data, bytes):
raise TypeError("ext data is not type \'bytes\'")
elif sys.version_info[0] == 2 and not isinstance(data, str):
raise TypeError("ext data is not type \'str\'")
self.type = type
self.data = data
@@ -129,7 +124,7 @@ class Ext(object):
"""
s = "Ext Object (Type: {:d}, Data: ".format(self.type)
s += " ".join(["0x{:02}".format(ord(self.data[i:i + 1]))
for i in xrange(min(len(self.data), 8))])
for i in range(min(len(self.data), 8))])
if len(self.data) > 8:
s += " ..."
s += ")"
@@ -452,94 +447,6 @@ def _pack_map(obj, fp, options):
########################################
# Pack for Python 2, with 'unicode' type, 'str' type, and 'long' type
def _pack2(obj, fp, **options):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
fp: a .write()-supporting file-like object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
to a callable that packs an instance of the type
into an Ext object
force_float_precision (str): "single" to force packing floats as
IEEE-754 single-precision floats,
"double" to force packing floats as
IEEE-754 double-precision floats.
Returns:
None.
Raises:
UnsupportedType(PackException):
Object type not supported for packing.
Example:
>>> f = open('test.bin', 'wb')
>>> umsgpack.pack({u"compact": True, u"schema": 0}, f)
>>>
"""
global compatibility
ext_handlers = options.get("ext_handlers")
if obj is None:
_pack_nil(obj, fp, options)
elif ext_handlers and obj.__class__ in ext_handlers:
_pack_ext(ext_handlers[obj.__class__](obj), fp, options)
elif obj.__class__ in _ext_class_to_type:
try:
_pack_ext(Ext(_ext_class_to_type[obj.__class__], obj.packb()), fp, options)
except AttributeError:
raise NotImplementedError("Ext serializable class {:s} is missing implementation of packb()".format(repr(obj.__class__)))
elif isinstance(obj, bool):
_pack_boolean(obj, fp, options)
elif isinstance(obj, (int, long)):
_pack_integer(obj, fp, options)
elif isinstance(obj, float):
_pack_float(obj, fp, options)
elif compatibility and isinstance(obj, unicode):
_pack_oldspec_raw(bytes(obj), fp, options)
elif compatibility and isinstance(obj, bytes):
_pack_oldspec_raw(obj, fp, options)
elif isinstance(obj, unicode):
_pack_string(obj, fp, options)
elif isinstance(obj, str):
_pack_binary(obj, fp, options)
elif isinstance(obj, (list, tuple)):
_pack_array(obj, fp, options)
elif isinstance(obj, dict):
_pack_map(obj, fp, options)
elif isinstance(obj, datetime.datetime):
_pack_ext_timestamp(obj, fp, options)
elif isinstance(obj, Ext):
_pack_ext(obj, fp, options)
elif ext_handlers:
# Linear search for superclass
t = next((t for t in ext_handlers.keys() if isinstance(obj, t)), None)
if t:
_pack_ext(ext_handlers[t](obj), fp, options)
else:
raise UnsupportedTypeException(
"unsupported type: {:s}".format(str(type(obj))))
elif _ext_class_to_type:
# Linear search for superclass
t = next((t for t in _ext_class_to_type if isinstance(obj, t)), None)
if t:
try:
_pack_ext(Ext(_ext_class_to_type[t], obj.packb()), fp, options)
except AttributeError:
raise NotImplementedError("Ext serializable class {:s} is missing implementation of packb()".format(repr(t)))
else:
raise UnsupportedTypeException("unsupported type: {:s}".format(str(type(obj))))
else:
raise UnsupportedTypeException("unsupported type: {:s}".format(str(type(obj))))
# Pack for Python 3, with unicode 'str' type, 'bytes' type, and no 'long' type
def _pack3(obj, fp, **options):
"""
@@ -627,40 +534,6 @@ def _pack3(obj, fp, **options):
raise UnsupportedTypeException(
"unsupported type: {:s}".format(str(type(obj))))
def _packb2(obj, **options):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
to a callable that packs an instance of the type
into an Ext object
force_float_precision (str): "single" to force packing floats as
IEEE-754 single-precision floats,
"double" to force packing floats as
IEEE-754 double-precision floats.
Returns:
A 'str' containing serialized MessagePack bytes.
Raises:
UnsupportedType(PackException):
Object type not supported for packing.
Example:
>>> umsgpack.packb({u"compact": True, u"schema": 0})
'\x82\xa7compact\xc3\xa6schema\x00'
>>>
"""
fp = io.BytesIO()
_pack2(obj, fp, **options)
return fp.getvalue()
def _packb3(obj, **options):
"""
Serialize a Python object into MessagePack bytes.
@@ -885,9 +758,9 @@ def _unpack_array(code, fp, options):
raise Exception("logic error, not array: 0x{:02x}".format(ord(code)))
if options.get('use_tuple'):
return tuple((_unpack(fp, options) for i in xrange(length)))
return tuple((_unpack(fp, options) for i in range(length)))
return [_unpack(fp, options) for i in xrange(length)]
return [_unpack(fp, options) for i in range(length)]
def _deep_list_to_tuple(obj):
@@ -907,7 +780,7 @@ def _unpack_map(code, fp, options):
raise Exception("logic error, not map: 0x{:02x}".format(ord(code)))
d = {} if not options.get('use_ordered_dict') else collections.OrderedDict()
for _ in xrange(length):
for _ in range(length):
# Unpack key
k = _unpack(fp, options)
@@ -938,53 +811,6 @@ def _unpack(fp, options):
########################################
def _unpack2(fp, **options):
"""
Deserialize MessagePack bytes into a Python object.
Args:
fp: a .read()-supporting file-like object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping integer Ext
type to a callable that unpacks an instance of
Ext into an object
use_ordered_dict (bool): unpack maps into OrderedDict, instead of
unordered dict (default False)
use_tuple (bool): unpacks arrays into tuples, instead of lists (default
False)
allow_invalid_utf8 (bool): unpack invalid strings into instances of
InvalidString, for access to the bytes
(default False)
Returns:
A Python object.
Raises:
InsufficientDataException(UnpackException):
Insufficient data to unpack the serialized object.
InvalidStringException(UnpackException):
Invalid UTF-8 string encountered during unpacking.
UnsupportedTimestampException(UnpackException):
Unsupported timestamp format encountered during unpacking.
ReservedCodeException(UnpackException):
Reserved code encountered during unpacking.
UnhashableKeyException(UnpackException):
Unhashable key encountered during map unpacking.
The serialized map cannot be deserialized into a Python dictionary.
DuplicateKeyException(UnpackException):
Duplicate key encountered during map unpacking.
Example:
>>> f = open('test.bin', 'rb')
>>> umsgpack.unpackb(f)
{u'compact': True, u'schema': 0}
>>>
"""
return _unpack(fp, options)
def _unpack3(fp, **options):
"""
Deserialize MessagePack bytes into a Python object.
@@ -1149,27 +975,11 @@ def __init():
global _utc_tzinfo
global _float_precision
global _unpack_dispatch_table
global xrange
# Compatibility mode for handling strings/bytes with the old specification
compatibility = False
if sys.version_info[0] == 3:
_utc_tzinfo = datetime.timezone.utc
else:
class UTC(datetime.tzinfo):
ZERO = datetime.timedelta(0)
def utcoffset(self, dt):
return UTC.ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return UTC.ZERO
_utc_tzinfo = UTC()
_utc_tzinfo = datetime.timezone.utc
# Calculate an aware epoch datetime
_epoch = datetime.datetime(1970, 1, 1, tzinfo=_utc_tzinfo)
@@ -1181,25 +991,14 @@ def __init():
_float_precision = "single"
# Map packb and unpackb to the appropriate version
if sys.version_info[0] == 3:
pack = _pack3
packb = _packb3
dump = _pack3
dumps = _packb3
unpack = _unpack3
unpackb = _unpackb3
load = _unpack3
loads = _unpackb3
xrange = range
else:
pack = _pack2
packb = _packb2
dump = _pack2
dumps = _packb2
unpack = _unpack2
unpackb = _unpackb2
load = _unpack2
loads = _unpackb2
pack = _pack3
packb = _packb3
dump = _pack3
dumps = _packb3
unpack = _unpack3
unpackb = _unpackb3
load = _unpack3
loads = _unpackb3
# Build a dispatch table for fast lookup of unpacking function
+1 -1
View File
@@ -1,4 +1,4 @@
# Sphinx build info version 1
# This file records the configuration used when building these files. When it is not found, a full rebuild will be done.
config: e9bf292f6fd8e17bc5dda6fda8e6c07e
config: 3b25ffffee9a87e66aaacb67b195a708
tags: 645f666f9bcd5a90fca523b33c5a78b7
+7 -7
View File
@@ -1589,15 +1589,15 @@ Reticulum uses separate, prioritized queues for processing inbound packets. The
You can tune the queue sizes from the defaults, for example if you're running a setup where you want to simply drop most traffic from ingress-limited interfaces. The queue sizes are configured in the ``[reticulum]`` section of the config
* | The ``qlen_in_data`` option sets the maximum size of the data
queue. Defaults to ``4096``.
queue. Defaults to ``1024``.
* | The ``qlen_in_announce`` option sets the maximum size of the announce
queue. Defaults to ``256``.
* | The ``qlen_in_pr`` option sets the maximum size of the path request
queue. Defaults to ``256``.
* | The ``qlen_in_il`` option sets the maximum size of the ingress limiter
queue. Defaults to ``128``.
* | The ``qlen_in_pr`` option sets the maximum size of the path request
queue. Defaults to ``128``.
* | The ``qlen_in_il`` option sets the maximum size of the ingress limiter
queue. Defaults to ``8``.
If an inbound packet arrives and its target queue is full, the packet is dropped. Reticulum will always completely drain higher-priority queues before starting to drain a lower-priority one. As an example, the ingress limiter queue will only start draining once all other queues are empty.
+1 -1
View File
@@ -1,5 +1,5 @@
const DOCUMENTATION_OPTIONS = {
VERSION: '1.5.0',
VERSION: '1.5.2',
LANGUAGE: 'en',
COLLAPSE_INDEX: false,
BUILDER: 'html',
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Distributed Development - Reticulum Network Stack 1.5.0 documentation</title>
<title>Distributed Development - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -431,7 +431,7 @@
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Code Examples - Reticulum Network Stack 1.5.0 documentation</title>
<title>Code Examples - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -3648,7 +3648,7 @@
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>An Explanation of Reticulum for Human Beings - Reticulum Network Stack 1.5.0 documentation</title>
<title>An Explanation of Reticulum for Human Beings - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -296,7 +296,7 @@
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -5,7 +5,7 @@
<meta name="color-scheme" content="light dark"><link rel="index" title="Index" href="#"><link rel="search" title="Search" href="search.html">
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 --><title>Index - Reticulum Network Stack 1.5.0 documentation</title>
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 --><title>Index - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -178,7 +178,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -202,7 +202,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -856,7 +856,7 @@
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Getting Started Fast - Reticulum Network Stack 1.5.0 documentation</title>
<title>Getting Started Fast - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -776,7 +776,7 @@ section of this manual.</p>
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Git Over Reticulum - Reticulum Network Stack 1.5.0 documentation</title>
<title>Git Over Reticulum - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -1594,7 +1594,7 @@ done
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Communications Hardware - Reticulum Network Stack 1.5.0 documentation</title>
<title>Communications Hardware - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -676,7 +676,7 @@ can be used with Reticulum. This includes virtual software modems such as
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Reticulum Network Stack 1.5.0 documentation</title>
<title>Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="#"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="#"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -721,7 +721,7 @@ to participate in the development of Reticulum itself.</p>
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+8 -8
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Configuring Interfaces - Reticulum Network Stack 1.5.0 documentation</title>
<title>Configuring Interfaces - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -1786,22 +1786,22 @@ interface basis under the relevant interface configuration section.</p>
<div><ul>
<li><div class="line-block">
<div class="line">The <code class="docutils literal notranslate"><span class="pre">qlen_in_data</span></code> option sets the maximum size of the data
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">4096</span></code>.</div>
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">1024</span></code>.</div>
</div>
</li>
<li><div class="line-block">
<div class="line">The <code class="docutils literal notranslate"><span class="pre">qlen_in_announce</span></code> option sets the maximum size of the announce
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">256</span></code>.</div>
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">128</span></code>.</div>
</div>
</li>
<li><div class="line-block">
<div class="line">The <code class="docutils literal notranslate"><span class="pre">qlen_in_pr</span></code> option sets the maximum size of the path request
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">256</span></code>.</div>
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">128</span></code>.</div>
</div>
</li>
<li><div class="line-block">
<div class="line">The <code class="docutils literal notranslate"><span class="pre">qlen_in_il</span></code> option sets the maximum size of the ingress limiter
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">128</span></code>.</div>
queue. Defaults to <code class="docutils literal notranslate"><span class="pre">8</span></code>.</div>
</div>
</li>
</ul>
@@ -1908,7 +1908,7 @@ queue. Defaults to <code class="docutils literal notranslate"><span class="pre">
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Reticulum License - Reticulum Network Stack 1.5.0 documentation</title>
<title>Reticulum License - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -345,7 +345,7 @@ SOFTWARE.
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Building Networks - Reticulum Network Stack 1.5.0 documentation</title>
<title>Building Networks - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -664,7 +664,7 @@ differently than a mobile device roaming between radio cells.</p>
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
Binary file not shown.
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>API Reference - Reticulum Network Stack 1.5.0 documentation</title>
<title>API Reference - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -2588,7 +2588,7 @@ will announce it.</p>
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -8,7 +8,7 @@
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<meta name="robots" content="noindex" />
<title>Search - Reticulum Network Stack 1.5.0 documentation</title><link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<title>Search - Reticulum Network Stack 1.5.2 documentation</title><link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo-extensions.css?v=8dab3a3b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="#" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -304,7 +304,7 @@
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+1 -1
View File
@@ -1 +1 @@
Search.setIndex({"alltitles":{"A Carrier-Grade Fallacy":[[16,"a-carrier-grade-fallacy"]],"API Reference":[[10,null]],"ARM64":[[3,"arm64"]],"AX.25 KISS Interface":[[7,"ax-25-kiss-interface"]],"Accessing Repository Pages":[[4,"accessing-repository-pages"]],"Adding Radio Interfaces":[[3,"adding-radio-interfaces"]],"An Explanation of Reticulum for Human Beings":[[2,null]],"Anchor In The Flow":[[16,"anchor-in-the-flow"]],"Android":[[3,"android"]],"Announce":[[1,"announce"]],"Announce Propagation Rules":[[13,"announce-propagation-rules"]],"Announce Rate Control":[[7,"announce-rate-control"]],"Announcing Presence":[[16,"announcing-presence"]],"Artifact-Centered Workflows":[[0,"artifact-centered-workflows"]],"Author Identity Binding":[[4,"author-identity-binding"]],"Auto Interface":[[7,"auto-interface"]],"Automated Blocking":[[7,"automated-blocking"]],"Automated List Sourcing":[[14,"automated-list-sourcing"]],"Automatic Mirror Synchronization":[[4,"automatic-mirror-synchronization"]],"Backbone Interface":[[7,"backbone-interface"]],"Blackhole Management":[[14,"blackhole-management"]],"Bootstrapping Connectivity":[[3,"bootstrapping-connectivity"]],"Broadcast":[[1,"broadcast"]],"Buffer":[[1,"buffer"]],"Build Personal Infrastructure":[[3,"build-personal-infrastructure"]],"Building Networks":[[9,null]],"Channel":[[1,"channel"]],"Code Examples":[[1,null]],"Combining Hardware Types":[[5,"combining-hardware-types"]],"Command-Line Interaction":[[4,"command-line-interaction"]],"Commit Signing":[[4,"commit-signing"]],"Common Interface Options":[[7,"common-interface-options"]],"Communications Hardware":[[5,null]],"Composable Primitives":[[0,"composable-primitives"]],"Concepts & Overview":[[9,"concepts-overview"]],"Conceptual Overview":[[13,"conceptual-overview"]],"Configuration":[[4,"configuration"],[4,"id1"]],"Configuration & Data":[[14,"configuration-data"]],"Configuration Example":[[4,"configuration-example"]],"Configuration Methods":[[4,"configuration-methods"]],"Configuring Interfaces":[[7,null]],"Connect to the Distributed Backbone":[[3,"connect-to-the-distributed-backbone"]],"Connecting Remotes":[[7,"connecting-remotes"]],"Connecting Reticulum Instances Over the Internet":[[3,"connecting-reticulum-instances-over-the-internet"]],"Contributing to the Global Ret":[[3,"contributing-to-the-global-ret"]],"Cost Of A Byte":[[16,"cost-of-a-byte"]],"Creating Empty Repositories":[[4,"creating-empty-repositories"]],"Creating RNodes":[[5,"creating-rnodes"]],"Creating Signed Releases":[[4,"creating-signed-releases"]],"Creating a Network With Reticulum":[[3,"creating-a-network-with-reticulum"]],"Creating and Using Custom Interfaces":[[3,"creating-and-using-custom-interfaces"]],"Creating and Using a Network Identity":[[13,"creating-and-using-a-network-identity"]],"Creator Permissions":[[4,"creator-permissions"]],"Cryptographic Attribution":[[4,"cryptographic-attribution"]],"Cryptographic Primitives":[[13,"cryptographic-primitives"]],"Current Status":[[15,"current-status"]],"Current Usage":[[13,"current-usage"]],"Custom Interfaces":[[1,"custom-interfaces"],[7,"custom-interfaces"]],"Customizing Templates":[[4,"customizing-templates"]],"Death To The Address":[[16,"death-to-the-address"]],"Debian Bookworm":[[3,"debian-bookworm"]],"Decentralization Or Uncentralizability?":[[16,"decentralization-or-uncentralizability"]],"Design Patterns For Post-IP Systems":[[16,"design-patterns-for-post-ip-systems"]],"Destination Naming":[[13,"destination-naming"]],"Destinations":[[13,"destinations"]],"Destinations, Not Addresses":[[9,"destinations-not-addresses"]],"Develop a Program with Reticulum":[[3,"develop-a-program-with-reticulum"]],"Discoverable Interfaces":[[7,"discoverable-interfaces"]],"Discovering Interfaces":[[14,"discovering-interfaces"]],"Discovery Parameters":[[7,"discovery-parameters"]],"Distributed Development":[[0,null]],"Distribution Without Intermediaries":[[0,"distribution-without-intermediaries"]],"Donations":[[12,"donations"]],"Echo":[[1,"echo"]],"Emergent Patterns":[[16,"emergent-patterns"]],"Enabling Discovery":[[7,"enabling-discovery"]],"Enabling the Git Page Node":[[4,"enabling-the-git-page-node"]],"Encryption Is Not A Feature":[[16,"encryption-is-not-a-feature"]],"Ethernet-based Hardware":[[5,"ethernet-based-hardware"]],"Ethics Of The Tool":[[16,"ethics-of-the-tool"]],"Example Configuration":[[7,"example-configuration"]],"Fabric Of The Independent":[[16,"fabric-of-the-independent"]],"Fallacy Of The Cloud":[[16,"fallacy-of-the-cloud"]],"Filetransfer":[[1,"filetransfer"]],"Finding Your Way":[[3,"finding-your-way"]],"Fixed Serial Port Names":[[14,"fixed-serial-port-names"]],"Flow & Time":[[16,"flow-time"]],"Forking Repositories":[[4,"forking-repositories"]],"Formatting & Syntax Highlighting":[[4,"formatting-syntax-highlighting"]],"Future Implications":[[13,"future-implications"]],"Getting Further":[[13,"getting-further"]],"Getting Started Fast":[[3,null]],"Git Configuration Parameters":[[4,"git-configuration-parameters"]],"Git OveLine truncated
Search.setIndex({"alltitles":{"A Carrier-Grade Fallacy":[[16,"a-carrier-grade-fallacy"]],"API Reference":[[10,null]],"ARM64":[[3,"arm64"]],"AX.25 KISS Interface":[[7,"ax-25-kiss-interface"]],"Accessing Repository Pages":[[4,"accessing-repository-pages"]],"Adding Radio Interfaces":[[3,"adding-radio-interfaces"]],"An Explanation of Reticulum for Human Beings":[[2,null]],"Anchor In The Flow":[[16,"anchor-in-the-flow"]],"Android":[[3,"android"]],"Announce":[[1,"announce"]],"Announce Propagation Rules":[[13,"announce-propagation-rules"]],"Announce Rate Control":[[7,"announce-rate-control"]],"Announcing Presence":[[16,"announcing-presence"]],"Artifact-Centered Workflows":[[0,"artifact-centered-workflows"]],"Author Identity Binding":[[4,"author-identity-binding"]],"Auto Interface":[[7,"auto-interface"]],"Automated Blocking":[[7,"automated-blocking"]],"Automated List Sourcing":[[14,"automated-list-sourcing"]],"Automatic Mirror Synchronization":[[4,"automatic-mirror-synchronization"]],"Backbone Interface":[[7,"backbone-interface"]],"Blackhole Management":[[14,"blackhole-management"]],"Bootstrapping Connectivity":[[3,"bootstrapping-connectivity"]],"Broadcast":[[1,"broadcast"]],"Buffer":[[1,"buffer"]],"Build Personal Infrastructure":[[3,"build-personal-infrastructure"]],"Building Networks":[[9,null]],"Channel":[[1,"channel"]],"Code Examples":[[1,null]],"Combining Hardware Types":[[5,"combining-hardware-types"]],"Command-Line Interaction":[[4,"command-line-interaction"]],"Commit Signing":[[4,"commit-signing"]],"Common Interface Options":[[7,"common-interface-options"]],"Communications Hardware":[[5,null]],"Composable Primitives":[[0,"composable-primitives"]],"Concepts & Overview":[[9,"concepts-overview"]],"Conceptual Overview":[[13,"conceptual-overview"]],"Configuration":[[4,"configuration"],[4,"id1"]],"Configuration & Data":[[14,"configuration-data"]],"Configuration Example":[[4,"configuration-example"]],"Configuration Methods":[[4,"configuration-methods"]],"Configuring Interfaces":[[7,null]],"Connect to the Distributed Backbone":[[3,"connect-to-the-distributed-backbone"]],"Connecting Remotes":[[7,"connecting-remotes"]],"Connecting Reticulum Instances Over the Internet":[[3,"connecting-reticulum-instances-over-the-internet"]],"Contributing to the Global Ret":[[3,"contributing-to-the-global-ret"]],"Cost Of A Byte":[[16,"cost-of-a-byte"]],"Creating Empty Repositories":[[4,"creating-empty-repositories"]],"Creating RNodes":[[5,"creating-rnodes"]],"Creating Signed Releases":[[4,"creating-signed-releases"]],"Creating a Network With Reticulum":[[3,"creating-a-network-with-reticulum"]],"Creating and Using Custom Interfaces":[[3,"creating-and-using-custom-interfaces"]],"Creating and Using a Network Identity":[[13,"creating-and-using-a-network-identity"]],"Creator Permissions":[[4,"creator-permissions"]],"Cryptographic Attribution":[[4,"cryptographic-attribution"]],"Cryptographic Primitives":[[13,"cryptographic-primitives"]],"Current Status":[[15,"current-status"]],"Current Usage":[[13,"current-usage"]],"Custom Interfaces":[[1,"custom-interfaces"],[7,"custom-interfaces"]],"Customizing Templates":[[4,"customizing-templates"]],"Death To The Address":[[16,"death-to-the-address"]],"Debian Bookworm":[[3,"debian-bookworm"]],"Decentralization Or Uncentralizability?":[[16,"decentralization-or-uncentralizability"]],"Design Patterns For Post-IP Systems":[[16,"design-patterns-for-post-ip-systems"]],"Destination Naming":[[13,"destination-naming"]],"Destinations":[[13,"destinations"]],"Destinations, Not Addresses":[[9,"destinations-not-addresses"]],"Develop a Program with Reticulum":[[3,"develop-a-program-with-reticulum"]],"Discoverable Interfaces":[[7,"discoverable-interfaces"]],"Discovering Interfaces":[[14,"discovering-interfaces"]],"Discovery Parameters":[[7,"discovery-parameters"]],"Distributed Development":[[0,null]],"Distribution Without Intermediaries":[[0,"distribution-without-intermediaries"]],"Donations":[[12,"donations"]],"Echo":[[1,"echo"]],"Emergent Patterns":[[16,"emergent-patterns"]],"Enabling Discovery":[[7,"enabling-discovery"]],"Enabling the Git Page Node":[[4,"enabling-the-git-page-node"]],"Encryption Is Not A Feature":[[16,"encryption-is-not-a-feature"]],"Ethernet-based Hardware":[[5,"ethernet-based-hardware"]],"Ethics Of The Tool":[[16,"ethics-of-the-tool"]],"Example Configuration":[[7,"example-configuration"]],"Fabric Of The Independent":[[16,"fabric-of-the-independent"]],"Fallacy Of The Cloud":[[16,"fallacy-of-the-cloud"]],"Filetransfer":[[1,"filetransfer"]],"Finding Your Way":[[3,"finding-your-way"]],"Fixed Serial Port Names":[[14,"fixed-serial-port-names"]],"Flow & Time":[[16,"flow-time"]],"Forking Repositories":[[4,"forking-repositories"]],"Formatting & Syntax Highlighting":[[4,"formatting-syntax-highlighting"]],"Future Implications":[[13,"future-implications"]],"Getting Further":[[13,"getting-further"]],"Getting Started Fast":[[3,null]],"Git Configuration Parameters":[[4,"git-configuration-parameters"]],"Git OveLine truncated
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Programs Using Reticulum - Reticulum Network Stack 1.5.0 documentation</title>
<title>Programs Using Reticulum - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -513,7 +513,7 @@ plugin system for expandability.</p>
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Support Reticulum - Reticulum Network Stack 1.5.0 documentation</title>
<title>Support Reticulum - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -383,7 +383,7 @@ circumstances, so we rely on old-fashioned human feedback.</p>
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Understanding Reticulum - Reticulum Network Stack 1.5.0 documentation</title>
<title>Understanding Reticulum - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -1119,7 +1119,7 @@ those risks are acceptable to you.</p>
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Using Reticulum on Your System - Reticulum Network Stack 1.5.0 documentation</title>
<title>Using Reticulum on Your System - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -1644,7 +1644,7 @@ systemctl --user enable rnsd.service
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>What is Reticulum? - Reticulum Network Stack 1.5.0 documentation</title>
<title>What is Reticulum? - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -505,7 +505,7 @@ network, and vice versa.</p>
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -7,7 +7,7 @@
<link rel="prefetch" href="_static/rns_logo_512.png" as="image">
<!-- Generated with Sphinx 8.2.3 and Furo 2025.09.25.dev1 -->
<title>Zen of Reticulum - Reticulum Network Stack 1.5.0 documentation</title>
<title>Zen of Reticulum - Reticulum Network Stack 1.5.2 documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css?v=d111a655" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?v=580074bf" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css?v=76b2166b" />
@@ -180,7 +180,7 @@
</label>
</div>
<div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.0 documentation</div></a>
<a href="index.html"><div class="brand">Reticulum Network Stack 1.5.2 documentation</div></a>
</div>
<div class="header-right">
<div class="theme-toggle-container theme-toggle-header">
@@ -204,7 +204,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.0 documentation</span>
<span class="sidebar-brand-text">Reticulum Network Stack 1.5.2 documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -677,7 +677,7 @@ Imagine a messaging app. You write it once. It works on a laptop connected to fi
</aside>
</div>
</div><script src="_static/documentation_options.js?v=e0a75244"></script>
</div><script src="_static/documentation_options.js?v=73275c37"></script>
<script src="_static/doctools.js?v=9bcbadda"></script>
<script src="_static/sphinx_highlight.js?v=dc90522c"></script>
<script src="_static/scripts/furo.js?v=46bd48cc"></script>
+4 -4
View File
@@ -1501,16 +1501,16 @@ Reticulum uses separate, prioritized queues for processing inbound packets. The
You can tune the queue sizes from the defaults, for example if you’re running a setup where you want to simply drop most traffic from ingress-limited interfaces. The queue sizes are configured in the `[reticulum]` section of the config
> * The `qlen_in_data` option sets the maximum size of the data
> queue. Defaults to `4096`.
> queue. Defaults to `1024`.
>
> * The `qlen_in_announce` option sets the maximum size of the announce
> queue. Defaults to `256`.
> queue. Defaults to `128`.
>
> * The `qlen_in_pr` option sets the maximum size of the path request
> queue. Defaults to `256`.
> queue. Defaults to `128`.
>
> * The `qlen_in_il` option sets the maximum size of the ingress limiter
> queue. Defaults to `128`.
> queue. Defaults to `8`.
>
If an inbound packet arrives and its target queue is full, the packet is dropped. Reticulum will always completely drain higher-priority queues before starting to drain a lower-priority one. As an example, the ingress limiter queue will only start draining once all other queues are empty.
+7 -7
View File
@@ -1589,15 +1589,15 @@ Reticulum uses separate, prioritized queues for processing inbound packets. The
You can tune the queue sizes from the defaults, for example if you're running a setup where you want to simply drop most traffic from ingress-limited interfaces. The queue sizes are configured in the ``[reticulum]`` section of the config
* | The ``qlen_in_data`` option sets the maximum size of the data
queue. Defaults to ``4096``.
queue. Defaults to ``1024``.
* | The ``qlen_in_announce`` option sets the maximum size of the announce
queue. Defaults to ``256``.
* | The ``qlen_in_pr`` option sets the maximum size of the path request
queue. Defaults to ``256``.
* | The ``qlen_in_il`` option sets the maximum size of the ingress limiter
queue. Defaults to ``128``.
* | The ``qlen_in_pr`` option sets the maximum size of the path request
queue. Defaults to ``128``.
* | The ``qlen_in_il`` option sets the maximum size of the ingress limiter
queue. Defaults to ``8``.
If an inbound packet arrives and its target queue is full, the packet is dropped. Reticulum will always completely drain higher-priority queues before starting to drain a lower-priority one. As an example, the ingress limiter queue will only start draining once all other queues are empty.
+148 -21
View File
@@ -1,7 +1,11 @@
import setuptools
import sys
import os
import shutil
import subprocess
pure_python = False
native_build = False
pure_notice = "\n\n**Warning!** *This package is the zero-dependency version of Reticulum. You should almost certainly use the [normal package](https://pypi.org/project/rns) instead. Do NOT install this package unless you know exactly why you are doing it!*"
if '--pure' in sys.argv:
@@ -9,6 +13,11 @@ if '--pure' in sys.argv:
sys.argv.remove('--pure')
print("Building pure-python wheel")
if '--native' in sys.argv:
native_build = True
sys.argv.remove('--native')
print("Building native (compiled) wheel")
exec(open("RNS/_version.py", "r").read())
with open("README.md", "r") as fh:
long_description = fh.read()
@@ -26,6 +35,126 @@ else:
requirements = ['cryptography>=3.4.7', 'pyserial>=3.5']
excluded_modules = ["tests.*", "tests"]
DIRECTIVES = { "annotation_typing": False }
NATIVE_EXCLUDES = { "RNS.Interfaces.AX25KISSInterface",
"RNS.Interfaces.I2PInterface",
"RNS.Interfaces.KISSInterface",
"RNS.Interfaces.RNodeInterface",
"RNS.Interfaces.RNodeMultiInterface",
"RNS.Interfaces.SerialInterface",
"RNS.Interfaces.WeaveInterface",
"RNS.Utilities.rngit.client",
"RNS.Utilities.rngit.commitsigs",
"RNS.Utilities.rngit.highlight",
"RNS.Utilities.rngit.main",
"RNS.Utilities.rngit.pages",
"RNS.Utilities.rngit.server",
"RNS.Utilities.rngit.util",
"RNS.Utilities.rnsh._version",
"RNS.Utilities.rnsh.args",
"RNS.Utilities.rnsh.exception",
"RNS.Utilities.rnsh.helpers",
"RNS.Utilities.rnsh.initiator",
"RNS.Utilities.rnsh.listener",
"RNS.Utilities.rnsh.loop",
"RNS.Utilities.rnsh.process",
"RNS.Utilities.rnsh.protocol",
"RNS.Utilities.rnsh.retry",
"RNS.Utilities.rnsh.rnsh",
"RNS.Utilities.rnsh.session",
"RNS.Utilities.rnsd",
"RNS.Utilities.rncp",
"RNS.Utilities.rnid",
"RNS.Utilities.rnir",
"RNS.Utilities.rnodeconf",
"RNS.Utilities.rnpath",
"RNS.Utilities.rnprobe",
"RNS.Utilities.rnpkg",
"RNS.Utilities.rnstatus",
"RNS.Utilities.rnx",
"RNS._version" }
ext_modules = []
compiled_modules = set()
build_cmdclass = {}
from setuptools.command.build_ext import build_ext as _build_ext
from setuptools.command.build_py import build_py as _build_py
if native_build:
from setuptools import Extension
from Cython.Build import cythonize
native_opt = os.environ.get("RNS_NATIVE_OPT", "-O3")
if sys.platform == "win32": native_cargs = []
else: native_cargs = [native_opt, "-g0", "-fno-lto"]
rns_root = "RNS"
for root, dirs, files in os.walk(rns_root):
dirs[:] = [d for d in dirs if d != "__pycache__"]
for fn in files:
if not fn.endswith(".py"): continue
if fn == "__init__.py": continue
path = os.path.join(root, fn).replace(os.sep, "/")
if path.startswith("RNS/vendor/i2plib/"): continue
if path == "RNS/vendor/configobj.py": continue
modname = path[:-3].replace("/", ".")
if modname in NATIVE_EXCLUDES: continue
compiled_modules.add(modname)
ext_modules.append(Extension(modname, [path], extra_compile_args=list(native_cargs)))
ext_modules = cythonize(ext_modules, language_level=3, compiler_directives=DIRECTIVES)
if pure_python: print("Warning: --pure is ignored when building --native")
# Exclude the CRNS development shim from built wheels
excluded_modules += ["CRNS", "CRNS.*"]
# Trim superfluous symbol tables
class NativeBuildExt(_build_ext):
def run(self):
super().run()
if sys.platform == "win32": return
strip = shutil.which("strip")
if strip is None: return
for output in self.get_outputs():
if output.endswith((".so", ".pyd")):
try:
if sys.platform == "darwin": subprocess.run([strip, "-x", output], check=True)
else: subprocess.run([strip, "--strip-unneeded", output], check=True)
except Exception: pass
# Exclude sources of files that were compiled
# to an so, and inject build info.
class NativeBuildPy(_build_py):
def run(self):
super().run()
if native_build: self._write_buildinfo()
def find_package_modules(self, package, package_dir):
modules = super().find_package_modules(package, package_dir)
if native_build:
modules = [ (pkg, mod, fname) for (pkg, mod, fname) in modules
if (pkg + "." + mod) not in compiled_modules ]
return modules
def get_outputs(self, include_bytecode=True):
outputs = super().get_outputs(include_bytecode)
if native_build: outputs.append(self._buildinfo_path())
return outputs
def _buildinfo_path(self):
return os.path.join(self.build_lib, "RNS", "_buildinfo.py")
def _write_buildinfo(self):
path = self._buildinfo_path()
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as fh:
fh.write("# Generated build information\n")
fh.write("compiled = True\n")
if native_build: build_cmdclass = { "build_ext": NativeBuildExt, "build_py": NativeBuildPy }
packages = setuptools.find_packages(exclude=excluded_modules)
setuptools.setup(
@@ -40,29 +169,27 @@ setuptools.setup(
packages=packages,
license="Reticulum License",
license_files = ("LICENSE"),
classifiers=[
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Development Status :: 5 - Production/Stable",
],
classifiers=[ "Programming Language :: Python :: 3",
"Operating System :: OS Independent",
"Development Status :: 5 - Production/Stable" ],
entry_points= {
'console_scripts': [
'rnsd=RNS.Utilities.rnsd:main',
'rnstatus=RNS.Utilities.rnstatus:main',
'rnprobe=RNS.Utilities.rnprobe:main',
'rnpath=RNS.Utilities.rnpath:main',
'rnid=RNS.Utilities.rnid:main',
'rncp=RNS.Utilities.rncp:main',
'rnx=RNS.Utilities.rnx:main',
'rnir=RNS.Utilities.rnir:main',
'rnpkg=RNS.Utilities.rnpkg:main',
'rnsh=RNS.Utilities.rnsh.rnsh:main',
'rngit=RNS.Utilities.rngit.server:main',
'rngcs=RNS.Utilities.rngit.commitsigs:main',
'git-remote-rns=RNS.Utilities.rngit.client:main',
'rnodeconf=RNS.Utilities.rnodeconf:main',
]
'console_scripts': [ 'rnsd=RNS.Utilities.rnsd:main',
'rnstatus=RNS.Utilities.rnstatus:main',
'rnprobe=RNS.Utilities.rnprobe:main',
'rnpath=RNS.Utilities.rnpath:main',
'rnid=RNS.Utilities.rnid:main',
'rncp=RNS.Utilities.rncp:main',
'rnx=RNS.Utilities.rnx:main',
'rnir=RNS.Utilities.rnir:main',
'rnpkg=RNS.Utilities.rnpkg:main',
'rnsh=RNS.Utilities.rnsh.rnsh:main',
'rngit=RNS.Utilities.rngit.server:main',
'rngcs=RNS.Utilities.rngit.commitsigs:main',
'git-remote-rns=RNS.Utilities.rngit.client:main',
'rnodeconf=RNS.Utilities.rnodeconf:main' ]
},
install_requires=requirements,
python_requires='>=3.7',
ext_modules=ext_modules,
cmdclass=build_cmdclass,
)
+5 -25
View File
@@ -1,26 +1,6 @@
compiling = False
noticed = False
notice_delay = 0.3
import time
import sys
import threading
from importlib.util import find_spec
if find_spec("pyximport") and find_spec("cython"):
import pyximport; pyxloader = pyximport.install(pyimport=True, language_level=3)[1]
import os
if os.environ.get("RNS_COMPILE"): from CRNS import RNS
else: import RNS
def notice_job():
global noticed
started = time.time()
while compiling:
if time.time() > started+notice_delay and compiling:
noticed = True
print("Compiling RNS object code... ", end="")
sys.stdout.flush()
break
time.sleep(0.1)
compiling = True
threading.Thread(target=notice_job, daemon=True).start()
import RNS; compiling = False
if noticed: print("Done."); sys.stdout.flush()
notice = f"Starting tests in {'compiled' if RNS.compiled else 'interpreted'} mode"
print(f"\n{notice}\n"+"="*len(notice)+"\n\n")
+6 -2
View File
@@ -5,6 +5,10 @@ from .hashes import TestSHA512
from .identity import TestIdentity
from .link import TestLink
from .channel import TestChannel
from .hkdf import TestHKDF
from .ifac import TestIFAC
from .coalesced_transmit import TestTransmitBuffer
from .hdlc import TestReceiveBuffer
from .egress import TestHWMLimiter
if __name__ == '__main__':
unittest.main(verbosity=2)
if __name__ == '__main__': unittest.main(verbosity=2)
+458
View File
@@ -0,0 +1,458 @@
import unittest
import os
import time
import random
import socket
import threading
from RNS.Interfaces.util.TransmitBuffer import TransmitBuffer
from RNS.Interfaces.util.HDLC import HDLC
TARGET = TransmitBuffer.COALESCE_TARGET
FRAME_SEED = 0x7842AB1E
def framed(payload): return bytes([HDLC.FLAG]) + HDLC.escape(payload) + bytes([HDLC.FLAG])
def unframe(stream):
frames = []
fb = stream
while True:
frame_start = fb.find(bytes([HDLC.FLAG]))
if frame_start != -1:
frame_end = fb.find(bytes([HDLC.FLAG]), frame_start + 1)
if frame_end != -1:
frame = fb[frame_start + 1:frame_end]
frame = frame.replace(bytes([HDLC.ESC, HDLC.FLAG ^ HDLC.ESC_MASK]), bytes([HDLC.FLAG]))
frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
if len(frame) > 0:
frames.append(bytes(frame))
fb = fb[frame_end:]
else: break
else: break
return frames
def rng_payload(rng, size):
raw = bytearray(os.urandom(size))
if size > 0:
for off in range(0, size, max(size // 32, 1)):
raw[off] = 0x7E if (off % 2) else 0x7D
return bytes(raw)
def assert_accounting(test, tb, expect_len, expect_sendable, expect_frames):
test.assertEqual(len(tb), expect_len)
test.assertEqual(tb.sendable, expect_sendable)
test.assertEqual(tb.frames_buffered, expect_frames)
test.assertTrue(0 <= tb.sendable <= len(tb))
class TestTransmitBuffer(unittest.TestCase):
def test_01_empty_state(self):
print("")
tb = TransmitBuffer()
assert_accounting(self, tb, 0, 0, 0)
self.assertEqual(tb.chunks_buffered, 0)
self.assertEqual(tb.drain_to(None), 0) # no chunks -> nothing to do
# Test that frames appended to an idle queue become sendable
# at once, so no coalescing latency is incurred for sparse traffic.
def test_02_sparse_visibility(self):
print("")
tb = TransmitBuffer()
for payload_size in (200, 1024, 16384, 65534):
tb.append(framed(rng_payload(random.Random(FRAME_SEED), payload_size)))
self.assertGreater(tb.sendable, 0)
self.assertGreater(len(tb), 0)
# Test that small frames coalesce into chunks bounded by
# the configured coalescing target.
def test_03_coalescing(self):
print("")
tb = TransmitBuffer()
rng = random.Random(FRAME_SEED)
payloads = [rng_payload(rng, 200) for _ in range(2000)]
for p in payloads: tb.append(framed(p))
self.assertEqual(len(tb), sum(len(framed(p)) for p in payloads))
self.assertEqual(tb.frames_buffered, len(payloads))
for chunk, frames in tb._chunks:
self.assertLessEqual(len(chunk), TARGET)
self.assertGreater(len(chunk), 0)
self.assertGreater(frames, 0)
# Visible accounting must match the chunk queue; buffered accounting
# must additionally include the producer's in-progress coalescing
# chunk, which is not visible to the consumer yet.
in_cur = len(tb._cur) if tb._cur is not None else 0
in_cur_frames = tb._cur_frames if tb._cur is not None else 0
visible = sum(len(c) for c, _ in tb._chunks)
visible_frames = sum(frames for _, frames in tb._chunks)
self.assertEqual(tb.sendable, visible)
self.assertEqual(tb.sendable + in_cur, len(tb))
self.assertEqual(visible_frames + in_cur_frames, len(payloads))
self.assertEqual(tb.frames_buffered, len(payloads))
# Test that frames whose on-wire size is at or above the coalescing
# target are queued as their own chunk. Frames just below must coalesce.
# Must apply to final, framed and escape on-wire stream.
def test_04_large_frame_granularity(self):
print("")
tb = TransmitBuffer()
below = bytes([HDLC.FLAG]) + b"A" * (TARGET - 10) + bytes([HDLC.FLAG])
at = bytes([HDLC.FLAG]) + b"B" * (TARGET - 2) + bytes([HDLC.FLAG])
above = bytes([HDLC.FLAG]) + b"C" * TARGET + bytes([HDLC.FLAG])
big = bytes([HDLC.FLAG]) + b"D" * 262144 + bytes([HDLC.FLAG])
self.assertLess(len(below), TARGET)
self.assertEqual(len(at), TARGET)
self.assertGreater(len(above), TARGET)
tb.append(below)
tb.append(at)
tb.append(above)
tb.append(big)
chunks = list(tb._chunks)
self.assertEqual(len(chunks), 4) # 1 coalesced chunk + 3 own chunks
self.assertEqual(chunks[0][1], 1)
self.assertEqual(chunks[0][0], below)
self.assertEqual(chunks[1][1], 1)
self.assertEqual(chunks[1][0], at)
self.assertEqual(chunks[2][1], 1)
self.assertEqual(chunks[2][0], above)
self.assertEqual(chunks[3][1], 1)
self.assertEqual(chunks[3][0], big)
self.assertEqual(tb.frames_buffered, 4)
# Test that a partially written head chunk resumes
# correctly on the next drain.
def test_05_partial_head_resume(self):
print("")
a, b = socket.socketpair()
a.setblocking(False)
b.setblocking(False)
a.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
tb = TransmitBuffer()
rng = random.Random(FRAME_SEED)
payloads = [rng_payload(rng, 262144) for _ in range(8)]
frames = [framed(p) for p in payloads]
for f in frames: tb.append(f)
expected = b"".join(frames)
# Drain without any receiver: Small kernel buffer forces partial
# writes, and the drain must stop gracefully on BlockingIOError.
written = 0
w = tb.drain_to(a)
self.assertGreater(w, 0)
self.assertLess(w, len(frames[0]))
written += w
self.assertLess(tb.sendable, len(expected))
w = tb.drain_to(a) # window still full, must not raise or corrupt
self.assertGreaterEqual(w, 0)
written += w
self.assertGreaterEqual(len(tb), 0)
# Drain the kernel side, then run the drain to completion.
got = bytearray()
def recv_loop():
while len(got) < len(expected):
try: d = b.recv(1 << 20)
except BlockingIOError:
time.sleep(0.001)
continue
if not d:
break
got.extend(d)
rt = threading.Thread(target=recv_loop, daemon=True)
rt.start()
while tb.sendable > 0:
w = tb.drain_to(a)
if w == 0: time.sleep(0.001)
rt.join(timeout=10)
self.assertFalse(rt.is_alive())
self.assertEqual(bytes(got), expected)
assert_accounting(self, tb, 0, 0, 0)
a.close(); b.close()
# Test that a full kernel window stops the drain without
# any exceptions, and that a later drain delivers the rest.
def test_06_graceful_blocking_io(self):
print("")
a, b = socket.socketpair()
a.setblocking(False)
b.setblocking(False)
a.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
tb = TransmitBuffer()
rng = random.Random(FRAME_SEED)
frames = [framed(rng_payload(rng, 200)) for _ in range(100000)]
for f in frames:
tb.append(f)
expected = b"".join(frames)
# Fill the kernel window. Repeated drains must never raise, and must
# eventually make no progress while the window is full.
for _ in range(5_000_000):
w = tb.drain_to(a)
if w == 0: break
if w < 0: self.fail("drain_to returned a negative count")
self.assertGreater(len(tb), 0)
# Production for the burst has ended, release the coalescing tail.
tb.flush()
got = bytearray()
def recv_loop():
while len(got) < len(expected):
try: d = b.recv(1 << 20)
except BlockingIOError:
time.sleep(0.001)
continue
if not d:
break
got.extend(d)
rt = threading.Thread(target=recv_loop, daemon=True)
rt.start()
while tb.sendable > 0:
w = tb.drain_to(a)
if w == 0: time.sleep(0.001)
rt.join(timeout=10)
self.assertFalse(rt.is_alive())
self.assertEqual(bytes(got), expected)
assert_accounting(self, tb, 0, 0, 0)
a.close(); b.close()
# Exactness test of end-to-end, in-order roundtrip delivery.
def test_07_roundtrip_and_frame_integrity(self):
print("")
a, b = socket.socketpair()
a.setblocking(True)
b.setblocking(True)
tb = TransmitBuffer()
rng = random.Random(FRAME_SEED)
sizes = [200, 512, 1024, 4096, 8192, 16384, 65534, 65536, 65537, 262144]
payloads = [rng_payload(rng, size) for size in sizes] * 8
frames = [framed(p) for p in payloads]
for f in frames: tb.append(f)
expected = b"".join(frames)
# Non-blocking socket, pipelined drain and receive
a.setblocking(False)
b.setblocking(False)
got = bytearray()
wrote = 0
deadline = time.time() + 30
while tb.sendable > 0 or len(got) < len(expected):
self.assertLess(time.time(), deadline, "test timed out")
if tb.sendable > 0: wrote += tb.drain_to(a)
try:
d = b.recv(1 << 20)
if d: got.extend(d)
except BlockingIOError:
time.sleep(0.0002)
self.assertEqual(wrote, len(expected))
assert_accounting(self, tb, 0, 0, 0)
self.assertEqual(bytes(got), expected)
self.assertEqual(unframe(bytes(got)), payloads)
a.close(); b.close()
# Test that a producer flush makes the in-progress coalescing
# tail visible, and that the buffer is fully drainable afterwards.
def test_08_flush_releases_tail(self):
print("")
tb = TransmitBuffer()
rng = random.Random(FRAME_SEED)
f1 = framed(rng_payload(rng, 200))
f2 = framed(rng_payload(rng, 200))
f3 = framed(rng_payload(rng, 200))
tb.append(f1) # Queue idle -> visible immediately
tb.append(f2) # Queue busy -> coalesced into tail
tb.append(f3) # Queue busy -> coalesced into tail
self.assertEqual(tb.sendable, len(f1))
self.assertEqual(len(tb), len(f1) + len(f2) + len(f3))
self.assertEqual(tb.chunks_buffered, 1)
tb.flush()
self.assertEqual(tb.sendable, len(f1) + len(f2) + len(f3))
self.assertEqual(tb.chunks_buffered, 2)
self.assertEqual(tb.frames_buffered, 3)
# Ensure frames appended while the queue is busy are not
# stranded in the coalescing tail.
def test_09_stranded_tail_delivery(self):
print("")
a, b = socket.socketpair()
a.setblocking(False)
b.setblocking(False)
tb = TransmitBuffer()
rng = random.Random(FRAME_SEED)
f1 = framed(rng_payload(rng, 200))
f2 = framed(rng_payload(rng, 200))
f3 = framed(rng_payload(rng, 200))
expected = f1 + f2 + f3
tb.append(f1) # queue idle -> own chunk, visible
tb.append(f2) # queue busy -> coalescing tail, invisible
tb.append(f3) # queue busy -> coalescing tail, invisible
self.assertEqual(tb.sendable, len(f1))
# No further appends. Draining alone without a flush must
# release and deliver the coalescing tail.
got = bytearray()
deadline = time.time() + 10
while tb.sendable > 0 or len(got) < len(expected):
self.assertLess(time.time(), deadline, "test timed out")
tb.drain_to(a)
try:
d = b.recv(1 << 20)
if d: got.extend(d)
except BlockingIOError:
time.sleep(0.0002)
self.assertEqual(bytes(got), expected)
assert_accounting(self, tb, 0, 0, 0)
a.close(); b.close()
# Test that the coalescing tail is released when the queue
# drains, and that len() is the total buffered and senable
# is the transmittable part.
def test_10_sendable_gating(self):
print("")
a, b = socket.socketpair()
a.setblocking(False)
b.setblocking(False)
b.settimeout(5.0)
tb = TransmitBuffer()
rng = random.Random(FRAME_SEED)
frames = [framed(rng_payload(rng, 200)) for _ in range(400)]
expected = b"".join(frames)
for f in frames:
tb.append(f)
self.assertEqual(tb.sendable + (len(tb._cur) if tb._cur is not None else 0), len(tb))
# Drain to completion. The drain must release the tail by itself.
got = bytearray()
deadline = time.time() + 10
while tb.sendable > 0 or len(got) < len(expected):
self.assertLess(time.time(), deadline, "test timed out")
tb.drain_to(a)
try:
d = b.recv(1 << 20)
if d: got.extend(d)
except BlockingIOError:
time.sleep(0.0002)
self.assertEqual(bytes(got), expected)
assert_accounting(self, tb, 0, 0, 0)
a.close(); b.close()
# Exactness test of concurrent producer append while consumer drains.
def test_11_concurrent_producer_consumer(self):
print("")
a, b = socket.socketpair()
a.setblocking(False)
b.setblocking(False)
b.settimeout(5.0)
tb = TransmitBuffer()
rng = random.Random(FRAME_SEED)
sizes = [200, 1024, 8192, 65536, 262144]
payloads = [rng_payload(rng, rng.choice(sizes)) for _ in range(2500)]
frames = [framed(p) for p in payloads]
total = sum(len(f) for f in frames)
expected = b"".join(frames)
producer_errors = []
def producer():
try:
for f in frames: tb.append(f)
except Exception as e:
producer_errors.append(e)
pt = threading.Thread(target=producer, daemon=True)
pt.start()
got = bytearray()
def recv_loop():
while len(got) < total:
try: d = b.recv(1 << 20)
except BlockingIOError:
time.sleep(0.001)
continue
except socket.timeout: break
if not d: break
got.extend(d)
rt = threading.Thread(target=recv_loop, daemon=True)
rt.start()
ct0 = time.perf_counter()
while pt.is_alive() or tb.sendable > 0:
tb.drain_to(a)
time.sleep(0.0002)
# Final drain once the producer has exited.
w = 1
while w > 0: w = tb.drain_to(a)
t_elapsed = time.perf_counter() - ct0
pt.join(timeout=10)
self.assertFalse(pt.is_alive())
self.assertEqual(producer_errors, [])
# Production for the burst has ended. Release the coalescing tail so
# every appended byte is transmittable, then drain to completion.
tb.flush()
w = 1
while w > 0: w = tb.drain_to(a)
rt.join(timeout=10)
self.assertFalse(rt.is_alive())
self.assertEqual(len(got), total)
self.assertEqual(bytes(got), expected)
assert_accounting(self, tb, 0, 0, 0)
a.close(); b.close()
print(f"Concurrent {len(frames)}-frame burst ({total/1e6:.1f} MB) drained in {t_elapsed*1000:.1f} ms")
# Test small-frame flood and execution time.
def test_12_small_frame_burst(self):
print("")
a, b = socket.socketpair()
a.setblocking(False)
b.setblocking(False)
tb = TransmitBuffer()
rng = random.Random(FRAME_SEED)
frames = [framed(rng_payload(rng, 200)) for _ in range(50000)]
total = sum(len(f) for f in frames)
expected = b"".join(frames)
got = bytearray()
def recv_loop():
while len(got) < total:
try: d = b.recv(1 << 20)
except BlockingIOError:
time.sleep(0.001)
continue
if not d: break
got.extend(d)
rt = threading.Thread(target=recv_loop, daemon=True)
rt.start()
t0 = time.perf_counter()
for f in frames: tb.append(f)
tb.flush()
while tb.sendable > 0: tb.drain_to(a)
rt.join(timeout=15)
t_elapsed = time.perf_counter() - t0
self.assertFalse(rt.is_alive())
self.assertEqual(len(got), total)
self.assertEqual(bytes(got), expected)
assert_accounting(self, tb, 0, 0, 0)
a.close(); b.close()
print(f"50k x 200B flood ({total/1e6:.1f} MB) appended+drained in {t_elapsed*1000:.1f} ms")
self.assertLess(t_elapsed, 10.0)
if __name__ == "__main__": unittest.main(verbosity=2)
+204
View File
@@ -0,0 +1,204 @@
import unittest
import time
from RNS.Interfaces.util.TransmitBuffer import TransmitBuffer
from RNS.Interfaces.BackboneInterface import BackboneInterface, BackboneClientInterface
def framed(payload): return b"\x7e" + payload + b"\x7e"
class FakeSock:
def send(self, data): return len(data)
def fileno(self): return 999999
def close(self): return
class FakeIF:
def __init__(self, tb=None):
self.transmit_buffer = tb if tb is not None else TransmitBuffer()
self._dp_ec_prev_sent = 0
self._dp_ec_zero_ticks = 0
self._dp_ec_last_drain = 10.0
self.tx_stalled = False
self.detached = False
self.socket = FakeSock()
self.torn_down = False
def receive(self, data): self.torn_down = True
class TestHWMLimiter(unittest.TestCase):
def test_01_hard_valve_bounds_memory(self):
print("")
tb = TransmitBuffer()
limit = 4096
accepted_count = 0
total_accepted = 0
rejected = 0
for _ in range(200):
for size in (500, 700):
frame = framed(b"x" * size)
accepted = tb.append(frame, limit)
if accepted:
accepted_count += 1
total_accepted += len(frame)
self.assertLessEqual(len(tb), limit)
else:
rejected += 1
# Rejection implies the frame would breach the limit.
self.assertGreater(total_accepted + len(frame), limit)
# The limit must never be exceeded, some frames must have been
# rejected, and the buffer must still be fully drainable.
self.assertGreater(rejected, 0)
self.assertLessEqual(len(tb), limit)
drained = tb.drain_to(FakeSock())
self.assertEqual(drained, total_accepted)
self.assertEqual(len(tb), 0)
def test_02_oversized_frame_rejected(self):
print("")
tb = TransmitBuffer()
limit = 2048
self.assertTrue(tb.append(framed(b"x" * 500), limit))
# A single frame that would exceed the limit is rejected outright,
# even against an empty buffer.
self.assertFalse(tb.append(framed(b"x" * 3000), limit))
self.assertEqual(len(tb), len(framed(b"x" * 500)))
# The buffer remains fully functional after rejection.
self.assertTrue(tb.append(framed(b"x" * 1000), limit))
self.assertEqual(len(tb), len(framed(b"x" * 500)) + len(framed(b"x" * 1000)))
drained = tb.drain_to(FakeSock())
self.assertEqual(drained, len(framed(b"x" * 500)) + len(framed(b"x" * 1000)))
def test_03_valve_accepts_after_drain(self):
print("")
tb = TransmitBuffer()
limit = 2048
for _ in range(10): self.assertTrue(tb.append(framed(b"x" * 200), limit))
self.assertEqual(len(tb), len(framed(b"x" * 200)) * 10)
# Drain most of the buffer; appends are accepted again up to the
# limit, and the total stays bounded.
tb.drain_to(FakeSock())
for _ in range(10): self.assertTrue(tb.append(framed(b"x" * 200), limit))
self.assertLessEqual(len(tb), limit)
def test_04_append_without_limit_unbounded(self):
print("")
tb = TransmitBuffer()
for _ in range(100): self.assertTrue(tb.append(framed(b"x" * 200)))
self.assertEqual(len(tb), len(framed(b"x" * 200)) * 100)
def test_05_stall_engages_on_zero_drain(self):
print("")
tb = TransmitBuffer()
iface = FakeIF(tb)
# Fill beyond the mid watermark.
while len(tb) <= BackboneInterface.DP_EC_MID_WM: tb.append(framed(b"y" * 4096))
# No drain progress, fewer than STALL_TICKS evaluations must not stall.
for tick in range(BackboneInterface.DP_EC_STALL_TICKS - 1):
BackboneInterface._dp_ec_evaluate(iface, 11.0 + tick)
self.assertFalse(iface.tx_stalled)
# The STALL_TICKSth zero-drain tick at/above the
# mid watermark engages the gate.
BackboneInterface._dp_ec_evaluate(iface, 15.0)
self.assertTrue(iface.tx_stalled)
def test_06_stall_releases_below_mid(self):
print("")
tb = TransmitBuffer()
iface = FakeIF(tb)
while len(tb) <= BackboneInterface.DP_EC_MID_WM: tb.append(framed(b"y" * 4096))
for t in range(BackboneInterface.DP_EC_STALL_TICKS + 1): BackboneInterface._dp_ec_evaluate(iface, 11.0 + t)
self.assertTrue(iface.tx_stalled)
# Drain the buffer completely; the next tick releases the gate.
tb.drain_to(FakeSock())
self.assertEqual(len(tb), 0)
BackboneInterface._dp_ec_evaluate(iface, 20.0)
self.assertFalse(iface.tx_stalled)
self.assertEqual(iface._dp_ec_zero_ticks, 0)
def test_07_stall_engages_on_drain_eta(self):
print("")
tb = TransmitBuffer()
iface = FakeIF(tb)
while len(tb) <= BackboneInterface.DP_EC_MID_WM: tb.append(framed(b"y" * 4096))
# Pretend 512 bytes drained since the last tick, the queue would
# take far longer than DP_EC_MAX_ETA to clear at that rate.
iface._dp_ec_prev_sent = tb._tx_sent - 512
BackboneInterface._dp_ec_evaluate(iface, 11.0)
self.assertTrue(iface.tx_stalled)
def test_08_stall_hysteresis_no_flap(self):
print("")
tb = TransmitBuffer()
iface = FakeIF(tb)
while len(tb) <= BackboneInterface.DP_EC_MID_WM: tb.append(framed(b"y" * 4096))
# Engage the gate with an ETA above max.
buffered = len(tb)
iface._dp_ec_prev_sent = tb._tx_sent - 128
BackboneInterface._dp_ec_evaluate(iface, 11.0)
self.assertTrue(iface.tx_stalled)
# A drain ETA between RELEASE and MAX is the hysteresis band,
# the gate must stay engaged without flapping.
mid_eta = (BackboneInterface.DP_EC_MAX_ETA + BackboneInterface.DP_EC_RELEASE_ETA) / 2
mid_drain = buffered / mid_eta
iface._dp_ec_prev_sent = tb._tx_sent - mid_drain
BackboneInterface._dp_ec_evaluate(iface, 12.0)
self.assertTrue(iface.tx_stalled)
# Only when drainage clears the queue well within the release
# ETA is the gate released.
fast_drain = buffered / (BackboneInterface.DP_EC_RELEASE_ETA / 2)
iface._dp_ec_prev_sent = tb._tx_sent - fast_drain
BackboneInterface._dp_ec_evaluate(iface, 13.0)
self.assertFalse(iface.tx_stalled)
def test_09_sendable_zero_no_stall(self):
print("")
tb = TransmitBuffer()
iface = FakeIF(tb)
while len(tb) <= BackboneInterface.DP_EC_MID_WM: tb.append(framed(b"y" * 4096))
# A tick with nothing sendable. All data still unsent but none in
# the drainer's visible set is impossible with a full buffer, so
# simulate the empty state instead. An empty buffer must reset
# stall state and the dead-drain clock.
tb.drain_to(FakeSock())
BackboneInterface._dp_ec_evaluate(iface, 11.0)
self.assertFalse(iface.tx_stalled)
self.assertEqual(iface._dp_ec_last_drain, 11.0)
def test_10_dead_peer_escalation(self):
print("")
tb = TransmitBuffer()
iface = FakeIF(tb)
while len(tb) <= BackboneInterface.DP_EC_MID_WM: tb.append(framed(b"y" * 4096))
# Last drain progress a long time ago, no drain since.
iface._dp_ec_last_drain = 10.0
iface._dp_ec_zero_ticks = BackboneInterface.DP_EC_STALL_TICKS
escalated = BackboneInterface._dp_ec_evaluate(iface, 100.0)
self.assertTrue(escalated)
self.assertTrue(iface.torn_down)
def test_11_process_outgoing_gate(self):
print("")
# Construct a shell client interface object without full
# initialisation. Process_outgoing only requires the
# egress-control state and the transmit buffer gating.
iface = object.__new__(BackboneClientInterface)
iface.online = True
iface.detached = False
iface.tx_stalled = True
iface.tx_hwm = 1024
iface.tx_drops = 0
iface.tx_dropped_bytes = 0
iface.transmit_buffer = TransmitBuffer()
iface.socket = None
iface.process_outgoing(b"gated-frame")
self.assertEqual(iface.tx_drops, 1)
self.assertEqual(iface.tx_dropped_bytes, len(framed(b"gated-frame")))
self.assertEqual(len(iface.transmit_buffer), 0)
if __name__ == "__main__": unittest.main(verbosity=2)
+266
View File
@@ -0,0 +1,266 @@
import unittest
import os
import time
import random
from RNS.Interfaces.util.HDLC import HDLC, ReceiveBuffer
SEED = 0x52EC0FF
MIN_LEN = 19 # HEADER_MINSIZE
MTU = 1048576
def framed(payload): return HDLC.FLAG_B + HDLC.escape(payload) + HDLC.FLAG_B
def rand_payload(rng, size):
p = bytearray(os.urandom(size))
for off in range(0, max(size, 1), max(size // 16, 1)):
p[off] = 0x7E if (off % 2) else 0x7D
return bytes(p)
# Original, pre-refactor HDLC handler algorithm
def legacy_feed(state, data, mtu, min_len, max_len):
if len(data) > 0:
state["buf"] += data
flags_remaining = True
while flags_remaining:
frame_start = state["buf"].find(HDLC.FLAG)
if frame_start != -1:
frame_end = state["buf"].find(HDLC.FLAG, frame_start+1)
if frame_end != -1:
frame = state["buf"][frame_start+1:frame_end]
frame = frame.replace(bytes([HDLC.ESC, HDLC.FLAG ^ HDLC.ESC_MASK]), bytes([HDLC.FLAG]))
frame = frame.replace(bytes([HDLC.ESC, HDLC.ESC ^ HDLC.ESC_MASK]), bytes([HDLC.ESC]))
frame_len = len(frame)
if frame_len != 0:
if check_frame_len(frame_len, min_len, max_len): state["frames"].append(frame)
else: state["invalids"].append(frame_len)
state["buf"] = state["buf"][frame_end:]
else:
if len(state["buf"]) > mtu*2: state["buf"] = b""
flags_remaining = False
else:
state["buf"] = b""
flags_remaining = False
def check_frame_len(frame_len, min_len, max_len):
if frame_len <= min_len: return False
elif max_len == None: return True
elif frame_len > max_len: return False
else: return True
class Harness:
def __init__(self, mtu=MTU, min_len=MIN_LEN, max_len=None, track_invalid=True):
self.frames = []
self.invalids = []
self.rb = ReceiveBuffer(mtu, min_len, max_len, on_frame=self.frames.append,
on_invalid=self.invalids.append if track_invalid else None)
def unconsumed(self):
return bytes(self.rb._buf[self.rb._off:])
class TestReceiveBuffer(unittest.TestCase):
# Legacy parity, also checks that the closing flag of
# the last consumed frame is retained as the start
# marker for the next unframing.
def test_01_single_frame_roundtrip(self):
print("")
rng = random.Random(SEED)
for size in (20, 200, 4096, 262144):
p = rand_payload(rng, size)
h = Harness()
h.rb.feed(framed(p))
self.assertEqual(h.frames, [p])
self.assertEqual(h.invalids, [])
self.assertEqual(h.unconsumed(), HDLC.FLAG_B)
self.assertEqual(len(h.rb), 1)
# Test frames split across arbitrary feed boundaries
def test_02_split_chunks_straddle(self):
print("")
rng = random.Random(SEED)
payloads = [rand_payload(rng, rng.choice((20, 200, 1024, 16384))) for _ in range(200)]
stream = b"".join(framed(p) for p in payloads)
h = Harness()
# One-byte-per-feed pathological case
for byte in stream: h.rb.feed(bytes([byte]))
self.assertEqual(h.frames, payloads)
self.assertEqual(len(h.rb), 1) # trailing flag
# Test exactness of escape-heavy payloads
def test_03_escape_roundtrip(self):
print("")
rng = random.Random(SEED ^ 0xE5C)
payloads = []
for _ in range(100):
size = rng.choice((64, 512, 8192))
p = bytearray(os.urandom(size))
# Dense 0x7E/0x7D injection
for i in range(0, size, 3): p[i] = 0x7E if (i % 2) else 0x7D
payloads.append(bytes(p))
h = Harness()
for p in payloads: h.rb.feed(framed(p))
self.assertEqual(h.frames, payloads)
# Empty frames must skip silently
def test_04_consecutive_flags_skipped(self):
print("")
rng = random.Random(SEED)
p1 = rand_payload(rng, 100)
p2 = rand_payload(rng, 100)
h = Harness()
h.rb.feed(framed(p1) + HDLC.FLAG_B + HDLC.FLAG_B + framed(p2))
self.assertEqual(h.frames, [p1, p2])
self.assertEqual(h.invalids, [])
# Test that invalid sized frames report correctly
def test_05_size_range(self):
print("")
h = Harness(min_len=19, max_len=100)
h.rb.feed(framed(b"x" * 5)) # frame len 5 -> too short
h.rb.feed(framed(b"x" * 19)) # frame len 19 -> not > 19, which is bad
h.rb.feed(framed(b"x" * 100)) # frame len 100 -> within range
h.rb.feed(framed(b"x" * 101)) # frame len 101 -> too long
self.assertEqual(h.frames, [b"x" * 100])
self.assertEqual(h.invalids, [5, 19, 101])
# Without an on_invalid hook, out-of-range frames are dropped
h2 = Harness(min_len=19, max_len=100, track_invalid=False)
h2.rb.feed(framed(b"x" * 5))
h2.rb.feed(framed(b"x" * 50))
h2.rb.feed(framed(b"x" * 101))
self.assertEqual(h2.frames, [b"x" * 50])
self.assertEqual(h2.invalids, [])
# A flag without a closing flag is retained up to the
# overflow bound, beyond which the buffer must reset
def test_06_partial_and_overflow_reset(self):
print("")
h = Harness(mtu=1024)
# Partial frame within bound must retained
h.rb.feed(b"\x7e" + b"Y" * 100)
self.assertEqual(len(h.rb), 101)
self.assertEqual(h.frames, [])
# ... and completing it delivers the frame
h.rb.feed(b"Z" * 40 + b"\x7e")
self.assertEqual(h.frames, [b"Y" * 100 + b"Z" * 40])
self.assertEqual(len(h.rb), 1)
# Partial frame past the overflow bound must drop and reset
h2 = Harness(mtu=1024)
h2.rb.feed(b"\x7e" + b"Y" * 5000)
self.assertEqual(len(h2.rb), 0)
# Buffer must be usable after the reset
h2.rb.feed(framed(b"x" * 100))
self.assertEqual(h2.frames, [b"x" * 100])
# Test that input without any flag is discarded immediately
def test_07_garbage_reset(self):
print("")
h = Harness()
h.rb.feed(b"\x00" * 100000 + b"\x01" * 100000)
self.assertEqual(len(h.rb), 0)
self.assertEqual(h.frames, [])
h.rb.feed(framed(b"x" * 100))
self.assertEqual(h.frames, [b"x" * 100])
# Random stream parity checks
def test_08_parity_random_streams(self):
print("")
rng = random.Random(SEED)
verified = 0
def inert(size): return bytes(rng.randrange(1, 0x7D) for _ in range(size))
for round in range(20):
stream = bytearray()
intended = []
for _ in range(rng.randrange(5, 60)):
kind = rng.randrange(5)
if kind == 0: stream += inert(rng.randrange(40, 300)) # Garbage
elif kind == 1: stream += b"\x7e" + inert(rng.randrange(50, 400)) # Unclosed partial
else:
p = rand_payload(rng, rng.randrange(20, 8192))
intended.append(p)
stream += framed(p)
legacy = {"buf": b"", "frames": [], "invalids": []}
mine = Harness()
pos = 0
while pos < len(stream):
step = rng.randrange(1, 4096)
chunk = bytes(stream[pos:pos + step])
pos += step
legacy_feed(legacy, chunk, MTU, MIN_LEN, None)
mine.rb.feed(chunk)
# Behavioural and internal-state parity after every chunk
self.assertEqual(mine.frames, legacy["frames"])
self.assertEqual(mine.invalids, legacy["invalids"])
self.assertEqual(mine.unconsumed(), legacy["buf"])
# Full-stream parity and intended-payload presence.
self.assertEqual(mine.frames, legacy["frames"])
self.assertEqual(mine.unconsumed(), legacy["buf"])
for p in intended: self.assertGreaterEqual(mine.frames.count(p), intended.count(p))
verified += 1
print(f" Random-stream parity: {verified} streams verified")
# Small-frame flood parity
def test_09_parity_flood(self):
print("")
rng = random.Random(SEED)
payloads = [rand_payload(rng, 200) for _ in range(20000)]
stream = b"".join(framed(p) for p in payloads)
legacy = {"buf": b"", "frames": [], "invalids": []}
mine = Harness()
t0 = time.perf_counter()
for i in range(0, len(stream), MTU):
chunk = stream[i:i + MTU]
legacy_feed(legacy, chunk, MTU, MIN_LEN, None)
mine.rb.feed(chunk)
t_elapsed = time.perf_counter() - t0
self.assertEqual(mine.frames, legacy["frames"])
self.assertEqual(mine.frames, payloads)
self.assertEqual(mine.unconsumed(), legacy["buf"])
self.assertLess(t_elapsed, 10.0)
print(f" 20k x 200B flood ({len(stream)/1e6:.1f} MB) parity-verified in {t_elapsed*1000:.1f} ms")
# Large frames in small chunks
def test_10_parity_large_frames(self):
print("")
rng = random.Random(SEED ^ 0x1AF)
payloads = [rand_payload(rng, 262144) for _ in range(8)]
stream = b"".join(framed(p) for p in payloads)
legacy = {"buf": b"", "frames": [], "invalids": []}
mine = Harness(mtu=262144)
pos = 0
while pos < len(stream):
chunk = stream[pos:pos + 4096]
pos += 4096
legacy_feed(legacy, chunk, 262144, MIN_LEN, None)
mine.rb.feed(chunk)
self.assertEqual(mine.frames, legacy["frames"])
self.assertEqual(mine.unconsumed(), legacy["buf"])
self.assertEqual(mine.frames, payloads)
# After a burst is fully consumed, the internal buffer must be compacted
def test_11_len_and_compaction(self):
print("")
rng = random.Random(SEED)
h = Harness()
for _ in range(1000):
h.rb.feed(framed(rand_payload(rng, 200)))
self.assertEqual(len(h.rb), 1) # Trailing flag marker
self.assertEqual(len(h.rb._buf), 1) # Fully compacted
self.assertEqual(h.rb._off, 0)
self.assertEqual(len(h.frames), 1000)
if __name__ == "__main__": unittest.main(verbosity=2)
+188
View File
@@ -0,0 +1,188 @@
import unittest
import os
import time
import random
import RNS
from RNS.Cryptography import hkdf
from RNS.Cryptography.HKDF import hkdf_legacy
HKDF_TEST_SEED = 0x5EE5FAC
# RFC 5869 test vectors HKDF SHA-256 vectors
RFC5869_CASES = [
# A.1: basic test case
(
bytes([0x0b]) * 22,
bytes(range(0x00, 0x0d)),
bytes(range(0xf0, 0xfa)),
42,
"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865",
),
# A.2: longer inputs/outputs
(
bytes(range(0x00, 0x50)),
bytes(range(0x60, 0xb0)),
bytes(range(0xb0, 0x100)),
82,
"b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c"
"59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71"
"cc30c58179ec3e87c14c01d5c1f3434f1d87",
),
# A.3: zero-length salt/info
(
bytes([0x0b]) * 22,
b"",
b"",
42,
"8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8",
),
]
def rand_bytes(rng, length):
return bytes(rng.randrange(256) for _ in range(length))
class TestHKDF(unittest.TestCase):
def test_01_rfc5869_vectors(self):
print("")
for index, (ikm, salt, info, length, expected_hex) in enumerate(RFC5869_CASES):
expected = bytes.fromhex(expected_hex)
new_out = hkdf(length=length, derive_from=ikm, salt=salt, context=info)
leg_out = hkdf_legacy(length=length, derive_from=ikm, salt=salt, context=info)
self.assertEqual(new_out, expected)
self.assertEqual(leg_out, expected)
print(f"RFC 5869 test case {index+1}: OK (optimized = legacy = reference, {len(expected)} bytes)")
def test_02_parity_matrix(self):
print("")
rng = random.Random(HKDF_TEST_SEED)
# Core lengths: block boundaries, block+1, counter wrap at
# 256 blocks (8192 bytes), +1/-1 around it, and medium sizes.
lengths_core = [ 1, 2, 31, 32, 33, 63, 64, 65, 96, 127, 128, 129,
255, 256, 257, 511, 512, 513, 1024, 4096, 8191, 8192, 8193 ]
# Large lengths: exercised with a reduced combination set.
lengths_large = [16384, 65536, 262144]
derive_lens = [1, 7, 16, 32, 64]
salt_lens = [None, 0, 1, 16, 32, 64, 100]
context_lens = [None, 0, 1, 16, 64, 128]
derive_lens_large = [16, 64]
salt_lens_large = [None, 32, 100]
context_lens_large = [None, 16, 128]
verified = 0
for length in lengths_core:
for dlen in derive_lens:
for slen in salt_lens:
for clen in context_lens:
derive_from = rand_bytes(rng, dlen)
salt = None if slen is None else (b"" if slen == 0 else rand_bytes(rng, slen))
context = None if clen is None else (b"" if clen == 0 else rand_bytes(rng, clen))
new_out = hkdf(length=length, derive_from=derive_from, salt=salt, context=context)
leg_out = hkdf_legacy(length=length, derive_from=derive_from, salt=salt, context=context)
self.assertEqual(new_out, leg_out)
verified += 1
for length in lengths_large:
for dlen in derive_lens_large:
for slen in salt_lens_large:
for clen in context_lens_large:
derive_from = rand_bytes(rng, dlen)
salt = None if slen is None else (b"" if slen == 0 else rand_bytes(rng, slen))
context = None if clen is None else (b"" if clen == 0 else rand_bytes(rng, clen))
new_out = hkdf(length=length, derive_from=derive_from, salt=salt, context=context)
leg_out = hkdf_legacy(length=length, derive_from=derive_from, salt=salt, context=context)
self.assertEqual(new_out, leg_out)
verified += 1
print(f"HKDF parity matrix: {verified} deterministic cases verified (optimized == legacy)")
def test_03_error_parity(self):
print("")
invalid_cases = [
dict(length=0, derive_from=b"x"),
dict(length=None, derive_from=b"x"),
dict(length=-1, derive_from=b"x"),
dict(length="x", derive_from=b"x"),
dict(length=32, derive_from=""),
dict(length=32, derive_from=None),
]
def raised_exception(fn, kwargs):
try:
fn(**kwargs)
return None
except Exception as e: return (type(e).__name__, str(e))
for kwargs in invalid_cases:
new_exc = raised_exception(hkdf, kwargs)
leg_exc = raised_exception(hkdf_legacy, kwargs)
# Both implementations must raise the exact same exception
# type with the exact same message on invalid arguments
self.assertIsNotNone(new_exc)
self.assertEqual(new_exc, leg_exc)
print(f"HKDF error parity: {len(invalid_cases)} invalid-argument cases raise identical exception types and messages")
@unittest.skipIf(os.getenv("RNS_SKIP_PERF_TESTS") != None, "Skipping performance tests")
def test_04_benchmark(self):
print("")
rng = random.Random(HKDF_TEST_SEED ^ 0xA11CE)
salt = RNS.Reticulum.IFAC_SALT
sizes = [1500, 16384, 262144]
runs = {1500: 40, 16384: 20, 262144: 8}
print("HKDF implementation benchmark (optimized vs legacy):")
print(f"{'length':>9} {'legacy avg':>12} {'opt avg':>9} {'speedup':>10}")
print("-" * 48)
leg_total = new_total = 0.0
for size in sizes:
derive_from = rand_bytes(rng, 16)
context = rand_bytes(rng, 7)
n = runs[size]
hkdf_legacy(length=size, derive_from=derive_from, salt=salt, context=context)
hkdf(length=size, derive_from=derive_from, salt=salt, context=context)
t0 = time.perf_counter()
for _ in range(n):
hkdf_legacy(length=size, derive_from=derive_from, salt=salt, context=context)
leg_avg = (time.perf_counter() - t0) / n
t0 = time.perf_counter()
for _ in range(n):
hkdf(length=size, derive_from=derive_from, salt=salt, context=context)
new_avg = (time.perf_counter() - t0) / n
leg_total += leg_avg
new_total += new_avg
print(f"{size:>9} {leg_avg*1000:9.3f}m {new_avg*1000:9.3f}m {leg_avg/new_avg:8.1f}x")
print(f"\nThroughput at {sizes[-1]} bytes: legacy {sizes[-1]/leg_avg/1e6*8:.2f} Mbps, "
f"new {sizes[-1]/new_avg/1e6*8:.2f} Mbps")
print(f"Overall speedup across benchmarks: {leg_total/new_total:.1f}x")
print()
if __name__ == "__main__":
unittest.main(verbosity=2)
+296
View File
@@ -0,0 +1,296 @@
import unittest
import os
import time
import random
import RNS
from RNS import Transport
IFAC_TEST_SEED = 0x1FACAD3
IFAC_NETNAME = b"rns-ifac-test-net"
def rand_bytes(rng, length):
return bytes(rng.randrange(256) for _ in range(length))
class FakeInterface:
def __init__(self, ifac_size, ifac_key):
self.ifac_size = ifac_size
self.ifac_key = ifac_key
self.ifac_identity = RNS.Identity.from_bytes(ifac_key)
self.violations = []
def ifac_violation(self, description):
self.violations.append(description)
def make_interface(ifac_size):
ifac_key = RNS.Cryptography.hkdf(length=64, derive_from=RNS.Identity.full_hash(IFAC_NETNAME),
salt=RNS.Reticulum.IFAC_SALT, context=None)
return FakeInterface(ifac_size, ifac_key)
def make_plain_packet(rng, size, pattern="random"):
"""Generate a deterministic protocol-realistic packet: a random or
structured payload with the IFAC flag bit of the first header byte
clear (as plaintext frames always have)."""
if pattern == "random": raw = rand_bytes(rng, size)
elif pattern == "zeros": raw = bytes(size)
elif pattern == "ones": raw = bytes([0xFF]) * size
elif pattern == "seq": raw = bytes((i % 256) for i in range(size))
else: raise ValueError(f"Unknown pattern {pattern}")
raw = bytearray(raw)
raw[0] &= 0x7F
return bytes(raw)
class TestIFAC(unittest.TestCase):
def test_01_outgoing_parity(self):
print("")
rng = random.Random(IFAC_TEST_SEED)
sizes = [8, 16, 32, 100, 500, 1064, 4096, 16384]
ifac_sizes = [1, 8, 16]
patterns = ["random", "zeros", "ones", "seq"]
verified = 0
for size in sizes:
for ifac_size in ifac_sizes:
iface = make_interface(ifac_size)
for pattern in patterns:
raw = make_plain_packet(rng, size, pattern)
out_new = Transport.handle_outgoing_ifac(iface, raw)
out_leg = Transport.handle_outgoing_ifac_legacy(iface, raw)
self.assertEqual(out_new, out_leg)
self.assertEqual(len(out_new), size + ifac_size)
verified += 1
for ifac_size in (8, 16):
iface = make_interface(ifac_size)
raw = make_plain_packet(rng, 262144, "random")
out_new = Transport.handle_outgoing_ifac(iface, raw)
out_leg = Transport.handle_outgoing_ifac_legacy(iface, raw)
self.assertEqual(out_new, out_leg)
verified += 1
print(f"IFAC outgoing parity: {verified} deterministic cases verified")
def test_02_incoming_parity(self):
print("")
rng = random.Random(IFAC_TEST_SEED ^ 0x1FAC)
sizes = [8, 16, 32, 100, 500, 1064, 4096, 16384]
ifac_sizes = [1, 8, 16]
patterns = ["random", "zeros", "ones", "seq"]
verified = 0
for size in sizes:
for ifac_size in ifac_sizes:
iface = make_interface(ifac_size)
for pattern in patterns:
raw = make_plain_packet(rng, size, pattern)
frame = Transport.handle_outgoing_ifac(iface, raw)
ok_new, out_new = Transport.handle_ifac(frame, iface)
ok_leg, out_leg = Transport.handle_ifac_legacy(frame, iface)
self.assertTrue(ok_new)
self.assertTrue(ok_leg)
self.assertEqual(out_new, out_leg)
verified += 1
for ifac_size in (8, 16):
iface = make_interface(ifac_size)
raw = make_plain_packet(rng, 262144, "random")
frame = Transport.handle_outgoing_ifac(iface, raw)
ok_new, out_new = Transport.handle_ifac(frame, iface)
ok_leg, out_leg = Transport.handle_ifac_legacy(frame, iface)
self.assertTrue(ok_new)
self.assertTrue(ok_leg)
self.assertEqual(out_new, out_leg)
verified += 1
print(f"IFAC incoming parity: {verified} deterministic cases verified")
def test_03_roundtrip(self):
print("")
rng = random.Random(IFAC_TEST_SEED ^ 0x0FAC)
# All four TX/RX handler combinations must recover the original packet
combos = [
(Transport.handle_outgoing_ifac, Transport.handle_ifac),
(Transport.handle_outgoing_ifac, Transport.handle_ifac_legacy),
(Transport.handle_outgoing_ifac_legacy, Transport.handle_ifac),
(Transport.handle_outgoing_ifac_legacy, Transport.handle_ifac_legacy),
]
sizes = [16, 1064, 16384]
ifac_sizes = [1, 8, 16]
verified = 0
for tx, rx in combos:
for size in sizes:
for ifac_size in ifac_sizes:
iface = make_interface(ifac_size)
raw = make_plain_packet(rng, size, "random")
frame = tx(iface, raw)
ok, out = rx(frame, iface)
self.assertTrue(ok)
self.assertEqual(out, raw)
verified += 1
print(f"IFAC round-trip: {verified} deterministic TX/RX combinations verified\n All four handler pairings recover the packet exactly.")
def test_04_invariants(self):
print("")
rng = random.Random(IFAC_TEST_SEED ^ 0xCAFE)
iface = make_interface(16)
for size in (16, 1064, 16384):
raw = make_plain_packet(rng, size, "random")
out_new = Transport.handle_outgoing_ifac(iface, raw)
out_leg = Transport.handle_outgoing_ifac_legacy(iface, raw)
# IFAC flag must be set on the masked frame
self.assertEqual(out_new[0] & 0x80, 0x80)
# The IFAC tag region must be transmitted in the clear and
# identical in both implementations
self.assertEqual(out_new[2:2+iface.ifac_size], out_leg[2:2+iface.ifac_size])
self.assertEqual(out_new[2:2+iface.ifac_size], iface.ifac_identity.sign(raw)[-iface.ifac_size:])
# Second header byte must be masked identically
self.assertEqual(out_new[1], out_leg[1])
# The incoming handler must clear the IFAC flag in its output
ok, out = Transport.handle_ifac(out_new, iface)
self.assertTrue(ok)
self.assertEqual(out[0] & 0x80, 0)
print("IFAC invariants: flag set on frame, tag in clear and identical, flag cleared on input recovery")
def test_05_invalid_tags(self):
print("")
rng = random.Random(IFAC_TEST_SEED ^ 0xBAD)
sizes = [100, 1064, 16384]
ifac_sizes = [1, 8, 16]
for size in sizes:
for ifac_size in ifac_sizes:
iface = make_interface(ifac_size)
raw = make_plain_packet(rng, size, "random")
frame = bytearray(Transport.handle_outgoing_ifac(iface, raw))
corruptions = []
# Corrupt a masked payload byte
corrupted = bytearray(frame)
corrupted[-1] ^= 0x01
corruptions.append(bytes(corrupted))
# Corrupt the second header byte
corrupted = bytearray(frame)
corrupted[1] ^= 0x40
corruptions.append(bytes(corrupted))
# Corrupt a byte in the IFAC tag region
if ifac_size > 0:
corrupted = bytearray(frame)
corrupted[2 + ifac_size//2] ^= 0x01
corruptions.append(bytes(corrupted))
for corrupted in corruptions:
ok_new, out_new = Transport.handle_ifac(corrupted, iface)
ok_leg, out_leg = Transport.handle_ifac_legacy(corrupted, iface)
# Both implementations must behave identically on any
# corrupted frame, including the violation report
self.assertEqual(ok_new, ok_leg)
self.assertEqual(out_new, out_leg)
self.assertEqual(iface.violations[-1:], ["Invalid IFAC on packet"])
# With >= 8 bytes of tag entropy, rejection is
# deterministic. At ifac_size = 1 the truncated tag has
# only 8 bits, so a corrupted frame can statistically
# collide with the original truncation (1/256) - both
# implementations behave identically either way.
if ifac_size >= 8: self.assertFalse(ok_new)
print("IFAC invalid tags: behaviour and violation reporting identical "
"between implementations; deterministic rejection verified for "
"8+ byte tags")
@unittest.skipIf(os.getenv("RNS_SKIP_PERF_TESTS") != None, "Skipping performance tests")
def test_06_benchmark(self):
print("")
rng = random.Random(IFAC_TEST_SEED ^ 0xBEEF)
sizes = [1500, 16384, 262144]
runs = {1500: 30, 16384: 15, 262144: 5}
print("IFAC handler benchmark (optimized vs legacy):")
print(f"{'size':>8} {'out lgc':>11} {'out opt':>11} {'out spd':>8} | "
f"{'in lgc':>11} {'in new':>11} {'in spd':>8}")
print("-" * 84)
total_leg = total_new = 0.0
for size in sizes:
iface = make_interface(16)
raw = make_plain_packet(rng, size, "random")
frame = Transport.handle_outgoing_ifac(iface, raw)
n = runs[size]
# Warmup
Transport.handle_outgoing_ifac_legacy(iface, raw)
Transport.handle_outgoing_ifac(iface, raw)
Transport.handle_ifac_legacy(frame, iface)
Transport.handle_ifac(frame, iface)
t0 = time.perf_counter()
for _ in range(n): Transport.handle_outgoing_ifac_legacy(iface, raw)
out_leg = (time.perf_counter() - t0) / n
t0 = time.perf_counter()
for _ in range(n): Transport.handle_outgoing_ifac(iface, raw)
out_new = (time.perf_counter() - t0) / n
t0 = time.perf_counter()
for _ in range(n): Transport.handle_ifac_legacy(frame, iface)
in_leg = (time.perf_counter() - t0) / n
t0 = time.perf_counter()
for _ in range(n): Transport.handle_ifac(frame, iface)
in_new = (time.perf_counter() - t0) / n
total_leg += out_leg + in_leg
total_new += out_new + in_new
def ms(t): return f"{t*1000:.3f}m"
print(f"{size:>8} {ms(out_leg):>11} {ms(out_new):>11} {out_leg/out_new:7.1f}x | "
f"{ms(in_leg):>11} {ms(in_new):>11} {in_leg/in_new:7.1f}x")
print(f"\nCombined TX+RX at {sizes[-1]} bytes: legacy "
f"{(out_leg+in_leg)*1000:.2f} ms/pkt, optimized {(out_new+in_new)*1000:.2f} ms/pkt, "
f"{(out_leg+in_leg)/(out_new+in_new):.1f}x speedup")
print(f"Overall speedup across benchmarks: {total_leg/total_new:.1f}x")
print()
if __name__ == "__main__":
unittest.main(verbosity=2)
+951
View File
@@ -0,0 +1,951 @@
#!/usr/bin/env python3
#
# Usage examples:
#
# python3 tests/transport_throughput.py
# python3 tests/transport_throughput.py --scenario transit_single_135
# python3 tests/transport_throughput.py --mode inline --runs 5
# python3 tests/transport_throughput.py --list-scenarios
#
import unittest
import os
import sys
import time
import gc
import struct
import platform
import tempfile
import statistics
# Ensure that the Reticulum tree this suite lives in is the one being
# benchmarked, even if a different version of Reticulum is installed in
# site-packages.
_SUITE_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if os.path.isdir(os.path.join(_SUITE_ROOT, "RNS")):
sys.path.insert(0, _SUITE_ROOT)
import RNS
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
BENCHMARK_CONFIG = {
"scenarios": None, # None = all, or a list of scenario names
"mode": "both", # "inline", "drainer" or "both"
"runs": 3, # measurement runs per scenario/mode, median is reported
}
SCENARIO_DESCRIPTIONS = {
"transit_single_135": "SINGLE transit relay, 135 B payload, 3-hop path",
"transit_single_475": "SINGLE transit relay, 475 B payload, 3-hop path",
"transit_single_1024": "SINGLE transit relay, 1 KiB payload, 3-hop path",
"transit_single_16384": "SINGLE transit relay, 16 KiB payload, 3-hop path",
"transit_single_final": "SINGLE transit relay, final hop, header strip, 135 B",
"transit_link_135": "LINK transit relay via link table, cross-interface, 135 B",
"transit_link_475": "LINK transit relay via link table, cross-interface, 475 B",
"transit_link_1024": "LINK transit relay via link table, cross-interface, 1024 B",
"transit_link_16384": "LINK transit relay via link table, cross-interface, 16384 B",
"transit_link_32768": "LINK transit relay via link table, cross-interface, 32768 B",
"terminus_link": "LINK terminus delivery, token decrypt, 135 B",
"terminus_single": "SINGLE local delivery, ephemeral-key decrypt, 135 B",
"announce_ingress": "Announce ingress, fresh destinations, validation + path insert",
"outbound_path": "Outbound insertion into transport, known 3-hop path, 135 B",
}
# Default packet counts per scenario and mode.
DEFAULT_PACKETS = {
"transit_single_135": {"inline": 20000, "drainer": 20000},
"transit_single_475": {"inline": 20000, "drainer": 20000},
"transit_single_1024": {"inline": 20000, "drainer": 20000},
"transit_single_16384": {"inline": 10000, "drainer": 10000},
"transit_single_final": {"inline": 20000, "drainer": 20000},
"transit_link_135": {"inline": 20000, "drainer": 20000},
"transit_link_475": {"inline": 20000, "drainer": 20000},
"transit_link_1024": {"inline": 20000, "drainer": 20000},
"transit_link_16384": {"inline": 10000, "drainer": 10000},
"transit_link_32768": {"inline": 10000, "drainer": 10000},
"terminus_link": {"inline": 6000, "drainer": 6000},
"terminus_single": {"inline": 3000, "drainer": 3000},
"announce_ingress": {"inline": 1000, "drainer": 1000},
"outbound_path": {"inline": 8000, "drainer": 0},
}
INLINE_SAMPLE_STEP = 64 # sample a timing point every N packets for p50/p95
DRAINER_CHUNK = 256 # packets fed per drainer backpressure step
class BenchmarkInterface(RNS.Interfaces.Interface.Interface):
HW_MTU = 1048576
BITRATE = 1_000_000_000
def __init__(self, name="bench"):
super().__init__()
self.name = name
self.IN = True
self.OUT = True
self.online = True
self.bitrate = self.BITRATE
self.HW_MTU = BenchmarkInterface.HW_MTU
self.mode = RNS.Interfaces.Interface.Interface.MODE_FULL
self.gravity = 0
self.ifac_size = 0
self.ifac_key = None
self.ifac_identity = None
self.parent_interface = None
self.ingress_control = False
self.announce_rate_target = RNS.Interfaces.Interface.Interface.DEFAULT_AR_TARGET
self.announce_rate_grace = RNS.Interfaces.Interface.Interface.DEFAULT_AR_GRACE
self.announce_rate_penalty = RNS.Interfaces.Interface.Interface.DEFAULT_AR_PENALTY
def process_outgoing(self, data):
self.txb += len(data)
def __str__(self):
return f"BenchmarkInterface[{self.name}]"
class Scenario:
kind = "ingress" # "ingress" or "outbound"
def __init__(self, name, description, interface, frames, packets, runs,
inline_offset, drainer_offset, size, completion_counter=None,
fresh_per_run=False):
self.name = name
self.description = description
self.interface = interface
self.frame_size = size
self.frames = frames # pool of unique raw frames
self.packets_inline = packets.get("inline", 0)
self.packets_drainer = packets.get("drainer", 0)
self.runs = runs
self.inline_offset = inline_offset
self.drainer_offset = drainer_offset
self.completion_counter = completion_counter
# When true, each run uses a dedicated fresh slice of frames
# (required where processing is not idempotent, e.g. announces).
# When false, runs reuse the same pool with the duplicate filter
# reset in between.
self.fresh_per_run = fresh_per_run
def can_drainer(self):
return self.packets_drainer > 0 and self.completion_counter is not None
def n_for_mode(self, mode):
if mode == "inline": return self.packets_inline
if mode == "drainer": return self.packets_drainer
class CountingDestination(RNS.Destination):
"""A destination that counts successful deliveries, for use as a
completion counter in drainer mode."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.delivered = 0
def receive(self, packet):
result = super().receive(packet)
if result:
self.delivered += 1
return result
def _register_link(link):
with RNS.Transport.active_links_lock:
RNS.Transport.active_links.append(link)
if hasattr(RNS.Transport, "active_links_map"):
RNS.Transport.active_links_map[link.link_id] = link
def _make_minimal_link(instance, interface):
"""Constructs a minimal, active Link object suitable for benchmark delivery."""
import importlib
_link_mod = importlib.import_module("RNS.Link")
link = RNS.Link.__new__(RNS.Link)
link.mode = RNS.Link.MODE_DEFAULT
link.rtt = 0.1
link.mtu = RNS.Reticulum.MTU
link.establishment_cost = 0
link.establishment_rate = None
link.expected_rate = None
link.callbacks = _link_mod.LinkCallbacks()
link.resource_strategy = RNS.Link.ACCEPT_NONE
link.last_resource_window = None
link.last_resource_eifr = None
link.outgoing_resources = []
link.incoming_resources = []
link.pending_requests = []
link.last_inbound = 0
link.last_outbound = 0
link.last_keepalive = 0
link.last_proof = 0
link.last_data = 0
link.tx = 0
link.rx = 0
link.txbytes = 0
link.rxbytes = 0
link.rssi = None
link.snr = None
link.q = None
link.traffic_timeout_factor = RNS.Link.TRAFFIC_TIMEOUT_FACTOR
link.keepalive_timeout_factor = RNS.Link.KEEPALIVE_TIMEOUT_FACTOR
link.keepalive = RNS.Link.KEEPALIVE
link.stale_time = RNS.Link.STALE_TIME
link.watchdog_lock = False
link.status = RNS.Link.ACTIVE
link.activated_at = time.time()
link.type = RNS.Destination.LINK
link.owner = instance
link.initiator = False
link.expected_hops = 1
link.rebalanced = None
link.attached_interface = interface
link._channel = None
link._Link__remote_identity = None
link._Link__track_phy_stats = False
link.derived_key = os.urandom(64)
link.token = RNS.Cryptography.Token(link.derived_key)
link.link_id = os.urandom(RNS.Reticulum.TRUNCATED_HASHLENGTH//8)
link.hash = link.link_id
link.hexhash = link.link_id.hex()
from RNS.Cryptography.Proxies import Ed25519PrivateKeyProxy
link.sig_prv = Ed25519PrivateKeyProxy.from_private_bytes(link.derived_key[:32])
class _DestinationShim:
pass
link.destination = _DestinationShim()
link.destination.type = RNS.Destination.LINK
link.destination.proof_strategy = RNS.Destination.PROVE_NONE
_dest_mod = importlib.import_module("RNS.Destination")
link.destination.callbacks = _dest_mod.Callbacks()
link.destination.status = RNS.Link.ACTIVE
link.destination.last_outbound = 0
link.destination.tx = 0
link.destination.txbytes = 0
link.destination.attached_interface = interface
link.destination.mtu = RNS.Reticulum.MTU
link.destination.rssi = None
link.destination.snr = None
link.destination.q = None
link.destination.rtt = RNS.Link.TRAFFIC_TIMEOUT_MIN_MS/1000
link.destination.traffic_timeout_factor = 1.0
return link
def _transit_single_frame(interface, dst_h, payload):
"""One HEADER_2|TRANSPORT|SINGLE|DATA frame addressed to this instance."""
flags = (RNS.Packet.HEADER_2 << 6) | (RNS.Transport.TRANSPORT << 4) \
| (RNS.Destination.SINGLE << 2) | RNS.Packet.DATA
return (struct.pack("!B", flags) + struct.pack("!B", 1)
+ RNS.Transport.identity.hash + dst_h
+ bytes([RNS.Packet.NONE]) + payload)
def _transit_link_frame(interface, link_id, payload):
"""One HEADER_2|TRANSPORT|LINK|DATA frame addressed to this instance."""
flags = (RNS.Packet.HEADER_2 << 6) | (RNS.Transport.TRANSPORT << 4) \
| (RNS.Destination.LINK << 2) | RNS.Packet.DATA
return (struct.pack("!B", flags) + struct.pack("!B", 1)
+ RNS.Transport.identity.hash + link_id
+ bytes([RNS.Packet.NONE]) + payload)
def _terminus_link_frame(link, payload):
"""One HEADER_1|BROADCAST|LINK|DATA frame for a local active link,
encrypted with the link token."""
flags = (RNS.Packet.HEADER_1 << 6) | (RNS.Transport.BROADCAST << 4) \
| (RNS.Destination.LINK << 2) | RNS.Packet.DATA
ciphertext = link.encrypt(payload)
return (struct.pack("!B", flags) + struct.pack("!B", 0)
+ link.link_id + bytes([RNS.Packet.NONE]) + ciphertext)
def _payload(i, size, marker):
"""Deterministic, unique payload of `size` bytes."""
return i.to_bytes(8, "big") + bytes([marker]) * (size - 8)
def build_scenarios(instance, interface, interface_b, requested=None):
"""Builds all benchmark scenarios and returns a dict name -> Scenario."""
scenarios = {}
runs = BENCHMARK_CONFIG["runs"]
def _slices(packets, fresh=False):
inline_n = packets.get("inline", 0)
drainer_n = packets.get("drainer", 0)
if fresh:
# Fresh frames per run for both modes
total = (inline_n + drainer_n) * runs
return total, inline_n, drainer_n, 0, inline_n * runs
else:
# One re-usable pool of the largest mode's frame count
total = max(inline_n, drainer_n)
return total, inline_n, drainer_n, 0, 0
# --- SINGLE transit relay, several payload sizes -----------------------
sizes = [("135", 135), ("475", 475), ("1024", 1024), ("16384", 16384)]
for suffix, size in sizes:
name = f"transit_single_{suffix}"
total, inline_n, drainer_n, off_i, off_d = _slices(DEFAULT_PACKETS[name])
dst_h = RNS.Cryptography.hkdf(length=16,
derive_from=f"T{suffix}dst".encode(),
salt=b"bench", context=None)
next_hop = RNS.Cryptography.hkdf(length=16,
derive_from=f"T{suffix}nh".encode(),
salt=b"bench", context=None)
now = time.time()
with RNS.Transport.path_table_lock:
RNS.Transport.path_table[dst_h] = [
now, next_hop, 3, now + 3600, [], interface, bytes(32)
]
frames = [_transit_single_frame(interface, dst_h,
_payload(i, size, 0x57))
for i in range(total)]
scenarios[name] = Scenario(
name,
f"SINGLE transit relay, {size} B payload, 3-hop path",
interface, frames, DEFAULT_PACKETS[name], runs,
off_i, off_d, size,
completion_counter=lambda: RNS.Transport.tx_packets,
)
# --- SINGLE transit relay, final hop (header strip) --------------------
name = "transit_single_final"
total, inline_n, drainer_n, off_i, off_d = _slices(DEFAULT_PACKETS[name])
dst_h = RNS.Cryptography.hkdf(length=16, derive_from=b"TFdst",
salt=b"bench", context=None)
next_hop = RNS.Cryptography.hkdf(length=16, derive_from=b"TFnh",
salt=b"bench", context=None)
now = time.time()
with RNS.Transport.path_table_lock:
RNS.Transport.path_table[dst_h] = [
now, next_hop, 1, now + 3600, [], interface, bytes(32)
]
frames = [_transit_single_frame(interface, dst_h,
_payload(i, 135, 0x46))
for i in range(total)]
scenarios[name] = Scenario(
name,
"SINGLE transit relay, final hop, transport header strip, 135 B",
interface, frames, DEFAULT_PACKETS[name], runs,
off_i, off_d, 135,
completion_counter=lambda: RNS.Transport.tx_packets,
)
# --- LINK transit relay (cross-interface) ------------------------------
sizes = [("135", 135), ("475", 475), ("1024", 1024), ("16384", 16384), ("32768", 32768)]
for suffix, size in sizes:
name = f"transit_link_{suffix}"
total, inline_n, drainer_n, off_i, off_d = _slices(DEFAULT_PACKETS[name])
link_id = RNS.Cryptography.hkdf(length=16, derive_from=b"Llink",
salt=b"bench", context=None)
now = time.time()
with RNS.Transport.link_table_lock:
# timestamp, next-hop transport id, outbound iface, remaining hops,
# received-on iface, taken hops, original destination hash,
# validated, proof timeout
RNS.Transport.link_table[link_id] = [
now, RNS.Transport.identity.hash, interface_b, 2,
interface, 2, os.urandom(16), True, now + 60
]
frames = [_transit_link_frame(interface, link_id,
_payload(i, size, 0x4C))
for i in range(total)]
scenarios[name] = Scenario(
name,
f"LINK transit relay via link table, cross-interface, {size} B",
interface, frames, DEFAULT_PACKETS[name], runs,
off_i, off_d, size,
completion_counter=lambda: RNS.Transport.tx_packets,
)
# --- LINK terminus delivery --------------------------------------------
name = "terminus_link"
total, inline_n, drainer_n, off_i, off_d = _slices(DEFAULT_PACKETS[name])
link = _make_minimal_link(instance, interface)
_register_link(link)
frames = [_terminus_link_frame(link, _payload(i, 135, 0x6C))
for i in range(total)]
scenarios[name] = Scenario(
name,
"LINK terminus delivery, token decrypt, no app callback, 135 B",
interface, frames, DEFAULT_PACKETS[name], runs,
off_i, off_d, 135,
completion_counter=lambda: link.rx,
)
# --- SINGLE local delivery ---------------------------------------------
name = "terminus_single"
total, inline_n, drainer_n, off_i, off_d = _slices(DEFAULT_PACKETS[name])
identity = RNS.Identity()
# The Destination initialiser automatically registers IN destinations
# with the transport core.
destination = CountingDestination(identity, RNS.Destination.IN,
RNS.Destination.SINGLE,
"bench", "terminus")
frames = []
for i in range(total):
packet = RNS.Packet(destination, _payload(i, 135, 0x53),
RNS.Packet.DATA, create_receipt=False)
packet.pack()
frames.append(packet.raw)
scenarios[name] = Scenario(
name,
"SINGLE local delivery, ephemeral-key decrypt, 135 B",
interface, frames, DEFAULT_PACKETS[name], runs,
off_i, off_d, 135,
completion_counter=lambda: destination.delivered,
)
# --- Announce ingress ----------------------------------------------------
name = "announce_ingress"
total, inline_n, drainer_n, off_i, off_d = _slices(DEFAULT_PACKETS[name],
fresh=True)
name_hash = RNS.Identity.full_hash(b"rns.throughput.bench")[
:RNS.Identity.NAME_HASH_LENGTH//8]
frames = []; tsize = 0
for i in range(total):
ann_identity = RNS.Identity()
dst_h = RNS.Identity.full_hash(name_hash + ann_identity.hash)[
:RNS.Reticulum.TRUNCATED_HASHLENGTH//8]
random_hash = os.urandom(5) + int(time.time() + i).to_bytes(5, "big")
signed_data = dst_h + ann_identity.get_public_key() + name_hash \
+ random_hash + b""
signature = ann_identity.sign(signed_data)
announce_data = ann_identity.get_public_key() + name_hash \
+ random_hash + b"" + signature
flags = (RNS.Packet.HEADER_1 << 6) \
| (RNS.Destination.SINGLE << 2) | RNS.Packet.ANNOUNCE
fbs = struct.pack("!B", flags) + struct.pack("!B", 0) + dst_h + bytes([RNS.Packet.NONE]) + announce_data
frames.append(fbs)
tsize += len(fbs)
scenarios[name] = Scenario(
name,
"Announce ingress, fresh destinations, validation + path insert",
interface, frames, DEFAULT_PACKETS[name], runs,
off_i, off_d, int(tsize/total),
completion_counter=lambda: len(RNS.Transport.path_table),
fresh_per_run=True,
)
# --- Outbound insertion into transport ----------------------------------
name = "outbound_path"
packets = DEFAULT_PACKETS[name]
inline_n = packets.get("inline", 0)
total = inline_n # pool is re-used across runs
dst_h = RNS.Cryptography.hkdf(length=16, derive_from=b"Odst",
salt=b"bench", context=None)
next_hop = RNS.Cryptography.hkdf(length=16, derive_from=b"Onh",
salt=b"bench", context=None)
now = time.time()
with RNS.Transport.path_table_lock:
RNS.Transport.path_table[dst_h] = [
now, next_hop, 3, now + 3600, [], interface, bytes(32)
]
remote_id = RNS.Identity(create_keys=False)
remote_id.load_public_key(os.urandom(RNS.Identity.KEYSIZE//8))
outbound_destination = RNS.Destination(remote_id, RNS.Destination.OUT,
RNS.Destination.SINGLE,
"bench", "outbound")
outbound_destination.hash = dst_h
outbound_destination.hexhash = dst_h.hex()
frames = []
for i in range(total):
packet = RNS.Packet(outbound_destination, _payload(i, 135, 0x4F),
RNS.Packet.DATA, create_receipt=False)
packet.pack()
frames.append(packet)
outbound = Scenario(
name,
"Outbound insertion into transport, known 3-hop path, 135 B",
interface, frames, packets, runs,
0, 0, 135,
completion_counter=None,
)
outbound.kind = "outbound"
scenarios[name] = outbound
if requested is not None:
missing = [s for s in requested if s not in scenarios]
if missing:
raise KeyError(f"Unknown scenario(s): {', '.join(missing)}. "
f"Available: {', '.join(sorted(scenarios))}")
scenarios = {name: scenarios[name] for name in requested}
return scenarios
def _reset_transport_state():
RNS.Transport.packet_hashlist = set()
RNS.Transport.packet_hashlist_prev = set()
RNS.Transport.reverse_table = {}
def _percentile(sorted_values, p):
if not sorted_values:
return 0.0
index = min(len(sorted_values) - 1, int(len(sorted_values) * p))
return sorted_values[index]
def _feed(frame, interface):
RNS.Transport.preprocess_inbound(frame, interface)
def _bench_inline(interface, frames, n, runs, offset, fresh_per_run=False):
"""Synchronous benchmark: process each frame in the calling thread,
bypassing the inbound queue. Returns (run_means_us, samples_us)."""
run_means = []
all_samples = []
# Bypass the inbound queue so processing happens entirely in the
# calling thread; restore the previous setting afterwards.
previous_queue_state = RNS.Transport.USE_INBOUND_QUEUE
RNS.Transport.USE_INBOUND_QUEUE = False
try:
for r in range(runs):
_reset_transport_state()
gc.collect()
gc.disable()
base = offset + (r * n if fresh_per_run else 0)
t0 = time.perf_counter()
prev = None
samples = []
step = INLINE_SAMPLE_STEP
next_sample = step
for i in range(n):
_feed(frames[base + i], interface)
if i == next_sample:
now = time.perf_counter()
if prev is not None:
samples.append((now - prev) / step)
prev = now
next_sample += step
dt = time.perf_counter() - t0
gc.enable()
run_means.append(dt / n * 1e6)
all_samples.extend(samples)
finally:
RNS.Transport.USE_INBOUND_QUEUE = previous_queue_state
return run_means, [s * 1e6 for s in all_samples]
def _bench_drainer(scenario, n, runs):
"""Feed frames through the inbound queue from the calling thread
while the drainer thread processes them. Backpressure is applied
via the scenario completion counter, so no frames are dropped and
the pipeline stays saturated."""
run_means = []
# Ensure the inbound queue and drainer are used; restore afterwards.
previous_queue_state = RNS.Transport.USE_INBOUND_QUEUE
RNS.Transport.USE_INBOUND_QUEUE = True
try:
for r in range(runs):
_reset_transport_state()
gc.collect()
gc.disable()
base = scenario.drainer_offset \
+ (r * n if scenario.fresh_per_run else 0)
baseline = scenario.completion_counter()
fed = 0
t0 = time.perf_counter()
chunk = DRAINER_CHUNK
while fed < n:
batch = min(chunk, n - fed)
for i in range(fed, fed + batch):
_feed(scenario.frames[base + i], scenario.interface)
fed += batch
target = baseline + fed
while scenario.completion_counter() < target-800: # Assumes default inbound queue of 1024
time.sleep(0.0002)
dt = time.perf_counter() - t0
gc.enable()
run_means.append(dt / n * 1e6)
finally:
RNS.Transport.USE_INBOUND_QUEUE = previous_queue_state
return run_means
def _bench_outbound(packets, n, runs, offset):
"""Synchronous benchmark of the outbound path: insert each packet
into transport for a known path via Transport.outbound(). The packet
pool is re-used across runs."""
run_means = []
for r in range(runs):
gc.collect()
gc.disable()
t0 = time.perf_counter()
for i in range(n):
RNS.Transport.outbound(packets[offset + i])
dt = time.perf_counter() - t0
gc.enable()
run_means.append(dt / n * 1e6)
return run_means
# ---------------------------------------------------------------------------
# Output helpers
# ---------------------------------------------------------------------------
def _fmt_us(value):
return f"{value:>10.2f}"
def _fmt_pps(value):
return f"{value:>12,.0f}"
def print_environment_header():
tree_fastpath = "present" if hasattr(RNS.Transport, "USE_FP_CACHE") else "absent"
print("=" * 40)
print("Reticulum Transport Throughput Benchmark")
print("=" * 40)
print(f" RNS version : {RNS.__version__}")
print(f" Mode : {'compiled' if RNS.compiled else 'interpreted'}")
print(f" crypto : {RNS.Cryptography.backend()}")
print(f" transport : enabled")
print(f" fast path : {tree_fastpath}")
print(f" python : {platform.python_version()}")
print(f" platform : {platform.platform()}")
print(f" machine : {platform.machine()}, cpus: {os.cpu_count()}")
print()
def print_scenario_table(scenario, results):
"""results: dict mode -> dict(runs, mean_us, pps, stdev, p50, p95)."""
print(f"Scenario: {scenario.name} - {scenario.description}")
print(f" {'mode':<9}{'n':>8}{'runs':>6}{'mean µs':>13}{'pps':>16}"
f"{'p50':>11}{'p95':>11}")
print(" " + "-" * 75)
for mode in ("inline", "drainer"):
if mode not in results:
continue
r = results[mode]
n = scenario.n_for_mode(mode)
p50 = f"{r['p50']:>9.2f} µs" if r["p50"] is not None else "-"
p95 = f"{r['p95']:>9.2f} µs" if r["p95"] is not None else "-"
spread = ""
if r.get("stdev") is not None:
spread = f" ±{r['stdev']:.2f}"
if mode == "inline": mode = "direct"
print(f" {mode:<9}{n:>8}{r['runs']:>6}{_fmt_us(r['mean_us']):>13}"
f"{_fmt_pps(r['pps']):>16}{p50:>11}{p95:>11} "
f"({r['runs']} runs, median{spread})")
print()
for mode in ("inline", "drainer"):
if mode not in results:
continue
r = results[mode]
tp = r['pps']*scenario.frame_size*8
if mode == "inline": mode = "direct"
print(f"{mode:<8} : {RNS.prettyspeed(tp)}")
print()
def print_pps_matrix(rows):
"""rows: list of (scenario_name, inline_pps, drainer_pps, fsize)"""
if not rows:
return
print("-" * 72)
print("Transport Throughput, median of runs")
print(f" {'scenario':<22}{'direct':>14}{'drainer':>14}")
print(" " + "-" * 70)
for name, inline_pps, drainer_pps, fsize in rows:
i = f"{inline_pps:>12,.0f}" if inline_pps else "-"
d = f"{drainer_pps:>12,.0f}" if drainer_pps else "-"
itp = RNS.prettyspeed(inline_pps*fsize*8) if inline_pps else "-"
dtp = RNS.prettyspeed(drainer_pps*fsize*8) if drainer_pps else "-"
print(f" {name:<22}{i:>14}{d:>14}{itp:>16} / {dtp}")
print()
# ---------------------------------------------------------------------------
# Test suite
# ---------------------------------------------------------------------------
_instance = None
_interfaces = None
_scenarios = None
_config_dir = None
def _start_transport():
global _instance, _interfaces, _scenarios, _config_dir
_config_dir = tempfile.mkdtemp(prefix="rns-transport-bench-")
config_dir = _config_dir
with open(os.path.join(config_dir, "config"), "w") as fh:
fh.write(
"[reticulum]\n"
" enable_transport = yes\n"
" share_instance = No\n"
" panic_on_interface_error = No\n"
"\n"
"[logging]\n"
" loglevel = 0\n"
"\n"
"[interfaces]\n"
)
# Raise queue lengths for to avoid drops
# at high feed rates
RNS.Transport.INBOUND_DA_QUEUE_LENGTH = 4096
RNS.Transport.INBOUND_AN_QUEUE_LENGTH = 1024
RNS.Transport.INBOUND_PR_QUEUE_LENGTH = 1024
RNS.Transport.INBOUND_IL_QUEUE_LENGTH = 1024
_instance = RNS.Reticulum(configdir=config_dir,
loglevel=RNS.LOG_CRITICAL,
logdest=lambda *a, **k: None)
while not RNS.Transport.ready:
time.sleep(0.05)
interface = BenchmarkInterface("line-a")
interface_b = BenchmarkInterface("line-b")
RNS.Transport.add_interface(interface)
RNS.Transport.add_interface(interface_b)
RNS.Transport.prioritize_interfaces()
_interfaces = (interface, interface_b)
requested = BENCHMARK_CONFIG["scenarios"]
_scenarios = build_scenarios(_instance, interface, interface_b,
requested=requested)
class TestTransportThroughput(unittest.TestCase):
@classmethod
def setUpClass(cls):
if _scenarios is None:
_start_transport()
@classmethod
def tearDownClass(cls):
if RNS.Transport._should_run:
RNS.Transport.exit_handler()
if _config_dir is not None:
import shutil
shutil.rmtree(_config_dir, ignore_errors=True)
def _run_scenario_matrix(self, scenario_names):
rows = []
# Only include scenarios selected via the command line
scenario_names = [name for name in scenario_names
if name in _scenarios]
for name in scenario_names:
scenario = _scenarios[name]
results = {}
mode_filter = BENCHMARK_CONFIG["mode"]
runs = BENCHMARK_CONFIG["runs"]
if scenario.kind == "outbound":
# The outbound path is synchronous; it only has an
# inline-equivalent measurement, and follows the mode
# filter's "inline" selector.
if mode_filter in ("inline", "both"):
run_means = _bench_outbound(scenario.frames,
scenario.packets_inline,
runs, 0)
mean_us = statistics.median(run_means)
results["inline"] = {
"runs": runs,
"mean_us": mean_us,
"pps": 1e6 / mean_us,
"stdev": statistics.stdev(run_means) if len(run_means) > 2 else None,
"p50": None,
"p95": None,
}
else:
if mode_filter in ("inline", "both") and scenario.packets_inline:
n = scenario.packets_inline
run_means, samples = _bench_inline(scenario.interface,
scenario.frames, n, runs,
scenario.inline_offset,
scenario.fresh_per_run)
mean_us = statistics.median(run_means)
stdev = statistics.stdev(run_means) if len(run_means) > 2 else None
sorted_samples = sorted(samples)
results["inline"] = {
"runs": runs,
"mean_us": mean_us,
"pps": 1e6 / mean_us,
"stdev": stdev,
"p50": _percentile(sorted_samples, 0.50),
"p95": _percentile(sorted_samples, 0.95),
}
if mode_filter in ("drainer", "both") and scenario.can_drainer():
n = scenario.packets_drainer
run_means = _bench_drainer(scenario, n, runs)
mean_us = statistics.median(run_means)
stdev = statistics.stdev(run_means) if len(run_means) > 2 else None
results["drainer"] = {
"runs": runs,
"mean_us": mean_us,
"pps": 1e6 / mean_us,
"stdev": stdev,
"p50": None,
"p95": None,
}
if results:
print_scenario_table(scenario, results)
rows.append((name,
results.get("inline", {}).get("pps"),
results.get("drainer", {}).get("pps"),
scenario.frame_size))
print_pps_matrix(rows)
def test_01_transit_throughput(self):
print("")
print_environment_header()
self._run_scenario_matrix([
"transit_single_135",
"transit_single_475",
"transit_single_1024",
"transit_single_16384",
"transit_single_final",
"transit_link_135",
"transit_link_475",
"transit_link_1024",
"transit_link_16384",
"transit_link_32768",
])
def test_02_delivery_throughput(self):
print("")
self._run_scenario_matrix([
"terminus_link_135",
"terminus_link_475",
"terminus_link_1024",
"terminus_link_16384",
"terminus_single",
"announce_ingress",
"outbound_path",
])
def _usage():
return (
"\nUsage: python3 tests/transport_throughput.py [options]\n"
"\n"
"Options:\n"
" -s, --scenario NAME Run only the named scenario\n"
" --mode MODE Measurement mode: inline, drainer or both\n"
" (default: both)\n"
" --runs N Measurement runs per scenario/mode, median\n"
" is reported (default: 3)\n"
" --list-scenarios List available scenarios and exit\n"
" -h, --help Show this help and exit\n"
)
if __name__ == "__main__":
argv = sys.argv[1:]
rest = []
i = 0
while i < len(argv):
arg = argv[i]
if arg in ("-s", "--scenario"):
BENCHMARK_CONFIG["scenarios"] = BENCHMARK_CONFIG["scenarios"] or []
BENCHMARK_CONFIG["scenarios"].append(argv[i + 1])
i += 2
elif arg == "--mode":
mode = argv[i + 1]
if mode not in ("inline", "drainer", "both"):
raise SystemExit(f"Invalid mode '{mode}'" + _usage())
BENCHMARK_CONFIG["mode"] = mode
i += 2
elif arg == "--runs":
BENCHMARK_CONFIG["runs"] = max(1, int(argv[i + 1]))
i += 2
elif arg == "--list-scenarios":
print("\nAvailable scenarios:")
for name in sorted(SCENARIO_DESCRIPTIONS):
print(f" {name:<22} {SCENARIO_DESCRIPTIONS[name]}")
raise SystemExit(0)
elif arg in ("-h", "--help"):
raise SystemExit(_usage())
else:
rest.append(arg)
i += 1
unittest.main(argv=[sys.argv[0]] + rest, verbosity=2)
# Pre:
#
# Transport Throughput - PPS matrix (median of runs)
# scenario direct drainer
# ----------------------------------------------------------------------
# transit_single_135 208,550 184,075 225.23 Mbps / 198.80 Mbps
# transit_single_475 195,652 130,808 743.48 Mbps / 497.07 Mbps
# transit_single_1024 169,828 111,446 1.39 Gbps / 912.97 Mbps
# transit_single_16384 49,618 74,101 6.50 Gbps / 9.71 Gbps
# transit_single_final 204,604 112,925 220.97 Mbps / 121.96 Mbps
# transit_link_135 272,813 234,430 294.64 Mbps / 253.18 Mbps
# transit_link_475 260,003 227,895 988.01 Mbps / 866.00 Mbps
# transit_link_1024 232,763 145,872 1.91 Gbps / 1.19 Gbps
# transit_link_16384 84,028 73,313 11.01 Gbps / 9.61 Gbps
#
# terminus_single 29,813 25,663 32.20 Mbps / 27.72 Mbps
# announce_ingress 7,561 7,242 10.10 Mbps / 9.68 Mbps
# outbound_path 696,106 - 751.79 Mbps / -
#
# No Fastpath:
#
# Transport Throughput - PPS matrix (median of runs)
# scenario direct drainer
# ----------------------------------------------------------------------
# transit_single_135 247,667 162,090 267.48 Mbps / 175.06 Mbps
# transit_single_475 233,514 159,717 887.35 Mbps / 606.92 Mbps
# transit_single_1024 211,443 175,994 1.73 Gbps / 1.44 Gbps
# transit_single_16384 78,963 72,532 10.35 Gbps / 9.51 Gbps
# transit_single_final 240,855 112,702 260.12 Mbps / 121.72 Mbps
# transit_link_135 266,614 220,571 287.94 Mbps / 238.22 Mbps
# transit_link_475 256,347 152,410 974.12 Mbps / 579.16 Mbps
# transit_link_1024 228,080 194,444 1.87 Gbps / 1.59 Gbps
# transit_link_16384 82,149 73,720 10.77 Gbps / 9.66 Gbps
#
# terminus_single 29,764 28,308 32.15 Mbps / 30.57 Mbps
# announce_ingress 7,394 7,150 9.88 Mbps / 9.55 Mbps
# outbound_path 872,747 - 942.57 Mbps / -
# ----------------------------------------------------------------------
#
#
# Fastpath:
#
# Transport Throughput - PPS matrix (median of runs)
# scenario direct drainer
# ----------------------------------------------------------------------
# transit_single_135 407,561 411,426 440.17 Mbps / 444.34 Mbps
# transit_single_475 378,867 377,964 1.44 Gbps / 1.44 Gbps
# transit_single_1024 320,878 325,910 2.63 Gbps / 2.67 Gbps
# transit_single_16384 94,265 94,357 12.36 Gbps / 12.37 Gbps
# transit_single_final 395,245 399,247 426.86 Mbps / 431.19 Mbps
# transit_link_135 453,216 451,863 489.47 Mbps / 488.01 Mbps
# transit_link_475 417,013 417,294 1.58 Gbps / 1.59 Gbps
# transit_link_1024 347,548 353,783 2.85 Gbps / 2.90 Gbps
# transit_link_16384 96,682 96,871 12.67 Gbps / 12.70 Gbps
#
# terminus_single 29,451 25,862 31.81 Mbps / 27.93 Mbps
# announce_ingress 7,495 6,996 10.01 Mbps / 9.35 Mbps
# outbound_path 840,738 - 908.00 Mbps / -