mirror of
https://github.com/markqvist/Reticulum
synced 2026-11-23 07:20:32 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea98db4f53 | ||
|
|
ad3c06636b | ||
|
|
9ce4502961 | ||
|
|
a3cd84111f | ||
|
|
d5b2fc5609 | ||
|
|
83a30b187a | ||
|
|
943771a3f9 | ||
|
|
5b4117dadc | ||
|
|
6bc0481cdf | ||
|
|
4eebf0b685 | ||
|
|
149e415109 | ||
|
|
53ed9c1ed3 | ||
|
|
ccc5468bcc | ||
|
|
c1d7c12b52 | ||
|
|
9878b18377 | ||
|
|
6e8c976421 | ||
|
|
b28f5ebf7a | ||
|
|
77c8256a1a | ||
|
|
dc9cf0c2f4 | ||
|
|
fa07c8c87c | ||
|
|
b7fe01237d | ||
|
|
3543dc9802 | ||
|
|
5b04a88026 | ||
|
|
5fdd661081 | ||
|
|
ae0191578f | ||
|
|
e714c559cc | ||
|
|
75cbc73f64 | ||
|
|
d32ba8c1a1 | ||
|
|
ff3a72209e | ||
|
|
803b548951 | ||
|
|
67a45ac5e9 | ||
|
|
e71c01959f | ||
|
|
0a1b9453b2 | ||
|
|
79cad39e78 | ||
|
|
de0dac695b | ||
|
|
281c47f3e0 | ||
|
|
99c428a9f5 | ||
|
|
cb9071b478 | ||
|
|
10848b7cff | ||
|
|
89e73db94a | ||
|
|
0ec84c7491 | ||
|
|
ac9130f01f | ||
|
|
54a919f045 | ||
|
|
bafc09d3a6 | ||
|
|
419956bada | ||
|
|
1a16fdb727 | ||
|
|
3b7cfc0666 | ||
|
|
de76b8939f | ||
|
|
d80245b62c | ||
|
|
dcbc7638d0 | ||
|
|
0536b972d7 | ||
|
|
47add6381d | ||
|
|
be2ba7c2f3 | ||
|
|
dd204e11ce | ||
|
|
be4ee32908 | ||
|
|
9f66b5a6a3 | ||
|
|
d38a8de571 | ||
|
|
dea0124c57 | ||
|
|
aba8d606dd | ||
|
|
8221f82dc0 | ||
|
|
38e9d1cdd4 | ||
|
|
17e980ff79 | ||
|
|
f111709902 | ||
|
|
2d2167140d | ||
|
|
d044db2931 | ||
|
|
516cb106c1 | ||
|
|
7e197542e5 | ||
|
|
77f7632584 | ||
|
|
5e013464da | ||
|
|
b9278ce352 | ||
|
|
d81421dad3 | ||
|
|
629e4fde2d | ||
|
|
7311dc8544 | ||
|
|
0e070aacf6 | ||
|
|
39899651ee | ||
|
|
1034d78828 | ||
|
|
9c2f424aaa | ||
|
|
dca5b9639e | ||
|
|
40281f91da | ||
|
|
cf5d6a796e | ||
|
|
9302415f9e | ||
|
|
9da6664976 | ||
|
|
1694a17a75 | ||
|
|
3fdfe93ec7 | ||
|
|
a9538e9fd1 | ||
|
|
956d688e10 | ||
|
|
1c83e732ad | ||
|
|
5da0870e2a | ||
|
|
171868c6cb | ||
|
|
cfddb9abe6 | ||
|
|
929aba0282 | ||
|
|
7347034f9a | ||
|
|
aef9e5b416 | ||
|
|
e806ae5837 | ||
|
|
602085a1cd | ||
|
|
84597f3186 | ||
|
|
88c629e3ad | ||
|
|
2058596dd1 | ||
|
|
b123a756b0 | ||
|
|
bfab2964b6 | ||
|
|
1bad7f5807 | ||
|
|
26e3ca4f2b | ||
|
|
d25ea38c84 | ||
|
|
e32d4df754 | ||
|
|
561e2f23e1 | ||
|
|
b397870c97 | ||
|
|
6f6751d6b6 | ||
|
|
2aed542e61 | ||
|
|
091e021d0e | ||
|
|
fc69f323a8 | ||
|
|
6b2c5bcf0b | ||
|
|
3885d23293 | ||
|
|
b1aa527861 | ||
|
|
4c69b376b2 | ||
|
|
2b1b9589f1 | ||
|
|
378840a6bf | ||
|
|
7b8923b61f | ||
|
|
b3ef214e72 | ||
|
|
cab513fa31 | ||
|
|
60eb0509f2 | ||
|
|
42f6d64b9c | ||
|
|
6ba7cc8cb4 | ||
|
|
880db0a7b7 | ||
|
|
5f2f4438d0 | ||
|
|
7488336985 | ||
|
|
614e7bd834 | ||
|
|
386ef1f370 | ||
|
|
4ab0755d0a | ||
|
|
d478e380c9 | ||
|
|
05e6717d21 | ||
|
|
9ae3db169e | ||
|
|
68cda4a855 | ||
|
|
4b914fb9a4 | ||
|
|
bde5611a0d | ||
|
|
49073fcca5 | ||
|
|
6738db5437 | ||
|
|
49918c7e1d | ||
|
|
954567c581 | ||
|
|
77a1bb9b19 | ||
|
|
df80181006 | ||
|
|
0c0034f1ae | ||
|
|
2e9443ffe2 | ||
|
|
65222e0de8 | ||
|
|
db7daa4d94 | ||
|
|
c95bb551ab | ||
|
|
acecc1f490 | ||
|
|
39e3854dac | ||
|
|
6cd5be18ec | ||
|
|
0e2041c837 | ||
|
|
338173802d | ||
|
|
40a862acbd | ||
|
|
d825e39379 | ||
|
|
731a63b01b | ||
|
|
7c912d0936 | ||
|
|
503bd6c87b | ||
|
|
1a70bd3cd1 | ||
|
|
636012bbe5 | ||
|
|
e1b7bc316c | ||
|
|
1c488947bd | ||
|
|
1809461a07 | ||
|
|
01a78bee2a | ||
|
|
8c08b9ce09 | ||
|
|
efb8c8500d | ||
|
|
f366dd9cf2 | ||
|
|
0d15cfc134 | ||
|
|
e81532f541 | ||
|
|
d41afd2d81 | ||
|
|
7a1291d530 | ||
|
|
fc0f84f23e | ||
|
|
c2eac12ff5 | ||
|
|
e46496032c | ||
|
|
2d7f858a54 | ||
|
|
9ebcb55cb5 | ||
|
|
bbc1a0d06b | ||
|
|
31298e5eda | ||
|
|
e31c570d2b | ||
|
|
9b4947ef46 | ||
|
|
0d9bf5b862 | ||
|
|
c6f9ef1047 | ||
|
|
90ac62620d | ||
|
|
0c41027765 | ||
|
|
691211bf0d | ||
|
|
0ec51cce67 | ||
|
|
55755c6b3c | ||
|
|
72ba27d63c | ||
|
|
6c1182c2c2 | ||
|
|
ce81b339dc | ||
|
|
3db15dae44 | ||
|
|
38a73f9508 | ||
|
|
ebd9b862e9 | ||
|
|
4fc8e03d65 |
No files matched your search
+271
-5
@@ -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()
|
||||
+109
-4
@@ -1,10 +1,12 @@
|
||||
### 2026-07-26: RNS 1.4.2
|
||||
### 2026-08-28: RNS 1.5.2
|
||||
|
||||
This maintenance release fixes bugs in blackholed identity filtering and recursive path request handling for RNode interfaces.
|
||||
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**
|
||||
- Fixed a bug where recursive path requests would cause a division by zero error on uninitialized RNode interfaces.
|
||||
- Fixed slow blackholed filtering for discovered interfaces on Android in some cases.
|
||||
- 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:
|
||||
@@ -34,10 +36,112 @@ 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.
|
||||
|
||||
**Changes**
|
||||
- Added ability to include operator LXMF address in interface discovery information
|
||||
- Added prioritized inbound traffic processing to the transport core
|
||||
- Added configurable inbound queue lengths for data, announce, path request and ingress limited traffic
|
||||
- Added early filtering for inbound traffic and improved filtering performance
|
||||
- Added per-interface protocol violation tracking
|
||||
- Added in-flight path requests tracking
|
||||
- Added request and response batching for in-flight path requests
|
||||
- Added ability to signal blackholed status in announce validation return to the API
|
||||
- Added full link MDU utilization for `Channel` and `Buffer`
|
||||
- Added inbound queue pressure and queue drop statistics to `rnstatus`
|
||||
- Added detailed announce and path request traffic flow statistics per interface to `rnstatus`
|
||||
- Added total announce and PR count/frequency stats per interface to `rnstatus`
|
||||
- Added data flow speed and composition stats to `rnstatus`
|
||||
- Added protocol violation stats to `rnstatus`
|
||||
- Added active link statistics to `rnstatus`
|
||||
- Added blocked IP listings to `rnstatus`
|
||||
- Added medium bitrate based timeout calculation helpers and RPC functions, by **Zenith**
|
||||
- Added extra timeout for discovery path requests when slow interfaces are online, by **Zenith**
|
||||
- Added adaptive timeouts to `rncp`, `rnpath`, `rnprobe` and `rnx`, by **Zenith**
|
||||
- Added adaptive timeout calculation to `rngit`, by **Zenith**
|
||||
- Improved overall Transport inbound processing speed
|
||||
- Improved path request handling significantly
|
||||
- Improved path request ingress limiting and accounting
|
||||
- Improved egress limiting responsiveness under high incoming path request load
|
||||
- Improved transport background job processing
|
||||
- Improved early rejection of packets with excessive hop counts
|
||||
- Fixed `BackboneInterface` EPOLL receive starvation and ingress control timestamp handling, by **JRG**
|
||||
- Fixed potential transport deadlock on receipts lock when callbacks sends packets, by **JRG**
|
||||
- Fixed transport state handling edge cases in path request, announce queue and pending link processing, by **JRG**
|
||||
- Fixed link watchdog not resetting on receive exceptions, by **JRG**
|
||||
- Fixed `Resource` cancellation on multi-segment resources, by **JRG**
|
||||
- Fixed `Resource` transfer part index alignment and rebinding, by **JRG**
|
||||
- Fixed stale BLE device reference in `RNodeInterface`, by **JRG**
|
||||
- Fixed ratchet cleaning retained preservation, by **JRG**
|
||||
- Fixed invalid `rnstatus` statistics handling, by **JRG**
|
||||
- Fixed various bugs in packet, link and interface handling, by **JRG**
|
||||
- Fixed per-interface burst count inconsistencies in `rnstatus` output
|
||||
- Fixed `rngit` file resource operations failing on Windows
|
||||
- Fixed `rnodeconf` config summary incorrectly displaying WiFi mode
|
||||
- Fixed speedtest example aborting transfers on stale link status
|
||||
- Updated documentation, including manual sections on queue tuning and interface discovery options
|
||||
|
||||
### 2026-07-26: RNS 1.4.2
|
||||
|
||||
This maintenance release fixes bugs in blackholed identity filtering and recursive path request handling for RNode interfaces.
|
||||
|
||||
**Changes**
|
||||
- Fixed a bug where recursive path requests would cause a division by zero error on uninitialized RNode interfaces.
|
||||
- Fixed slow blackholed filtering for discovered interfaces on Android in some cases.
|
||||
|
||||
### 2026-07-24: RNS 1.4.1
|
||||
|
||||
This release significantly improves path convergence and stability with the new path re-balancing functionality. It also introduces interface gravity configuration, new API functionality and fixes a range of bugs and inefficiencies.
|
||||
|
||||
**Changes**
|
||||
- Added dynamic path re-balancing
|
||||
- Added `set_max_request_size` to `Destination` API
|
||||
- Added `max_response_size` to request API
|
||||
@@ -56,6 +160,7 @@ This release significantly improves path convergence and stability with the new
|
||||
- Fixed various memory inefficiencies
|
||||
- Fixed loglevel `LOG_EXTREME` not being usable in some cases
|
||||
- Fixed historical interface discoveries not being cleaned according to blackholed identities
|
||||
|
||||
### 2026-07-20: RNS 1.4.0
|
||||
|
||||
This release focuses on performance, stability and reliability improvements, particularly with resource-constrained systems in mind. It also fixes several bugs, reduces logging noise, and makes information about blocked `BackboneInterface` clients available in `ifstats`.
|
||||
|
||||
@@ -239,7 +239,7 @@ def link_established(link):
|
||||
RNS.log("Link established with server, sending...")
|
||||
rd = os.urandom(link.mdu)
|
||||
started = time.time()
|
||||
while link.status == RNS.Link.ACTIVE and data_sent < data_cap*1.25:
|
||||
while link.status != RNS.Link.CLOSED and data_sent < data_cap*1.25:
|
||||
RNS.Packet(server_link, rd, create_receipt=False).send()
|
||||
data_sent += len(rd)
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
+5
-4
@@ -53,7 +53,8 @@ class StreamDataMessage(MessageBase):
|
||||
The stream id is limited to 2 bytes - 2 bit
|
||||
"""
|
||||
|
||||
OVERHEAD = 2 + 6 # 2 for stream data message header, 6 for channel envelope
|
||||
HEADER_LEN = 2 # 2 for stream data message header
|
||||
OVERHEAD = HEADER_LEN + 6 # 6 for channel envelope
|
||||
MAX_DATA_LEN = RNS.Link.MDU - OVERHEAD
|
||||
"""
|
||||
When the Buffer package is imported, this value is
|
||||
@@ -226,7 +227,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
|
||||
self._stream_id = stream_id
|
||||
self._channel = channel
|
||||
self._eof = False
|
||||
self._mdu = channel.mdu - StreamDataMessage.OVERHEAD
|
||||
self._mdu = channel.mdu - StreamDataMessage.HEADER_LEN
|
||||
|
||||
def write(self, __b: bytes) -> int | None:
|
||||
try:
|
||||
@@ -242,7 +243,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
|
||||
chunk_segment_length = int(chunk_len/comp_try)
|
||||
compressed_chunk = bz2.compress(__b[:chunk_segment_length])
|
||||
compressed_length = len(compressed_chunk)
|
||||
if compressed_length < StreamDataMessage.MAX_DATA_LEN and compressed_length < chunk_segment_length:
|
||||
if compressed_length < self._mdu and compressed_length < chunk_segment_length:
|
||||
comp_success = True
|
||||
break
|
||||
else:
|
||||
@@ -252,7 +253,7 @@ class RawChannelWriter(RawIOBase, AbstractContextManager):
|
||||
chunk = compressed_chunk
|
||||
processed_length = chunk_segment_length
|
||||
else:
|
||||
chunk = bytes(__b[:StreamDataMessage.MAX_DATA_LEN])
|
||||
chunk = bytes(__b[:self._mdu])
|
||||
processed_length = len(chunk)
|
||||
|
||||
message = StreamDataMessage(self._stream_id, chunk, self._eof, comp_success)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -180,4 +180,9 @@ def digest(key, msg, digest):
|
||||
outer.update(key.translate(trans_5C))
|
||||
inner.update(msg)
|
||||
outer.update(inner.digest())
|
||||
return outer.digest()
|
||||
return outer.digest()
|
||||
|
||||
def _cd_internal(a, b): return a == b
|
||||
try: from hmac import compare_digest as _cd
|
||||
except ImportError: _cd = _cd_internal
|
||||
compare_digest = _cd
|
||||
@@ -80,7 +80,7 @@ class Token():
|
||||
received_hmac = token[-32:]
|
||||
expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest()
|
||||
|
||||
if received_hmac == expected_hmac: return True
|
||||
if HMAC.compare_digest(received_hmac, expected_hmac): return True
|
||||
else: return False
|
||||
|
||||
|
||||
|
||||
@@ -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__"]))
|
||||
+1
-1
@@ -206,7 +206,7 @@ class Destination:
|
||||
def _clean_ratchets(self):
|
||||
if self.ratchets != None:
|
||||
if len (self.ratchets) > self.retained_ratchets:
|
||||
self.ratchets = self.ratchets[:Destination.RATCHET_COUNT]
|
||||
self.ratchets = self.ratchets[:self.retained_ratchets]
|
||||
|
||||
def _persist_ratchets(self):
|
||||
try:
|
||||
|
||||
+39
-3
@@ -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
|
||||
@@ -27,6 +35,7 @@ SPREADINGFACTOR = 0x0B
|
||||
CODINGRATE = 0x0C
|
||||
MODULATION = 0x0D
|
||||
CHANNEL = 0x0E
|
||||
OP_ADDR = 0xF0
|
||||
|
||||
APP_NAME = "rnstransport"
|
||||
|
||||
@@ -123,7 +132,7 @@ class InterfaceAnnouncer():
|
||||
interface.discovery_height = dhgt
|
||||
|
||||
except Exception as e:
|
||||
RNS.log(f"Error while getting reachable_on from executable at {interface.reachable_on}: {e}", RNS.LOG_ERROR)
|
||||
RNS.log(f"Error while getting discovery location from executable at {interface.reachable_on}: {e}", RNS.LOG_ERROR)
|
||||
RNS.log(f"Aborting discovery announce", RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
@@ -131,16 +140,21 @@ 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,
|
||||
HEIGHT: interface.discovery_height}
|
||||
|
||||
if interface.discovery_lxmf_address: info[OP_ADDR] = interface.discovery_lxmf_address
|
||||
|
||||
if interface_type == "TCPClientInterface" and not interface.kiss_framing:
|
||||
RNS.log(f"Invalid interface discovery configuration for {interface}, aborting discovery announce", RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
if interface_type in ["BackboneInterface", "TCPServerInterface"]:
|
||||
if not interface.reachable_on: return None
|
||||
reachable_on = self.sanitize(interface.reachable_on)
|
||||
|
||||
if not RNS.vendor.platformutils.is_windows():
|
||||
@@ -410,6 +424,11 @@ class InterfaceAnnounceHandler:
|
||||
discovery_hash_material = info["transport_id"]+info["name"]
|
||||
info["discovery_hash"] = RNS.Identity.full_hash(discovery_hash_material.encode("utf-8"))
|
||||
|
||||
if info and OP_ADDR in unpacked:
|
||||
if type(unpacked[OP_ADDR]) not in [type(None), bytes]: raise ValueError("Invalid data in operator LXMF address field of announce")
|
||||
if unpacked[OP_ADDR] and len(unpacked[OP_ADDR]) == RNS.Identity.TRUNCATED_HASHLENGTH//8:
|
||||
info["operator_lxmf_address"] = RNS.hexrep(unpacked[OP_ADDR], delimit=False)
|
||||
|
||||
if self.callback and callable(self.callback): self.callback(info)
|
||||
|
||||
except Exception as e:
|
||||
@@ -713,14 +732,22 @@ class InterfaceDiscovery():
|
||||
return
|
||||
|
||||
if interface_type == "I2PInterface":
|
||||
RNS.log(f"Auto-connecting discovered I2P interfaces is not yet implemented, aborting auto-connect", RNS.LOG_WARNING)
|
||||
RNS.log(f"You can obtain the configuration entry and add this interface manually instead using rnstatus -D", RNS.LOG_WARNING)
|
||||
RNS.log(f"Auto-connecting discovered I2P interfaces is not yet implemented, aborting auto-connect", RNS.LOG_DEBUG)
|
||||
RNS.log(f"You can obtain the configuration entry and add this interface manually instead using rnstatus -D", RNS.LOG_DEBUG)
|
||||
return
|
||||
|
||||
if is_ygg_ipv6(info["reachable_on"]):
|
||||
# TODO: Somehow detect if yggdrasil is enabled on the system
|
||||
return
|
||||
|
||||
if is_onion_address(info["reachable_on"]):
|
||||
# TODO: Somehow detect if TOR is enabled on the system
|
||||
return
|
||||
|
||||
if is_ip_address(info["reachable_on"]) and is_invalid_ip_address(info["reachable_on"]):
|
||||
RNS.log(f"Not auto-connecting discovered interface with invalid IP address: {info['reachable_on']}", RNS.LOG_DEBUG)
|
||||
return
|
||||
|
||||
interface_name = info["name"]
|
||||
config_entry = info["config_entry"]
|
||||
interface_config = {}
|
||||
@@ -851,6 +878,15 @@ def is_ygg_ipv6(address_string):
|
||||
try: return ipaddress.ip_address(address_string) in ipaddress.IPv6Network("200::/7")
|
||||
except: return False
|
||||
|
||||
def is_onion_address(address_string):
|
||||
try: return address_string.lower().endswith(".onion")
|
||||
except: return False
|
||||
|
||||
INVALID_IP_ADDRESSES = ["127.0.0.1", "0.0.0.0"]
|
||||
def is_invalid_ip_address(address_string):
|
||||
if not address_string in INVALID_IP_ADDRESSES: return False
|
||||
else: return True
|
||||
|
||||
def is_hostname(hostname):
|
||||
if hostname[-1] == ".": hostname = hostname[:-1]
|
||||
if len(hostname) > 253: return False
|
||||
|
||||
+12
-8
@@ -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
|
||||
@@ -508,7 +508,7 @@ class Identity:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def validate_announce(packet, only_validate_signature=False):
|
||||
def validate_announce(packet, only_validate_signature=False, signal_blackholed=False):
|
||||
try:
|
||||
if packet.packet_type == RNS.Packet.ANNOUNCE:
|
||||
keysize = Identity.KEYSIZE//8
|
||||
@@ -553,9 +553,11 @@ class Identity:
|
||||
if len(RNS.Transport.blackholed_identities) > 0:
|
||||
if announced_identity.hash in RNS.Transport.blackholed_identities:
|
||||
RNS.log(f"Invalidated and dropped announce from blackholed identity {RNS.prettyhexrep(announced_identity.hash)}", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||
return False
|
||||
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
|
||||
@@ -757,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):
|
||||
@@ -777,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())
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
@@ -1742,7 +1740,7 @@ class BLEConnection(BluetoothDispatcher):
|
||||
ble_devices = self.find_target_devices()
|
||||
|
||||
if len(ble_devices) > 0: self.ble_device = ble_devices.pop()
|
||||
else: self.ble_device == None
|
||||
else: self.ble_device = None
|
||||
|
||||
if self.ble_device != None:
|
||||
if self.was_connected:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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__"]))
|
||||
@@ -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):
|
||||
@@ -169,13 +182,34 @@ class BackboneInterface(Interface):
|
||||
else:
|
||||
raise SystemError("Insufficient parameters to create listener")
|
||||
|
||||
__ic_burst_stats_throttle = 0.95
|
||||
__last_ic_burst_count_check = 0
|
||||
__last_ic_burst_count_state = 0
|
||||
@property
|
||||
def ic_burst_count(self):
|
||||
if time.time() > self.__last_ic_burst_count_check + self.__ic_burst_stats_throttle:
|
||||
self.__last_ic_burst_count_state = len([i.ic_burst_active for i in self.spawned_interfaces if i.ic_burst_active])
|
||||
self.__last_ic_burst_count_check = time.time()
|
||||
|
||||
return self.__last_ic_burst_count_state
|
||||
|
||||
__last_ic_pr_burst_count_check = 0
|
||||
__last_ic_pr_burst_count_state = 0
|
||||
@property
|
||||
def ic_pr_burst_count(self):
|
||||
if time.time() > self.__last_ic_pr_burst_count_check + self.__ic_burst_stats_throttle:
|
||||
self.__last_ic_pr_burst_count_state = len([i.ic_pr_burst_active for i in self.spawned_interfaces if i.ic_pr_burst_active])
|
||||
self.__last_ic_pr_burst_count_check = time.time()
|
||||
|
||||
return self.__last_ic_pr_burst_count_state
|
||||
|
||||
__last_ic_burst_check = 0
|
||||
__last_ic_burst_state = False
|
||||
@property
|
||||
def ic_burst_active(self):
|
||||
if time.time() > self.__last_ic_burst_check + 2:
|
||||
if time.time() > self.__last_ic_burst_check + self.__ic_burst_stats_throttle:
|
||||
self.__last_ic_burst_state = any(i.ic_burst_active for i in self.spawned_interfaces)
|
||||
self.__last_ic_burst_check = time.time()
|
||||
|
||||
return self.__last_ic_burst_state
|
||||
|
||||
@@ -186,9 +220,10 @@ class BackboneInterface(Interface):
|
||||
__ic_burst_activated = 0
|
||||
@property
|
||||
def ic_burst_activated(self):
|
||||
if time.time() > self.__ic_burst_activated_check + 2:
|
||||
if time.time() > self.__ic_burst_activated_check + self.__ic_burst_stats_throttle:
|
||||
activated = [i.ic_burst_activated for i in self.spawned_interfaces if i.ic_burst_active]
|
||||
if activated: self.__ic_burst_activated = min(activated)
|
||||
self.__ic_burst_activated_check = time.time()
|
||||
|
||||
return self.__ic_burst_activated
|
||||
|
||||
@@ -200,8 +235,9 @@ class BackboneInterface(Interface):
|
||||
__last_ic_pr_burst_state = False
|
||||
@property
|
||||
def ic_pr_burst_active(self):
|
||||
if time.time() > self.__last_ic_pr_burst_check + 2:
|
||||
if time.time() > self.__last_ic_pr_burst_check + self.__ic_burst_stats_throttle:
|
||||
self.__last_ic_pr_burst_state = any(i.ic_pr_burst_active for i in self.spawned_interfaces)
|
||||
self.__last_ic_pr_burst_check = time.time()
|
||||
|
||||
return self.__last_ic_pr_burst_state
|
||||
|
||||
@@ -212,9 +248,10 @@ class BackboneInterface(Interface):
|
||||
__ic_pr_burst_activated = 0
|
||||
@property
|
||||
def ic_pr_burst_activated(self):
|
||||
if time.time() > self.__ic_pr_burst_activated_check + 2:
|
||||
if time.time() > self.__ic_pr_burst_activated_check + self.__ic_burst_stats_throttle:
|
||||
activated = [i.ic_pr_burst_activated for i in self.spawned_interfaces if i.ic_pr_burst_active]
|
||||
if activated: self.__ic_pr_burst_activated = min(activated)
|
||||
self.__ic_pr_burst_activated_check = time.time()
|
||||
|
||||
return self.__ic_pr_burst_activated
|
||||
|
||||
@@ -223,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():
|
||||
@@ -264,9 +303,9 @@ 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 EPOLL_IN for file descriptor {fileno}: {e}", RNS.LOG_WARNING)
|
||||
RNS.log(f"An error occurred while registering EPOLLIN for file descriptor {fileno}: {e}", RNS.LOG_WARNING)
|
||||
|
||||
@staticmethod
|
||||
def deregister_fileno(fileno):
|
||||
@@ -295,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.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:
|
||||
@@ -311,18 +560,21 @@ class BackboneInterface(Interface):
|
||||
BackboneInterface.ensure_epoll()
|
||||
try:
|
||||
while True:
|
||||
events = BackboneInterface.epoll.poll(1)
|
||||
for fileno, event in BackboneInterface.epoll.poll(1):
|
||||
if fileno in BackboneInterface.spawned_interface_filenos:
|
||||
spawned_interface = BackboneInterface.spawned_interface_filenos[fileno]
|
||||
client_socket = spawned_interface.socket
|
||||
if client_socket and fileno == client_socket.fileno() and (event & select.EPOLLIN):
|
||||
socket_valid = client_socket and fileno == client_socket.fileno()
|
||||
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:
|
||||
@@ -337,9 +589,10 @@ class BackboneInterface(Interface):
|
||||
except Exception as e: RNS.log(f"Error while removing spawned interface from {pif}: {e}", RNS.LOG_ERROR)
|
||||
|
||||
spawned_interface.receive(received_bytes)
|
||||
|
||||
elif client_socket and fileno == client_socket.fileno() and (event & select.EPOLLOUT):
|
||||
try: written = client_socket.send(spawned_interface.transmit_buffer)
|
||||
|
||||
socket_valid_after_read = socket_valid and fileno in BackboneInterface.spawned_interface_filenos
|
||||
if socket_valid_after_read and (event & select.EPOLLOUT):
|
||||
try: written = spawned_interface.transmit_buffer.drain_to(client_socket)
|
||||
except Exception as e:
|
||||
written = 0
|
||||
if not spawned_interface.detached:
|
||||
@@ -366,16 +619,17 @@ 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
|
||||
|
||||
elif client_socket and fileno == client_socket.fileno() and event & (select.EPOLLHUP):
|
||||
elif socket_valid_after_read and (event & select.EPOLLHUP):
|
||||
BackboneInterface.deregister_fileno(fileno)
|
||||
try:
|
||||
if fileno in BackboneInterface.spawned_interface_filenos: BackboneInterface.spawned_interface_filenos.pop(fileno)
|
||||
@@ -398,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)
|
||||
@@ -498,17 +753,25 @@ class BackboneInterface(Interface):
|
||||
|
||||
return True
|
||||
|
||||
def received_announce(self, from_spawned=False):
|
||||
if from_spawned: self.ia_freq_deque.append(time.time())
|
||||
def received_announce(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.ia_freq_deque.append(time.time())
|
||||
self.arxb += size
|
||||
|
||||
def sent_announce(self, from_spawned=False):
|
||||
if from_spawned: self.oa_freq_deque.append(time.time())
|
||||
def sent_announce(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.oa_freq_deque.append(time.time())
|
||||
self.atxb += size
|
||||
|
||||
def received_path_request(self, from_spawned=False):
|
||||
if from_spawned: self.ip_freq_deque.append(time.time())
|
||||
def received_path_request(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.ip_freq_deque.append(time.time())
|
||||
self.prxb += size
|
||||
|
||||
def sent_path_request(self, from_spawned=False):
|
||||
if from_spawned: self.op_freq_deque.append(time.time())
|
||||
def sent_path_request(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.op_freq_deque.append(time.time())
|
||||
self.ptxb += size
|
||||
|
||||
def process_outgoing(self, data):
|
||||
pass
|
||||
@@ -531,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):
|
||||
@@ -609,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
|
||||
@@ -699,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)
|
||||
@@ -758,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:
|
||||
@@ -825,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:
|
||||
|
||||
@@ -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)
|
||||
@@ -871,17 +872,25 @@ class I2PInterface(Interface):
|
||||
def process_outgoing(self, data):
|
||||
pass
|
||||
|
||||
def received_announce(self, from_spawned=False):
|
||||
if from_spawned: self.ia_freq_deque.append(time.time())
|
||||
def received_announce(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.ia_freq_deque.append(time.time())
|
||||
self.arxb += size
|
||||
|
||||
def sent_announce(self, from_spawned=False):
|
||||
if from_spawned: self.oa_freq_deque.append(time.time())
|
||||
def sent_announce(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.oa_freq_deque.append(time.time())
|
||||
self.atxb += size
|
||||
|
||||
def received_path_request(self, from_spawned=False):
|
||||
if from_spawned: self.ip_freq_deque.append(time.time())
|
||||
def received_path_request(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.ip_freq_deque.append(time.time())
|
||||
self.prxb += size
|
||||
|
||||
def sent_path_request(self, from_spawned=False):
|
||||
if from_spawned: self.op_freq_deque.append(time.time())
|
||||
def sent_path_request(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.op_freq_deque.append(time.time())
|
||||
self.ptxb += size
|
||||
|
||||
def detach(self):
|
||||
RNS.log("Detaching "+str(self), RNS.LOG_DEBUG)
|
||||
|
||||
+100
-30
@@ -82,7 +82,7 @@ class Interface:
|
||||
IC_BURST_PENALTY = 15
|
||||
IC_HELD_RELEASE_INTERVAL = 5
|
||||
IC_DEQUE_MIN_SAMPLE = 2
|
||||
IC_BURST_MIN_SAMPLES = 6
|
||||
EC_BURST_MIN_SAMPLES = 2
|
||||
EC_PR_FREQ = 5
|
||||
EGRESS_CONTROL = False
|
||||
|
||||
@@ -93,10 +93,19 @@ class Interface:
|
||||
|
||||
AUTOCONFIGURE_MTU = False
|
||||
FIXED_MTU = False
|
||||
DEFAULT_IFAC_SIZE = 16
|
||||
|
||||
def __init__(self):
|
||||
self.rxb = 0
|
||||
self.txb = 0
|
||||
self.arxb = 0
|
||||
self.atxb = 0
|
||||
self.arxc = 0
|
||||
self.atxc = 0
|
||||
self.prxb = 0
|
||||
self.ptxb = 0
|
||||
self.prxc = 0
|
||||
self.ptxc = 0
|
||||
self.gravity = 0
|
||||
self.created = time.time()
|
||||
self.detached = False
|
||||
@@ -117,11 +126,15 @@ 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
|
||||
self.ic_burst_sustained = 0
|
||||
self.ic_pr_burst_active = False
|
||||
self.ic_pr_burst_activated = 0
|
||||
self.ic_pr_burst_sustained = 0
|
||||
self.ic_pr_burst_cooldown = 0
|
||||
self.ic_held_release = 0
|
||||
self.ic_max_held_announces = RNS.Reticulum.get_instance()._default_ic_max_held_announces()
|
||||
self.ic_burst_hold = RNS.Reticulum.get_instance()._default_ic_burst_hold()
|
||||
@@ -135,12 +148,35 @@ 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)
|
||||
self.ip_freq_deque = deque(maxlen=Interface.IA_FREQ_SAMPLES)
|
||||
self.op_freq_deque = deque(maxlen=Interface.OA_FREQ_SAMPLES)
|
||||
|
||||
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"))
|
||||
return self.__hash
|
||||
@@ -155,8 +191,10 @@ class Interface:
|
||||
ia_freq = self.incoming_announce_frequency()
|
||||
|
||||
if self.ic_burst_active:
|
||||
if ia_freq < freq_threshold and time.time() > self.ic_burst_activated+self.ic_burst_hold:
|
||||
if ia_freq < freq_threshold and time.time() > self.ic_burst_activated+self.ic_burst_hold and time.time() > self.ic_burst_sustained+self.ic_burst_hold:
|
||||
if len(self.ia_freq_deque) >= self.IC_DEQUE_MIN_SAMPLE: self.ic_burst_active = False
|
||||
else:
|
||||
if ia_freq >= freq_threshold: self.ic_burst_sustained = time.time()
|
||||
|
||||
return True
|
||||
|
||||
@@ -164,6 +202,7 @@ class Interface:
|
||||
if ia_freq > freq_threshold:
|
||||
self.ic_burst_active = True
|
||||
self.ic_burst_activated = time.time()
|
||||
self.ic_burst_sustained = time.time()
|
||||
self.ic_held_release = time.time() + self.ic_burst_penalty
|
||||
return True
|
||||
|
||||
@@ -177,8 +216,12 @@ class Interface:
|
||||
ip_freq = self.incoming_pr_frequency()
|
||||
|
||||
if self.ic_pr_burst_active:
|
||||
if ip_freq < freq_threshold and time.time() > self.ic_pr_burst_activated+self.ic_burst_hold:
|
||||
self.ic_pr_burst_active = False
|
||||
if ip_freq < freq_threshold and time.time() > self.ic_pr_burst_activated+self.ic_burst_hold and time.time() > self.ic_pr_burst_sustained+self.ic_burst_hold:
|
||||
if self.ic_pr_burst_cooldown <= 0: self.ic_pr_burst_active = False
|
||||
else: self.ic_pr_burst_cooldown -= 1
|
||||
else:
|
||||
self.ic_pr_burst_cooldown = 3
|
||||
if ip_freq >= freq_threshold: self.ic_pr_burst_sustained = time.time()
|
||||
|
||||
return True
|
||||
|
||||
@@ -186,6 +229,8 @@ class Interface:
|
||||
if ip_freq > freq_threshold:
|
||||
self.ic_pr_burst_active = True
|
||||
self.ic_pr_burst_activated = time.time()
|
||||
self.ic_pr_burst_sustained = time.time()
|
||||
self.ic_pr_burst_cooldown = 3
|
||||
return True
|
||||
|
||||
else: return False
|
||||
@@ -195,28 +240,28 @@ class Interface:
|
||||
def should_egress_limit_pr(self):
|
||||
if self.egress_control:
|
||||
freq_threshold = self.ec_pr_freq
|
||||
op_freq = self.outgoing_pr_frequency()
|
||||
op_freq = self.outgoing_pr_frequency(preemptive=True)
|
||||
|
||||
if op_freq > freq_threshold:
|
||||
if len(self.op_freq_deque) >= self.IC_BURST_MIN_SAMPLES: return True
|
||||
if len(self.op_freq_deque) >= self.EC_BURST_MIN_SAMPLES: return True
|
||||
|
||||
return False
|
||||
|
||||
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
|
||||
@@ -247,32 +292,56 @@ class Interface:
|
||||
RNS.log("Releasing held announce packet "+str(selected_announce_packet)+" from "+str(self), RNS.LOG_EXTREME)
|
||||
self.ic_held_release = time.time() + self.ic_held_release_interval
|
||||
self.held_announces.pop(selected_announce_packet.destination_hash)
|
||||
def release(): RNS.Transport.inbound(selected_announce_packet.raw, selected_announce_packet.receiving_interface)
|
||||
def release(): RNS.Transport.inbound(selected_announce_packet.raw, selected_announce_packet.receiving_interface, tc=RNS.Transport.TC_INGRESS_LIMITED, ifac_handled=True)
|
||||
threading.Thread(target=release, daemon=True).start()
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("An error occurred while processing held announces for "+str(self), RNS.LOG_ERROR)
|
||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
def received_announce(self, from_spawned=False):
|
||||
def received_announce(self, size=0, from_spawned=False):
|
||||
self.arxc += 1; self.arxb += size
|
||||
self.ia_freq_deque.append(time.time())
|
||||
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
||||
self.parent_interface.received_announce(from_spawned=True)
|
||||
self.parent_interface.received_announce(size=size, from_spawned=True)
|
||||
|
||||
def sent_announce(self, from_spawned=False):
|
||||
def sent_announce(self, size=0, from_spawned=False):
|
||||
self.atxc += 1; self.atxb += size
|
||||
self.oa_freq_deque.append(time.time())
|
||||
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
||||
self.parent_interface.sent_announce(from_spawned=True)
|
||||
self.parent_interface.sent_announce(size=size, from_spawned=True)
|
||||
|
||||
def received_path_request(self, from_spawned=False):
|
||||
def received_path_request(self, size=0, from_spawned=False):
|
||||
self.prxc += 1; self.prxb += size
|
||||
self.ip_freq_deque.append(time.time())
|
||||
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
||||
self.parent_interface.received_path_request(from_spawned=True)
|
||||
self.parent_interface.received_path_request(size=size, from_spawned=True)
|
||||
|
||||
def sent_path_request(self, from_spawned=False):
|
||||
def sent_path_request(self, size=0, from_spawned=False):
|
||||
self.ptxc += 1; self.ptxb += size
|
||||
self.op_freq_deque.append(time.time())
|
||||
if hasattr(self, "parent_interface") and self.parent_interface != None:
|
||||
self.parent_interface.sent_path_request(from_spawned=True)
|
||||
self.parent_interface.sent_path_request(size=size, from_spawned=True)
|
||||
|
||||
def protocol_violation(self, description=None):
|
||||
self.protocol_violations += 1
|
||||
RNS.log(f"Protocol violation on {self}: {description}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||
return None
|
||||
|
||||
def ifac_violation(self, description=None):
|
||||
self.ifac_violations += 1
|
||||
RNS.log(f"IFAC violation on {self}: {description}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||
return None
|
||||
|
||||
def packet_filter_hit(self):
|
||||
self.packet_filter_hits += 1
|
||||
return None
|
||||
|
||||
@property
|
||||
def ic_burst_count(self): return None
|
||||
|
||||
@property
|
||||
def ic_pr_burst_count(self): return None
|
||||
|
||||
def incoming_announce_frequency(self):
|
||||
n = len(self.ia_freq_deque)
|
||||
@@ -307,8 +376,8 @@ class Interface:
|
||||
hz = n / span
|
||||
return hz
|
||||
|
||||
def outgoing_pr_frequency(self):
|
||||
n = len(self.op_freq_deque)
|
||||
def outgoing_pr_frequency(self, preemptive=False):
|
||||
n = len(self.op_freq_deque)+(1 if preemptive else 0)
|
||||
if not len(self.op_freq_deque) > 1: return 0
|
||||
else:
|
||||
oldest = self.op_freq_deque[0]
|
||||
@@ -341,12 +410,13 @@ class Interface:
|
||||
selected = entries[0]
|
||||
|
||||
now = time.time()
|
||||
tx_time = (len(selected["raw"])*8) / self.bitrate
|
||||
tx_size = len(selected["raw"])
|
||||
tx_time = (tx_size*8) / self.bitrate
|
||||
wait_time = (tx_time / self.announce_cap)
|
||||
self.announce_allowed_at = now + wait_time
|
||||
|
||||
self.process_outgoing(selected["raw"])
|
||||
self.sent_announce()
|
||||
RNS.Transport.transmit(self, selected["raw"])
|
||||
self.sent_announce(tx_size)
|
||||
|
||||
if selected in self.announce_queue:
|
||||
self.announce_queue.remove(selected)
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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():
|
||||
@@ -70,6 +61,7 @@ class LocalClientInterface(Interface):
|
||||
self.epoll_backend = False
|
||||
self.HW_MTU = 262144
|
||||
self.online = False
|
||||
self.ifac_size = self.DEFAULT_IFAC_SIZE
|
||||
|
||||
if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}"
|
||||
else: self.socket_path = None
|
||||
@@ -83,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
|
||||
|
||||
@@ -194,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
|
||||
|
||||
@@ -219,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
|
||||
@@ -254,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:
|
||||
@@ -283,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
|
||||
@@ -296,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)
|
||||
@@ -382,6 +361,7 @@ class LocalServerInterface(Interface):
|
||||
self.epoll_backend = False
|
||||
self.online = False
|
||||
self.clients = 0
|
||||
self.ifac_size = self.DEFAULT_IFAC_SIZE
|
||||
|
||||
if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}"
|
||||
else: self.socket_path = None
|
||||
@@ -429,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
|
||||
|
||||
@@ -481,17 +462,25 @@ class LocalServerInterface(Interface):
|
||||
def process_outgoing(self, data):
|
||||
pass
|
||||
|
||||
def received_announce(self, from_spawned=False):
|
||||
if from_spawned: self.ia_freq_deque.append(time.time())
|
||||
def received_announce(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.ia_freq_deque.append(time.time())
|
||||
self.arxb += size
|
||||
|
||||
def sent_announce(self, from_spawned=False):
|
||||
if from_spawned: self.oa_freq_deque.append(time.time())
|
||||
def sent_announce(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.oa_freq_deque.append(time.time())
|
||||
self.atxb += size
|
||||
|
||||
def received_path_request(self, from_spawned=False):
|
||||
if from_spawned: self.ip_freq_deque.append(time.time())
|
||||
def received_path_request(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.ip_freq_deque.append(time.time())
|
||||
self.prxb += size
|
||||
|
||||
def sent_path_request(self, from_spawned=False):
|
||||
if from_spawned: self.op_freq_deque.append(time.time())
|
||||
def sent_path_request(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.op_freq_deque.append(time.time())
|
||||
self.ptxb += size
|
||||
|
||||
def __str__(self):
|
||||
if self.socket_path: return "Shared Instance["+str(self.socket_path.replace("\0", ""))+"]"
|
||||
@@ -502,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)
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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:
|
||||
@@ -543,17 +546,25 @@ class RNodeMultiInterface(Interface):
|
||||
if written != len(frame):
|
||||
raise IOError("Serial interface only wrote "+str(written)+" bytes of "+str(len(data)))
|
||||
|
||||
def received_announce(self, from_spawned=False):
|
||||
if from_spawned: self.ia_freq_deque.append(time.time())
|
||||
def received_announce(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.ia_freq_deque.append(time.time())
|
||||
self.arxb += size
|
||||
|
||||
def sent_announce(self, from_spawned=False):
|
||||
if from_spawned: self.oa_freq_deque.append(time.time())
|
||||
def sent_announce(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.oa_freq_deque.append(time.time())
|
||||
self.atxb += size
|
||||
|
||||
def received_path_request(self, from_spawned=False):
|
||||
if from_spawned: self.ip_freq_deque.append(time.time())
|
||||
def received_path_request(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.ip_freq_deque.append(time.time())
|
||||
self.prxb += size
|
||||
|
||||
def sent_path_request(self, from_spawned=False):
|
||||
if from_spawned: self.op_freq_deque.append(time.time())
|
||||
def sent_path_request(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.op_freq_deque.append(time.time())
|
||||
self.ptxb += size
|
||||
|
||||
def readLoop(self):
|
||||
try:
|
||||
@@ -993,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
|
||||
@@ -1116,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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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:
|
||||
@@ -646,17 +647,25 @@ class TCPServerInterface(Interface):
|
||||
self.spawned_interfaces.append(spawned_interface)
|
||||
spawned_interface.read_loop()
|
||||
|
||||
def received_announce(self, from_spawned=False):
|
||||
if from_spawned: self.ia_freq_deque.append(time.time())
|
||||
def received_announce(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.ia_freq_deque.append(time.time())
|
||||
self.arxb += size
|
||||
|
||||
def sent_announce(self, from_spawned=False):
|
||||
if from_spawned: self.oa_freq_deque.append(time.time())
|
||||
def sent_announce(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.oa_freq_deque.append(time.time())
|
||||
self.atxb += size
|
||||
|
||||
def received_path_request(self, from_spawned=False):
|
||||
if from_spawned: self.ip_freq_deque.append(time.time())
|
||||
def received_path_request(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.ip_freq_deque.append(time.time())
|
||||
self.prxb += size
|
||||
|
||||
def sent_path_request(self, from_spawned=False):
|
||||
if from_spawned: self.op_freq_deque.append(time.time())
|
||||
def sent_path_request(self, size=0, from_spawned=False):
|
||||
if from_spawned:
|
||||
self.op_freq_deque.append(time.time())
|
||||
self.ptxb += size
|
||||
|
||||
def process_outgoing(self, data):
|
||||
pass
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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__"]))
|
||||
@@ -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
|
||||
@@ -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}>"
|
||||
@@ -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__"]))
|
||||
+10
-5
@@ -191,7 +191,7 @@ class Link:
|
||||
|
||||
if len(data) == Link.ECPUBSIZE+Link.LINK_MTU_SIZE:
|
||||
RNS.log("Link request includes MTU signalling", RNS.LOG_EXTREME) if RNS.sl(RNS.LOG_EXTREME) else None
|
||||
try: link.mtu = Link.mtu_from_lr_packet(packet) or Reticulum.MTU
|
||||
try: link.mtu = Link.mtu_from_lr_packet(packet) or RNS.Reticulum.MTU
|
||||
except Exception as e:
|
||||
RNS.trace_exception(e)
|
||||
link.mtu = RNS.Reticulum.MTU
|
||||
@@ -683,8 +683,8 @@ class Link:
|
||||
except Exception as e: pass
|
||||
|
||||
def link_closed(self):
|
||||
for resource in self.incoming_resources: resource.cancel()
|
||||
for resource in self.outgoing_resources: resource.cancel()
|
||||
for resource in self.incoming_resources.copy(): resource.cancel()
|
||||
for resource in self.outgoing_resources.copy(): resource.cancel()
|
||||
if self._channel: self._channel._shutdown()
|
||||
|
||||
self.prv = None
|
||||
@@ -928,6 +928,13 @@ class Link:
|
||||
|
||||
def receive(self, packet):
|
||||
self.watchdog_lock = True
|
||||
try: self.__receive(packet)
|
||||
except Exception as e:
|
||||
RNS.log(f"Error on {self} while receiving packet: {e}", RNS.LOG_ERROR)
|
||||
RNS.trace_exception(e)
|
||||
finally: self.watchdog_lock = False
|
||||
|
||||
def __receive(self, packet):
|
||||
if not self.status == Link.CLOSED and not (self.initiator and packet.context == RNS.Packet.KEEPALIVE and packet.data == bytes([0xFF])):
|
||||
if packet.receiving_interface != self.attached_interface:
|
||||
RNS.log(f"Link-associated packet received on unexpected interface {packet.receiving_interface} instead of {self.attached_interface}! Someone might be trying to manipulate your communication!", RNS.LOG_ERROR)
|
||||
@@ -1156,8 +1163,6 @@ class Link:
|
||||
threading.Thread(target=job, daemon=True).start()
|
||||
self.__update_phy_stats(packet, query_shared=True)
|
||||
|
||||
self.watchdog_lock = False
|
||||
|
||||
def encrypt(self, plaintext):
|
||||
try:
|
||||
if not self.token:
|
||||
|
||||
+21
-8
@@ -118,6 +118,7 @@ class Packet:
|
||||
__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"
|
||||
__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):
|
||||
@@ -159,6 +160,8 @@ class Packet:
|
||||
self.packet_hash = None
|
||||
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
|
||||
@@ -260,18 +263,23 @@ class Packet:
|
||||
self.destination_hash = self.raw[DST_LEN+2:2*DST_LEN+2]
|
||||
self.context = ord(self.raw[2*DST_LEN+2:2*DST_LEN+3])
|
||||
self.data = self.raw[2*DST_LEN+3:]
|
||||
if len(self.transport_id) != DST_LEN: raise ValueError("Malformed Transport ID field")
|
||||
if len(self.destination_hash) != DST_LEN: raise ValueError("Malformed destination hash field")
|
||||
else:
|
||||
self.transport_id = None
|
||||
self.destination_hash = self.raw[2:DST_LEN+2]
|
||||
self.context = ord(self.raw[DST_LEN+2:DST_LEN+3])
|
||||
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):
|
||||
@@ -281,6 +289,7 @@ class Packet:
|
||||
:returns: A :ref:`RNS.PacketReceipt<api-packetreceipt>` instance if *create_receipt* was set to *True* when the packet was instantiated, if not returns *None*. If the packet could not be sent *False* is returned.
|
||||
"""
|
||||
if not self.sent:
|
||||
if self.hops >= RNS.Transport.PATHFINDER_M: return False
|
||||
if not self.packed: self.pack()
|
||||
if self.destination.type == RNS.Destination.LINK:
|
||||
if self.destination.status == RNS.Link.CLOSED:
|
||||
@@ -296,7 +305,7 @@ class Packet:
|
||||
|
||||
if RNS.Transport.outbound(self): return self.receipt
|
||||
else:
|
||||
RNS.log("No interfaces could process the outbound packet", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||
RNS.log(f"No interfaces could process the outbound {self.hops} hop, type {self.packet_type} packet for {self.destination}", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||
self.sent = False
|
||||
self.receipt = None
|
||||
return False
|
||||
@@ -345,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:]
|
||||
@@ -357,25 +370,25 @@ class Packet:
|
||||
:returns: The physical layer *Received Signal Strength Indication* if available, otherwise ``None``.
|
||||
"""
|
||||
if self.rssi != None: return self.rssi
|
||||
else: return reticulum.get_packet_rssi(self.packet_hash)
|
||||
else: return RNS.Reticulum.get_instance().get_packet_rssi(self.packet_hash)
|
||||
|
||||
def get_snr(self):
|
||||
"""
|
||||
:returns: The physical layer *Signal-to-Noise Ratio* if available, otherwise ``None``.
|
||||
"""
|
||||
if self.snr != None: return self.snr
|
||||
else: return reticulum.get_packet_snr(self.packet_hash)
|
||||
else: return RNS.Reticulum.get_instance().get_packet_snr(self.packet_hash)
|
||||
|
||||
def get_q(self):
|
||||
"""
|
||||
:returns: The physical layer *Link Quality* if available, otherwise ``None``.
|
||||
"""
|
||||
if self.q != None: return self.q
|
||||
else: return reticulum.get_packet_q(self.packet_hash)
|
||||
else: return RNS.Reticulum.get_instance().get_packet_q(self.packet_hash)
|
||||
|
||||
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
|
||||
@@ -400,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
|
||||
|
||||
+39
-31
@@ -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]
|
||||
@@ -447,8 +456,8 @@ class Resource:
|
||||
self.hashmap = b""
|
||||
collision_guard_list = []
|
||||
for i in range(0,hashmap_entries):
|
||||
data = self.data[i*self.sdu:(i+1)*self.sdu]
|
||||
map_hash = self.get_map_hash(data)
|
||||
part_data = self.data[i*self.sdu:(i+1)*self.sdu]
|
||||
map_hash = self.get_map_hash(part_data)
|
||||
|
||||
if map_hash in collision_guard_list:
|
||||
RNS.log("Found hash collision in resource map, remapping...", RNS.LOG_DEBUG) if RNS.sl(RNS.LOG_DEBUG) else None
|
||||
@@ -460,7 +469,7 @@ class Resource:
|
||||
if len(collision_guard_list) > ResourceAdvertisement.COLLISION_GUARD_SIZE:
|
||||
collision_guard_list.pop(0)
|
||||
|
||||
part = RNS.Packet(link, data, context=RNS.Packet.RESOURCE)
|
||||
part = RNS.Packet(link, part_data, context=RNS.Packet.RESOURCE)
|
||||
part.pack()
|
||||
part.map_hash = map_hash
|
||||
|
||||
@@ -865,9 +874,9 @@ class Resource:
|
||||
part_data = packet.data
|
||||
part_hash = self.get_map_hash(part_data)
|
||||
|
||||
consecutive_index = self.consecutive_completed_height if self.consecutive_completed_height >= 0 else 0
|
||||
i = consecutive_index
|
||||
for map_hash in self.hashmap[consecutive_index:consecutive_index+self.window]:
|
||||
search_start = self.consecutive_completed_height+1
|
||||
i = search_start
|
||||
for map_hash in self.hashmap[search_start:search_start+self.window]:
|
||||
if map_hash == part_hash:
|
||||
if self.parts[i] == None:
|
||||
|
||||
@@ -878,9 +887,6 @@ class Resource:
|
||||
self.outstanding_parts -= 1
|
||||
|
||||
# Update consecutive completed pointer
|
||||
if i == self.consecutive_completed_height + 1:
|
||||
self.consecutive_completed_height = i
|
||||
|
||||
cp = self.consecutive_completed_height + 1
|
||||
while cp < len(self.parts) and self.parts[cp] != None:
|
||||
self.consecutive_completed_height = cp
|
||||
@@ -1088,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()
|
||||
|
||||
@@ -1100,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:
|
||||
@@ -1120,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)
|
||||
@@ -1241,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:
|
||||
@@ -1365,4 +1373,4 @@ class ResourceAdvertisement:
|
||||
|
||||
if adv.t > Resource.MAX_EFFICIENT_SIZE*3: raise ValueError("Invalid transfer size")
|
||||
|
||||
return adv
|
||||
return adv
|
||||
+223
-24
@@ -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
|
||||
"""
|
||||
@@ -140,6 +140,9 @@ class Reticulum:
|
||||
# TODO: Let Reticulum somehow continously build a map of per-hop
|
||||
# latencies and use this map for global timeout calculation.
|
||||
DEFAULT_PER_HOP_TIMEOUT = 6
|
||||
"""
|
||||
The default per-hop timeout value used in various timeout calculations.
|
||||
"""
|
||||
|
||||
# Length of truncated hashes in bits.
|
||||
TRUNCATED_HASHLENGTH = 128
|
||||
@@ -187,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()
|
||||
|
||||
@@ -207,7 +208,7 @@ class Reticulum:
|
||||
@staticmethod
|
||||
def get_instance():
|
||||
"""
|
||||
Return the currently running Reticulum instance
|
||||
Returns the currently running Reticulum instance.
|
||||
"""
|
||||
return Reticulum.__instance
|
||||
|
||||
@@ -284,6 +285,10 @@ class Reticulum:
|
||||
Reticulum.__ic_held_release_interval = None
|
||||
Reticulum.__ec_pr_freq = None
|
||||
Reticulum.__egress_control = None
|
||||
Reticulum.__inbound_data_queue_length = None
|
||||
Reticulum.__inbound_announce_queue_length = None
|
||||
Reticulum.__inbound_pr_queue_length = None
|
||||
Reticulum.__inbound_il_queue_length = None
|
||||
|
||||
Reticulum.panic_on_interface_error = False
|
||||
|
||||
@@ -536,7 +541,8 @@ class Reticulum:
|
||||
|
||||
if option == "link_mtu_discovery":
|
||||
v = self.config["reticulum"].as_bool(option)
|
||||
if v == True: Reticulum.__link_mtu_discovery = True
|
||||
if v == True: Reticulum.__link_mtu_discovery = True
|
||||
elif v == False: Reticulum.__link_mtu_discovery = False
|
||||
|
||||
if option == "enable_remote_management":
|
||||
v = self.config["reticulum"].as_bool(option)
|
||||
@@ -696,6 +702,22 @@ class Reticulum:
|
||||
v = self.config["reticulum"].as_float(option)
|
||||
if v >= 0: Reticulum.__ic_held_release_interval = v
|
||||
|
||||
if option == "qlen_in_data":
|
||||
v = self.config["reticulum"].as_int(option)
|
||||
if v > 0: Reticulum.__inbound_data_queue_length = v
|
||||
|
||||
if option == "qlen_in_announce":
|
||||
v = self.config["reticulum"].as_int(option)
|
||||
if v > 0: Reticulum.__inbound_announce_queue_length = v
|
||||
|
||||
if option == "qlen_in_pr":
|
||||
v = self.config["reticulum"].as_int(option)
|
||||
if v > 0: Reticulum.__inbound_pr_queue_length = v
|
||||
|
||||
if option == "qlen_in_il":
|
||||
v = self.config["reticulum"].as_int(option)
|
||||
if v > 0: Reticulum.__inbound_il_queue_length = v
|
||||
|
||||
|
||||
if RNS.compiled: RNS.log("Reticulum running in compiled mode", RNS.LOG_DEBUG)
|
||||
else: RNS.log("Reticulum running in interpreted mode", RNS.LOG_DEBUG)
|
||||
@@ -713,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:
|
||||
@@ -860,6 +887,7 @@ class Reticulum:
|
||||
discovery_announce_interval = None
|
||||
discovery_stamp_value = None
|
||||
discovery_name = None
|
||||
discovery_lxmf_address = None
|
||||
discovery_encrypt = False
|
||||
reachable_on = None
|
||||
publish_ifac = False
|
||||
@@ -891,6 +919,11 @@ class Reticulum:
|
||||
if "discovery_frequency" in c: discovery_frequency = c.as_int("discovery_frequency")
|
||||
if "discovery_bandwidth" in c: discovery_bandwidth = c.as_int("discovery_bandwidth")
|
||||
if "discovery_modulation" in c: discovery_modulation = c.as_int("discovery_modulation")
|
||||
if "discovery_lxmf_address" in c:
|
||||
if len(c["discovery_lxmf_address"]) == RNS.Identity.TRUNCATED_HASHLENGTH//8*2:
|
||||
try: discovery_lxmf_address = bytes.fromhex(c["discovery_lxmf_address"])
|
||||
except: RNS.log(f"Invalid interface discovery LXMF address: {c['discovery_lxmf_address']}", RNS.LOG_ERROR)
|
||||
else: RNS.log(f"Invalid length for interface discovery LXMF address: {c['discovery_lxmf_address']}", RNS.LOG_ERROR)
|
||||
|
||||
if not interface_mode in [Interface.Interface.MODE_GATEWAY, Interface.Interface.MODE_ACCESS_POINT, Interface.Interface.MODE_INTERNAL]:
|
||||
if not ignore_config_warnings:
|
||||
@@ -922,6 +955,7 @@ class Reticulum:
|
||||
interface.discovery_publish_ifac = publish_ifac
|
||||
interface.reachable_on = reachable_on
|
||||
interface.discovery_name = discovery_name
|
||||
interface.discovery_lxmf_address = discovery_lxmf_address
|
||||
interface.discovery_encrypt = discovery_encrypt
|
||||
interface.discovery_stamp_value = discovery_stamp_value
|
||||
interface.discovery_location = discovery_location
|
||||
@@ -1250,17 +1284,21 @@ class Reticulum:
|
||||
mh = call["max_hops"]
|
||||
self.rpc_return(conn, self.get_path_table(max_hops=mh))
|
||||
|
||||
if path == "interface_stats": self.rpc_return(conn, self.get_interface_stats())
|
||||
if path == "rate_table": self.rpc_return(conn, self.get_rate_table())
|
||||
if path == "next_hop_if_name": self.rpc_return(conn, self.get_next_hop_if_name(call["destination_hash"]))
|
||||
if path == "next_hop": self.rpc_return(conn, self.get_next_hop(call["destination_hash"]))
|
||||
if path == "first_hop_timeout": self.rpc_return(conn, self.get_first_hop_timeout(call["destination_hash"]))
|
||||
if path == "link_count": self.rpc_return(conn, self.get_link_count())
|
||||
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 == "blackholed_identities": self.rpc_return(conn, self.get_blackholed_identities())
|
||||
if path == "is_blackholed": self.rpc_return(conn, self.is_blackholed(call["identity_hash"]))
|
||||
if path == "interface_stats": self.rpc_return(conn, self.get_interface_stats())
|
||||
if path == "rate_table": self.rpc_return(conn, self.get_rate_table())
|
||||
if path == "next_hop_if_name": self.rpc_return(conn, self.get_next_hop_if_name(call["destination_hash"]))
|
||||
if path == "next_hop": self.rpc_return(conn, self.get_next_hop(call["destination_hash"]))
|
||||
if path == "first_hop_timeout": self.rpc_return(conn, self.get_first_hop_timeout(call["destination_hash"]))
|
||||
if path == "lowest_interface_bitrate": self.rpc_return(conn, self.get_lowest_interface_bitrate())
|
||||
if path == "medium_path_timeout": self.rpc_return(conn, self.get_medium_path_timeout())
|
||||
if path == "link_count": self.rpc_return(conn, self.get_link_count())
|
||||
if path == "active_link_count": self.rpc_return(conn, self.get_active_link_count())
|
||||
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"]))
|
||||
|
||||
if "drop" in call:
|
||||
path = call["drop"]
|
||||
@@ -1440,6 +1478,26 @@ class Reticulum:
|
||||
else: ifstats["txs"] = 0
|
||||
else: ifstats["txs"] = 0
|
||||
|
||||
if hasattr(interface, "current_arx_speed"):
|
||||
if interface.current_arx_speed != None: ifstats["arxs"] = interface.current_arx_speed
|
||||
else: ifstats["arxs"] = 0
|
||||
else: ifstats["arxs"] = 0
|
||||
|
||||
if hasattr(interface, "current_atx_speed"):
|
||||
if interface.current_atx_speed != None: ifstats["atxs"] = interface.current_atx_speed
|
||||
else: ifstats["atxs"] = 0
|
||||
else: ifstats["atxs"] = 0
|
||||
|
||||
if hasattr(interface, "current_prx_speed"):
|
||||
if interface.current_prx_speed != None: ifstats["prxs"] = interface.current_prx_speed
|
||||
else: ifstats["prxs"] = 0
|
||||
else: ifstats["prxs"] = 0
|
||||
|
||||
if hasattr(interface, "current_ptx_speed"):
|
||||
if interface.current_ptx_speed != None: ifstats["ptxs"] = interface.current_ptx_speed
|
||||
else: ifstats["ptxs"] = 0
|
||||
else: ifstats["ptxs"] = 0
|
||||
|
||||
if hasattr(interface, "peers"):
|
||||
if interface.peers != None: ifstats["peers"] = len(interface.peers)
|
||||
else: ifstats["peers"] = None
|
||||
@@ -1470,8 +1528,21 @@ 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
|
||||
ifstats["atxb"] = interface.atxb
|
||||
ifstats["arxc"] = interface.arxc
|
||||
ifstats["atxc"] = interface.atxc
|
||||
ifstats["prxb"] = interface.prxb
|
||||
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()
|
||||
@@ -1482,21 +1553,63 @@ class Reticulum:
|
||||
ifstats["held_announces"] = len(interface.held_announces)
|
||||
ifstats["burst_active"] = interface.ic_burst_active
|
||||
ifstats["burst_activated"] = interface.ic_burst_activated
|
||||
ifstats["burst_count"] = interface.ic_burst_count
|
||||
ifstats["pr_burst_active"] = interface.ic_pr_burst_active
|
||||
ifstats["pr_burst_activated"] = interface.ic_pr_burst_activated
|
||||
ifstats["pr_burst_count"] = interface.ic_pr_burst_count
|
||||
ifstats["status"] = interface.online
|
||||
ifstats["mode"] = interface.mode
|
||||
ifstats["gravity"] = interface.gravity
|
||||
ifstats["announces_to_internal"] = interface.announces_to_internal
|
||||
ifstats["protocol_violations"] = interface.protocol_violations
|
||||
ifstats["ifac_violations"] = interface.ifac_violations
|
||||
ifstats["packet_filter_hits"] = interface.packet_filter_hits
|
||||
|
||||
interfaces.append(ifstats)
|
||||
|
||||
stats = {}
|
||||
stats["interfaces"] = interfaces
|
||||
stats["rxb"] = RNS.Transport.traffic_rxb
|
||||
stats["txb"] = RNS.Transport.traffic_txb
|
||||
stats["rxs"] = RNS.Transport.speed_rx
|
||||
stats["txs"] = RNS.Transport.speed_tx
|
||||
qsnapshot = RNS.Transport.inbound_queues.snapshot()
|
||||
dql = RNS.Transport.INBOUND_DA_QUEUE_LENGTH
|
||||
aql = RNS.Transport.INBOUND_AN_QUEUE_LENGTH
|
||||
pql = RNS.Transport.INBOUND_PR_QUEUE_LENGTH
|
||||
ilql = RNS.Transport.INBOUND_IL_QUEUE_LENGTH
|
||||
tql = dql+aql+pql+ilql
|
||||
|
||||
stats = {}
|
||||
stats["interfaces"] = interfaces
|
||||
stats["rxb"] = RNS.Transport.traffic_rxb
|
||||
stats["txb"] = RNS.Transport.traffic_txb
|
||||
stats["rxs"] = RNS.Transport.speed_rx
|
||||
stats["txs"] = RNS.Transport.speed_tx
|
||||
stats["arxb"] = RNS.Transport.announce_rxb
|
||||
stats["atxb"] = RNS.Transport.announce_txb
|
||||
stats["arxs"] = RNS.Transport.announce_speed_rx
|
||||
stats["atxs"] = RNS.Transport.announce_speed_tx
|
||||
stats["arxf"] = RNS.Transport.announce_freq_rx
|
||||
stats["atxf"] = RNS.Transport.announce_freq_tx
|
||||
stats["prxb"] = RNS.Transport.pr_rxb
|
||||
stats["ptxb"] = RNS.Transport.pr_txb
|
||||
stats["prxs"] = RNS.Transport.pr_speed_rx
|
||||
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]
|
||||
stats["rxqp"] = qsnapshot[1][2]
|
||||
stats["rxqil"] = qsnapshot[1][3]
|
||||
stats["rxqtd"] = qsnapshot[2][0]+qsnapshot[2][1]+qsnapshot[2][2]+qsnapshot[2][3]
|
||||
stats["rxqdd"] = qsnapshot[2][0]
|
||||
stats["rxqad"] = qsnapshot[2][1]
|
||||
stats["rxqpd"] = qsnapshot[2][2]
|
||||
stats["rxqild"] = qsnapshot[2][3]
|
||||
stats["tqpressure"] = qsnapshot[0]/tql if qsnapshot[0] else 0
|
||||
stats["dqpressure"] = qsnapshot[1][0]/dql if qsnapshot[1][0] else 0
|
||||
stats["aqpressure"] = qsnapshot[1][1]/aql if qsnapshot[1][1] else 0
|
||||
stats["pqpressure"] = qsnapshot[1][2]/pql if qsnapshot[1][2] else 0
|
||||
stats["ilqpressure"] = qsnapshot[1][3]/ilql if qsnapshot[1][3] else 0
|
||||
stats["txq"] = None
|
||||
|
||||
if Reticulum.transport_enabled():
|
||||
stats["transport_id"] = RNS.Transport.identity.hash
|
||||
@@ -1602,6 +1715,16 @@ class Reticulum:
|
||||
return str(RNS.Transport.next_hop_interface(destination))
|
||||
|
||||
def get_first_hop_timeout(self, destination):
|
||||
"""
|
||||
Returns a best-effort estimate of a reasonable minimum
|
||||
*first-hop* timeout value for a given destination hash.
|
||||
If a path is known, this calculation takes the next-hop
|
||||
interface's bitrate into account. If no path is currently
|
||||
known, returns ``DEFAULT_PER_HOP_TIMEOUT``.
|
||||
|
||||
:param destination: A destination hash, as *bytes*.
|
||||
:returns: First-hop timeout, in seconds.
|
||||
"""
|
||||
if self.is_connected_to_shared_instance:
|
||||
try:
|
||||
rpc_connection = self.get_rpc_client()
|
||||
@@ -1621,6 +1744,45 @@ class Reticulum:
|
||||
else:
|
||||
return RNS.Transport.first_hop_timeout(destination)
|
||||
|
||||
def get_lowest_interface_bitrate(self):
|
||||
"""
|
||||
Returns the bitrate of the slowest currently online
|
||||
interface, or None if no online interface bitrate
|
||||
|
||||
:returns: Lowest online interface bitrate in bits per second, or ``None``.
|
||||
"""
|
||||
if self.is_connected_to_shared_instance:
|
||||
try:
|
||||
rpc_connection = self.get_rpc_client()
|
||||
rpc_connection.send_bytes(mp.packb({"get": "lowest_interface_bitrate"}))
|
||||
return mp.unpackb(rpc_connection.recv_bytes())
|
||||
except Exception as e:
|
||||
RNS.log("An error occurred while getting lowest interface bitrate from shared instance: "+str(e), RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
else:
|
||||
return RNS.Transport.lowest_interface_bitrate
|
||||
|
||||
def get_medium_path_timeout(self):
|
||||
"""
|
||||
Returns an estimate of a reasonable minimum path request timeout covering
|
||||
a full round trip for an MTU on the slowest currently online interface
|
||||
plus per hop grace
|
||||
|
||||
:returns: Timeout in seconds or 0 if it's unknown.
|
||||
"""
|
||||
if self.is_connected_to_shared_instance:
|
||||
try:
|
||||
rpc_connection = self.get_rpc_client()
|
||||
rpc_connection.send_bytes(mp.packb({"get": "medium_path_timeout"}))
|
||||
return mp.unpackb(rpc_connection.recv_bytes())
|
||||
except Exception as e:
|
||||
RNS.log("An error occurred while getting medium path timeout from shared instance: "+str(e), RNS.LOG_ERROR)
|
||||
return 0
|
||||
|
||||
else:
|
||||
return RNS.Transport.medium_path_timeout()
|
||||
|
||||
def get_next_hop(self, destination):
|
||||
if self.is_connected_to_shared_instance:
|
||||
rpc_connection = self.get_rpc_client()
|
||||
@@ -1640,7 +1802,17 @@ class Reticulum:
|
||||
return response
|
||||
|
||||
else:
|
||||
return len(RNS.Transport.link_table)
|
||||
return RNS.Transport.link_count()
|
||||
|
||||
def get_active_link_count(self):
|
||||
if self.is_connected_to_shared_instance:
|
||||
rpc_connection = self.get_rpc_client()
|
||||
rpc_connection.send_bytes(mp.packb({"get": "active_link_count"}))
|
||||
response = mp.unpackb(rpc_connection.recv_bytes())
|
||||
return response
|
||||
|
||||
else:
|
||||
return RNS.Transport.active_link_count()
|
||||
|
||||
def get_packet_rssi(self, packet_hash):
|
||||
if self.is_connected_to_shared_instance:
|
||||
@@ -1684,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
|
||||
|
||||
@@ -1873,6 +2056,22 @@ class Reticulum:
|
||||
def local_hops_delta():
|
||||
return Reticulum.__local_hops_delta
|
||||
|
||||
@staticmethod
|
||||
def default_data_queue_length():
|
||||
return Reticulum.__inbound_data_queue_length
|
||||
|
||||
@staticmethod
|
||||
def default_announce_queue_length():
|
||||
return Reticulum.__inbound_announce_queue_length
|
||||
|
||||
@staticmethod
|
||||
def default_pr_queue_length():
|
||||
return Reticulum.__inbound_pr_queue_length
|
||||
|
||||
@staticmethod
|
||||
def default_il_queue_length():
|
||||
return Reticulum.__inbound_il_queue_length
|
||||
|
||||
# Default configuration file:
|
||||
__default_rns_config__ = '''# This is the default Reticulum config file.
|
||||
# You should probably edit it to include any additional,
|
||||
|
||||
+1395
-941
File diff suppressed because it is too large.
Load diff
@@ -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__"]))
|
||||
@@ -401,7 +401,7 @@ def fetch(configdir, identitypath = None, verbosity = 0, quietness = 0, destinat
|
||||
|
||||
i = 0
|
||||
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
||||
estab_timeout = time.time()+timeout
|
||||
estab_timeout = time.time()+max(timeout, reticulum.get_medium_path_timeout())
|
||||
while not RNS.Transport.has_path(destination_hash) and time.time() < estab_timeout:
|
||||
if not silent:
|
||||
time.sleep(0.1)
|
||||
@@ -431,6 +431,7 @@ def fetch(configdir, identitypath = None, verbosity = 0, quietness = 0, destinat
|
||||
)
|
||||
|
||||
link = RNS.Link(listener_destination)
|
||||
estab_timeout = max(estab_timeout, time.time()+link.establishment_timeout)
|
||||
while link.status != RNS.Link.ACTIVE and time.time() < estab_timeout:
|
||||
if not silent:
|
||||
time.sleep(0.1)
|
||||
@@ -656,7 +657,7 @@ def send(configdir, identitypath = None, verbosity = 0, quietness = 0, destinati
|
||||
|
||||
i = 0
|
||||
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
||||
estab_timeout = time.time()+timeout
|
||||
estab_timeout = time.time()+max(timeout, reticulum.get_medium_path_timeout())
|
||||
while not RNS.Transport.has_path(destination_hash) and time.time() < estab_timeout:
|
||||
if not silent:
|
||||
time.sleep(0.1)
|
||||
@@ -686,6 +687,7 @@ def send(configdir, identitypath = None, verbosity = 0, quietness = 0, destinati
|
||||
)
|
||||
|
||||
link = RNS.Link(receiver_destination)
|
||||
estab_timeout = max(estab_timeout, time.time()+link.establishment_timeout)
|
||||
while link.status != RNS.Link.ACTIVE and time.time() < estab_timeout:
|
||||
if not silent:
|
||||
time.sleep(0.1)
|
||||
@@ -878,8 +880,8 @@ def main():
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("")
|
||||
if resource != None:
|
||||
resource.cancel()
|
||||
if current_resource != None:
|
||||
current_resource.cancel()
|
||||
if link != None:
|
||||
link.teardown()
|
||||
RNS.exit()
|
||||
|
||||
@@ -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__"]))
|
||||
@@ -40,6 +40,7 @@ import subprocess
|
||||
|
||||
from RNS._version import __version__
|
||||
from RNS.Utilities.rngit import APP_NAME
|
||||
from RNS.Utilities.rngit.util import medium_path_timeout
|
||||
|
||||
from RNS.vendor.configobj import ConfigObj
|
||||
from tempfile import TemporaryDirectory
|
||||
@@ -223,7 +224,7 @@ class ReticulumGitClient():
|
||||
|
||||
RNS.log(f"Requesting path to {RNS.prettyhexrep(destination_hash)}", RNS.LOG_DEBUG)
|
||||
sys.stderr.write(f"Requesting path..."); sys.stderr.flush()
|
||||
if not RNS.Transport.await_path(destination_hash, timeout=self.path_timeout):
|
||||
if not RNS.Transport.await_path(destination_hash, timeout=medium_path_timeout(self.path_timeout)):
|
||||
sys.stderr.write(f"\n"); sys.stderr.flush()
|
||||
self.abort(f"Could not resolve path to {RNS.prettyhexrep(destination_hash)}")
|
||||
|
||||
@@ -291,6 +292,8 @@ class ReticulumGitClient():
|
||||
|
||||
if hasattr(self.request_response, "read") and callable(self.request_response.read):
|
||||
response_path = self.request_response.name
|
||||
try: self.request_response.close()
|
||||
except Exception as e: RNS.log(f"Could not close resource file descriptor before retain: {e}", RNS.LOG_ERROR)
|
||||
base_name = os.path.basename(response_path)
|
||||
retained_path = os.path.join(self.tmp_dir.name, base_name)
|
||||
shutil.move(response_path, retained_path)
|
||||
@@ -333,10 +336,10 @@ class ReticulumGitClient():
|
||||
try: self.connect_server()
|
||||
except Exception as e: self.abort(str(e))
|
||||
|
||||
timeout = self.link_timeout
|
||||
timeout = max(self.link_timeout, self.link.establishment_timeout)
|
||||
while not self.link_ready and not self.link_failed and timeout > 0:
|
||||
time.sleep(0.5)
|
||||
timeout -= 1
|
||||
timeout -= 0.5
|
||||
|
||||
if not self.link_ready: self.abort("Failed to establish link")
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -46,7 +46,7 @@ from datetime import datetime, timezone
|
||||
from RNS._version import __version__
|
||||
from RNS.Utilities.rngit import APP_NAME
|
||||
from RNS.Utilities.rngit.pages import NomadNetworkNode
|
||||
from RNS.Utilities.rngit.util import san_ref, san_refs, san_sha
|
||||
from RNS.Utilities.rngit.util import san_ref, san_refs, san_sha, medium_path_timeout
|
||||
from RNS.vendor.configobj import ConfigObj
|
||||
from RNS.vendor import umsgpack as mp
|
||||
from RNS.Utilities.rnid import create_rsg, validate_rsg, get_rsg_hash
|
||||
@@ -465,7 +465,7 @@ class ReticulumGitClient():
|
||||
def connect_remote(self, remote):
|
||||
destination_hash = self.parse_remote_destination_url(remote)
|
||||
print(f"Requesting path... ", end="")
|
||||
if not RNS.Transport.await_path(destination_hash, timeout=self.path_timeout):
|
||||
if not RNS.Transport.await_path(destination_hash, timeout=medium_path_timeout(self.path_timeout)):
|
||||
print(f"\n", end="")
|
||||
self.abort(f"Could not resolve path to {RNS.prettyhexrep(destination_hash)}")
|
||||
|
||||
@@ -479,6 +479,7 @@ class ReticulumGitClient():
|
||||
self.link = RNS.Link(self.destination)
|
||||
self.link.set_link_established_callback(self.link_established)
|
||||
self.link.set_link_closed_callback(self.link_closed)
|
||||
self.link_timeout = max(self.link_timeout, self.link.establishment_timeout)
|
||||
|
||||
def link_established(self, link):
|
||||
print(f"\rLink established ", end="")
|
||||
@@ -4896,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]
|
||||
|
||||
|
||||
@@ -814,3 +814,6 @@ class MarkdownToMicron:
|
||||
def convert_markdown_to_micron(text):
|
||||
converter = MarkdownToMicron()
|
||||
return converter.format_block(text)
|
||||
|
||||
def medium_path_timeout(default_timeout):
|
||||
return max(default_timeout, RNS.Reticulum.get_instance().get_medium_path_timeout())
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -3766,8 +3766,8 @@ def main():
|
||||
print("\nDevice configuration:")
|
||||
if ec_bt == 0x73: print(f" Bluetooth : Enabled")
|
||||
else: print(f" Bluetooth : Disabled")
|
||||
if ec_wifi == 0x01: print(f" WiFi : Enabled (Station)")
|
||||
if ec_wifi == 0x02: print(f" WiFi : Enabled (AP)")
|
||||
if ec_wifi == 0x01: print(f" WiFi : Enabled (Station)")
|
||||
elif ec_wifi == 0x02: print(f" WiFi : Enabled (AP)")
|
||||
else: print(f" WiFi : Disabled")
|
||||
if ec_wifi == 0x01 or ec_wifi == 0x02:
|
||||
if not ec_wchn: print(f" Channel : Unknown")
|
||||
|
||||
@@ -42,6 +42,7 @@ remote_link = None
|
||||
output_rst_str = "\r \r"
|
||||
def connect_remote(destination_hash, auth_identity, timeout, no_output = False, purpose="management"):
|
||||
global remote_link, reticulum
|
||||
timeout = max(timeout, reticulum.get_medium_path_timeout())
|
||||
if not RNS.Transport.has_path(destination_hash):
|
||||
if not no_output:
|
||||
print("Path to "+RNS.prettyhexrep(destination_hash)+" requested", end=" ")
|
||||
@@ -451,7 +452,7 @@ def program_setup(configdir, table, rates, drop, destination_hexhash, verbosity,
|
||||
|
||||
i = 0
|
||||
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
||||
limit = time.time()+timeout
|
||||
limit = time.time()+max(timeout, reticulum.get_medium_path_timeout())
|
||||
while not RNS.Transport.has_path(destination_hash) and time.time()<limit:
|
||||
time.sleep(0.1)
|
||||
print(("\b\b"+syms[i]+" "), end="")
|
||||
|
||||
@@ -81,7 +81,7 @@ def program_setup(configdir, destination_hexhash, size=None, full_name = None, v
|
||||
print("Path to "+RNS.prettyhexrep(destination_hash)+" requested ", end=" ")
|
||||
sys.stdout.flush()
|
||||
|
||||
_timeout = time.time() + (timeout or DEFAULT_TIMEOUT+reticulum.get_first_hop_timeout(destination_hash))
|
||||
_timeout = time.time() + (timeout or max(DEFAULT_TIMEOUT+reticulum.get_first_hop_timeout(destination_hash), reticulum.get_medium_path_timeout()))
|
||||
i = 0
|
||||
syms = "⢄⢂⢁⡁⡈⡐⡠"
|
||||
while not RNS.Transport.has_path(destination_hash) and not time.time() > _timeout:
|
||||
@@ -131,7 +131,7 @@ def program_setup(configdir, destination_hexhash, size=None, full_name = None, v
|
||||
|
||||
print("\rSent probe "+str(sent)+" ("+str(size)+" bytes) to "+RNS.prettyhexrep(destination_hash)+more+" ", end=" ")
|
||||
|
||||
_timeout = time.time() + (timeout or DEFAULT_TIMEOUT+reticulum.get_first_hop_timeout(destination_hash))
|
||||
_timeout = time.time() + (timeout or max(DEFAULT_TIMEOUT+reticulum.get_first_hop_timeout(destination_hash), reticulum.get_medium_path_timeout()))
|
||||
i = 0
|
||||
while receipt.status == RNS.PacketReceipt.SENT and not time.time() > _timeout:
|
||||
time.sleep(0.1)
|
||||
|
||||
@@ -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__
|
||||
@@ -405,7 +405,7 @@ async def initiate(configdir: str, rnsconfigdir:str, identitypath: str, logfile:
|
||||
chunk_segment = None
|
||||
|
||||
chunk_segment = None
|
||||
max_data_len = channel.mdu - protocol.StreamDataMessage.OVERHEAD
|
||||
max_data_len = channel.mdu - protocol.StreamDataMessage.HEADER_LEN
|
||||
while chunk_len > 32 and comp_try < comp_tries:
|
||||
chunk_segment_length = int(chunk_len/comp_try)
|
||||
compressed_chunk = bz2.compress(buf[:chunk_segment_length])
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -235,7 +235,7 @@ class ListenerSession:
|
||||
chunk_segment = None
|
||||
|
||||
chunk_segment = None
|
||||
max_data_len = self.channel.mdu - protocol.StreamDataMessage.OVERHEAD
|
||||
max_data_len = self.channel.mdu - protocol.StreamDataMessage.HEADER_LEN
|
||||
while chunk_len > 32 and comp_try < comp_tries:
|
||||
chunk_segment_length = int(chunk_len/comp_try)
|
||||
compressed_chunk = bz2.compress(buf[:chunk_segment_length])
|
||||
|
||||
+197
-53
@@ -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:
|
||||
@@ -152,9 +156,10 @@ def get_remote_status(destination_hash, include_lstats, identity, no_output=Fals
|
||||
|
||||
return request_result
|
||||
|
||||
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, remote_timeout=RNS.Transport.PATH_REQUEST_TIMEOUT, must_exit=True,
|
||||
rns_instance=None, traffic_totals=False, discovered_interfaces=False, config_entries=False, burst_filter=False):
|
||||
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, pps=False, profiling=False, remote_timeout=RNS.Transport.PATH_REQUEST_TIMEOUT):
|
||||
|
||||
if remote: require_shared = False
|
||||
else: require_shared = True
|
||||
@@ -172,7 +177,9 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
||||
else: return
|
||||
|
||||
link_count = None
|
||||
active_link_count = None
|
||||
stats = None
|
||||
profiling_results = None
|
||||
|
||||
details = False
|
||||
if config_entries:
|
||||
@@ -225,15 +232,18 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
||||
location = f"{lat}, {lon}{height}"
|
||||
else: location = "Unknown"
|
||||
|
||||
lxmf_addr = None
|
||||
transport_id = None
|
||||
network = None
|
||||
network = None
|
||||
if "operator_lxmf_address" in i: lxmf_addr = i['operator_lxmf_address']
|
||||
if "transport_id" in i: transport_id = i["transport_id"]
|
||||
if "transport_id" in i and "network_id" in i and i["transport_id"] != i["network_id"]:
|
||||
network = i["network_id"]
|
||||
|
||||
if idx > 0: print("\n"+"="*32+"\n")
|
||||
if idx > 0: print("\n"+"="*47+"\n")
|
||||
if network: print(f"Network ID : {network}")
|
||||
if transport_id: print(f"Transport ID : {transport_id}")
|
||||
if lxmf_addr: print(f"LXMF address : {lxmf_addr}")
|
||||
|
||||
print(f"Name : {name}")
|
||||
print(f"Type : {if_type}")
|
||||
@@ -258,8 +268,7 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
||||
config_lines = i["config_entry"].split('\n')
|
||||
for line in config_lines: print(f" {line}")
|
||||
|
||||
except Exception as e:
|
||||
pass
|
||||
except Exception as e: pass
|
||||
|
||||
else:
|
||||
print(f"{'Name':<25} {'Type':<12} {'Status':<12} {'Last Heard':<12} {'Value':<8} {'Location':<15}")
|
||||
@@ -323,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:
|
||||
@@ -336,6 +345,12 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
||||
if lstats:
|
||||
try: link_count = reticulum.get_link_count()
|
||||
except Exception as e: pass
|
||||
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
|
||||
@@ -361,34 +376,31 @@ 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 == "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 == "held":
|
||||
interfaces.sort(key=lambda i: i["held_announces"], 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:
|
||||
name = ifstat["name"]
|
||||
|
||||
@@ -458,6 +470,9 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
||||
p = ifstat["blocked_ips"] > 0
|
||||
if p: clients_string += "\n Blocked : "+str(ifstat["blocked_ips"])+" IP"+"s" if p else ""
|
||||
|
||||
if blocked_ips and "blocked_ip_list" in ifstat and len(ifstat["blocked_ip_list"]) > 0:
|
||||
for bip in ifstat["blocked_ip_list"]: clients_string += f"\n {bip}"
|
||||
|
||||
else:
|
||||
clients = None
|
||||
|
||||
@@ -477,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 = ""
|
||||
@@ -572,13 +590,17 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
||||
|
||||
burst_str = ""
|
||||
if "burst_active" in ifstat and ifstat["burst_active"]:
|
||||
if "burst_count" in ifstat and ifstat["burst_count"]: bcstr = f"on {ifstat['burst_count']} "
|
||||
else: bcstr = ""
|
||||
for_str = RNS.prettytime(time.time()-ifstat["burst_activated"])
|
||||
burst_str = f" burst for {for_str}"
|
||||
burst_str = f" burst {bcstr}for {for_str}"
|
||||
|
||||
pburst_str = ""
|
||||
if "pr_burst_active" in ifstat and ifstat["pr_burst_active"]:
|
||||
if "pr_burst_count" in ifstat and ifstat["pr_burst_count"]: prbcstr = f"on {ifstat['pr_burst_count']} "
|
||||
else: prbcstr = ""
|
||||
for_str = RNS.prettytime(time.time()-ifstat["pr_burst_activated"])
|
||||
pburst_str = f"burst for {for_str}"
|
||||
pburst_str = f"burst {prbcstr}for {for_str}"
|
||||
|
||||
rxb_str = "↓"+RNS.prettysize(ifstat["rxb"])
|
||||
txb_str = "↑"+RNS.prettysize(ifstat["txb"])
|
||||
@@ -593,8 +615,16 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
||||
|
||||
cspec = "c"
|
||||
if clients == None and "peers" in ifstat and ifstat["peers"]: clients = ifstat["peers"]; cspec = "p"
|
||||
if clients != None and clients > 0: pc_str = f"{RNS.prettyfrequency(ifstat['outgoing_announce_frequency']/clients, d=1, lpf=True)}/{cspec}"
|
||||
if clients != None and clients > 0: pc_str = f" {RNS.prettyfrequency(ifstat['outgoing_announce_frequency']/clients, d=1, lpf=True)}/{cspec}"
|
||||
else: pc_str = ""
|
||||
|
||||
if "prxs" in ifstat and "rxs" in ifstat and "ptxs" in ifstat and "txs" in ifstat:
|
||||
arxspct = min(100.0, (ifstat["arxs"] / ifstat["rxs"])*100.0) if ifstat["rxs"] and ifstat["arxs"] else 0.0
|
||||
atxspct = min(100.0, (ifstat["atxs"] / ifstat["txs"])*100.0) if ifstat["txs"] and ifstat["atxs"] else 0.0
|
||||
apctstr = f"(↓{int(arxspct)}% / ↑{int(atxspct)}% of flow)"
|
||||
if pc_str: pc_str = f"{pc_str} {apctstr}"
|
||||
else: pc_str = f"{apctstr}"
|
||||
|
||||
asr = True
|
||||
|
||||
psr = False
|
||||
@@ -610,8 +640,16 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
||||
ipf = RNS.prettyfrequency(ipn,d=1, lpf=True)+"↓"
|
||||
cspec = "c"
|
||||
if clients == None and "peers" in ifstat and ifstat["peers"]: clients = ifstat["peers"]; cspec = "p"
|
||||
if clients != None and clients > 0: rpc_str = f"{RNS.prettyfrequency(ifstat['outgoing_pr_frequency']/clients, d=1, lpf=True)}/{cspec}"
|
||||
if clients != None and clients > 0: rpc_str = f" {RNS.prettyfrequency(ifstat['outgoing_pr_frequency']/clients, d=1, lpf=True)}/{cspec}"
|
||||
else: rpc_str = ""
|
||||
|
||||
if "prxs" in ifstat and "rxs" in ifstat and "ptxs" in ifstat and "txs" in ifstat:
|
||||
prxspct = min(100.0, (ifstat["prxs"] / ifstat["rxs"])*100.0) if ifstat["rxs"] and ifstat["prxs"] else 0.0
|
||||
ptxspct = min(100.0, (ifstat["ptxs"] / ifstat["txs"])*100.0) if ifstat["txs"] and ifstat["ptxs"] else 0.0
|
||||
ppctstr = f"(↓{int(prxspct)}% / ↑{int(ptxspct)}% of flow)"
|
||||
if rpc_str: rpc_str = f"{rpc_str} {ppctstr}"
|
||||
else: rpc_str = f"{ppctstr}"
|
||||
|
||||
psr = True
|
||||
|
||||
if not asr: iaf = ""; oaf = ""
|
||||
@@ -627,12 +665,30 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
||||
rxb_str += (mlen-len(rxb_str))*" "
|
||||
txb_str += (mlen-len(txb_str))*" "
|
||||
|
||||
if "protocol_violations" in ifstat and "ifac_violations" in ifstat:
|
||||
pv = ifstat["protocol_violations"]; iv = ifstat["ifac_violations"]
|
||||
if pv or iv:
|
||||
pvstr = f"{pv} protocol{', ' if iv else ''}"
|
||||
ivstr = f"{iv} IFAC" if iv else ""
|
||||
print(f" Violatns. : {pvstr}{ivstr}")
|
||||
|
||||
if "packet_filter_hits" in ifstat and ifstat["packet_filter_hits"]:
|
||||
print(f" Flt. Hits : {ifstat['packet_filter_hits']}")
|
||||
|
||||
if psr:
|
||||
print(f" Path Rqs. : {opf} {rpc_str}")
|
||||
if ifstat["prxc"] and ifstat["ptxc"]:
|
||||
print(f" Path Rqs. : {ifstat['prxc']}↓ {ifstat['ptxc']}↑ total")
|
||||
print(f" {opf} {rpc_str}")
|
||||
else:
|
||||
print(f" Path Rqs. : {opf} {rpc_str}")
|
||||
print(f" {ipf} {pburst_str}")
|
||||
|
||||
if asr:
|
||||
print(f" Announces : {oaf} {pc_str}")
|
||||
if ifstat["arxc"] and ifstat["atxc"]:
|
||||
print(f" Announces : {ifstat['arxc']}↓ {ifstat['atxc']}↑ total")
|
||||
print(f" {oaf} {pc_str}")
|
||||
else:
|
||||
print(f" Announces : {oaf} {pc_str}")
|
||||
print(f" {iaf} {art_str}{burst_str}")
|
||||
|
||||
rxstat = rxb_str
|
||||
@@ -640,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}")
|
||||
|
||||
@@ -651,19 +712,96 @@ def program_setup(configdir, dispall=False, verbosity=0, name_filter=None, json=
|
||||
else:
|
||||
lstr = f" {link_count} entr{ms} in link table"
|
||||
|
||||
if active_link_count: lstr = f"{lstr} ({active_link_count} active)"
|
||||
|
||||
if traffic_totals:
|
||||
rxb_str = "↓"+RNS.prettysize(stats["rxb"])
|
||||
txb_str = "↑"+RNS.prettysize(stats["txb"])
|
||||
strdiff = len(rxb_str)-len(txb_str)
|
||||
if strdiff > 0:
|
||||
txb_str += " "*strdiff
|
||||
elif strdiff < 0:
|
||||
rxb_str += " "*-strdiff
|
||||
if strdiff > 0: txb_str += " "*strdiff
|
||||
elif strdiff < 0: rxb_str += " "*-strdiff
|
||||
|
||||
rxstat = rxb_str+" "+RNS.prettyspeed(stats["rxs"])
|
||||
txstat = txb_str+" "+RNS.prettyspeed(stats["txs"])
|
||||
|
||||
if pstats or astats:
|
||||
if "prxs" in stats and "ptxs" in stats and "arxs" in stats and "atxs" in stats:
|
||||
parxs = stats["prxs"]+stats["arxs"]
|
||||
patxs = stats["ptxs"]+stats["atxs"]
|
||||
drxpct = 100.0-min(100.0, (parxs / stats["rxs"])*100.0) if stats["rxs"] else 100.0
|
||||
dtxpct = 100.0-min(100.0, (patxs / stats["txs"])*100.0) if stats["txs"] else 100.0
|
||||
drxs = stats["rxs"]*(drxpct/100.0)
|
||||
dtxs = stats["txs"]*(dtxpct/100.0)
|
||||
|
||||
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:
|
||||
if "prxb" in stats and "ptxb" in stats and "prxs" in stats and "ptxs" in stats:
|
||||
prxb_str = "↓"+RNS.prettysize(stats["prxb"])
|
||||
ptxb_str = "↑"+RNS.prettysize(stats["ptxb"])
|
||||
strdiff = len(prxb_str)-len(ptxb_str)
|
||||
if strdiff > 0: ptxb_str += " "*strdiff
|
||||
elif strdiff < 0: prxb_str += " "*-strdiff
|
||||
|
||||
prxspct = min(100.0, (stats["prxs"] / stats["rxs"])*100.0) if stats["rxs"] and stats["prxs"] else 0.0
|
||||
ptxspct = min(100.0, (stats["ptxs"] / stats["txs"])*100.0) if stats["txs"] and stats["ptxs"] else 0.0
|
||||
|
||||
prxfstr = RNS.prettyfrequency(stats["prxf"])
|
||||
ptxfstr = RNS.prettyfrequency(stats["ptxf"])
|
||||
|
||||
prxstat = prxb_str+" "+RNS.prettyspeed(stats["prxs"])+f", {int(prxspct)}% of flow, {prxfstr}"
|
||||
ptxstat = ptxb_str+" "+RNS.prettyspeed(stats["ptxs"])+f", {int(ptxspct)}% of flow, {ptxfstr}"
|
||||
print(f"\n Path Rqs. : {ptxstat}\n {prxstat}")
|
||||
|
||||
if astats:
|
||||
if "arxb" in stats and "atxb" in stats and "arxs" in stats and "atxs" in stats:
|
||||
arxb_str = "↓"+RNS.prettysize(stats["arxb"])
|
||||
atxb_str = "↑"+RNS.prettysize(stats["atxb"])
|
||||
strdiff = len(arxb_str)-len(atxb_str)
|
||||
if strdiff > 0: atxb_str += " "*strdiff
|
||||
elif strdiff < 0: arxb_str += " "*-strdiff
|
||||
|
||||
arxspct = min(100.0, (stats["arxs"] / stats["rxs"])*100.0) if stats["rxs"] and stats["arxs"] else 0.0
|
||||
atxspct = min(100.0, (stats["atxs"] / stats["txs"])*100.0) if stats["txs"] and stats["atxs"] else 0.0
|
||||
|
||||
arxfstr = RNS.prettyfrequency(stats["arxf"])
|
||||
atxfstr = RNS.prettyfrequency(stats["atxf"])
|
||||
|
||||
arxstat = arxb_str+" "+RNS.prettyspeed(stats["arxs"])+f", {int(arxspct)}% of flow, {arxfstr}"
|
||||
atxstat = atxb_str+" "+RNS.prettyspeed(stats["atxs"])+f", {int(atxspct)}% of flow, {atxfstr}"
|
||||
print(f"\n Announces : {atxstat}\n {arxstat}")
|
||||
|
||||
|
||||
if queue_stats:
|
||||
tqdp = f", {stats['rxqtd']} dropped" if stats['rxqtd'] else ""
|
||||
dqdp = f", {stats['rxqdd']} dropped" if stats['rxqdd'] else ""
|
||||
aqdp = f", {stats['rxqad']} dropped" if stats['rxqad'] else ""
|
||||
pqdp = f", {stats['rxqpd']} dropped" if stats['rxqpd'] else ""
|
||||
ilqdp = f", {stats['rxqild']} dropped" if stats['rxqild'] else ""
|
||||
tqpress = f"{round(stats['tqpressure']*100.0, 1)}% total, {stats['rxqt']} pkts{tqdp}"
|
||||
dqpress = f"{round(stats['dqpressure']*100.0, 1)}% data, {stats['rxqd']} pkts{dqdp}"
|
||||
aqpress = f"{round(stats['aqpressure']*100.0, 1)}% announce, {stats['rxqa']} pkts{aqdp}"
|
||||
pqpress = f"{round(stats['pqpressure']*100.0, 1)}% path request, {stats['rxqp']} pkts{pqdp}"
|
||||
ilpress = f"{round(stats['ilqpressure']*100.0, 1)}% ingress limiter, {stats['rxqil']} pkts{ilqdp}"
|
||||
|
||||
print(f"\n Qu. Pressure : {tqpress}")
|
||||
print(f" {dqpress}")
|
||||
print(f" {aqpress}")
|
||||
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:
|
||||
@@ -699,8 +837,12 @@ def main(must_exit=True, rns_instance=None):
|
||||
parser.add_argument("-P", "--pr-stats", action="store_true", help="show path request stats", default=False)
|
||||
parser.add_argument("-l", "--link-stats", action="store_true", help="show link stats", default=False)
|
||||
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("-s", "--sort", action="store", help="sort interfaces by [rate, traffic, rx, tx, rxs, txs, announces, arx, atx, prx, ptx, held]", default=None, type=str)
|
||||
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("-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)
|
||||
@@ -737,7 +879,8 @@ def main(must_exit=True, rns_instance=None):
|
||||
program_setup(configdir = configarg, dispall = args.all, verbosity=args.verbose, name_filter=args.filter, json=args.json,
|
||||
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)
|
||||
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, pps=args.pps, profiling=args.profiling)
|
||||
|
||||
finally:
|
||||
sys.stdout = old_stdout
|
||||
@@ -754,7 +897,8 @@ def main(must_exit=True, rns_instance=None):
|
||||
program_setup(configdir = configarg, dispall = args.all, verbosity=args.verbose, name_filter=args.filter, json=args.json,
|
||||
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)
|
||||
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, pps=args.pps, profiling=args.profiling)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("")
|
||||
|
||||
@@ -347,7 +347,7 @@ def execute(configdir, identitypath = None, verbosity = 0, quietness = 0, detail
|
||||
|
||||
if not RNS.Transport.has_path(destination_hash):
|
||||
RNS.Transport.request_path(destination_hash)
|
||||
if not spin(until=lambda: RNS.Transport.has_path(destination_hash), msg="Path to "+RNS.prettyhexrep(destination_hash)+" requested", timeout=timeout):
|
||||
if not spin(until=lambda: RNS.Transport.has_path(destination_hash), msg="Path to "+RNS.prettyhexrep(destination_hash)+" requested", timeout=max(timeout, reticulum.get_medium_path_timeout())):
|
||||
print("Path not found")
|
||||
exit(242)
|
||||
|
||||
@@ -365,7 +365,7 @@ def execute(configdir, identitypath = None, verbosity = 0, quietness = 0, detail
|
||||
link = RNS.Link(listener_destination)
|
||||
link.did_identify = False
|
||||
|
||||
if not spin(until=lambda: link.status == RNS.Link.ACTIVE, msg="Establishing link with "+RNS.prettyhexrep(destination_hash), timeout=timeout):
|
||||
if not spin(until=lambda: link.status == RNS.Link.ACTIVE, msg="Establishing link with "+RNS.prettyhexrep(destination_hash), timeout=max(timeout, link.establishment_timeout)):
|
||||
print("Could not establish link with "+RNS.prettyhexrep(destination_hash))
|
||||
exit(243)
|
||||
|
||||
|
||||
+209
-88
@@ -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
@@ -1 +1 @@
|
||||
__version__ = "1.4.2"
|
||||
__version__ = "1.5.2"
|
||||
Vendored
+4
-2
@@ -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__"]))
|
||||
Vendored
+16
-217
@@ -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,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: 4e2f0f7390586c35b5c4b57cd1fc8b5b
|
||||
config: 3b25ffffee9a87e66aaacb67b195a708
|
||||
tags: 645f666f9bcd5a90fca523b33c5a78b7
|
||||
@@ -998,6 +998,9 @@ When ``discoverable`` is enabled, a variety of additional options become availab
|
||||
``discovery_name``
|
||||
A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.
|
||||
|
||||
``discovery_lxmf_address``
|
||||
An optional LXMF address for contacting the operator of this interface. The address will be displayed to users on remote systems when they view details for discovered interfaces. Useful for getting in touch with other operators to interconnect networks with and coordinating network coverage.
|
||||
|
||||
``announce_interval``
|
||||
The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).
|
||||
|
||||
@@ -1567,4 +1570,34 @@ but all the parameters are exposed for configuration if needed.
|
||||
|
||||
All of the above settings can be configured both as instance-wide defaults
|
||||
under the ``[reticulum]`` section of the configuration file, or on a per-
|
||||
interface basis under the relevant interface configuration section.
|
||||
interface basis under the relevant interface configuration section.
|
||||
|
||||
|
||||
Tuning Ingress Queues
|
||||
=====================
|
||||
|
||||
Reticulum uses separate, prioritized queues for processing inbound packets. The default four queues are drained in the following order:
|
||||
|
||||
1. Data and general traffic
|
||||
|
||||
2. Announces
|
||||
|
||||
3. Path requests
|
||||
|
||||
4. Ingress-limited traffic
|
||||
|
||||
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 ``1024``.
|
||||
|
||||
* | The ``qlen_in_announce`` option sets the maximum size of the announce
|
||||
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.
|
||||
@@ -337,8 +337,8 @@ Filter output to only show some interfaces:
|
||||
|
||||
.. code:: text
|
||||
|
||||
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A]
|
||||
[-l] [-t] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A] [-P] [-l]
|
||||
[-B] [-b] [-t] [-q] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
||||
|
||||
Reticulum Network Stack Status
|
||||
@@ -352,10 +352,14 @@ Filter output to only show some interfaces:
|
||||
--version show program's version number and exit
|
||||
-a, --all show all interfaces
|
||||
-A, --announce-stats show announce stats
|
||||
-P, --pr-stats show path request stats
|
||||
-l, --link-stats show link stats
|
||||
-B, --burst only show interfaces with active bursts
|
||||
-b, --blocked-ips show blocked IPs per interface
|
||||
-t, --totals display traffic totals
|
||||
-q, --queues display queue stats
|
||||
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
||||
announces, arx, atx, held]
|
||||
announces, arx, atx, prx, ptx, held]
|
||||
-r, --reverse reverse sorting
|
||||
-j, --json output in JSON format
|
||||
-R hash transport identity hash of remote instance to get status from
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const DOCUMENTATION_OPTIONS = {
|
||||
VERSION: '1.4.2',
|
||||
VERSION: '1.5.2',
|
||||
LANGUAGE: 'en',
|
||||
COLLAPSE_INDEX: false,
|
||||
BUILDER: 'html',
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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">
|
||||
@@ -365,10 +365,12 @@
|
||||
<li><a href="reference.html#RNS.Identity.decrypt">(RNS.Identity method)</a>
|
||||
</li>
|
||||
</ul></li>
|
||||
<li><a href="reference.html#RNS.Transport.deregister_announce_handler">deregister_announce_handler() (RNS.Transport static method)</a>
|
||||
<li><a href="reference.html#RNS.Reticulum.DEFAULT_PER_HOP_TIMEOUT">DEFAULT_PER_HOP_TIMEOUT (RNS.Reticulum attribute)</a>
|
||||
</li>
|
||||
</ul></td>
|
||||
<td style="width: 33%; vertical-align: top;"><ul>
|
||||
<li><a href="reference.html#RNS.Transport.deregister_announce_handler">deregister_announce_handler() (RNS.Transport static method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Destination.deregister_request_handler">deregister_request_handler() (RNS.Destination method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Destination">Destination (class in RNS)</a>
|
||||
@@ -434,12 +436,18 @@
|
||||
<li><a href="reference.html#RNS.Link.get_establishment_rate">get_establishment_rate() (RNS.Link method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Link.get_expected_rate">get_expected_rate() (RNS.Link method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Reticulum.get_first_hop_timeout">get_first_hop_timeout() (RNS.Reticulum method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Resource.get_hash">get_hash() (RNS.Resource method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Reticulum.get_instance">get_instance() (RNS.Reticulum static method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Reticulum.get_lowest_interface_bitrate">get_lowest_interface_bitrate() (RNS.Reticulum method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Link.get_mdu">get_mdu() (RNS.Link method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Reticulum.get_medium_path_timeout">get_medium_path_timeout() (RNS.Reticulum method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Link.get_mode">get_mode() (RNS.Link method)</a>
|
||||
</li>
|
||||
@@ -459,10 +467,10 @@
|
||||
<li><a href="reference.html#RNS.Resource.get_progress">(RNS.Resource method)</a>
|
||||
</li>
|
||||
</ul></li>
|
||||
<li><a href="reference.html#RNS.Identity.get_public_key">get_public_key() (RNS.Identity method)</a>
|
||||
</li>
|
||||
</ul></td>
|
||||
<td style="width: 33%; vertical-align: top;"><ul>
|
||||
<li><a href="reference.html#RNS.Identity.get_public_key">get_public_key() (RNS.Identity method)</a>
|
||||
</li>
|
||||
<li><a href="reference.html#RNS.Link.get_q">get_q() (RNS.Link method)</a>
|
||||
|
||||
<ul>
|
||||
@@ -848,7 +856,7 @@
|
||||
|
||||
</aside>
|
||||
</div>
|
||||
</div><script src="_static/documentation_options.js?v=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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">
|
||||
@@ -512,6 +512,7 @@ to participate in the development of Reticulum itself.</p>
|
||||
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#announce-rate-control">Announce Rate Control</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#new-destination-rate-limiting">New Destination Rate Limiting</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#path-request-burst-control">Path Request Burst Control</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="interfaces.html#tuning-ingress-queues">Tuning Ingress Queues</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="networks.html">Building Networks</a><ul>
|
||||
@@ -720,7 +721,7 @@ to participate in the development of Reticulum itself.</p>
|
||||
|
||||
</aside>
|
||||
</div>
|
||||
</div><script src="_static/documentation_options.js?v=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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">
|
||||
@@ -1151,6 +1151,8 @@ relevant regulation for your location, and to make decisions accordingly.</p>
|
||||
<dl class="simple">
|
||||
<dt><code class="docutils literal notranslate"><span class="pre">discovery_name</span></code></dt><dd><p>A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.</p>
|
||||
</dd>
|
||||
<dt><code class="docutils literal notranslate"><span class="pre">discovery_lxmf_address</span></code></dt><dd><p>An optional LXMF address for contacting the operator of this interface. The address will be displayed to users on remote systems when they view details for discovered interfaces. Useful for getting in touch with other operators to interconnect networks with and coordinating network coverage.</p>
|
||||
</dd>
|
||||
<dt><code class="docutils literal notranslate"><span class="pre">announce_interval</span></code></dt><dd><p>The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).</p>
|
||||
</dd>
|
||||
</dl>
|
||||
@@ -1768,6 +1770,44 @@ per second on a given interface.</div>
|
||||
under the <code class="docutils literal notranslate"><span class="pre">[reticulum]</span></code> section of the configuration file, or on a per-
|
||||
interface basis under the relevant interface configuration section.</p>
|
||||
</section>
|
||||
<section id="tuning-ingress-queues">
|
||||
<h2>Tuning Ingress Queues<a class="headerlink" href="#tuning-ingress-queues" title="Link to this heading">¶</a></h2>
|
||||
<p>Reticulum uses separate, prioritized queues for processing inbound packets. The default four queues are drained in the following order:</p>
|
||||
<blockquote>
|
||||
<div><ol class="arabic simple">
|
||||
<li><p>Data and general traffic</p></li>
|
||||
<li><p>Announces</p></li>
|
||||
<li><p>Path requests</p></li>
|
||||
<li><p>Ingress-limited traffic</p></li>
|
||||
</ol>
|
||||
</div></blockquote>
|
||||
<p>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 <code class="docutils literal notranslate"><span class="pre">[reticulum]</span></code> section of the config</p>
|
||||
<blockquote>
|
||||
<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">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">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">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">8</span></code>.</div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</div></blockquote>
|
||||
<p>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.</p>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
</article>
|
||||
@@ -1856,6 +1896,7 @@ interface basis under the relevant interface configuration section.</p>
|
||||
<li><a class="reference internal" href="#announce-rate-control">Announce Rate Control</a></li>
|
||||
<li><a class="reference internal" href="#new-destination-rate-limiting">New Destination Rate Limiting</a></li>
|
||||
<li><a class="reference internal" href="#path-request-burst-control">Path Request Burst Control</a></li>
|
||||
<li><a class="reference internal" href="#tuning-ingress-queues">Tuning Ingress Queues</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
@@ -1867,7 +1908,7 @@ interface basis under the relevant interface configuration section.</p>
|
||||
|
||||
</aside>
|
||||
</div>
|
||||
</div><script src="_static/documentation_options.js?v=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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.
@@ -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.4.2 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.4.2 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.4.2 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">
|
||||
@@ -335,10 +335,59 @@ alterations should be made on a per-interface basis instead.</p>
|
||||
to successfully establish links. Currently 5 bits per second.</p>
|
||||
</dd></dl>
|
||||
|
||||
<dl class="py attribute">
|
||||
<dt class="sig sig-object py" id="RNS.Reticulum.DEFAULT_PER_HOP_TIMEOUT">
|
||||
<span class="sig-name descname"><span class="pre">DEFAULT_PER_HOP_TIMEOUT</span></span><em class="property"><span class="w"> </span><span class="p"><span class="pre">=</span></span><span class="w"> </span><span class="pre">6</span></em><a class="headerlink" href="#RNS.Reticulum.DEFAULT_PER_HOP_TIMEOUT" title="Link to this definition">¶</a></dt>
|
||||
<dd><p>The default per-hop timeout value used in various timeout calculations.</p>
|
||||
</dd></dl>
|
||||
|
||||
<dl class="py method">
|
||||
<dt class="sig sig-object py" id="RNS.Reticulum.get_instance">
|
||||
<em class="property"><span class="k"><span class="pre">static</span></span><span class="w"> </span></em><span class="sig-name descname"><span class="pre">get_instance</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum.get_instance" title="Link to this definition">¶</a></dt>
|
||||
<dd><p>Return the currently running Reticulum instance</p>
|
||||
<dd><p>Returns the currently running Reticulum instance.</p>
|
||||
</dd></dl>
|
||||
|
||||
<dl class="py method">
|
||||
<dt class="sig sig-object py" id="RNS.Reticulum.get_first_hop_timeout">
|
||||
<span class="sig-name descname"><span class="pre">get_first_hop_timeout</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">destination</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum.get_first_hop_timeout" title="Link to this definition">¶</a></dt>
|
||||
<dd><p>Returns a best-effort estimate of a reasonable minimum
|
||||
<em>first-hop</em> timeout value for a given destination hash.
|
||||
If a path is known, this calculation takes the next-hop
|
||||
interface’s bitrate into account. If no path is currently
|
||||
known, returns <code class="docutils literal notranslate"><span class="pre">DEFAULT_PER_HOP_TIMEOUT</span></code>.</p>
|
||||
<dl class="field-list simple">
|
||||
<dt class="field-odd">Parameters<span class="colon">:</span></dt>
|
||||
<dd class="field-odd"><p><strong>destination</strong> – A destination hash, as <em>bytes</em>.</p>
|
||||
</dd>
|
||||
<dt class="field-even">Returns<span class="colon">:</span></dt>
|
||||
<dd class="field-even"><p>First-hop timeout, in seconds.</p>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd></dl>
|
||||
|
||||
<dl class="py method">
|
||||
<dt class="sig sig-object py" id="RNS.Reticulum.get_lowest_interface_bitrate">
|
||||
<span class="sig-name descname"><span class="pre">get_lowest_interface_bitrate</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum.get_lowest_interface_bitrate" title="Link to this definition">¶</a></dt>
|
||||
<dd><p>Returns the bitrate of the slowest currently online
|
||||
interface, or None if no online interface bitrate</p>
|
||||
<dl class="field-list simple">
|
||||
<dt class="field-odd">Returns<span class="colon">:</span></dt>
|
||||
<dd class="field-odd"><p>Lowest online interface bitrate in bits per second, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd></dl>
|
||||
|
||||
<dl class="py method">
|
||||
<dt class="sig sig-object py" id="RNS.Reticulum.get_medium_path_timeout">
|
||||
<span class="sig-name descname"><span class="pre">get_medium_path_timeout</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum.get_medium_path_timeout" title="Link to this definition">¶</a></dt>
|
||||
<dd><p>Returns an estimate of a reasonable minimum path request timeout covering
|
||||
a full round trip for an MTU on the slowest currently online interface
|
||||
plus per hop grace</p>
|
||||
<dl class="field-list simple">
|
||||
<dt class="field-odd">Returns<span class="colon">:</span></dt>
|
||||
<dd class="field-odd"><p>Timeout in seconds or 0 if it’s unknown.</p>
|
||||
</dd>
|
||||
</dl>
|
||||
</dd></dl>
|
||||
|
||||
<dl class="py method">
|
||||
@@ -2337,7 +2386,11 @@ will announce it.</p>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.LINK_MTU_DISCOVERY"><code class="docutils literal notranslate"><span class="pre">LINK_MTU_DISCOVERY</span></code></a></li>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.ANNOUNCE_CAP"><code class="docutils literal notranslate"><span class="pre">ANNOUNCE_CAP</span></code></a></li>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.MINIMUM_BITRATE"><code class="docutils literal notranslate"><span class="pre">MINIMUM_BITRATE</span></code></a></li>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.DEFAULT_PER_HOP_TIMEOUT"><code class="docutils literal notranslate"><span class="pre">DEFAULT_PER_HOP_TIMEOUT</span></code></a></li>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.get_instance"><code class="docutils literal notranslate"><span class="pre">get_instance()</span></code></a></li>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.get_first_hop_timeout"><code class="docutils literal notranslate"><span class="pre">get_first_hop_timeout()</span></code></a></li>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.get_lowest_interface_bitrate"><code class="docutils literal notranslate"><span class="pre">get_lowest_interface_bitrate()</span></code></a></li>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.get_medium_path_timeout"><code class="docutils literal notranslate"><span class="pre">get_medium_path_timeout()</span></code></a></li>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.should_use_implicit_proof"><code class="docutils literal notranslate"><span class="pre">should_use_implicit_proof()</span></code></a></li>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.transport_enabled"><code class="docutils literal notranslate"><span class="pre">transport_enabled()</span></code></a></li>
|
||||
<li><a class="reference internal" href="#RNS.Reticulum.link_mtu_discovery"><code class="docutils literal notranslate"><span class="pre">link_mtu_discovery()</span></code></a></li>
|
||||
@@ -2535,7 +2588,7 @@ will announce it.</p>
|
||||
|
||||
</aside>
|
||||
</div>
|
||||
</div><script src="_static/documentation_options.js?v=02f2166e"></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,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.4.2 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.4.2 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.4.2 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=02f2166e"></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 @@
|
||||
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
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
+11
-7
@@ -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.4.2 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.4.2 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.4.2 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">
|
||||
@@ -558,8 +558,8 @@ Reticulum Transport Instance <5245a8efe1788c6a1cd36144a270e13b> running
|
||||
</pre></div>
|
||||
</div>
|
||||
<p><strong>All Command-Line Options</strong></p>
|
||||
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A]
|
||||
[-l] [-t] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A] [-P] [-l]
|
||||
[-B] [-b] [-t] [-q] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
||||
|
||||
Reticulum Network Stack Status
|
||||
@@ -573,10 +573,14 @@ options:
|
||||
--version show program's version number and exit
|
||||
-a, --all show all interfaces
|
||||
-A, --announce-stats show announce stats
|
||||
-P, --pr-stats show path request stats
|
||||
-l, --link-stats show link stats
|
||||
-B, --burst only show interfaces with active bursts
|
||||
-b, --blocked-ips show blocked IPs per interface
|
||||
-t, --totals display traffic totals
|
||||
-q, --queues display queue stats
|
||||
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
||||
announces, arx, atx, held]
|
||||
announces, arx, atx, prx, ptx, held]
|
||||
-r, --reverse reverse sorting
|
||||
-j, --json output in JSON format
|
||||
-R hash transport identity hash of remote instance to get status from
|
||||
@@ -1640,7 +1644,7 @@ systemctl --user enable rnsd.service
|
||||
|
||||
</aside>
|
||||
</div>
|
||||
</div><script src="_static/documentation_options.js?v=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -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.4.2 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.4.2 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.4.2 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=02f2166e"></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>
|
||||
|
||||
@@ -183,6 +183,7 @@ to participate in the development of Reticulum itself.
|
||||
* [Announce Rate Control](interfaces.md#announce-rate-control)
|
||||
* [New Destination Rate Limiting](interfaces.md#new-destination-rate-limiting)
|
||||
* [Path Request Burst Control](interfaces.md#path-request-burst-control)
|
||||
* [Tuning Ingress Queues](interfaces.md#tuning-ingress-queues)
|
||||
* [Building Networks](networks.md)
|
||||
* [Concepts & Overview](networks.md#concepts-overview)
|
||||
* [Introductory Considerations](networks.md#introductory-considerations)
|
||||
|
||||
@@ -939,6 +939,9 @@ When `discoverable` is enabled, a variety of additional options become available
|
||||
`discovery_name`
|
||||
: A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.
|
||||
|
||||
`discovery_lxmf_address`
|
||||
: An optional LXMF address for contacting the operator of this interface. The address will be displayed to users on remote systems when they view details for discovered interfaces. Useful for getting in touch with other operators to interconnect networks with and coordinating network coverage.
|
||||
|
||||
`announce_interval`
|
||||
: The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).
|
||||
|
||||
@@ -1484,4 +1487,30 @@ but all the parameters are exposed for configuration if needed.
|
||||
|
||||
All of the above settings can be configured both as instance-wide defaults
|
||||
under the `[reticulum]` section of the configuration file, or on a per-
|
||||
interface basis under the relevant interface configuration section.
|
||||
interface basis under the relevant interface configuration section.
|
||||
|
||||
## Tuning Ingress Queues
|
||||
|
||||
Reticulum uses separate, prioritized queues for processing inbound packets. The default four queues are drained in the following order:
|
||||
|
||||
> 1. Data and general traffic
|
||||
> 2. Announces
|
||||
> 3. Path requests
|
||||
> 4. Ingress-limited traffic
|
||||
|
||||
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 `1024`.
|
||||
>
|
||||
> * The `qlen_in_announce` option sets the maximum size of the announce
|
||||
> 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.
|
||||
@@ -69,9 +69,44 @@ alterations should be made on a per-interface basis instead.
|
||||
Minimum bitrate required across a medium for Reticulum to be able
|
||||
to successfully establish links. Currently 5 bits per second.
|
||||
|
||||
#### `DEFAULT_PER_HOP_TIMEOUT = 6`
|
||||
|
||||
The default per-hop timeout value used in various timeout calculations.
|
||||
|
||||
#### `static get_instance()`
|
||||
|
||||
Return the currently running Reticulum instance
|
||||
Returns the currently running Reticulum instance.
|
||||
|
||||
#### `get_first_hop_timeout(destination)`
|
||||
|
||||
Returns a best-effort estimate of a reasonable minimum
|
||||
*first-hop* timeout value for a given destination hash.
|
||||
If a path is known, this calculation takes the next-hop
|
||||
interface’s bitrate into account. If no path is currently
|
||||
known, returns `DEFAULT_PER_HOP_TIMEOUT`.
|
||||
|
||||
* **Parameters:**
|
||||
**destination** – A destination hash, as *bytes*.
|
||||
|
||||
* **Returns:**
|
||||
First-hop timeout, in seconds.
|
||||
|
||||
#### `get_lowest_interface_bitrate()`
|
||||
|
||||
Returns the bitrate of the slowest currently online
|
||||
interface, or None if no online interface bitrate
|
||||
|
||||
* **Returns:**
|
||||
Lowest online interface bitrate in bits per second, or `None`.
|
||||
|
||||
#### `get_medium_path_timeout()`
|
||||
|
||||
Returns an estimate of a reasonable minimum path request timeout covering
|
||||
a full round trip for an MTU on the slowest currently online interface
|
||||
plus per hop grace
|
||||
|
||||
* **Returns:**
|
||||
Timeout in seconds or 0 if it’s unknown.
|
||||
|
||||
#### `static should_use_implicit_proof()`
|
||||
|
||||
|
||||
@@ -318,8 +318,8 @@ Reticulum Transport Instance <5245a8efe1788c6a1cd36144a270e13b> running
|
||||
**All Command-Line Options**
|
||||
|
||||
```text
|
||||
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A]
|
||||
[-l] [-t] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A] [-P] [-l]
|
||||
[-B] [-b] [-t] [-q] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
||||
|
||||
Reticulum Network Stack Status
|
||||
@@ -333,10 +333,14 @@ options:
|
||||
--version show program's version number and exit
|
||||
-a, --all show all interfaces
|
||||
-A, --announce-stats show announce stats
|
||||
-P, --pr-stats show path request stats
|
||||
-l, --link-stats show link stats
|
||||
-B, --burst only show interfaces with active bursts
|
||||
-b, --blocked-ips show blocked IPs per interface
|
||||
-t, --totals display traffic totals
|
||||
-q, --queues display queue stats
|
||||
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
||||
announces, arx, atx, held]
|
||||
announces, arx, atx, prx, ptx, held]
|
||||
-r, --reverse reverse sorting
|
||||
-j, --json output in JSON format
|
||||
-R hash transport identity hash of remote instance to get status from
|
||||
|
||||
@@ -998,6 +998,9 @@ When ``discoverable`` is enabled, a variety of additional options become availab
|
||||
``discovery_name``
|
||||
A human-readable name for the interface. This name will be displayed to users on remote systems when they list discovered interfaces. If not specified, the interface name (the section header) will be used.
|
||||
|
||||
``discovery_lxmf_address``
|
||||
An optional LXMF address for contacting the operator of this interface. The address will be displayed to users on remote systems when they view details for discovered interfaces. Useful for getting in touch with other operators to interconnect networks with and coordinating network coverage.
|
||||
|
||||
``announce_interval``
|
||||
The interval in minutes between successive discovery announces for this interface. Default is 360 minutes (6 hours). For stable, long-running infrastructure, higher intervals (12 to 22 hours) are usually sufficient and reduce network load. Minimum allowed value is 5 minutes (but expect to have your announces throttled if using intervals below one hour).
|
||||
|
||||
@@ -1567,4 +1570,34 @@ but all the parameters are exposed for configuration if needed.
|
||||
|
||||
All of the above settings can be configured both as instance-wide defaults
|
||||
under the ``[reticulum]`` section of the configuration file, or on a per-
|
||||
interface basis under the relevant interface configuration section.
|
||||
interface basis under the relevant interface configuration section.
|
||||
|
||||
|
||||
Tuning Ingress Queues
|
||||
=====================
|
||||
|
||||
Reticulum uses separate, prioritized queues for processing inbound packets. The default four queues are drained in the following order:
|
||||
|
||||
1. Data and general traffic
|
||||
|
||||
2. Announces
|
||||
|
||||
3. Path requests
|
||||
|
||||
4. Ingress-limited traffic
|
||||
|
||||
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 ``1024``.
|
||||
|
||||
* | The ``qlen_in_announce`` option sets the maximum size of the announce
|
||||
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.
|
||||
@@ -337,8 +337,8 @@ Filter output to only show some interfaces:
|
||||
|
||||
.. code:: text
|
||||
|
||||
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A]
|
||||
[-l] [-t] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||
usage: rnstatus [-h] [--config CONFIG] [--version] [-a] [-A] [-P] [-l]
|
||||
[-B] [-b] [-t] [-q] [-s SORT] [-r] [-j] [-R hash] [-i path]
|
||||
[-w seconds] [-d] [-D] [-m] [-I seconds] [-v] [filter]
|
||||
|
||||
Reticulum Network Stack Status
|
||||
@@ -352,10 +352,14 @@ Filter output to only show some interfaces:
|
||||
--version show program's version number and exit
|
||||
-a, --all show all interfaces
|
||||
-A, --announce-stats show announce stats
|
||||
-P, --pr-stats show path request stats
|
||||
-l, --link-stats show link stats
|
||||
-B, --burst only show interfaces with active bursts
|
||||
-b, --blocked-ips show blocked IPs per interface
|
||||
-t, --totals display traffic totals
|
||||
-q, --queues display queue stats
|
||||
-s, --sort SORT sort interfaces by [rate, traffic, rx, tx, rxs, txs,
|
||||
announces, arx, atx, held]
|
||||
announces, arx, atx, prx, ptx, held]
|
||||
-r, --reverse reverse sorting
|
||||
-j, --json output in JSON format
|
||||
-R hash transport identity hash of remote instance to get status from
|
||||
|
||||
@@ -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
@@ -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
@@ -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)
|
||||
@@ -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
@@ -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
@@ -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
@@ -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)
|
||||
@@ -145,6 +145,34 @@ class TestIdentity(unittest.TestCase):
|
||||
print("Sign/validate 16KB chunks: "+self.size_str(b/t, "b")+"ps")
|
||||
|
||||
|
||||
def test_3_timings(self):
|
||||
import random
|
||||
random.seed(618736)
|
||||
print("")
|
||||
blobs = []
|
||||
times = []
|
||||
t = RNS.Cryptography.Token(key=random.randbytes(64))
|
||||
for n in range(0, 1000): blobs.append(random.randbytes(64))
|
||||
|
||||
for a in blobs:
|
||||
for b in blobs:
|
||||
st = time.time()
|
||||
res = t.verify_hmac(b)
|
||||
d = time.time()-st
|
||||
times.append(d)
|
||||
|
||||
import statistics
|
||||
tmin = min(times)*1000000
|
||||
tmax = max(times)*1000000
|
||||
tmean = (sum(times)/len(times))*1000000
|
||||
tmed = statistics.median(times)*1000000
|
||||
tmdev = tmax - tmin
|
||||
mpct = (tmax/tmed)*100
|
||||
print(" HMAC timings:")
|
||||
print(" µs min/avg/med/max/mdev: "+str(round(tmin, 3))+"/"+str(round(tmean, 3))+"/"+str(round(tmed, 3))+"/"+str(round(tmax, 3))+"/"+str(round(tmdev, 3)))
|
||||
print(" Max deviation from median: "+str(round(mpct, 1))+"%")
|
||||
print()
|
||||
|
||||
def test_2_encrypt(self):
|
||||
print("")
|
||||
|
||||
|
||||
+296
@@ -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)
|
||||
+22
-25
@@ -13,7 +13,6 @@ import RNS
|
||||
import os
|
||||
from tests.channel import MessageTest
|
||||
from RNS.Channel import MessageBase
|
||||
from RNS.Buffer import StreamDataMessage
|
||||
from RNS.Interfaces.LocalInterface import LocalClientInterface
|
||||
from math import ceil
|
||||
|
||||
@@ -27,7 +26,9 @@ fixed_keys = [
|
||||
("08bb35f92b06a0832991165a0d9b4fd91af7b7765ce4572aa6222070b11b767092b61b0fd18b3a59cae6deb9db6d4bfb1c7fcfe076cfd66eea7ddd5f877543b9", "d13712efc45ef87674fb5ac26c37c912"),
|
||||
]
|
||||
|
||||
BUFFER_TEST_TARGET = 32000
|
||||
BUFFER_TEST_TARGET = 256000
|
||||
BUFFER_TEST_TARGET_SLOW = 1800
|
||||
SLOW_TEST_MARKER = b"@SLOW_TEST_MARKER"
|
||||
LINK_UP_WAIT = 0.050
|
||||
|
||||
def targets_job(caller):
|
||||
@@ -734,23 +735,16 @@ class TestLink(unittest.TestCase):
|
||||
# 1000))
|
||||
|
||||
if local_interface.bitrate < 1000:
|
||||
target_bytes = 3000
|
||||
target_bytes = BUFFER_TEST_TARGET_SLOW-len(SLOW_TEST_MARKER)
|
||||
message = SLOW_TEST_MARKER
|
||||
else:
|
||||
target_bytes = BUFFER_TEST_TARGET
|
||||
message = b""
|
||||
|
||||
random.seed(154889)
|
||||
message = random.randbytes(target_bytes)
|
||||
message += random.randbytes(target_bytes)
|
||||
buffer_read_target = len(message)
|
||||
|
||||
# the return message will have an appendage string " back at you"
|
||||
# for every StreamDataMessage that arrives. To verify, we need
|
||||
# to insert that string every MAX_DATA_LEN and also at the end.
|
||||
expected_rx_message = b""
|
||||
for i in range(0, len(message)):
|
||||
if i > 0 and (i % StreamDataMessage.MAX_DATA_LEN) == 0:
|
||||
expected_rx_message += " back at you".encode("utf-8")
|
||||
expected_rx_message += bytes([message[i]])
|
||||
expected_rx_message += " back at you".encode("utf-8")
|
||||
expected_rx_message = message + " back at you".encode("utf-8")
|
||||
|
||||
# since the segments will be received at max length for a
|
||||
# StreamDataMessage, the appended text will end up in a
|
||||
@@ -760,7 +754,7 @@ class TestLink(unittest.TestCase):
|
||||
buffer.write(message)
|
||||
buffer.flush()
|
||||
|
||||
timeout = time.time() + 4
|
||||
timeout = time.time() + 2.5
|
||||
while not time.time() > timeout:
|
||||
time.sleep(1)
|
||||
print(f"Received {len(received)} chunks so far")
|
||||
@@ -864,28 +858,31 @@ def targets(yp=False):
|
||||
|
||||
response_data = []
|
||||
def handle_buffer(ready_bytes: int):
|
||||
global buffer_read_len, BUFFER_TEST_TARGET
|
||||
global buffer_read_len, BUFFER_TEST_TARGET, BUFFER_TEST_TARGET_SLOW
|
||||
data = buffer.read(ready_bytes)
|
||||
buffer_read_len += len(data)
|
||||
response_data.append(data)
|
||||
|
||||
if SLOW_TEST_MARKER in data:
|
||||
BUFFER_TEST_TARGET = BUFFER_TEST_TARGET_SLOW
|
||||
|
||||
if data == "Hi there".encode("utf-8"):
|
||||
RNS.log("Sending response")
|
||||
for data in response_data:
|
||||
buffer.write(data + " back at you".encode("utf-8"))
|
||||
buffer.flush()
|
||||
buffer_read_len = 0
|
||||
buffer.write(b"".join(response_data) + " back at you".encode("utf-8"))
|
||||
buffer.flush()
|
||||
response_data.clear()
|
||||
buffer_read_len = 0
|
||||
|
||||
if buffer_read_len == BUFFER_TEST_TARGET:
|
||||
RNS.log("Sending response")
|
||||
for data in response_data:
|
||||
buffer.write(data + " back at you".encode("utf-8"))
|
||||
buffer.flush()
|
||||
buffer_read_len = 0
|
||||
buffer.write(b"".join(response_data) + " back at you".encode("utf-8"))
|
||||
buffer.flush()
|
||||
response_data.clear()
|
||||
buffer_read_len = 0
|
||||
|
||||
buffer = RNS.Buffer.create_bidirectional_buffer(0, 0, channel, handle_buffer)
|
||||
|
||||
m_rns = RNS.Reticulum("./tests/rnsconfig", logdest=RNS.LOG_FILE, loglevel=RNS.LOG_EXTREME)
|
||||
m_rns = RNS.Reticulum("./tests/rnsconfig", logdest=RNS.LOG_FILE)
|
||||
id1 = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[0][0]))
|
||||
d1 = RNS.Destination(id1, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "link", "establish")
|
||||
d1.set_proof_strategy(RNS.Destination.PROVE_ALL)
|
||||
|
||||
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user