Compare commits

...
86 Commits
Author SHA1 Message Date
Mark Qvist 5387264dcb Updated changelog 2025-05-15 22:24:33 +02:00
Mark Qvist 308a6906db Updated manual 2025-05-15 15:32:31 +02:00
Mark Qvist 96ce7e3f47 Updated changelog 2025-05-15 15:32:20 +02:00
Mark Qvist f186b6266b Implemented dynamic keepalive and link timeout calculation 2025-05-15 12:50:16 +02:00
Mark Qvist 756029e5af Added option to specify shared instance type 2025-05-15 01:14:55 +02:00
Mark Qvist c1673f39b6 Updated changelog 2025-05-13 19:46:18 +02:00
Mark Qvist 30a08c4192 Updated manual 2025-05-13 18:01:13 +02:00
Mark Qvist d680f4d411 Cleanup 2025-05-13 17:59:26 +02:00
Mark Qvist 29a52e19cf Cleanup 2025-05-13 17:25:00 +02:00
Mark Qvist 11511168dc Cleanup 2025-05-13 13:32:35 +02:00
Mark Qvist d4ea698236 Cleanup 2025-05-13 13:29:20 +02:00
Mark Qvist 11e06b477e Cleanup 2025-05-13 13:26:26 +02:00
Mark Qvist 4e4c68071f Removed legacy encryption modes. Default to AES-256 for links and packets. 2025-05-13 13:18:44 +02:00
Mark Qvist 5f502746a4 Updated tests 2025-05-13 13:16:37 +02:00
Mark Qvist 17bbb9c0b4 Updated docs 2025-05-12 20:20:29 +02:00
Mark Qvist 8b13d6e08b Fixed announce handlers not triggering after shared instance disappearance/reappearance 2025-05-12 11:41:06 +02:00
Mark Qvist efa512be32 Cleanup 2025-05-11 16:40:14 +02:00
Mark Qvist 594f5fba1e Added ability to return file resources for request responses. Added option to specify request response auto-compression limits. 2025-05-11 16:37:57 +02:00
Mark Qvist 2912fb2184 Added option to specify resource auto-compression limits 2025-05-11 16:37:19 +02:00
Mark Qvist 02496f39f7 Removed completed tasks from roadmap 2025-05-11 11:30:06 +02:00
Mark Qvist 4e31f113c6 Optimised hardware MTU autoconfig 2025-05-10 23:15:43 +02:00
Mark Qvist 9aded3e1da Updated readme 2025-05-10 23:09:21 +02:00
Mark Qvist 3337d18e9a Added allow overwrite option to rncp 2025-05-10 21:44:42 +02:00
Mark Qvist 2cb6d019f9 Improved rncp memory utilisation and performance 2025-05-10 21:19:57 +02:00
Mark Qvist 3dc260a300 Updated link tests 2025-05-10 20:59:23 +02:00
Mark Qvist 4d7f5b8ca6 Let shared instance handle packet hashlist 2025-05-10 20:58:54 +02:00
Mark Qvist 48be5f65d8 Faster link cleanup on close 2025-05-10 20:58:01 +02:00
Mark Qvist b5d854a55c Resource performance and memory optimisations 2025-05-10 20:57:32 +02:00
Mark Qvist 552663c625 Fixed offset 2025-05-10 17:00:27 +02:00
Mark Qvist e6f0b92464 Updated example 2025-05-10 17:00:02 +02:00
Mark Qvist 08a6820aa0 Updated descriptions 2025-05-10 15:42:22 +02:00
Mark Qvist cc1faa55be Updated readme 2025-05-10 15:39:51 +02:00
Mark Qvist 840966f3e6 Updated version 2025-05-10 15:38:28 +02:00
Mark Qvist 763078a1ae Added ability to include metadata on resource transfers 2025-05-10 15:38:06 +02:00
Mark Qvist 5fb6abd019 Added resource example 2025-05-10 15:32:06 +02:00
Mark Qvist 7065856229 Added resource with metadata tests 2025-05-10 15:31:35 +02:00
Mark Qvist 668ef9253a Cleanup 2025-05-09 12:07:00 +02:00
Mark Qvist 6f333b8234 Cleanup 2025-05-09 12:04:55 +02:00
Mark Qvist 32c839f497 Updated changelog 2025-05-09 11:31:54 +02:00
Mark Qvist cbdef1d538 Updated manual 2025-05-09 11:21:13 +02:00
Mark Qvist c398b34dd8 Fixed potential unhandled exception on fast-flapping connections 2025-05-08 10:57:34 +02:00
Mark Qvist 9a1884cfec Updated manual 2025-05-07 12:10:53 +02:00
Mark Qvist 378dc1e931 Added link mode get method to Link API 2025-05-06 19:09:40 +02:00
Mark Qvist be821b6927 Added instance_name option and description to default config file 2025-05-06 19:09:20 +02:00
Mark Qvist af46e98865 Improved ratchet persist reliability 2025-05-06 18:18:05 +02:00
Mark Qvist 65b1667ae7 Updated readme 2025-05-06 17:57:08 +02:00
Mark Qvist 5bc1fc2bde Updated readme 2025-05-06 17:55:45 +02:00
Mark Qvist 4ae0f28aa0 Cleanup 2025-05-06 17:48:38 +02:00
Mark Qvist 62ecc0549d Updated readme 2025-05-06 17:25:53 +02:00
Mark Qvist cbf4c71a73 Added pure-python AES-256 implementation 2025-05-06 17:20:55 +02:00
Mark Qvist 1d27fae370 Updated github test workflow 2025-05-06 16:45:16 +02:00
Mark Qvist 05b9a80a07 Path MTU clamping handling with link mode signalling 2025-05-06 16:37:04 +02:00
Mark Qvist 38241452d3 Dynamic link mode establishment 2025-05-06 16:31:36 +02:00
Mark Qvist 40e040807a Link mode signalling generators 2025-05-06 16:12:54 +02:00
Mark Qvist 437da99d63 Handle AES-256 compatibility in Identity 2025-05-06 16:12:15 +02:00
Mark Qvist 3cbcbec942 Updated tests for link modes 2025-05-06 14:23:42 +02:00
Mark Qvist bc7a8cd09f Updated documentation 2025-05-06 14:14:42 +02:00
Mark Qvist ab0ac46d5a Enabled AES_256_CBC link mode 2025-05-06 12:10:34 +02:00
Mark Qvist d7791c60e2 Implemented compatibility handling for AES-256 migration 2025-05-06 12:08:17 +02:00
Mark Qvist 5dc8cdc6dc Merge branch 'master' of github.com:markqvist/Reticulum 2025-04-29 11:42:23 +02:00
Mark Qvist cdc33a25c5 Updated readme 2025-04-29 11:42:07 +02:00
markqvist 2b6766f68a Merge pull request #801 from LinuxinaBit/master
Generative AI Policy
2025-04-28 15:29:32 +02:00
Linux in a Bit e871bbdc07 Add Generative AI Policy reminder to 🐛-bug-report.md 2025-04-20 15:04:55 -05:00
Linux in a Bit 6a98158ba6 [Contributing.md] Add LLM Policy; Emphasize CLA 2025-04-20 14:59:23 -05:00
Mark Qvist ef8d44c257 Updated changelog 2025-04-20 21:23:08 +02:00
Mark Qvist 6a48a4d1c0 Updated version 2025-04-18 12:25:47 +02:00
Mark Qvist 4d2ba28934 Docs build 2025-04-17 23:04:00 +02:00
Mark Qvist 98d4f1c69e Fixed instance name from config being overwritten if option was not last in section 2025-04-17 15:02:08 +02:00
Mark Qvist a0f0d73204 Improved ratchet persist 2025-04-17 14:25:24 +02:00
Mark Qvist 1dbb1a6a35 Merge branch 'linkmodes' 2025-04-16 14:11:14 +02:00
Mark Qvist cc50ca82b8 Added todo note 2025-04-16 14:09:43 +02:00
Mark Qvist 373790c890 Added AES-256 support to Link 2025-04-16 14:05:34 +02:00
Mark Qvist ef30d21b58 Added AES_256_CBC support to Token 2025-04-16 14:03:40 +02:00
Mark Qvist c4cafed6aa Added AES_128_CBC and AES_256_CBC mode proxies 2025-04-16 14:01:26 +02:00
Mark Qvist 828eec5e0d Cleanup 2025-04-16 01:30:11 +02:00
Mark Qvist a8c50fe7d4 Link mode signalling fields 2025-04-16 00:44:30 +02:00
Mark Qvist ab9fc7b370 Updated docs 2025-04-16 00:43:35 +02:00
Mark Qvist 0dc972f7c9 Updated docs 2025-04-16 00:41:50 +02:00
Mark Qvist 796cffe29d Updated docs 2025-04-16 00:40:29 +02:00
Mark Qvist a0f6c99fb5 Updated docs 2025-04-16 00:37:11 +02:00
Mark Qvist eff0c91ed0 Updated docs 2025-04-16 00:35:56 +02:00
Mark Qvist dba6cd8393 Updated license 2025-04-15 20:48:12 +02:00
Mark Qvist e7daceec82 Updated license 2025-04-15 20:19:33 +02:00
Mark Qvist a65473f6ab Updated docs 2025-04-15 18:57:12 +02:00
Mark Qvist 1851fda9e0 Fixed interface string representation 2025-04-15 18:51:52 +02:00
Mark Qvist 80eec131f8 Updated docs 2025-04-15 18:25:12 +02:00
94 changed files with 2650 additions and 1124 deletions

No files matched your search

