Reticulum/RNS/__init__.py

623 lines
23 KiB
Python
Raw Normal View History

2025-04-15 20:19:33 +02:00
# Reticulum License
2022-04-01 17:18:18 +02:00
#
2025-04-15 20:19:33 +02:00
# Copyright (c) 2016-2025 Mark Qvist
2022-04-01 17:18:18 +02:00
#
# 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:
#
2025-04-15 20:19:33 +02:00
# - 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.
2022-04-01 17:18:18 +02:00
#
# 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.
2016-06-03 19:02:02 +02:00
import os
2018-04-16 22:04:28 +02:00
import sys
2016-06-03 19:02:02 +02:00
import glob
2018-03-19 16:39:08 +01:00
import time
2025-01-12 18:51:27 +01:00
import datetime
import random
import threading
2016-06-03 19:02:02 +02:00
from collections import deque
from threading import Lock, Condition
2021-08-19 14:10:37 +02:00
from ._version import __version__
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"))]))
2018-03-19 16:39:08 +01:00
2025-04-08 15:23:44 +02:00
import importlib.util
if importlib.util.find_spec("cython"): import cython; compiled = cython.compiled
else: compiled = False
2025-02-23 15:18:12 +01:00
LOG_NONE = -1
2018-03-19 16:39:08 +01:00
LOG_CRITICAL = 0
LOG_ERROR = 1
LOG_WARNING = 2
LOG_NOTICE = 3
LOG_INFO = 4
LOG_VERBOSE = 5
LOG_DEBUG = 6
2026-07-18 15:07:06 +02:00
LOG_PATHING = 7
LOG_EXTREME = 8
2018-03-19 16:39:08 +01:00
2020-08-13 12:15:56 +02:00
LOG_STDOUT = 0x91
2018-03-19 16:39:08 +01:00
LOG_FILE = 0x92
LOG_CALLBACK = 0x93
2018-03-19 16:39:08 +01:00
LOG_MAXSIZE = 30*1024*1024
LOG_MAXROT = 9
2021-10-08 19:23:10 +02:00
2022-11-01 20:26:55 +01:00
loglevel = LOG_NOTICE
logfile = None
logdest = LOG_STDOUT
logcall = None
2026-05-28 16:52:39 +02:00
logtimestamps = True
2022-11-01 20:26:55 +01:00
logtimefmt = "%Y-%m-%d %H:%M:%S"
2025-01-12 18:51:27 +01:00
logtimefmt_p = "%H:%M:%S.%f"
2022-11-01 20:26:55 +01:00
compact_log_fmt = False
2018-03-19 16:39:08 +01:00
instance_random = random.Random()
instance_random.seed(os.urandom(10))
_always_override_destination = False
2018-03-19 16:39:08 +01:00
def loglevelname(level):
2026-05-11 23:31:25 +02:00
if (level == LOG_CRITICAL): return "[Critical]"
if (level == LOG_ERROR): return "[Error] "
if (level == LOG_WARNING): return "[Warning] "
if (level == LOG_NOTICE): return "[Notice] "
if (level == LOG_INFO): return "[Info] "
if (level == LOG_VERBOSE): return "[Verbose] "
if (level == LOG_DEBUG): return "[Debug] "
2026-07-18 15:07:06 +02:00
if (level == LOG_PATHING): return "[Pathing] "
2026-05-11 23:31:25 +02:00
if (level == LOG_EXTREME): return "[Extra] "
2020-08-13 12:15:56 +02:00
return "Unknown"
2018-03-19 16:39:08 +01:00
2021-08-19 14:10:37 +02:00
def version():
return __version__
2021-12-01 11:40:44 +01:00
def host_os():
from .vendor.platformutils import get_platform
return get_platform()
def timestamp_str(time_s):
timestamp = time.localtime(time_s)
return time.strftime(logtimefmt, timestamp)
2025-01-12 18:51:27 +01:00
def precise_timestamp_str(time_s):
return datetime.datetime.now().strftime(logtimefmt_p)[:-3]
_log_thread = None
_log_thread_lock = Lock()
_log_queue = deque()
_log_cond = Condition()
def _ensure_log_thread():
global _log_thread
if _log_thread is None or not _log_thread.is_alive():
_log_thread = threading.Thread(target=_log_job, daemon=True)
_log_thread.start()
2026-05-06 01:03:43 +02:00
def sl(level=3): return loglevel >= level
2025-01-12 18:51:27 +01:00
def log(msg, level=3, _override_destination = False, pt=False):
global compact_log_fmt
2025-02-23 15:18:12 +01:00
if loglevel == LOG_NONE: return
_ensure_log_thread()
msg = str(msg)
2020-08-13 12:15:56 +02:00
if loglevel >= level:
with _log_cond:
if pt: logstring = "["+precise_timestamp_str(time.time())+"] "+loglevelname(level)+" "+msg
else:
if not compact_log_fmt: logstring = ("["+timestamp_str(time.time())+"] " if logtimestamps else "")+loglevelname(level)+" "+msg
else: logstring = ("["+timestamp_str(time.time())+"] " if logtimestamps else "")+msg
_log_queue.append((logstring, level, _override_destination))
_log_cond.notify()
def _log_job():
global _always_override_destination
if not _log_thread_lock.acquire(blocking=False): return
try:
file = None
if (logdest == LOG_FILE and logfile != None):
try:
file = open(logfile, "a", buffering=1)
except Exception as e:
_always_override_destination = True
log("Exception occurred while opening log file: "+str(e), LOG_CRITICAL)
log("Dumping future log events to console!", LOG_CRITICAL)
while True:
with _log_cond:
try:
logstring, level, _override_destination = _log_queue.popleft()
except IndexError as e:
_log_cond.wait()
continue
if (logdest == LOG_STDOUT or _always_override_destination or _override_destination):
if not threading.main_thread().is_alive(): return
else:
try: print(logstring)
except: pass
elif (logdest == LOG_FILE and logfile != None and file != None):
try:
file.write(logstring+"\n")
if os.path.getsize(logfile) > LOG_MAXSIZE:
file.close()
for i in range(LOG_MAXROT, 0, -1):
oldfile = f"{logfile}.{i}"
if os.path.isfile(oldfile):
if i == LOG_MAXROT:
os.unlink(oldfile)
else:
rotfile = f"{logfile}.{i+1}"
os.rename(oldfile, rotfile)
rotfile = f"{logfile}.1"
os.rename(logfile, rotfile)
file = open(logfile, "a", buffering=1)
except Exception as e:
_always_override_destination = True
log("Exception occurred while writing log message to log file: "+str(e), LOG_CRITICAL)
log("Dumping future log events to console!", LOG_CRITICAL)
log(msg, level)
elif logdest == LOG_CALLBACK:
try: logcall(logstring)
except Exception as e:
_always_override_destination = True
log("Exception occurred while calling external log handler: "+str(e), LOG_CRITICAL)
log("Dumping future log events to console!", LOG_CRITICAL)
log(msg, level)
finally:
if file is not None: file.close()
_log_thread_lock.release()
2018-03-19 18:11:50 +01:00
def rand():
result = instance_random.random()
2020-08-13 12:15:56 +02:00
return result
2024-01-14 18:56:20 +01:00
def trace_exception(e):
import traceback
exception_info = "".join(traceback.TracebackException.from_exception(e).format())
log(f"An unhandled {str(type(e))} exception occurred: {str(e)}", LOG_ERROR)
log(exception_info, LOG_ERROR)
2018-03-19 18:11:50 +01:00
def hexrep(data, delimit=True):
2026-05-11 23:31:25 +02:00
try: iter(data)
except TypeError: data = [data]
2020-08-13 12:15:56 +02:00
delimiter = ":"
2026-05-11 23:31:25 +02:00
if not delimit: delimiter = ""
2020-08-13 12:15:56 +02:00
hexrep = delimiter.join("{:02x}".format(c) for c in data)
return hexrep
2018-03-20 12:32:41 +01:00
def prettyhexrep(data):
2020-08-13 12:15:56 +02:00
delimiter = ""
hexrep = "<"+delimiter.join("{:02x}".format(c) for c in data)+">"
return hexrep
2018-04-16 22:04:28 +02:00
def prettyspeed(num, suffix="b"):
return prettysize(num/8, suffix=suffix)+"ps"
2022-06-09 14:46:36 +02:00
def prettysize(num, suffix='B'):
units = ['','K','M','G','T','P','E','Z']
last_unit = 'Y'
if suffix == 'b':
num *= 8
units = ['','K','M','G','T','P','E','Z']
last_unit = 'Y'
for unit in units:
if abs(num) < 1000.0:
2026-05-11 23:31:25 +02:00
if unit == "": return "%.0f %s%s" % (num, unit, suffix)
else: return "%.2f %s%s" % (num, unit, suffix)
2022-06-09 14:46:36 +02:00
num /= 1000.0
return "%.2f%s%s" % (num, last_unit, suffix)
def prettyfrequency(hz, suffix="Hz", d=2, lpf=False):
if hz == 0: return "0 Hz"
if not lpf: num = hz*1e6
else: num = hz
if not lpf: units = ["µ", "m", "", "K","M","G","T","P","E","Z"]
else: units = ["", "K","M","G","T","P","E","Z"]
last_unit = "Y"
for unit in units:
if abs(num) < 1000.0:
2026-05-09 00:50:19 +02:00
if d == 2: return "%.2f %s%s" % (num, unit, suffix)
else: return "%s %s%s" % (str(round(num,d)), unit, suffix)
num /= 1000.0
return "%.2f%s%s" % (num, last_unit, suffix)
2023-10-24 13:24:40 +02:00
def prettydistance(m, suffix="m"):
num = m*1e6
units = ["µ", "m", "c", ""]
last_unit = "K"
2023-10-24 01:41:49 +02:00
for unit in units:
2023-10-24 13:24:40 +02:00
divisor = 1000.0
if unit == "m": divisor = 10
if unit == "c": divisor = 100
2026-05-11 23:31:25 +02:00
if abs(num) < divisor: return "%.2f %s%s" % (num, unit, suffix)
2023-10-24 13:24:40 +02:00
num /= divisor
2023-10-24 01:41:49 +02:00
2023-10-24 13:24:40 +02:00
return "%.2f %s%s" % (num, last_unit, suffix)
2023-10-24 01:41:49 +02:00
def prettytime(time, verbose=False, compact=False):
neg = False
if time < 0:
time = abs(time)
neg = True
2022-07-02 13:12:54 +02:00
days = int(time // (24 * 3600))
time = time % (24 * 3600)
hours = int(time // 3600)
time %= 3600
minutes = int(time // 60)
time %= 60
2026-05-11 23:31:25 +02:00
if compact: seconds = int(time)
else: seconds = round(time, 2)
2022-07-02 13:12:54 +02:00
ss = "" if seconds == 1 else "s"
sm = "" if minutes == 1 else "s"
sh = "" if hours == 1 else "s"
sd = "" if days == 1 else "s"
2023-10-24 01:41:49 +02:00
displayed = 0
2022-07-02 13:12:54 +02:00
components = []
2023-10-24 01:41:49 +02:00
if days > 0 and ((not compact) or displayed < 2):
2022-07-02 13:12:54 +02:00
components.append(str(days)+" day"+sd if verbose else str(days)+"d")
2023-10-24 01:41:49 +02:00
displayed += 1
2022-07-02 13:12:54 +02:00
2023-10-24 01:41:49 +02:00
if hours > 0 and ((not compact) or displayed < 2):
2022-07-02 13:12:54 +02:00
components.append(str(hours)+" hour"+sh if verbose else str(hours)+"h")
2023-10-24 01:41:49 +02:00
displayed += 1
2022-07-02 13:12:54 +02:00
2023-10-24 01:41:49 +02:00
if minutes > 0 and ((not compact) or displayed < 2):
2022-07-02 13:12:54 +02:00
components.append(str(minutes)+" minute"+sm if verbose else str(minutes)+"m")
2023-10-24 01:41:49 +02:00
displayed += 1
2022-07-02 13:12:54 +02:00
2023-10-24 01:41:49 +02:00
if seconds > 0 and ((not compact) or displayed < 2):
2022-07-02 13:12:54 +02:00
components.append(str(seconds)+" second"+ss if verbose else str(seconds)+"s")
2023-10-24 01:41:49 +02:00
displayed += 1
2022-07-02 13:12:54 +02:00
i = 0
tstr = ""
for c in components:
i += 1
2026-05-11 23:31:25 +02:00
if i == 1: pass
elif i < len(components): tstr += ", "
elif i == len(components): tstr += " and "
2022-07-02 13:12:54 +02:00
tstr += c
2026-05-11 23:31:25 +02:00
if tstr == "": return "0s"
2022-11-23 17:15:46 +01:00
else:
2026-05-11 23:31:25 +02:00
if not neg: return tstr
else: return f"-{tstr}"
2022-07-02 13:12:54 +02:00
2024-09-15 15:12:53 +02:00
def prettyshorttime(time, verbose=False, compact=False):
neg = False
2024-09-15 15:12:53 +02:00
time = time*1e6
if time < 0:
time = abs(time)
neg = True
2024-09-15 15:12:53 +02:00
seconds = int(time // 1e6); time %= 1e6
milliseconds = int(time // 1e3); time %= 1e3
2026-05-11 23:31:25 +02:00
if compact: microseconds = int(time)
else: microseconds = round(time, 2)
2024-09-15 15:12:53 +02:00
ss = "" if seconds == 1 else "s"
sms = "" if milliseconds == 1 else "s"
sus = "" if microseconds == 1 else "s"
displayed = 0
components = []
if seconds > 0 and ((not compact) or displayed < 2):
components.append(str(seconds)+" second"+ss if verbose else str(seconds)+"s")
displayed += 1
if milliseconds > 0 and ((not compact) or displayed < 2):
components.append(str(milliseconds)+" millisecond"+sms if verbose else str(milliseconds)+"ms")
displayed += 1
if microseconds > 0 and ((not compact) or displayed < 2):
components.append(str(microseconds)+" microsecond"+sus if verbose else str(microseconds)+"µs")
displayed += 1
i = 0
tstr = ""
for c in components:
i += 1
2026-05-11 23:31:25 +02:00
if i == 1: pass
elif i < len(components): tstr += ", "
elif i == len(components): tstr += " and "
2024-09-15 15:12:53 +02:00
tstr += c
2026-05-11 23:31:25 +02:00
if tstr == "": return "0us"
2024-09-15 15:12:53 +02:00
else:
2026-05-11 23:31:25 +02:00
if not neg: return tstr
else: return f"-{tstr}"
2024-09-15 15:12:53 +02:00
2022-06-30 14:02:57 +02:00
def phyparams():
print("Required Physical Layer MTU : "+str(Reticulum.MTU)+" bytes")
print("Plaintext Packet MDU : "+str(Packet.PLAIN_MDU)+" bytes")
print("Encrypted Packet MDU : "+str(Packet.ENCRYPTED_MDU)+" bytes")
print("Link Curve : "+str(Link.CURVE))
2023-03-04 18:37:28 +01:00
print("Link Packet MDU : "+str(Link.MDU)+" bytes")
2022-06-30 14:02:57 +02:00
print("Link Public Key Size : "+str(Link.ECPUBSIZE*8)+" bits")
print("Link Private Key Size : "+str(Link.KEYSIZE*8)+" bits")
2026-05-11 23:31:25 +02:00
def panic(): os._exit(255)
exit_called = False
2025-02-23 15:18:12 +01:00
def exit(code=0):
global exit_called
if not exit_called:
exit_called = True
Reticulum.exit_handler()
2025-02-23 15:18:12 +01:00
os._exit(code)
2024-09-15 15:12:53 +02:00
2026-05-05 23:42:00 +02:00
def _detach_stdout():
sys.stdout = open(os.devnull, "w")
sys.stderr = open(os.devnull, "w")
2025-01-10 20:07:17 +01:00
class Profiler:
2025-01-12 17:51:02 +01:00
_ran = False
2025-01-10 21:37:45 +01:00
profilers = {}
2025-01-10 20:07:17 +01:00
tags = {}
2024-09-15 15:12:53 +02:00
2025-01-10 21:37:45 +01:00
@staticmethod
def get_profiler(tag=None, super_tag=None):
2026-05-11 23:31:25 +02:00
if tag in Profiler.profilers: return Profiler.profilers[tag]
2025-01-10 21:37:45 +01:00
else:
profiler = Profiler(tag, super_tag)
Profiler.profilers[tag] = profiler
return profiler
2025-01-10 20:07:17 +01:00
def __init__(self, tag=None, super_tag=None):
2025-01-10 21:37:45 +01:00
self.paused = False
self.pause_time = 0
self.pause_started = None
2025-01-10 20:07:17 +01:00
self.tag = tag
self.super_tag = super_tag
2026-05-11 23:31:25 +02:00
2025-01-10 21:37:45 +01:00
if self.super_tag in Profiler.profilers:
self.super_profiler = Profiler.profilers[self.super_tag]
self.pause_super = self.super_profiler.pause
self.resume_super = self.super_profiler.resume
2026-05-11 23:31:25 +02:00
2025-01-10 21:37:45 +01:00
else:
2026-05-11 23:31:25 +02:00
def noop(self=None): pass
2025-01-10 21:37:45 +01:00
self.super_profiler = None
self.pause_super = noop
self.resume_super = noop
2024-09-15 15:12:53 +02:00
2025-01-10 20:07:17 +01:00
def __enter__(self):
2025-01-10 21:37:45 +01:00
self.pause_super()
2025-01-10 20:07:17 +01:00
tag = self.tag
super_tag = self.super_tag
thread_ident = threading.get_ident()
2026-05-11 23:31:25 +02:00
if not tag in Profiler.tags: Profiler.tags[tag] = {"threads": {}, "super": super_tag}
2025-01-10 20:07:17 +01:00
if not thread_ident in Profiler.tags[tag]["threads"]:
Profiler.tags[tag]["threads"][thread_ident] = {"current_start": None, "captures": []}
2024-09-15 15:12:53 +02:00
2025-01-10 20:07:17 +01:00
Profiler.tags[tag]["threads"][thread_ident]["current_start"] = time.perf_counter()
2025-01-10 21:37:45 +01:00
self.resume_super()
2024-09-15 15:12:53 +02:00
2025-01-10 20:07:17 +01:00
def __exit__(self, exc_type, exc_value, traceback):
2025-01-10 21:37:45 +01:00
self.pause_super()
2025-01-10 20:07:17 +01:00
tag = self.tag
super_tag = self.super_tag
2025-01-10 21:37:45 +01:00
end = time.perf_counter() - self.pause_time
self.pause_time = 0
2025-01-10 20:07:17 +01:00
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)
2025-01-12 17:51:02 +01:00
if not Profiler._ran:
Profiler._ran = True
2025-01-10 21:37:45 +01:00
self.resume_super()
def pause(self, pause_started=None):
if not self.paused:
self.paused = True
self.pause_started = pause_started or time.perf_counter()
self.pause_super(self.pause_started)
def resume(self):
if self.paused:
self.pause_time += time.perf_counter() - self.pause_started
self.paused = False
self.resume_super()
2025-01-10 20:07:17 +01:00
@staticmethod
2026-05-11 23:31:25 +02:00
def ran(): return Profiler._ran
2025-01-10 20:07:17 +01:00
@staticmethod
def results():
from statistics import mean, median, stdev
results = {}
2024-09-15 15:12:53 +02:00
for tag in sorted(Profiler.tags):
2025-01-10 20:07:17 +01:00
tag_captures = []
tag_entry = Profiler.tags[tag]
2024-09-15 15:12:53 +02:00
2025-01-10 20:07:17 +01:00
for thread_ident in tag_entry["threads"]:
thread_entry = tag_entry["threads"][thread_ident]
thread_captures = thread_entry["captures"]
sample_count = len(thread_captures)
2025-01-12 17:51:02 +01:00
if sample_count > 1:
2026-05-11 23:31:25 +02:00
thread_results = { "count": sample_count,
"mean": mean(thread_captures),
"median": median(thread_captures),
"stdev": stdev(thread_captures) }
2025-01-12 17:51:02 +01:00
elif sample_count == 1:
2026-05-11 23:31:25 +02:00
thread_results = { "count": sample_count,
"mean": mean(thread_captures),
"median": median(thread_captures),
"stdev": None }
2025-01-10 20:07:17 +01:00
tag_captures.extend(thread_captures)
sample_count = len(tag_captures)
2025-01-12 17:51:02 +01:00
if sample_count > 1:
2026-05-11 23:31:25 +02:00
tag_results = { "name": tag,
"super": tag_entry["super"],
"count": len(tag_captures),
"mean": mean(tag_captures),
"median": median(tag_captures),
"stdev": stdev(tag_captures) }
2025-01-12 17:51:02 +01:00
elif sample_count == 1:
2026-05-11 23:31:25 +02:00
tag_results = { "name": tag,
"super": tag_entry["super"],
"count": len(tag_captures),
"mean": mean(tag_captures),
"median": median(tag_captures),
"stdev": None }
2024-09-15 15:12:53 +02:00
2025-01-12 17:51:02 +01:00
results[tag] = tag_results
2025-01-10 20:07:17 +01:00
return results
@staticmethod
def format_results(results):
2025-01-10 20:07:17 +01:00
def print_results_recursive(tag, results, level=0):
results_str = print_tag_results(tag, level+1) + "\n"
2024-09-15 15:12:53 +02:00
2025-01-10 20:07:17 +01:00
for tag_name in results:
sub_tag = results[tag_name]
if sub_tag["super"] == tag["name"]:
results_str += print_results_recursive(sub_tag, results, level=level+1)
return results_str
2024-09-15 15:12:53 +02:00
2025-01-10 20:07:17 +01:00
def print_tag_results(tag, level):
ind = " "*level
name = tag["name"]; count = tag["count"]
mean = tag["mean"]; median = tag["median"]; stdev = tag["stdev"]
results_str = f" {ind}{name}\n"
results_str += f" {ind} Samples : {count}\n"
2025-01-12 17:51:02 +01:00
if stdev != None:
results_str += f" {ind} Mean : {prettyshorttime(mean)}\n"
results_str += f" {ind} Median : {prettyshorttime(median)}\n"
results_str += f" {ind} St.dev. : {prettyshorttime(stdev)}\n"
results_str += f" {ind} Total : {prettyshorttime(mean*count)}\n"
return results_str
2024-09-15 16:46:52 +02:00
results_str = ""
for tag_name in results:
tag = results[tag_name]
if tag["super"] == None:
results_str += print_results_recursive(tag, results)
return results_str
2025-01-10 21:37:45 +01:00
2026-04-28 14:38:32 +02:00
profile = Profiler.get_profiler
2026-05-11 23:22:13 +02:00
# The base-256 table is likely to change. Currently, it is just
# experimental, so don't count on it too much just yet.
2026-04-28 14:38:32 +02:00
b256 = [
# 0 1 2 3 4 5 6 7 8 9 A B C D F F
"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p", # 0x0 Latin & numerals
"q","r","s","t","u","v","x","y","z","æ","ø","0","1","2","3","4", # 0x1 Latin & numerals
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P", # 0x2 Latin & numerals
"Q","R","S","T","U","W","X","Y","Z","Æ","Ø","5","6","7","8","9", # 0x3 Latin & numerals
"α","β","γ","δ","ε","ζ","η","θ","ι","κ","λ","μ","ν","ξ","π","ρ", # 0x4 Greek
"σ","τ","φ","χ","ψ","ω","Γ","Δ","Θ","Λ","Ξ","Π","Σ","Φ","Ψ","Ω", # 0x5 Greek
"Б","Д","Ж","З","И","Л","П","Ц","Ч","Ш","Щ","Ъ","Ы","Э","Ю","Я", # 0x6 Cyrillic
"б","д","ж","з","и","л","п","ц","ч","ш","щ","ъ","ы","э","ю","я", # 0x7 Cyrillic
"Ա","Բ","Գ","Դ","Ե","Զ","Է","Ը","Թ","Ժ","Ի","Խ","Ծ","Կ","Հ","Ձ", # 0x8 Armenian Capitals
"Ղ","Ճ","Մ","Յ","Ն","Շ","Ո","Չ","Պ","Ջ","Վ","Ր","Ց","Ւ","Ք","Ֆ", # 0x9 Armenian Captials
"ᚠ","ᚢ","ᚦ","ᚱ","ᚹ","ᚺ","ᚾ","ᛈ","ᛇ","ᛉ","ᛊ","ᛏ","ᛒ","ᛖ","ᛗ","ᛟ", # 0xA Elder Futhark
"イ","ウ","オ","カ","キ","ケ","サ","シ","ス","セ","タ","チ","テ","ト","ナ","ヌ", # 0xB Katakana
"ネ","ヒ","フ","ヘ","ホ","マ","ミ","ム","メ","モ","ヤ","ラ","リ","ル","レ","ワ", # 0xC Katakana
"𐑐","𐑑","𐑒","𐑔","𐑕","𐑗","𐑙","𐑳","𐑶","𐑸","𐑹","𐑺","𐑻","𐑽","𐑾","𐑿", # 0xD Shavian
"᱑","᱕","᱘","᱙","ᱚ","ᱝ","ᱟ","ᱣ","ᱦ","ᱨ","ᱬ","ᱭ","ᱰ","ᱳ","ᱶ","ᱷ", # 0xE Ol Chiki
"𐌳","𐌸","𐌾","𐐀","𐐁","𐐂","𐐆","𐐇","𐐈","𐐉","𐐊","𐐋","𐐌","𐐍","𐐎","𐐏", # 0xF Gothic & Deseret
]
2026-05-11 23:22:13 +02:00
def b256rep(data): return "".join(bytes_to_b256(data))
def prettyb256rep(data): return f"<{b256rep(data)}>"
def b256_to_byte(point):
if not type(point) == str or not len(point) == 1: raise TypeError("Invalid input data for base256 byte decode")
try: return b256.index(point)
except Exception as e: raise ValueError(f"Could not decode base256 byte: {e}")
def b256_to_bytes(b256rep):
if not type(b256rep) == str: raise TypeError("Invalid input data for base256 decode")
try: return bytes([b256.index(c) for c in b256rep])
except Exception as e: raise ValueError(f"Could not decode base256: {e}")
def byte_to_b256(input_byte):
if type(input_byte) == bytes and not len(input_byte) == 1: TypeError("Invalid input data for base256 byte encode")
if type(input_byte) == bytes and len(input_byte) == 1: input_byte = ord(input_byte)
if not type(input_byte) == int: raise TypeError("Invalid input data for base256 byte encode")
try: return b256[int(input_byte)]
except Exception as e: raise TypeError(f"Could not encode byte to base256: {e}")
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