@@ -12,6 +12,7 @@ Before creating a bug report on this issue tracker, you **must** read the [Contr
- The issue tracker is used by developers of this project. **Do not use it to ask general questions, or for support requests**. - The issue tracker is used by developers of this project. **Do not use it to ask general questions, or for support requests**.
- Ideas and feature requests can be made on the [Discussions](https://github.com/markqvist/Reticulum/discussions). **Only** feature requests accepted by maintainers and developers are tracked and included on the issue tracker. **Do not post feature requests here**. - Ideas and feature requests can be made on the [Discussions](https://github.com/markqvist/Reticulum/discussions). **Only** feature requests accepted by maintainers and developers are tracked and included on the issue tracker. **Do not post feature requests here**.
- Do not submit code written using large language models (LLMs) or other generative 'AI' programs (see the [Generative AI Policy](/Contributing.md#generative-ai-policy) for details).
- After reading the [Contribution Guidelines](https://github.com/markqvist/Reticulum/blob/master/Contributing.md), **delete this section only** (*"Read the Contribution Guidelines"*) from your bug report, **and fill in all the other sections**. - After reading the [Contribution Guidelines](https://github.com/markqvist/Reticulum/blob/master/Contributing.md), **delete this section only** (*"Read the Contribution Guidelines"*) from your bug report, **and fill in all the other sections**.
**Describe the Bug** **Describe the Bug**
+3 -1
View File
@@ -29,7 +29,9 @@ jobs:
uses: actions/setup-python@v5 uses: actions/setup-python@v5
with: with:
python-version: 3.x python-version: 3.x
- run: make test - run: |
python -m pip install -q cryptography
make test
package: package:
needs: test needs: test
+85
View File
@@ -1,3 +1,88 @@
### 2025-05-15: RNS β 0.9.6
This release activates AES-256 as the default encryption mode for all communication. It is the last release that will support the old AES-128 based modes, which will be entirely phased out in the next release.
This release also includes a number of API and resource consumption improvements, and fixes a bug.
**Changes**
- Enabled AES-256 as default encryption mode for all traffic
- Added dynamic link keepalive and timeout calculation
- Added ability to efficiently transfer files as responses in the `Request` API
- Added ability to include metadata on `Resource` transfers
- Added option to specify `Resource` auto-compression limits
- Added option to specify `Request` response auto-compression limits
- Added `Resource` transfer example
- Added allow overwrite option to `rncp`
- Improved hardware MTU auto-configuration
- Improved handling of file transfers using the `Resource` API
- Improved `Resource` transfer memory consumption
- Improved memory consumption of applications connected to a shared instance
- Improved `rncp` memory consumption for large files
- Fixed announce handlers not triggering after shared instance disappearance
**Release Hashes**
```
a23c64a04c1e83fd0ab449f564ac904da7fd4f61c0faf68a063f486cc48b44bd rns-0.9.6-py3-none-any.whl
4544882dea902b18b00d8a04c9ab93201974573b7b63c3db06cb310b0acec240 rnspure-0.9.6-py3-none-any.whl
```
### 2025-05-09: RNS β 0.9.5
This release initiates migration of Reticulum from AES-128 to AES-256 as the default link and packet cipher mode. It is a compatibility/migration release, that while supporting AES-256 doesn't use it by default. It will work with both the old AES-128 based modes, and the new AES-256 based modes. There's a very slight penalty in performance to support both the old and new modes at the same time, but only for single packet APIs (not links), and it really shouldn't be noticeable in any everyday use.
In the next release, version `0.9.6`, Reticulum will transition fully to AES-256 and use it by default for all communications. That means that both single packets and links will use AES-256 by default. The old AES-128 link mode may or may not be available for a few releases, but will ultimately be phased out entirely.
The update requires no intervention, configuration changes or anything similar from a users or developers perspective. Everything should simply work. This goes both for the `0.9.5` update, and the next `0.9.6` update that transitions fully to AES-256.
**Changes**
- Added support for AES-256 mode to links and packets
- Added dynamic link mode support
- Added temporary backwards compatibility for AES-128 link and packet modes
- Added `get_mode()` method to link API
- Added tests for all enabled link modes
- Added `instance_name` option and description to default config file
- Improved ratchet persist reliability if Reticulum is force killed while persisting ratchets
- Fixed interface string representation for some interfaces
- Fixed instance name config option being overwritten if option was not last in section
- Fixed unhandled potential exception on fast-flapping `BackboneInterface` connections
**Release Hashes**
```
ae6587c86c98cae0df73567af093cc92fe204e71bb01f2506da9aec626a27e97 rns-0.9.5-py3-none-any.whl
96208c1d1234e3e4b1c18ca986bad5d4693aeb431453efd7ade33b87f35600e1 rnspure-0.9.5-py3-none-any.whl
```
### 2025-04-15: RNS β 0.9.4
This release significantly improves memory utilisation and performance. It also includes a few new features and general improvements to the included utilities and programs.
**Changes**
- Significantly improved memory utilisation, thread count and performance on nodes with many interfaces or clients
- Switched local instance communication to run over abstract domain sockets on Linux and Android
- Switched instance IPC to run over abstract domain sockets on Linux and Android
- Added kernel event based I/O backend on Linux and Android
- Added fast `BackboneInterface` type
- Added support for XIAO-ESP32S3 to `rnodeconf`
- Added interactive shell option to `rnsd`
- Added API option to search for identity by identity hash
- Added option to run TCP and Backbone interfaces in AP mode
- Improved `RNodeMultiInterface` host communications specification
- Improved `rncp` statistics output
- Improved link and reverse-table culling
- Fixed an occasional I/O thread hang on instance shutdown, that would result in an error printed to the console
- Fixed various minor interface logging inconsistencies
- Fixed various minor interface checking inconsistencies
- Updated internal `configobj` implementation
- Refactored various parts of the transport core code
- Swicthed to using internal `netinfo` implementation instead of including full `ifaddr` library
- Cleaned out unneeded dependencies
**Release Hashes**
```
737294f29e013f9fa9c8c1326006d0547497607156828fee3dc2a0d3ddd754e7 rns-0.9.4-py3-none-any.whl
0bd8a908af115c27733484853d779574d6383ebc1d78160e5a72c14ed9692a13 rnspure-0.9.4-py3-none-any.whl
```
### 2025-03-13: RNS β 0.9.3 ### 2025-03-13: RNS β 0.9.3
This maintenance release improves performance and fixes a number of bugs. This maintenance release improves performance and fixes a number of bugs.
+9 -1
View File
@@ -40,4 +40,12 @@ Pull requests have a high chance of being accepted if they are:
Even new ideas and proposals that have not been approved by a maintainer, or fall outside the established roadmap, are *occasionally* accepted - if they possess the remaining of the above qualities. If not, they will be closed and removed without comments or explanation. Even new ideas and proposals that have not been approved by a maintainer, or fall outside the established roadmap, are *occasionally* accepted - if they possess the remaining of the above qualities. If not, they will be closed and removed without comments or explanation.
By contributing code to this project, you agree that copyright for the code is transferred to the Reticulum maintainers and that the code is irrevocably placed under the [MIT license](./LICENSE). ## Generative AI Policy
Contributions written using large language models (LLMs) or other generative 'AI' programs are prohibited. LLMs produce errors so frequently and in a way that is so unlike human error that issues will regularly remain undetected and slip through, even with stringent review. This is not a worthwhile tradeoff for Reticulum, especially considering the limited time maintainers have to correct these issues, and we ask that you refrain from using any such output in your contributions.
This applies to all official Reticlulm projects and documentation as well as all submitted issues and discussion in official channels, except in cases where language translation and/or speech recogntion technologies are required for communication. We also ask that you avoid using LLMs for troubleshooting, as results can be misleading, and instead request help in one of our [various communities](https://reticulum.network/start.html).
## Contributor License Agreement
By contributing code to this project, you agree that copyright for the code is transferred to the Reticulum maintainers and that the code is irrevocably placed under the [Reticulum License](./LICENSE).
-2
View File
@@ -1,5 +1,3 @@
# MIT License - Copyright (c) 2024 Mark Qvist / unsigned.io
# This example illustrates creating a custom interface # This example illustrates creating a custom interface
# definition, that can be loaded and used by Reticulum at # definition, that can be loaded and used by Reticulum at
# runtime. Any number of custom interfaces can be created # runtime. Any number of custom interfaces can be created
+2 -2
View File
@@ -1,6 +1,6 @@
########################################################## ##########################################################
# This RNS example demonstrates how to set perform # # This RNS example demonstrates how to perform requests #
# requests and receive responses over a link. # # and receive responses over a link. #
########################################################## ##########################################################
import os import os
+294
View File
@@ -0,0 +1,294 @@
##########################################################
# This RNS example demonstrates how to transfer a #
# resource over an established link #
##########################################################
import os
import sys
import time
import random
import argparse
import RNS
# Let's define an app name. We'll use this for all
# destinations we create. Since this echo example
# is part of a range of example utilities, we'll put
# them all within the app namespace "example_utilities"
APP_NAME = "example_utilities"
##########################################################
#### Server Part #########################################
##########################################################
# A reference to the latest client link that connected
latest_client_link = None
# This initialisation is executed when the users chooses
# to run as a server
def server(configpath):
# We must first initialise Reticulum
reticulum = RNS.Reticulum(configpath)
# Randomly create a new identity for our link example
server_identity = RNS.Identity()
# We create a destination that clients can connect to. We
# want clients to create links to this destination, so we
# need to create a "single" destination type.
server_destination = RNS.Destination(
server_identity,
RNS.Destination.IN,
RNS.Destination.SINGLE,
APP_NAME,
"resourceexample"
)
# We configure a function that will get called every time
# a new client creates a link to this destination.
server_destination.set_link_established_callback(client_connected)
# Everything's ready!
# Let's Wait for client resources or user input
server_loop(server_destination)
def server_loop(destination):
# Let the user know that everything is ready
RNS.log(
"Resource example "+
RNS.prettyhexrep(destination.hash)+
" running, waiting for a connection."
)
RNS.log("Hit enter to manually send an announce (Ctrl-C to quit)")
# We enter a loop that runs until the users exits.
# If the user hits enter, we will announce our server
# destination on the network, which will let clients
# know how to create messages directed towards it.
while True:
entered = input()
destination.announce()
RNS.log("Sent announce from "+RNS.prettyhexrep(destination.hash))
# When a client establishes a link to our server
# destination, this function will be called with
# a reference to the link.
def client_connected(link):
global latest_client_link
RNS.log("Client connected")
# We configure the link to accept all resources
# and set a callback for completed resources
link.set_resource_strategy(RNS.Link.ACCEPT_ALL)
link.set_resource_concluded_callback(resource_concluded)
link.set_link_closed_callback(client_disconnected)
latest_client_link = link
def client_disconnected(link):
RNS.log("Client disconnected")
def resource_concluded(resource):
if resource.status == RNS.Resource.COMPLETE:
RNS.log(f"Resource {resource} received")
RNS.log(f"Metadata: {resource.metadata}")
RNS.log(f"Data length: {os.stat(resource.data.name).st_size}")
RNS.log(f"Data can be read directly from: {resource.data}")
RNS.log(f"Data can be moved or copied from: {resource.data.name}")
RNS.log(f"First 32 bytes of data: {RNS.hexrep(resource.data.read(32))}")
else:
RNS.log(f"Receiving resource {resource} failed")
##########################################################
#### Client Part #########################################
##########################################################
# A reference to the server link
server_link = None
def random_text_generator():
texts = ["They looked up", "On each full moon", "Becky was upset", "I’ll stay away from it", "The pet shop stocks everything"]
return texts[random.randint(0, len(texts)-1)]
# This initialisation is executed when the users chooses
# to run as a client
def client(destination_hexhash, configpath):
# We need a binary representation of the destination
# hash that was entered on the command line
try:
dest_len = (RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2
if len(destination_hexhash) != dest_len:
raise ValueError(
"Destination length is invalid, must be {hex} hexadecimal characters ({byte} bytes).".format(hex=dest_len, byte=dest_len//2)
)
destination_hash = bytes.fromhex(destination_hexhash)
except:
RNS.log("Invalid destination entered. Check your input!\n")
sys.exit(0)
# We must first initialise Reticulum
reticulum = RNS.Reticulum(configpath)
# Check if we know a path to the destination
if not RNS.Transport.has_path(destination_hash):
RNS.log("Destination is not yet known. Requesting path and waiting for announce to arrive...")
RNS.Transport.request_path(destination_hash)
while not RNS.Transport.has_path(destination_hash):
time.sleep(0.1)
# Recall the server identity
server_identity = RNS.Identity.recall(destination_hash)
# Inform the user that we'll begin connecting
RNS.log("Establishing link with server...")
# When the server identity is known, we set
# up a destination
server_destination = RNS.Destination(
server_identity,
RNS.Destination.OUT,
RNS.Destination.SINGLE,
APP_NAME,
"resourceexample"
)
# And create a link
link = RNS.Link(server_destination)
# We'll set up functions to inform the
# user when the link is established or closed
link.set_link_established_callback(link_established)
link.set_link_closed_callback(link_closed)
# Everything is set up, so let's enter a loop
# for the user to interact with the example
client_loop()
def client_loop():
global server_link
# Wait for the link to become active
while not server_link:
time.sleep(0.1)
should_quit = False
while not should_quit:
try:
print("> ", end=" ")
text = input()
# Check if we should quit the example
if text == "quit" or text == "q" or text == "exit":
should_quit = True
server_link.teardown()
else:
# Generate 32 megabytes of random data
data = os.urandom(32*1024*1024)
RNS.log(f"Data length: {len(data)}")
RNS.log(f"First 32 bytes of data: {RNS.hexrep(data[:32])}")
# Generate some metadata
metadata = {"text": random_text_generator(), "numbers": [1,2,3,4], "blob": os.urandom(16)}
# Send the resource
resource = RNS.Resource(data, server_link, metadata=metadata, callback=resource_concluded_sending, auto_compress=False)
# Alternatively, you can stream data
# directly from an open file descriptor
# with open("/path/to/file", "rb") as data_file:
# resource = RNS.Resource(data_file, server_link, metadata=metadata, callback=resource_concluded_sending, auto_compress=False)
except Exception as e:
RNS.log("Error while sending resource over the link: "+str(e))
should_quit = True
server_link.teardown()
def resource_concluded_sending(resource):
if resource.status == RNS.Resource.COMPLETE: RNS.log(f"The resource {resource} was sent successfully")
else: RNS.log(f"Sending the resource {resource} failed")
# This function is called when a link
# has been established with the server
def link_established(link):
# We store a reference to the link
# instance for later use
global server_link
server_link = link
# Inform the user that the server is
# connected
RNS.log("Link established with server, hit enter to sand a resource, or type in \"quit\" to quit")
# When a link is closed, we'll inform the
# user, and exit the program
def link_closed(link):
if link.teardown_reason == RNS.Link.TIMEOUT:
RNS.log("The link timed out, exiting now")
elif link.teardown_reason == RNS.Link.DESTINATION_CLOSED:
RNS.log("The link was closed by the server, exiting now")
else:
RNS.log("Link closed, exiting now")
time.sleep(1.5)
sys.exit(0)
##########################################################
#### Program Startup #####################################
##########################################################
# This part of the program runs at startup,
# and parses input of from the user, and then
# starts up the desired program mode.
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description="Simple resource example")
parser.add_argument(
"-s",
"--server",
action="store_true",
help="wait for incoming resources from clients"
)
parser.add_argument(
"--config",
action="store",
default=None,
help="path to alternative Reticulum config directory",
type=str
)
parser.add_argument(
"destination",
nargs="?",
default=None,
help="hexadecimal hash of the server destination",
type=str
)
args = parser.parse_args()
if args.config:
configarg = args.config
else:
configarg = None
if args.server:
server(configarg)
else:
if (args.destination == None):
print("")
parser.print_help()
print("")
else:
client(args.destination, configarg)
except KeyboardInterrupt:
print("")
sys.exit(0)
+12 -4
View File
@@ -1,6 +1,6 @@
MIT License, unless otherwise noted Reticulum License
Copyright (c) 2016-2024 Mark Qvist / unsigned.io Copyright (c) 2016-2025 Mark Qvist
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all - The Software shall not be used in any kind of system which includes amongst
copies or substantial portions of the Software. 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 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+32 -19
View File
@@ -52,7 +52,7 @@ For more info, see [reticulum.network](https://reticulum.network/) and [the FAQ
- Forward Secrecy is available for all communication types, both for single packets and over links - Forward Secrecy is available for all communication types, both for single packets and over links
- Reticulum uses the following format for encrypted tokens: - Reticulum uses the following format for encrypted tokens:
- Ephemeral per-packet and link keys and derived from an ECDH key exchange on Curve25519 - Ephemeral per-packet and link keys and derived from an ECDH key exchange on Curve25519
- AES-128 in CBC mode with PKCS7 padding - AES-256 in CBC mode with PKCS7 padding
- HMAC using SHA256 for authentication - HMAC using SHA256 for authentication
- IVs are generated through os.urandom() - IVs are generated through os.urandom()
- Unforgeable packet delivery confirmations - Unforgeable packet delivery confirmations
@@ -62,7 +62,7 @@ For more info, see [reticulum.network](https://reticulum.network/) and [the FAQ
- Easily create your own custom interfaces for communicating over anything - Easily create your own custom interfaces for communicating over anything
- Authentication and virtual network segmentation on all supported interface types - Authentication and virtual network segmentation on all supported interface types
- An intuitive and easy-to-use API - An intuitive and easy-to-use API
- Simpler and easier to use than sockets APIs and simpler, but more powerful - Simpler and easier to use than sockets APIs, but more powerful
- Makes building distributed and decentralised applications much simpler - Makes building distributed and decentralised applications much simpler
- Reliable and efficient transfer of arbitrary amounts of data - Reliable and efficient transfer of arbitrary amounts of data
- Reticulum can handle a few bytes of data or files of many gigabytes - Reticulum can handle a few bytes of data or files of many gigabytes
@@ -86,9 +86,10 @@ following resources.
- You can use the [rnsh](https://github.com/acehoss/rnsh) program to establish remote shell sessions over Reticulum. - You can use the [rnsh](https://github.com/acehoss/rnsh) program to establish remote shell sessions over Reticulum.
- [LXMF](https://github.com/markqvist/lxmf) is a distributed, delay and disruption tolerant message transfer protocol built on Reticulum - [LXMF](https://github.com/markqvist/lxmf) is a distributed, delay and disruption tolerant message transfer protocol built on Reticulum
- The [LXST](https://github.com/markqvist/lxst) protocol and framework provides real-time audio and signals transport over Reticulum. It includes primitives and utilities for building voice-based applications and hardware devices, such as the `rnphone` program, that can be used to build hardware telephones.
- For an off-grid, encrypted and resilient mesh communications platform, see [Nomad Network](https://github.com/markqvist/NomadNet) - For an off-grid, encrypted and resilient mesh communications platform, see [Nomad Network](https://github.com/markqvist/NomadNet)
- The Android, Linux, macOS and Windows app [Sideband](https://github.com/markqvist/Sideband) has a graphical interface and focuses on ease of use. - The Android, Linux, macOS and Windows app [Sideband](https://github.com/markqvist/Sideband) has a graphical interface and many advanced features, such as file transfers, image and voice messages, real-time voice calls, a distributed telemetry system, mapping capabilities and full plugin extensibility.
- [MeshChat](https://github.com/liamcottle/reticulum-meshchat) is a user-friendly LXMF client, that also supports voice calls. - [MeshChat](https://github.com/liamcottle/reticulum-meshchat) is a user-friendly LXMF client with a web-based interface, that also supports image and voice messages, as well as file transfers. It also includes a built-in page browser for browsing Nomad Network nodes.
## Where can Reticulum be used? ## Where can Reticulum be used?
Over practically any medium that can support at least a half-duplex channel Over practically any medium that can support at least a half-duplex channel
@@ -296,23 +297,28 @@ You can help support the continued development of open, free and private communi
``` ```
84FpY1QbxHcgdseePYNmhTHcrgMX4nFfBYtz2GKYToqHVVhJp8Eaw1Z1EedRnKD19b3B8NiLCGVxzKV17UMmmeEsCrPyA5w 84FpY1QbxHcgdseePYNmhTHcrgMX4nFfBYtz2GKYToqHVVhJp8Eaw1Z1EedRnKD19b3B8NiLCGVxzKV17UMmmeEsCrPyA5w
``` ```
- Ethereum
```
0xFDabC71AC4c0C78C95aDDDe3B4FA19d6273c5E73
```
- Bitcoin - Bitcoin
``` ```
35G9uWVzrpJJibzUwpNUQGQNFzLirhrYAH bc1p4a6axuvl7n9hpapfj8sv5reqj8kz6uxa67d5en70vzrttj0fmcusgxsfk5
```
- Ethereum
```
0xae89F3B94fC4AD6563F0864a55F9a697a90261ff
``` ```
- Ko-Fi: https://ko-fi.com/markqvist - Ko-Fi: https://ko-fi.com/markqvist
Are certain features in the development roadmap are important to you or your
organisation? Make them a reality quickly by sponsoring their implementation.
## Cryptographic Primitives ## Cryptographic Primitives
Reticulum uses a simple suite of efficient, strong and well-tested cryptographic Reticulum uses a simple suite of efficient, strong and well-tested cryptographic
primitives, with widely available implementations that can be used both on primitives, with widely available implementations that can be used both on
general-purpose CPUs and on microcontrollers. The utilised primitives are: general-purpose CPUs and on microcontrollers.
One of the primary considerations for choosing this particular set of primitives is
that they can be implemented *safely* with relatively few pitfalls, on practically
all current computing platforms.
The primitives listed here **are authoritative**. Anything claiming to be Reticulum,
but not using these exact primitives **is not** Reticulum, and possibly an
intentionally compromised or weakened clone. The utilised primitives are:
- Reticulum Identity Keys are 512-bit Curve25519 keysets - Reticulum Identity Keys are 512-bit Curve25519 keysets
- A 256-bit Ed25519 key for signatures - A 256-bit Ed25519 key for signatures
@@ -320,15 +326,15 @@ general-purpose CPUs and on microcontrollers. The utilised primitives are:
- HKDF for key derivation - HKDF for key derivation
- Encrypted tokens are based on the [Fernet spec](https://github.com/fernet/spec/) - Encrypted tokens are based on the [Fernet spec](https://github.com/fernet/spec/)
- Ephemeral keys derived from an ECDH key exchange on Curve25519 - Ephemeral keys derived from an ECDH key exchange on Curve25519
- AES-128 in CBC mode with PKCS7 padding
- HMAC using SHA256 for message authentication - HMAC using SHA256 for message authentication
- IVs are generated through os.urandom() - IVs must be generated through `os.urandom()` or better
- AES-256 in CBC mode with PKCS7 padding
- No Fernet version and timestamp metadata fields - No Fernet version and timestamp metadata fields
- SHA-256 - SHA-256
- SHA-512 - SHA-512
In the default installation configuration, the `X25519`, `Ed25519` and In the default installation configuration, the `X25519`, `Ed25519`,
`AES-128-CBC` primitives are provided by [OpenSSL](https://www.openssl.org/) and `AES-256-CBC` primitives are provided by [OpenSSL](https://www.openssl.org/)
(via the [PyCA/cryptography](https://github.com/pyca/cryptography) package). (via the [PyCA/cryptography](https://github.com/pyca/cryptography) package).
The hashing functions `SHA-256` and `SHA-512` are provided by the standard The hashing functions `SHA-256` and `SHA-512` are provided by the standard
Python [hashlib](https://docs.python.org/3/library/hashlib.html). The `HKDF`, Python [hashlib](https://docs.python.org/3/library/hashlib.html). The `HKDF`,
@@ -342,13 +348,19 @@ provided by the following internal implementations:
Reticulum also includes a complete implementation of all necessary primitives Reticulum also includes a complete implementation of all necessary primitives
in pure Python. If OpenSSL & PyCA are not available on the system when in pure Python. If OpenSSL and PyCA are not available on the system when
Reticulum is started, Reticulum will instead use the internal pure-python Reticulum is started, Reticulum will instead use the internal pure-python
primitives. A trivial consequence of this is performance, with the OpenSSL primitives. A trivial consequence of this is performance, with the OpenSSL
backend being *much* faster. The most important consequence however, is the backend being *much* faster. The most important consequence however, is the
potential loss of security by using primitives that has not seen the same potential loss of security by using primitives that has not seen the same
amount of scrutiny, testing and review as those from OpenSSL. amount of scrutiny, testing and review as those from OpenSSL.
Please note that by default, installing Reticulum will **require** OpenSSL and
PyCA to also be automatically installed if not already available. It is only
possible to use the pure-python primitives if this requirement is specifically
overridden by the user, for example by installing the `rnspure` package instead
of the normal `rns` package, or by running directly from local source-code.
If you want to use the internal pure-python primitives, it is **highly If you want to use the internal pure-python primitives, it is **highly
advisable** that you have a good understanding of the risks that this pose, and advisable** that you have a good understanding of the risks that this pose, and
make an informed decision on whether those risks are acceptable to you. make an informed decision on whether those risks are acceptable to you.
@@ -372,7 +384,8 @@ projects:
- [PyCA/cryptography](https://github.com/pyca/cryptography), *BSD License* - [PyCA/cryptography](https://github.com/pyca/cryptography), *BSD License*
- [Pure-25519](https://github.com/warner/python-pure25519) by [Brian Warner](https://github.com/warner), *MIT License* - [Pure-25519](https://github.com/warner/python-pure25519) by [Brian Warner](https://github.com/warner), *MIT License*
- [Pysha2](https://github.com/thomdixon/pysha2) by [Thom Dixon](https://github.com/thomdixon), *MIT License* - [Pysha2](https://github.com/thomdixon/pysha2) by [Thom Dixon](https://github.com/thomdixon), *MIT License*
- [Python-AES](https://github.com/orgurar/python-aes) by [Or Gur Arie](https://github.com/orgurar), *MIT License* - [Python AES-128](https://github.com/orgurar/python-aes) by [Or Gur Arie](https://github.com/orgurar), *MIT License*
- [Python AES-256](https://github.com/boppreh/aes) by [BoppreH](https://github.com/boppreh), *MIT License*
- [Curve25519.py](https://gist.github.com/nickovs/cc3c22d15f239a2640c185035c06f8a3#file-curve25519-py) by [Nicko van Someren](https://gist.github.com/nickovs), *Public Domain* - [Curve25519.py](https://gist.github.com/nickovs/cc3c22d15f239a2640c185035c06f8a3#file-curve25519-py) by [Nicko van Someren](https://gist.github.com/nickovs), *Public Domain*
- [I2Plib](https://github.com/l-n-s/i2plib) by [Viktor Villainov](https://github.com/l-n-s) - [I2Plib](https://github.com/l-n-s/i2plib) by [Viktor Villainov](https://github.com/l-n-s)
- [PySerial](https://github.com/pyserial/pyserial) by Chris Liechti, *BSD License* - [PySerial](https://github.com/pyserial/pyserial) by Chris Liechti, *BSD License*
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors. # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors. # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+55 -12
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2022-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -24,23 +32,57 @@ import RNS.Cryptography.Provider as cp
import RNS.vendor.platformutils as pu import RNS.vendor.platformutils as pu
if cp.PROVIDER == cp.PROVIDER_INTERNAL: if cp.PROVIDER == cp.PROVIDER_INTERNAL:
from .aes import AES from .aes import AES128
from .aes import AES256
elif cp.PROVIDER == cp.PROVIDER_PYCA: elif cp.PROVIDER == cp.PROVIDER_PYCA:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
if pu.cryptography_old_api(): from cryptography.hazmat.backends import default_backend
if pu.cryptography_old_api():
from cryptography.hazmat.backends import default_backend
class AES_128_CBC: class AES_128_CBC:
@staticmethod @staticmethod
def encrypt(plaintext, key, iv): def encrypt(plaintext, key, iv):
if len(key) != 16: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if cp.PROVIDER == cp.PROVIDER_INTERNAL: if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES(key) cipher = AES128(key)
return cipher.encrypt(plaintext, iv) return cipher.encrypt(plaintext, iv)
elif cp.PROVIDER == cp.PROVIDER_PYCA:
if not pu.cryptography_old_api():
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
else:
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
return ciphertext
@staticmethod
def decrypt(ciphertext, key, iv):
if len(key) != 16: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES128(key)
return cipher.decrypt(ciphertext, iv)
elif cp.PROVIDER == cp.PROVIDER_PYCA:
if not pu.cryptography_old_api():
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
else:
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
return plaintext
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 cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES256(key)
return cipher.encrypt_cbc(plaintext, iv)
elif cp.PROVIDER == cp.PROVIDER_PYCA: elif cp.PROVIDER == cp.PROVIDER_PYCA:
if not pu.cryptography_old_api(): if not pu.cryptography_old_api():
cipher = Cipher(algorithms.AES(key), modes.CBC(iv)) cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
@@ -53,9 +95,10 @@ class AES_128_CBC:
@staticmethod @staticmethod
def decrypt(ciphertext, key, iv): def decrypt(ciphertext, key, iv):
if len(key) != 32: raise ValueError(f"Invalid key length {len(key)*8} for {self}")
if cp.PROVIDER == cp.PROVIDER_INTERNAL: if cp.PROVIDER == cp.PROVIDER_INTERNAL:
cipher = AES(key) cipher = AES256(key)
return cipher.decrypt(ciphertext, iv) return cipher.decrypt_cbc(ciphertext, iv)
elif cp.PROVIDER == cp.PROVIDER_PYCA: elif cp.PROVIDER == cp.PROVIDER_PYCA:
if not pu.cryptography_old_api(): if not pu.cryptography_old_api():
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2022-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2022-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2022-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2022-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2022-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2022-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+48 -44
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2022-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -25,7 +33,9 @@ import time
from RNS.Cryptography import HMAC from RNS.Cryptography import HMAC
from RNS.Cryptography import PKCS7 from RNS.Cryptography import PKCS7
from RNS.Cryptography import AES
from RNS.Cryptography.AES import AES_128_CBC from RNS.Cryptography.AES import AES_128_CBC
from RNS.Cryptography.AES import AES_256_CBC
class Token(): class Token():
""" """
@@ -40,71 +50,65 @@ class Token():
TOKEN_OVERHEAD = 48 # Bytes TOKEN_OVERHEAD = 48 # Bytes
@staticmethod @staticmethod
def generate_key(): def generate_key(mode=AES_256_CBC):
return os.urandom(32) if mode == AES_128_CBC: return os.urandom(32)
elif mode == AES_256_CBC: return os.urandom(64)
else: raise TypeError(f"Invalid token mode: {mode}")
def __init__(self, key = None): def __init__(self, key=None, mode=AES):
if key == None: if key == None: raise ValueError("Token key cannot be None")
raise ValueError("Token key cannot be None")
if len(key) != 32: if mode == AES:
raise ValueError("Token key must be 32 bytes, not "+str(len(key))) if len(key) == 32:
self.mode = AES_128_CBC
self._signing_key = key[:16] self._signing_key = key[:16]
self._encryption_key = key[16:] self._encryption_key = key[16:]
elif len(key) == 64:
self.mode = AES_256_CBC
self._signing_key = key[:32]
self._encryption_key = key[32:]
else: raise ValueError("Token key must be 128 or 256 bits, not "+str(len(key)*8))
else: raise TypeError(f"Invalid token mode: {mode}")
def verify_hmac(self, token): def verify_hmac(self, token):
if len(token) <= 32: if len(token) <= 32: raise ValueError("Cannot verify HMAC on token of only "+str(len(token))+" bytes")
raise ValueError("Cannot verify HMAC on token of only "+str(len(token))+" bytes")
else: else:
received_hmac = token[-32:] received_hmac = token[-32:]
expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest() expected_hmac = HMAC.new(self._signing_key, token[:-32]).digest()
if received_hmac == expected_hmac: if received_hmac == expected_hmac: return True
return True else: return False
else:
return False
def encrypt(self, data = None): def encrypt(self, data = None):
if not isinstance(data, bytes): raise TypeError("Token plaintext input must be bytes")
iv = os.urandom(16) iv = os.urandom(16)
current_time = int(time.time())
if not isinstance(data, bytes): ciphertext = self.mode.encrypt(
raise TypeError("Token plaintext input must be bytes")
ciphertext = AES_128_CBC.encrypt(
plaintext = PKCS7.pad(data), plaintext = PKCS7.pad(data),
key = self._encryption_key, key = self._encryption_key,
iv = iv, iv = iv)
)
signed_parts = iv+ciphertext signed_parts = iv+ciphertext
return signed_parts + HMAC.new(self._signing_key, signed_parts).digest() return signed_parts + HMAC.new(self._signing_key, signed_parts).digest()
def decrypt(self, token = None): def decrypt(self, token = None):
if not isinstance(token, bytes): if not isinstance(token, bytes): raise TypeError("Token must be bytes")
raise TypeError("Token must be bytes") if not self.verify_hmac(token): raise ValueError("Token HMAC was invalid")
if not self.verify_hmac(token):
raise ValueError("Token HMAC was invalid")
iv = token[:16] iv = token[:16]
ciphertext = token[16:-32] ciphertext = token[16:-32]
try: try:
plaintext = PKCS7.unpad( return PKCS7.unpad(
AES_128_CBC.decrypt( self.mode.decrypt(
ciphertext, ciphertext = ciphertext,
self._encryption_key, key = self._encryption_key,
iv, iv = iv))
)
)
return plaintext except Exception as e: raise ValueError(f"Could not decrypt token: {e}")
except Exception as e:
raise ValueError("Could not decrypt token")
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2022-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+2 -1
View File
@@ -1 +1,2 @@
from .aes import AES from .aes128 import AES128
from .aes256 import AES256
-271
View File
@@ -1,271 +0,0 @@
# MIT License
# Copyright (c) 2021 Or Gur Arie
# 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 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 .utils import *
class AES:
# AES-128 block size
block_size = 16
# AES-128 encrypts messages with 10 rounds
_rounds = 10
# initiate the AES objecy
def __init__(self, key):
"""
Initializes the object with a given key.
"""
# make sure key length is right
assert len(key) == AES.block_size
# ExpandKey
self._round_keys = self._expand_key(key)
# will perform the AES ExpandKey phase
def _expand_key(self, master_key):
"""
Expands and returns a list of key matrices for the given master_key.
"""
# Initialize round keys with raw key material.
key_columns = bytes2matrix(master_key)
iteration_size = len(master_key) // 4
# Each iteration has exactly as many columns as the key material.
i = 1
while len(key_columns) < (self._rounds + 1) * 4:
# Copy previous word.
word = list(key_columns[-1])
# Perform schedule_core once every "row".
if len(key_columns) % iteration_size == 0:
# Circular shift.
word.append(word.pop(0))
# Map to S-BOX.
word = [s_box[b] for b in word]
# XOR with first byte of R-CON, since the others bytes of R-CON are 0.
word[0] ^= r_con[i]
i += 1
elif len(master_key) == 32 and len(key_columns) % iteration_size == 4:
# Run word through S-box in the fourth iteration when using a
# 256-bit key.
word = [s_box[b] for b in word]
# XOR with equivalent word from previous iteration.
word = bytes(i^j for i, j in zip(word, key_columns[-iteration_size]))
key_columns.append(word)
# Group key words in 4x4 byte matrices.
return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)]
# encrypt a single block of data with AES
def _encrypt_block(self, plaintext):
"""
Encrypts a single block of 16 byte long plaintext.
"""
# length of a single block
assert len(plaintext) == AES.block_size
# perform on a matrix
state = bytes2matrix(plaintext)
# AddRoundKey
add_round_key(state, self._round_keys[0])
# 9 main rounds
for i in range(1, self._rounds):
# SubBytes
sub_bytes(state)
# ShiftRows
shift_rows(state)
# MixCols
mix_columns(state)
# AddRoundKey
add_round_key(state, self._round_keys[i])
# last round, w/t AddRoundKey step
sub_bytes(state)
shift_rows(state)
add_round_key(state, self._round_keys[-1])
# return the encrypted matrix as bytes
return matrix2bytes(state)
# decrypt a single block of data with AES
def _decrypt_block(self, ciphertext):
"""
Decrypts a single block of 16 byte long ciphertext.
"""
# length of a single block
assert len(ciphertext) == AES.block_size
# perform on a matrix
state = bytes2matrix(ciphertext)
# in reverse order, last round is first
add_round_key(state, self._round_keys[-1])
inv_shift_rows(state)
inv_sub_bytes(state)
for i in range(self._rounds - 1, 0, -1):
# nain rounds
add_round_key(state, self._round_keys[i])
inv_mix_columns(state)
inv_shift_rows(state)
inv_sub_bytes(state)
# initial AddRoundKey phase
add_round_key(state, self._round_keys[0])
# return bytes
return matrix2bytes(state)
# will encrypt the entire data
def encrypt(self, plaintext, iv):
"""
Encrypts `plaintext` using CBC mode and PKCS#7 padding, with the given
initialization vector (iv).
"""
# iv length must be same as block size
assert len(iv) == AES.block_size
assert len(plaintext) % AES.block_size == 0
ciphertext_blocks = []
previous = iv
for plaintext_block in split_blocks(plaintext):
# in CBC mode every block is XOR'd with the previous block
xorred = xor_bytes(plaintext_block, previous)
# encrypt current block
block = self._encrypt_block(xorred)
previous = block
# append to ciphertext
ciphertext_blocks.append(block)
# return as bytes
return b''.join(ciphertext_blocks)
# will decrypt the entire data
def decrypt(self, ciphertext, iv):
"""
Decrypts `ciphertext` using CBC mode and PKCS#7 padding, with the given
initialization vector (iv).
"""
# iv length must be same as block size
assert len(iv) == AES.block_size
plaintext_blocks = []
previous = iv
for ciphertext_block in split_blocks(ciphertext):
# in CBC mode every block is XOR'd with the previous block
xorred = xor_bytes(previous, self._decrypt_block(ciphertext_block))
# append plaintext
plaintext_blocks.append(xorred)
previous = ciphertext_block
return b''.join(plaintext_blocks)
def test():
# modules and classes requiered for test only
import os
class bcolors:
OK = '\033[92m' #GREEN
WARNING = '\033[93m' #YELLOW
FAIL = '\033[91m' #RED
RESET = '\033[0m' #RESET COLOR
# will test AES class by performing an encryption / decryption
print("AES Tests")
print("=========")
# generate a secret key and print details
key = os.urandom(AES.block_size)
_aes = AES(key)
print(f"Algorithm: AES-CBC-{AES.block_size*8}")
print(f"Secret Key: {key.hex()}")
print()
# test single block encryption / decryption
iv = os.urandom(AES.block_size)
single_block_text = b"SingleBlock Text"
print("Single Block Tests")
print("------------------")
print(f"iv: {iv.hex()}")
print(f"plain text: '{single_block_text.decode()}'")
ciphertext_block = _aes._encrypt_block(single_block_text)
plaintext_block = _aes._decrypt_block(ciphertext_block)
print(f"Ciphertext Hex: {ciphertext_block.hex()}")
print(f"Plaintext: {plaintext_block.decode()}")
assert plaintext_block == single_block_text
print(bcolors.OK + "Single Block Test Passed Successfully" + bcolors.RESET)
print()
# test a less than a block length phrase
iv = os.urandom(AES.block_size)
short_text = b"Just Text"
print("Short Text Tests")
print("----------------")
print(f"iv: {iv.hex()}")
print(f"plain text: '{short_text.decode()}'")
ciphertext_short = _aes.encrypt(short_text, iv)
plaintext_short = _aes.decrypt(ciphertext_short, iv)
print(f"Ciphertext Hex: {ciphertext_short.hex()}")
print(f"Plaintext: {plaintext_short.decode()}")
assert short_text == plaintext_short
print(bcolors.OK + "Short Text Test Passed Successfully" + bcolors.RESET)
print()
# test an arbitrary length phrase
iv = os.urandom(AES.block_size)
text = b"This Text is longer than one block"
print("Arbitrary Length Tests")
print("----------------------")
print(f"iv: {iv.hex()}")
print(f"plain text: '{text.decode()}'")
ciphertext = _aes.encrypt(text, iv)
plaintext = _aes.decrypt(ciphertext, iv)
print(f"Ciphertext Hex: {ciphertext.hex()}")
print(f"Plaintext: {plaintext.decode()}")
assert text == plaintext
print(bcolors.OK + "Arbitrary Length Text Test Passed Successfully" + bcolors.RESET)
print()
if __name__ == "__main__":
# test AES class
test()
+326
View File
@@ -0,0 +1,326 @@
# MIT License
# Copyright (c) 2021 Or Gur Arie
# 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 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.
## AES lookup tables
# resource: https://en.wikipedia.org/wiki/Rijndael_S-box
s_box = (
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,
)
inv_s_box = (
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D,
)
## AES AddRoundKey
# Round constants https://en.wikipedia.org/wiki/AES_key_schedule#Round_constants
r_con = (
0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A,
0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A,
0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39,
)
def add_round_key(s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
## AES SubBytes
def sub_bytes(s):
for i in range(4):
for j in range(4):
s[i][j] = s_box[s[i][j]]
def inv_sub_bytes(s):
for i in range(4):
for j in range(4):
s[i][j] = inv_s_box[s[i][j]]
## AES ShiftRows
def shift_rows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3]
def inv_shift_rows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3]
## AES MixColumns
# learned from http://cs.ucsb.edu/~koc/cs178/projects/JT/aes.c
xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def mix_single_column(a):
# see Sec 4.1.2 in The Design of Rijndael
t = a[0] ^ a[1] ^ a[2] ^ a[3]
u = a[0]
a[0] ^= t ^ xtime(a[0] ^ a[1])
a[1] ^= t ^ xtime(a[1] ^ a[2])
a[2] ^= t ^ xtime(a[2] ^ a[3])
a[3] ^= t ^ xtime(a[3] ^ u)
def mix_columns(s):
for i in range(4):
mix_single_column(s[i])
def inv_mix_columns(s):
# see Sec 4.1.3 in The Design of Rijndael
for i in range(4):
u = xtime(xtime(s[i][0] ^ s[i][2]))
v = xtime(xtime(s[i][1] ^ s[i][3]))
s[i][0] ^= u
s[i][1] ^= v
s[i][2] ^= u
s[i][3] ^= v
mix_columns(s)
## AES Bytes
def bytes2matrix(text):
""" Converts a 16-byte array into a 4x4 matrix. """
return [list(text[i:i+4]) for i in range(0, len(text), 4)]
def matrix2bytes(matrix):
""" Converts a 4x4 matrix into a 16-byte array. """
return bytes(sum(matrix, []))
def xor_bytes(a, b):
""" Returns a new byte array with the elements xor'ed. """
return bytes(i^j for i, j in zip(a, b))
def split_blocks(message, block_size=16, require_padding=True):
assert len(message) % block_size == 0 or not require_padding
return [message[i:i+16] for i in range(0, len(message), block_size)]
class AES128:
# AES-128 block size
block_size = 16
# AES-128 encrypts messages with 10 rounds
_rounds = 10
# initiate the AES objecy
def __init__(self, key):
"""
Initializes the object with a given key.
"""
# make sure key length is right
assert len(key) == AES128.block_size
# ExpandKey
self._round_keys = self._expand_key(key)
# will perform the AES ExpandKey phase
def _expand_key(self, master_key):
"""
Expands and returns a list of key matrices for the given master_key.
"""
# Initialize round keys with raw key material.
key_columns = bytes2matrix(master_key)
iteration_size = len(master_key) // 4
# Each iteration has exactly as many columns as the key material.
i = 1
while len(key_columns) < (self._rounds + 1) * 4:
# Copy previous word.
word = list(key_columns[-1])
# Perform schedule_core once every "row".
if len(key_columns) % iteration_size == 0:
# Circular shift.
word.append(word.pop(0))
# Map to S-BOX.
word = [s_box[b] for b in word]
# XOR with first byte of R-CON, since the others bytes of R-CON are 0.
word[0] ^= r_con[i]
i += 1
elif len(master_key) == 32 and len(key_columns) % iteration_size == 4:
# Run word through S-box in the fourth iteration when using a
# 256-bit key.
word = [s_box[b] for b in word]
# XOR with equivalent word from previous iteration.
word = bytes(i^j for i, j in zip(word, key_columns[-iteration_size]))
key_columns.append(word)
# Group key words in 4x4 byte matrices.
return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)]
# encrypt a single block of data with AES
def _encrypt_block(self, plaintext):
"""
Encrypts a single block of 16 byte long plaintext.
"""
# length of a single block
assert len(plaintext) == AES128.block_size
# perform on a matrix
state = bytes2matrix(plaintext)
# AddRoundKey
add_round_key(state, self._round_keys[0])
# 9 main rounds
for i in range(1, self._rounds):
# SubBytes
sub_bytes(state)
# ShiftRows
shift_rows(state)
# MixCols
mix_columns(state)
# AddRoundKey
add_round_key(state, self._round_keys[i])
# last round, w/t AddRoundKey step
sub_bytes(state)
shift_rows(state)
add_round_key(state, self._round_keys[-1])
# return the encrypted matrix as bytes
return matrix2bytes(state)
# decrypt a single block of data with AES
def _decrypt_block(self, ciphertext):
"""
Decrypts a single block of 16 byte long ciphertext.
"""
# length of a single block
assert len(ciphertext) == AES128.block_size
# perform on a matrix
state = bytes2matrix(ciphertext)
# in reverse order, last round is first
add_round_key(state, self._round_keys[-1])
inv_shift_rows(state)
inv_sub_bytes(state)
for i in range(self._rounds - 1, 0, -1):
# nain rounds
add_round_key(state, self._round_keys[i])
inv_mix_columns(state)
inv_shift_rows(state)
inv_sub_bytes(state)
# initial AddRoundKey phase
add_round_key(state, self._round_keys[0])
# return bytes
return matrix2bytes(state)
# will encrypt the entire data
def encrypt(self, plaintext, iv):
"""
Encrypts `plaintext` using CBC mode and PKCS#7 padding, with the given
initialization vector (iv).
"""
# iv length must be same as block size
assert len(iv) == AES128.block_size
assert len(plaintext) % AES128.block_size == 0
ciphertext_blocks = []
previous = iv
for plaintext_block in split_blocks(plaintext):
# in CBC mode every block is XOR'd with the previous block
xorred = xor_bytes(plaintext_block, previous)
# encrypt current block
block = self._encrypt_block(xorred)
previous = block
# append to ciphertext
ciphertext_blocks.append(block)
# return as bytes
return b''.join(ciphertext_blocks)
# will decrypt the entire data
def decrypt(self, ciphertext, iv):
"""
Decrypts `ciphertext` using CBC mode and PKCS#7 padding, with the given
initialization vector (iv).
"""
# iv length must be same as block size
assert len(iv) == AES128.block_size
plaintext_blocks = []
previous = iv
for ciphertext_block in split_blocks(ciphertext):
# in CBC mode every block is XOR'd with the previous block
xorred = xor_bytes(previous, self._decrypt_block(ciphertext_block))
# append plaintext
plaintext_blocks.append(xorred)
previous = ciphertext_block
return b''.join(plaintext_blocks)
@@ -1,17 +1,17 @@
# MIT License # MIT License
#
# Copyright (c) 2021 Or Gur Arie # Copyright (c) 2024 BoppreH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights # in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all # The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software. # copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -20,12 +20,6 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE. # SOFTWARE.
'''
Utils class for AES encryption / decryption
'''
## AES lookup tables
# resource: https://en.wikipedia.org/wiki/Rijndael_S-box
s_box = ( s_box = (
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
@@ -64,53 +58,33 @@ inv_s_box = (
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D,
) )
## AES AddRoundKey
# Round constants https://en.wikipedia.org/wiki/AES_key_schedule#Round_constants
r_con = (
0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A,
0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A,
0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39,
)
def add_round_key(s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
## AES SubBytes
def sub_bytes(s): def sub_bytes(s):
for i in range(4): for i in range(4):
for j in range(4): for j in range(4):
s[i][j] = s_box[s[i][j]] s[i][j] = s_box[s[i][j]]
def inv_sub_bytes(s): def inv_sub_bytes(s):
for i in range(4): for i in range(4):
for j in range(4): for j in range(4):
s[i][j] = inv_s_box[s[i][j]] s[i][j] = inv_s_box[s[i][j]]
## AES ShiftRows
def shift_rows(s): def shift_rows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1] s[0][1], s[1][1], s[2][1], s[3][1] = s[1][1], s[2][1], s[3][1], s[0][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2] s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3] s[0][3], s[1][3], s[2][3], s[3][3] = s[3][3], s[0][3], s[1][3], s[2][3]
def inv_shift_rows(s): def inv_shift_rows(s):
s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1] s[0][1], s[1][1], s[2][1], s[3][1] = s[3][1], s[0][1], s[1][1], s[2][1]
s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2] s[0][2], s[1][2], s[2][2], s[3][2] = s[2][2], s[3][2], s[0][2], s[1][2]
s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3] s[0][3], s[1][3], s[2][3], s[3][3] = s[1][3], s[2][3], s[3][3], s[0][3]
def add_round_key(s, k):
for i in range(4):
for j in range(4):
s[i][j] ^= k[i][j]
## AES MixColumns
# learned from http://cs.ucsb.edu/~koc/cs178/projects/JT/aes.c
xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1) xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)
def mix_single_column(a): def mix_single_column(a):
# see Sec 4.1.2 in The Design of Rijndael # see Sec 4.1.2 in The Design of Rijndael
t = a[0] ^ a[1] ^ a[2] ^ a[3] t = a[0] ^ a[1] ^ a[2] ^ a[3]
@@ -120,12 +94,10 @@ def mix_single_column(a):
a[2] ^= t ^ xtime(a[2] ^ a[3]) a[2] ^= t ^ xtime(a[2] ^ a[3])
a[3] ^= t ^ xtime(a[3] ^ u) a[3] ^= t ^ xtime(a[3] ^ u)
def mix_columns(s): def mix_columns(s):
for i in range(4): for i in range(4):
mix_single_column(s[i]) mix_single_column(s[i])
def inv_mix_columns(s): def inv_mix_columns(s):
# see Sec 4.1.3 in The Design of Rijndael # see Sec 4.1.3 in The Design of Rijndael
for i in range(4): for i in range(4):
@@ -138,22 +110,127 @@ def inv_mix_columns(s):
mix_columns(s) mix_columns(s)
r_con = (
## AES Bytes 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
def bytes2matrix(text): 0x80, 0x1B, 0x36, 0x6C, 0xD8, 0xAB, 0x4D, 0x9A,
""" Converts a 16-byte array into a 4x4 matrix. """ 0x2F, 0x5E, 0xBC, 0x63, 0xC6, 0x97, 0x35, 0x6A,
return [list(text[i:i+4]) for i in range(0, len(text), 4)] 0xD4, 0xB3, 0x7D, 0xFA, 0xEF, 0xC5, 0x91, 0x39,
)
def matrix2bytes(matrix):
""" Converts a 4x4 matrix into a 16-byte array. """
return bytes(sum(matrix, []))
def xor_bytes(a, b): def bytes2matrix(text): return [list(text[i:i+4]) for i in range(0, len(text), 4)]
""" Returns a new byte array with the elements xor'ed. """ def matrix2bytes(matrix): return bytes(sum(matrix, []))
return bytes(i^j for i, j in zip(a, b)) def xor_bytes(a, b): return bytes(i^j for i, j in zip(a, b))
def inc_bytes(a):
out = list(a)
for i in reversed(range(len(out))):
if out[i] == 0xFF:
out[i] = 0
else:
out[i] += 1
break
return bytes(out)
def split_blocks(message, block_size=16, require_padding=True): def split_blocks(message, block_size=16, require_padding=True):
assert len(message) % block_size == 0 or not require_padding assert len(message) % block_size == 0 or not require_padding
return [message[i:i+16] for i in range(0, len(message), block_size)] return [message[i:i+16] for i in range(0, len(message), block_size)]
class AES256:
rounds_by_key_size = {32: 14}
def __init__(self, master_key):
assert len(master_key) in AES256.rounds_by_key_size
self.n_rounds = AES256.rounds_by_key_size[len(master_key)]
self._key_matrices = self._expand_key(master_key)
def _expand_key(self, master_key):
# Initialize round keys with raw key material.
key_columns = bytes2matrix(master_key)
iteration_size = len(master_key) // 4
i = 1
while len(key_columns) < (self.n_rounds + 1) * 4:
# Copy previous word.
word = list(key_columns[-1])
# Perform schedule_core once every "row".
if len(key_columns) % iteration_size == 0:
# Circular shift.
word.append(word.pop(0))
# Map to S-BOX.
word = [s_box[b] for b in word]
# XOR with first byte of R-CON, since the others bytes of R-CON are 0.
word[0] ^= r_con[i]
i += 1
elif len(master_key) == 32 and len(key_columns) % iteration_size == 4:
# Run word through S-box in the fourth iteration when using a
# 256-bit key.
word = [s_box[b] for b in word]
# XOR with equivalent word from previous iteration.
word = xor_bytes(word, key_columns[-iteration_size])
key_columns.append(word)
# Group key words in 4x4 byte matrices.
return [key_columns[4*i : 4*(i+1)] for i in range(len(key_columns) // 4)]
def encrypt_block(self, plaintext):
assert len(plaintext) == 16
plain_state = bytes2matrix(plaintext)
add_round_key(plain_state, self._key_matrices[0])
for i in range(1, self.n_rounds):
sub_bytes(plain_state)
shift_rows(plain_state)
mix_columns(plain_state)
add_round_key(plain_state, self._key_matrices[i])
sub_bytes(plain_state)
shift_rows(plain_state)
add_round_key(plain_state, self._key_matrices[-1])
return matrix2bytes(plain_state)
def decrypt_block(self, ciphertext):
assert len(ciphertext) == 16
cipher_state = bytes2matrix(ciphertext)
add_round_key(cipher_state, self._key_matrices[-1])
inv_shift_rows(cipher_state)
inv_sub_bytes(cipher_state)
for i in range(self.n_rounds - 1, 0, -1):
add_round_key(cipher_state, self._key_matrices[i])
inv_mix_columns(cipher_state)
inv_shift_rows(cipher_state)
inv_sub_bytes(cipher_state)
add_round_key(cipher_state, self._key_matrices[0])
return matrix2bytes(cipher_state)
def encrypt_cbc(self, plaintext, iv):
if len(iv) != 16: raise ValueError(f"Invalid IV length: {len(iv)}")
blocks = []
previous = iv
for plaintext_block in split_blocks(plaintext):
block = self.encrypt_block(xor_bytes(plaintext_block, previous))
blocks.append(block)
previous = block
return b''.join(blocks)
def decrypt_cbc(self, ciphertext, iv):
if len(iv) != 16: raise ValueError(f"Invalid IV length: {len(iv)}")
blocks = []
previous = iv
for ciphertext_block in split_blocks(ciphertext):
blocks.append(xor_bytes(previous, self.decrypt_block(ciphertext_block)))
previous = ciphertext_block
return b''.join(blocks)
__all__ = ["AES256"]
+29 -16
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -202,12 +210,16 @@ class Destination:
def _persist_ratchets(self): def _persist_ratchets(self):
try: try:
with self.ratchet_file_lock: with self.ratchet_file_lock:
temp_write_path = self.ratchets_path+".tmp"
packed_ratchets = umsgpack.packb(self.ratchets) packed_ratchets = umsgpack.packb(self.ratchets)
persisted_data = {"signature": self.sign(packed_ratchets), "ratchets": packed_ratchets} persisted_data = {"signature": self.sign(packed_ratchets), "ratchets": packed_ratchets}
ratchets_file = open(self.ratchets_path, "wb") ratchets_file = open(temp_write_path, "wb")
ratchets_file.write(umsgpack.packb(persisted_data)) ratchets_file.write(umsgpack.packb(persisted_data))
ratchets_file.close() ratchets_file.close()
if os.path.isfile(self.ratchets_path): os.unlink(self.ratchets_path)
os.rename(temp_write_path, self.ratchets_path)
except Exception as e: except Exception as e:
RNS.trace_exception(e)
self.ratchets = None self.ratchets = None
self.ratchets_path = None self.ratchets_path = None
raise OSError("Could not write ratchet file contents for "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) raise OSError("Could not write ratchet file contents for "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
@@ -365,7 +377,7 @@ class Destination:
else: else:
self.proof_strategy = proof_strategy self.proof_strategy = proof_strategy
def register_request_handler(self, path, response_generator = None, allow = ALLOW_NONE, allowed_list = None): def register_request_handler(self, path, response_generator = None, allow = ALLOW_NONE, allowed_list = None, auto_compress = True):
""" """
Registers a request handler. Registers a request handler.
@@ -373,17 +385,15 @@ class Destination:
:param response_generator: A function or method with the signature *response_generator(path, data, request_id, link_id, remote_identity, requested_at)* to be called. Whatever this funcion returns will be sent as a response to the requester. If the function returns ``None``, no response will be sent. :param response_generator: A function or method with the signature *response_generator(path, data, request_id, link_id, remote_identity, requested_at)* to be called. Whatever this funcion returns will be sent as a response to the requester. If the function returns ``None``, no response will be sent.
:param allow: One of ``RNS.Destination.ALLOW_NONE``, ``RNS.Destination.ALLOW_ALL`` or ``RNS.Destination.ALLOW_LIST``. If ``RNS.Destination.ALLOW_LIST`` is set, the request handler will only respond to requests for identified peers in the supplied list. :param allow: One of ``RNS.Destination.ALLOW_NONE``, ``RNS.Destination.ALLOW_ALL`` or ``RNS.Destination.ALLOW_LIST``. If ``RNS.Destination.ALLOW_LIST`` is set, the request handler will only respond to requests for identified peers in the supplied list.
:param allowed_list: A list of *bytes-like* :ref:`RNS.Identity<api-identity>` hashes. :param allowed_list: A list of *bytes-like* :ref:`RNS.Identity<api-identity>` hashes.
:param auto_compress: If ``True`` or ``False``, determines whether automatic compression of responses should be carried out. If set to an integer value, responses will only be auto-compressed if under this size in bytes. If omitted, the default compression settings will be followed.
:raises: ``ValueError`` if any of the supplied arguments are invalid. :raises: ``ValueError`` if any of the supplied arguments are invalid.
""" """
if path == None or path == "": if path == None or path == "": raise ValueError("Invalid path specified")
raise ValueError("Invalid path specified") elif not callable(response_generator): raise ValueError("Invalid response generator specified")
elif not callable(response_generator): elif not allow in Destination.request_policies: raise ValueError("Invalid request policy")
raise ValueError("Invalid response generator specified")
elif not allow in Destination.request_policies:
raise ValueError("Invalid request policy")
else: else:
path_hash = RNS.Identity.truncated_hash(path.encode("utf-8")) path_hash = RNS.Identity.truncated_hash(path.encode("utf-8"))
request_handler = [path, response_generator, allow, allowed_list] request_handler = [path, response_generator, allow, allowed_list, auto_compress]
self.request_handlers[path_hash] = request_handler self.request_handlers[path_hash] = request_handler
def deregister_request_handler(self, path): def deregister_request_handler(self, path):
@@ -407,7 +417,8 @@ class Destination:
else: else:
plaintext = self.decrypt(packet.data) plaintext = self.decrypt(packet.data)
packet.ratchet_id = self.latest_ratchet_id packet.ratchet_id = self.latest_ratchet_id
if plaintext != None: if plaintext == None: return False
else:
if packet.packet_type == RNS.Packet.DATA: if packet.packet_type == RNS.Packet.DATA:
if self.callbacks.packet != None: if self.callbacks.packet != None:
try: try:
@@ -415,6 +426,8 @@ class Destination:
except Exception as e: except Exception as e:
RNS.log("Error while executing receive callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Error while executing receive callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
return True
def incoming_link_request(self, data, packet): def incoming_link_request(self, data, packet):
if self.accept_link_requests: if self.accept_link_requests:
link = RNS.Link.validate_request(self, data, packet) link = RNS.Link.validate_request(self, data, packet)
@@ -450,6 +463,7 @@ class Destination:
self.ratchets_path = None self.ratchets_path = None
RNS.trace_exception(e) RNS.trace_exception(e)
raise OSError("Could not read ratchet file contents for "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) raise OSError("Could not read ratchet file contents for "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
else: else:
RNS.log("No existing ratchet data found, initialising new ratchet file for "+str(self), RNS.LOG_DEBUG) RNS.log("No existing ratchet data found, initialising new ratchet file for "+str(self), RNS.LOG_DEBUG)
self.ratchets = [] self.ratchets = []
@@ -475,7 +489,6 @@ class Destination:
self.latest_ratchet_time = 0 self.latest_ratchet_time = 0
self._reload_ratchets(ratchets_path) self._reload_ratchets(ratchets_path)
# TODO: Remove at some point
RNS.log("Ratchets enabled on "+str(self), RNS.LOG_DEBUG) RNS.log("Ratchets enabled on "+str(self), RNS.LOG_DEBUG)
return True return True
@@ -629,7 +642,7 @@ class Destination:
RNS.log(f"Decryption still failing after ratchet reload. The contained exception was: {e}", RNS.LOG_ERROR) RNS.log(f"Decryption still failing after ratchet reload. The contained exception was: {e}", RNS.LOG_ERROR)
raise e raise e
RNS.log("Decryption succeeded after ratchet reload", RNS.LOG_NOTICE) if decrypted: RNS.log("Decryption succeeded after ratchet reload", RNS.LOG_NOTICE)
return decrypted return decrypted
+62 -25
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors. # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -71,13 +79,16 @@ class Identity:
HASHLENGTH = 256 # In bits HASHLENGTH = 256 # In bits
SIGLENGTH = KEYSIZE # In bits SIGLENGTH = KEYSIZE # In bits
NAME_HASH_LENGTH = 80 NAME_HASH_LENGTH = 80
TRUNCATED_HASHLENGTH = RNS.Reticulum.TRUNCATED_HASHLENGTH TRUNCATED_HASHLENGTH = RNS.Reticulum.TRUNCATED_HASHLENGTH
""" """
Constant specifying the truncated hash length (in bits) used by Reticulum Constant specifying the truncated hash length (in bits) used by Reticulum
for addressable hashes and other purposes. Non-configurable. for addressable hashes and other purposes. Non-configurable.
""" """
DERIVED_KEY_LENGTH = 512//8
DERIVED_KEY_LENGTH_LEGACY = 256//8
# Storage # Storage
known_destinations = {} known_destinations = {}
known_ratchets = {} known_ratchets = {}
@@ -669,7 +680,7 @@ class Identity:
shared_key = ephemeral_key.exchange(target_public_key) shared_key = ephemeral_key.exchange(target_public_key)
derived_key = RNS.Cryptography.hkdf( derived_key = RNS.Cryptography.hkdf(
length=32, length=Identity.DERIVED_KEY_LENGTH,
derive_from=shared_key, derive_from=shared_key,
salt=self.get_salt(), salt=self.get_salt(),
context=self.get_context(), context=self.get_context(),
@@ -683,6 +694,45 @@ class Identity:
else: else:
raise KeyError("Encryption failed because identity does not hold a public key") raise KeyError("Encryption failed because identity does not hold a public key")
# Post 0.9.6 decryption will only accept AES-256
def __decrypt(self, shared_key, ciphertext):
derived_key = RNS.Cryptography.hkdf(
length=Identity.DERIVED_KEY_LENGTH,
derive_from=shared_key,
salt=self.get_salt(),
context=self.get_context())
token = Token(derived_key)
plaintext = token.decrypt(ciphertext)
return plaintext
# This handles decryption during migration to AES-256 where
# older instances may still use AES-128. If decryption fails
# initially, AES-128 will be attempted as a fallback mode.
# This handler will be removed in RNS 0.9.6.
def __migration_decrypt(self, shared_key, ciphertext):
try:
derived_key = RNS.Cryptography.hkdf(
length=Identity.DERIVED_KEY_LENGTH,
derive_from=shared_key,
salt=self.get_salt(),
context=self.get_context())
token = Token(derived_key)
plaintext = token.decrypt(ciphertext)
except Exception as e:
# RNS.log("Decryption failed, attempting legacy mode fallback", RNS.LOG_DEBUG)
derived_key = RNS.Cryptography.hkdf(
length=Identity.DERIVED_KEY_LENGTH_LEGACY,
derive_from=shared_key,
salt=self.get_salt(),
context=self.get_context())
token = Token(derived_key)
plaintext = token.decrypt(ciphertext)
return plaintext
def decrypt(self, ciphertext_token, ratchets=None, enforce_ratchets=False, ratchet_id_receiver=None): def decrypt(self, ciphertext_token, ratchets=None, enforce_ratchets=False, ratchet_id_receiver=None):
""" """
@@ -692,6 +742,7 @@ class Identity:
:returns: Plaintext as *bytes*, or *None* if decryption fails. :returns: Plaintext as *bytes*, or *None* if decryption fails.
:raises: *KeyError* if the instance does not hold a private key. :raises: *KeyError* if the instance does not hold a private key.
""" """
if self.prv != None: if self.prv != None:
if len(ciphertext_token) > Identity.KEYSIZE//8//2: if len(ciphertext_token) > Identity.KEYSIZE//8//2:
plaintext = None plaintext = None
@@ -706,15 +757,7 @@ class Identity:
ratchet_prv = X25519PrivateKey.from_private_bytes(ratchet) ratchet_prv = X25519PrivateKey.from_private_bytes(ratchet)
ratchet_id = Identity._get_ratchet_id(ratchet_prv.public_key().public_bytes()) ratchet_id = Identity._get_ratchet_id(ratchet_prv.public_key().public_bytes())
shared_key = ratchet_prv.exchange(peer_pub) shared_key = ratchet_prv.exchange(peer_pub)
derived_key = RNS.Cryptography.hkdf( plaintext = self.__migration_decrypt(shared_key, ciphertext)
length=32,
derive_from=shared_key,
salt=self.get_salt(),
context=self.get_context(),
)
token = Token(derived_key)
plaintext = token.decrypt(ciphertext)
if ratchet_id_receiver: if ratchet_id_receiver:
ratchet_id_receiver.latest_ratchet_id = ratchet_id ratchet_id_receiver.latest_ratchet_id = ratchet_id
@@ -731,15 +774,8 @@ class Identity:
if plaintext == None: if plaintext == None:
shared_key = self.prv.exchange(peer_pub) shared_key = self.prv.exchange(peer_pub)
derived_key = RNS.Cryptography.hkdf( plaintext = self.__migration_decrypt(shared_key, ciphertext)
length=32,
derive_from=shared_key,
salt=self.get_salt(),
context=self.get_context(),
)
token = Token(derived_key)
plaintext = token.decrypt(ciphertext)
if ratchet_id_receiver: if ratchet_id_receiver:
ratchet_id_receiver.latest_ratchet_id = None ratchet_id_receiver.latest_ratchet_id = None
@@ -748,7 +784,8 @@ class Identity:
if ratchet_id_receiver: if ratchet_id_receiver:
ratchet_id_receiver.latest_ratchet_id = None ratchet_id_receiver.latest_ratchet_id = None
return plaintext; return plaintext
else: else:
RNS.log("Decryption failed because the token size was invalid.", RNS.LOG_DEBUG) RNS.log("Decryption failed because the token size was invalid.", RNS.LOG_DEBUG)
return None return None
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2022 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+59 -45
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -311,7 +319,8 @@ class BackboneInterface(Interface):
client_socket, address = server_socket.accept() client_socket, address = server_socket.accept()
client_socket.setblocking(0) client_socket.setblocking(0)
if not owner_interface.incoming_connection(client_socket): if not owner_interface.incoming_connection(client_socket):
client_socket.close() try: client_socket.close()
except Exception as e: RNS.log(f"Error while closing socket for failed incoming connection: {e}", RNS.LOG_ERROR)
elif fileno == server_socket.fileno() and (event & select.EPOLLHUP): elif fileno == server_socket.fileno() and (event & select.EPOLLHUP):
try: BackboneInterface.deregister_fileno(fileno) try: BackboneInterface.deregister_fileno(fileno)
@@ -329,48 +338,53 @@ class BackboneInterface(Interface):
def incoming_connection(self, socket): def incoming_connection(self, socket):
RNS.log("Accepting incoming connection", RNS.LOG_VERBOSE) RNS.log("Accepting incoming connection", RNS.LOG_VERBOSE)
spawned_configuration = {"name": "Client on "+self.name, "target_host": None, "target_port": None} try:
spawned_interface = BackboneClientInterface(self.owner, spawned_configuration, connected_socket=socket) spawned_configuration = {"name": "Client on "+self.name, "target_host": None, "target_port": None}
spawned_interface.OUT = self.OUT spawned_interface = BackboneClientInterface(self.owner, spawned_configuration, connected_socket=socket)
spawned_interface.IN = self.IN spawned_interface.OUT = self.OUT
spawned_interface.socket = socket spawned_interface.IN = self.IN
spawned_interface.target_ip = socket.getpeername()[0] spawned_interface.socket = socket
spawned_interface.target_port = str(socket.getpeername()[1]) spawned_interface.target_ip = socket.getpeername()[0]
spawned_interface.parent_interface = self spawned_interface.target_port = str(socket.getpeername()[1])
spawned_interface.bitrate = self.bitrate spawned_interface.parent_interface = self
spawned_interface.optimise_mtu() spawned_interface.bitrate = self.bitrate
spawned_interface.optimise_mtu()
spawned_interface.ifac_size = self.ifac_size
spawned_interface.ifac_netname = self.ifac_netname spawned_interface.ifac_size = self.ifac_size
spawned_interface.ifac_netkey = self.ifac_netkey spawned_interface.ifac_netname = self.ifac_netname
if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None: spawned_interface.ifac_netkey = self.ifac_netkey
ifac_origin = b"" if spawned_interface.ifac_netname != None or spawned_interface.ifac_netkey != None:
if spawned_interface.ifac_netname != None: ifac_origin = b""
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netname.encode("utf-8")) if spawned_interface.ifac_netname != None:
if spawned_interface.ifac_netkey != None: ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netname.encode("utf-8"))
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netkey.encode("utf-8")) if spawned_interface.ifac_netkey != None:
ifac_origin += RNS.Identity.full_hash(spawned_interface.ifac_netkey.encode("utf-8"))
ifac_origin_hash = RNS.Identity.full_hash(ifac_origin) ifac_origin_hash = RNS.Identity.full_hash(ifac_origin)
spawned_interface.ifac_key = RNS.Cryptography.hkdf( spawned_interface.ifac_key = RNS.Cryptography.hkdf(
length=64, length=64,
derive_from=ifac_origin_hash, derive_from=ifac_origin_hash,
salt=RNS.Reticulum.IFAC_SALT, salt=RNS.Reticulum.IFAC_SALT,
context=None context=None
) )
spawned_interface.ifac_identity = RNS.Identity.from_bytes(spawned_interface.ifac_key) spawned_interface.ifac_identity = RNS.Identity.from_bytes(spawned_interface.ifac_key)
spawned_interface.ifac_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key)) spawned_interface.ifac_signature = spawned_interface.ifac_identity.sign(RNS.Identity.full_hash(spawned_interface.ifac_key))
spawned_interface.announce_rate_target = self.announce_rate_target spawned_interface.announce_rate_target = self.announce_rate_target
spawned_interface.announce_rate_grace = self.announce_rate_grace spawned_interface.announce_rate_grace = self.announce_rate_grace
spawned_interface.announce_rate_penalty = self.announce_rate_penalty spawned_interface.announce_rate_penalty = self.announce_rate_penalty
spawned_interface.mode = self.mode spawned_interface.mode = self.mode
spawned_interface.HW_MTU = self.HW_MTU spawned_interface.HW_MTU = self.HW_MTU
spawned_interface.online = True spawned_interface.online = True
RNS.log("Spawned new BackboneClient Interface: "+str(spawned_interface), RNS.LOG_VERBOSE) RNS.log("Spawned new BackboneClient Interface: "+str(spawned_interface), RNS.LOG_VERBOSE)
RNS.Transport.interfaces.append(spawned_interface) RNS.Transport.interfaces.append(spawned_interface)
while spawned_interface in self.spawned_interfaces: self.spawned_interfaces.remove(spawned_interface) while spawned_interface in self.spawned_interfaces: self.spawned_interfaces.remove(spawned_interface)
self.spawned_interfaces.append(spawned_interface) self.spawned_interfaces.append(spawned_interface)
BackboneInterface.add_client_socket(socket, spawned_interface) BackboneInterface.add_client_socket(socket, spawned_interface)
except Exception as e:
RNS.log(f"An error occurred while accepting incoming connection on {self}: {e}", RNS.LOG_ERROR)
return False
return True return True
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+21 -13
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -127,23 +135,23 @@ class Interface:
def optimise_mtu(self): def optimise_mtu(self):
if self.AUTOCONFIGURE_MTU: if self.AUTOCONFIGURE_MTU:
if self.bitrate > 500_000_000: if self.bitrate >= 1_000_000_000:
self.HW_MTU = 524288 self.HW_MTU = 524288
elif self.bitrate > 16_000_000: elif self.bitrate > 750_000_000:
self.HW_MTU = 262144 self.HW_MTU = 262144
elif self.bitrate > 8_000_000: elif self.bitrate > 400_000_000:
self.HW_MTU = 131072 self.HW_MTU = 131072
elif self.bitrate > 4_000_000: elif self.bitrate > 200_000_000:
self.HW_MTU = 65536 self.HW_MTU = 65536
elif self.bitrate > 2_000_000: elif self.bitrate > 100_000_000:
self.HW_MTU = 32768 self.HW_MTU = 32768
elif self.bitrate > 1_000_000: elif self.bitrate > 10_000_000:
self.HW_MTU = 16384 self.HW_MTU = 16384
elif self.bitrate > 500_000: elif self.bitrate > 5_000_000:
self.HW_MTU = 8192 self.HW_MTU = 8192
elif self.bitrate > 250_000: elif self.bitrate > 2_000_000:
self.HW_MTU = 4096 self.HW_MTU = 4096
elif self.bitrate > 125_000: elif self.bitrate > 1_000_000:
self.HW_MTU = 2048 self.HW_MTU = 2048
elif self.bitrate > 62_500: elif self.bitrate > 62_500:
self.HW_MTU = 1024 self.HW_MTU = 1024
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+16 -8
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -62,7 +70,7 @@ class LocalClientInterface(Interface):
self.HW_MTU = 262144 self.HW_MTU = 262144
self.online = False self.online = False
if socket_path != None and RNS.vendor.platformutils.use_af_unix(): self.socket_path = f"\0rns/{socket_path}" if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}"
else: self.socket_path = None else: self.socket_path = None
self.IN = True self.IN = True
@@ -329,8 +337,8 @@ class LocalClientInterface(Interface):
def __str__(self): def __str__(self):
if self.socket_path: return "Shared Instance["+str(self.socket_path.replace("\0", ""))+"]" if self.socket_path: return "LocalInterface["+str(self.socket_path.replace("\0", ""))+"]"
else: return "Shared Instance["+str(self.target_port)+"]" else: return "LocalInterface["+str(self.target_port)+"]"
class LocalServerInterface(Interface): class LocalServerInterface(Interface):
@@ -342,7 +350,7 @@ class LocalServerInterface(Interface):
self.online = False self.online = False
self.clients = 0 self.clients = 0
if socket_path != None and RNS.vendor.platformutils.use_af_unix(): self.socket_path = f"\0rns/{socket_path}" if socket_path != None and RNS.Reticulum.get_instance().use_af_unix: self.socket_path = f"\0rns/{socket_path}"
else: self.socket_path = None else: self.socket_path = None
self.IN = True self.IN = True
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2024 Jacob Eva. Adapted from the RNodeInterface by Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+1 -1
View File
@@ -1,7 +1,7 @@
# MIT License # MIT License
# #
# Copyright (c) 2025 Mark Qvist
# Copyright (c) 2014 Stefan C. Mueller # Copyright (c) 2014 Stefan C. Mueller
# Copyright (c) 2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
+182 -78
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors. # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -32,6 +40,7 @@ import struct
import math import math
import time import time
import RNS import RNS
import io
class LinkCallbacks: class LinkCallbacks:
def __init__(self): def __init__(self):
@@ -71,19 +80,23 @@ class Link:
LINK_MTU_SIZE = 3 LINK_MTU_SIZE = 3
TRAFFIC_TIMEOUT_MIN_MS = 5 TRAFFIC_TIMEOUT_MIN_MS = 5
TRAFFIC_TIMEOUT_FACTOR = 6 TRAFFIC_TIMEOUT_FACTOR = 6
KEEPALIVE_MAX_RTT = 1.75
KEEPALIVE_TIMEOUT_FACTOR = 4 KEEPALIVE_TIMEOUT_FACTOR = 4
""" """
RTT timeout factor used in link timeout calculation. RTT timeout factor used in link timeout calculation.
""" """
STALE_GRACE = 2 STALE_GRACE = 5
""" """
Grace period in seconds used in link timeout calculation. Grace period in seconds used in link timeout calculation.
""" """
KEEPALIVE = 360 KEEPALIVE_MAX = 360
KEEPALIVE_MIN = 5
KEEPALIVE = KEEPALIVE_MAX
""" """
Interval for sending keep-alive packets on established links in seconds. Default interval for sending keep-alive packets on established links in seconds.
""" """
STALE_TIME = 2*KEEPALIVE STALE_FACTOR = 2
STALE_TIME = STALE_FACTOR*KEEPALIVE
""" """
If no traffic or keep-alive packets are received within this period, the If no traffic or keep-alive packets are received within this period, the
link will be marked as stale, and a final keep-alive packet will be sent. link will be marked as stale, and a final keep-alive packet will be sent.
@@ -92,39 +105,82 @@ class Link:
and will be torn down. and will be torn down.
""" """
PENDING = 0x00 WATCHDOG_MAX_SLEEP = 5
HANDSHAKE = 0x01
ACTIVE = 0x02
STALE = 0x03
CLOSED = 0x04
TIMEOUT = 0x01 PENDING = 0x00
INITIATOR_CLOSED = 0x02 HANDSHAKE = 0x01
DESTINATION_CLOSED = 0x03 ACTIVE = 0x02
STALE = 0x03
CLOSED = 0x04
ACCEPT_NONE = 0x00 TIMEOUT = 0x01
ACCEPT_APP = 0x01 INITIATOR_CLOSED = 0x02
ACCEPT_ALL = 0x02 DESTINATION_CLOSED = 0x03
ACCEPT_NONE = 0x00
ACCEPT_APP = 0x01
ACCEPT_ALL = 0x02
resource_strategies = [ACCEPT_NONE, ACCEPT_APP, ACCEPT_ALL] resource_strategies = [ACCEPT_NONE, ACCEPT_APP, ACCEPT_ALL]
MODE_AES128_CBC = 0x00
MODE_AES256_CBC = 0x01
MODE_AES256_GCM = 0x02
MODE_OTP_RESERVED = 0x03
MODE_PQ_RESERVED_1 = 0x04
MODE_PQ_RESERVED_2 = 0x05
MODE_PQ_RESERVED_3 = 0x06
MODE_PQ_RESERVED_4 = 0x07
ENABLED_MODES = [MODE_AES128_CBC, MODE_AES256_CBC]
MODE_DEFAULT = MODE_AES256_CBC
MODE_DESCRIPTIONS = {MODE_AES128_CBC: "AES_128_CBC",
MODE_AES256_CBC: "AES_256_CBC",
MODE_AES256_GCM: "MODE_AES256_GCM",
MODE_OTP_RESERVED: "MODE_OTP_RESERVED",
MODE_PQ_RESERVED_1: "MODE_PQ_RESERVED_1",
MODE_PQ_RESERVED_2: "MODE_PQ_RESERVED_2",
MODE_PQ_RESERVED_3: "MODE_PQ_RESERVED_3",
MODE_PQ_RESERVED_4: "MODE_PQ_RESERVED_4"}
MTU_BYTEMASK = 0x1FFFFF
MODE_BYTEMASK = 0xE0
@staticmethod @staticmethod
def mtu_bytes(mtu): def signalling_bytes(mtu, mode):
return struct.pack(">I", mtu & 0xFFFFFF)[1:] if not mode in Link.ENABLED_MODES: raise TypeError(f"Requested link mode {Link.MODE_DESCRIPTIONS[mode]} not enabled")
signalling_value = (mtu & Link.MTU_BYTEMASK)+(((mode<<5) & Link.MODE_BYTEMASK)<<16)
return struct.pack(">I", signalling_value)[1:]
@staticmethod @staticmethod
def mtu_from_lr_packet(packet): def mtu_from_lr_packet(packet):
if len(packet.data) == Link.ECPUBSIZE+Link.LINK_MTU_SIZE: if len(packet.data) == Link.ECPUBSIZE+Link.LINK_MTU_SIZE:
return (packet.data[Link.ECPUBSIZE] << 16) + (packet.data[Link.ECPUBSIZE+1] << 8) + (packet.data[Link.ECPUBSIZE+2]) return (packet.data[Link.ECPUBSIZE] << 16) + (packet.data[Link.ECPUBSIZE+1] << 8) + (packet.data[Link.ECPUBSIZE+2]) & Link.MTU_BYTEMASK
else: else: return None
return None
@staticmethod @staticmethod
def mtu_from_lp_packet(packet): def mtu_from_lp_packet(packet):
if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE: if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE:
mtu_bytes = packet.data[RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE] mtu_bytes = packet.data[RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE]
return (mtu_bytes[0] << 16) + (mtu_bytes[1] << 8) + (mtu_bytes[2]) return (mtu_bytes[0] << 16) + (mtu_bytes[1] << 8) + (mtu_bytes[2]) & Link.MTU_BYTEMASK
else: else: return None
return None
@staticmethod
def mode_byte(mode):
if mode in Link.ENABLED_MODES: return (mode << 5) & Link.MODE_BYTEMASK
else: raise TypeError(f"Requested link mode {mode} not enabled")
@staticmethod
def mode_from_lr_packet(packet):
if len(packet.data) > Link.ECPUBSIZE:
mode = (packet.data[Link.ECPUBSIZE] & Link.MODE_BYTEMASK) >> 5
return mode
else: return Link.MODE_DEFAULT
@staticmethod
def mode_from_lp_packet(packet):
if len(packet.data) > RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2:
mode = packet.data[RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2] >> 5
return mode
else: return Link.MODE_DEFAULT
@staticmethod @staticmethod
def validate_request(owner, data, packet): def validate_request(owner, data, packet):
@@ -141,6 +197,11 @@ class Link:
RNS.trace_exception(e) RNS.trace_exception(e)
link.mtu = RNS.Reticulum.MTU link.mtu = RNS.Reticulum.MTU
link.mode = Link.mode_from_lr_packet(packet)
# TODO: Remove debug
RNS.log(f"Incoming link request with mode {Link.MODE_DESCRIPTIONS[link.mode]}", RNS.LOG_DEBUG)
link.update_mdu() link.update_mdu()
link.destination = packet.destination link.destination = packet.destination
link.establishment_timeout = Link.ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, packet.hops) + Link.KEEPALIVE link.establishment_timeout = Link.ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, packet.hops) + Link.KEEPALIVE
@@ -169,9 +230,9 @@ class Link:
return None return None
def __init__(self, destination=None, established_callback = None, closed_callback = None, owner=None, peer_pub_bytes = None, peer_sig_pub_bytes = None): def __init__(self, destination=None, established_callback=None, closed_callback=None, owner=None, peer_pub_bytes=None, peer_sig_pub_bytes=None, mode=MODE_DEFAULT):
if destination != None and destination.type != RNS.Destination.SINGLE: if destination != None and destination.type != RNS.Destination.SINGLE: raise TypeError("Links can only be established to the \"single\" destination type")
raise TypeError("Links can only be established to the \"single\" destination type") self.mode = mode
self.rtt = None self.rtt = None
self.mtu = RNS.Reticulum.MTU self.mtu = RNS.Reticulum.MTU
self.establishment_cost = 0 self.establishment_cost = 0
@@ -186,6 +247,7 @@ class Link:
self.pending_requests = [] self.pending_requests = []
self.last_inbound = 0 self.last_inbound = 0
self.last_outbound = 0 self.last_outbound = 0
self.last_keepalive = 0
self.last_proof = 0 self.last_proof = 0
self.last_data = 0 self.last_data = 0
self.tx = 0 self.tx = 0
@@ -244,12 +306,14 @@ class Link:
self.set_link_closed_callback(closed_callback) self.set_link_closed_callback(closed_callback)
if self.initiator: if self.initiator:
link_mtu = b"" signalling_bytes = b""
nh_hw_mtu = RNS.Transport.next_hop_interface_hw_mtu(destination.hash) nh_hw_mtu = RNS.Transport.next_hop_interface_hw_mtu(destination.hash)
if RNS.Reticulum.link_mtu_discovery() and nh_hw_mtu: if RNS.Reticulum.link_mtu_discovery() and nh_hw_mtu:
link_mtu = Link.mtu_bytes(nh_hw_mtu) signalling_bytes = Link.signalling_bytes(nh_hw_mtu, self.mode)
RNS.log(f"Signalling link MTU of {RNS.prettysize(nh_hw_mtu)} for link", RNS.LOG_DEBUG) # TODO: Remove debug RNS.log(f"Signalling link MTU of {RNS.prettysize(nh_hw_mtu)} for link", RNS.LOG_DEBUG) # TODO: Remove debug
self.request_data = self.pub_bytes+self.sig_pub_bytes+link_mtu else: signalling_bytes = Link.signalling_bytes(RNS.Reticulum.MTU, self.mode)
RNS.log(f"Establishing link with mode {Link.MODE_DESCRIPTIONS[self.mode]}", RNS.LOG_DEBUG) # TODO: Remove debug
self.request_data = self.pub_bytes+self.sig_pub_bytes+signalling_bytes
self.packet = RNS.Packet(destination, self.request_data, packet_type=RNS.Packet.LINKREQUEST) self.packet = RNS.Packet(destination, self.request_data, packet_type=RNS.Packet.LINKREQUEST)
self.packet.pack() self.packet.pack()
self.establishment_cost += len(self.packet.raw) self.establishment_cost += len(self.packet.raw)
@@ -291,25 +355,25 @@ class Link:
self.status = Link.HANDSHAKE self.status = Link.HANDSHAKE
self.shared_key = self.prv.exchange(self.peer_pub) self.shared_key = self.prv.exchange(self.peer_pub)
if self.mode == Link.MODE_AES128_CBC: derived_key_length = 32
elif self.mode == Link.MODE_AES256_CBC: derived_key_length = 64
else: raise TypeError(f"Invalid link mode {self.mode} on {self}")
self.derived_key = RNS.Cryptography.hkdf( self.derived_key = RNS.Cryptography.hkdf(
length=32, length=derived_key_length,
derive_from=self.shared_key, derive_from=self.shared_key,
salt=self.get_salt(), salt=self.get_salt(),
context=self.get_context(), context=self.get_context())
)
else: else: RNS.log("Handshake attempt on "+str(self)+" with invalid state "+str(self.status), RNS.LOG_ERROR)
RNS.log("Handshake attempt on "+str(self)+" with invalid state "+str(self.status), RNS.LOG_ERROR)
def prove(self): def prove(self):
mtu_bytes = b"" signalling_bytes = Link.signalling_bytes(self.mtu, self.mode)
if self.mtu != RNS.Reticulum.MTU: signed_data = self.link_id+self.pub_bytes+self.sig_pub_bytes+signalling_bytes
mtu_bytes = Link.mtu_bytes(self.mtu)
signed_data = self.link_id+self.pub_bytes+self.sig_pub_bytes+mtu_bytes
signature = self.owner.identity.sign(signed_data) signature = self.owner.identity.sign(signed_data)
proof_data = signature+self.pub_bytes+mtu_bytes proof_data = signature+self.pub_bytes+signalling_bytes
proof = RNS.Packet(self, proof_data, packet_type=RNS.Packet.PROOF, context=RNS.Packet.LRPROOF) proof = RNS.Packet(self, proof_data, packet_type=RNS.Packet.PROOF, context=RNS.Packet.LRPROOF)
proof.send() proof.send()
self.establishment_cost += len(proof.raw) self.establishment_cost += len(proof.raw)
@@ -332,11 +396,14 @@ class Link:
def validate_proof(self, packet): def validate_proof(self, packet):
try: try:
if self.status == Link.PENDING: if self.status == Link.PENDING:
mtu_bytes = b"" signalling_bytes = b""
confirmed_mtu = None confirmed_mtu = None
mode = Link.mode_from_lp_packet(packet)
RNS.log(f"Validating link request proof with mode {Link.MODE_DESCRIPTIONS[mode]}", RNS.LOG_DEBUG) # TODO: Remove debug
if mode != self.mode: raise TypeError(f"Invalid link mode {mode} in link request proof")
if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE: if len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2+Link.LINK_MTU_SIZE:
confirmed_mtu = Link.mtu_from_lp_packet(packet) confirmed_mtu = Link.mtu_from_lp_packet(packet)
mtu_bytes = Link.mtu_bytes(confirmed_mtu) signalling_bytes = Link.signalling_bytes(confirmed_mtu, mode)
packet.data = packet.data[:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2] packet.data = packet.data[:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2]
RNS.log(f"Destination confirmed link MTU of {RNS.prettysize(confirmed_mtu)}", RNS.LOG_DEBUG) # TODO: Remove debug RNS.log(f"Destination confirmed link MTU of {RNS.prettysize(confirmed_mtu)}", RNS.LOG_DEBUG) # TODO: Remove debug
@@ -347,7 +414,7 @@ class Link:
self.handshake() self.handshake()
self.establishment_cost += len(packet.raw) self.establishment_cost += len(packet.raw)
signed_data = self.link_id+self.peer_pub_bytes+self.peer_sig_pub_bytes+mtu_bytes signed_data = self.link_id+self.peer_pub_bytes+self.peer_sig_pub_bytes+signalling_bytes
signature = packet.data[:RNS.Identity.SIGLENGTH//8] signature = packet.data[:RNS.Identity.SIGLENGTH//8]
if self.destination.identity.validate(signature, signed_data): if self.destination.identity.validate(signature, signed_data):
@@ -363,11 +430,13 @@ class Link:
self.activated_at = time.time() self.activated_at = time.time()
self.last_proof = self.activated_at self.last_proof = self.activated_at
RNS.Transport.activate_link(self) RNS.Transport.activate_link(self)
RNS.log("Link "+str(self)+" established with "+str(self.destination)+", RTT is "+str(round(self.rtt, 3))+"s", RNS.LOG_DEBUG) RNS.log("Link "+str(self)+" established with "+str(self.destination)+", RTT is "+RNS.prettyshorttime(self.rtt), RNS.LOG_DEBUG)
if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0: if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0:
self.establishment_rate = self.establishment_cost/self.rtt self.establishment_rate = self.establishment_cost/self.rtt
self.__update_keepalive()
rtt_data = umsgpack.packb(self.rtt) rtt_data = umsgpack.packb(self.rtt)
rtt_packet = RNS.Packet(self, rtt_data, context=RNS.Packet.LRRTT) rtt_packet = RNS.Packet(self, rtt_data, context=RNS.Packet.LRRTT)
rtt_packet.send() rtt_packet.send()
@@ -475,6 +544,8 @@ class Link:
if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0: if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0:
self.establishment_rate = self.establishment_cost/self.rtt self.establishment_rate = self.establishment_cost/self.rtt
self.__update_keepalive()
try: try:
if self.owner.callbacks.link_established != None: if self.owner.callbacks.link_established != None:
self.owner.callbacks.link_established(self) self.owner.callbacks.link_established(self)
@@ -562,6 +633,12 @@ class Link:
else: else:
return None return None
def get_mode(self):
"""
:returns: The mode of an established link.
"""
return self.mode
def get_salt(self): def get_salt(self):
return self.link_id return self.link_id
@@ -611,23 +688,23 @@ class Link:
def had_outbound(self, is_keepalive=False): def had_outbound(self, is_keepalive=False):
self.last_outbound = time.time() self.last_outbound = time.time()
if not is_keepalive: if not is_keepalive: self.last_data = self.last_outbound
self.last_data = self.last_outbound else: self.last_keepalive = self.last_outbound
def __teardown_packet(self):
teardown_packet = RNS.Packet(self, self.link_id, context=RNS.Packet.LINKCLOSE)
teardown_packet.send()
self.had_outbound()
def teardown(self): def teardown(self):
""" """
Closes the link and purges encryption keys. New keys will Closes the link and purges encryption keys. New keys will
be used if a new link to the same destination is established. be used if a new link to the same destination is established.
""" """
if self.status != Link.PENDING and self.status != Link.CLOSED: if self.status != Link.PENDING and self.status != Link.CLOSED: self.__teardown_packet()
teardown_packet = RNS.Packet(self, self.link_id, context=RNS.Packet.LINKCLOSE)
teardown_packet.send()
self.had_outbound()
self.status = Link.CLOSED self.status = Link.CLOSED
if self.initiator: if self.initiator: self.teardown_reason = Link.INITIATOR_CLOSED
self.teardown_reason = Link.INITIATOR_CLOSED else: self.teardown_reason = Link.DESTINATION_CLOSED
else:
self.teardown_reason = Link.DESTINATION_CLOSED
self.link_closed() self.link_closed()
def teardown_packet(self, packet): def teardown_packet(self, packet):
@@ -714,9 +791,10 @@ class Link:
elif self.status == Link.ACTIVE: elif self.status == Link.ACTIVE:
activated_at = self.activated_at if self.activated_at != None else 0 activated_at = self.activated_at if self.activated_at != None else 0
last_inbound = max(max(self.last_inbound, self.last_proof), activated_at) last_inbound = max(max(self.last_inbound, self.last_proof), activated_at)
now = time.time()
if time.time() >= last_inbound + self.keepalive: if now >= last_inbound + self.keepalive:
if self.initiator: if self.initiator and now >= self.last_keepalive + self.keepalive:
self.send_keepalive() self.send_keepalive()
if time.time() >= last_inbound + self.stale_time: if time.time() >= last_inbound + self.stale_time:
@@ -730,6 +808,7 @@ class Link:
elif self.status == Link.STALE: elif self.status == Link.STALE:
sleep_time = 0.001 sleep_time = 0.001
self.__teardown_packet()
self.status = Link.CLOSED self.status = Link.CLOSED
self.teardown_reason = Link.TIMEOUT self.teardown_reason = Link.TIMEOUT
self.link_closed() self.link_closed()
@@ -742,6 +821,7 @@ class Link:
self.teardown() self.teardown()
sleep_time = 0.1 sleep_time = 0.1
sleep_time = min(sleep_time, Link.WATCHDOG_MAX_SLEEP)
sleep(sleep_time) sleep(sleep_time)
if not self.__track_phy_stats: if not self.__track_phy_stats:
@@ -764,6 +844,10 @@ class Link:
self.snr = packet.snr self.snr = packet.snr
if packet.q != None: if packet.q != None:
self.q = packet.q self.q = packet.q
def __update_keepalive(self):
self.keepalive = max(min(self.rtt*(Link.KEEPALIVE_MAX/Link.KEEPALIVE_MAX_RTT), Link.KEEPALIVE_MAX), Link.KEEPALIVE_MIN)
self.stale_time = self.keepalive * Link.STALE_FACTOR
def send_keepalive(self): def send_keepalive(self):
keepalive_packet = RNS.Packet(self, bytes([0xFF]), context=RNS.Packet.KEEPALIVE) keepalive_packet = RNS.Packet(self, bytes([0xFF]), context=RNS.Packet.KEEPALIVE)
@@ -782,6 +866,7 @@ class Link:
response_generator = request_handler[1] response_generator = request_handler[1]
allow = request_handler[2] allow = request_handler[2]
allowed_list = request_handler[3] allowed_list = request_handler[3]
auto_compress = request_handler[4]
allowed = False allowed = False
if not allow == RNS.Destination.ALLOW_NONE: if not allow == RNS.Destination.ALLOW_NONE:
@@ -800,18 +885,29 @@ class Link:
else: else:
raise TypeError("Invalid signature for response generator callback") raise TypeError("Invalid signature for response generator callback")
if response != None: file_response = False
packed_response = umsgpack.packb([request_id, response]) file_handle = None
if type(response) == list or type(response) == tuple:
metadata = None
if len(response) > 0 and type(response[0]) == io.BufferedReader:
if len(response) > 1: metadata = response[1]
file_handle = response[0]
file_response = True
if len(packed_response) <= self.mdu: if response != None:
RNS.Packet(self, packed_response, RNS.Packet.DATA, context = RNS.Packet.RESPONSE).send() if file_response:
response_resource = RNS.Resource(file_handle, self, metadata=metadata, request_id = request_id, is_response = True, auto_compress=auto_compress)
else: else:
response_resource = RNS.Resource(packed_response, self, request_id = request_id, is_response = True) packed_response = umsgpack.packb([request_id, response])
if len(packed_response) <= self.mdu:
RNS.Packet(self, packed_response, RNS.Packet.DATA, context = RNS.Packet.RESPONSE).send()
else:
response_resource = RNS.Resource(packed_response, self, request_id = request_id, is_response = True, auto_compress=auto_compress)
else: else:
identity_string = str(self.get_remote_identity()) if self.get_remote_identity() != None else "<Unknown>" identity_string = str(self.get_remote_identity()) if self.get_remote_identity() != None else "<Unknown>"
RNS.log("Request "+RNS.prettyhexrep(request_id)+" from "+identity_string+" not allowed for: "+str(path), RNS.LOG_DEBUG) RNS.log("Request "+RNS.prettyhexrep(request_id)+" from "+identity_string+" not allowed for: "+str(path), RNS.LOG_DEBUG)
def handle_response(self, request_id, response_data, response_size, response_transfer_size): def handle_response(self, request_id, response_data, response_size, response_transfer_size, metadata=None):
if self.status == Link.ACTIVE: if self.status == Link.ACTIVE:
remove = None remove = None
for pending_request in self.pending_requests: for pending_request in self.pending_requests:
@@ -822,7 +918,7 @@ class Link:
if pending_request.response_transfer_size == None: if pending_request.response_transfer_size == None:
pending_request.response_transfer_size = 0 pending_request.response_transfer_size = 0
pending_request.response_transfer_size += response_transfer_size pending_request.response_transfer_size += response_transfer_size
pending_request.response_received(response_data) pending_request.response_received(response_data, metadata)
except Exception as e: except Exception as e:
RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR)
@@ -845,12 +941,21 @@ class Link:
def response_resource_concluded(self, resource): def response_resource_concluded(self, resource):
if resource.status == RNS.Resource.COMPLETE: if resource.status == RNS.Resource.COMPLETE:
packed_response = resource.data.read() # If the response resource has metadata, this
unpacked_response = umsgpack.unpackb(packed_response) # is a file response, and we'll pass the open
request_id = unpacked_response[0] # file handle directly.
response_data = unpacked_response[1] if resource.has_metadata:
self.handle_response(resource.request_id, resource.data, resource.total_size, resource.size, metadata=resource.metadata)
# If not, we'll unpack the response data and
# pass the unpacked structure to the handler
else:
packed_response = resource.data.read()
unpacked_response = umsgpack.unpackb(packed_response)
request_id = unpacked_response[0]
response_data = unpacked_response[1]
self.handle_response(request_id, response_data, resource.total_size, resource.size)
self.handle_response(request_id, response_data, resource.total_size, resource.size)
else: else:
RNS.log("Incoming response resource failed with status: "+RNS.hexrep([resource.status]), RNS.LOG_DEBUG) RNS.log("Incoming response resource failed with status: "+RNS.hexrep([resource.status]), RNS.LOG_DEBUG)
for pending_request in self.pending_requests: for pending_request in self.pending_requests:
@@ -1085,8 +1190,7 @@ class Link:
def encrypt(self, plaintext): def encrypt(self, plaintext):
try: try:
if not self.token: if not self.token:
try: try: self.token = Token(self.derived_key)
self.token = Token(self.derived_key)
except Exception as e: except Exception as e:
RNS.log("Could not instantiate token while performing encryption on link "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Could not instantiate token while performing encryption on link "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
raise e raise e
@@ -1100,9 +1204,7 @@ class Link:
def decrypt(self, ciphertext): def decrypt(self, ciphertext):
try: try:
if not self.token: if not self.token: self.token = Token(self.derived_key)
self.token = Token(self.derived_key)
return self.token.decrypt(ciphertext) return self.token.decrypt(ciphertext)
except Exception as e: except Exception as e:
@@ -1277,6 +1379,7 @@ class RequestReceipt():
self.response = None self.response = None
self.response_transfer_size = None self.response_transfer_size = None
self.response_size = None self.response_size = None
self.metadata = None
self.status = RequestReceipt.SENT self.status = RequestReceipt.SENT
self.sent_at = time.time() self.sent_at = time.time()
self.progress = 0 self.progress = 0
@@ -1363,10 +1466,11 @@ class RequestReceipt():
resource.cancel() resource.cancel()
def response_received(self, response): def response_received(self, response, metadata=None):
if not self.status == RequestReceipt.FAILED: if not self.status == RequestReceipt.FAILED:
self.progress = 1.0 self.progress = 1.0
self.response = response self.response = response
self.metadata = metadata
self.status = RequestReceipt.READY self.status = RequestReceipt.READY
self.response_concluded_at = time.time() self.response_concluded_at = time.time()
+14 -6
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors. # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -35,10 +43,10 @@ class Packet:
For ``RNS.Destination.GROUP`` destinations, Reticulum will use the For ``RNS.Destination.GROUP`` destinations, Reticulum will use the
pre-shared key configured for the destination. All packets to group pre-shared key configured for the destination. All packets to group
destinations are encrypted with the same AES-128 key. destinations are encrypted with the same AES-256 key.
For ``RNS.Destination.SINGLE`` destinations, Reticulum will use a newly For ``RNS.Destination.SINGLE`` destinations, Reticulum will use a newly
derived ephemeral AES-128 key for every packet. derived ephemeral AES-256 key for every packet.
For :ref:`RNS.Link<api-link>` destinations, Reticulum will use per-link For :ref:`RNS.Link<api-link>` destinations, Reticulum will use per-link
ephemeral keys, and offers **Forward Secrecy**. ephemeral keys, and offers **Forward Secrecy**.
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors. # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+149 -70
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors. # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -25,6 +33,7 @@ import os
import bz2 import bz2
import math import math
import time import time
import struct
import tempfile import tempfile
import threading import threading
from threading import Lock from threading import Lock
@@ -99,22 +108,20 @@ class Resource:
# it is to be handled within reasonable # it is to be handled within reasonable
# time constraint, even on small systems. # time constraint, even on small systems.
# #
# A small system in this regard is
# defined as a Raspberry Pi, which should
# be able to compress, encrypt and hash-map
# the resource in about 10 seconds.
#
# This constant will be used when determining # This constant will be used when determining
# how to sequence the sending of large resources. # how to sequence the sending of large resources.
# #
# Capped at 16777215 (0xFFFFFF) per segment to # Capped at 16777215 (0xFFFFFF) per segment to
# fit in 3 bytes in resource advertisements. # fit in 3 bytes in resource advertisements.
MAX_EFFICIENT_SIZE = 16 * 1024 * 1024 - 1 MAX_EFFICIENT_SIZE = 1 * 1024 * 1024 - 1
RESPONSE_MAX_GRACE_TIME = 10 RESPONSE_MAX_GRACE_TIME = 10
# Max metadata size is 16777215 (0xFFFFFF) bytes
METADATA_MAX_SIZE = 16 * 1024 * 1024 - 1
# The maximum size to auto-compress with # The maximum size to auto-compress with
# bz2 before sending. # bz2 before sending.
AUTO_COMPRESS_MAX_SIZE = MAX_EFFICIENT_SIZE AUTO_COMPRESS_MAX_SIZE = 64 * 1024 * 1024
PART_TIMEOUT_FACTOR = 4 PART_TIMEOUT_FACTOR = 4
PART_TIMEOUT_FACTOR_AFTER_RTT = 2 PART_TIMEOUT_FACTOR_AFTER_RTT = 2
@@ -188,12 +195,15 @@ class Resource:
resource.started_transferring = resource.last_activity resource.started_transferring = resource.last_activity
resource.storagepath = RNS.Reticulum.resourcepath+"/"+resource.original_hash.hex() resource.storagepath = RNS.Reticulum.resourcepath+"/"+resource.original_hash.hex()
resource.meta_storagepath = resource.storagepath+".meta"
resource.segment_index = adv.i resource.segment_index = adv.i
resource.total_segments = adv.l resource.total_segments = adv.l
if adv.l > 1:
resource.split = True if adv.l > 1: resource.split = True
else: else: resource.split = False
resource.split = False
if adv.x: resource.has_metadata = True
else: resource.has_metadata = False
resource.hashmap = [None] * resource.total_parts resource.hashmap = [None] * resource.total_parts
resource.hashmap_height = 0 resource.hashmap_height = 0
@@ -219,9 +229,7 @@ class Resource:
RNS.log("Error while executing resource started callback from "+str(resource)+". The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Error while executing resource started callback from "+str(resource)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
resource.hashmap_update(0, resource.hashmap_raw) resource.hashmap_update(0, resource.hashmap_raw)
resource.watchdog_job() resource.watchdog_job()
return resource return resource
else: else:
@@ -235,15 +243,33 @@ class Resource:
# Create a resource for transmission to a remote destination # Create a resource for transmission to a remote destination
# The data passed can be either a bytes-array or a file opened # The data passed can be either a bytes-array or a file opened
# in binary read mode. # in binary read mode.
def __init__(self, data, link, advertise=True, auto_compress=True, callback=None, progress_callback=None, timeout = None, segment_index = 1, original_hash = None, request_id = None, is_response = False): def __init__(self, data, link, metadata=None, advertise=True, auto_compress=True, callback=None, progress_callback=None,
timeout = None, segment_index = 1, original_hash = None, request_id = None, is_response = False, sent_metadata_size=0):
data_size = None data_size = None
resource_data = None resource_data = None
self.assembly_lock = False self.assembly_lock = False
self.preparing_next_segment = False self.preparing_next_segment = False
self.next_segment = None self.next_segment = None
self.metadata = None
self.has_metadata = False
self.metadata_size = sent_metadata_size
if metadata != None:
packed_metadata = umsgpack.packb(metadata)
metadata_size = len(packed_metadata)
if metadata_size > Resource.METADATA_MAX_SIZE:
raise SystemError("Resource metadata size exceeded")
else:
self.metadata = struct.pack(">I", metadata_size)[1:] + packed_metadata
self.metadata_size = len(self.metadata)
self.has_metadata = True
else:
self.metadata = b""
if sent_metadata_size > 0: self.has_metadata = True
if data != None: if data != None:
if not hasattr(data, "read") and len(data) > Resource.MAX_EFFICIENT_SIZE: if not hasattr(data, "read") and self.metadata_size + len(data) > Resource.MAX_EFFICIENT_SIZE:
original_data = data original_data = data
data_size = len(original_data) data_size = len(original_data)
data = tempfile.TemporaryFile() data = tempfile.TemporaryFile()
@@ -251,31 +277,43 @@ class Resource:
del original_data del original_data
if hasattr(data, "read"): if hasattr(data, "read"):
if data_size == None: if data_size == None: data_size = os.stat(data.name).st_size
data_size = os.stat(data.name).st_size self.total_size = data_size + self.metadata_size
self.total_size = data_size if self.total_size <= Resource.MAX_EFFICIENT_SIZE:
if data_size <= Resource.MAX_EFFICIENT_SIZE:
self.total_segments = 1 self.total_segments = 1
self.segment_index = 1 self.segment_index = 1
self.split = False self.split = False
resource_data = data.read() resource_data = data.read()
data.close() data.close()
else: else:
self.total_segments = ((data_size-1)//Resource.MAX_EFFICIENT_SIZE)+1 # 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.segment_index = segment_index
self.split = True self.split = True
seek_index = segment_index-1 seek_index = segment_index-1
seek_position = seek_index*Resource.MAX_EFFICIENT_SIZE first_read_size = Resource.MAX_EFFICIENT_SIZE - self.metadata_size
if segment_index == 1:
seek_position = 0
segment_read_size = first_read_size
else:
seek_position = first_read_size + ((seek_index-1)*Resource.MAX_EFFICIENT_SIZE)
segment_read_size = Resource.MAX_EFFICIENT_SIZE
data.seek(seek_position) data.seek(seek_position)
resource_data = data.read(Resource.MAX_EFFICIENT_SIZE) resource_data = data.read(segment_read_size)
self.input_file = data self.input_file = data
elif isinstance(data, bytes): elif isinstance(data, bytes):
data_size = len(data) data_size = len(data)
self.total_size = data_size self.total_size = data_size + self.metadata_size
resource_data = data resource_data = data
self.total_segments = 1 self.total_segments = 1
@@ -288,7 +326,9 @@ class Resource:
else: else:
raise TypeError("Invalid data instance type passed to resource initialisation") raise TypeError("Invalid data instance type passed to resource initialisation")
data = resource_data if resource_data:
if self.has_metadata: data = self.metadata + resource_data
else: data = resource_data
self.status = Resource.NONE self.status = Resource.NONE
self.link = link self.link = link
@@ -319,7 +359,16 @@ class Resource:
self.request_id = request_id self.request_id = request_id
self.started_transferring = None self.started_transferring = None
self.is_response = is_response self.is_response = is_response
self.auto_compress = auto_compress self.auto_compress_limit = Resource.AUTO_COMPRESS_MAX_SIZE
self.auto_compress_option = auto_compress
if type(auto_compress) == bool:
self.auto_compress = auto_compress
elif type(auto_compress) == int:
self.auto_compress = True
self.auto_compress_limit = auto_compress
else:
raise TypeError(f"Invalid type {type(auto_compress)} for auto_compress option")
self.req_hashlist = [] self.req_hashlist = []
self.receiver_min_consecutive_height = 0 self.receiver_min_consecutive_height = 0
@@ -335,7 +384,7 @@ class Resource:
self.uncompressed_data = data self.uncompressed_data = data
compression_began = time.time() compression_began = time.time()
if (auto_compress and len(self.uncompressed_data) <= Resource.AUTO_COMPRESS_MAX_SIZE): if self.auto_compress and data_size <= self.auto_compress_limit:
RNS.log("Compressing resource data...", RNS.LOG_EXTREME) RNS.log("Compressing resource data...", RNS.LOG_EXTREME)
self.compressed_data = bz2.compress(self.uncompressed_data) self.compressed_data = bz2.compress(self.uncompressed_data)
RNS.log("Compression completed in "+str(round(time.time()-compression_began, 3))+" seconds", RNS.LOG_EXTREME) RNS.log("Compression completed in "+str(round(time.time()-compression_began, 3))+" seconds", RNS.LOG_EXTREME)
@@ -354,19 +403,20 @@ class Resource:
self.data += self.compressed_data self.data += self.compressed_data
self.compressed = True self.compressed = True
self.uncompressed_data = None
else: else:
self.data = b"" self.data = b""
self.data += RNS.Identity.get_random_hash()[:Resource.RANDOM_HASH_SIZE] self.data += RNS.Identity.get_random_hash()[:Resource.RANDOM_HASH_SIZE]
self.data += self.uncompressed_data self.data += self.uncompressed_data
self.uncompressed_data = self.data
self.compressed = False self.compressed = False
self.compressed_data = None self.compressed_data = None
if auto_compress: if self.auto_compress and data_size <= self.auto_compress_limit:
RNS.log("Compression did not decrease size, sending uncompressed", RNS.LOG_EXTREME) RNS.log("Compression did not decrease size, sending uncompressed", RNS.LOG_EXTREME)
self.compressed_data = None
self.uncompressed_data = None
# Resources handle encryption directly to # Resources handle encryption directly to
# make optimal use of packet MTU on an entire # make optimal use of packet MTU on an entire
# encrypted stream. The Resource instance will # encrypted stream. The Resource instance will
@@ -419,7 +469,8 @@ class Resource:
self.parts.append(part) self.parts.append(part)
RNS.log("Hashmap computation concluded in "+str(round(time.time()-hashmap_computation_began, 3))+" seconds", RNS.LOG_EXTREME) RNS.log("Hashmap computation concluded in "+str(round(time.time()-hashmap_computation_began, 3))+" seconds", RNS.LOG_EXTREME)
self.data = None
if advertise: if advertise:
self.advertise() self.advertise()
else: else:
@@ -504,8 +555,7 @@ class Resource:
if self.link: self.link.expected_rate = self.eifr if self.link: self.link.expected_rate = self.eifr
def watchdog_job(self): def watchdog_job(self):
thread = threading.Thread(target=self.__watchdog_job) thread = threading.Thread(target=self.__watchdog_job, daemon=True)
thread.daemon = True
thread.start() thread.start()
def __watchdog_job(self): def __watchdog_job(self):
@@ -551,6 +601,7 @@ class Resource:
else: else:
sleep_time = self.last_activity + self.part_timeout_factor*((3*self.sdu)/self.eifr) + Resource.RETRY_GRACE_TIME + extra_wait - time.time() sleep_time = self.last_activity + self.part_timeout_factor*((3*self.sdu)/self.eifr) + Resource.RETRY_GRACE_TIME + extra_wait - time.time()
# TODO: Remove debug at some point
# RNS.log(f"EIFR {RNS.prettyspeed(self.eifr)}, ETOF {RNS.prettyshorttime(expected_tof_remaining)} ", RNS.LOG_DEBUG, pt=True) # RNS.log(f"EIFR {RNS.prettyspeed(self.eifr)}, ETOF {RNS.prettyshorttime(expected_tof_remaining)} ", RNS.LOG_DEBUG, pt=True)
# RNS.log(f"Resource ST {RNS.prettyshorttime(sleep_time)}, RTT {RNS.prettyshorttime(self.rtt or self.link.rtt)}, {self.outstanding_parts} left", RNS.LOG_DEBUG, pt=True) # RNS.log(f"Resource ST {RNS.prettyshorttime(sleep_time)}, RTT {RNS.prettyshorttime(self.rtt or self.link.rtt)}, {self.outstanding_parts} left", RNS.LOG_DEBUG, pt=True)
@@ -620,29 +671,37 @@ class Resource:
self.status = Resource.ASSEMBLING self.status = Resource.ASSEMBLING
stream = b"".join(self.parts) stream = b"".join(self.parts)
if self.encrypted: if self.encrypted: data = self.link.decrypt(stream)
data = self.link.decrypt(stream) else: data = stream
else:
data = stream
# Strip off random hash # Strip off random hash
data = data[Resource.RANDOM_HASH_SIZE:] data = data[Resource.RANDOM_HASH_SIZE:]
if self.compressed: if self.compressed: self.data = bz2.decompress(data)
self.data = bz2.decompress(data) else: self.data = data
else:
self.data = data
calculated_hash = RNS.Identity.full_hash(self.data+self.random_hash) calculated_hash = RNS.Identity.full_hash(self.data+self.random_hash)
if calculated_hash == self.hash: if calculated_hash == self.hash:
if self.has_metadata and self.segment_index == 1:
# TODO: Add early metadata_ready callback
metadata_size = self.data[0] << 16 | self.data[1] << 8 | self.data[2]
packed_metadata = self.data[3:3+metadata_size]
metadata_file = open(self.meta_storagepath, "wb")
metadata_file.write(packed_metadata)
metadata_file.close()
del packed_metadata
data = self.data[3+metadata_size:]
else:
data = self.data
self.file = open(self.storagepath, "ab") self.file = open(self.storagepath, "ab")
self.file.write(self.data) self.file.write(data)
self.file.close() self.file.close()
self.status = Resource.COMPLETE self.status = Resource.COMPLETE
del data
self.prove() self.prove()
else:
self.status = Resource.CORRUPT else: self.status = Resource.CORRUPT
except Exception as e: except Exception as e:
@@ -654,21 +713,27 @@ class Resource:
if self.segment_index == self.total_segments: if self.segment_index == self.total_segments:
if self.callback != None: if self.callback != None:
if not os.path.isfile(self.meta_storagepath):
self.metadata = None
else:
metadata_file = open(self.meta_storagepath, "rb")
self.metadata = umsgpack.unpackb(metadata_file.read())
metadata_file.close()
try: os.unlink(self.meta_storagepath)
except Exception as e:
RNS.log(f"Error while cleaning up resource metadata file, the contained exception was: {e}", RNS.LOG_ERROR)
self.data = open(self.storagepath, "rb") self.data = open(self.storagepath, "rb")
try: try: self.callback(self)
self.callback(self)
except Exception as e: except Exception as e:
RNS.log("Error while executing resource assembled callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) RNS.log("Error while executing resource assembled callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
try: try:
if hasattr(self.data, "close") and callable(self.data.close): if hasattr(self.data, "close") and callable(self.data.close): self.data.close()
self.data.close() if os.path.isfile(self.storagepath): os.unlink(self.storagepath)
os.unlink(self.storagepath)
except Exception as e: except Exception as e:
RNS.log("Error while cleaning up resource files, the contained exception was:", RNS.LOG_ERROR) RNS.log(f"Error while cleaning up resource files, the contained exception was: {e}", RNS.LOG_ERROR)
RNS.log(str(e))
else: else:
RNS.log("Resource segment "+str(self.segment_index)+" of "+str(self.total_segments)+" received, waiting for next segment to be announced", RNS.LOG_DEBUG) RNS.log("Resource segment "+str(self.segment_index)+" of "+str(self.total_segments)+" received, waiting for next segment to be announced", RNS.LOG_DEBUG)
@@ -699,7 +764,8 @@ class Resource:
request_id = self.request_id, request_id = self.request_id,
is_response = self.is_response, is_response = self.is_response,
advertise = False, advertise = False,
auto_compress = self.auto_compress, auto_compress = self.auto_compress_option,
sent_metadata_size = self.metadata_size,
) )
def validate_proof(self, proof_data): def validate_proof(self, proof_data):
@@ -712,18 +778,18 @@ class Resource:
# If all segments were processed, we'll # If all segments were processed, we'll
# signal that the resource sending concluded # signal that the resource sending concluded
if self.callback != None: if self.callback != None:
try: try: self.callback(self)
self.callback(self) except Exception as e: RNS.log("Error while executing resource concluded callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
except Exception as e:
RNS.log("Error while executing resource concluded callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
finally: finally:
try: try:
if hasattr(self, "input_file"): if hasattr(self, "input_file"):
if hasattr(self.input_file, "close") and callable(self.input_file.close): if hasattr(self.input_file, "close") and callable(self.input_file.close): self.input_file.close()
self.input_file.close() except Exception as e: RNS.log("Error while closing resource input file: "+str(e), RNS.LOG_ERROR)
else:
except Exception as e: try:
RNS.log("Error while closing resource input file: "+str(e), RNS.LOG_ERROR) if hasattr(self, "input_file"):
if hasattr(self.input_file, "close") and callable(self.input_file.close): self.input_file.close()
except Exception as e: RNS.log("Error while closing resource input file: "+str(e), RNS.LOG_ERROR)
else: else:
# Otherwise we'll recursively create the # Otherwise we'll recursively create the
# next segment of the resource # next segment of the resource
@@ -731,8 +797,16 @@ class Resource:
RNS.log(f"Next segment preparation for resource {self} was not started yet, manually preparing now. This will cause transfer slowdown.", RNS.LOG_WARNING) RNS.log(f"Next segment preparation for resource {self} was not started yet, manually preparing now. This will cause transfer slowdown.", RNS.LOG_WARNING)
self.__prepare_next_segment() self.__prepare_next_segment()
while self.next_segment == None: while self.next_segment == None: time.sleep(0.05)
time.sleep(0.05)
self.data = None
self.metadata = None
self.parts = None
self.input_file = None
self.link = None
self.req_hashlist = None
self.hashmap = None
self.next_segment.advertise() self.next_segment.advertise()
else: else:
pass pass
@@ -1194,6 +1268,7 @@ class ResourceAdvertisement:
self.c = resource.compressed # Compression flag self.c = resource.compressed # Compression flag
self.e = resource.encrypted # Encryption flag self.e = resource.encrypted # Encryption flag
self.s = resource.split # Split flag self.s = resource.split # Split flag
self.x = resource.has_metadata # Metadata flag
self.i = resource.segment_index # Segment index self.i = resource.segment_index # Segment index
self.l = resource.total_segments # Total segments self.l = resource.total_segments # Total segments
self.q = resource.request_id # ID of associated request self.q = resource.request_id # ID of associated request
@@ -1209,7 +1284,7 @@ class ResourceAdvertisement:
self.p = True self.p = True
# Flags # Flags
self.f = 0x00 | self.p << 4 | self.u << 3 | self.s << 2 | self.c << 1 | self.e self.f = 0x00 | self.x << 5 | self.p << 4 | self.u << 3 | self.s << 2 | self.c << 1 | self.e
def get_transfer_size(self): def get_transfer_size(self):
return self.t return self.t
@@ -1229,6 +1304,9 @@ class ResourceAdvertisement:
def is_compressed(self): def is_compressed(self):
return self.c return self.c
def has_metadata(self):
return self.x
def get_link(self): def get_link(self):
return self.link return self.link
@@ -1278,5 +1356,6 @@ class ResourceAdvertisement:
adv.s = True if ((adv.f >> 2) & 0x01) == 0x01 else False adv.s = True if ((adv.f >> 2) & 0x01) == 0x01 else False
adv.u = True if ((adv.f >> 3) & 0x01) == 0x01 else False adv.u = True if ((adv.f >> 3) & 0x01) == 0x01 else False
adv.p = True if ((adv.f >> 4) & 0x01) == 0x01 else False adv.p = True if ((adv.f >> 4) & 0x01) == 0x01 else False
adv.x = True if ((adv.f >> 5) & 0x01) == 0x01 else False
return adv return adv
+52 -15
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors. # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -203,7 +211,8 @@ class Reticulum:
""" """
return Reticulum.__instance return Reticulum.__instance
def __init__(self,configdir=None, loglevel=None, logdest=None, verbosity=None, require_shared_instance=False): def __init__(self,configdir=None, loglevel=None, logdest=None, verbosity=None,
require_shared_instance=False, shared_instance_type=None):
""" """
Initialises and starts a Reticulum instance. This must be Initialises and starts a Reticulum instance. This must be
done before any other operations, and Reticulum will not done before any other operations, and Reticulum will not
@@ -255,9 +264,11 @@ class Reticulum:
self.local_control_port = 37429 self.local_control_port = 37429
self.local_socket_path = None self.local_socket_path = None
self.share_instance = True self.share_instance = True
self.shared_instance_type = shared_instance_type
self.rpc_listener = None self.rpc_listener = None
self.rpc_key = None self.rpc_key = None
self.rpc_type = "AF_INET" self.rpc_type = "AF_INET"
self.use_af_unix = False
self.ifac_salt = Reticulum.IFAC_SALT self.ifac_salt = Reticulum.IFAC_SALT
@@ -314,12 +325,11 @@ class Reticulum:
self.__apply_config() self.__apply_config()
RNS.log(f"Utilising cryptography backend \"{RNS.Cryptography.Provider.backend()}\"", RNS.LOG_DEBUG) RNS.log(f"Utilising cryptography backend \"{RNS.Cryptography.Provider.backend()}\"", RNS.LOG_DEBUG)
RNS.log(f"Configuration loaded from {self.configpath}", RNS.LOG_VERBOSE) RNS.log(f"Configuration loaded from {self.configpath}", RNS.LOG_VERBOSE)
RNS.Identity.load_known_destinations()
RNS.Identity.load_known_destinations()
RNS.Transport.start(self) RNS.Transport.start(self)
if RNS.vendor.platformutils.use_af_unix(): if self.use_af_unix:
self.rpc_addr = f"\0rns/{self.local_socket_path}/rpc" self.rpc_addr = f"\0rns/{self.local_socket_path}/rpc"
self.rpc_type = "AF_UNIX" self.rpc_type = "AF_UNIX"
else: else:
@@ -447,7 +457,11 @@ class Reticulum:
if option == "instance_name": if option == "instance_name":
value = self.config["reticulum"][option] value = self.config["reticulum"][option]
self.local_socket_path = value self.local_socket_path = value
else: self.local_socket_path = "default" if option == "shared_instance_type":
if self.shared_instance_type == None:
value = self.config["reticulum"][option].lower()
if value in ["tcp", "unix"]:
self.shared_instance_type = value
if option == "shared_instance_port": if option == "shared_instance_port":
value = int(self.config["reticulum"][option]) value = int(self.config["reticulum"][option])
self.local_interface_port = value self.local_interface_port = value
@@ -506,6 +520,17 @@ class Reticulum:
if RNS.compiled: RNS.log("Reticulum running in compiled mode", RNS.LOG_DEBUG) if RNS.compiled: RNS.log("Reticulum running in compiled mode", RNS.LOG_DEBUG)
else: RNS.log("Reticulum running in interpreted mode", RNS.LOG_DEBUG) else: RNS.log("Reticulum running in interpreted mode", RNS.LOG_DEBUG)
if RNS.vendor.platformutils.use_af_unix():
if self.shared_instance_type == "tcp": self.use_af_unix = False
else: self.use_af_unix = True
else:
self.shared_instance_type = "tcp"
self.use_af_unix = False
if self.local_socket_path == None and self.use_af_unix:
self.local_socket_path = "default"
self.__start_local_interface() self.__start_local_interface()
if self.is_shared_instance or self.is_standalone_instance: if self.is_shared_instance or self.is_standalone_instance:
@@ -1360,12 +1385,24 @@ share_instance = Yes
# If you want to run multiple *different* shared instances # If you want to run multiple *different* shared instances
# on the same system, you will need to specify different # on the same system, you will need to specify different
# shared instance ports for each. The defaults are given # instance names for each. On platforms supporting domain
# below, and again, these options can be left out if you # sockets, this can be done with the instance_name option:
# don't need them.
shared_instance_port = 37428 instance_name = default
instance_control_port = 37429
# Some platforms don't support domain sockets, and if that
# is the case, you can isolate different instances by
# specifying a unique set of ports for each:
# shared_instance_port = 37428
# instance_control_port = 37429
# If you want to explicitly use TCP for shared instance
# communication, instead of domain sockets, this is also
# possible, by using the following option:
# shared_instance_type = tcp
# You can configure Reticulum to panic and forcibly close # You can configure Reticulum to panic and forcibly close
@@ -1374,7 +1411,7 @@ instance_control_port = 37429
# an optional directive, and can be left out for brevity. # an optional directive, and can be left out for brevity.
# This behaviour is disabled by default. # This behaviour is disabled by default.
panic_on_interface_error = No # panic_on_interface_error = No
[logging] [logging]
+41 -28
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors. # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -1062,7 +1070,7 @@ class Transport:
if should_transmit: if should_transmit:
if not stored_hash: if not stored_hash:
Transport.packet_hashlist.add(packet.packet_hash) Transport.add_packet_hash(packet.packet_hash)
stored_hash = True stored_hash = True
Transport.transmit(interface, packet.raw) Transport.transmit(interface, packet.raw)
@@ -1074,11 +1082,16 @@ class Transport:
Transport.jobs_locked = False Transport.jobs_locked = False
return sent return sent
@staticmethod
def add_packet_hash(packet_hash):
if not Transport.owner.is_connected_to_shared_instance:
Transport.packet_hashlist.add(packet_hash)
@staticmethod @staticmethod
def packet_filter(packet): def packet_filter(packet):
# TODO: Think long and hard about this. # If connected to a shared instance, it will handle
# Is it even strictly necessary with the current # packet filtering
# transport rules? if Transport.owner.is_connected_to_shared_instance: return True
# Filter packets intended for other transport instances # Filter packets intended for other transport instances
if packet.transport_id != None and packet.packet_type != RNS.Packet.ANNOUNCE: if packet.transport_id != None and packet.packet_type != RNS.Packet.ANNOUNCE:
@@ -1266,7 +1279,7 @@ class Transport:
remember_packet_hash = False remember_packet_hash = False
if remember_packet_hash: if remember_packet_hash:
Transport.packet_hashlist.add(packet.packet_hash) Transport.add_packet_hash(packet.packet_hash)
# TODO: Enable when caching has been redesigned # TODO: Enable when caching has been redesigned
# Transport.cache(packet) # Transport.cache(packet)
@@ -1353,6 +1366,7 @@ class Transport:
proof_timeout += now + RNS.Link.ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, remaining_hops) proof_timeout += now + RNS.Link.ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, remaining_hops)
path_mtu = RNS.Link.mtu_from_lr_packet(packet) path_mtu = RNS.Link.mtu_from_lr_packet(packet)
mode = RNS.Link.mode_from_lr_packet(packet)
nh_mtu = outbound_interface.HW_MTU nh_mtu = outbound_interface.HW_MTU
if path_mtu: if path_mtu:
if outbound_interface.HW_MTU == None: if outbound_interface.HW_MTU == None:
@@ -1366,7 +1380,7 @@ class Transport:
else: else:
if nh_mtu < path_mtu: if nh_mtu < path_mtu:
path_mtu = nh_mtu path_mtu = nh_mtu
clamped_mtu = RNS.Link.mtu_bytes(path_mtu) clamped_mtu = RNS.Link.signalling_bytes(path_mtu, mode)
RNS.log(f"Clamping link MTU to {RNS.prettysize(nh_mtu)}", RNS.LOG_DEBUG) # TODO: Remove debug RNS.log(f"Clamping link MTU to {RNS.prettysize(nh_mtu)}", RNS.LOG_DEBUG) # TODO: Remove debug
new_raw = new_raw[:-RNS.Link.LINK_MTU_SIZE]+clamped_mtu new_raw = new_raw[:-RNS.Link.LINK_MTU_SIZE]+clamped_mtu
@@ -1431,7 +1445,7 @@ class Transport:
# Add this packet to the filter hashlist if we # Add this packet to the filter hashlist if we
# have determined that it's actually our turn # have determined that it's actually our turn
# to process it. # to process it.
Transport.packet_hashlist.add(packet.packet_hash) Transport.add_packet_hash(packet.packet_hash)
new_raw = packet.raw[0:1] new_raw = packet.raw[0:1]
new_raw += struct.pack("!B", packet.hops) new_raw += struct.pack("!B", packet.hops)
@@ -1820,6 +1834,7 @@ class Transport:
for destination in Transport.destinations: for destination in Transport.destinations:
if destination.hash == packet.destination_hash and destination.type == packet.destination_type: if destination.hash == packet.destination_hash and destination.type == packet.destination_type:
path_mtu = RNS.Link.mtu_from_lr_packet(packet) path_mtu = RNS.Link.mtu_from_lr_packet(packet)
mode = RNS.Link.mode_from_lr_packet(packet)
if packet.receiving_interface.AUTOCONFIGURE_MTU or packet.receiving_interface.FIXED_MTU: if packet.receiving_interface.AUTOCONFIGURE_MTU or packet.receiving_interface.FIXED_MTU:
nh_mtu = packet.receiving_interface.HW_MTU nh_mtu = packet.receiving_interface.HW_MTU
else: else:
@@ -1833,7 +1848,7 @@ class Transport:
else: else:
if nh_mtu < path_mtu: if nh_mtu < path_mtu:
path_mtu = nh_mtu path_mtu = nh_mtu
clamped_mtu = RNS.Link.mtu_bytes(path_mtu) clamped_mtu = RNS.Link.signalling_bytes(path_mtu, mode)
RNS.log(f"Clamping link MTU to {RNS.prettysize(nh_mtu)}", RNS.LOG_DEBUG) # TODO: Remove debug RNS.log(f"Clamping link MTU to {RNS.prettysize(nh_mtu)}", RNS.LOG_DEBUG) # TODO: Remove debug
packet.data = packet.data[:-RNS.Link.LINK_MTU_SIZE]+clamped_mtu packet.data = packet.data[:-RNS.Link.LINK_MTU_SIZE]+clamped_mtu
@@ -1871,18 +1886,17 @@ class Transport:
for destination in Transport.destinations: for destination in Transport.destinations:
if destination.hash == packet.destination_hash and destination.type == packet.destination_type: if destination.hash == packet.destination_hash and destination.type == packet.destination_type:
packet.destination = destination packet.destination = destination
destination.receive(packet) if destination.receive(packet):
if destination.proof_strategy == RNS.Destination.PROVE_ALL:
packet.prove()
if destination.proof_strategy == RNS.Destination.PROVE_ALL: elif destination.proof_strategy == RNS.Destination.PROVE_APP:
packet.prove() if destination.callbacks.proof_requested:
try:
elif destination.proof_strategy == RNS.Destination.PROVE_APP: if destination.callbacks.proof_requested(packet):
if destination.callbacks.proof_requested: packet.prove()
try: except Exception as e:
if destination.callbacks.proof_requested(packet): RNS.log("Error while executing proof request callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
packet.prove()
except Exception as e:
RNS.log("Error while executing proof request callback. The contained exception was: "+str(e), RNS.LOG_ERROR)
# Handling for proofs and link-request proofs # Handling for proofs and link-request proofs
elif packet.packet_type == RNS.Packet.PROOF: elif packet.packet_type == RNS.Packet.PROOF:
@@ -1895,15 +1909,15 @@ class Transport:
if packet.receiving_interface == link_entry[IDX_LT_NH_IF]: if packet.receiving_interface == link_entry[IDX_LT_NH_IF]:
try: try:
if len(packet.data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2 or len(packet.data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2+RNS.Link.LINK_MTU_SIZE: if len(packet.data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2 or len(packet.data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2+RNS.Link.LINK_MTU_SIZE:
mtu_bytes = b"" signalling_bytes = b""
if len(packet.data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2+RNS.Link.LINK_MTU_SIZE: if len(packet.data) == RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2+RNS.Link.LINK_MTU_SIZE:
mtu_bytes = RNS.Link.mtu_bytes(RNS.Link.mtu_from_lp_packet(packet)) signalling_bytes = RNS.Link.signalling_bytes(RNS.Link.mtu_from_lp_packet(packet), RNS.Link.mode_from_lp_packet(packet))
peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2] peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+RNS.Link.ECPUBSIZE//2]
peer_identity = RNS.Identity.recall(link_entry[IDX_LT_DSTHASH]) peer_identity = RNS.Identity.recall(link_entry[IDX_LT_DSTHASH])
peer_sig_pub_bytes = peer_identity.get_public_key()[RNS.Link.ECPUBSIZE//2:RNS.Link.ECPUBSIZE] peer_sig_pub_bytes = peer_identity.get_public_key()[RNS.Link.ECPUBSIZE//2:RNS.Link.ECPUBSIZE]
signed_data = packet.destination_hash+peer_pub_bytes+peer_sig_pub_bytes+mtu_bytes signed_data = packet.destination_hash+peer_pub_bytes+peer_sig_pub_bytes+signalling_bytes
signature = packet.data[:RNS.Identity.SIGLENGTH//8] signature = packet.data[:RNS.Identity.SIGLENGTH//8]
if peer_identity.validate(signature, signed_data): if peer_identity.validate(signature, signed_data):
@@ -1945,7 +1959,7 @@ class Transport:
# Add this packet to the filter hashlist if we # Add this packet to the filter hashlist if we
# have determined that it's actually destined # have determined that it's actually destined
# for this system, and then validate the proof # for this system, and then validate the proof
Transport.packet_hashlist.add(packet.packet_hash) Transport.add_packet_hash(packet.packet_hash)
link.validate_proof(packet) link.validate_proof(packet)
elif packet.context == RNS.Packet.RESOURCE_PRF: elif packet.context == RNS.Packet.RESOURCE_PRF:
@@ -2763,7 +2777,6 @@ class Transport:
Transport.reverse_table = {} Transport.reverse_table = {}
Transport.link_table = {} Transport.link_table = {}
Transport.held_announces = {} Transport.held_announces = {}
Transport.announce_handlers = []
Transport.tunnels = {} Transport.tunnels = {}
@staticmethod @staticmethod
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2022 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+101 -92
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -11,8 +11,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -25,6 +33,7 @@
import RNS import RNS
import argparse import argparse
import threading import threading
import shutil
import time import time
import sys import sys
import os import os
@@ -34,6 +43,7 @@ from RNS._version import __version__
APP_NAME = "rncp" APP_NAME = "rncp"
allow_all = False allow_all = False
allow_fetch = False allow_fetch = False
allow_overwrite_on_receive = False
fetch_auto_compress = True fetch_auto_compress = True
fetch_jail = None fetch_jail = None
save_path = None save_path = None
@@ -47,13 +57,14 @@ erase_str = "\33[2K\r"
def listen(configdir, verbosity = 0, quietness = 0, allowed = [], display_identity = False, def listen(configdir, verbosity = 0, quietness = 0, allowed = [], display_identity = False,
limit = None, disable_auth = None, fetch_allowed = False, no_compress=False, limit = None, disable_auth = None, fetch_allowed = False, no_compress=False,
jail = None, save = None, announce = False): jail = None, save = None, announce = False, allow_overwrite=False):
global allow_all, allow_fetch, allowed_identity_hashes, fetch_jail, save_path, fetch_auto_compress global allow_all, allow_fetch, allowed_identity_hashes, fetch_jail, save_path
from tempfile import TemporaryFile global fetch_auto_compress, allow_overwrite_on_receive
allow_fetch = fetch_allowed allow_fetch = fetch_allowed
fetch_auto_compress = not no_compress fetch_auto_compress = not no_compress
allow_overwrite_on_receive = allow_overwrite
identity = None identity = None
if announce < 0: if announce < 0:
announce = False announce = False
@@ -175,22 +186,15 @@ def listen(configdir, verbosity = 0, quietness = 0, allowed = [], display_identi
if target_link != None: if target_link != None:
RNS.log("Sending file "+str(file_path)+" to client", RNS.LOG_VERBOSE) RNS.log("Sending file "+str(file_path)+" to client", RNS.LOG_VERBOSE)
temp_file = TemporaryFile() try:
real_file = open(file_path, "rb") metadata = {"name": os.path.basename(file_path).encode("utf-8") }
filename_bytes = os.path.basename(file_path).encode("utf-8") fetch_resource = RNS.Resource(open(file_path, "rb"), target_link, metadata=metadata, auto_compress=fetch_auto_compress)
filename_len = len(filename_bytes) return True
if filename_len > 0xFFFF: except Exception as e:
print("Filename exceeds max size, cannot send") RNS.log(f"Could not send file to client. The contained exception was: {e}", RNS.LOG_ERROR)
RNS.exit(1) return False
temp_file.write(filename_len.to_bytes(2, "big"))
temp_file.write(filename_bytes)
temp_file.write(real_file.read())
temp_file.seek(0)
fetch_resource = RNS.Resource(temp_file, target_link, auto_compress=fetch_auto_compress)
return True
else: else:
return None return None
@@ -215,8 +219,7 @@ def listen(configdir, verbosity = 0, quietness = 0, allowed = [], display_identi
threading.Thread(target=job, daemon=True).start() threading.Thread(target=job, daemon=True).start()
while True: while True: time.sleep(1)
time.sleep(1)
def client_link_established(link): def client_link_established(link):
RNS.log("Incoming link established", RNS.LOG_VERBOSE) RNS.log("Incoming link established", RNS.LOG_VERBOSE)
@@ -261,34 +264,42 @@ def receive_resource_started(resource):
print("Starting resource transfer "+RNS.prettyhexrep(resource.hash)+id_str) print("Starting resource transfer "+RNS.prettyhexrep(resource.hash)+id_str)
def receive_resource_concluded(resource): def receive_resource_concluded(resource):
global save_path global save_path, allow_overwrite_on_receive
if resource.status == RNS.Resource.COMPLETE: if resource.status == RNS.Resource.COMPLETE:
print(str(resource)+" completed") print(str(resource)+" completed")
if resource.total_size > 4: if resource.metadata == None:
filename_len = int.from_bytes(resource.data.read(2), "big") print("Invalid data received, ignoring resource")
filename = resource.data.read(filename_len).decode("utf-8") return
counter = 0
if save_path:
saved_filename = os.path.abspath(os.path.expanduser(save_path+"/"+filename))
if not saved_filename.startswith(save_path+"/"):
RNS.log(f"Invalid save path {saved_filename}, ignoring", RNS.LOG_ERROR)
return
else:
saved_filename = filename
full_save_path = saved_filename
while os.path.isfile(full_save_path):
counter += 1
full_save_path = saved_filename+"."+str(counter)
file = open(full_save_path, "wb")
file.write(resource.data.read())
file.close()
else: else:
print("Invalid data received, ignoring resource") try:
filename = os.path.basename(resource.metadata["name"].decode("utf-8"))
counter = 0
if save_path:
saved_filename = os.path.abspath(os.path.expanduser(save_path+"/"+filename))
if not saved_filename.startswith(save_path+"/"):
RNS.log(f"Invalid save path {saved_filename}, ignoring", RNS.LOG_ERROR)
return
else:
saved_filename = filename
full_save_path = saved_filename
if allow_overwrite_on_receive:
if os.path.isfile(full_save_path):
try: os.unlink(full_save_path)
except Exception as e:
RNS.log(f"Could not overwrite existing file {full_save_path}, renaming instead", RNS.LOG_ERROR)
while os.path.isfile(full_save_path):
counter += 1
full_save_path = saved_filename+"."+str(counter)
shutil.move(resource.data.name, full_save_path)
except Exception as e:
RNS.log(f"An error occurred while saving received resource: {e}", RNS.LOG_ERROR)
return
else: else:
print("Resource failed") print("Resource failed")
@@ -334,10 +345,11 @@ def sender_progress(resource):
resource_done = True resource_done = True
link = None link = None
def fetch(configdir, verbosity = 0, quietness = 0, destination = None, file = None, timeout = RNS.Transport.PATH_REQUEST_TIMEOUT, silent=False, phy_rates=False, save=None): def fetch(configdir, verbosity = 0, quietness = 0, destination = None, file = None, timeout = RNS.Transport.PATH_REQUEST_TIMEOUT, silent=False, phy_rates=False, save=None, allow_overwrite=False):
global current_resource, resource_done, link, speed, show_phy_rates, save_path global current_resource, resource_done, link, speed, show_phy_rates, save_path, allow_overwrite_on_receive
targetloglevel = 3+verbosity-quietness targetloglevel = 3+verbosity-quietness
show_phy_rates = phy_rates show_phy_rates = phy_rates
allow_overwrite_on_receive = allow_overwrite
if save: if save:
sp = os.path.abspath(os.path.expanduser(save)) sp = os.path.abspath(os.path.expanduser(save))
@@ -473,32 +485,40 @@ def fetch(configdir, verbosity = 0, quietness = 0, destination = None, file = No
def fetch_resource_concluded(resource): def fetch_resource_concluded(resource):
nonlocal resource_resolved, resource_status nonlocal resource_resolved, resource_status
global save_path global save_path, allow_overwrite_on_receive
if resource.status == RNS.Resource.COMPLETE: if resource.status == RNS.Resource.COMPLETE:
if resource.total_size > 4: if resource.metadata == None:
filename_len = int.from_bytes(resource.data.read(2), "big") print("Invalid data received, ignoring resource")
filename = resource.data.read(filename_len).decode("utf-8") return
counter = 0
if save_path:
saved_filename = os.path.abspath(os.path.expanduser(save_path+"/"+filename))
else:
saved_filename = filename
full_save_path = saved_filename
while os.path.isfile(full_save_path):
counter += 1
full_save_path = saved_filename+"."+str(counter)
file = open(full_save_path, "wb")
file.write(resource.data.read())
file.close()
resource_status = "completed"
else: else:
print("Invalid data received, ignoring resource") try:
resource_status = "invalid_data" filename = os.path.basename(resource.metadata["name"].decode("utf-8"))
counter = 0
if save_path:
saved_filename = os.path.abspath(os.path.expanduser(save_path+"/"+filename))
if not saved_filename.startswith(save_path+"/"):
print(f"Invalid save path {saved_filename}, ignoring")
return
else:
saved_filename = filename
full_save_path = saved_filename
if allow_overwrite_on_receive:
if os.path.isfile(full_save_path):
try: os.unlink(full_save_path)
except Exception as e:
print(f"Could not overwrite existing file {full_save_path}, renaming instead")
while os.path.isfile(full_save_path):
counter += 1
full_save_path = saved_filename+"."+str(counter)
shutil.move(resource.data.name, full_save_path)
except Exception as e:
print(f"An error occurred while saving received resource: {e}")
return
else: else:
print("Resource failed") print("Resource failed")
@@ -596,7 +616,6 @@ def fetch(configdir, verbosity = 0, quietness = 0, destination = None, file = No
def send(configdir, verbosity = 0, quietness = 0, destination = None, file = None, timeout = RNS.Transport.PATH_REQUEST_TIMEOUT, silent=False, phy_rates=False, no_compress=False): def send(configdir, verbosity = 0, quietness = 0, destination = None, file = None, timeout = RNS.Transport.PATH_REQUEST_TIMEOUT, silent=False, phy_rates=False, no_compress=False):
global current_resource, resource_done, link, speed, show_phy_rates, phy_got_total, phy_speed global current_resource, resource_done, link, speed, show_phy_rates, phy_got_total, phy_speed
from tempfile import TemporaryFile
targetloglevel = 3+verbosity-quietness targetloglevel = 3+verbosity-quietness
show_phy_rates = phy_rates show_phy_rates = phy_rates
@@ -618,21 +637,7 @@ def send(configdir, verbosity = 0, quietness = 0, destination = None, file = Non
print("File not found") print("File not found")
sys.exit(1) sys.exit(1)
temp_file = TemporaryFile() metadata = {"name": os.path.basename(file_path).encode("utf-8") }
real_file = open(file_path, "rb")
filename_bytes = os.path.basename(file_path).encode("utf-8")
filename_len = len(filename_bytes)
if filename_len > 0xFFFF:
print("Filename exceeds max size, cannot send")
RNS.exit(1)
else:
print("Preparing file...", end=es)
temp_file.write(filename_len.to_bytes(2, "big"))
temp_file.write(filename_bytes)
temp_file.write(real_file.read())
temp_file.seek(0)
print(f"{erase_str}", end="") print(f"{erase_str}", end="")
@@ -719,9 +724,12 @@ def send(configdir, verbosity = 0, quietness = 0, destination = None, file = Non
link.identify(identity) link.identify(identity)
auto_compress = True auto_compress = True
if no_compress: if no_compress: auto_compress = False
auto_compress = False try: resource = RNS.Resource(open(file_path, "rb"), link, metadata=metadata, callback = sender_progress, progress_callback = sender_progress, auto_compress = auto_compress)
resource = RNS.Resource(temp_file, link, callback = sender_progress, progress_callback = sender_progress, auto_compress = auto_compress) except Exception as e:
print(f"Could not start transfer: {e}")
RNS.exit(1)
current_resource = resource current_resource = resource
while resource.status < RNS.Resource.TRANSFERRING: while resource.status < RNS.Resource.TRANSFERRING:
@@ -792,8 +800,6 @@ def send(configdir, verbosity = 0, quietness = 0, destination = None, file = Non
print("\n"+str(file_path)+" copied to "+RNS.prettyhexrep(destination_hash)) print("\n"+str(file_path)+" copied to "+RNS.prettyhexrep(destination_hash))
link.teardown() link.teardown()
time.sleep(0.25) time.sleep(0.25)
real_file.close()
temp_file.close()
RNS.exit(0) RNS.exit(0)
def main(): def main():
@@ -811,6 +817,7 @@ def main():
parser.add_argument("-f", '--fetch', action='store_true', default=False, help="fetch file from remote listener instead of sending") parser.add_argument("-f", '--fetch', action='store_true', default=False, help="fetch file from remote listener instead of sending")
parser.add_argument("-j", "--jail", metavar="path", action="store", default=None, help="restrict fetch requests to specified path", type=str) parser.add_argument("-j", "--jail", metavar="path", action="store", default=None, help="restrict fetch requests to specified path", type=str)
parser.add_argument("-s", "--save", metavar="path", action="store", default=None, help="save received files in specified path", type=str) parser.add_argument("-s", "--save", metavar="path", action="store", default=None, help="save received files in specified path", type=str)
parser.add_argument('-O', '--overwrite', action='store_true', default=False, help="Allow overwriting received files, instead of adding postfix")
parser.add_argument("-b", action='store', metavar="seconds", default=-1, help="announce interval, 0 to only announce at startup", type=int) parser.add_argument("-b", action='store', metavar="seconds", default=-1, help="announce interval, 0 to only announce at startup", type=int)
parser.add_argument('-a', metavar="allowed_hash", dest="allowed", action='append', help="allow this identity (or add in ~/.rncp/allowed_identities)", type=str) parser.add_argument('-a', metavar="allowed_hash", dest="allowed", action='append', help="allow this identity (or add in ~/.rncp/allowed_identities)", type=str)
parser.add_argument('-n', '--no-auth', action='store_true', default=False, help="accept requests from anyone") parser.add_argument('-n', '--no-auth', action='store_true', default=False, help="accept requests from anyone")
@@ -836,6 +843,7 @@ def main():
# limit=args.limit, # limit=args.limit,
disable_auth=args.no_auth, disable_auth=args.no_auth,
announce=args.b, announce=args.b,
allow_overwrite=args.overwrite,
) )
elif args.fetch: elif args.fetch:
@@ -850,6 +858,7 @@ def main():
silent = args.silent, silent = args.silent,
phy_rates = args.phy_rates, phy_rates = args.phy_rates,
save = args.save, save = args.save,
allow_overwrite=args.overwrite,
) )
else: else:
print("") print("")
+12 -4
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# MIT License # Reticulum License
# #
# Copyright (c) 2023-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -11,8 +11,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# MIT License # Reticulum License
# #
# Copyright (c) 2023-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -11,8 +11,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# MIT License # Reticulum License
# #
# Copyright (c) 2018-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -11,8 +11,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -11,8 +11,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -11,8 +11,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+31 -11
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -11,8 +11,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
@@ -109,12 +117,24 @@ share_instance = Yes
# If you want to run multiple *different* shared instances # If you want to run multiple *different* shared instances
# on the same system, you will need to specify different # on the same system, you will need to specify different
# shared instance ports for each. The defaults are given # instance names for each. On platforms supporting domain
# below, and again, these options can be left out if you # sockets, this can be done with the instance_name option:
# don't need them.
shared_instance_port = 37428 instance_name = default
instance_control_port = 37429
# Some platforms don't support domain sockets, and if that
# is the case, you can isolate different instances by
# specifying a unique set of ports for each:
# shared_instance_port = 37428
# instance_control_port = 37429
# If you want to explicitly use TCP for shared instance
# communication, instead of domain sockets, this is also
# possible, by using the following option:
# shared_instance_type = tcp
# On systems where running instances may not have access # On systems where running instances may not have access
@@ -146,7 +166,7 @@ instance_control_port = 37429
# an optional directive, and can be left out for brevity. # an optional directive, and can be left out for brevity.
# This behaviour is disabled by default. # This behaviour is disabled by default.
panic_on_interface_error = No # panic_on_interface_error = No
# When Transport is enabled, it is possible to allow the # When Transport is enabled, it is possible to allow the
@@ -157,7 +177,7 @@ panic_on_interface_error = No
# Transport Instance, and printed to the log at startup. # Transport Instance, and printed to the log at startup.
# Optional, and disabled by default. # Optional, and disabled by default.
respond_to_probes = No # respond_to_probes = No
[logging] [logging]
+12 -4
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -11,8 +11,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -11,8 +11,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+12 -4
View File
@@ -1,6 +1,6 @@
# MIT License # Reticulum License
# #
# Copyright (c) 2016-2025 Mark Qvist / unsigned.io and contributors # Copyright (c) 2016-2025 Mark Qvist
# #
# Permission is hereby granted, free of charge, to any person obtaining a copy # Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal # of this software and associated documentation files (the "Software"), to deal
@@ -9,8 +9,16 @@
# copies of the Software, and to permit persons to whom the Software is # copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions: # furnished to do so, subject to the following conditions:
# #
# The above copyright notice and this permission notice shall be included in all # - The Software shall not be used in any kind of system which includes amongst
# copies or substantial portions of the Software. # 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 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.9.4" __version__ = "0.9.6"
+30
View File
@@ -1,3 +1,33 @@
# Reticulum License
#
# Copyright (c) 2016-2025 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.
def get_platform(): def get_platform():
from os import environ from os import environ
if "ANDROID_ARGUMENT" in environ: return "android" if "ANDROID_ARGUMENT" in environ: return "android"
+3 -18
View File
@@ -14,18 +14,6 @@ This document outlines the currently established development roadmap for Reticul
## Currently Active Work Areas ## Currently Active Work Areas
For each release cycle of Reticulum, improvements and additions from the five [Primary Efforts](#primary-efforts) are selected as active work areas, and can be expected to be included in the upcoming releases within that cycle. While not entirely set in stone for each release cycle, they serve as a pointer of what to expect in the near future. For each release cycle of Reticulum, improvements and additions from the five [Primary Efforts](#primary-efforts) are selected as active work areas, and can be expected to be included in the upcoming releases within that cycle. While not entirely set in stone for each release cycle, they serve as a pointer of what to expect in the near future.
- The current `0.8.x` release cycle aims at completing
- [ ] Hot-pluggable interface system
- [ ] External interface plugins
- [ ] Network-wide path balancing and multi-pathing
- [ ] Expanded hardware support
- [ ] Overhauling and updating the documentation
- [ ] Distributed Destination Naming System
- [ ] A standalone RNS Daemon app for Android
- [ ] Addding automatic retries to all use cases of the `Request` API
- [ ] Performance and memory optimisations of the Python reference implementation
- [ ] Fixing bugs discovered while operating Reticulum systems and applications
## Primary Efforts ## Primary Efforts
The development path for Reticulum is currently laid out in five distinct areas: *Comprehensibility*, *Universality*, *Functionality*, *Usability & Utility* and *Interfaceability*. Conceptualising the development of Reticulum into these areas serves to advance the implementation and work towards the Foundational Goals & Values of Reticulum. The development path for Reticulum is currently laid out in five distinct areas: *Comprehensibility*, *Universality*, *Functionality*, *Usability & Utility* and *Interfaceability*. Conceptualising the development of Reticulum into these areas serves to advance the implementation and work towards the Foundational Goals & Values of Reticulum.
@@ -50,17 +38,14 @@ These efforts are aimed at improving the ease of which Reticulum is understood,
### Universality ### Universality
These efforts seek to broaden the universality of the Reticulum software and hardware ecosystem by continously diversifying platform support, and by improving the overall availability and ease of deployment of the Reticulum stack. These efforts seek to broaden the universality of the Reticulum software and hardware ecosystem by continously diversifying platform support, and by improving the overall availability and ease of deployment of the Reticulum stack.
- OpenWRT support
- Create a standalone RNS Daemon app for Android - Create a standalone RNS Daemon app for Android
- A lightweight and portable C implementation for microcontrollers, µRNS - A lightweight and portable C implementation for microcontrollers, µRNS
- A portable, high-performance Reticulum implementation in C/C++, see [#21](https://github.com/markqvist/Reticulum/discussions/21) - A portable, high-performance Reticulum implementation in C/C++, see [#21](https://github.com/markqvist/Reticulum/discussions/21)
- Performance and memory optimisations of the Python implementation
- Bindings for other programming languages - Bindings for other programming languages
### Functionality ### Functionality
These efforts aim to expand and improve the core functionality and reliability of Reticulum. These efforts aim to expand and improve the core functionality and reliability of Reticulum.
- Add support for user-supplied external interface drivers
- Add interface hot-plug and live up/down control to running instances - Add interface hot-plug and live up/down control to running instances
- Add automatic retries to all use cases of the `Request` API - Add automatic retries to all use cases of the `Request` API
- Network-wide path balancing - Network-wide path balancing
@@ -70,11 +55,11 @@ These efforts aim to expand and improve the core functionality and reliability o
- [Metric-based path selection and multiple paths](https://github.com/markqvist/Reticulum/discussions/86) - [Metric-based path selection and multiple paths](https://github.com/markqvist/Reticulum/discussions/86)
### Usability & Utility ### Usability & Utility
These effors seek to make Reticulum easier to use and operate, and to expand the utility of the stack on deployed systems. These efforts seek to make Reticulum easier to use and operate, and to expand the utility of the stack on deployed systems.
- Easy way to share interface configurations, see [#19](https://github.com/markqvist/Reticulum/discussions/19) - Easy way to share interface configurations, see [#19](https://github.com/markqvist/Reticulum/discussions/19)
- Transit traffic display in rnstatus - Transit traffic display in `rnstatus`
- rnsconfig utility - `rnsconfig` utility
### Interfaceability ### Interfaceability
These efforts aim to expand the types of physical and virtual interfaces that Reticulum can natively use to transport data. These efforts aim to expand the types of physical and virtual interfaces that Reticulum can natively use to transport data.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1,4 +1,4 @@
# Sphinx build info version 1 # Sphinx build info version 1
# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
config: b499af51edc22529181ef3b25973fa2b config: cce3deb193d6110f18b4ace0b3f4099b
tags: 645f666f9bcd5a90fca523b33c5a78b7 tags: 645f666f9bcd5a90fca523b33c5a78b7
+15 -7
View File
@@ -453,7 +453,7 @@ For exchanges of small amounts of information, Reticulum offers the *Packet* API
public signing key. public signing key.
* | In case the packet is addressed to a *group* destination type, the packet will be encrypted with the * | In case the packet is addressed to a *group* destination type, the packet will be encrypted with the
pre-shared AES-128 key associated with the destination. In case the packet is addressed to a *plain* pre-shared AES-256 key associated with the destination. In case the packet is addressed to a *plain*
destination type, the payload data will not be encrypted. Neither of these two destination types can offer destination type, the payload data will not be encrypted. Neither of these two destination types can offer
forward secrecy. In general, it is recommended to always use the *single* destination type, unless it is forward secrecy. In general, it is recommended to always use the *single* destination type, unless it is
strictly necessary to use one of the others. strictly necessary to use one of the others.
@@ -858,9 +858,17 @@ of the different interface modes, and how they are configured.
Cryptographic Primitives Cryptographic Primitives
------------------------ ------------------------
Reticulum has been designed to use a simple suite of efficient, strong and modern Reticulum uses a simple suite of efficient, strong and well-tested cryptographic
cryptographic primitives, with widely available implementations that can be used primitives, with widely available implementations that can be used both on
both on general-purpose CPUs and on microcontrollers. The necessary primitives are: general-purpose CPUs and on microcontrollers.
One of the primary considerations for choosing this particular set of primitives is
that they can be implemented *safely* with relatively few pitfalls, on practically
all current computing platforms.
The primitives listed here **are authoritative**. Anything claiming to be Reticulum,
but not using these exact primitives **is not** Reticulum, and possibly an
intentionally compromised or weakened clone. The utilised primitives are:
* Ed25519 for signatures * Ed25519 for signatures
@@ -872,11 +880,11 @@ both on general-purpose CPUs and on microcontrollers. The necessary primitives a
* Ephemeral keys derived from an ECDH key exchange on Curve25519 * Ephemeral keys derived from an ECDH key exchange on Curve25519
* AES-128 in CBC mode with PKCS7 padding * AES-256 in CBC mode with PKCS7 padding
* HMAC using SHA256 for message authentication * HMAC using SHA256 for message authentication
* IVs are generated through os.urandom() * IVs must be generated through ``os.urandom()`` or better
* No Fernet version and timestamp metadata fields * No Fernet version and timestamp metadata fields
@@ -884,7 +892,7 @@ both on general-purpose CPUs and on microcontrollers. The necessary primitives a
* SHA-512 * SHA-512
In the default installation configuration, the ``X25519``, ``Ed25519`` and ``AES-128-CBC`` In the default installation configuration, the ``X25519``, ``Ed25519`` and ``AES-256-CBC``
primitives are provided by `OpenSSL <https://www.openssl.org/>`_ (via the `PyCA/cryptography <https://github.com/pyca/cryptography>`_ primitives are provided by `OpenSSL <https://www.openssl.org/>`_ (via the `PyCA/cryptography <https://github.com/pyca/cryptography>`_
package). The hashing functions ``SHA-256`` and ``SHA-512`` are provided by the standard package). The hashing functions ``SHA-256`` and ``SHA-512`` are provided by the standard
Python `hashlib <https://docs.python.org/3/library/hashlib.html>`_. The ``HKDF``, ``HMAC``, Python `hashlib <https://docs.python.org/3/library/hashlib.html>`_. The ``HKDF``, ``HMAC``,
+34 -10
View File
@@ -69,12 +69,12 @@ configuration file is created. The default configuration looks like this:
# If you enable Transport, your system will route traffic # If you enable Transport, your system will route traffic
# for other peers, pass announces and serve path requests. # for other peers, pass announces and serve path requests.
# This should only be done for systems that are suited to # This should be done for systems that are suited to act
# act as transport nodes, ie. if they are stationary and # as transport nodes, ie. if they are stationary and
# always-on. This directive is optional and can be removed # always-on. This directive is optional and can be removed
# for brevity. # for brevity.
enable_transport = False enable_transport = No
# By default, the first program to launch the Reticulum # By default, the first program to launch the Reticulum
@@ -91,12 +91,24 @@ configuration file is created. The default configuration looks like this:
# If you want to run multiple *different* shared instances # If you want to run multiple *different* shared instances
# on the same system, you will need to specify different # on the same system, you will need to specify different
# shared instance ports for each. The defaults are given # instance names for each. On platforms supporting domain
# below, and again, these options can be left out if you # sockets, this can be done with the instance_name option:
# don't need them.
shared_instance_port = 37428 instance_name = default
instance_control_port = 37429
# Some platforms don't support domain sockets, and if that
# is the case, you can isolate different instances by
# specifying a unique set of ports for each:
# shared_instance_port = 37428
# instance_control_port = 37429
# If you want to explicitly use TCP for shared instance
# communication, instead of domain sockets, this is also
# possible, by using the following option:
# shared_instance_type = tcp
# On systems where running instances may not have access # On systems where running instances may not have access
@@ -110,13 +122,25 @@ configuration file is created. The default configuration looks like this:
# rpc_key = e5c032d3ec4e64a6aca9927ba8ab73336780f6d71790 # rpc_key = e5c032d3ec4e64a6aca9927ba8ab73336780f6d71790
# It is possible to allow remote management of Reticulum
# systems using the various built-in utilities, such as
# rnstatus and rnpath. You will need to specify one or
# more Reticulum Identity hashes for authenticating the
# queries from client programs. For this purpose, you can
# use existing identity files, or generate new ones with
# the rnid utility.
# enable_remote_management = yes
# remote_management_allowed = 9fb6d773498fb3feda407ed8ef2c3229, 2d882c5586e548d79b5af27bca1776dc
# You can configure Reticulum to panic and forcibly close # You can configure Reticulum to panic and forcibly close
# if an unrecoverable interface error occurs, such as the # if an unrecoverable interface error occurs, such as the
# hardware device for an interface disappearing. This is # hardware device for an interface disappearing. This is
# an optional directive, and can be left out for brevity. # an optional directive, and can be left out for brevity.
# This behaviour is disabled by default. # This behaviour is disabled by default.
panic_on_interface_error = No # panic_on_interface_error = No
# When Transport is enabled, it is possible to allow the # When Transport is enabled, it is possible to allow the
@@ -127,7 +151,7 @@ configuration file is created. The default configuration looks like this:
# Transport Instance, and printed to the log at startup. # Transport Instance, and printed to the log at startup.
# Optional, and disabled by default. # Optional, and disabled by default.
respond_to_probes = No # respond_to_probes = No
[logging] [logging]
+1 -1
View File
@@ -68,7 +68,7 @@ What does Reticulum Offer?
* Ephemeral per-packet and link keys and derived from an ECDH key exchange on Curve25519 * Ephemeral per-packet and link keys and derived from an ECDH key exchange on Curve25519
* AES-128 in CBC mode with PKCS7 padding * AES-256 in CBC mode with PKCS7 padding
* HMAC using SHA256 for authentication * HMAC using SHA256 for authentication
+1 -1
View File
@@ -1,6 +1,6 @@
var DOCUMENTATION_OPTIONS = { var DOCUMENTATION_OPTIONS = {
URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'),
VERSION: '0.9.4 beta', VERSION: '0.9.6 beta',
LANGUAGE: 'en', LANGUAGE: 'en',
COLLAPSE_INDEX: false, COLLAPSE_INDEX: false,
BUILDER: 'html', BUILDER: 'html',
+6 -8
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Support Reticulum" href="support.html" /><link rel="prev" title="Building Networks" href="networks.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Support Reticulum" href="support.html" /><link rel="prev" title="Building Networks" href="networks.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>Code Examples - Reticulum Network Stack 0.9.4 beta documentation</title> <title>Code Examples - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -1610,8 +1610,8 @@ the link has been established.</p>
<span id="example-request"></span><h2>Requests &amp; Responses<a class="headerlink" href="#requests-responses" title="Permalink to this heading">#</a></h2> <span id="example-request"></span><h2>Requests &amp; Responses<a class="headerlink" href="#requests-responses" title="Permalink to this heading">#</a></h2>
<p>The <em>Request</em> example explores sending requests and receiving responses.</p> <p>The <em>Request</em> example explores sending requests and receiving responses.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1">##########################################################</span> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1">##########################################################</span>
<span class="c1"># This RNS example demonstrates how to set perform #</span> <span class="c1"># This RNS example demonstrates how to perform requests #</span>
<span class="c1"># requests and receive responses over a link. #</span> <span class="c1"># and receive responses over a link. #</span>
<span class="c1">##########################################################</span> <span class="c1">##########################################################</span>
<span class="kn">import</span><span class="w"> </span><span class="nn">os</span> <span class="kn">import</span><span class="w"> </span><span class="nn">os</span>
@@ -3244,9 +3244,7 @@ interface to efficiently pass files of any size over a Reticulum <a class="refer
Any number of custom interfaces can be loaded and utilised by Reticulum, and Any number of custom interfaces can be loaded and utilised by Reticulum, and
will be fully on-par with natively included interfaces, including all supported will be fully on-par with natively included interfaces, including all supported
<a class="reference internal" href="interfaces.html#interfaces-modes"><span class="std std-ref">interface modes</span></a> and <a class="reference internal" href="interfaces.html#interfaces-options"><span class="std std-ref">common configuration options</span></a>.</p> <a class="reference internal" href="interfaces.html#interfaces-modes"><span class="std std-ref">interface modes</span></a> and <a class="reference internal" href="interfaces.html#interfaces-options"><span class="std std-ref">common configuration options</span></a>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># MIT License - Copyright (c) 2024 Mark Qvist / unsigned.io</span> <div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># This example illustrates creating a custom interface</span>
<span class="c1"># This example illustrates creating a custom interface</span>
<span class="c1"># definition, that can be loaded and used by Reticulum at</span> <span class="c1"># definition, that can be loaded and used by Reticulum at</span>
<span class="c1"># runtime. Any number of custom interfaces can be created</span> <span class="c1"># runtime. Any number of custom interfaces can be created</span>
<span class="c1"># and loaded. To use the interface place it in the folder</span> <span class="c1"># and loaded. To use the interface place it in the folder</span>
+3 -3
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>An Explanation of Reticulum for Human Beings - Reticulum Network Stack 0.9.4 beta documentation</title> <title>An Explanation of Reticulum for Human Beings - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
+5 -3
View File
@@ -4,7 +4,7 @@
<meta name="viewport" content="width=device-width,initial-scale=1"/> <meta name="viewport" content="width=device-width,initial-scale=1"/>
<meta name="color-scheme" content="light dark"><link rel="index" title="Index" href="#" /><link rel="search" title="Search" href="search.html" /> <meta name="color-scheme" content="light dark"><link rel="index" title="Index" href="#" /><link rel="search" title="Search" href="search.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/><title>Index - Reticulum Network Stack 0.9.4 beta documentation</title> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/><title>Index - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -139,7 +139,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -165,7 +165,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -389,6 +389,8 @@
<li><a href="reference.html#RNS.Reticulum.get_instance">get_instance() (RNS.Reticulum static method)</a> <li><a href="reference.html#RNS.Reticulum.get_instance">get_instance() (RNS.Reticulum static method)</a>
</li> </li>
<li><a href="reference.html#RNS.Link.get_mdu">get_mdu() (RNS.Link method)</a> <li><a href="reference.html#RNS.Link.get_mdu">get_mdu() (RNS.Link method)</a>
</li>
<li><a href="reference.html#RNS.Link.get_mode">get_mode() (RNS.Link method)</a>
</li> </li>
<li><a href="reference.html#RNS.Link.get_mtu">get_mtu() (RNS.Link method)</a> <li><a href="reference.html#RNS.Link.get_mtu">get_mtu() (RNS.Link method)</a>
</li> </li>
+3 -3
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Using Reticulum on Your System" href="using.html" /><link rel="prev" title="What is Reticulum?" href="whatis.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Using Reticulum on Your System" href="using.html" /><link rel="prev" title="What is Reticulum?" href="whatis.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>Getting Started Fast - Reticulum Network Stack 0.9.4 beta documentation</title> <title>Getting Started Fast - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
+3 -3
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Configuring Interfaces" href="interfaces.html" /><link rel="prev" title="Understanding Reticulum" href="understanding.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Configuring Interfaces" href="interfaces.html" /><link rel="prev" title="Understanding Reticulum" href="understanding.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>Communications Hardware - Reticulum Network Stack 0.9.4 beta documentation</title> <title>Communications Hardware - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
+3 -3
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="What is Reticulum?" href="whatis.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="What is Reticulum?" href="whatis.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>Reticulum Network Stack 0.9.4 beta documentation</title> <title>Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="#"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="#"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
+3 -3
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Building Networks" href="networks.html" /><link rel="prev" title="Communications Hardware" href="hardware.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Building Networks" href="networks.html" /><link rel="prev" title="Communications Hardware" href="hardware.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>Configuring Interfaces - Reticulum Network Stack 0.9.4 beta documentation</title> <title>Configuring Interfaces - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
+3 -3
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Code Examples" href="examples.html" /><link rel="prev" title="Configuring Interfaces" href="interfaces.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Code Examples" href="examples.html" /><link rel="prev" title="Configuring Interfaces" href="interfaces.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>Building Networks - Reticulum Network Stack 0.9.4 beta documentation</title> <title>Building Networks - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
Binary file not shown.
+21 -9
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="prev" title="Support Reticulum" href="support.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="prev" title="Support Reticulum" href="support.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>API Reference - Reticulum Network Stack 0.9.4 beta documentation</title> <title>API Reference - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -228,7 +228,7 @@ This chapter lists and explains all classes exposed by the Reticulum Network Sta
<p id="api-reticulum"><h3> Reticulum </h3></p> <p id="api-reticulum"><h3> Reticulum </h3></p>
<dl class="py class"> <dl class="py class">
<dt class="sig sig-object py" id="RNS.Reticulum"> <dt class="sig sig-object py" id="RNS.Reticulum">
<em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">RNS.</span></span><span class="sig-name descname"><span class="pre">Reticulum</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">configdir</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">loglevel</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">logdest</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">verbosity</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">require_shared_instance</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum" title="Permalink to this definition">#</a></dt> <em class="property"><span class="pre">class</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">RNS.</span></span><span class="sig-name descname"><span class="pre">Reticulum</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">configdir</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">loglevel</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">logdest</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">verbosity</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">require_shared_instance</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">shared_instance_type</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Reticulum" title="Permalink to this definition">#</a></dt>
<dd><p>This class is used to initialise access to Reticulum within a <dd><p>This class is used to initialise access to Reticulum within a
program. You must create exactly one instance of this class before program. You must create exactly one instance of this class before
carrying out any other RNS operations, such as creating destinations carrying out any other RNS operations, such as creating destinations
@@ -817,7 +817,7 @@ proofs should be returned for received packets.</p>
<dl class="py method"> <dl class="py method">
<dt class="sig sig-object py" id="RNS.Destination.register_request_handler"> <dt class="sig sig-object py" id="RNS.Destination.register_request_handler">
<span class="sig-name descname"><span class="pre">register_request_handler</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">path</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">response_generator</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">allow</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">ALLOW_NONE</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">allowed_list</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Destination.register_request_handler" title="Permalink to this definition">#</a></dt> <span class="sig-name descname"><span class="pre">register_request_handler</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">path</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">response_generator</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">allow</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">ALLOW_NONE</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">allowed_list</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">auto_compress</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Destination.register_request_handler" title="Permalink to this definition">#</a></dt>
<dd><p>Registers a request handler.</p> <dd><p>Registers a request handler.</p>
<dl class="field-list simple"> <dl class="field-list simple">
<dt class="field-odd">Parameters<span class="colon">:</span></dt> <dt class="field-odd">Parameters<span class="colon">:</span></dt>
@@ -826,6 +826,7 @@ proofs should be returned for received packets.</p>
<li><p><strong>response_generator</strong> – A function or method with the signature <em>response_generator(path, data, request_id, link_id, remote_identity, requested_at)</em> to be called. Whatever this funcion returns will be sent as a response to the requester. If the function returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, no response will be sent.</p></li> <li><p><strong>response_generator</strong> – A function or method with the signature <em>response_generator(path, data, request_id, link_id, remote_identity, requested_at)</em> to be called. Whatever this funcion returns will be sent as a response to the requester. If the function returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, no response will be sent.</p></li>
<li><p><strong>allow</strong> – One of <code class="docutils literal notranslate"><span class="pre">RNS.Destination.ALLOW_NONE</span></code>, <code class="docutils literal notranslate"><span class="pre">RNS.Destination.ALLOW_ALL</span></code> or <code class="docutils literal notranslate"><span class="pre">RNS.Destination.ALLOW_LIST</span></code>. If <code class="docutils literal notranslate"><span class="pre">RNS.Destination.ALLOW_LIST</span></code> is set, the request handler will only respond to requests for identified peers in the supplied list.</p></li> <li><p><strong>allow</strong> – One of <code class="docutils literal notranslate"><span class="pre">RNS.Destination.ALLOW_NONE</span></code>, <code class="docutils literal notranslate"><span class="pre">RNS.Destination.ALLOW_ALL</span></code> or <code class="docutils literal notranslate"><span class="pre">RNS.Destination.ALLOW_LIST</span></code>. If <code class="docutils literal notranslate"><span class="pre">RNS.Destination.ALLOW_LIST</span></code> is set, the request handler will only respond to requests for identified peers in the supplied list.</p></li>
<li><p><strong>allowed_list</strong> – A list of <em>bytes-like</em> <a class="reference internal" href="#api-identity"><span class="std std-ref">RNS.Identity</span></a> hashes.</p></li> <li><p><strong>allowed_list</strong> – A list of <em>bytes-like</em> <a class="reference internal" href="#api-identity"><span class="std std-ref">RNS.Identity</span></a> hashes.</p></li>
<li><p><strong>auto_compress</strong> – If <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>, determines whether automatic compression of responses should be carried out. If set to an integer value, responses will only be auto-compressed if under this size in bytes. If omitted, the default compression settings will be followed.</p></li>
</ul> </ul>
</dd> </dd>
<dt class="field-even">Raises<span class="colon">:</span></dt> <dt class="field-even">Raises<span class="colon">:</span></dt>
@@ -1015,9 +1016,9 @@ they are addressed to a <code class="docutils literal notranslate"><span class="
<code class="docutils literal notranslate"><span class="pre">RNS.Destination.GROUP</span></code> destination or a <a class="reference internal" href="#api-link"><span class="std std-ref">RNS.Link</span></a>.</p> <code class="docutils literal notranslate"><span class="pre">RNS.Destination.GROUP</span></code> destination or a <a class="reference internal" href="#api-link"><span class="std std-ref">RNS.Link</span></a>.</p>
<p>For <code class="docutils literal notranslate"><span class="pre">RNS.Destination.GROUP</span></code> destinations, Reticulum will use the <p>For <code class="docutils literal notranslate"><span class="pre">RNS.Destination.GROUP</span></code> destinations, Reticulum will use the
pre-shared key configured for the destination. All packets to group pre-shared key configured for the destination. All packets to group
destinations are encrypted with the same AES-128 key.</p> destinations are encrypted with the same AES-256 key.</p>
<p>For <code class="docutils literal notranslate"><span class="pre">RNS.Destination.SINGLE</span></code> destinations, Reticulum will use a newly <p>For <code class="docutils literal notranslate"><span class="pre">RNS.Destination.SINGLE</span></code> destinations, Reticulum will use a newly
derived ephemeral AES-128 key for every packet.</p> derived ephemeral AES-256 key for every packet.</p>
<p>For <a class="reference internal" href="#api-link"><span class="std std-ref">RNS.Link</span></a> destinations, Reticulum will use per-link <p>For <a class="reference internal" href="#api-link"><span class="std std-ref">RNS.Link</span></a> destinations, Reticulum will use per-link
ephemeral keys, and offers <strong>Forward Secrecy</strong>.</p> ephemeral keys, and offers <strong>Forward Secrecy</strong>.</p>
<dl class="field-list simple"> <dl class="field-list simple">
@@ -1194,14 +1195,14 @@ and encrypted connectivity with the specified destination.</p>
<dl class="py attribute"> <dl class="py attribute">
<dt class="sig sig-object py" id="RNS.Link.STALE_GRACE"> <dt class="sig sig-object py" id="RNS.Link.STALE_GRACE">
<span class="sig-name descname"><span class="pre">STALE_GRACE</span></span><em class="property"><span class="w"> </span><span class="p"><span class="pre">=</span></span><span class="w"> </span><span class="pre">2</span></em><a class="headerlink" href="#RNS.Link.STALE_GRACE" title="Permalink to this definition">#</a></dt> <span class="sig-name descname"><span class="pre">STALE_GRACE</span></span><em class="property"><span class="w"> </span><span class="p"><span class="pre">=</span></span><span class="w"> </span><span class="pre">5</span></em><a class="headerlink" href="#RNS.Link.STALE_GRACE" title="Permalink to this definition">#</a></dt>
<dd><p>Grace period in seconds used in link timeout calculation.</p> <dd><p>Grace period in seconds used in link timeout calculation.</p>
</dd></dl> </dd></dl>
<dl class="py attribute"> <dl class="py attribute">
<dt class="sig sig-object py" id="RNS.Link.KEEPALIVE"> <dt class="sig sig-object py" id="RNS.Link.KEEPALIVE">
<span class="sig-name descname"><span class="pre">KEEPALIVE</span></span><em class="property"><span class="w"> </span><span class="p"><span class="pre">=</span></span><span class="w"> </span><span class="pre">360</span></em><a class="headerlink" href="#RNS.Link.KEEPALIVE" title="Permalink to this definition">#</a></dt> <span class="sig-name descname"><span class="pre">KEEPALIVE</span></span><em class="property"><span class="w"> </span><span class="p"><span class="pre">=</span></span><span class="w"> </span><span class="pre">360</span></em><a class="headerlink" href="#RNS.Link.KEEPALIVE" title="Permalink to this definition">#</a></dt>
<dd><p>Interval for sending keep-alive packets on established links in seconds.</p> <dd><p>Default interval for sending keep-alive packets on established links in seconds.</p>
</dd></dl> </dd></dl>
<dl class="py attribute"> <dl class="py attribute">
@@ -1332,6 +1333,16 @@ statistics, you will be able to retrieve stats such as <em>RSSI</em>, <em>SNR</e
</dl> </dl>
</dd></dl> </dd></dl>
<dl class="py method">
<dt class="sig sig-object py" id="RNS.Link.get_mode">
<span class="sig-name descname"><span class="pre">get_mode</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Link.get_mode" title="Permalink to this definition">#</a></dt>
<dd><dl class="field-list simple">
<dt class="field-odd">Returns<span class="colon">:</span></dt>
<dd class="field-odd"><p>The mode of an established link.</p>
</dd>
</dl>
</dd></dl>
<dl class="py method"> <dl class="py method">
<dt class="sig sig-object py" id="RNS.Link.get_age"> <dt class="sig sig-object py" id="RNS.Link.get_age">
<span class="sig-name descname"><span class="pre">get_age</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Link.get_age" title="Permalink to this definition">#</a></dt> <span class="sig-name descname"><span class="pre">get_age</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#RNS.Link.get_age" title="Permalink to this definition">#</a></dt>
@@ -2247,6 +2258,7 @@ will announce it.</p>
<li><a class="reference internal" href="#RNS.Link.get_mtu"><code class="docutils literal notranslate"><span class="pre">get_mtu()</span></code></a></li> <li><a class="reference internal" href="#RNS.Link.get_mtu"><code class="docutils literal notranslate"><span class="pre">get_mtu()</span></code></a></li>
<li><a class="reference internal" href="#RNS.Link.get_mdu"><code class="docutils literal notranslate"><span class="pre">get_mdu()</span></code></a></li> <li><a class="reference internal" href="#RNS.Link.get_mdu"><code class="docutils literal notranslate"><span class="pre">get_mdu()</span></code></a></li>
<li><a class="reference internal" href="#RNS.Link.get_expected_rate"><code class="docutils literal notranslate"><span class="pre">get_expected_rate()</span></code></a></li> <li><a class="reference internal" href="#RNS.Link.get_expected_rate"><code class="docutils literal notranslate"><span class="pre">get_expected_rate()</span></code></a></li>
<li><a class="reference internal" href="#RNS.Link.get_mode"><code class="docutils literal notranslate"><span class="pre">get_mode()</span></code></a></li>
<li><a class="reference internal" href="#RNS.Link.get_age"><code class="docutils literal notranslate"><span class="pre">get_age()</span></code></a></li> <li><a class="reference internal" href="#RNS.Link.get_age"><code class="docutils literal notranslate"><span class="pre">get_age()</span></code></a></li>
<li><a class="reference internal" href="#RNS.Link.no_inbound_for"><code class="docutils literal notranslate"><span class="pre">no_inbound_for()</span></code></a></li> <li><a class="reference internal" href="#RNS.Link.no_inbound_for"><code class="docutils literal notranslate"><span class="pre">no_inbound_for()</span></code></a></li>
<li><a class="reference internal" href="#RNS.Link.no_outbound_for"><code class="docutils literal notranslate"><span class="pre">no_outbound_for()</span></code></a></li> <li><a class="reference internal" href="#RNS.Link.no_outbound_for"><code class="docutils literal notranslate"><span class="pre">no_outbound_for()</span></code></a></li>
+3 -3
View File
@@ -4,7 +4,7 @@
<meta name="viewport" content="width=device-width,initial-scale=1"/> <meta name="viewport" content="width=device-width,initial-scale=1"/>
<meta name="color-scheme" content="light dark"><link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="#" /> <meta name="color-scheme" content="light dark"><link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="#" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/><title>Search - Reticulum Network Stack 0.9.4 beta documentation</title><link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/><title>Search - Reticulum Network Stack 0.9.6 beta documentation</title><link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo-extensions.css?digest=30d1aed668e5c3a91c3e3bf6a60b675221979f0e" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo-extensions.css?digest=30d1aed668e5c3a91c3e3bf6a60b675221979f0e" />
@@ -138,7 +138,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -164,7 +164,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="#" role="search"> </a><form class="sidebar-search-container" method="get" action="#" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
+1 -1
View File
@@ -1 +1 @@
Search.setIndex({"docnames": ["examples", "forhumans", "gettingstartedfast", "hardware", "index", "interfaces", "networks", "reference", "support", "understanding", "using", "whatis"], "filenames": ["examples.rst", "forhumans.rst", "gettingstartedfast.rst", "hardware.rst", "index.rst", "interfaces.rst", "networks.rst", "reference.rst", "support.rst", "understanding.rst", "using.rst", "whatis.rst"], "titles": ["Code Examples", "An Explanation of Reticulum for Human Beings", "Getting Started Fast", "Communications Hardware", "Reticulum Network Stack Manual", "Configuring Interfaces", "Building Networks", "API Reference", "Support Reticulum", "Understanding Reticulum", "Using Reticulum on Your System", "What is Reticulum?"], "terms": {"A": [0, 2, 5, 6, 7, 9, 10], "number": [0, 2, 5, 6, 7, 9, 10], "ar": [0, 2, 3, 5, 6, 7, 8, 9, 10, 11], "includ": [0, 3, 4, 5, 7, 9, 11], "sourc": [0, 2, 3, 6, 9, 11], "distribut": [0, 2, 6, 7, 9, 10, 11], "reticulum": [0, 5, 6, 7], "you": [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], "can": [0, 2, 3, 4, 5, 6, 7, 8, 9, 10], "us": [0, 3, 4, 5, 6, 7, 9], "learn": [0, 2, 8, 9], "how": [0, 2, 3, 5, 6, 9, 10, 11], "write": [0, 2, 5, 7, 9, 10], "your": [0, 2, 3, 4, 5, 6, 7, 8, 9, 11], "own": [0, 2, 6, 7, 9, 10, 11], "program": [0, 3, 4, 5, 7, 9, 11], "The": [0, 2, 3, 4, 5, 6, 7, 11], "demonstr": [0, 5], "bare": [0, 5], "minimum": [0, 5, 6, 7, 9], "setup": [0, 2, 4, 5, 10], "requir": [0, 2, 5, 6, 7, 9, 10, 11], "connect": [0, 3, 4, 6, 7, 9, 10, 11], "network": [0, 3, 5, 7, 9, 10, 11], "from": [0, 2, 3, 5, 6, 7, 9, 10, 11], "In": [0, 2, 3, 5, 6, 7, 9, 10, 11], "about": [0, 2, 3, 5, 6, 7, 9], "five": 0, "line": [0, 2, 4, 5, 6, 9, 10, 11], "have": [0, 2, 3, 5, 6, 7, 9, 10], "stack": [0, 2, 6, 7, 9, 10, 11], "initialis": [0, 7, 10], "readi": [0, 2, 3, 5, 6, 7, 11], "pass": [0, 3, 5, 6, 7, 9, 10], "traffic": [0, 2, 5, 6, 7, 9, 10], "thi": [0, 2, 3, 4, 5, 6, 7, 9, 10, 11], "rn": [0, 2, 3, 7, 9, 10], "start": [0, 3, 4, 5, 7, 9, 10], "up": [0, 2, 3, 5, 6, 7, 9, 10, 11], "gener": [0, 2, 3, 5, 6, 7, 9, 10, 11], "new": [0, 4, 6, 7, 9, 10], "destin": [0, 2, 4, 6, 7, 10], "let": [0, 2, 5, 6, 9, 10], "user": [0, 2, 5, 6, 9, 10, 11], "send": [0, 5, 7, 9, 10], "an": [0, 2, 3, 5, 6, 7, 9, 10, 11], "import": [0, 2, 3, 5, 6, 7, 8, 9], "argpars": 0, "sy": 0, "": [0, 2, 5, 6, 9, 10, 11], "defin": [0, 5, 7, 9, 10], "app": [0, 2, 7, 9], "name": [0, 2, 4, 5, 6, 7], "we": [0, 2, 3, 5, 8, 9], "ll": [0, 2, 11], "all": [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], "creat": [0, 4, 5, 6, 7, 9, 10, 11], "sinc": [0, 2, 5, 6, 7, 9], "basic": [0, 2, 4, 5, 7, 10], "i": [0, 2, 3, 4, 5, 6, 7, 8, 9, 10], "part": [0, 5, 6, 7, 9, 10], "rang": [0, 2, 3, 5, 6, 9, 10, 11], "util": [0, 3, 4, 5, 9], "put": [0, 3, 5, 10], "them": [0, 2, 3, 5, 6, 8, 9, 10, 11], "within": [0, 2, 5, 6, 7, 9], "namespac": 0, "example_util": 0, "app_nam": [0, 7], "execut": [0, 2, 5, 7, 10], "when": [0, 2, 3, 5, 6, 7, 9, 10], "def": 0, "program_setup": 0, "configpath": 0, "must": [0, 2, 5, 6, 7, 9, 10], "first": [0, 2, 5, 7, 9, 10], "randomli": [0, 9], "ident": [0, 2, 4, 7, 10, 11], "our": [0, 9], "just": [0, 2, 3, 5, 6, 9, 11], "endpoint": [0, 6, 7, 9], "address": [0, 2, 5, 6, 7, 9, 10, 11], "commun": [0, 2, 4, 5, 6, 7, 8, 9, 10, 11], "also": [0, 2, 3, 4, 5, 6, 7, 9, 10, 11], "exist": [0, 2, 3, 5, 9, 10, 11], "which": [0, 2, 5, 6, 7, 9, 10], "know": [0, 2, 3, 6, 7, 9, 11], "thei": [0, 2, 5, 6, 7, 9, 10], "reachabl": [0, 2, 5, 6, 7, 9, 10], "automat": [0, 2, 5, 6, 7, 9, 10, 11], "path": [0, 2, 3, 5, 7, 9, 10], "anywher": [0, 5], "els": [0, 2, 6, 9], "IN": [0, 7], "singl": [0, 5, 7, 9, 10, 11], "minimalsampl": 0, "configur": [0, 2, 3, 4, 6, 7, 9, 11], "prove": [0, 9], "packet": [0, 2, 4, 5, 6, 7, 10, 11], "By": [0, 2, 5, 7, 9, 10], "do": [0, 2, 3, 5, 7, 9, 10, 11], "proof": [0, 7, 9, 10], "each": [0, 2, 5, 6, 7, 9, 10], "incom": [0, 5, 7, 10], "transmit": [0, 5, 9], "back": [0, 5, 9, 11], "sender": [0, 2, 6, 9, 10], "anyon": [0, 2, 3, 5, 6, 7, 9, 10], "tri": 0, "whether": [0, 2, 5, 7, 9], "wa": [0, 3, 5, 6, 7, 9, 10, 11], "receiv": [0, 2, 5, 7, 9, 10], "correctli": 0, "set_proof_strategi": [0, 7], "prove_al": [0, 7], "everyth": [0, 6, 9], "hand": 0, "over": [0, 3, 4, 5, 7, 9, 10, 11], "control": [0, 2, 3, 4, 6, 7, 9, 11], "loop": 0, "announceloop": 0, "log": [0, 2, 5, 10], "prettyhexrep": 0, "hash": [0, 2, 7, 9, 10], "run": [0, 2, 3, 5, 6, 7, 9, 10, 11], "hit": 0, "enter": [0, 10], "manual": [0, 2, 5, 6, 7, 10], "ctrl": 0, "c": [0, 6, 10], "quit": [0, 2], "until": [0, 2, 5, 7], "exit": [0, 2, 7, 10], "If": [0, 2, 3, 5, 6, 7, 9, 10, 11], "server": [0, 2, 3, 4, 7, 10], "client": [0, 2, 3, 4, 7, 10], "messag": [0, 2, 7, 9, 10], "direct": [0, 2, 3, 6, 7, 9, 10], "toward": [0, 5, 9], "while": [0, 2, 3, 5, 6, 7, 9, 11], "true": [0, 2, 5, 7, 10], "input": [0, 10], "sent": [0, 2, 7, 9, 10], "startup": [0, 2, 10], "get": [0, 3, 4, 5, 7, 10, 11], "pars": 0, "desir": [0, 3, 5, 9], "mode": [0, 2, 3, 4, 9, 10, 11], "__name__": 0, "__main__": 0, "try": [0, 4, 5, 7], "parser": 0, "argumeLine truncated Search.setIndex({"docnames": ["examples", "forhumans", "gettingstartedfast", "hardware", "index", "interfaces", "networks", "reference", "support", "understanding", "using", "whatis"], "filenames": ["examples.rst", "forhumans.rst", "gettingstartedfast.rst", "hardware.rst", "index.rst", "interfaces.rst", "networks.rst", "reference.rst", "support.rst", "understanding.rst", "using.rst", "whatis.rst"], "titles": ["Code Examples", "An Explanation of Reticulum for Human Beings", "Getting Started Fast", "Communications Hardware", "Reticulum Network Stack Manual", "Configuring Interfaces", "Building Networks", "API Reference", "Support Reticulum", "Understanding Reticulum", "Using Reticulum on Your System", "What is Reticulum?"], "terms": {"A": [0, 2, 5, 6, 7, 9, 10], "number": [0, 2, 5, 6, 7, 9, 10], "ar": [0, 2, 3, 5, 6, 7, 8, 9, 10, 11], "includ": [0, 3, 4, 5, 7, 9, 11], "sourc": [0, 2, 3, 6, 9, 11], "distribut": [0, 2, 6, 7, 9, 10, 11], "reticulum": [0, 5, 6, 7], "you": [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], "can": [0, 2, 3, 4, 5, 6, 7, 8, 9, 10], "us": [0, 3, 4, 5, 6, 7, 9], "learn": [0, 2, 8, 9], "how": [0, 2, 3, 5, 6, 9, 10, 11], "write": [0, 2, 5, 7, 9, 10], "your": [0, 2, 3, 4, 5, 6, 7, 8, 9, 11], "own": [0, 2, 6, 7, 9, 10, 11], "program": [0, 3, 4, 5, 7, 9, 11], "The": [0, 2, 3, 4, 5, 6, 7, 11], "demonstr": [0, 5], "bare": [0, 5], "minimum": [0, 5, 6, 7, 9], "setup": [0, 2, 4, 5, 10], "requir": [0, 2, 5, 6, 7, 9, 10, 11], "connect": [0, 3, 4, 6, 7, 9, 10, 11], "network": [0, 3, 5, 7, 9, 10, 11], "from": [0, 2, 3, 5, 6, 7, 9, 10, 11], "In": [0, 2, 3, 5, 6, 7, 9, 10, 11], "about": [0, 2, 3, 5, 6, 7, 9], "five": 0, "line": [0, 2, 4, 5, 6, 9, 10, 11], "have": [0, 2, 3, 5, 6, 7, 9, 10], "stack": [0, 2, 6, 7, 9, 10, 11], "initialis": [0, 7, 10], "readi": [0, 2, 3, 5, 6, 7, 11], "pass": [0, 3, 5, 6, 7, 9, 10], "traffic": [0, 2, 5, 6, 7, 9, 10], "thi": [0, 2, 3, 4, 5, 6, 7, 9, 10, 11], "rn": [0, 2, 3, 7, 9, 10], "start": [0, 3, 4, 5, 7, 9, 10], "up": [0, 2, 3, 5, 6, 7, 9, 10, 11], "gener": [0, 2, 3, 5, 6, 7, 9, 10, 11], "new": [0, 4, 6, 7, 9, 10], "destin": [0, 2, 4, 6, 7, 10], "let": [0, 2, 5, 6, 9, 10], "user": [0, 2, 5, 6, 9, 10, 11], "send": [0, 5, 7, 9, 10], "an": [0, 2, 3, 5, 6, 7, 9, 10, 11], "import": [0, 2, 3, 5, 6, 7, 8, 9], "argpars": 0, "sy": 0, "": [0, 2, 5, 6, 9, 10, 11], "defin": [0, 5, 7, 9, 10], "app": [0, 2, 7, 9], "name": [0, 2, 4, 5, 6, 7], "we": [0, 2, 3, 5, 8, 9], "ll": [0, 2, 11], "all": [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], "creat": [0, 4, 5, 6, 7, 9, 10, 11], "sinc": [0, 2, 5, 6, 7, 9], "basic": [0, 2, 4, 5, 7, 10], "i": [0, 2, 3, 4, 5, 6, 7, 8, 9, 10], "part": [0, 5, 6, 7, 9, 10], "rang": [0, 2, 3, 5, 6, 9, 10, 11], "util": [0, 3, 4, 5, 9], "put": [0, 3, 5, 10], "them": [0, 2, 3, 5, 6, 8, 9, 10, 11], "within": [0, 2, 5, 6, 7, 9], "namespac": 0, "example_util": 0, "app_nam": [0, 7], "execut": [0, 2, 5, 7, 10], "when": [0, 2, 3, 5, 6, 7, 9, 10], "def": 0, "program_setup": 0, "configpath": 0, "must": [0, 2, 5, 6, 7, 9, 10], "first": [0, 2, 5, 7, 9, 10], "randomli": [0, 9], "ident": [0, 2, 4, 7, 10, 11], "our": [0, 9], "just": [0, 2, 3, 5, 6, 9, 11], "endpoint": [0, 6, 7, 9], "address": [0, 2, 5, 6, 7, 9, 10, 11], "commun": [0, 2, 4, 5, 6, 7, 8, 9, 10, 11], "also": [0, 2, 3, 4, 5, 6, 7, 9, 10, 11], "exist": [0, 2, 3, 5, 9, 10, 11], "which": [0, 2, 5, 6, 7, 9, 10], "know": [0, 2, 3, 6, 7, 9, 11], "thei": [0, 2, 5, 6, 7, 9, 10], "reachabl": [0, 2, 5, 6, 7, 9, 10], "automat": [0, 2, 5, 6, 7, 9, 10, 11], "path": [0, 2, 3, 5, 7, 9, 10], "anywher": [0, 5], "els": [0, 2, 6, 9], "IN": [0, 7], "singl": [0, 5, 7, 9, 10, 11], "minimalsampl": 0, "configur": [0, 2, 3, 4, 6, 7, 9, 11], "prove": [0, 9], "packet": [0, 2, 4, 5, 6, 7, 10, 11], "By": [0, 2, 5, 7, 9, 10], "do": [0, 2, 3, 5, 7, 9, 10, 11], "proof": [0, 7, 9, 10], "each": [0, 2, 5, 6, 7, 9, 10], "incom": [0, 5, 7, 10], "transmit": [0, 5, 9], "back": [0, 5, 9, 11], "sender": [0, 2, 6, 9, 10], "anyon": [0, 2, 3, 5, 6, 7, 9, 10], "tri": 0, "whether": [0, 2, 5, 7, 9], "wa": [0, 3, 5, 6, 7, 9, 10, 11], "receiv": [0, 2, 5, 7, 9, 10], "correctli": 0, "set_proof_strategi": [0, 7], "prove_al": [0, 7], "everyth": [0, 6, 9], "hand": 0, "over": [0, 3, 4, 5, 7, 9, 10, 11], "control": [0, 2, 3, 4, 6, 7, 9, 11], "loop": 0, "announceloop": 0, "log": [0, 2, 5, 10], "prettyhexrep": 0, "hash": [0, 2, 7, 9, 10], "run": [0, 2, 3, 5, 6, 7, 9, 10, 11], "hit": 0, "enter": [0, 10], "manual": [0, 2, 5, 6, 7, 10], "ctrl": 0, "c": [0, 6, 10], "quit": [0, 2], "until": [0, 2, 5, 7], "exit": [0, 2, 7, 10], "If": [0, 2, 3, 5, 6, 7, 9, 10, 11], "server": [0, 2, 3, 4, 7, 10], "client": [0, 2, 3, 4, 7, 10], "messag": [0, 2, 7, 9, 10], "direct": [0, 2, 3, 6, 7, 9, 10], "toward": [0, 5, 9], "while": [0, 2, 3, 5, 6, 7, 9, 11], "true": [0, 2, 5, 7, 10], "input": [0, 10], "sent": [0, 2, 7, 9, 10], "startup": [0, 2, 10], "get": [0, 3, 4, 5, 7, 10, 11], "pars": 0, "desir": [0, 3, 5, 9], "mode": [0, 2, 3, 4, 7, 9, 10, 11], "__name__": 0, "__main__": 0, "try": [0, 4, 5, 7], "parser": 0, "argLine truncated
+3 -3
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="API Reference" href="reference.html" /><link rel="prev" title="Code Examples" href="examples.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="API Reference" href="reference.html" /><link rel="prev" title="Code Examples" href="examples.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>Support Reticulum - Reticulum Network Stack 0.9.4 beta documentation</title> <title>Support Reticulum - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
+16 -10
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Communications Hardware" href="hardware.html" /><link rel="prev" title="Using Reticulum on Your System" href="using.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Communications Hardware" href="hardware.html" /><link rel="prev" title="Using Reticulum on Your System" href="using.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>Understanding Reticulum - Reticulum Network Stack 0.9.4 beta documentation</title> <title>Understanding Reticulum - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -673,7 +673,7 @@ public signing key.</div>
</li> </li>
<li><div class="line-block"> <li><div class="line-block">
<div class="line">In case the packet is addressed to a <em>group</em> destination type, the packet will be encrypted with the <div class="line">In case the packet is addressed to a <em>group</em> destination type, the packet will be encrypted with the
pre-shared AES-128 key associated with the destination. In case the packet is addressed to a <em>plain</em> pre-shared AES-256 key associated with the destination. In case the packet is addressed to a <em>plain</em>
destination type, the payload data will not be encrypted. Neither of these two destination types can offer destination type, the payload data will not be encrypted. Neither of these two destination types can offer
forward secrecy. In general, it is recommended to always use the <em>single</em> destination type, unless it is forward secrecy. In general, it is recommended to always use the <em>single</em> destination type, unless it is
strictly necessary to use one of the others.</div> strictly necessary to use one of the others.</div>
@@ -1062,9 +1062,15 @@ of the different interface modes, and how they are configured.</p>
</section> </section>
<section id="cryptographic-primitives"> <section id="cryptographic-primitives">
<span id="understanding-primitives"></span><h3>Cryptographic Primitives<a class="headerlink" href="#cryptographic-primitives" title="Permalink to this heading">#</a></h3> <span id="understanding-primitives"></span><h3>Cryptographic Primitives<a class="headerlink" href="#cryptographic-primitives" title="Permalink to this heading">#</a></h3>
<p>Reticulum has been designed to use a simple suite of efficient, strong and modern <p>Reticulum uses a simple suite of efficient, strong and well-tested cryptographic
cryptographic primitives, with widely available implementations that can be used primitives, with widely available implementations that can be used both on
both on general-purpose CPUs and on microcontrollers. The necessary primitives are:</p> general-purpose CPUs and on microcontrollers.</p>
<p>One of the primary considerations for choosing this particular set of primitives is
that they can be implemented <em>safely</em> with relatively few pitfalls, on practically
all current computing platforms.</p>
<p>The primitives listed here <strong>are authoritative</strong>. Anything claiming to be Reticulum,
but not using these exact primitives <strong>is not</strong> Reticulum, and possibly an
intentionally compromised or weakened clone. The utilised primitives are:</p>
<ul class="simple"> <ul class="simple">
<li><p>Ed25519 for signatures</p></li> <li><p>Ed25519 for signatures</p></li>
<li><p>X25519 for ECDH key exchanges</p></li> <li><p>X25519 for ECDH key exchanges</p></li>
@@ -1072,16 +1078,16 @@ both on general-purpose CPUs and on microcontrollers. The necessary primitives a
<li><p>Encrypted tokens are based on the Fernet spec</p> <li><p>Encrypted tokens are based on the Fernet spec</p>
<ul> <ul>
<li><p>Ephemeral keys derived from an ECDH key exchange on Curve25519</p></li> <li><p>Ephemeral keys derived from an ECDH key exchange on Curve25519</p></li>
<li><p>AES-128 in CBC mode with PKCS7 padding</p></li> <li><p>AES-256 in CBC mode with PKCS7 padding</p></li>
<li><p>HMAC using SHA256 for message authentication</p></li> <li><p>HMAC using SHA256 for message authentication</p></li>
<li><p>IVs are generated through os.urandom()</p></li> <li><p>IVs must be generated through <code class="docutils literal notranslate"><span class="pre">os.urandom()</span></code> or better</p></li>
<li><p>No Fernet version and timestamp metadata fields</p></li> <li><p>No Fernet version and timestamp metadata fields</p></li>
</ul> </ul>
</li> </li>
<li><p>SHA-256</p></li> <li><p>SHA-256</p></li>
<li><p>SHA-512</p></li> <li><p>SHA-512</p></li>
</ul> </ul>
<p>In the default installation configuration, the <code class="docutils literal notranslate"><span class="pre">X25519</span></code>, <code class="docutils literal notranslate"><span class="pre">Ed25519</span></code> and <code class="docutils literal notranslate"><span class="pre">AES-128-CBC</span></code> <p>In the default installation configuration, the <code class="docutils literal notranslate"><span class="pre">X25519</span></code>, <code class="docutils literal notranslate"><span class="pre">Ed25519</span></code> and <code class="docutils literal notranslate"><span class="pre">AES-256-CBC</span></code>
primitives are provided by <a class="reference external" href="https://www.openssl.org/">OpenSSL</a> (via the <a class="reference external" href="https://github.com/pyca/cryptography">PyCA/cryptography</a> primitives are provided by <a class="reference external" href="https://www.openssl.org/">OpenSSL</a> (via the <a class="reference external" href="https://github.com/pyca/cryptography">PyCA/cryptography</a>
package). The hashing functions <code class="docutils literal notranslate"><span class="pre">SHA-256</span></code> and <code class="docutils literal notranslate"><span class="pre">SHA-512</span></code> are provided by the standard package). The hashing functions <code class="docutils literal notranslate"><span class="pre">SHA-256</span></code> and <code class="docutils literal notranslate"><span class="pre">SHA-512</span></code> are provided by the standard
Python <a class="reference external" href="https://docs.python.org/3/library/hashlib.html">hashlib</a>. The <code class="docutils literal notranslate"><span class="pre">HKDF</span></code>, <code class="docutils literal notranslate"><span class="pre">HMAC</span></code>, Python <a class="reference external" href="https://docs.python.org/3/library/hashlib.html">hashlib</a>. The <code class="docutils literal notranslate"><span class="pre">HKDF</span></code>, <code class="docutils literal notranslate"><span class="pre">HMAC</span></code>,
+37 -13
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Understanding Reticulum" href="understanding.html" /><link rel="prev" title="Getting Started Fast" href="gettingstartedfast.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Understanding Reticulum" href="understanding.html" /><link rel="prev" title="Getting Started Fast" href="gettingstartedfast.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>Using Reticulum on Your System - Reticulum Network Stack 0.9.4 beta documentation</title> <title>Using Reticulum on Your System - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -277,12 +277,12 @@ configuration file is created. The default configuration looks like this:</p>
<span class="c1"># If you enable Transport, your system will route traffic</span> <span class="c1"># If you enable Transport, your system will route traffic</span>
<span class="c1"># for other peers, pass announces and serve path requests.</span> <span class="c1"># for other peers, pass announces and serve path requests.</span>
<span class="c1"># This should only be done for systems that are suited to</span> <span class="c1"># This should be done for systems that are suited to act</span>
<span class="c1"># act as transport nodes, ie. if they are stationary and</span> <span class="c1"># as transport nodes, ie. if they are stationary and</span>
<span class="c1"># always-on. This directive is optional and can be removed</span> <span class="c1"># always-on. This directive is optional and can be removed</span>
<span class="c1"># for brevity.</span> <span class="c1"># for brevity.</span>
<span class="n">enable_transport</span> <span class="o">=</span> <span class="kc">False</span> <span class="n">enable_transport</span> <span class="o">=</span> <span class="n">No</span>
<span class="c1"># By default, the first program to launch the Reticulum</span> <span class="c1"># By default, the first program to launch the Reticulum</span>
@@ -299,12 +299,24 @@ configuration file is created. The default configuration looks like this:</p>
<span class="c1"># If you want to run multiple *different* shared instances</span> <span class="c1"># If you want to run multiple *different* shared instances</span>
<span class="c1"># on the same system, you will need to specify different</span> <span class="c1"># on the same system, you will need to specify different</span>
<span class="c1"># shared instance ports for each. The defaults are given</span> <span class="c1"># instance names for each. On platforms supporting domain</span>
<span class="c1"># below, and again, these options can be left out if you</span> <span class="c1"># sockets, this can be done with the instance_name option:</span>
<span class="c1"># don&#39;t need them.</span>
<span class="n">shared_instance_port</span> <span class="o">=</span> <span class="mi">37428</span> <span class="n">instance_name</span> <span class="o">=</span> <span class="n">default</span>
<span class="n">instance_control_port</span> <span class="o">=</span> <span class="mi">37429</span>
<span class="c1"># Some platforms don&#39;t support domain sockets, and if that</span>
<span class="c1"># is the case, you can isolate different instances by</span>
<span class="c1"># specifying a unique set of ports for each:</span>
<span class="c1"># shared_instance_port = 37428</span>
<span class="c1"># instance_control_port = 37429</span>
<span class="c1"># If you want to explicitly use TCP for shared instance</span>
<span class="c1"># communication, instead of domain sockets, this is also</span>
<span class="c1"># possible, by using the following option:</span>
<span class="c1"># shared_instance_type = tcp</span>
<span class="c1"># On systems where running instances may not have access</span> <span class="c1"># On systems where running instances may not have access</span>
@@ -318,13 +330,25 @@ configuration file is created. The default configuration looks like this:</p>
<span class="c1"># rpc_key = e5c032d3ec4e64a6aca9927ba8ab73336780f6d71790</span> <span class="c1"># rpc_key = e5c032d3ec4e64a6aca9927ba8ab73336780f6d71790</span>
<span class="c1"># It is possible to allow remote management of Reticulum</span>
<span class="c1"># systems using the various built-in utilities, such as</span>
<span class="c1"># rnstatus and rnpath. You will need to specify one or</span>
<span class="c1"># more Reticulum Identity hashes for authenticating the</span>
<span class="c1"># queries from client programs. For this purpose, you can</span>
<span class="c1"># use existing identity files, or generate new ones with</span>
<span class="c1"># the rnid utility.</span>
<span class="c1"># enable_remote_management = yes</span>
<span class="c1"># remote_management_allowed = 9fb6d773498fb3feda407ed8ef2c3229, 2d882c5586e548d79b5af27bca1776dc</span>
<span class="c1"># You can configure Reticulum to panic and forcibly close</span> <span class="c1"># You can configure Reticulum to panic and forcibly close</span>
<span class="c1"># if an unrecoverable interface error occurs, such as the</span> <span class="c1"># if an unrecoverable interface error occurs, such as the</span>
<span class="c1"># hardware device for an interface disappearing. This is</span> <span class="c1"># hardware device for an interface disappearing. This is</span>
<span class="c1"># an optional directive, and can be left out for brevity.</span> <span class="c1"># an optional directive, and can be left out for brevity.</span>
<span class="c1"># This behaviour is disabled by default.</span> <span class="c1"># This behaviour is disabled by default.</span>
<span class="n">panic_on_interface_error</span> <span class="o">=</span> <span class="n">No</span> <span class="c1"># panic_on_interface_error = No</span>
<span class="c1"># When Transport is enabled, it is possible to allow the</span> <span class="c1"># When Transport is enabled, it is possible to allow the</span>
@@ -335,7 +359,7 @@ configuration file is created. The default configuration looks like this:</p>
<span class="c1"># Transport Instance, and printed to the log at startup.</span> <span class="c1"># Transport Instance, and printed to the log at startup.</span>
<span class="c1"># Optional, and disabled by default.</span> <span class="c1"># Optional, and disabled by default.</span>
<span class="n">respond_to_probes</span> <span class="o">=</span> <span class="n">No</span> <span class="c1"># respond_to_probes = No</span>
<span class="p">[</span><span class="n">logging</span><span class="p">]</span> <span class="p">[</span><span class="n">logging</span><span class="p">]</span>
+4 -4
View File
@@ -6,7 +6,7 @@
<link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Getting Started Fast" href="gettingstartedfast.html" /><link rel="prev" title="Reticulum Network Stack Manual" href="index.html" /> <link rel="index" title="Index" href="genindex.html" /><link rel="search" title="Search" href="search.html" /><link rel="next" title="Getting Started Fast" href="gettingstartedfast.html" /><link rel="prev" title="Reticulum Network Stack Manual" href="index.html" />
<meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/> <meta name="generator" content="sphinx-5.3.0, furo 2022.09.29.dev1"/>
<title>What is Reticulum? - Reticulum Network Stack 0.9.4 beta documentation</title> <title>What is Reticulum? - Reticulum Network Stack 0.9.6 beta documentation</title>
<link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" /> <link rel="stylesheet" type="text/css" href="_static/styles/furo.css?digest=189ec851f9bb375a2509b67be1f64f0cf212b702" />
<link rel="stylesheet" type="text/css" href="_static/copybutton.css" /> <link rel="stylesheet" type="text/css" href="_static/copybutton.css" />
@@ -141,7 +141,7 @@
</label> </label>
</div> </div>
<div class="header-center"> <div class="header-center">
<a href="index.html"><div class="brand">Reticulum Network Stack 0.9.4 beta documentation</div></a> <a href="index.html"><div class="brand">Reticulum Network Stack 0.9.6 beta documentation</div></a>
</div> </div>
<div class="header-right"> <div class="header-right">
<div class="theme-toggle-container theme-toggle-header"> <div class="theme-toggle-container theme-toggle-header">
@@ -167,7 +167,7 @@
<img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/> <img class="sidebar-logo" src="_static/rns_logo_512.png" alt="Logo"/>
</div> </div>
<span class="sidebar-brand-text">Reticulum Network Stack 0.9.4 beta documentation</span> <span class="sidebar-brand-text">Reticulum Network Stack 0.9.6 beta documentation</span>
</a><form class="sidebar-search-container" method="get" action="search.html" role="search"> </a><form class="sidebar-search-container" method="get" action="search.html" role="search">
<input class="sidebar-search" placeholder="Search" name="q" aria-label="Search"> <input class="sidebar-search" placeholder="Search" name="q" aria-label="Search">
@@ -279,7 +279,7 @@ considered complete and stable at the moment, but could change if absolutely war
<li><p>Reticulum uses the following format for encrypted tokens:</p> <li><p>Reticulum uses the following format for encrypted tokens:</p>
<ul> <ul>
<li><p>Ephemeral per-packet and link keys and derived from an ECDH key exchange on Curve25519</p></li> <li><p>Ephemeral per-packet and link keys and derived from an ECDH key exchange on Curve25519</p></li>
<li><p>AES-128 in CBC mode with PKCS7 padding</p></li> <li><p>AES-256 in CBC mode with PKCS7 padding</p></li>
<li><p>HMAC using SHA256 for authentication</p></li> <li><p>HMAC using SHA256 for authentication</p></li>
<li><p>IVs are generated through os.urandom()</p></li> <li><p>IVs are generated through os.urandom()</p></li>
</ul> </ul>
+15 -7
View File
@@ -453,7 +453,7 @@ For exchanges of small amounts of information, Reticulum offers the *Packet* API
public signing key. public signing key.
* | In case the packet is addressed to a *group* destination type, the packet will be encrypted with the * | In case the packet is addressed to a *group* destination type, the packet will be encrypted with the
pre-shared AES-128 key associated with the destination. In case the packet is addressed to a *plain* pre-shared AES-256 key associated with the destination. In case the packet is addressed to a *plain*
destination type, the payload data will not be encrypted. Neither of these two destination types can offer destination type, the payload data will not be encrypted. Neither of these two destination types can offer
forward secrecy. In general, it is recommended to always use the *single* destination type, unless it is forward secrecy. In general, it is recommended to always use the *single* destination type, unless it is
strictly necessary to use one of the others. strictly necessary to use one of the others.
@@ -858,9 +858,17 @@ of the different interface modes, and how they are configured.
Cryptographic Primitives Cryptographic Primitives
------------------------ ------------------------
Reticulum has been designed to use a simple suite of efficient, strong and modern Reticulum uses a simple suite of efficient, strong and well-tested cryptographic
cryptographic primitives, with widely available implementations that can be used primitives, with widely available implementations that can be used both on
both on general-purpose CPUs and on microcontrollers. The necessary primitives are: general-purpose CPUs and on microcontrollers.
One of the primary considerations for choosing this particular set of primitives is
that they can be implemented *safely* with relatively few pitfalls, on practically
all current computing platforms.
The primitives listed here **are authoritative**. Anything claiming to be Reticulum,
but not using these exact primitives **is not** Reticulum, and possibly an
intentionally compromised or weakened clone. The utilised primitives are:
* Ed25519 for signatures * Ed25519 for signatures
@@ -872,11 +880,11 @@ both on general-purpose CPUs and on microcontrollers. The necessary primitives a
* Ephemeral keys derived from an ECDH key exchange on Curve25519 * Ephemeral keys derived from an ECDH key exchange on Curve25519
* AES-128 in CBC mode with PKCS7 padding * AES-256 in CBC mode with PKCS7 padding
* HMAC using SHA256 for message authentication * HMAC using SHA256 for message authentication
* IVs are generated through os.urandom() * IVs must be generated through ``os.urandom()`` or better
* No Fernet version and timestamp metadata fields * No Fernet version and timestamp metadata fields
@@ -884,7 +892,7 @@ both on general-purpose CPUs and on microcontrollers. The necessary primitives a
* SHA-512 * SHA-512
In the default installation configuration, the ``X25519``, ``Ed25519`` and ``AES-128-CBC`` In the default installation configuration, the ``X25519``, ``Ed25519`` and ``AES-256-CBC``
primitives are provided by `OpenSSL <https://www.openssl.org/>`_ (via the `PyCA/cryptography <https://github.com/pyca/cryptography>`_ primitives are provided by `OpenSSL <https://www.openssl.org/>`_ (via the `PyCA/cryptography <https://github.com/pyca/cryptography>`_
package). The hashing functions ``SHA-256`` and ``SHA-512`` are provided by the standard package). The hashing functions ``SHA-256`` and ``SHA-512`` are provided by the standard
Python `hashlib <https://docs.python.org/3/library/hashlib.html>`_. The ``HKDF``, ``HMAC``, Python `hashlib <https://docs.python.org/3/library/hashlib.html>`_. The ``HKDF``, ``HMAC``,
+34 -10
View File
@@ -69,12 +69,12 @@ configuration file is created. The default configuration looks like this:
# If you enable Transport, your system will route traffic # If you enable Transport, your system will route traffic
# for other peers, pass announces and serve path requests. # for other peers, pass announces and serve path requests.
# This should only be done for systems that are suited to # This should be done for systems that are suited to act
# act as transport nodes, ie. if they are stationary and # as transport nodes, ie. if they are stationary and
# always-on. This directive is optional and can be removed # always-on. This directive is optional and can be removed
# for brevity. # for brevity.
enable_transport = False enable_transport = No
# By default, the first program to launch the Reticulum # By default, the first program to launch the Reticulum
@@ -91,12 +91,24 @@ configuration file is created. The default configuration looks like this:
# If you want to run multiple *different* shared instances # If you want to run multiple *different* shared instances
# on the same system, you will need to specify different # on the same system, you will need to specify different
# shared instance ports for each. The defaults are given # instance names for each. On platforms supporting domain
# below, and again, these options can be left out if you # sockets, this can be done with the instance_name option:
# don't need them.
shared_instance_port = 37428 instance_name = default
instance_control_port = 37429
# Some platforms don't support domain sockets, and if that
# is the case, you can isolate different instances by
# specifying a unique set of ports for each:
# shared_instance_port = 37428
# instance_control_port = 37429
# If you want to explicitly use TCP for shared instance
# communication, instead of domain sockets, this is also
# possible, by using the following option:
# shared_instance_type = tcp
# On systems where running instances may not have access # On systems where running instances may not have access
@@ -110,13 +122,25 @@ configuration file is created. The default configuration looks like this:
# rpc_key = e5c032d3ec4e64a6aca9927ba8ab73336780f6d71790 # rpc_key = e5c032d3ec4e64a6aca9927ba8ab73336780f6d71790
# It is possible to allow remote management of Reticulum
# systems using the various built-in utilities, such as
# rnstatus and rnpath. You will need to specify one or
# more Reticulum Identity hashes for authenticating the
# queries from client programs. For this purpose, you can
# use existing identity files, or generate new ones with
# the rnid utility.
# enable_remote_management = yes
# remote_management_allowed = 9fb6d773498fb3feda407ed8ef2c3229, 2d882c5586e548d79b5af27bca1776dc
# You can configure Reticulum to panic and forcibly close # You can configure Reticulum to panic and forcibly close
# if an unrecoverable interface error occurs, such as the # if an unrecoverable interface error occurs, such as the
# hardware device for an interface disappearing. This is # hardware device for an interface disappearing. This is
# an optional directive, and can be left out for brevity. # an optional directive, and can be left out for brevity.
# This behaviour is disabled by default. # This behaviour is disabled by default.
panic_on_interface_error = No # panic_on_interface_error = No
# When Transport is enabled, it is possible to allow the # When Transport is enabled, it is possible to allow the
@@ -127,7 +151,7 @@ configuration file is created. The default configuration looks like this:
# Transport Instance, and printed to the log at startup. # Transport Instance, and printed to the log at startup.
# Optional, and disabled by default. # Optional, and disabled by default.
respond_to_probes = No # respond_to_probes = No
[logging] [logging]
+1 -1
View File
@@ -68,7 +68,7 @@ What does Reticulum Offer?
* Ephemeral per-packet and link keys and derived from an ECDH key exchange on Curve25519 * Ephemeral per-packet and link keys and derived from an ECDH key exchange on Curve25519
* AES-128 in CBC mode with PKCS7 padding * AES-256 in CBC mode with PKCS7 padding
* HMAC using SHA256 for authentication * HMAC using SHA256 for authentication
+3 -1
View File
@@ -34,10 +34,12 @@ setuptools.setup(
long_description_content_type="text/markdown", long_description_content_type="text/markdown",
url="https://reticulum.network/", url="https://reticulum.network/",
packages=packages, packages=packages,
license="Reticulum License",
license_files = ("LICENSE"),
classifiers=[ classifiers=[
"Programming Language :: Python :: 3", "Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent", "Operating System :: OS Independent",
"Development Status :: 4 - Beta",
], ],
entry_points= { entry_points= {
'console_scripts': [ 'console_scripts': [
+5 -2
View File
@@ -8,7 +8,7 @@ signed_message = "e51a008b8b8ba855993d8892a40daad84a6fb69a7138e1b5f69b427fe03449
sig_from_key_0 = "3020ef58f861591826a61c3d2d4a25b949cdb3094085ba6b1177a6f2a05f3cdd24d1095d6fdd078f0b2826e80b261c93c1ff97fbfd4857f25706d57dd073590c" sig_from_key_0 = "3020ef58f861591826a61c3d2d4a25b949cdb3094085ba6b1177a6f2a05f3cdd24d1095d6fdd078f0b2826e80b261c93c1ff97fbfd4857f25706d57dd073590c"
encrypted_message = "71884a271ead43558fcf1e331c5aebcd43498f16da16f8056b0893ce6b15d521eaa4f31639cd34da1b57995944076c4f14f300f2d2612111d21a3429a9966ac1da68545c00c7887d8b26f6c1ab9defa020b9519849ca41b7904199882802b6542771df85144a79890289d3c02daef6c26652c5ce9de231a2" encrypted_message = "71884a271ead43558fcf1e331c5aebcd43498f16da16f8056b0893ce6b15d521eaa4f31639cd34da1b57995944076c4f14f300f2d2612111d21a3429a9966ac1da68545c00c7887d8b26f6c1ab9defa020b9519849ca41b7904199882802b6542771df85144a79890289d3c02daef6c26652c5ce9de231a2"
fixed_token = "54d6ba347f3f2fe74fa52d6844a9090c049a6f437d7d151b9bd7db3e6785dd40286c451babda82660cbb4827517365b740675adf60d4b82778d7f7815a0e9818f2f2d3f15c0365e9d4f08df4f8261e5549c8c398e92bc66750fcd4ce7ea150f8a8761936341129e89afd22eaa57c303ccbe045d0b2fc7b8637946e16627419ef1fea0a0fef974c418a98af046d61e8e064f42c4948b0c81701106583c8f224329c0b475cb2168dc2e3fbf649edb79c58b7c839a509e146ec8d26589cb990c76c756fdefd0110410a6ab84fa3a722db74" fixed_token = "e37705f9b432d3711acf028678b0b9d37fdf7e00a3b47c95251aad61447df2620b5b9978783c3d9f2fb762e68c8b57c554928fb70dd79c1033ce5865f91761aad3e992790f63456092cb69b7b045f539147f7ba10d480e300f193576ae2d75a7884809b76bd17e05a735383305c0aa5621395bbf51e8cc66c1c536f339f2bea600f08f8f9a76564b2522cd904b6c2b6e553ec3d4df718ae70434c734297b313539338d184d2c64a9c4ddbc9b9a4947d0b45f5a274f65ae9f6bb203562fd5cede6abd3c615b699156e08fa33b841647a0"
fixed_keys = [ fixed_keys = [
("f8953ffaf607627e615603ff1530c82c434cf87c07179dd7689ea776f30b964cfb7ba6164af00c5111a45e69e57d885e1285f8dbfe3a21e95ae17cf676b0f8b7", "650b5d76b6bec0390d1f8cfca5bd33f9"), ("f8953ffaf607627e615603ff1530c82c434cf87c07179dd7689ea776f30b964cfb7ba6164af00c5111a45e69e57d885e1285f8dbfe3a21e95ae17cf676b0f8b7", "650b5d76b6bec0390d1f8cfca5bd33f9"),
@@ -148,9 +148,12 @@ class TestIdentity(unittest.TestCase):
def test_2_encrypt(self): def test_2_encrypt(self):
print("") print("")
# Test decryption of known token # Test loading identity from bytes
fid = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[0][0])) fid = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[0][0]))
self.assertEqual(fid.hash, bytes.fromhex(fixed_keys[0][1])) self.assertEqual(fid.hash, bytes.fromhex(fixed_keys[0][1]))
# Test decryption of known AES-256 token
print("Testing decryption of known token")
plaintext = fid.decrypt(bytes.fromhex(fixed_token)) plaintext = fid.decrypt(bytes.fromhex(fixed_token))
self.assertEqual(plaintext, bytes.fromhex(encrypted_message)) self.assertEqual(plaintext, bytes.fromhex(encrypted_message))
+229 -40
View File
@@ -1,3 +1,6 @@
# import tracemalloc
# tracemalloc.start()
import unittest import unittest
import subprocess import subprocess
@@ -25,6 +28,7 @@ fixed_keys = [
] ]
BUFFER_TEST_TARGET = 32000 BUFFER_TEST_TARGET = 32000
LINK_UP_WAIT = 0.050
def targets_job(caller): def targets_job(caller):
cmd = "python -c \"from tests.link import targets; targets()\"" cmd = "python -c \"from tests.link import targets; targets()\""
@@ -65,10 +69,11 @@ class TestLink(unittest.TestCase):
close_rns() close_rns()
@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_0_valid_announce(self): def test_00_valid_announce(self):
init_rns(self) init_rns(self)
print("") print("")
print("Testing valid announce...")
fid = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[3][0])) fid = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[3][0]))
dst = RNS.Destination(fid, RNS.Destination.IN, RNS.Destination.SINGLE, "test", "announce") dst = RNS.Destination(fid, RNS.Destination.IN, RNS.Destination.SINGLE, "test", "announce")
ap = dst.announce(send=False) ap = dst.announce(send=False)
@@ -76,10 +81,11 @@ class TestLink(unittest.TestCase):
self.assertEqual(RNS.Identity.validate_announce(ap), True) self.assertEqual(RNS.Identity.validate_announce(ap), True)
@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_1_invalid_announce(self): def test_01_invalid_announce(self):
init_rns(self) init_rns(self)
print("") print("")
print("Testing invalid announce...")
fid = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[4][0])) fid = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[4][0]))
dst = RNS.Destination(fid, RNS.Destination.IN, RNS.Destination.SINGLE, "test", "announce") dst = RNS.Destination(fid, RNS.Destination.IN, RNS.Destination.SINGLE, "test", "announce")
ap = dst.announce(send=False) ap = dst.announce(send=False)
@@ -92,7 +98,7 @@ class TestLink(unittest.TestCase):
self.assertEqual(RNS.Identity.validate_announce(ap), False) self.assertEqual(RNS.Identity.validate_announce(ap), False)
@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_2_establish(self): def test_02_establish(self):
init_rns(self) init_rns(self)
print("") print("")
@@ -106,18 +112,42 @@ class TestLink(unittest.TestCase):
self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d"))
print("Testing default mode link establishment...")
l1 = RNS.Link(dest) l1 = RNS.Link(dest)
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.ACTIVE) self.assertEqual(l1.status, RNS.Link.ACTIVE)
l1.teardown() l1.teardown()
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.CLOSED) self.assertEqual(l1.status, RNS.Link.CLOSED)
print("Testing AES_128_CBC mode link establishment...")
l2 = RNS.Link(dest, mode=RNS.Link.MODE_AES128_CBC)
time.sleep(LINK_UP_WAIT)
self.assertEqual(l2.status, RNS.Link.ACTIVE)
self.assertEqual(l2.mode, RNS.Link.MODE_AES128_CBC)
self.assertEqual(len(l2.derived_key), 32)
l2.teardown()
time.sleep(LINK_UP_WAIT)
self.assertEqual(l2.status, RNS.Link.CLOSED)
print("Testing AES_256_CBC mode link establishment...")
l3 = RNS.Link(dest, mode=RNS.Link.MODE_AES256_CBC)
time.sleep(LINK_UP_WAIT)
self.assertEqual(l3.status, RNS.Link.ACTIVE)
self.assertEqual(l3.mode, RNS.Link.MODE_AES256_CBC)
self.assertEqual(len(l3.derived_key), 64)
l3.teardown()
time.sleep(LINK_UP_WAIT)
self.assertEqual(l3.status, RNS.Link.CLOSED)
@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_3_packets(self): def test_03a_packets(self):
init_rns(self) init_rns(self)
print("") print("")
print("Testing default mode link packets...")
# TODO: Load this from public bytes only # TODO: Load this from public bytes only
id1 = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[0][0])) id1 = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[0][0]))
@@ -131,7 +161,7 @@ class TestLink(unittest.TestCase):
self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d"))
l1 = RNS.Link(dest) l1 = RNS.Link(dest)
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.ACTIVE) self.assertEqual(l1.status, RNS.Link.ACTIVE)
b = 0 b = 0
@@ -165,6 +195,7 @@ class TestLink(unittest.TestCase):
if not r.status == RNS.PacketReceipt.DELIVERED: if not r.status == RNS.PacketReceipt.DELIVERED:
all_ok = False all_ok = False
break break
time.sleep(0.01)
pduration = time.time()-pstart pduration = time.time()-pstart
@@ -182,11 +213,84 @@ class TestLink(unittest.TestCase):
print("Single packet and proof round-trip throughput is "+self.size_str(b/pduration, "b")+"ps") print("Single packet and proof round-trip throughput is "+self.size_str(b/pduration, "b")+"ps")
l1.teardown() l1.teardown()
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.CLOSED) self.assertEqual(l1.status, RNS.Link.CLOSED)
@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_4_micro_resource(self): def test_03b_packets(self):
init_rns(self)
print("")
print("Testing AES_256_CBC mode link packets...")
# TODO: Load this from public bytes only
id1 = RNS.Identity.from_bytes(bytes.fromhex(fixed_keys[0][0]))
self.assertEqual(id1.hash, bytes.fromhex(fixed_keys[0][1]))
RNS.Transport.request_path(bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d"))
time.sleep(0.2)
dest = RNS.Destination(id1, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "link", "establish")
self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d"))
l1 = RNS.Link(dest, mode=RNS.Link.MODE_AES256_CBC)
time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.ACTIVE)
b = 0
pr_t = 0
receipts = []
if RNS.Cryptography.backend() == "internal" or RNS.Reticulum.MTU > 500:
num_packets = 50
else:
num_packets = 500
packet_size = RNS.Link.MDU
pstart = time.time()
print("Sending "+str(num_packets)+" link packets of "+str(packet_size)+" bytes...")
for i in range(0, num_packets):
time.sleep(0.003)
b += packet_size
data = os.urandom(packet_size)
start = time.time()
p = RNS.Packet(l1, data)
receipts.append(p.send())
pr_t += time.time() - start
print("Sent "+self.size_str(b)+", "+self.size_str(b/pr_t, "b")+"ps")
print("Checking receipts...", end=" ")
all_ok = False
receipt_timeout = time.time() + 35
while not all_ok and time.time() < receipt_timeout:
for r in receipts:
all_ok = True
if not r.status == RNS.PacketReceipt.DELIVERED:
all_ok = False
break
time.sleep(0.01)
pduration = time.time()-pstart
n_failed = 0
for r in receipts:
if not r.status == RNS.PacketReceipt.DELIVERED:
n_failed += 1
if n_failed > 0:
ns = "s" if n_failed != 1 else ""
print("Failed to receive proof for "+str(n_failed)+" packet"+ns)
self.assertEqual(all_ok, True)
print("OK!")
print("Single packet and proof round-trip throughput is "+self.size_str(b/pduration, "b")+"ps")
l1.teardown()
time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.CLOSED)
@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_04_micro_resource(self):
init_rns(self) init_rns(self)
print("") print("")
print("Micro resource test") print("Micro resource test")
@@ -203,7 +307,7 @@ class TestLink(unittest.TestCase):
self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d"))
l1 = RNS.Link(dest) l1 = RNS.Link(dest)
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.ACTIVE) self.assertEqual(l1.status, RNS.Link.ACTIVE)
resource_timeout = 120 resource_timeout = 120
@@ -219,14 +323,38 @@ class TestLink(unittest.TestCase):
t = time.time() - start t = time.time() - start
self.assertEqual(resource.status, RNS.Resource.COMPLETE) self.assertEqual(resource.status, RNS.Resource.COMPLETE)
print("Resource completed at "+self.size_str(resource_size/t, "b")+"ps") print("Resource completed at "+self.size_str(resource.total_size/t, "b")+f"ps ({RNS.prettysize(resource.total_size)}, {RNS.prettyshorttime(t)})")
# Test sending resource with metadata
data = os.urandom(resource_size)
metadata = {"text": "Some text", "numbers": [1,2,3,4], "blob": os.urandom(32)}
print("Sending "+self.size_str(resource_size)+" resource with metadata...")
resource = RNS.Resource(data, l1, metadata=metadata, timeout=resource_timeout)
start = time.time()
# This is a hack, don't do it. Use the callbacks instead.
while resource.status < RNS.Resource.COMPLETE:
time.sleep(0.01)
t = time.time() - start
self.assertEqual(resource.status, RNS.Resource.COMPLETE)
print("Resource completed at "+self.size_str(resource.total_size/t, "b")+f"ps ({RNS.prettysize(resource.total_size)}, {RNS.prettyshorttime(t)})")
# Test sending resource with invalid size metadata
data = os.urandom(resource_size)
metadata = os.urandom(RNS.Resource.METADATA_MAX_SIZE+1)
print("Sending "+self.size_str(resource_size)+" resource with invalid size metadata...")
exception_raised = False
try: resource = RNS.Resource(data, l1, metadata=metadata, timeout=resource_timeout)
except SystemError: exception_raised = True
self.assertEqual(exception_raised, True)
l1.teardown() l1.teardown()
time.sleep(0.5) time.sleep(0.5)
self.assertEqual(l1.status, RNS.Link.CLOSED) self.assertEqual(l1.status, RNS.Link.CLOSED)
@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_5_mini_resource(self): def test_05_mini_resource(self):
init_rns(self) init_rns(self)
print("") print("")
print("Mini resource test") print("Mini resource test")
@@ -243,11 +371,13 @@ class TestLink(unittest.TestCase):
self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d"))
l1 = RNS.Link(dest) l1 = RNS.Link(dest)
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.ACTIVE) self.assertEqual(l1.status, RNS.Link.ACTIVE)
resource_timeout = 120 resource_timeout = 120
resource_size = 256*1000 resource_size = 256*1000
# Test sending resource without metadata
data = os.urandom(resource_size) data = os.urandom(resource_size)
print("Sending "+self.size_str(resource_size)+" resource...") print("Sending "+self.size_str(resource_size)+" resource...")
resource = RNS.Resource(data, l1, timeout=resource_timeout) resource = RNS.Resource(data, l1, timeout=resource_timeout)
@@ -259,14 +389,29 @@ class TestLink(unittest.TestCase):
t = time.time() - start t = time.time() - start
self.assertEqual(resource.status, RNS.Resource.COMPLETE) self.assertEqual(resource.status, RNS.Resource.COMPLETE)
print("Resource completed at "+self.size_str(resource_size/t, "b")+"ps") print("Resource completed at "+self.size_str(resource.total_size/t, "b")+f"ps ({RNS.prettysize(resource.total_size)}, {RNS.prettyshorttime(t)})")
# Test sending resource with metadata
data = os.urandom(resource_size)
metadata = {"text": "Some text", "numbers": [1,2,3,4], "blob": os.urandom(8192)}
print("Sending "+self.size_str(resource_size)+" resource with metadata...")
resource = RNS.Resource(data, l1, metadata=metadata, timeout=resource_timeout)
start = time.time()
# This is a hack, don't do it. Use the callbacks instead.
while resource.status < RNS.Resource.COMPLETE:
time.sleep(0.01)
t = time.time() - start
self.assertEqual(resource.status, RNS.Resource.COMPLETE)
print("Resource completed at "+self.size_str(resource.total_size/t, "b")+f"ps ({RNS.prettysize(resource.total_size)}, {RNS.prettyshorttime(t)})")
l1.teardown() l1.teardown()
time.sleep(0.5) time.sleep(0.5)
self.assertEqual(l1.status, RNS.Link.CLOSED) self.assertEqual(l1.status, RNS.Link.CLOSED)
@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_6_small_resource(self): def test_06_small_resource(self):
init_rns(self) init_rns(self)
print("") print("")
print("Small resource test") print("Small resource test")
@@ -282,7 +427,7 @@ class TestLink(unittest.TestCase):
self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d"))
l1 = RNS.Link(dest) l1 = RNS.Link(dest)
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.ACTIVE) self.assertEqual(l1.status, RNS.Link.ACTIVE)
resource_timeout = 120 resource_timeout = 120
@@ -298,15 +443,30 @@ class TestLink(unittest.TestCase):
t = time.time() - start t = time.time() - start
self.assertEqual(resource.status, RNS.Resource.COMPLETE) self.assertEqual(resource.status, RNS.Resource.COMPLETE)
print("Resource completed at "+self.size_str(resource_size/t, "b")+"ps") print("Resource completed at "+self.size_str(resource.total_size/t, "b")+f"ps ({RNS.prettysize(resource.total_size)}, {RNS.prettyshorttime(t)})")
# Test sending resource with metadata
data = os.urandom(resource_size)
metadata = {"text": "Some text", "numbers": [1,2,3,4], "blob": os.urandom(8192)}
print("Sending "+self.size_str(resource_size)+" resource with metadata...")
resource = RNS.Resource(data, l1, metadata=metadata, timeout=resource_timeout)
start = time.time()
# This is a hack, don't do it. Use the callbacks instead.
while resource.status < RNS.Resource.COMPLETE:
time.sleep(0.01)
t = time.time() - start
self.assertEqual(resource.status, RNS.Resource.COMPLETE)
print("Resource completed at "+self.size_str(resource.total_size/t, "b")+f"ps ({RNS.prettysize(resource.total_size)}, {RNS.prettyshorttime(t)})")
l1.teardown() l1.teardown()
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.CLOSED) self.assertEqual(l1.status, RNS.Link.CLOSED)
@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_7_medium_resource(self): def test_07_medium_resource(self):
if RNS.Cryptography.backend() == "internal": if RNS.Cryptography.backend() == "internal":
print("Skipping medium resource test...") print("Skipping medium resource test...")
return return
@@ -326,26 +486,41 @@ class TestLink(unittest.TestCase):
self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d"))
l1 = RNS.Link(dest) l1 = RNS.Link(dest)
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.ACTIVE) self.assertEqual(l1.status, RNS.Link.ACTIVE)
resource_timeout = 120 resource_timeout = 120
resource_size = 5*1000*1000 resource_size = 5*1000*1000
data = os.urandom(resource_size) data = os.urandom(resource_size)
print("Sending "+self.size_str(resource_size)+" resource...") print("Sending "+self.size_str(resource_size)+" resource...")
resource = RNS.Resource(data, l1, timeout=resource_timeout, auto_compress=False) resource = RNS.Resource(data, l1, timeout=resource_timeout, callback=self.lr_callback, auto_compress=False)
start = time.time() start = time.time()
# This is a hack, don't do it. Use the callbacks instead. TestLink.large_resource_status = resource.status
while resource.status < RNS.Resource.COMPLETE: while TestLink.large_resource_status < RNS.Resource.COMPLETE:
time.sleep(0.01) time.sleep(0.001)
t = time.time() - start t = time.time() - start
self.assertEqual(resource.status, RNS.Resource.COMPLETE) self.assertEqual(resource.status, RNS.Resource.COMPLETE)
print("Resource completed at "+self.size_str(resource_size/t, "b")+"ps") print("Resource completed at "+self.size_str(resource.total_size/t, "b")+f"ps ({RNS.prettysize(resource.total_size)}, {RNS.prettyshorttime(t)})")
# Test sending resource with metadata
data = os.urandom(resource_size)
metadata = {"text": "Some text", "numbers": [1,2,3,4], "blob": os.urandom(8192)}
print("Sending "+self.size_str(resource_size)+" resource with metadata...")
resource = RNS.Resource(data, l1, timeout=resource_timeout, callback=self.lr_callback, auto_compress=False)
start = time.time()
TestLink.large_resource_status = resource.status
while TestLink.large_resource_status < RNS.Resource.COMPLETE:
time.sleep(0.001)
t = time.time() - start
self.assertEqual(resource.status, RNS.Resource.COMPLETE)
print("Resource completed at "+self.size_str(resource.total_size/t, "b")+f"ps ({RNS.prettysize(resource.total_size)}, {RNS.prettyshorttime(t)})")
l1.teardown() l1.teardown()
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.CLOSED) self.assertEqual(l1.status, RNS.Link.CLOSED)
large_resource_status = None large_resource_status = None
@@ -353,7 +528,7 @@ class TestLink(unittest.TestCase):
TestLink.large_resource_status = resource.status TestLink.large_resource_status = resource.status
@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_9_large_resource(self): def test_09_large_resource(self):
if RNS.Cryptography.backend() == "internal": if RNS.Cryptography.backend() == "internal":
print("Skipping large resource test...") print("Skipping large resource test...")
return return
@@ -373,7 +548,7 @@ class TestLink(unittest.TestCase):
self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d"))
l1 = RNS.Link(dest) l1 = RNS.Link(dest)
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.ACTIVE) self.assertEqual(l1.status, RNS.Link.ACTIVE)
resource_timeout = 120 resource_timeout = 120
@@ -385,17 +560,31 @@ class TestLink(unittest.TestCase):
TestLink.large_resource_status = resource.status TestLink.large_resource_status = resource.status
while TestLink.large_resource_status < RNS.Resource.COMPLETE: while TestLink.large_resource_status < RNS.Resource.COMPLETE:
time.sleep(0.01) time.sleep(0.001)
t = time.time() - start t = time.time() - start
self.assertEqual(TestLink.large_resource_status, RNS.Resource.COMPLETE) self.assertEqual(TestLink.large_resource_status, RNS.Resource.COMPLETE)
print("Resource completed at "+self.size_str(resource_size/t, "b")+"ps") print("Resource completed at "+self.size_str(resource.total_size/t, "b")+f"ps ({RNS.prettysize(resource.total_size)}, {RNS.prettyshorttime(t)})")
# Test sending resource with metadata
metadata = {"text": "Some text", "numbers": [1,2,3,4], "blob": os.urandom(8192)}
print("Sending "+self.size_str(resource_size)+" resource with metadata...")
resource = RNS.Resource(data, l1, timeout=resource_timeout, callback=self.lr_callback, auto_compress=False)
start = time.time()
TestLink.large_resource_status = resource.status
while TestLink.large_resource_status < RNS.Resource.COMPLETE:
time.sleep(0.01)
t = time.time() - start
self.assertEqual(resource.status, RNS.Resource.COMPLETE)
print("Resource with metadata completed at "+self.size_str(resource.total_size/t, "b")+f"ps ({RNS.prettysize(resource.total_size)}, {RNS.prettyshorttime(t)})")
l1.teardown() l1.teardown()
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.CLOSED) self.assertEqual(l1.status, RNS.Link.CLOSED)
#@skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_10_channel_round_trip(self): def test_10_channel_round_trip(self):
global c_rns global c_rns
init_rns(self) init_rns(self)
@@ -430,7 +619,7 @@ class TestLink(unittest.TestCase):
channel.add_message_handler(handle_message) channel.add_message_handler(handle_message)
channel.send(test_message) channel.send(test_message)
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(1, len(received)) self.assertEqual(1, len(received))
@@ -443,11 +632,11 @@ class TestLink(unittest.TestCase):
self.assertEqual(0, len(l1._channel._rx_ring)) self.assertEqual(0, len(l1._channel._rx_ring))
l1.teardown() l1.teardown()
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.CLOSED) self.assertEqual(l1.status, RNS.Link.CLOSED)
self.assertEqual(0, len(l1._channel._rx_ring)) self.assertEqual(0, len(l1._channel._rx_ring))
# @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None, "Skipping")
def test_11_buffer_round_trip(self): def test_11_buffer_round_trip(self):
global c_rns global c_rns
init_rns(self) init_rns(self)
@@ -466,7 +655,7 @@ class TestLink(unittest.TestCase):
self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d")) self.assertEqual(dest.hash, bytes.fromhex("fb48da0e82e6e01ba0c014513f74540d"))
l1 = RNS.Link(dest) l1 = RNS.Link(dest)
time.sleep(1) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.ACTIVE) self.assertEqual(l1.status, RNS.Link.ACTIVE)
buffer = None buffer = None
@@ -481,7 +670,7 @@ class TestLink(unittest.TestCase):
buffer.write("Hi there".encode("utf-8")) buffer.write("Hi there".encode("utf-8"))
buffer.flush() buffer.flush()
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(1 , len(received)) self.assertEqual(1 , len(received))
@@ -490,10 +679,10 @@ class TestLink(unittest.TestCase):
self.assertEqual("Hi there back at you", rx_message) self.assertEqual("Hi there back at you", rx_message)
l1.teardown() l1.teardown()
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.CLOSED) self.assertEqual(l1.status, RNS.Link.CLOSED)
# @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None and os.getenv('RUN_SLOW_TESTS') == None, "Skipping") @skipIf(os.getenv('SKIP_NORMAL_TESTS') != None and os.getenv('RUN_SLOW_TESTS') == None, "Skipping")
def test_12_buffer_round_trip_big(self, local_bitrate = None): def test_12_buffer_round_trip_big(self, local_bitrate = None):
global c_rns, buffer_read_target global c_rns, buffer_read_target
init_rns(self) init_rns(self)
@@ -595,7 +784,7 @@ class TestLink(unittest.TestCase):
self.assertEqual(expected_rx_message, rx_message) self.assertEqual(expected_rx_message, rx_message)
l1.teardown() l1.teardown()
time.sleep(0.5) time.sleep(LINK_UP_WAIT)
self.assertEqual(l1.status, RNS.Link.CLOSED) self.assertEqual(l1.status, RNS.Link.CLOSED)
finally: finally:
local_interface.bitrate = original_bitrate local_interface.bitrate = original_bitrate