mirror of
https://github.com/ratspeak/microReticulum
synced 2026-11-22 23:10:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b9bee2701b | ||
|
|
83b88146f4 | ||
|
|
3ddf3c362b | ||
|
|
15b9f13db6 | ||
|
|
dd1e04ab53 | ||
|
|
858010cee0 | ||
|
|
670820a41e | ||
|
|
afc5496d0e | ||
|
|
290a1336eb | ||
|
|
1cadb453eb | ||
|
|
e13b300b0c | ||
|
|
753dce608e | ||
|
|
9d6bbac9a6 | ||
|
|
e93e71dc69 | ||
|
|
b1071754be | ||
|
|
c877730b91 | ||
|
|
dd7c749ea3 | ||
|
|
352de23ed0 | ||
|
|
166083aba7 | ||
|
|
40eeccc646 | ||
|
|
798512e8f7 | ||
|
|
36d5241e9d | ||
|
|
65ecaef894 | ||
|
|
ed362a52ee | ||
|
|
fb76b6707b | ||
|
|
6f3c08de93 | ||
|
|
8b052eb4c3 | ||
|
|
7023c9444a | ||
|
|
1acd840182 | ||
|
|
b44d3743ec | ||
|
|
813d9095d7 | ||
|
|
bb291795da | ||
|
|
bc33c0af64 | ||
|
|
184e6b0250 | ||
|
|
af9fbab780 | ||
|
|
79271a018b | ||
|
|
3bc64abbde | ||
|
|
425c2a9907 | ||
|
|
392363c1b0 | ||
|
|
491fbd034e | ||
|
|
c69087ba40 | ||
|
|
4d6f0b9de2 |
No files matched your search
@@ -11,7 +11,7 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
env: [native, native17, native20]
|
env: [native, native14, native17, native20]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|||||||
@@ -3,3 +3,5 @@
|
|||||||
.vscode/c_cpp_properties.json
|
.vscode/c_cpp_properties.json
|
||||||
.vscode/launch.json
|
.vscode/launch.json
|
||||||
.vscode/ipch
|
.vscode/ipch
|
||||||
|
destination_table
|
||||||
|
cache/
|
||||||
@@ -1,5 +1,12 @@
|
|||||||
# microReticulum
|
# microReticulum
|
||||||
|
|
||||||
|
This Ratspeak fork is retained for the legacy rsDeck, rsPager and rsCardputer
|
||||||
|
firmware. Current handheld firmware is developed in
|
||||||
|
[Ratspeak Handheld](https://github.com/ratspeak/ratspeak-handheld), using
|
||||||
|
[rsReticulumLite](https://github.com/ratspeak/rsReticulumLite) and
|
||||||
|
[rsLXMFLite](https://github.com/ratspeak/rsLXMFLite). The upstream-derived notes
|
||||||
|
below describe the retained C++ library.
|
||||||
|
|
||||||
Port of Reticulum Network Stack to C++ specifically but not exclusively targeting 32-bit and better MCUs.
|
Port of Reticulum Network Stack to C++ specifically but not exclusively targeting 32-bit and better MCUs.
|
||||||
|
|
||||||
Note that this is a library implementing the Reticulum Network Stack and not a useful application on its own. For an actual application, see [microReticulum_Firmware](https://github.com/attermann/microReticulum_Firmware) which is a version of RNode firmware that implements a Reticulm Transport Node.
|
Note that this is a library implementing the Reticulum Network Stack and not a useful application on its own. For an actual application, see [microReticulum_Firmware](https://github.com/attermann/microReticulum_Firmware) which is a version of RNode firmware that implements a Reticulm Transport Node.
|
||||||
@@ -18,9 +25,33 @@ This API is dependent on the following external libraries:
|
|||||||
- `-DRNS_MEM_LOG` Used to enable logging of low-level memory operations for debug purposes
|
- `-DRNS_MEM_LOG` Used to enable logging of low-level memory operations for debug purposes
|
||||||
- `-DRNS_USE_FS` Used to enable use of file system by RNS for persistence
|
- `-DRNS_USE_FS` Used to enable use of file system by RNS for persistence
|
||||||
- `-DRNS_PERSIST_PATHS` Used to enable persistence of RNS paths in file system (also requires `-DRNS_USE_FS`)
|
- `-DRNS_PERSIST_PATHS` Used to enable persistence of RNS paths in file system (also requires `-DRNS_USE_FS`)
|
||||||
- `-DRNS_USE_TLSF=1` Enables the use of the TLSF (Two-Level Segregate Fit) dynamic memory manager for efficient management of constrained MCU memory with minimal fragmentation. Currently only required on NRF52 boards (ESP32 already uses TLSF internally).
|
|
||||||
- `-RNS_TLSF_BUFFER_SIZ=N` Defines the TLSF memory pool buffer size (N bytes, default 0 which means dynamic)
|
## Memory Management Build Options
|
||||||
- `-DRNS_USE_ALLOCATOR=1` Enables the replacement of default new/delete operators with custom implementations that take advantage of optimized memory managers (eg, TLSF). Currently only required on NRF52 boards (ESP32 already uses TLSF internally).
|
|
||||||
|
Two classes of memory allocator are defined; the container allocator (`RNS_CONTAINER_ALLOCATOR`) which is used for certain long-lived STL containers (e.g. path table), and the default allocator (`RNS_DEFAULT_ALLOCATOR`) which is used for all other C++ memory allocation (new/delete).
|
||||||
|
|
||||||
|
Each class of allocator can be configured to use a separate type of allocator. Available memory allocators are:
|
||||||
|
- `RNS_HEAP_ALLOCATOR`: Basic allocator that uses default system HEAP.
|
||||||
|
- `RNS_HEAP_POOL_ALLOCATOR`: Optimized TLSF managed HEAP buffer
|
||||||
|
- `RNS_PSRAM_ALLOCATOR`: Basic allocator that uses PSRAM memory (if PSRAM is available)
|
||||||
|
- `RNS_PSRAM_POOL_ALLOCATOR`: Optimized TLSF managed PSRAM buffer (if PSRAM is available)
|
||||||
|
|
||||||
|
Each class of allocator pool can have a separate buffer size:
|
||||||
|
- `RNS_HEAP_POOL_BUFFER_SIZE=N` Defines the HEAP TLSF memory pool buffer size (N bytes, default 0 which means dynamic)
|
||||||
|
- `RNS_PSRAM_POOL_BUFFER_SIZE=N` Defines the PSRAM TLSF memory pool buffer size (N bytes, default 0 which means dynamic)
|
||||||
|
|
||||||
|
"POOL" allocators use TLSF (Two-Level Segregate Fit) for efficient management of constrained MCU memory with minimal fragmentation.
|
||||||
|
|
||||||
|
The allocator for each class can be configured using build flags in `platformio.ini`, for example:
|
||||||
|
|
||||||
|
```
|
||||||
|
[env]
|
||||||
|
build_flags =
|
||||||
|
-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_ALLOCATOR
|
||||||
|
-DRNS_CONTAINER_ALLOCATOR=RNS_PSRAM_POOL_ALLOCATOR
|
||||||
|
```
|
||||||
|
|
||||||
|
NOTE: Currently `-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_POOL_ALLOCATOR` is only required on NRF52 boards since ESP32 already uses TLSF internally.
|
||||||
|
|
||||||
## Building
|
## Building
|
||||||
|
|
||||||
@@ -31,7 +62,7 @@ Building and uploading to hardware is simple through the VSCode PlatformIO IDE
|
|||||||
- In PlatformIO, select the environment for intended board
|
- In PlatformIO, select the environment for intended board
|
||||||
- Build, Upload, and Monitor to observe application logging
|
- Build, Upload, and Monitor to observe application logging
|
||||||
|
|
||||||
Instructions for command line builds and building of individual example applications coming soon.
|
Command-line build and test commands are listed below.
|
||||||
|
|
||||||
## PlatformIO Command Line
|
## PlatformIO Command Line
|
||||||
|
|
||||||
|
|||||||
@@ -247,14 +247,13 @@ void UniversalFileSystem::listDir(const char* dir) {
|
|||||||
//if (!file) {
|
//if (!file) {
|
||||||
File* file = new File(SPIFFS.open(file_path, mode));
|
File* file = new File(SPIFFS.open(file_path, mode));
|
||||||
if (file == nullptr || !(*file)) {
|
if (file == nullptr || !(*file)) {
|
||||||
|
if (file != nullptr) delete file;
|
||||||
ERRORF("open_file: failed to open output file %s", file_path);
|
ERRORF("open_file: failed to open output file %s", file_path);
|
||||||
return {RNS::Type::NONE};
|
return {RNS::Type::NONE};
|
||||||
}
|
}
|
||||||
TRACEF("open_file: successfully opened file %s", file_path);
|
TRACEF("open_file: successfully opened file %s", file_path);
|
||||||
return RNS::FileStream(new UniversalFileStream(file));
|
return RNS::FileStream(new UniversalFileStream(file));
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
//File file = File(InternalFS);
|
|
||||||
File* file = new File(InternalFS);
|
|
||||||
int mode;
|
int mode;
|
||||||
if (file_mode == RNS::FileStream::MODE_READ) {
|
if (file_mode == RNS::FileStream::MODE_READ) {
|
||||||
mode = FILE_O_READ;
|
mode = FILE_O_READ;
|
||||||
@@ -274,7 +273,10 @@ void UniversalFileSystem::listDir(const char* dir) {
|
|||||||
ERRORF("open_file: unsupported mode %d", file_mode);
|
ERRORF("open_file: unsupported mode %d", file_mode);
|
||||||
return {RNS::Type::NONE};
|
return {RNS::Type::NONE};
|
||||||
}
|
}
|
||||||
if (!file->open(file_path, mode)) {
|
//File file = File(InternalFS);
|
||||||
|
File* file = new File(InternalFS);
|
||||||
|
if (file == nullptr || !file->open(file_path, mode)) {
|
||||||
|
if (file != nullptr) delete file;
|
||||||
ERRORF("open_file: failed to open output file %s", file_path);
|
ERRORF("open_file: failed to open output file %s", file_path);
|
||||||
return {RNS::Type::NONE};
|
return {RNS::Type::NONE};
|
||||||
}
|
}
|
||||||
@@ -430,7 +432,7 @@ void UniversalFileSystem::listDir(const char* dir) {
|
|||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
/*virtua*/ std::list<std::string> UniversalFileSystem::list_directory(const char* directory_path) {
|
/*virtua*/ std::list<std::string> UniversalFileSystem::list_directory(const char* directory_path, Callbacks::DirectoryListing callback /*= nullptr*/) {
|
||||||
TRACEF("list_directory: listing directory %s", directory_path);
|
TRACEF("list_directory: listing directory %s", directory_path);
|
||||||
std::list<std::string> files;
|
std::list<std::string> files;
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
@@ -447,7 +449,8 @@ void UniversalFileSystem::listDir(const char* dir) {
|
|||||||
while (file) {
|
while (file) {
|
||||||
if (!file.isDirectory()) {
|
if (!file.isDirectory()) {
|
||||||
char* name = (char*)file.name();
|
char* name = (char*)file.name();
|
||||||
files.push_back(name);
|
if (callback) callback(name);
|
||||||
|
else files.push_back(name);
|
||||||
}
|
}
|
||||||
// CBA Following close required to avoid leaking memory
|
// CBA Following close required to avoid leaking memory
|
||||||
file.close();
|
file.close();
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ public:
|
|||||||
virtual bool directory_exists(const char* directory_path);
|
virtual bool directory_exists(const char* directory_path);
|
||||||
virtual bool create_directory(const char* directory_path);
|
virtual bool create_directory(const char* directory_path);
|
||||||
virtual bool remove_directory(const char* directory_path);
|
virtual bool remove_directory(const char* directory_path);
|
||||||
virtual std::list<std::string> list_directory(const char* directory_path);
|
virtual std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr);
|
||||||
virtual size_t storage_size();
|
virtual size_t storage_size();
|
||||||
virtual size_t storage_available();
|
virtual size_t storage_available();
|
||||||
|
|
||||||
|
|||||||
+14
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "microReticulum",
|
"name": "microReticulum",
|
||||||
"version": "0.2.9",
|
"version": "0.2.10",
|
||||||
"description": "Port of Reticulum Network Stack to C++ specifically but not exclusively targeting 32-bit and better MCUs",
|
"description": "Port of Reticulum Network Stack to C++ specifically but not exclusively targeting 32-bit and better MCUs",
|
||||||
"keywords": "reticulum, rns, mesh, embedded, mcu, esp32, nrf52, native",
|
"keywords": "reticulum, rns, mesh, embedded, mcu, esp32, nrf52, native",
|
||||||
"repository":
|
"repository":
|
||||||
@@ -27,5 +27,17 @@
|
|||||||
"export": {},
|
"export": {},
|
||||||
"exclude": [
|
"exclude": [
|
||||||
".github"
|
".github"
|
||||||
]
|
],
|
||||||
|
"build": {
|
||||||
|
"srcFilter": [
|
||||||
|
"+<*>",
|
||||||
|
"-<Compression/blocksort.c>",
|
||||||
|
"-<Compression/bz2_compress.c>",
|
||||||
|
"-<Compression/bz2_decompress.c>",
|
||||||
|
"-<Compression/bzlib.c>",
|
||||||
|
"-<Compression/crctable.c>",
|
||||||
|
"-<Compression/huffman.c>",
|
||||||
|
"-<Compression/randtable.c>"
|
||||||
|
]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -1,5 +1,5 @@
|
|||||||
name=microReticulum
|
name=microReticulum
|
||||||
version=0.2.9
|
version=0.2.10
|
||||||
author=Chad Attermann <attermann@gmail.com>
|
author=Chad Attermann <attermann@gmail.com>
|
||||||
maintainer=Chad Attermann <attermann@gmail.com>
|
maintainer=Chad Attermann <attermann@gmail.com>
|
||||||
sentence=Port of Reticulum Network Stack to C++
|
sentence=Port of Reticulum Network Stack to C++
|
||||||
|
|||||||
+45
-16
@@ -45,6 +45,19 @@ lib_deps =
|
|||||||
${env.lib_deps}
|
${env.lib_deps}
|
||||||
lib_compat_mode = off
|
lib_compat_mode = off
|
||||||
|
|
||||||
|
[env:native14]
|
||||||
|
platform = native
|
||||||
|
build_unflags =
|
||||||
|
${env.build_unflags}
|
||||||
|
-std=gnu++11
|
||||||
|
build_flags =
|
||||||
|
${env.build_flags}
|
||||||
|
-std=gnu++14
|
||||||
|
-DNATIVE
|
||||||
|
lib_deps =
|
||||||
|
${env.lib_deps}
|
||||||
|
lib_compat_mode = off
|
||||||
|
|
||||||
[env:native17]
|
[env:native17]
|
||||||
platform = native
|
platform = native
|
||||||
build_unflags =
|
build_unflags =
|
||||||
@@ -73,9 +86,13 @@ lib_compat_mode = off
|
|||||||
|
|
||||||
[env:native_debug]
|
[env:native_debug]
|
||||||
platform = native
|
platform = native
|
||||||
|
build_unflags =
|
||||||
|
${env.build_unflags}
|
||||||
|
-std=gnu++11
|
||||||
build_flags =
|
build_flags =
|
||||||
${env.build_flags}
|
${env.build_flags}
|
||||||
-std=gnu++11
|
;-std=gnu++11
|
||||||
|
-std=gnu++17
|
||||||
-DNATIVE
|
-DNATIVE
|
||||||
; CBA TEST
|
; CBA TEST
|
||||||
;-fsanitize=address
|
;-fsanitize=address
|
||||||
@@ -83,31 +100,36 @@ build_flags =
|
|||||||
-g
|
-g
|
||||||
;-O1
|
;-O1
|
||||||
-O0
|
-O0
|
||||||
;-DRNS_MEM_LOG
|
;-DBOARD_HAS_PSRAM=1
|
||||||
-DRNS_USE_ALLOCATOR=1
|
;-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_ALLOCATOR
|
||||||
-DRNS_USE_TLSF=1
|
-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_POOL_ALLOCATOR
|
||||||
|
-DRNS_CONTAINER_ALLOCATOR=RNS_ALTHEAP_POOL_ALLOCATOR
|
||||||
|
;-DRNS_HEAP_POOL_BUFFER_SIZE=81920
|
||||||
|
;-DRNS_HEAP_POOL_BUFFER_SIZE=102400
|
||||||
|
-DRNS_HEAP_POOL_BUFFER_SIZE=204800
|
||||||
|
;-DRNS_HEAP_POOL_BUFFER_SIZE=307200
|
||||||
|
;-DRNS_HEAP_POOL_BUFFER_SIZE=409600
|
||||||
|
;-DRNS_HEAP_POOL_BUFFER_SIZE=512000
|
||||||
|
;-DRNS_HEAP_POOL_BUFFER_SIZE=614400
|
||||||
|
;-DRNS_HEAP_POOL_BUFFER_SIZE=1024000
|
||||||
|
-DRNS_ALTHEAP_POOL_BUFFER_SIZE=2048000
|
||||||
-DTLSF_DEBUG=1
|
-DTLSF_DEBUG=1
|
||||||
;-DRNS_TLSF_BUFFER_SIZE=81920
|
;-DRNS_MEM_LOG
|
||||||
;-DRNS_TLSF_BUFFER_SIZE=102400
|
|
||||||
-DRNS_TLSF_BUFFER_SIZE=204800
|
|
||||||
;-DRNS_TLSF_BUFFER_SIZE=307200
|
|
||||||
;-DRNS_TLSF_BUFFER_SIZE=409600
|
|
||||||
;-DRNS_TLSF_BUFFER_SIZE=512000
|
|
||||||
;-DRNS_TLSF_BUFFER_SIZE=614400
|
|
||||||
;-DRNS_TLSF_BUFFER_SIZE=1024000
|
|
||||||
lib_deps =
|
lib_deps =
|
||||||
${env.lib_deps}
|
${env.lib_deps}
|
||||||
lib_compat_mode = off
|
lib_compat_mode = off
|
||||||
|
test_flags = -vvv
|
||||||
|
|
||||||
[env:embedded]
|
[env:embedded]
|
||||||
framework = arduino
|
framework = arduino
|
||||||
upload_speed = 460800
|
upload_speed = 460800
|
||||||
build_unflags =
|
build_unflags =
|
||||||
${env.build_unflags}
|
${env.build_unflags}
|
||||||
;-std=gnu++11
|
-std=gnu++11
|
||||||
|
;-fno-rtti
|
||||||
build_flags =
|
build_flags =
|
||||||
${env.build_flags}
|
${env.build_flags}
|
||||||
;-std=gnu++17
|
-std=gnu++17
|
||||||
lib_deps =
|
lib_deps =
|
||||||
${env.lib_deps}
|
${env.lib_deps}
|
||||||
|
|
||||||
@@ -168,6 +190,13 @@ build_flags =
|
|||||||
-DBOARD_ESP32
|
-DBOARD_ESP32
|
||||||
-DMSGPACK_USE_BOOST=OFF
|
-DMSGPACK_USE_BOOST=OFF
|
||||||
-DARDUINO_USB_CDC_ON_BOOT=1
|
-DARDUINO_USB_CDC_ON_BOOT=1
|
||||||
|
; CBA TEST
|
||||||
|
-DBOARD_HAS_PSRAM=1
|
||||||
|
;-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_ALLOCATOR
|
||||||
|
-DRNS_DEFAULT_ALLOCATOR=RNS_PSRAM_ALLOCATOR
|
||||||
|
;-DRNS_CONTAINER_ALLOCATOR=RNS_PSRAM_ALLOCATOR
|
||||||
|
-DRNS_CONTAINER_ALLOCATOR=RNS_PSRAM_POOL_ALLOCATOR
|
||||||
|
-DRNS_PSRAM_POOL_BUFFER_SIZE=2048000
|
||||||
lib_deps =
|
lib_deps =
|
||||||
${env:embedded.lib_deps}
|
${env:embedded.lib_deps}
|
||||||
monitor_filters = esp32_exception_decoder
|
monitor_filters = esp32_exception_decoder
|
||||||
@@ -184,8 +213,8 @@ build_flags =
|
|||||||
-I variants/rak4630
|
-I variants/rak4630
|
||||||
-fexceptions
|
-fexceptions
|
||||||
-DBOARD_NRF52
|
-DBOARD_NRF52
|
||||||
-DRNS_USE_ALLOCATOR=1
|
-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_POOL_ALLOCATOR
|
||||||
-DRNS_USE_TLSF=1
|
-DRNS_HEAP_POOL_BUFFER_SIZE=204800
|
||||||
-DMSGPACK_USE_BOOST=OFF
|
-DMSGPACK_USE_BOOST=OFF
|
||||||
lib_deps =
|
lib_deps =
|
||||||
${env:embedded.lib_deps}
|
${env:embedded.lib_deps}
|
||||||
|
|||||||
+4
-2
@@ -1,6 +1,7 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
|
#include "Utilities/Memory.h"
|
||||||
|
|
||||||
#include <ArduinoJson.h>
|
#include <ArduinoJson.h>
|
||||||
|
|
||||||
@@ -40,9 +41,9 @@ namespace RNS {
|
|||||||
class Bytes {
|
class Bytes {
|
||||||
|
|
||||||
private:
|
private:
|
||||||
//typedef std::vector<uint8_t> Data;
|
|
||||||
using Data = std::vector<uint8_t>;
|
using Data = std::vector<uint8_t>;
|
||||||
//typedef std::shared_ptr<Data> SharedData;
|
// CBA Need to fix msgpack serialize/deserialize before enabling ContainerAllocator
|
||||||
|
//using Data = std::vector<uint8_t, Utilities::Memory::ContainerAllocator<uint8_t>>;
|
||||||
using SharedData = std::shared_ptr<Data>;
|
using SharedData = std::shared_ptr<Data>;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
@@ -433,6 +434,7 @@ inline RNS::Bytes& operator << (RNS::Bytes& lhbytes, const char* rhstr) {
|
|||||||
return lhbytes;
|
return lhbytes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//CBA TODO Standardize where custom object de/serialization lives
|
||||||
namespace ArduinoJson {
|
namespace ArduinoJson {
|
||||||
// Serialize
|
// Serialize
|
||||||
inline bool convertToJson(const RNS::Bytes& src, JsonVariant dst) {
|
inline bool convertToJson(const RNS::Bytes& src, JsonVariant dst) {
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
/// BZ2 compression shim — no-op on this build.
|
||||||
|
///
|
||||||
|
/// The vendored libbzip2 is intentionally NOT linked on embedded targets:
|
||||||
|
/// bzip2's working-set memory and decode-table state are too large for
|
||||||
|
/// MCU-class devices (a single decompress can use multiples of available
|
||||||
|
/// SRAM). The functions below are kept so callers in Resource.cpp can
|
||||||
|
/// still link against this symbol surface without any conditional
|
||||||
|
/// compilation, but they never compress and never decompress.
|
||||||
|
///
|
||||||
|
/// To re-introduce a portable compression scheme later, replace these
|
||||||
|
/// implementations with something MCU-safe (e.g. heatshrink or LZ4) and
|
||||||
|
/// negotiate support through the LXMF announce capability list, NOT bz2.
|
||||||
|
|
||||||
|
#include "BZ2.h"
|
||||||
|
|
||||||
|
namespace RNS {
|
||||||
|
namespace Compression {
|
||||||
|
|
||||||
|
Bytes bz2_compress(const uint8_t* /*data*/, size_t /*len*/) {
|
||||||
|
return Bytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
Bytes bz2_decompress(const uint8_t* /*data*/, size_t /*len*/, size_t /*max_size*/) {
|
||||||
|
return Bytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
CompressResult try_compress(const Bytes& data) {
|
||||||
|
return { data, false };
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace Compression
|
||||||
|
} // namespace RNS
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
/// BZ2 compression/decompression wrapper for Reticulum Resource transfers.
|
||||||
|
/// Uses the vendored libbzip2 (bzip2-1.0.8, BSD license).
|
||||||
|
///
|
||||||
|
/// Matches Python's bz2.compress()/bz2.decompress() and Rust's bzip2 crate.
|
||||||
|
|
||||||
|
#include "../Bytes.h"
|
||||||
|
#include <cstdint>
|
||||||
|
#include <cstddef>
|
||||||
|
|
||||||
|
namespace RNS {
|
||||||
|
namespace Compression {
|
||||||
|
|
||||||
|
/// Compress data using bz2. Returns empty Bytes on failure.
|
||||||
|
Bytes bz2_compress(const uint8_t* data, size_t len);
|
||||||
|
inline Bytes bz2_compress(const Bytes& data) { return bz2_compress(data.data(), data.size()); }
|
||||||
|
|
||||||
|
/// Decompress bz2 data. Returns empty Bytes on failure.
|
||||||
|
/// max_size limits decompressed output (0 = no limit).
|
||||||
|
Bytes bz2_decompress(const uint8_t* data, size_t len, size_t max_size = 0);
|
||||||
|
inline Bytes bz2_decompress(const Bytes& data, size_t max_size = 0) { return bz2_decompress(data.data(), data.size(), max_size); }
|
||||||
|
|
||||||
|
/// Try compression: returns (compressed, true) if smaller, (original, false) otherwise.
|
||||||
|
struct CompressResult {
|
||||||
|
Bytes data;
|
||||||
|
bool compressed;
|
||||||
|
};
|
||||||
|
CompressResult try_compress(const Bytes& data);
|
||||||
|
|
||||||
|
} // namespace Compression
|
||||||
|
} // namespace RNS
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
/* bzip2 source intentionally removed on this fork.
|
||||||
|
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||||
|
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
/* bzip2 source intentionally removed on this fork.
|
||||||
|
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||||
|
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
/* bzip2 source intentionally removed on this fork.
|
||||||
|
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||||
|
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
/* bzip2 source intentionally removed on this fork.
|
||||||
|
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||||
|
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
|
||||||
|
/*-------------------------------------------------------------*/
|
||||||
|
/*--- Public header file for the library. ---*/
|
||||||
|
/*--- bzlib.h ---*/
|
||||||
|
/*-------------------------------------------------------------*/
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------
|
||||||
|
This file is part of bzip2/libbzip2, a program and library for
|
||||||
|
lossless, block-sorting data compression.
|
||||||
|
|
||||||
|
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||||
|
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||||
|
|
||||||
|
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||||
|
README file.
|
||||||
|
|
||||||
|
This program is released under the terms of the license contained
|
||||||
|
in the file LICENSE.
|
||||||
|
------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef _BZLIB_H
|
||||||
|
#define _BZLIB_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define BZ_RUN 0
|
||||||
|
#define BZ_FLUSH 1
|
||||||
|
#define BZ_FINISH 2
|
||||||
|
|
||||||
|
#define BZ_OK 0
|
||||||
|
#define BZ_RUN_OK 1
|
||||||
|
#define BZ_FLUSH_OK 2
|
||||||
|
#define BZ_FINISH_OK 3
|
||||||
|
#define BZ_STREAM_END 4
|
||||||
|
#define BZ_SEQUENCE_ERROR (-1)
|
||||||
|
#define BZ_PARAM_ERROR (-2)
|
||||||
|
#define BZ_MEM_ERROR (-3)
|
||||||
|
#define BZ_DATA_ERROR (-4)
|
||||||
|
#define BZ_DATA_ERROR_MAGIC (-5)
|
||||||
|
#define BZ_IO_ERROR (-6)
|
||||||
|
#define BZ_UNEXPECTED_EOF (-7)
|
||||||
|
#define BZ_OUTBUFF_FULL (-8)
|
||||||
|
#define BZ_CONFIG_ERROR (-9)
|
||||||
|
|
||||||
|
typedef
|
||||||
|
struct {
|
||||||
|
char *next_in;
|
||||||
|
unsigned int avail_in;
|
||||||
|
unsigned int total_in_lo32;
|
||||||
|
unsigned int total_in_hi32;
|
||||||
|
|
||||||
|
char *next_out;
|
||||||
|
unsigned int avail_out;
|
||||||
|
unsigned int total_out_lo32;
|
||||||
|
unsigned int total_out_hi32;
|
||||||
|
|
||||||
|
void *state;
|
||||||
|
|
||||||
|
void *(*bzalloc)(void *,int,int);
|
||||||
|
void (*bzfree)(void *,void *);
|
||||||
|
void *opaque;
|
||||||
|
}
|
||||||
|
bz_stream;
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef BZ_IMPORT
|
||||||
|
#define BZ_EXPORT
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef BZ_NO_STDIO
|
||||||
|
/* Need a definitition for FILE */
|
||||||
|
#include <stdio.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
# include <windows.h>
|
||||||
|
# ifdef small
|
||||||
|
/* windows.h define small to char */
|
||||||
|
# undef small
|
||||||
|
# endif
|
||||||
|
# ifdef BZ_EXPORT
|
||||||
|
# define BZ_API(func) WINAPI func
|
||||||
|
# define BZ_EXTERN extern
|
||||||
|
# else
|
||||||
|
/* import windows dll dynamically */
|
||||||
|
# define BZ_API(func) (WINAPI * func)
|
||||||
|
# define BZ_EXTERN
|
||||||
|
# endif
|
||||||
|
#else
|
||||||
|
# define BZ_API(func) func
|
||||||
|
# define BZ_EXTERN extern
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*-- Core (low-level) library functions --*/
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzCompressInit) (
|
||||||
|
bz_stream* strm,
|
||||||
|
int blockSize100k,
|
||||||
|
int verbosity,
|
||||||
|
int workFactor
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzCompress) (
|
||||||
|
bz_stream* strm,
|
||||||
|
int action
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) (
|
||||||
|
bz_stream* strm
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) (
|
||||||
|
bz_stream *strm,
|
||||||
|
int verbosity,
|
||||||
|
int small
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzDecompress) (
|
||||||
|
bz_stream* strm
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) (
|
||||||
|
bz_stream *strm
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- High(er) level library functions --*/
|
||||||
|
|
||||||
|
#ifndef BZ_NO_STDIO
|
||||||
|
#define BZ_MAX_UNUSED 5000
|
||||||
|
|
||||||
|
typedef void BZFILE;
|
||||||
|
|
||||||
|
BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) (
|
||||||
|
int* bzerror,
|
||||||
|
FILE* f,
|
||||||
|
int verbosity,
|
||||||
|
int small,
|
||||||
|
void* unused,
|
||||||
|
int nUnused
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN void BZ_API(BZ2_bzReadClose) (
|
||||||
|
int* bzerror,
|
||||||
|
BZFILE* b
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) (
|
||||||
|
int* bzerror,
|
||||||
|
BZFILE* b,
|
||||||
|
void** unused,
|
||||||
|
int* nUnused
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzRead) (
|
||||||
|
int* bzerror,
|
||||||
|
BZFILE* b,
|
||||||
|
void* buf,
|
||||||
|
int len
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) (
|
||||||
|
int* bzerror,
|
||||||
|
FILE* f,
|
||||||
|
int blockSize100k,
|
||||||
|
int verbosity,
|
||||||
|
int workFactor
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN void BZ_API(BZ2_bzWrite) (
|
||||||
|
int* bzerror,
|
||||||
|
BZFILE* b,
|
||||||
|
void* buf,
|
||||||
|
int len
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN void BZ_API(BZ2_bzWriteClose) (
|
||||||
|
int* bzerror,
|
||||||
|
BZFILE* b,
|
||||||
|
int abandon,
|
||||||
|
unsigned int* nbytes_in,
|
||||||
|
unsigned int* nbytes_out
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) (
|
||||||
|
int* bzerror,
|
||||||
|
BZFILE* b,
|
||||||
|
int abandon,
|
||||||
|
unsigned int* nbytes_in_lo32,
|
||||||
|
unsigned int* nbytes_in_hi32,
|
||||||
|
unsigned int* nbytes_out_lo32,
|
||||||
|
unsigned int* nbytes_out_hi32
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*-- Utility functions --*/
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) (
|
||||||
|
char* dest,
|
||||||
|
unsigned int* destLen,
|
||||||
|
char* source,
|
||||||
|
unsigned int sourceLen,
|
||||||
|
int blockSize100k,
|
||||||
|
int verbosity,
|
||||||
|
int workFactor
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) (
|
||||||
|
char* dest,
|
||||||
|
unsigned int* destLen,
|
||||||
|
char* source,
|
||||||
|
unsigned int sourceLen,
|
||||||
|
int small,
|
||||||
|
int verbosity
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
|
/*--
|
||||||
|
Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp)
|
||||||
|
to support better zlib compatibility.
|
||||||
|
This code is not _officially_ part of libbzip2 (yet);
|
||||||
|
I haven't tested it, documented it, or considered the
|
||||||
|
threading-safeness of it.
|
||||||
|
If this code breaks, please contact both Yoshioka and me.
|
||||||
|
--*/
|
||||||
|
|
||||||
|
BZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) (
|
||||||
|
void
|
||||||
|
);
|
||||||
|
|
||||||
|
#ifndef BZ_NO_STDIO
|
||||||
|
BZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) (
|
||||||
|
const char *path,
|
||||||
|
const char *mode
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) (
|
||||||
|
int fd,
|
||||||
|
const char *mode
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzread) (
|
||||||
|
BZFILE* b,
|
||||||
|
void* buf,
|
||||||
|
int len
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzwrite) (
|
||||||
|
BZFILE* b,
|
||||||
|
void* buf,
|
||||||
|
int len
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN int BZ_API(BZ2_bzflush) (
|
||||||
|
BZFILE* b
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN void BZ_API(BZ2_bzclose) (
|
||||||
|
BZFILE* b
|
||||||
|
);
|
||||||
|
|
||||||
|
BZ_EXTERN const char * BZ_API(BZ2_bzerror) (
|
||||||
|
BZFILE *b,
|
||||||
|
int *errnum
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
/*-------------------------------------------------------------*/
|
||||||
|
/*--- end bzlib.h ---*/
|
||||||
|
/*-------------------------------------------------------------*/
|
||||||
@@ -0,0 +1,509 @@
|
|||||||
|
|
||||||
|
/*-------------------------------------------------------------*/
|
||||||
|
/*--- Private header file for the library. ---*/
|
||||||
|
/*--- bzlib_private.h ---*/
|
||||||
|
/*-------------------------------------------------------------*/
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------
|
||||||
|
This file is part of bzip2/libbzip2, a program and library for
|
||||||
|
lossless, block-sorting data compression.
|
||||||
|
|
||||||
|
bzip2/libbzip2 version 1.0.8 of 13 July 2019
|
||||||
|
Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>
|
||||||
|
|
||||||
|
Please read the WARNING, DISCLAIMER and PATENTS sections in the
|
||||||
|
README file.
|
||||||
|
|
||||||
|
This program is released under the terms of the license contained
|
||||||
|
in the file LICENSE.
|
||||||
|
------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
|
||||||
|
#ifndef _BZLIB_PRIVATE_H
|
||||||
|
#define _BZLIB_PRIVATE_H
|
||||||
|
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
#ifndef BZ_NO_STDIO
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <ctype.h>
|
||||||
|
#include <string.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "bzlib.h"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- General stuff. --*/
|
||||||
|
|
||||||
|
#define BZ_VERSION "1.0.8, 13-Jul-2019"
|
||||||
|
|
||||||
|
typedef char Char;
|
||||||
|
typedef unsigned char Bool;
|
||||||
|
typedef unsigned char UChar;
|
||||||
|
typedef int Int32;
|
||||||
|
typedef unsigned int UInt32;
|
||||||
|
typedef short Int16;
|
||||||
|
typedef unsigned short UInt16;
|
||||||
|
|
||||||
|
#define True ((Bool)1)
|
||||||
|
#define False ((Bool)0)
|
||||||
|
|
||||||
|
#ifndef __GNUC__
|
||||||
|
#define __inline__ /* */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef BZ_NO_STDIO
|
||||||
|
|
||||||
|
extern void BZ2_bz__AssertH__fail ( int errcode );
|
||||||
|
#define AssertH(cond,errcode) \
|
||||||
|
{ if (!(cond)) BZ2_bz__AssertH__fail ( errcode ); }
|
||||||
|
|
||||||
|
#if BZ_DEBUG
|
||||||
|
#define AssertD(cond,msg) \
|
||||||
|
{ if (!(cond)) { \
|
||||||
|
fprintf ( stderr, \
|
||||||
|
"\n\nlibbzip2(debug build): internal error\n\t%s\n", msg );\
|
||||||
|
exit(1); \
|
||||||
|
}}
|
||||||
|
#else
|
||||||
|
#define AssertD(cond,msg) /* */
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define VPrintf0(zf) \
|
||||||
|
fprintf(stderr,zf)
|
||||||
|
#define VPrintf1(zf,za1) \
|
||||||
|
fprintf(stderr,zf,za1)
|
||||||
|
#define VPrintf2(zf,za1,za2) \
|
||||||
|
fprintf(stderr,zf,za1,za2)
|
||||||
|
#define VPrintf3(zf,za1,za2,za3) \
|
||||||
|
fprintf(stderr,zf,za1,za2,za3)
|
||||||
|
#define VPrintf4(zf,za1,za2,za3,za4) \
|
||||||
|
fprintf(stderr,zf,za1,za2,za3,za4)
|
||||||
|
#define VPrintf5(zf,za1,za2,za3,za4,za5) \
|
||||||
|
fprintf(stderr,zf,za1,za2,za3,za4,za5)
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
|
extern void bz_internal_error ( int errcode );
|
||||||
|
#define AssertH(cond,errcode) \
|
||||||
|
{ if (!(cond)) bz_internal_error ( errcode ); }
|
||||||
|
#define AssertD(cond,msg) do { } while (0)
|
||||||
|
#define VPrintf0(zf) do { } while (0)
|
||||||
|
#define VPrintf1(zf,za1) do { } while (0)
|
||||||
|
#define VPrintf2(zf,za1,za2) do { } while (0)
|
||||||
|
#define VPrintf3(zf,za1,za2,za3) do { } while (0)
|
||||||
|
#define VPrintf4(zf,za1,za2,za3,za4) do { } while (0)
|
||||||
|
#define VPrintf5(zf,za1,za2,za3,za4,za5) do { } while (0)
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#define BZALLOC(nnn) (strm->bzalloc)(strm->opaque,(nnn),1)
|
||||||
|
#define BZFREE(ppp) (strm->bzfree)(strm->opaque,(ppp))
|
||||||
|
|
||||||
|
|
||||||
|
/*-- Header bytes. --*/
|
||||||
|
|
||||||
|
#define BZ_HDR_B 0x42 /* 'B' */
|
||||||
|
#define BZ_HDR_Z 0x5a /* 'Z' */
|
||||||
|
#define BZ_HDR_h 0x68 /* 'h' */
|
||||||
|
#define BZ_HDR_0 0x30 /* '0' */
|
||||||
|
|
||||||
|
/*-- Constants for the back end. --*/
|
||||||
|
|
||||||
|
#define BZ_MAX_ALPHA_SIZE 258
|
||||||
|
#define BZ_MAX_CODE_LEN 23
|
||||||
|
|
||||||
|
#define BZ_RUNA 0
|
||||||
|
#define BZ_RUNB 1
|
||||||
|
|
||||||
|
#define BZ_N_GROUPS 6
|
||||||
|
#define BZ_G_SIZE 50
|
||||||
|
#define BZ_N_ITERS 4
|
||||||
|
|
||||||
|
#define BZ_MAX_SELECTORS (2 + (900000 / BZ_G_SIZE))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- Stuff for randomising repetitive blocks. --*/
|
||||||
|
|
||||||
|
extern Int32 BZ2_rNums[512];
|
||||||
|
|
||||||
|
#define BZ_RAND_DECLS \
|
||||||
|
Int32 rNToGo; \
|
||||||
|
Int32 rTPos \
|
||||||
|
|
||||||
|
#define BZ_RAND_INIT_MASK \
|
||||||
|
s->rNToGo = 0; \
|
||||||
|
s->rTPos = 0 \
|
||||||
|
|
||||||
|
#define BZ_RAND_MASK ((s->rNToGo == 1) ? 1 : 0)
|
||||||
|
|
||||||
|
#define BZ_RAND_UPD_MASK \
|
||||||
|
if (s->rNToGo == 0) { \
|
||||||
|
s->rNToGo = BZ2_rNums[s->rTPos]; \
|
||||||
|
s->rTPos++; \
|
||||||
|
if (s->rTPos == 512) s->rTPos = 0; \
|
||||||
|
} \
|
||||||
|
s->rNToGo--;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- Stuff for doing CRCs. --*/
|
||||||
|
|
||||||
|
extern UInt32 BZ2_crc32Table[256];
|
||||||
|
|
||||||
|
#define BZ_INITIALISE_CRC(crcVar) \
|
||||||
|
{ \
|
||||||
|
crcVar = 0xffffffffL; \
|
||||||
|
}
|
||||||
|
|
||||||
|
#define BZ_FINALISE_CRC(crcVar) \
|
||||||
|
{ \
|
||||||
|
crcVar = ~(crcVar); \
|
||||||
|
}
|
||||||
|
|
||||||
|
#define BZ_UPDATE_CRC(crcVar,cha) \
|
||||||
|
{ \
|
||||||
|
crcVar = (crcVar << 8) ^ \
|
||||||
|
BZ2_crc32Table[(crcVar >> 24) ^ \
|
||||||
|
((UChar)cha)]; \
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- States and modes for compression. --*/
|
||||||
|
|
||||||
|
#define BZ_M_IDLE 1
|
||||||
|
#define BZ_M_RUNNING 2
|
||||||
|
#define BZ_M_FLUSHING 3
|
||||||
|
#define BZ_M_FINISHING 4
|
||||||
|
|
||||||
|
#define BZ_S_OUTPUT 1
|
||||||
|
#define BZ_S_INPUT 2
|
||||||
|
|
||||||
|
#define BZ_N_RADIX 2
|
||||||
|
#define BZ_N_QSORT 12
|
||||||
|
#define BZ_N_SHELL 18
|
||||||
|
#define BZ_N_OVERSHOOT (BZ_N_RADIX + BZ_N_QSORT + BZ_N_SHELL + 2)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- Structure holding all the compression-side stuff. --*/
|
||||||
|
|
||||||
|
typedef
|
||||||
|
struct {
|
||||||
|
/* pointer back to the struct bz_stream */
|
||||||
|
bz_stream* strm;
|
||||||
|
|
||||||
|
/* mode this stream is in, and whether inputting */
|
||||||
|
/* or outputting data */
|
||||||
|
Int32 mode;
|
||||||
|
Int32 state;
|
||||||
|
|
||||||
|
/* remembers avail_in when flush/finish requested */
|
||||||
|
UInt32 avail_in_expect;
|
||||||
|
|
||||||
|
/* for doing the block sorting */
|
||||||
|
UInt32* arr1;
|
||||||
|
UInt32* arr2;
|
||||||
|
UInt32* ftab;
|
||||||
|
Int32 origPtr;
|
||||||
|
|
||||||
|
/* aliases for arr1 and arr2 */
|
||||||
|
UInt32* ptr;
|
||||||
|
UChar* block;
|
||||||
|
UInt16* mtfv;
|
||||||
|
UChar* zbits;
|
||||||
|
|
||||||
|
/* for deciding when to use the fallback sorting algorithm */
|
||||||
|
Int32 workFactor;
|
||||||
|
|
||||||
|
/* run-length-encoding of the input */
|
||||||
|
UInt32 state_in_ch;
|
||||||
|
Int32 state_in_len;
|
||||||
|
BZ_RAND_DECLS;
|
||||||
|
|
||||||
|
/* input and output limits and current posns */
|
||||||
|
Int32 nblock;
|
||||||
|
Int32 nblockMAX;
|
||||||
|
Int32 numZ;
|
||||||
|
Int32 state_out_pos;
|
||||||
|
|
||||||
|
/* map of bytes used in block */
|
||||||
|
Int32 nInUse;
|
||||||
|
Bool inUse[256];
|
||||||
|
UChar unseqToSeq[256];
|
||||||
|
|
||||||
|
/* the buffer for bit stream creation */
|
||||||
|
UInt32 bsBuff;
|
||||||
|
Int32 bsLive;
|
||||||
|
|
||||||
|
/* block and combined CRCs */
|
||||||
|
UInt32 blockCRC;
|
||||||
|
UInt32 combinedCRC;
|
||||||
|
|
||||||
|
/* misc administratium */
|
||||||
|
Int32 verbosity;
|
||||||
|
Int32 blockNo;
|
||||||
|
Int32 blockSize100k;
|
||||||
|
|
||||||
|
/* stuff for coding the MTF values */
|
||||||
|
Int32 nMTF;
|
||||||
|
Int32 mtfFreq [BZ_MAX_ALPHA_SIZE];
|
||||||
|
UChar selector [BZ_MAX_SELECTORS];
|
||||||
|
UChar selectorMtf[BZ_MAX_SELECTORS];
|
||||||
|
|
||||||
|
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||||
|
Int32 code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||||
|
Int32 rfreq [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||||
|
/* second dimension: only 3 needed; 4 makes index calculations faster */
|
||||||
|
UInt32 len_pack[BZ_MAX_ALPHA_SIZE][4];
|
||||||
|
|
||||||
|
}
|
||||||
|
EState;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- externs for compression. --*/
|
||||||
|
|
||||||
|
extern void
|
||||||
|
BZ2_blockSort ( EState* );
|
||||||
|
|
||||||
|
extern void
|
||||||
|
BZ2_compressBlock ( EState*, Bool );
|
||||||
|
|
||||||
|
extern void
|
||||||
|
BZ2_bsInitWrite ( EState* );
|
||||||
|
|
||||||
|
extern void
|
||||||
|
BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 );
|
||||||
|
|
||||||
|
extern void
|
||||||
|
BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 );
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- states for decompression. --*/
|
||||||
|
|
||||||
|
#define BZ_X_IDLE 1
|
||||||
|
#define BZ_X_OUTPUT 2
|
||||||
|
|
||||||
|
#define BZ_X_MAGIC_1 10
|
||||||
|
#define BZ_X_MAGIC_2 11
|
||||||
|
#define BZ_X_MAGIC_3 12
|
||||||
|
#define BZ_X_MAGIC_4 13
|
||||||
|
#define BZ_X_BLKHDR_1 14
|
||||||
|
#define BZ_X_BLKHDR_2 15
|
||||||
|
#define BZ_X_BLKHDR_3 16
|
||||||
|
#define BZ_X_BLKHDR_4 17
|
||||||
|
#define BZ_X_BLKHDR_5 18
|
||||||
|
#define BZ_X_BLKHDR_6 19
|
||||||
|
#define BZ_X_BCRC_1 20
|
||||||
|
#define BZ_X_BCRC_2 21
|
||||||
|
#define BZ_X_BCRC_3 22
|
||||||
|
#define BZ_X_BCRC_4 23
|
||||||
|
#define BZ_X_RANDBIT 24
|
||||||
|
#define BZ_X_ORIGPTR_1 25
|
||||||
|
#define BZ_X_ORIGPTR_2 26
|
||||||
|
#define BZ_X_ORIGPTR_3 27
|
||||||
|
#define BZ_X_MAPPING_1 28
|
||||||
|
#define BZ_X_MAPPING_2 29
|
||||||
|
#define BZ_X_SELECTOR_1 30
|
||||||
|
#define BZ_X_SELECTOR_2 31
|
||||||
|
#define BZ_X_SELECTOR_3 32
|
||||||
|
#define BZ_X_CODING_1 33
|
||||||
|
#define BZ_X_CODING_2 34
|
||||||
|
#define BZ_X_CODING_3 35
|
||||||
|
#define BZ_X_MTF_1 36
|
||||||
|
#define BZ_X_MTF_2 37
|
||||||
|
#define BZ_X_MTF_3 38
|
||||||
|
#define BZ_X_MTF_4 39
|
||||||
|
#define BZ_X_MTF_5 40
|
||||||
|
#define BZ_X_MTF_6 41
|
||||||
|
#define BZ_X_ENDHDR_2 42
|
||||||
|
#define BZ_X_ENDHDR_3 43
|
||||||
|
#define BZ_X_ENDHDR_4 44
|
||||||
|
#define BZ_X_ENDHDR_5 45
|
||||||
|
#define BZ_X_ENDHDR_6 46
|
||||||
|
#define BZ_X_CCRC_1 47
|
||||||
|
#define BZ_X_CCRC_2 48
|
||||||
|
#define BZ_X_CCRC_3 49
|
||||||
|
#define BZ_X_CCRC_4 50
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- Constants for the fast MTF decoder. --*/
|
||||||
|
|
||||||
|
#define MTFA_SIZE 4096
|
||||||
|
#define MTFL_SIZE 16
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- Structure holding all the decompression-side stuff. --*/
|
||||||
|
|
||||||
|
typedef
|
||||||
|
struct {
|
||||||
|
/* pointer back to the struct bz_stream */
|
||||||
|
bz_stream* strm;
|
||||||
|
|
||||||
|
/* state indicator for this stream */
|
||||||
|
Int32 state;
|
||||||
|
|
||||||
|
/* for doing the final run-length decoding */
|
||||||
|
UChar state_out_ch;
|
||||||
|
Int32 state_out_len;
|
||||||
|
Bool blockRandomised;
|
||||||
|
BZ_RAND_DECLS;
|
||||||
|
|
||||||
|
/* the buffer for bit stream reading */
|
||||||
|
UInt32 bsBuff;
|
||||||
|
Int32 bsLive;
|
||||||
|
|
||||||
|
/* misc administratium */
|
||||||
|
Int32 blockSize100k;
|
||||||
|
Bool smallDecompress;
|
||||||
|
Int32 currBlockNo;
|
||||||
|
Int32 verbosity;
|
||||||
|
|
||||||
|
/* for undoing the Burrows-Wheeler transform */
|
||||||
|
Int32 origPtr;
|
||||||
|
UInt32 tPos;
|
||||||
|
Int32 k0;
|
||||||
|
Int32 unzftab[256];
|
||||||
|
Int32 nblock_used;
|
||||||
|
Int32 cftab[257];
|
||||||
|
Int32 cftabCopy[257];
|
||||||
|
|
||||||
|
/* for undoing the Burrows-Wheeler transform (FAST) */
|
||||||
|
UInt32 *tt;
|
||||||
|
|
||||||
|
/* for undoing the Burrows-Wheeler transform (SMALL) */
|
||||||
|
UInt16 *ll16;
|
||||||
|
UChar *ll4;
|
||||||
|
|
||||||
|
/* stored and calculated CRCs */
|
||||||
|
UInt32 storedBlockCRC;
|
||||||
|
UInt32 storedCombinedCRC;
|
||||||
|
UInt32 calculatedBlockCRC;
|
||||||
|
UInt32 calculatedCombinedCRC;
|
||||||
|
|
||||||
|
/* map of bytes used in block */
|
||||||
|
Int32 nInUse;
|
||||||
|
Bool inUse[256];
|
||||||
|
Bool inUse16[16];
|
||||||
|
UChar seqToUnseq[256];
|
||||||
|
|
||||||
|
/* for decoding the MTF values */
|
||||||
|
UChar mtfa [MTFA_SIZE];
|
||||||
|
Int32 mtfbase[256 / MTFL_SIZE];
|
||||||
|
UChar selector [BZ_MAX_SELECTORS];
|
||||||
|
UChar selectorMtf[BZ_MAX_SELECTORS];
|
||||||
|
UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||||
|
|
||||||
|
Int32 limit [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||||
|
Int32 base [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||||
|
Int32 perm [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
|
||||||
|
Int32 minLens[BZ_N_GROUPS];
|
||||||
|
|
||||||
|
/* save area for scalars in the main decompress code */
|
||||||
|
Int32 save_i;
|
||||||
|
Int32 save_j;
|
||||||
|
Int32 save_t;
|
||||||
|
Int32 save_alphaSize;
|
||||||
|
Int32 save_nGroups;
|
||||||
|
Int32 save_nSelectors;
|
||||||
|
Int32 save_EOB;
|
||||||
|
Int32 save_groupNo;
|
||||||
|
Int32 save_groupPos;
|
||||||
|
Int32 save_nextSym;
|
||||||
|
Int32 save_nblockMAX;
|
||||||
|
Int32 save_nblock;
|
||||||
|
Int32 save_es;
|
||||||
|
Int32 save_N;
|
||||||
|
Int32 save_curr;
|
||||||
|
Int32 save_zt;
|
||||||
|
Int32 save_zn;
|
||||||
|
Int32 save_zvec;
|
||||||
|
Int32 save_zj;
|
||||||
|
Int32 save_gSel;
|
||||||
|
Int32 save_gMinlen;
|
||||||
|
Int32* save_gLimit;
|
||||||
|
Int32* save_gBase;
|
||||||
|
Int32* save_gPerm;
|
||||||
|
|
||||||
|
}
|
||||||
|
DState;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/*-- Macros for decompression. --*/
|
||||||
|
|
||||||
|
#define BZ_GET_FAST(cccc) \
|
||||||
|
/* c_tPos is unsigned, hence test < 0 is pointless. */ \
|
||||||
|
if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \
|
||||||
|
s->tPos = s->tt[s->tPos]; \
|
||||||
|
cccc = (UChar)(s->tPos & 0xff); \
|
||||||
|
s->tPos >>= 8;
|
||||||
|
|
||||||
|
#define BZ_GET_FAST_C(cccc) \
|
||||||
|
/* c_tPos is unsigned, hence test < 0 is pointless. */ \
|
||||||
|
if (c_tPos >= (UInt32)100000 * (UInt32)ro_blockSize100k) return True; \
|
||||||
|
c_tPos = c_tt[c_tPos]; \
|
||||||
|
cccc = (UChar)(c_tPos & 0xff); \
|
||||||
|
c_tPos >>= 8;
|
||||||
|
|
||||||
|
#define SET_LL4(i,n) \
|
||||||
|
{ if (((i) & 0x1) == 0) \
|
||||||
|
s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0xf0) | (n); else \
|
||||||
|
s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0x0f) | ((n) << 4); \
|
||||||
|
}
|
||||||
|
|
||||||
|
#define GET_LL4(i) \
|
||||||
|
((((UInt32)(s->ll4[(i) >> 1])) >> (((i) << 2) & 0x4)) & 0xF)
|
||||||
|
|
||||||
|
#define SET_LL(i,n) \
|
||||||
|
{ s->ll16[i] = (UInt16)(n & 0x0000ffff); \
|
||||||
|
SET_LL4(i, n >> 16); \
|
||||||
|
}
|
||||||
|
|
||||||
|
#define GET_LL(i) \
|
||||||
|
(((UInt32)s->ll16[i]) | (GET_LL4(i) << 16))
|
||||||
|
|
||||||
|
#define BZ_GET_SMALL(cccc) \
|
||||||
|
/* c_tPos is unsigned, hence test < 0 is pointless. */ \
|
||||||
|
if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \
|
||||||
|
cccc = BZ2_indexIntoF ( s->tPos, s->cftab ); \
|
||||||
|
s->tPos = GET_LL(s->tPos);
|
||||||
|
|
||||||
|
|
||||||
|
/*-- externs for decompression. --*/
|
||||||
|
|
||||||
|
extern Int32
|
||||||
|
BZ2_indexIntoF ( Int32, Int32* );
|
||||||
|
|
||||||
|
extern Int32
|
||||||
|
BZ2_decompress ( DState* );
|
||||||
|
|
||||||
|
extern void
|
||||||
|
BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*,
|
||||||
|
Int32, Int32, Int32 );
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*-- BZ_NO_STDIO seems to make NULL disappear on some platforms. --*/
|
||||||
|
|
||||||
|
#ifdef BZ_NO_STDIO
|
||||||
|
#ifndef NULL
|
||||||
|
#define NULL 0
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*-------------------------------------------------------------*/
|
||||||
|
/*--- end bzlib_private.h ---*/
|
||||||
|
/*-------------------------------------------------------------*/
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
/* bzip2 source intentionally removed on this fork.
|
||||||
|
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||||
|
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
/* bzip2 source intentionally removed on this fork.
|
||||||
|
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||||
|
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
/* bzip2 source intentionally removed on this fork.
|
||||||
|
* See src/Compression/BZ2.cpp — the RNS::Compression API is a no-op shim
|
||||||
|
* because bz2 is too memory-heavy for MCU-class targets. */
|
||||||
@@ -31,13 +31,10 @@ namespace RNS { namespace Cryptography {
|
|||||||
//DEBUGF("PKCS7::pad: len: %zu", len);
|
//DEBUGF("PKCS7::pad: len: %zu", len);
|
||||||
size_t padlen = bs - (len % bs);
|
size_t padlen = bs - (len % bs);
|
||||||
//DEBUGF("PKCS7::pad: pad len: %zu", padlen);
|
//DEBUGF("PKCS7::pad: pad len: %zu", padlen);
|
||||||
// create zero-filled byte padding array of size padlen
|
// PKCS7: fill ALL padding bytes with padlen value (RFC 5652 §6.3)
|
||||||
//p v = bytes([padlen])
|
//p v = bytes([padlen])
|
||||||
//uint8_t pad[padlen] = {0};
|
|
||||||
uint8_t pad[padlen];
|
uint8_t pad[padlen];
|
||||||
memset(pad, 0, padlen);
|
memset(pad, (uint8_t)padlen, padlen);
|
||||||
// set last byte of padding array to size of padding
|
|
||||||
pad[padlen-1] = (uint8_t)padlen;
|
|
||||||
// concatenate data with padding
|
// concatenate data with padding
|
||||||
//p return data+v*padlen
|
//p return data+v*padlen
|
||||||
data.append(pad, padlen);
|
data.append(pad, padlen);
|
||||||
|
|||||||
+62
-13
@@ -101,15 +101,23 @@ Destination::Destination(const Identity& identity, const Type::Destination::dire
|
|||||||
/*static*/ Bytes Destination::hash(const Identity& identity, const char* app_name, const char* aspects) {
|
/*static*/ Bytes Destination::hash(const Identity& identity, const char* app_name, const char* aspects) {
|
||||||
//p name_hash = Identity::full_hash(Destination.expand_name(None, app_name, *aspects).encode("utf-8"))[:(RNS.Identity.NAME_HASH_LENGTH//8)]
|
//p name_hash = Identity::full_hash(Destination.expand_name(None, app_name, *aspects).encode("utf-8"))[:(RNS.Identity.NAME_HASH_LENGTH//8)]
|
||||||
//p addr_hash_material = name_hash
|
//p addr_hash_material = name_hash
|
||||||
|
std::string expanded = expand_name({Type::NONE}, app_name, aspects);
|
||||||
Bytes addr_hash_material = name_hash(app_name, aspects);
|
Bytes addr_hash_material = name_hash(app_name, aspects);
|
||||||
|
TRACEF("[DIAG] Dest::hash: expanded='%s' name_hash=%s",
|
||||||
|
expanded.c_str(), addr_hash_material.toHex().c_str());
|
||||||
if (identity) {
|
if (identity) {
|
||||||
|
TRACEF("[DIAG] Dest::hash: identity_hash=%s", identity.hash().toHex().c_str());
|
||||||
addr_hash_material << identity.hash();
|
addr_hash_material << identity.hash();
|
||||||
}
|
}
|
||||||
|
TRACEF("[DIAG] Dest::hash: material(%d)=%s",
|
||||||
|
(int)addr_hash_material.size(), addr_hash_material.toHex().c_str());
|
||||||
|
|
||||||
//p return RNS.Identity.full_hash(addr_hash_material)[:RNS.Reticulum.TRUNCATED_HASHLENGTH//8]
|
//p return RNS.Identity.full_hash(addr_hash_material)[:RNS.Reticulum.TRUNCATED_HASHLENGTH//8]
|
||||||
// CBA TODO valid alternative?
|
// CBA TODO valid alternative?
|
||||||
//return Identity::full_hash(addr_hash_material).left(Type::Reticulum::TRUNCATED_HASHLENGTH/8);
|
//return Identity::full_hash(addr_hash_material).left(Type::Reticulum::TRUNCATED_HASHLENGTH/8);
|
||||||
return Identity::truncated_hash(addr_hash_material);
|
Bytes result = Identity::truncated_hash(addr_hash_material);
|
||||||
|
TRACEF("[DIAG] Dest::hash: result=%s", result.toHex().c_str());
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -253,9 +261,32 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
Bytes destination_hash = _object->_hash;
|
Bytes destination_hash = _object->_hash;
|
||||||
//p random_hash = Identity::get_random_hash()[0:5] << int(time.time()).to_bytes(5, "big")
|
//p random_hash = Identity::get_random_hash()[0:5] + int(time.time()).to_bytes(5, "big")
|
||||||
// CBA TODO add in time to random hash
|
// 5 random bytes + 5 big-endian epoch timestamp bytes (matches Python reference)
|
||||||
Bytes random_hash = Cryptography::random(Type::Identity::RANDOM_HASH_LENGTH/8);
|
// CRITICAL: Must use Unix epoch (like Python's time.time()), NOT OS::time()
|
||||||
|
// which returns uptime on Arduino. Python Transport compares these timestamps
|
||||||
|
// for announce freshness — uptime-based values cause re-announces to be
|
||||||
|
// rejected by nodes that have cached a previous epoch-based timestamp.
|
||||||
|
Bytes random_part = Cryptography::random(5);
|
||||||
|
#ifdef ARDUINO
|
||||||
|
// On ESP32, time(nullptr) returns Unix epoch after NTP sync,
|
||||||
|
// or ~0 before sync. Either is better than millis()-based uptime.
|
||||||
|
uint64_t ts = (uint64_t)::time(nullptr);
|
||||||
|
if (ts < 1700000000) {
|
||||||
|
// NTP not yet synced — fall back to OS::time() (uptime seconds).
|
||||||
|
// Not ideal, but the announce will still work for first-time paths.
|
||||||
|
ts = (uint64_t)OS::time();
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
uint64_t ts = (uint64_t)OS::time();
|
||||||
|
#endif
|
||||||
|
uint8_t time_bytes[5];
|
||||||
|
time_bytes[0] = (ts >> 32) & 0xFF;
|
||||||
|
time_bytes[1] = (ts >> 24) & 0xFF;
|
||||||
|
time_bytes[2] = (ts >> 16) & 0xFF;
|
||||||
|
time_bytes[3] = (ts >> 8) & 0xFF;
|
||||||
|
time_bytes[4] = ts & 0xFF;
|
||||||
|
Bytes random_hash = random_part + Bytes(time_bytes, 5);
|
||||||
|
|
||||||
Bytes new_app_data(app_data);
|
Bytes new_app_data(app_data);
|
||||||
if (new_app_data.empty() && !_object->_default_app_data.empty()) {
|
if (new_app_data.empty() && !_object->_default_app_data.empty()) {
|
||||||
@@ -263,26 +294,27 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
|
|||||||
}
|
}
|
||||||
|
|
||||||
Bytes signed_data;
|
Bytes signed_data;
|
||||||
//TRACEF("Destination::announce: hash: %s", _object->_hash.toHex().c_str());
|
TRACEF("[ANN-DIAG] dest_hash: %s", _object->_hash.toHex().c_str());
|
||||||
//TRACEF("Destination::announce: public key: %s", _object->_identity.get_public_key().toHex().c_str());
|
TRACEF("[ANN-DIAG] identity: %s", _object->_identity.hash().toHex().c_str());
|
||||||
//TRACEF("Destination::announce: name hash: %s", _object->_name_hash.toHex().c_str());
|
TRACEF("[ANN-DIAG] pub_key(%d): %s", (int)_object->_identity.get_public_key().size(), _object->_identity.get_public_key().toHex().c_str());
|
||||||
//TRACEF("Destination::announce: random hash: %s", random_hash.toHex().c_str());
|
TRACEF("[ANN-DIAG] name_hash: %s", _object->_name_hash.toHex().c_str());
|
||||||
//TRACEF("Destination::announce: app data: %s", new_app_data.toHex().c_str());
|
TRACEF("[ANN-DIAG] random_hash: %s", random_hash.toHex().c_str());
|
||||||
//TRACEF("Destination::announce: app data text:%s", new_app_data.toString().c_str());
|
TRACEF("[ANN-DIAG] app_data(%d):%s", (int)new_app_data.size(), new_app_data.toHex().c_str());
|
||||||
signed_data << _object->_hash << _object->_identity.get_public_key() << _object->_name_hash << random_hash;
|
signed_data << _object->_hash << _object->_identity.get_public_key() << _object->_name_hash << random_hash;
|
||||||
if (new_app_data) {
|
if (new_app_data) {
|
||||||
signed_data << new_app_data;
|
signed_data << new_app_data;
|
||||||
}
|
}
|
||||||
//TRACEF("Destination::announce: signed data: %s", signed_data.toHex().c_str());
|
TRACEF("[ANN-DIAG] signed_data(%d): %s", (int)signed_data.size(), signed_data.toHex().c_str());
|
||||||
|
|
||||||
Bytes signature(_object->_identity.sign(signed_data));
|
Bytes signature(_object->_identity.sign(signed_data));
|
||||||
//TRACEF("Destination::announce: signature: %s", signature.toHex().c_str());
|
TRACEF("[ANN-DIAG] signature: %s", signature.toHex().c_str());
|
||||||
|
|
||||||
announce_data << _object->_identity.get_public_key() << _object->_name_hash << random_hash << signature;
|
announce_data << _object->_identity.get_public_key() << _object->_name_hash << random_hash << signature;
|
||||||
|
|
||||||
if (new_app_data) {
|
if (new_app_data) {
|
||||||
announce_data << new_app_data;
|
announce_data << new_app_data;
|
||||||
}
|
}
|
||||||
|
TRACEF("[ANN-DIAG] announce_data(%d): %s", (int)announce_data.size(), announce_data.toHex().c_str());
|
||||||
|
|
||||||
// CBA ACCUMULATES
|
// CBA ACCUMULATES
|
||||||
try {
|
try {
|
||||||
@@ -374,25 +406,38 @@ bool Destination::deregister_request_handler(const Bytes& path) {
|
|||||||
|
|
||||||
void Destination::receive(const Packet& packet) {
|
void Destination::receive(const Packet& packet) {
|
||||||
assert(_object);
|
assert(_object);
|
||||||
|
Serial.printf("[DEST-RX] receive: pkt_type=%d data=%d bytes dest=%s\n",
|
||||||
|
(int)packet.packet_type(), (int)packet.data().size(),
|
||||||
|
packet.destination_hash().toHex().substr(0, 12).c_str());
|
||||||
if (packet.packet_type() == Type::Packet::LINKREQUEST) {
|
if (packet.packet_type() == Type::Packet::LINKREQUEST) {
|
||||||
|
Serial.println("[DEST-RX] → LINKREQUEST, entering incoming_link_request");
|
||||||
Bytes plaintext(packet.data());
|
Bytes plaintext(packet.data());
|
||||||
incoming_link_request(plaintext, packet);
|
incoming_link_request(plaintext, packet);
|
||||||
|
Serial.println("[DEST-RX] ← LINKREQUEST done");
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
// CBA TODO Why isn't the Packet decrypting itself?
|
// CBA TODO Why isn't the Packet decrypting itself?
|
||||||
|
Serial.printf("[DEST-RX] → decrypting %d bytes...\n", (int)packet.data().size());
|
||||||
Bytes plaintext(decrypt(packet.data()));
|
Bytes plaintext(decrypt(packet.data()));
|
||||||
//TRACEF("Destination::receive: decrypted data: %s", plaintext.toHex().c_str());
|
|
||||||
if (plaintext) {
|
if (plaintext) {
|
||||||
|
Serial.printf("[DEST-RX] decrypt OK, %d bytes plaintext\n", (int)plaintext.size());
|
||||||
if (packet.packet_type() == Type::Packet::DATA) {
|
if (packet.packet_type() == Type::Packet::DATA) {
|
||||||
if (_object->_callbacks._packet) {
|
if (_object->_callbacks._packet) {
|
||||||
try {
|
try {
|
||||||
|
Serial.println("[DEST-RX] → calling packet callback");
|
||||||
_object->_callbacks._packet(plaintext, packet);
|
_object->_callbacks._packet(plaintext, packet);
|
||||||
|
Serial.println("[DEST-RX] ← packet callback done");
|
||||||
}
|
}
|
||||||
catch (std::exception& e) {
|
catch (std::exception& e) {
|
||||||
DEBUGF("Error while executing receive callback from %s. The contained exception was: %s", toString().c_str(), e.what());
|
DEBUGF("Error while executing receive callback from %s. The contained exception was: %s", toString().c_str(), e.what());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Serial.println("[DEST-RX] → proving packet");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Serial.printf("[DEST] DECRYPT FAILED for %d byte packet to %s\n",
|
||||||
|
(int)packet.data().size(), packet.destination_hash().toHex().substr(0, 16).c_str());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -431,6 +476,10 @@ Encrypts information for ``RNS.Destination.SINGLE`` or ``RNS.Destination.GROUP``
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (_object->_type == SINGLE && _object->_identity) {
|
if (_object->_type == SINGLE && _object->_identity) {
|
||||||
|
// TODO: Re-enable ratchet encryption once fully compatible with Python reference.
|
||||||
|
// Currently causes "Decryption with ratchets failed" on receiving Python clients.
|
||||||
|
//Bytes ratchet = Identity::get_ratchet(_object->_hash);
|
||||||
|
//return _object->_identity.encrypt(data, ratchet);
|
||||||
return _object->_identity.encrypt(data);
|
return _object->_identity.encrypt(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+12
-2
@@ -8,12 +8,19 @@
|
|||||||
#include <list>
|
#include <list>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
|
#include <functional>
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
|
|
||||||
namespace RNS {
|
namespace RNS {
|
||||||
|
|
||||||
class FileSystemImpl {
|
class FileSystemImpl {
|
||||||
|
|
||||||
|
public:
|
||||||
|
struct Callbacks {
|
||||||
|
//using DirectoryListing = void(*)(const char* file_name);
|
||||||
|
using DirectoryListing = std::function<void(const char*)>;
|
||||||
|
};
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
FileSystemImpl() { MEMF("FileSystem::FileSystemImpl object created, this: 0x%X", this); }
|
FileSystemImpl() { MEMF("FileSystem::FileSystemImpl object created, this: 0x%X", this); }
|
||||||
public:
|
public:
|
||||||
@@ -31,7 +38,7 @@ namespace RNS {
|
|||||||
virtual bool directory_exists(const char* directory_path) = 0;
|
virtual bool directory_exists(const char* directory_path) = 0;
|
||||||
virtual bool create_directory(const char* directory_path) = 0;
|
virtual bool create_directory(const char* directory_path) = 0;
|
||||||
virtual bool remove_directory(const char* directory_path) = 0;
|
virtual bool remove_directory(const char* directory_path) = 0;
|
||||||
virtual std::list<std::string> list_directory(const char* directory_path) = 0;
|
virtual std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr) = 0;
|
||||||
virtual size_t storage_size() = 0;
|
virtual size_t storage_size() = 0;
|
||||||
virtual size_t storage_available() = 0;
|
virtual size_t storage_available() = 0;
|
||||||
|
|
||||||
@@ -40,6 +47,9 @@ namespace RNS {
|
|||||||
|
|
||||||
class FileSystem {
|
class FileSystem {
|
||||||
|
|
||||||
|
public:
|
||||||
|
using Callbacks = FileSystemImpl::Callbacks;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
FileSystem(Type::NoneConstructor none) {
|
FileSystem(Type::NoneConstructor none) {
|
||||||
MEMF("FileSystem NONE object created, this: 0x%X, impl: 0x%X", this, _impl.get());
|
MEMF("FileSystem NONE object created, this: 0x%X, impl: 0x%X", this, _impl.get());
|
||||||
@@ -103,7 +113,7 @@ namespace RNS {
|
|||||||
inline bool directory_exists(const char* directory_path) { assert(_impl); return _impl->directory_exists(directory_path); }
|
inline bool directory_exists(const char* directory_path) { assert(_impl); return _impl->directory_exists(directory_path); }
|
||||||
inline bool create_directory(const char* directory_path) { assert(_impl); return _impl->create_directory(directory_path); }
|
inline bool create_directory(const char* directory_path) { assert(_impl); return _impl->create_directory(directory_path); }
|
||||||
inline bool remove_directory(const char* directory_path) { assert(_impl); return _impl->remove_directory(directory_path); }
|
inline bool remove_directory(const char* directory_path) { assert(_impl); return _impl->remove_directory(directory_path); }
|
||||||
inline std::list<std::string> list_directory(const char* directory_path) { assert(_impl); return _impl->list_directory(directory_path); }
|
inline std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr) { assert(_impl); return _impl->list_directory(directory_path, callback); }
|
||||||
inline size_t storage_size() { assert(_impl); return _impl->storage_size(); }
|
inline size_t storage_size() { assert(_impl); return _impl->storage_size(); }
|
||||||
inline size_t storage_available() { assert(_impl); return _impl->storage_available(); }
|
inline size_t storage_available() { assert(_impl); return _impl->storage_available(); }
|
||||||
|
|
||||||
|
|||||||
+264
-82
@@ -23,11 +23,13 @@ using namespace RNS::Utilities;
|
|||||||
#define RNS_KNOWN_DESTINATIONS_MAX 100
|
#define RNS_KNOWN_DESTINATIONS_MAX 100
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
/*static*/ std::map<Bytes, Identity::IdentityEntry> Identity::_known_destinations;
|
/*static*/ Identity::IdentityTable Identity::_known_destinations;
|
||||||
/*static*/ bool Identity::_saving_known_destinations = false;
|
/*static*/ bool Identity::_saving_known_destinations = false;
|
||||||
// CBA
|
// CBA
|
||||||
// CBA ACCUMULATES
|
// CBA ACCUMULATES
|
||||||
/*static*/ uint16_t Identity::_known_destinations_maxsize = RNS_KNOWN_DESTINATIONS_MAX;
|
/*static*/ uint16_t Identity::_known_destinations_maxsize = RNS_KNOWN_DESTINATIONS_MAX;
|
||||||
|
/*static*/ bool Identity::_known_destinations_dirty = false;
|
||||||
|
/*static*/ Identity::RatchetTable Identity::_known_ratchets;
|
||||||
|
|
||||||
Identity::Identity(bool create_keys /*= true*/) : _object(new Object()) {
|
Identity::Identity(bool create_keys /*= true*/) : _object(new Object()) {
|
||||||
if (create_keys) {
|
if (create_keys) {
|
||||||
@@ -200,9 +202,11 @@ Can be used to load previously created and saved identities into Reticulum.
|
|||||||
//p _known_destinations[destination_hash] = {OS::time(), packet_hash, public_key, app_data};
|
//p _known_destinations[destination_hash] = {OS::time(), packet_hash, public_key, app_data};
|
||||||
// CBA ACCUMULATES
|
// CBA ACCUMULATES
|
||||||
try {
|
try {
|
||||||
_known_destinations.insert({destination_hash, {OS::time(), packet_hash, public_key, app_data}});
|
// Use insert_or_assign so the timestamp is always refreshed.
|
||||||
// CBA IMMEDIATE CULL
|
_known_destinations.insert_or_assign(destination_hash, IdentityEntry{OS::time(), packet_hash, public_key, app_data});
|
||||||
cull_known_destinations();
|
// Defer cull to periodic jobs instead of per-announce to avoid
|
||||||
|
// O(n log n) sorting on every inbound packet.
|
||||||
|
_known_destinations_dirty = true;
|
||||||
}
|
}
|
||||||
catch (const std::bad_alloc&) {
|
catch (const std::bad_alloc&) {
|
||||||
ERRORF("remember: bad_alloc - OUT OF MEMORY, identity not stored for %s", destination_hash.toHex().c_str());
|
ERRORF("remember: bad_alloc - OUT OF MEMORY, identity not stored for %s", destination_hash.toHex().c_str());
|
||||||
@@ -265,13 +269,18 @@ Recall last heard app_data for a destination hash.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*static*/ bool Identity::save_known_destinations() {
|
/*
|
||||||
// TODO: Improve the storage method so we don't have to
|
Binary format for known_destinations persistence:
|
||||||
// deserialize and serialize the entire table on every
|
[uint16_t entry_count]
|
||||||
// save, but the only changes. It might be possible to
|
For each entry:
|
||||||
// simply overwrite on exit now that every local client
|
[uint16_t dest_hash_len][dest_hash bytes]
|
||||||
// disconnect triggers a data persist.
|
[double timestamp]
|
||||||
|
[uint16_t packet_hash_len][packet_hash bytes]
|
||||||
|
[uint16_t public_key_len][public_key bytes]
|
||||||
|
[uint16_t app_data_len][app_data bytes]
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*static*/ bool Identity::save_known_destinations() {
|
||||||
bool success = false;
|
bool success = false;
|
||||||
try {
|
try {
|
||||||
if (_saving_known_destinations) {
|
if (_saving_known_destinations) {
|
||||||
@@ -290,39 +299,47 @@ Recall last heard app_data for a destination hash.
|
|||||||
_saving_known_destinations = true;
|
_saving_known_destinations = true;
|
||||||
double save_start = OS::time();
|
double save_start = OS::time();
|
||||||
|
|
||||||
std::map<Bytes, IdentityEntry> storage_known_destinations;
|
if (_known_destinations.empty()) {
|
||||||
// TODO
|
_saving_known_destinations = false;
|
||||||
/*
|
return true;
|
||||||
if os.path.isfile(RNS.Reticulum.storagepath+"/known_destinations"):
|
|
||||||
try:
|
|
||||||
file = open(RNS.Reticulum.storagepath+"/known_destinations","rb")
|
|
||||||
storage_known_destinations = umsgpack.load(file)
|
|
||||||
file.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
*/
|
|
||||||
|
|
||||||
for (auto& [destination_hash, identity_entry] : storage_known_destinations) {
|
|
||||||
if (_known_destinations.find(destination_hash) == _known_destinations.end()) {
|
|
||||||
//_known_destinations[destination_hash] = storage_known_destinations[destination_hash];
|
|
||||||
//_known_destinations[destination_hash] = identity_entry;
|
|
||||||
// CBA ACCUMULATES
|
|
||||||
_known_destinations.insert({destination_hash, identity_entry});
|
|
||||||
// CBA IMMEDIATE CULL
|
|
||||||
cull_known_destinations();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO
|
// Serialize to binary buffer
|
||||||
/*
|
Bytes buf(1024);
|
||||||
DEBUGF("Saving %zu known destinations to storage...", _known_destinations.size());
|
uint16_t count = (uint16_t)_known_destinations.size();
|
||||||
file = open(RNS.Reticulum.storagepath+"/known_destinations","wb")
|
buf.append((const uint8_t*)&count, sizeof(count));
|
||||||
umsgpack.dump(Identity.known_destinations, file)
|
|
||||||
file.close()
|
|
||||||
DEBUGF("Saved known destinations to storage in %.3f seconds", OS::round(OS::time() - save_start, 3));
|
|
||||||
*/
|
|
||||||
|
|
||||||
success = true;
|
for (const auto& [dest_hash, entry] : _known_destinations) {
|
||||||
|
uint16_t len;
|
||||||
|
|
||||||
|
len = (uint16_t)dest_hash.size();
|
||||||
|
buf.append((const uint8_t*)&len, sizeof(len));
|
||||||
|
buf.append(dest_hash.data(), dest_hash.size());
|
||||||
|
|
||||||
|
buf.append((const uint8_t*)&entry._timestamp, sizeof(entry._timestamp));
|
||||||
|
|
||||||
|
len = (uint16_t)entry._packet_hash.size();
|
||||||
|
buf.append((const uint8_t*)&len, sizeof(len));
|
||||||
|
if (len > 0) buf.append(entry._packet_hash.data(), entry._packet_hash.size());
|
||||||
|
|
||||||
|
len = (uint16_t)entry._public_key.size();
|
||||||
|
buf.append((const uint8_t*)&len, sizeof(len));
|
||||||
|
if (len > 0) buf.append(entry._public_key.data(), entry._public_key.size());
|
||||||
|
|
||||||
|
len = (uint16_t)entry._app_data.size();
|
||||||
|
buf.append((const uint8_t*)&len, sizeof(len));
|
||||||
|
if (len > 0) buf.append(entry._app_data.data(), entry._app_data.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
char filepath[Type::Reticulum::FILEPATH_MAXSIZE];
|
||||||
|
snprintf(filepath, Type::Reticulum::FILEPATH_MAXSIZE, "%s/known_destinations", Reticulum::_storagepath);
|
||||||
|
|
||||||
|
if (OS::write_file(filepath, buf) == buf.size()) {
|
||||||
|
DEBUGF("Saved %zu known destinations to storage in %.3f seconds", _known_destinations.size(), OS::round(OS::time() - save_start, 3));
|
||||||
|
success = true;
|
||||||
|
} else {
|
||||||
|
ERROR("Failed to write known destinations to storage");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (std::exception& e) {
|
catch (std::exception& e) {
|
||||||
ERRORF("Error while saving known destinations to disk, the contained exception was: %s", e.what());
|
ERRORF("Error while saving known destinations to disk, the contained exception was: %s", e.what());
|
||||||
@@ -334,26 +351,114 @@ Recall last heard app_data for a destination hash.
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*static*/ void Identity::load_known_destinations() {
|
/*static*/ void Identity::load_known_destinations() {
|
||||||
// TODO
|
char filepath[Type::Reticulum::FILEPATH_MAXSIZE];
|
||||||
/*
|
snprintf(filepath, Type::Reticulum::FILEPATH_MAXSIZE, "%s/known_destinations", Reticulum::_storagepath);
|
||||||
if os.path.isfile(RNS.Reticulum.storagepath+"/known_destinations"):
|
|
||||||
try:
|
|
||||||
file = open(RNS.Reticulum.storagepath+"/known_destinations","rb")
|
|
||||||
loaded_known_destinations = umsgpack.load(file)
|
|
||||||
file.close()
|
|
||||||
|
|
||||||
Identity.known_destinations = {}
|
if (!OS::file_exists(filepath)) {
|
||||||
for known_destination in loaded_known_destinations:
|
VERBOSE("Destinations file does not exist, no known destinations loaded");
|
||||||
if len(known_destination) == RNS.Reticulum.TRUNCATED_HASHLENGTH//8:
|
return;
|
||||||
Identity.known_destinations[known_destination] = loaded_known_destinations[known_destination]
|
}
|
||||||
|
|
||||||
RNS.log("Loaded "+str(len(Identity.known_destinations))+" known destination from storage", RNS.LOG_VERBOSE)
|
try {
|
||||||
except:
|
Bytes buf;
|
||||||
RNS.log("Error loading known destinations from disk, file will be recreated on exit", RNS.LOG_ERROR)
|
if (OS::read_file(filepath, buf) == 0) {
|
||||||
else:
|
ERROR("Failed to read known destinations file");
|
||||||
RNS.log("Destinations file does not exist, no known destinations loaded", RNS.LOG_VERBOSE)
|
return;
|
||||||
*/
|
}
|
||||||
|
|
||||||
|
const uint8_t* ptr = buf.data();
|
||||||
|
size_t remaining = buf.size();
|
||||||
|
|
||||||
|
if (remaining < sizeof(uint16_t)) return;
|
||||||
|
uint16_t count;
|
||||||
|
memcpy(&count, ptr, sizeof(count));
|
||||||
|
ptr += sizeof(count);
|
||||||
|
remaining -= sizeof(count);
|
||||||
|
|
||||||
|
size_t loaded = 0;
|
||||||
|
for (uint16_t i = 0; i < count && remaining > 0; i++) {
|
||||||
|
uint16_t len;
|
||||||
|
|
||||||
|
// dest_hash
|
||||||
|
if (remaining < sizeof(len)) break;
|
||||||
|
memcpy(&len, ptr, sizeof(len)); ptr += sizeof(len); remaining -= sizeof(len);
|
||||||
|
if (remaining < len || len != Type::Reticulum::TRUNCATED_HASHLENGTH/8) break;
|
||||||
|
Bytes dest_hash(ptr, len); ptr += len; remaining -= len;
|
||||||
|
|
||||||
|
// timestamp
|
||||||
|
if (remaining < sizeof(double)) break;
|
||||||
|
double timestamp;
|
||||||
|
memcpy(×tamp, ptr, sizeof(timestamp)); ptr += sizeof(timestamp); remaining -= sizeof(timestamp);
|
||||||
|
|
||||||
|
// packet_hash
|
||||||
|
if (remaining < sizeof(len)) break;
|
||||||
|
memcpy(&len, ptr, sizeof(len)); ptr += sizeof(len); remaining -= sizeof(len);
|
||||||
|
if (remaining < len) break;
|
||||||
|
Bytes packet_hash(ptr, len); ptr += len; remaining -= len;
|
||||||
|
|
||||||
|
// public_key
|
||||||
|
if (remaining < sizeof(len)) break;
|
||||||
|
memcpy(&len, ptr, sizeof(len)); ptr += sizeof(len); remaining -= sizeof(len);
|
||||||
|
if (remaining < len) break;
|
||||||
|
Bytes public_key(ptr, len); ptr += len; remaining -= len;
|
||||||
|
|
||||||
|
// app_data
|
||||||
|
if (remaining < sizeof(len)) break;
|
||||||
|
memcpy(&len, ptr, sizeof(len)); ptr += sizeof(len); remaining -= sizeof(len);
|
||||||
|
if (remaining < len) break;
|
||||||
|
Bytes app_data(ptr, len); ptr += len; remaining -= len;
|
||||||
|
|
||||||
|
if (_known_destinations.find(dest_hash) == _known_destinations.end()) {
|
||||||
|
try {
|
||||||
|
_known_destinations.insert({dest_hash, {timestamp, packet_hash, public_key, app_data}});
|
||||||
|
loaded++;
|
||||||
|
}
|
||||||
|
catch (const std::bad_alloc&) {
|
||||||
|
ERROR("load_known_destinations: out of memory, stopping load");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize timestamps to current boot epoch.
|
||||||
|
// OS::time() on Arduino returns seconds since boot, not epoch time.
|
||||||
|
// Persisted entries carry timestamps from the previous boot session
|
||||||
|
// (e.g., 5000.0 = device had been up 5000s when saved). On a fresh
|
||||||
|
// boot at uptime 30s, a new announce would get timestamp 30.0 — which
|
||||||
|
// the LRU cull considers "older" than the persisted 5000.0, causing
|
||||||
|
// the NEW entry to be culled immediately. Fix: remap all loaded
|
||||||
|
// timestamps into [1.0, now-1] preserving their relative order, so
|
||||||
|
// any fresh announce at OS::time() is always "newest".
|
||||||
|
if (loaded > 0) {
|
||||||
|
double now = OS::time();
|
||||||
|
double max_ts = 0, min_ts = 1e18;
|
||||||
|
for (const auto& [key, entry] : _known_destinations) {
|
||||||
|
if (entry._timestamp > max_ts) max_ts = entry._timestamp;
|
||||||
|
if (entry._timestamp < min_ts) min_ts = entry._timestamp;
|
||||||
|
}
|
||||||
|
double range = max_ts - min_ts;
|
||||||
|
// Map [min_ts, max_ts] → [1.0, now - 1.0]
|
||||||
|
// All loaded entries end up before "now", preserving relative order
|
||||||
|
double target_max = (now > 2.0) ? now - 1.0 : 1.0;
|
||||||
|
double target_min = 1.0;
|
||||||
|
for (auto& [key, entry] : _known_destinations) {
|
||||||
|
if (range > 0.001) {
|
||||||
|
double normalized = (entry._timestamp - min_ts) / range;
|
||||||
|
entry._timestamp = target_min + normalized * (target_max - target_min);
|
||||||
|
} else {
|
||||||
|
entry._timestamp = target_min;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
VERBOSEF("Normalized %zu destination timestamps: [%.1f,%.1f] -> [%.1f,%.1f]",
|
||||||
|
loaded, min_ts, max_ts, target_min, target_max);
|
||||||
|
}
|
||||||
|
|
||||||
|
cull_known_destinations();
|
||||||
|
VERBOSEF("Loaded %zu known destinations from storage", loaded);
|
||||||
|
}
|
||||||
|
catch (std::exception& e) {
|
||||||
|
ERRORF("Error loading known destinations from disk, file will be recreated on exit: %s", e.what());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/*static*/ void Identity::cull_known_destinations() {
|
/*static*/ void Identity::cull_known_destinations() {
|
||||||
@@ -407,36 +512,72 @@ Recall last heard app_data for a destination hash.
|
|||||||
try {
|
try {
|
||||||
if (packet.packet_type() == Type::Packet::ANNOUNCE) {
|
if (packet.packet_type() == Type::Packet::ANNOUNCE) {
|
||||||
Bytes destination_hash = packet.destination_hash();
|
Bytes destination_hash = packet.destination_hash();
|
||||||
//TRACEF("Identity::validate_announce: destination_hash: %s", packet.destination_hash().toHex().c_str());
|
|
||||||
Bytes public_key = packet.data().left(KEYSIZE/8);
|
size_t keysize = KEYSIZE/8;
|
||||||
//TRACEF("Identity::validate_announce: public_key: %s", public_key.toHex().c_str());
|
size_t ratchetsize = Type::Identity::RATCHETSIZE/8;
|
||||||
Bytes name_hash = packet.data().mid(KEYSIZE/8, NAME_HASH_LENGTH/8);
|
size_t name_hash_len = NAME_HASH_LENGTH/8;
|
||||||
//TRACEF("Identity::validate_announce: name_hash: %s", name_hash.toHex().c_str());
|
size_t sig_len = SIGLENGTH/8;
|
||||||
Bytes random_hash = packet.data().mid(KEYSIZE/8 + NAME_HASH_LENGTH/8, RANDOM_HASH_LENGTH/8);
|
|
||||||
//TRACEF("Identity::validate_announce: random_hash: %s", random_hash.toHex().c_str());
|
Bytes public_key = packet.data().left(keysize);
|
||||||
Bytes signature = packet.data().mid(KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8, SIGLENGTH/8);
|
Bytes name_hash = packet.data().mid(keysize, name_hash_len);
|
||||||
//TRACEF("Identity::validate_announce: signature: %s", signature.toHex().c_str());
|
Bytes random_hash = packet.data().mid(keysize + name_hash_len, 10);
|
||||||
|
|
||||||
|
Bytes ratchet;
|
||||||
|
Bytes signature;
|
||||||
Bytes app_data;
|
Bytes app_data;
|
||||||
if (packet.data().size() > (KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8 + SIGLENGTH/8)) {
|
|
||||||
app_data = packet.data().mid(KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8 + SIGLENGTH/8);
|
// If the packet context flag is set, this announce contains a ratchet key
|
||||||
|
if (packet.context_flag() == Type::Packet::FLAG_SET) {
|
||||||
|
ratchet = packet.data().mid(keysize + name_hash_len + 10, ratchetsize);
|
||||||
|
signature = packet.data().mid(keysize + name_hash_len + 10 + ratchetsize, sig_len);
|
||||||
|
if (packet.data().size() > keysize + name_hash_len + 10 + ratchetsize + sig_len) {
|
||||||
|
app_data = packet.data().mid(keysize + name_hash_len + 10 + ratchetsize + sig_len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
signature = packet.data().mid(keysize + name_hash_len + 10, sig_len);
|
||||||
|
if (packet.data().size() > keysize + name_hash_len + 10 + sig_len) {
|
||||||
|
app_data = packet.data().mid(keysize + name_hash_len + 10 + sig_len);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
//TRACEF("Identity::validate_announce: app_data: %s", app_data.toHex().c_str());
|
|
||||||
//TRACEF("Identity::validate_announce: app_data text: %s", app_data.toString().c_str());
|
|
||||||
|
|
||||||
Bytes signed_data;
|
if (!ratchet && packet.data().size() <= keysize + name_hash_len + 10 + sig_len) {
|
||||||
signed_data << packet.destination_hash() << public_key << name_hash << random_hash+app_data;
|
|
||||||
//TRACEF("Identity::validate_announce: signed_data: %s", signed_data.toHex().c_str());
|
|
||||||
|
|
||||||
if (packet.data().size() <= KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8 + SIGLENGTH/8) {
|
|
||||||
app_data.clear();
|
app_data.clear();
|
||||||
}
|
}
|
||||||
|
else if (ratchet && packet.data().size() <= keysize + name_hash_len + 10 + ratchetsize + sig_len) {
|
||||||
|
app_data.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fast path: if this identity is already known with the same public key,
|
||||||
|
// skip the expensive Ed25519 signature verification (~150ms on ESP32).
|
||||||
|
// Just update app_data/timestamp and return true.
|
||||||
|
auto known_iter = _known_destinations.find(destination_hash);
|
||||||
|
if (known_iter != _known_destinations.end()
|
||||||
|
&& known_iter->second._public_key == public_key) {
|
||||||
|
remember(packet.get_hash(), destination_hash, public_key, app_data);
|
||||||
|
if (ratchet) {
|
||||||
|
remember_ratchet(destination_hash, ratchet);
|
||||||
|
}
|
||||||
|
TRACEF("validate_announce: known identity %s — skipped Ed25519 verify",
|
||||||
|
destination_hash.toHex().c_str());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Slow path: new or changed identity — full Ed25519 verify required
|
||||||
|
Bytes signed_data;
|
||||||
|
signed_data << destination_hash << public_key << name_hash << random_hash << ratchet << app_data;
|
||||||
|
|
||||||
Identity announced_identity(false);
|
Identity announced_identity(false);
|
||||||
announced_identity.load_public_key(public_key);
|
announced_identity.load_public_key(public_key);
|
||||||
|
|
||||||
if (announced_identity.pub() && announced_identity.validate(signature, signed_data)) {
|
if (announced_identity.pub() && announced_identity.validate(signature, signed_data)) {
|
||||||
|
TRACEF("[DIAG] validate_announce: name_hash=%s identity_hash=%s",
|
||||||
|
name_hash.toHex().c_str(), announced_identity.hash().toHex().c_str());
|
||||||
Bytes hash_material = name_hash << announced_identity.hash();
|
Bytes hash_material = name_hash << announced_identity.hash();
|
||||||
Bytes expected_hash = full_hash(hash_material).left(Type::Reticulum::TRUNCATED_HASHLENGTH/8);
|
Bytes expected_hash = full_hash(hash_material).left(Type::Reticulum::TRUNCATED_HASHLENGTH/8);
|
||||||
|
TRACEF("[DIAG] validate_announce: material(%d)=%s expected=%s actual=%s",
|
||||||
|
(int)hash_material.size(), hash_material.toHex().c_str(),
|
||||||
|
expected_hash.toHex().c_str(), packet.destination_hash().toHex().c_str());
|
||||||
//TRACEF("Identity::validate_announce: destination_hash: %s", packet.destination_hash().toHex().c_str());
|
//TRACEF("Identity::validate_announce: destination_hash: %s", packet.destination_hash().toHex().c_str());
|
||||||
//TRACEF("Identity::validate_announce: expected_hash: %s", expected_hash.toHex().c_str());
|
//TRACEF("Identity::validate_announce: expected_hash: %s", expected_hash.toHex().c_str());
|
||||||
|
|
||||||
@@ -456,7 +597,10 @@ Recall last heard app_data for a destination hash.
|
|||||||
}
|
}
|
||||||
|
|
||||||
remember(packet.get_hash(), packet.destination_hash(), public_key, app_data);
|
remember(packet.get_hash(), packet.destination_hash(), public_key, app_data);
|
||||||
//p del announced_identity
|
|
||||||
|
if (ratchet) {
|
||||||
|
remember_ratchet(packet.destination_hash(), ratchet);
|
||||||
|
}
|
||||||
|
|
||||||
std::string signal_str;
|
std::string signal_str;
|
||||||
// TODO
|
// TODO
|
||||||
@@ -481,14 +625,23 @@ Recall last heard app_data for a destination hash.
|
|||||||
TRACEF("Valid announce for %s %d hops away, received on %s%s", packet.destination_hash().toHex().c_str(), packet.hops(), packet.receiving_interface().toString().c_str(), signal_str.c_str());
|
TRACEF("Valid announce for %s %d hops away, received on %s%s", packet.destination_hash().toHex().c_str(), packet.hops(), packet.receiving_interface().toString().c_str(), signal_str.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TRACEF("[DIAG] ANNOUNCE VALID: dest=%s hops=%d ratchet=%s",
|
||||||
|
packet.destination_hash().toHex().c_str(), packet.hops(),
|
||||||
|
ratchet ? "YES" : "NO");
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
TRACEF("[DIAG] ANNOUNCE HASH MISMATCH: dest=%s expected=%s",
|
||||||
|
packet.destination_hash().toHex().c_str(), expected_hash.toHex().c_str());
|
||||||
DEBUGF("Received invalid announce for %s: Destination mismatch.", packet.destination_hash().toHex().c_str());
|
DEBUGF("Received invalid announce for %s: Destination mismatch.", packet.destination_hash().toHex().c_str());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
TRACEF("[DIAG] ANNOUNCE INVALID SIG: dest=%s datalen=%d ctxflag=%d",
|
||||||
|
packet.destination_hash().toHex().c_str(), (int)packet.data().size(),
|
||||||
|
packet.context_flag());
|
||||||
DEBUGF("Received invalid announce for %s: Invalid signature.", packet.destination_hash().toHex().c_str());
|
DEBUGF("Received invalid announce for %s: Invalid signature.", packet.destination_hash().toHex().c_str());
|
||||||
//p del announced_identity
|
//p del announced_identity
|
||||||
return false;
|
return false;
|
||||||
@@ -502,6 +655,27 @@ Recall last heard app_data for a destination hash.
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*static*/ void Identity::remember_ratchet(const Bytes& destination_hash, const Bytes& ratchet_pub) {
|
||||||
|
if (ratchet_pub.size() != Type::Identity::RATCHETSIZE/8) {
|
||||||
|
WARNINGF("Cannot remember ratchet for %s, invalid ratchet size %zu", destination_hash.toHex().c_str(), ratchet_pub.size());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
auto iter = _known_ratchets.find(destination_hash);
|
||||||
|
if (iter != _known_ratchets.end() && iter->second == ratchet_pub) {
|
||||||
|
return; // Already known, no change
|
||||||
|
}
|
||||||
|
TRACEF("Remembering ratchet for %s", destination_hash.toHex().c_str());
|
||||||
|
_known_ratchets.insert_or_assign(destination_hash, ratchet_pub);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*static*/ Bytes Identity::get_ratchet(const Bytes& destination_hash) {
|
||||||
|
auto iter = _known_ratchets.find(destination_hash);
|
||||||
|
if (iter != _known_ratchets.end()) {
|
||||||
|
return iter->second;
|
||||||
|
}
|
||||||
|
return {Bytes::NONE};
|
||||||
|
}
|
||||||
|
|
||||||
/*static*/ void Identity::persist_data() {
|
/*static*/ void Identity::persist_data() {
|
||||||
if (!Transport::reticulum() || !Transport::reticulum().is_connected_to_shared_instance()) {
|
if (!Transport::reticulum() || !Transport::reticulum().is_connected_to_shared_instance()) {
|
||||||
save_known_destinations();
|
save_known_destinations();
|
||||||
@@ -519,7 +693,7 @@ Encrypts information for the identity.
|
|||||||
:returns: Ciphertext token as *bytes*.
|
:returns: Ciphertext token as *bytes*.
|
||||||
:raises: *KeyError* if the instance does not hold a public key.
|
:raises: *KeyError* if the instance does not hold a public key.
|
||||||
*/
|
*/
|
||||||
const Bytes Identity::encrypt(const Bytes& plaintext) const {
|
const Bytes Identity::encrypt(const Bytes& plaintext, const Bytes& ratchet_key /*= {Bytes::NONE}*/) const {
|
||||||
assert(_object);
|
assert(_object);
|
||||||
TRACE("Identity::encrypt: encrypting data...");
|
TRACE("Identity::encrypt: encrypting data...");
|
||||||
if (!_object->_pub) {
|
if (!_object->_pub) {
|
||||||
@@ -529,9 +703,18 @@ const Bytes Identity::encrypt(const Bytes& plaintext) const {
|
|||||||
Bytes ephemeral_pub_bytes = ephemeral_key->public_key()->public_bytes();
|
Bytes ephemeral_pub_bytes = ephemeral_key->public_key()->public_bytes();
|
||||||
TRACEF("Identity::encrypt: ephemeral public key: %s", ephemeral_pub_bytes.toHex().c_str());
|
TRACEF("Identity::encrypt: ephemeral public key: %s", ephemeral_pub_bytes.toHex().c_str());
|
||||||
|
|
||||||
// CRYPTO: create shared key for key exchange using own public key
|
// CRYPTO: create shared key for key exchange
|
||||||
//shared_key = ephemeral_key.exchange(self.pub)
|
// Use ratchet public key if available for forward secrecy, otherwise identity public key
|
||||||
Bytes shared_key = ephemeral_key->exchange(_object->_pub_bytes);
|
Bytes shared_key;
|
||||||
|
TRACEF("[DIAG] ENCRYPT: ratchet=%s ephemeral=%.16s... plaintext=%dB",
|
||||||
|
ratchet_key ? "YES" : "NO", ephemeral_pub_bytes.toHex().c_str(), (int)plaintext.size());
|
||||||
|
if (ratchet_key) {
|
||||||
|
shared_key = ephemeral_key->exchange(ratchet_key);
|
||||||
|
TRACE("Identity::encrypt: using ratchet key for ECDH");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
shared_key = ephemeral_key->exchange(_object->_pub_bytes);
|
||||||
|
}
|
||||||
TRACEF("Identity::encrypt: shared key: %s", shared_key.toHex().c_str());
|
TRACEF("Identity::encrypt: shared key: %s", shared_key.toHex().c_str());
|
||||||
|
|
||||||
Bytes derived_key = Cryptography::hkdf(
|
Bytes derived_key = Cryptography::hkdf(
|
||||||
@@ -640,8 +823,7 @@ bool Identity::validate(const Bytes& signature, const Bytes& message) const {
|
|||||||
if (_object->_pub) {
|
if (_object->_pub) {
|
||||||
try {
|
try {
|
||||||
TRACEF("Identity::validate: Attempting to verify signature: %s and message: %s", signature.toHex().c_str(), message.toHex().c_str());
|
TRACEF("Identity::validate: Attempting to verify signature: %s and message: %s", signature.toHex().c_str(), message.toHex().c_str());
|
||||||
_object->_sig_pub->verify(signature, message);
|
return _object->_sig_pub->verify(signature, message);
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
catch (std::exception& e) {
|
catch (std::exception& e) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
+20
-3
@@ -7,6 +7,7 @@
|
|||||||
#include "Cryptography/Ed25519.h"
|
#include "Cryptography/Ed25519.h"
|
||||||
#include "Cryptography/X25519.h"
|
#include "Cryptography/X25519.h"
|
||||||
#include "Cryptography/Token.h"
|
#include "Cryptography/Token.h"
|
||||||
|
#include "Utilities/Memory.h"
|
||||||
|
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <string>
|
#include <string>
|
||||||
@@ -36,12 +37,18 @@ namespace RNS {
|
|||||||
Bytes _public_key;
|
Bytes _public_key;
|
||||||
Bytes _app_data;
|
Bytes _app_data;
|
||||||
};
|
};
|
||||||
|
//using IdentityTable = std::map<Bytes, IdentityEntry>;
|
||||||
|
using IdentityTable = std::map<Bytes, IdentityEntry, std::less<Bytes>, Utilities::Memory::ContainerAllocator<std::pair<const Bytes, IdentityEntry>>>;
|
||||||
|
|
||||||
public:
|
using RatchetTable = std::map<Bytes, Bytes>;
|
||||||
static std::map<Bytes, IdentityEntry> _known_destinations;
|
|
||||||
|
private:
|
||||||
|
static IdentityTable _known_destinations;
|
||||||
static bool _saving_known_destinations;
|
static bool _saving_known_destinations;
|
||||||
// CBA
|
// CBA
|
||||||
static uint16_t _known_destinations_maxsize;
|
static uint16_t _known_destinations_maxsize;
|
||||||
|
static bool _known_destinations_dirty;
|
||||||
|
static RatchetTable _known_ratchets;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
Identity(bool create_keys = true);
|
Identity(bool create_keys = true);
|
||||||
@@ -98,7 +105,7 @@ namespace RNS {
|
|||||||
inline const Bytes& get_salt() const { assert(_object); return _object->_hash; }
|
inline const Bytes& get_salt() const { assert(_object); return _object->_hash; }
|
||||||
inline const Bytes get_context() const { return {Bytes::NONE}; }
|
inline const Bytes get_context() const { return {Bytes::NONE}; }
|
||||||
|
|
||||||
const Bytes encrypt(const Bytes& plaintext) const;
|
const Bytes encrypt(const Bytes& plaintext, const Bytes& ratchet_key = {Bytes::NONE}) const;
|
||||||
const Bytes decrypt(const Bytes& ciphertext_token) const;
|
const Bytes decrypt(const Bytes& ciphertext_token) const;
|
||||||
const Bytes sign(const Bytes& message) const;
|
const Bytes sign(const Bytes& message) const;
|
||||||
bool validate(const Bytes& signature, const Bytes& message) const;
|
bool validate(const Bytes& signature, const Bytes& message) const;
|
||||||
@@ -148,6 +155,8 @@ namespace RNS {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static bool validate_announce(const Packet& packet);
|
static bool validate_announce(const Packet& packet);
|
||||||
|
static void remember_ratchet(const Bytes& destination_hash, const Bytes& ratchet_pub);
|
||||||
|
static Bytes get_ratchet(const Bytes& destination_hash);
|
||||||
static void persist_data();
|
static void persist_data();
|
||||||
static void exit_handler();
|
static void exit_handler();
|
||||||
|
|
||||||
@@ -166,6 +175,12 @@ namespace RNS {
|
|||||||
inline const Cryptography::Ed25519PublicKey::Ptr sig_pub() const { assert(_object); return _object->_sig_pub; }
|
inline const Cryptography::Ed25519PublicKey::Ptr sig_pub() const { assert(_object); return _object->_sig_pub; }
|
||||||
inline static uint16_t known_destinations_maxsize() { return _known_destinations_maxsize; }
|
inline static uint16_t known_destinations_maxsize() { return _known_destinations_maxsize; }
|
||||||
inline static void known_destinations_maxsize(uint16_t known_destinations_maxsize) { _known_destinations_maxsize = known_destinations_maxsize; }
|
inline static void known_destinations_maxsize(uint16_t known_destinations_maxsize) { _known_destinations_maxsize = known_destinations_maxsize; }
|
||||||
|
static void deferred_cull_known_destinations() {
|
||||||
|
if (_known_destinations_dirty) {
|
||||||
|
_known_destinations_dirty = false;
|
||||||
|
cull_known_destinations();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
inline std::string toString() const { if (!_object) return ""; return "{Identity:" + _object->_hash.toHex() + "}"; }
|
inline std::string toString() const { if (!_object) return ""; return "{Identity:" + _object->_hash.toHex() + "}"; }
|
||||||
|
|
||||||
@@ -197,6 +212,8 @@ namespace RNS {
|
|||||||
};
|
};
|
||||||
std::shared_ptr<Object> _object;
|
std::shared_ptr<Object> _object;
|
||||||
|
|
||||||
|
// CBA For access to private static members by Transport class
|
||||||
|
friend class Transport;
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
+13
-1
@@ -6,7 +6,7 @@
|
|||||||
using namespace RNS;
|
using namespace RNS;
|
||||||
using namespace RNS::Type::Interface;
|
using namespace RNS::Type::Interface;
|
||||||
|
|
||||||
/*static*/ uint8_t Interface::DISCOVER_PATHS_FOR = MODE_ACCESS_POINT | MODE_GATEWAY;
|
/*static*/ uint8_t Interface::DISCOVER_PATHS_FOR = MODE_ACCESS_POINT | MODE_GATEWAY | MODE_ROAMING;
|
||||||
|
|
||||||
void InterfaceImpl::handle_outgoing(const Bytes& data) {
|
void InterfaceImpl::handle_outgoing(const Bytes& data) {
|
||||||
//TRACEF("InterfaceImpl.handle_outgoing: data: %s", data.toHex().c_str());
|
//TRACEF("InterfaceImpl.handle_outgoing: data: %s", data.toHex().c_str());
|
||||||
@@ -35,6 +35,12 @@ void Interface::send_outgoing(const Bytes& data) {
|
|||||||
}
|
}
|
||||||
catch (const std::bad_alloc&) {
|
catch (const std::bad_alloc&) {
|
||||||
ERROR("Interface::send_outgoing: bad_alloc - OUT OF MEMORY");
|
ERROR("Interface::send_outgoing: bad_alloc - OUT OF MEMORY");
|
||||||
|
// Critical OOM, restarting
|
||||||
|
#if defined(ESP32)
|
||||||
|
ESP.restart();
|
||||||
|
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||||
|
NVIC_SystemReset();
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
catch (std::exception& e) {
|
catch (std::exception& e) {
|
||||||
ERRORF("Interface::send_outgoing: %s", e.what());
|
ERRORF("Interface::send_outgoing: %s", e.what());
|
||||||
@@ -56,6 +62,12 @@ void Interface::handle_incoming(const Bytes& data) {
|
|||||||
}
|
}
|
||||||
catch (const std::bad_alloc&) {
|
catch (const std::bad_alloc&) {
|
||||||
ERROR("Interface::handle_incoming: bad_alloc - OUT OF MEMORY");
|
ERROR("Interface::handle_incoming: bad_alloc - OUT OF MEMORY");
|
||||||
|
// Critical OOM, restarting
|
||||||
|
#if defined(ESP32)
|
||||||
|
ESP.restart();
|
||||||
|
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||||
|
NVIC_SystemReset();
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
catch (std::exception& e) {
|
catch (std::exception& e) {
|
||||||
ERRORF("Interface::handle_incoming: %s", e.what());
|
ERRORF("Interface::handle_incoming: %s", e.what());
|
||||||
|
|||||||
@@ -82,6 +82,7 @@ namespace RNS {
|
|||||||
std::list<AnnounceEntry> _announce_queue;
|
std::list<AnnounceEntry> _announce_queue;
|
||||||
bool _is_connected_to_shared_instance = false;
|
bool _is_connected_to_shared_instance = false;
|
||||||
bool _is_local_shared_instance = false;
|
bool _is_local_shared_instance = false;
|
||||||
|
|
||||||
//Bytes _hash;
|
//Bytes _hash;
|
||||||
HInterface _parent_interface;
|
HInterface _parent_interface;
|
||||||
//Transport& _owner;
|
//Transport& _owner;
|
||||||
|
|||||||
@@ -0,0 +1,661 @@
|
|||||||
|
#include "AutoInterface.h"
|
||||||
|
#include "AutoInterfacePeer.h"
|
||||||
|
|
||||||
|
#include "../Log.h"
|
||||||
|
#include "../Transport.h"
|
||||||
|
#include "../Utilities/OS.h"
|
||||||
|
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstring>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
// Sockets layer — POSIX on native, lwIP on Arduino. lwIP intentionally
|
||||||
|
// exposes a BSD-compatible API via <lwip/sockets.h> (socket/bind/recvfrom/
|
||||||
|
// sendto/setsockopt/fcntl all work as macros), so the bodies below are
|
||||||
|
// identical on both targets.
|
||||||
|
#ifdef ARDUINO
|
||||||
|
#include <lwip/opt.h>
|
||||||
|
// Defense in depth: AutoInterface needs IPv6 + MLD enabled in lwIP so
|
||||||
|
// IPV6_JOIN_GROUP works. espressif32@6.7.0's prebuilt SDK enables both
|
||||||
|
// (LWIP_IPV6=1, LWIP_IPV6_MLD inherited from LWIP_IPV6); if a future
|
||||||
|
// platform release flips that off, fail loudly at compile time so we
|
||||||
|
// don't ship silent multicast breakage.
|
||||||
|
#if !LWIP_IPV6
|
||||||
|
#error "AutoInterface requires lwIP IPv6. CONFIG_LWIP_IPV6 must be enabled."
|
||||||
|
#endif
|
||||||
|
#if !LWIP_IPV6_MLD
|
||||||
|
#error "AutoInterface requires lwIP MLD. CONFIG_LWIP_IPV6_MLD must be enabled."
|
||||||
|
#endif
|
||||||
|
#include <lwip/sockets.h>
|
||||||
|
#include <lwip/inet.h>
|
||||||
|
// errno on lwIP is provided via Arduino's stdlib; <cerrno> is safe to include.
|
||||||
|
#include <cerrno>
|
||||||
|
#else
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <fcntl.h>
|
||||||
|
#include <netinet/in.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace RNS {
|
||||||
|
|
||||||
|
AutoInterface::AutoInterface(const char* name,
|
||||||
|
const char* group_id,
|
||||||
|
char addr_type,
|
||||||
|
char scope,
|
||||||
|
uint16_t discovery_port,
|
||||||
|
uint16_t data_port,
|
||||||
|
uint8_t max_peers,
|
||||||
|
uint8_t multicast_hops)
|
||||||
|
: _addr_type(addr_type),
|
||||||
|
_scope(scope),
|
||||||
|
_discovery_port(discovery_port),
|
||||||
|
_unicast_disco_port(discovery_port + 1),
|
||||||
|
_data_port(data_port),
|
||||||
|
_max_peers(max_peers),
|
||||||
|
_multicast_hops(multicast_hops != 0
|
||||||
|
? multicast_hops
|
||||||
|
: (scope == SCOPE_LINK ? 1 : 32))
|
||||||
|
{
|
||||||
|
_name = name ? name : "AutoInterface";
|
||||||
|
_group_id_bytes = Bytes(group_id);
|
||||||
|
_HW_MTU = HW_MTU;
|
||||||
|
_FIXED_MTU = FIXED_MTU;
|
||||||
|
_bitrate = BITRATE_GUESS;
|
||||||
|
_IN = true;
|
||||||
|
_OUT = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
AutoInterface::~AutoInterface() {
|
||||||
|
if (_online) {
|
||||||
|
stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// Python / glibc / macOS produce lowercase canonical IPv6 strings;
|
||||||
|
// lwIP's ip6addr_ntoa_r produces UPPERCASE. RFC 5952 mandates
|
||||||
|
// lowercase, so normalize here so our SHA256 hashes wire-match
|
||||||
|
// every other AutoInterface implementation regardless of platform.
|
||||||
|
std::string canonicalize_ipv6(const std::string& addr_str) {
|
||||||
|
struct in6_addr tmp;
|
||||||
|
if (inet_pton(AF_INET6, addr_str.c_str(), &tmp) != 1) return addr_str;
|
||||||
|
char buf[INET6_ADDRSTRLEN];
|
||||||
|
if (inet_ntop(AF_INET6, &tmp, buf, sizeof(buf)) == nullptr) return addr_str;
|
||||||
|
std::string out(buf);
|
||||||
|
for (auto& c : out) {
|
||||||
|
if (c >= 'A' && c <= 'F') c = static_cast<char>(c - 'A' + 'a');
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::set_link_local(const std::string& addr_str, uint32_t scope_id) {
|
||||||
|
notify_link_change(addr_str, scope_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::notify_link_change(const std::string& addr_str,
|
||||||
|
uint32_t scope_id) {
|
||||||
|
// Re-canonicalize so the stored form is the lowercase RFC 5952 form
|
||||||
|
// regardless of whether the caller passed an expanded
|
||||||
|
// "fe80:0000:..." form (Arduino IPv6Address::toString) or
|
||||||
|
// uppercase from lwIP. Peers compute their expected self-token by
|
||||||
|
// hashing what they read off recvfrom + inet_ntop, which on every
|
||||||
|
// other implementation is lowercase canonical.
|
||||||
|
const std::string canon = canonicalize_ipv6(addr_str);
|
||||||
|
if (canon == _link_local_addr && scope_id == _scope_id) {
|
||||||
|
return; // idempotent no-op
|
||||||
|
}
|
||||||
|
|
||||||
|
struct in6_addr new_bin{};
|
||||||
|
if (inet_pton(AF_INET6, canon.c_str(), &new_bin) != 1) {
|
||||||
|
WARNINGF("AutoInterface::notify_link_change: invalid address '%s'",
|
||||||
|
addr_str.c_str());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remember the old link-local for self-echo suppression. Late
|
||||||
|
// multicast loopbacks of our previous announces would otherwise
|
||||||
|
// pass token validation (their token was hashed from our prior
|
||||||
|
// address) and get added as a "peer" pointing back at us.
|
||||||
|
if (!_link_local_addr.empty()) {
|
||||||
|
_self_link_local_history.push_front(_self_link_local_bin);
|
||||||
|
while (_self_link_local_history.size() > SELF_LL_HISTORY_MAX) {
|
||||||
|
_self_link_local_history.pop_back();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::memcpy(_self_link_local_bin.data(), &new_bin, 16);
|
||||||
|
_link_local_addr = canon;
|
||||||
|
_self_disco_token = compute_discovery_token(_group_id_bytes, _link_local_addr);
|
||||||
|
|
||||||
|
const uint32_t prev_scope_id = _scope_id;
|
||||||
|
_scope_id = scope_id;
|
||||||
|
|
||||||
|
if (_online && _disco_sock >= 0 && prev_scope_id != scope_id) {
|
||||||
|
// Leave the old multicast membership on the previous ifindex
|
||||||
|
// and rejoin on the new one. Both calls are best-effort:
|
||||||
|
// failure here is no worse than the start-time best-effort
|
||||||
|
// join (see open_sockets()), and we don't want a transient
|
||||||
|
// network blip to take the whole interface offline.
|
||||||
|
struct ipv6_mreq leave{};
|
||||||
|
std::memcpy(&leave.ipv6mr_multiaddr, _mcast_addr_bin.data(), 16);
|
||||||
|
leave.ipv6mr_interface = prev_scope_id;
|
||||||
|
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
|
||||||
|
&leave, sizeof(leave));
|
||||||
|
|
||||||
|
const unsigned int idx = static_cast<unsigned int>(scope_id);
|
||||||
|
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_IF,
|
||||||
|
&idx, sizeof(idx));
|
||||||
|
|
||||||
|
struct ipv6_mreq join{};
|
||||||
|
std::memcpy(&join.ipv6mr_multiaddr, _mcast_addr_bin.data(), 16);
|
||||||
|
join.ipv6mr_interface = idx;
|
||||||
|
if (::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
|
||||||
|
&join, sizeof(join)) != 0) {
|
||||||
|
WARNINGF("AutoInterface::notify_link_change: rejoin on "
|
||||||
|
"scope=%u failed (errno=%d)", (unsigned)scope_id, errno);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool AutoInterface::start() {
|
||||||
|
if (_online) return true;
|
||||||
|
if (_link_local_addr.empty()) {
|
||||||
|
WARNING("AutoInterface::start: no link-local address configured");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (_data_port == _unicast_disco_port || _data_port == _discovery_port) {
|
||||||
|
WARNINGF("AutoInterface::start: data_port (%u) collides with "
|
||||||
|
"discovery_port (%u) or unicast_disco_port (%u); "
|
||||||
|
"pick data_port at least 2 away from discovery_port",
|
||||||
|
(unsigned)_data_port, (unsigned)_discovery_port,
|
||||||
|
(unsigned)_unicast_disco_port);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compute group hash + multicast address now (cheap; idempotent).
|
||||||
|
_group_hash = compute_group_hash(_group_id_bytes);
|
||||||
|
_mcast_addr_str = compute_multicast_address(_group_hash, _addr_type, _scope);
|
||||||
|
struct in6_addr mc_tmp;
|
||||||
|
if (inet_pton(AF_INET6, _mcast_addr_str.c_str(), &mc_tmp) != 1) {
|
||||||
|
WARNING("AutoInterface::start: invalid multicast address");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
std::memcpy(_mcast_addr_bin.data(), &mc_tmp, 16);
|
||||||
|
|
||||||
|
if (!open_sockets()) {
|
||||||
|
close_sockets();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_online = true;
|
||||||
|
_final_init_done = false; // ignore any RX before peer_jobs first tick
|
||||||
|
_next_announce_ms = 0;
|
||||||
|
_next_peer_job_ms = PEER_JOB_INTERVAL_MS;
|
||||||
|
_last_mcast_echo_ms = 0;
|
||||||
|
_has_mcast_echo = false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::stop() {
|
||||||
|
if (!_online) return;
|
||||||
|
// Tear down all spawned peers — Transport must not retain stale refs.
|
||||||
|
for (auto& kv : _peers) {
|
||||||
|
Transport::deregister_interface(kv.second.wrapper);
|
||||||
|
kv.second.peer_iface->stop();
|
||||||
|
}
|
||||||
|
_peers.clear();
|
||||||
|
close_sockets();
|
||||||
|
_online = false;
|
||||||
|
_final_init_done = false;
|
||||||
|
_has_mcast_echo = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::loop() {
|
||||||
|
loop_at(static_cast<uint64_t>(Utilities::OS::ltime()));
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::loop_at(uint64_t now_ms) {
|
||||||
|
if (!_online) return;
|
||||||
|
|
||||||
|
// Drain RX (each capped to 4 packets / call to bound CPU).
|
||||||
|
poll_multicast();
|
||||||
|
poll_unicast_disco();
|
||||||
|
poll_data();
|
||||||
|
|
||||||
|
if (now_ms >= _next_announce_ms) {
|
||||||
|
announce_peer();
|
||||||
|
_next_announce_ms = now_ms + ANNOUNCE_INTERVAL_MS;
|
||||||
|
// First announce sent — RX may now process discovery packets.
|
||||||
|
_final_init_done = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (now_ms >= _next_peer_job_ms) {
|
||||||
|
peer_jobs(now_ms);
|
||||||
|
_next_peer_job_ms = now_ms + PEER_JOB_INTERVAL_MS;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::send_outgoing(const Bytes& /*data*/) {
|
||||||
|
// No-op. Outbound goes through per-peer wrappers (matches Python).
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Wire-format derivation ---
|
||||||
|
//
|
||||||
|
// Mirrors Python AutoInterface.py:
|
||||||
|
// - group_hash = SHA256(group_id) (lines 202-203)
|
||||||
|
// - mcast address = "ff{type}{scope}:0:{g[2:4]}:..." (lines 204-212)
|
||||||
|
// each ":NN:" pair is uint16 = (g[2k]<<8)|g[2k+1],
|
||||||
|
// printed with min-2 hex chars (Python "{:02x}")
|
||||||
|
// - discovery token = SHA256(group_id || link_local_addr_str) (lines 491-501)
|
||||||
|
// link_local_addr_str is canonical RFC 5952 (no scope suffix)
|
||||||
|
|
||||||
|
Bytes AutoInterface::compute_group_hash(const Bytes& group_id) {
|
||||||
|
return Identity::full_hash(group_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string AutoInterface::compute_multicast_address(const Bytes& group_hash,
|
||||||
|
char addr_type,
|
||||||
|
char scope) {
|
||||||
|
if (group_hash.size() < 14) {
|
||||||
|
return std::string();
|
||||||
|
}
|
||||||
|
const uint8_t* g = group_hash.data();
|
||||||
|
char buf[64];
|
||||||
|
std::snprintf(buf, sizeof(buf),
|
||||||
|
"ff%c%c:0:%02x:%02x:%02x:%02x:%02x:%02x",
|
||||||
|
addr_type, scope,
|
||||||
|
(unsigned)((g[2] << 8) | g[3]),
|
||||||
|
(unsigned)((g[4] << 8) | g[5]),
|
||||||
|
(unsigned)((g[6] << 8) | g[7]),
|
||||||
|
(unsigned)((g[8] << 8) | g[9]),
|
||||||
|
(unsigned)((g[10] << 8) | g[11]),
|
||||||
|
(unsigned)((g[12] << 8) | g[13]));
|
||||||
|
return std::string(buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
Bytes AutoInterface::compute_discovery_token(const Bytes& group_id,
|
||||||
|
const std::string& link_local_addr) {
|
||||||
|
Bytes material;
|
||||||
|
material.append(group_id);
|
||||||
|
material.append(link_local_addr);
|
||||||
|
return Identity::full_hash(material);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Peer table semantics ---
|
||||||
|
|
||||||
|
bool AutoInterface::has_peer(const IPv6Addr& addr) const {
|
||||||
|
return _peers.find(addr_key(addr)) != _peers.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
uint64_t AutoInterface::peer_last_heard_ms(const IPv6Addr& addr) const {
|
||||||
|
auto it = _peers.find(addr_key(addr));
|
||||||
|
return it == _peers.end() ? 0 : it->second.last_heard_ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::add_peer(const IPv6Addr& addr,
|
||||||
|
uint32_t scope_id,
|
||||||
|
uint64_t now_ms) {
|
||||||
|
const std::string key = addr_key(addr);
|
||||||
|
auto it = _peers.find(key);
|
||||||
|
if (it != _peers.end()) {
|
||||||
|
// Already known — just refresh the freshness timestamp.
|
||||||
|
it->second.last_heard_ms = now_ms;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (_peers.size() >= _max_peers) {
|
||||||
|
WARNING("AutoInterface: peer cap reached, ignoring new peer");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create the peer impl as a shared_ptr; alias it into a base
|
||||||
|
// shared_ptr<InterfaceImpl> so the Interface wrapper shares the same
|
||||||
|
// control block (no double-delete). The peer ctor already sets
|
||||||
|
// HW_MTU / FIXED_MTU / bitrate / IN / OUT.
|
||||||
|
auto peer_impl = std::make_shared<AutoInterfacePeer>(this, addr, scope_id);
|
||||||
|
std::shared_ptr<InterfaceImpl> base = peer_impl;
|
||||||
|
|
||||||
|
PeerEntry entry;
|
||||||
|
entry.addr = addr;
|
||||||
|
entry.scope_id = scope_id;
|
||||||
|
entry.last_heard_ms = now_ms;
|
||||||
|
entry.last_outbound_ms = now_ms;
|
||||||
|
entry.peer_iface = peer_impl;
|
||||||
|
entry.wrapper = Interface(base);
|
||||||
|
|
||||||
|
auto inserted = _peers.emplace(key, std::move(entry));
|
||||||
|
Interface& w = inserted.first->second.wrapper;
|
||||||
|
w.mode(_mode);
|
||||||
|
w.start(); // sets _online = true on the impl
|
||||||
|
Transport::register_interface(w);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::refresh_peer(const std::string& key, uint64_t now_ms) {
|
||||||
|
auto it = _peers.find(key);
|
||||||
|
if (it != _peers.end()) {
|
||||||
|
it->second.last_heard_ms = now_ms;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::peer_jobs(uint64_t now_ms) {
|
||||||
|
// Pass 1: collect timed-out peers (don't mutate map while iterating).
|
||||||
|
std::vector<std::string> to_remove;
|
||||||
|
to_remove.reserve(_peers.size());
|
||||||
|
for (const auto& kv : _peers) {
|
||||||
|
if (now_ms > kv.second.last_heard_ms + PEERING_TIMEOUT_MS) {
|
||||||
|
to_remove.push_back(kv.first);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass 2: deregister + erase.
|
||||||
|
for (const auto& key : to_remove) {
|
||||||
|
auto it = _peers.find(key);
|
||||||
|
if (it == _peers.end()) continue;
|
||||||
|
Transport::deregister_interface(it->second.wrapper);
|
||||||
|
it->second.peer_iface->stop();
|
||||||
|
_peers.erase(it);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass 3: reverse-peering — periodically send a unicast token to each
|
||||||
|
// peer so they see us even when our multicast announces are dropped
|
||||||
|
// by a hostile AP. Mirrors Python AutoInterface lines 393-403.
|
||||||
|
for (auto& kv : _peers) {
|
||||||
|
if (now_ms > kv.second.last_outbound_ms + REVERSE_PEERING_INTERVAL_MS) {
|
||||||
|
reverse_announce(kv.second.addr, kv.second.scope_id);
|
||||||
|
kv.second.last_outbound_ms = now_ms;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Test-only entry points ---
|
||||||
|
|
||||||
|
void AutoInterface::test_inject_peer(const IPv6Addr& addr,
|
||||||
|
uint32_t scope_id,
|
||||||
|
uint64_t now_ms) {
|
||||||
|
add_peer(addr, scope_id, now_ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::test_run_peer_jobs(uint64_t now_ms) {
|
||||||
|
peer_jobs(now_ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::test_loop_at(uint64_t now_ms) {
|
||||||
|
loop_at(now_ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Socket lifecycle ---
|
||||||
|
//
|
||||||
|
// Three non-blocking AF_INET6 / SOCK_DGRAM sockets:
|
||||||
|
// _disco_sock — RX multicast on _discovery_port + TX announces
|
||||||
|
// _unicast_sock — RX reverse-peering tokens on _unicast_disco_port
|
||||||
|
// _data_sock — RX peer payloads + TX peer payloads on _data_port
|
||||||
|
//
|
||||||
|
// Multicast group join (IPV6_JOIN_GROUP) is best-effort: failure logs a
|
||||||
|
// warning but does not fail start(). This lets us boot without LAN
|
||||||
|
// connectivity (or on hosts where the chosen scope id has no link-local
|
||||||
|
// IPv6) and recover later when the network comes up — Python AutoInterface
|
||||||
|
// has the same robustness property.
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// RAII helper to close a half-opened FD chain on early-return.
|
||||||
|
void try_close(int& fd) {
|
||||||
|
if (fd >= 0) {
|
||||||
|
::close(fd);
|
||||||
|
fd = -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool make_nonblocking(int fd) {
|
||||||
|
int flags = ::fcntl(fd, F_GETFL, 0);
|
||||||
|
if (flags < 0) return false;
|
||||||
|
return ::fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool bind_any(int fd, uint16_t port) {
|
||||||
|
sockaddr_in6 a{};
|
||||||
|
a.sin6_family = AF_INET6;
|
||||||
|
a.sin6_port = htons(port);
|
||||||
|
a.sin6_addr = in6addr_any;
|
||||||
|
return ::bind(fd, reinterpret_cast<sockaddr*>(&a), sizeof(a)) == 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool AutoInterface::open_sockets() {
|
||||||
|
const int yes = 1;
|
||||||
|
const int hops = static_cast<int>(_multicast_hops);
|
||||||
|
const unsigned int ifindex = static_cast<unsigned int>(_scope_id);
|
||||||
|
|
||||||
|
// --- Multicast discovery socket (RX + TX announces) ---
|
||||||
|
_disco_sock = ::socket(AF_INET6, SOCK_DGRAM, 0);
|
||||||
|
if (_disco_sock < 0) {
|
||||||
|
WARNING("AutoInterface: socket(disco) failed");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
::setsockopt(_disco_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||||
|
#ifdef SO_REUSEPORT
|
||||||
|
::setsockopt(_disco_sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));
|
||||||
|
#endif
|
||||||
|
const int v6only = 1;
|
||||||
|
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only));
|
||||||
|
// IPV6_MULTICAST_IF: outgoing multicast leaves on this interface
|
||||||
|
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_IF,
|
||||||
|
&ifindex, sizeof(ifindex));
|
||||||
|
// IPV6_MULTICAST_LOOP: receive our own multicast frames so we can detect
|
||||||
|
// the multicast echo (matches Python AutoInterface lines 451-464).
|
||||||
|
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &yes, sizeof(yes));
|
||||||
|
// IPV6_MULTICAST_HOPS — defaults to 1 for SCOPE_LINK (never leaks)
|
||||||
|
// and 32 for wider scopes; user can override via the constructor.
|
||||||
|
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &hops, sizeof(hops));
|
||||||
|
if (!bind_any(_disco_sock, _discovery_port)) {
|
||||||
|
WARNING("AutoInterface: bind(disco) failed");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!make_nonblocking(_disco_sock)) {
|
||||||
|
WARNING("AutoInterface: make_nonblocking(disco) failed");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// IPV6_JOIN_GROUP: best-effort (see header note).
|
||||||
|
struct ipv6_mreq mreq{};
|
||||||
|
std::memcpy(&mreq.ipv6mr_multiaddr, _mcast_addr_bin.data(), 16);
|
||||||
|
mreq.ipv6mr_interface = ifindex;
|
||||||
|
if (::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_JOIN_GROUP,
|
||||||
|
&mreq, sizeof(mreq)) != 0) {
|
||||||
|
WARNINGF("AutoInterface: IPV6_JOIN_GROUP failed (errno=%d) — "
|
||||||
|
"multicast RX may not work on this interface", errno);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Unicast discovery socket (port 29717) ---
|
||||||
|
_unicast_sock = ::socket(AF_INET6, SOCK_DGRAM, 0);
|
||||||
|
if (_unicast_sock < 0) return false;
|
||||||
|
::setsockopt(_unicast_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||||
|
#ifdef SO_REUSEPORT
|
||||||
|
::setsockopt(_unicast_sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));
|
||||||
|
#endif
|
||||||
|
::setsockopt(_unicast_sock, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only));
|
||||||
|
if (!bind_any(_unicast_sock, _unicast_disco_port)) {
|
||||||
|
WARNING("AutoInterface: bind(unicast) failed");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!make_nonblocking(_unicast_sock)) return false;
|
||||||
|
|
||||||
|
// --- Data socket (port 42671) ---
|
||||||
|
_data_sock = ::socket(AF_INET6, SOCK_DGRAM, 0);
|
||||||
|
if (_data_sock < 0) return false;
|
||||||
|
::setsockopt(_data_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
|
||||||
|
#ifdef SO_REUSEPORT
|
||||||
|
::setsockopt(_data_sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes));
|
||||||
|
#endif
|
||||||
|
::setsockopt(_data_sock, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only));
|
||||||
|
if (!bind_any(_data_sock, _data_port)) {
|
||||||
|
WARNING("AutoInterface: bind(data) failed");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!make_nonblocking(_data_sock)) return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::close_sockets() {
|
||||||
|
if (_disco_sock >= 0) {
|
||||||
|
// Best-effort leave group before closing.
|
||||||
|
struct ipv6_mreq mreq{};
|
||||||
|
std::memcpy(&mreq.ipv6mr_multiaddr, _mcast_addr_bin.data(), 16);
|
||||||
|
mreq.ipv6mr_interface = static_cast<unsigned int>(_scope_id);
|
||||||
|
::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_LEAVE_GROUP,
|
||||||
|
&mreq, sizeof(mreq));
|
||||||
|
}
|
||||||
|
try_close(_disco_sock);
|
||||||
|
try_close(_unicast_sock);
|
||||||
|
try_close(_data_sock);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- TX / RX paths (BSD socket API; lwIP exposes the same signatures). ---
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr int kPollBudget = 4; // packets per poll() call
|
||||||
|
|
||||||
|
void make_dst_sockaddr(sockaddr_in6& dst,
|
||||||
|
const AutoInterface::IPv6Addr& addr,
|
||||||
|
uint32_t scope_id,
|
||||||
|
uint16_t port) {
|
||||||
|
std::memset(&dst, 0, sizeof(dst));
|
||||||
|
dst.sin6_family = AF_INET6;
|
||||||
|
dst.sin6_port = htons(port);
|
||||||
|
dst.sin6_scope_id = scope_id;
|
||||||
|
std::memcpy(&dst.sin6_addr, addr.data(), 16);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::announce_peer() {
|
||||||
|
if (_disco_sock < 0 || _self_disco_token.size() < 32) return;
|
||||||
|
sockaddr_in6 dst;
|
||||||
|
make_dst_sockaddr(dst, _mcast_addr_bin, _scope_id, _discovery_port);
|
||||||
|
ssize_t n = ::sendto(_disco_sock,
|
||||||
|
_self_disco_token.data(), _self_disco_token.size(),
|
||||||
|
0, reinterpret_cast<sockaddr*>(&dst), sizeof(dst));
|
||||||
|
if (n < 0 && errno != ENETUNREACH && errno != EHOSTUNREACH) {
|
||||||
|
VERBOSEF("AutoInterface::announce_peer: sendto errno=%d", errno);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::reverse_announce(const IPv6Addr& peer_addr,
|
||||||
|
uint32_t peer_scope) {
|
||||||
|
if (_unicast_sock < 0 || _self_disco_token.size() < 32) return;
|
||||||
|
sockaddr_in6 dst;
|
||||||
|
make_dst_sockaddr(dst, peer_addr, peer_scope, _unicast_disco_port);
|
||||||
|
::sendto(_unicast_sock,
|
||||||
|
_self_disco_token.data(), _self_disco_token.size(),
|
||||||
|
0, reinterpret_cast<sockaddr*>(&dst), sizeof(dst));
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::poll_multicast() {
|
||||||
|
if (_disco_sock < 0) return;
|
||||||
|
for (int i = 0; i < kPollBudget; ++i) {
|
||||||
|
sockaddr_in6 src{};
|
||||||
|
socklen_t sl = sizeof(src);
|
||||||
|
ssize_t n = ::recvfrom(_disco_sock, _rx_buf, HW_MTU, 0,
|
||||||
|
reinterpret_cast<sockaddr*>(&src), &sl);
|
||||||
|
if (n <= 0) break;
|
||||||
|
if (!_final_init_done) continue;
|
||||||
|
|
||||||
|
// Self-echo: confirms multicast loopback works (carrier). Also
|
||||||
|
// suppress echoes of our previously-rotated link-locals so a
|
||||||
|
// late loopback after notify_link_change() doesn't accidentally
|
||||||
|
// peer us with our former self.
|
||||||
|
bool self_echo = std::memcmp(&src.sin6_addr,
|
||||||
|
_self_link_local_bin.data(), 16) == 0;
|
||||||
|
if (!self_echo) {
|
||||||
|
for (const auto& prev : _self_link_local_history) {
|
||||||
|
if (std::memcmp(&src.sin6_addr, prev.data(), 16) == 0) {
|
||||||
|
self_echo = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (self_echo) {
|
||||||
|
_last_mcast_echo_ms = static_cast<uint64_t>(Utilities::OS::ltime());
|
||||||
|
_has_mcast_echo = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (n < 32) continue;
|
||||||
|
|
||||||
|
char src_str[64];
|
||||||
|
::inet_ntop(AF_INET6, &src.sin6_addr, src_str, sizeof(src_str));
|
||||||
|
std::string canon = canonicalize_ipv6(src_str);
|
||||||
|
Bytes expected = compute_discovery_token(_group_id_bytes, canon);
|
||||||
|
if (expected.size() < 32) continue;
|
||||||
|
if (std::memcmp(_rx_buf, expected.data(), 32) != 0) continue;
|
||||||
|
|
||||||
|
IPv6Addr addr;
|
||||||
|
std::memcpy(addr.data(), &src.sin6_addr, 16);
|
||||||
|
add_peer(addr, src.sin6_scope_id,
|
||||||
|
static_cast<uint64_t>(Utilities::OS::ltime()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::poll_unicast_disco() {
|
||||||
|
if (_unicast_sock < 0) return;
|
||||||
|
for (int i = 0; i < kPollBudget; ++i) {
|
||||||
|
sockaddr_in6 src{};
|
||||||
|
socklen_t sl = sizeof(src);
|
||||||
|
ssize_t n = ::recvfrom(_unicast_sock, _rx_buf, HW_MTU, 0,
|
||||||
|
reinterpret_cast<sockaddr*>(&src), &sl);
|
||||||
|
if (n <= 0) break;
|
||||||
|
if (!_final_init_done) continue;
|
||||||
|
if (n < 32) continue;
|
||||||
|
|
||||||
|
char src_str[64];
|
||||||
|
::inet_ntop(AF_INET6, &src.sin6_addr, src_str, sizeof(src_str));
|
||||||
|
std::string canon = canonicalize_ipv6(src_str);
|
||||||
|
Bytes expected = compute_discovery_token(_group_id_bytes, canon);
|
||||||
|
if (expected.size() < 32) continue;
|
||||||
|
if (std::memcmp(_rx_buf, expected.data(), 32) != 0) continue;
|
||||||
|
|
||||||
|
IPv6Addr addr;
|
||||||
|
std::memcpy(addr.data(), &src.sin6_addr, 16);
|
||||||
|
add_peer(addr, src.sin6_scope_id,
|
||||||
|
static_cast<uint64_t>(Utilities::OS::ltime()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::poll_data() {
|
||||||
|
if (_data_sock < 0) return;
|
||||||
|
for (int i = 0; i < kPollBudget; ++i) {
|
||||||
|
sockaddr_in6 src{};
|
||||||
|
socklen_t sl = sizeof(src);
|
||||||
|
ssize_t n = ::recvfrom(_data_sock, _rx_buf, HW_MTU, 0,
|
||||||
|
reinterpret_cast<sockaddr*>(&src), &sl);
|
||||||
|
if (n <= 0) break;
|
||||||
|
IPv6Addr addr;
|
||||||
|
std::memcpy(addr.data(), &src.sin6_addr, 16);
|
||||||
|
Bytes data(_rx_buf, static_cast<size_t>(n));
|
||||||
|
route_inbound(data, addr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterface::route_inbound(const Bytes& data, const IPv6Addr& src) {
|
||||||
|
auto it = _peers.find(addr_key(src));
|
||||||
|
if (it == _peers.end()) return;
|
||||||
|
|
||||||
|
// MIF dedup ring — drops duplicates that arrive on multiple netifs
|
||||||
|
// within MIF_DEDUP_TTL_MS. Single-NIC devices rarely hit this but
|
||||||
|
// the cost is small and it matches Python's behaviour.
|
||||||
|
Bytes h = Identity::full_hash(data);
|
||||||
|
const uint64_t now = static_cast<uint64_t>(Utilities::OS::ltime());
|
||||||
|
for (const auto& d : _mif_dedup) {
|
||||||
|
if (d.hash == h && now < d.expires_ms) return;
|
||||||
|
}
|
||||||
|
_mif_dedup.push_back({h, now + MIF_DEDUP_TTL_MS});
|
||||||
|
while (_mif_dedup.size() > RNS_AUTOIFACE_MIF_DEDUP_LEN) {
|
||||||
|
_mif_dedup.pop_front();
|
||||||
|
}
|
||||||
|
|
||||||
|
it->second.last_heard_ms = now;
|
||||||
|
it->second.peer_iface->deliver_incoming(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace RNS
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "../Interface.h"
|
||||||
|
#include "../Bytes.h"
|
||||||
|
#include "../Identity.h"
|
||||||
|
|
||||||
|
#include <array>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <deque>
|
||||||
|
#include <map>
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
// MIF (multi-interface) dedup ring length. Override per device in
|
||||||
|
// platformio.ini build_flags for memory-tight targets (e.g. Ratcom).
|
||||||
|
#ifndef RNS_AUTOIFACE_MIF_DEDUP_LEN
|
||||||
|
#define RNS_AUTOIFACE_MIF_DEDUP_LEN 48
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Default cap on concurrent spawned peers. Each peer costs ~280 B plus
|
||||||
|
// whatever Transport caches for its paths. Override per device.
|
||||||
|
#ifndef RNS_AUTOIFACE_MAX_PEERS_DEFAULT
|
||||||
|
#define RNS_AUTOIFACE_MAX_PEERS_DEFAULT 8
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace RNS {
|
||||||
|
|
||||||
|
class AutoInterfacePeer;
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Reticulum AutoInterface — IPv6 link-local multicast LAN auto-discovery.
|
||||||
|
*
|
||||||
|
* Wire-compatible with the Python reference implementation
|
||||||
|
* (RNS/Interfaces/AutoInterface.py). Listens on a multicast group derived
|
||||||
|
* from SHA256(group_id) and spawns a per-peer AutoInterfacePeer Interface
|
||||||
|
* for each discovered node.
|
||||||
|
*
|
||||||
|
* Design notes:
|
||||||
|
* - One parent AutoInterface holds the multicast/unicast/data sockets.
|
||||||
|
* - One AutoInterfacePeer (registered with Transport) per peer.
|
||||||
|
* - Single-threaded, cooperative: loop() polls non-blocking sockets.
|
||||||
|
*
|
||||||
|
* Limitations vs the Python reference:
|
||||||
|
* - Single-NIC only. v1 does not enumerate system interfaces or take
|
||||||
|
* `devices` / `ignored_devices`; the host injects exactly one
|
||||||
|
* link-local address via set_link_local() / notify_link_change().
|
||||||
|
* - IFAC keying not implemented. A Python AutoInterface configured
|
||||||
|
* with `ifac_netname` / `ifac_netkey` is not interoperable with this
|
||||||
|
* implementation.
|
||||||
|
* - The host must call notify_link_change() on Wi-Fi reassociation
|
||||||
|
* (or any event that rotates the link-local address or interface
|
||||||
|
* index). Python's peer_jobs() polls for this every 4 s; the C++
|
||||||
|
* port is event-driven to keep the MCU loop hot path empty.
|
||||||
|
* - multicast_hops defaults to 1 for SCOPE_LINK and 32 for wider
|
||||||
|
* scopes. Crossing routers also requires MLD/router config beyond
|
||||||
|
* setting IPV6_MULTICAST_HOPS — same caveat as Python.
|
||||||
|
*
|
||||||
|
* Host integration recipe:
|
||||||
|
* 1. Resolve the link-local: WiFi.linkLocalIPv6().toString() (Arduino)
|
||||||
|
* or getifaddrs() (POSIX).
|
||||||
|
* 2. Resolve the interface index: esp_netif_get_netif_impl_index(...)
|
||||||
|
* (Arduino) or if_nametoindex(...) (POSIX).
|
||||||
|
* 3. Construct AutoInterface, set_link_local(addr, scope_id), start().
|
||||||
|
* 4. Register the parent with Transport::register_interface() — the
|
||||||
|
* library only registers spawned per-peer wrappers, not the parent.
|
||||||
|
* 5. Pump loop() from your main event loop (≤100 ms cadence).
|
||||||
|
* 6. On Wi-Fi reassociation, call notify_link_change(new_addr,
|
||||||
|
* new_scope_id) — no need to stop()/start().
|
||||||
|
*/
|
||||||
|
class AutoInterface : public InterfaceImpl {
|
||||||
|
public:
|
||||||
|
// Wire-compatible defaults — must match Python AutoInterface.py
|
||||||
|
static constexpr uint16_t DEFAULT_DISCOVERY_PORT = 29716;
|
||||||
|
static constexpr uint16_t DEFAULT_UNICAST_DISCO_PORT = 29717; // discovery + 1
|
||||||
|
static constexpr uint16_t DEFAULT_DATA_PORT = 42671;
|
||||||
|
static constexpr const char* DEFAULT_GROUP_ID = "reticulum";
|
||||||
|
static constexpr uint16_t HW_MTU = 1196;
|
||||||
|
static constexpr bool FIXED_MTU = true;
|
||||||
|
static constexpr uint32_t BITRATE_GUESS = 10 * 1000 * 1000;
|
||||||
|
|
||||||
|
static constexpr uint32_t ANNOUNCE_INTERVAL_MS = 1600;
|
||||||
|
static constexpr uint32_t PEER_JOB_INTERVAL_MS = 4000;
|
||||||
|
static constexpr uint32_t PEERING_TIMEOUT_MS = 22000;
|
||||||
|
static constexpr uint32_t MCAST_ECHO_TIMEOUT_MS = 6500;
|
||||||
|
static constexpr uint32_t REVERSE_PEERING_INTERVAL_MS = 5200; // 1.6 * 3.25
|
||||||
|
static constexpr uint32_t MIF_DEDUP_TTL_MS = 750;
|
||||||
|
|
||||||
|
static constexpr char SCOPE_LINK = '2';
|
||||||
|
static constexpr char SCOPE_ADMIN = '4';
|
||||||
|
static constexpr char SCOPE_SITE = '5';
|
||||||
|
static constexpr char SCOPE_ORGANISATION = '8';
|
||||||
|
static constexpr char SCOPE_GLOBAL = 'e';
|
||||||
|
|
||||||
|
static constexpr char MCAST_ADDR_TYPE_PERMANENT = '0';
|
||||||
|
static constexpr char MCAST_ADDR_TYPE_TEMPORARY = '1';
|
||||||
|
|
||||||
|
using IPv6Addr = std::array<uint8_t, 16>;
|
||||||
|
|
||||||
|
// multicast_hops = 0 → auto: 1 for SCOPE_LINK, 32 otherwise. Larger
|
||||||
|
// scopes (admin/site/org/global) also need router/MLD config to
|
||||||
|
// actually forward; this only sets the IPV6_MULTICAST_HOPS sockopt.
|
||||||
|
AutoInterface(const char* name = "AutoInterface",
|
||||||
|
const char* group_id = DEFAULT_GROUP_ID,
|
||||||
|
char addr_type = MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
char scope = SCOPE_LINK,
|
||||||
|
uint16_t discovery_port = DEFAULT_DISCOVERY_PORT,
|
||||||
|
uint16_t data_port = DEFAULT_DATA_PORT,
|
||||||
|
uint8_t max_peers = RNS_AUTOIFACE_MAX_PEERS_DEFAULT,
|
||||||
|
uint8_t multicast_hops = 0);
|
||||||
|
virtual ~AutoInterface();
|
||||||
|
|
||||||
|
// InterfaceImpl overrides
|
||||||
|
virtual bool start() override;
|
||||||
|
virtual void stop() override;
|
||||||
|
virtual void loop() override;
|
||||||
|
virtual void send_outgoing(const Bytes& data) override; // no-op (mirrors Python)
|
||||||
|
|
||||||
|
// Diagnostics / UI surface
|
||||||
|
size_t peer_count() const { return _peers.size(); }
|
||||||
|
bool has_carrier() const { return _has_mcast_echo; }
|
||||||
|
uint8_t multicast_hops() const { return _multicast_hops; }
|
||||||
|
const std::string& multicast_address() const { return _mcast_addr_str; }
|
||||||
|
const std::string& link_local_address() const { return _link_local_addr; }
|
||||||
|
bool has_peer(const IPv6Addr& addr) const;
|
||||||
|
uint64_t peer_last_heard_ms(const IPv6Addr& addr) const;
|
||||||
|
|
||||||
|
// Inject the local link-local address + interface scope id.
|
||||||
|
// Production code resolves these from WiFi.linkLocalIPv6() +
|
||||||
|
// esp_netif_get_netif_impl_index() (Arduino) or getifaddrs() +
|
||||||
|
// if_nametoindex() (native). May be called any time — internally
|
||||||
|
// dispatches to notify_link_change().
|
||||||
|
void set_link_local(const std::string& addr_str, uint32_t scope_id);
|
||||||
|
|
||||||
|
// Notify the library that the host's link-local address and/or
|
||||||
|
// interface scope id has changed (e.g. Wi-Fi reassociation, DHCPv6
|
||||||
|
// PD reissue). Recomputes the announce token so peers continue to
|
||||||
|
// validate us, rotates the previous link-local into the self-echo
|
||||||
|
// filter so late multicast loopback echoes don't accidentally peer
|
||||||
|
// us with our former self, and (if scope_id changed while online)
|
||||||
|
// leaves the old IPV6 multicast group and rejoins on the new
|
||||||
|
// interface index. Idempotent: a no-op if (addr, scope) match
|
||||||
|
// the current values. Safe to call before start().
|
||||||
|
void notify_link_change(const std::string& addr_str, uint32_t scope_id);
|
||||||
|
|
||||||
|
// Diagnostic FD accessors — returns -1 when closed.
|
||||||
|
int discovery_socket_fd() const { return _disco_sock; }
|
||||||
|
int unicast_socket_fd() const { return _unicast_sock; }
|
||||||
|
int data_socket_fd() const { return _data_sock; }
|
||||||
|
|
||||||
|
// Test-only entry points (do not call from production code).
|
||||||
|
// Allow driving the peer table without real sockets / real time.
|
||||||
|
void test_inject_peer(const IPv6Addr& addr, uint32_t scope_id, uint64_t now_ms);
|
||||||
|
void test_run_peer_jobs(uint64_t now_ms);
|
||||||
|
void test_loop_at(uint64_t now_ms);
|
||||||
|
size_t test_self_link_local_history_size() const {
|
||||||
|
return _self_link_local_history.size();
|
||||||
|
}
|
||||||
|
const Bytes& test_self_disco_token() const { return _self_disco_token; }
|
||||||
|
|
||||||
|
// Drive a single iteration with an injected clock. Production code
|
||||||
|
// uses the no-arg loop() which calls this with OS::ltime().
|
||||||
|
void loop_at(uint64_t now_ms);
|
||||||
|
|
||||||
|
virtual std::string toString() const override {
|
||||||
|
return "AutoInterface[" + _name + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wire-format derivation (pure, exposed for tests / external diagnostics).
|
||||||
|
// All match the Python reference (RNS/Interfaces/AutoInterface.py).
|
||||||
|
static Bytes compute_group_hash(const Bytes& group_id);
|
||||||
|
static std::string compute_multicast_address(const Bytes& group_hash,
|
||||||
|
char addr_type,
|
||||||
|
char scope);
|
||||||
|
static Bytes compute_discovery_token(const Bytes& group_id,
|
||||||
|
const std::string& link_local_addr);
|
||||||
|
|
||||||
|
protected:
|
||||||
|
friend class AutoInterfacePeer;
|
||||||
|
|
||||||
|
// Lifecycle helpers — implemented in commits 4+
|
||||||
|
bool open_sockets();
|
||||||
|
void close_sockets();
|
||||||
|
void poll_multicast();
|
||||||
|
void poll_unicast_disco();
|
||||||
|
void poll_data();
|
||||||
|
void announce_peer();
|
||||||
|
void reverse_announce(const IPv6Addr& peer_addr, uint32_t scope_id);
|
||||||
|
void peer_jobs(uint64_t now_ms);
|
||||||
|
void add_peer(const IPv6Addr& addr, uint32_t scope_id, uint64_t now_ms);
|
||||||
|
void refresh_peer(const std::string& key, uint64_t now_ms);
|
||||||
|
void route_inbound(const Bytes& data, const IPv6Addr& src);
|
||||||
|
|
||||||
|
// Map key derivation
|
||||||
|
static std::string addr_key(const IPv6Addr& addr) {
|
||||||
|
return std::string(reinterpret_cast<const char*>(addr.data()), addr.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configuration (immutable after start)
|
||||||
|
Bytes _group_id_bytes;
|
||||||
|
Bytes _group_hash;
|
||||||
|
char _addr_type;
|
||||||
|
char _scope;
|
||||||
|
uint16_t _discovery_port;
|
||||||
|
uint16_t _unicast_disco_port;
|
||||||
|
uint16_t _data_port;
|
||||||
|
uint8_t _max_peers;
|
||||||
|
uint8_t _multicast_hops;
|
||||||
|
std::string _mcast_addr_str;
|
||||||
|
IPv6Addr _mcast_addr_bin{};
|
||||||
|
|
||||||
|
// Sockets — opaque int FDs; -1 when closed
|
||||||
|
int _disco_sock = -1;
|
||||||
|
int _unicast_sock = -1;
|
||||||
|
int _data_sock = -1;
|
||||||
|
|
||||||
|
// Local link-local state
|
||||||
|
std::string _link_local_addr;
|
||||||
|
IPv6Addr _self_link_local_bin{};
|
||||||
|
uint32_t _scope_id = 0;
|
||||||
|
Bytes _self_disco_token;
|
||||||
|
// Recently rotated link-local addresses kept for self-echo
|
||||||
|
// suppression after notify_link_change(). Bounded at 4 — entries
|
||||||
|
// age out implicitly via the 22 s peer timeout if anything slips
|
||||||
|
// through.
|
||||||
|
std::deque<IPv6Addr> _self_link_local_history;
|
||||||
|
static constexpr size_t SELF_LL_HISTORY_MAX = 4;
|
||||||
|
|
||||||
|
// Peer table — keyed by 16-byte address (as std::string for cheap lookup)
|
||||||
|
struct PeerEntry {
|
||||||
|
IPv6Addr addr{};
|
||||||
|
uint32_t scope_id = 0;
|
||||||
|
uint64_t last_heard_ms = 0;
|
||||||
|
uint64_t last_outbound_ms = 0;
|
||||||
|
std::shared_ptr<AutoInterfacePeer> peer_iface;
|
||||||
|
Interface wrapper{Type::NONE};
|
||||||
|
};
|
||||||
|
std::map<std::string, PeerEntry> _peers;
|
||||||
|
|
||||||
|
// Multi-interface dedup ring
|
||||||
|
struct DedupEntry { Bytes hash; uint64_t expires_ms = 0; };
|
||||||
|
std::deque<DedupEntry> _mif_dedup;
|
||||||
|
|
||||||
|
// Pacing / state
|
||||||
|
uint64_t _next_announce_ms = 0;
|
||||||
|
uint64_t _next_peer_job_ms = 0;
|
||||||
|
uint64_t _last_mcast_echo_ms = 0;
|
||||||
|
bool _has_mcast_echo = false;
|
||||||
|
bool _final_init_done = false;
|
||||||
|
|
||||||
|
// RX scratch (single, reused across all three sockets — single-threaded).
|
||||||
|
uint8_t _rx_buf[HW_MTU + 4]{};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace RNS
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
#include "AutoInterfacePeer.h"
|
||||||
|
#include "AutoInterface.h"
|
||||||
|
|
||||||
|
#include "../Log.h"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#ifdef ARDUINO
|
||||||
|
#include <lwip/sockets.h>
|
||||||
|
#include <lwip/inet.h>
|
||||||
|
#else
|
||||||
|
#include <arpa/inet.h>
|
||||||
|
#include <netinet/in.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace RNS {
|
||||||
|
|
||||||
|
AutoInterfacePeer::AutoInterfacePeer(AutoInterface* parent,
|
||||||
|
const AutoInterface::IPv6Addr& addr,
|
||||||
|
uint32_t scope_id)
|
||||||
|
: _parent(parent),
|
||||||
|
_peer_addr(addr),
|
||||||
|
_peer_scope(scope_id)
|
||||||
|
{
|
||||||
|
_HW_MTU = AutoInterface::HW_MTU;
|
||||||
|
_FIXED_MTU = AutoInterface::FIXED_MTU;
|
||||||
|
_bitrate = AutoInterface::BITRATE_GUESS;
|
||||||
|
_IN = true;
|
||||||
|
_OUT = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
AutoInterfacePeer::~AutoInterfacePeer() {}
|
||||||
|
|
||||||
|
bool AutoInterfacePeer::start() { _online = true; return true; }
|
||||||
|
void AutoInterfacePeer::stop() { _online = false; }
|
||||||
|
void AutoInterfacePeer::loop() {} // RX driven by parent's poll_data()
|
||||||
|
|
||||||
|
void AutoInterfacePeer::send_outgoing(const Bytes& data) {
|
||||||
|
if (!_online || !_parent) return;
|
||||||
|
const int fd = _parent->_data_sock;
|
||||||
|
if (fd < 0) return;
|
||||||
|
sockaddr_in6 dst{};
|
||||||
|
dst.sin6_family = AF_INET6;
|
||||||
|
dst.sin6_port = htons(_parent->_data_port);
|
||||||
|
dst.sin6_scope_id = _peer_scope;
|
||||||
|
std::memcpy(&dst.sin6_addr, _peer_addr.data(), 16);
|
||||||
|
ssize_t n = sendto(fd, data.data(), data.size(), 0,
|
||||||
|
reinterpret_cast<sockaddr*>(&dst), sizeof(dst));
|
||||||
|
if (n > 0) {
|
||||||
|
_txb += static_cast<size_t>(n);
|
||||||
|
_parent->_txb += static_cast<size_t>(n);
|
||||||
|
handle_outgoing(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void AutoInterfacePeer::deliver_incoming(const Bytes& data) {
|
||||||
|
if (!_online) return;
|
||||||
|
handle_incoming(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string AutoInterfacePeer::toString() const {
|
||||||
|
// Lowercase RFC 5952 canonical form via inet_ntop, lowercased to match
|
||||||
|
// Python (lwIP emits uppercase). Display only — never used for hashing.
|
||||||
|
char buf[INET6_ADDRSTRLEN];
|
||||||
|
struct in6_addr a;
|
||||||
|
std::memcpy(&a, _peer_addr.data(), 16);
|
||||||
|
if (inet_ntop(AF_INET6, &a, buf, sizeof(buf)) == nullptr) {
|
||||||
|
return "AutoInterfacePeer[invalid]";
|
||||||
|
}
|
||||||
|
std::string out(buf);
|
||||||
|
for (auto& c : out) {
|
||||||
|
if (c >= 'A' && c <= 'F') c = static_cast<char>(c - 'A' + 'a');
|
||||||
|
}
|
||||||
|
return std::string("AutoInterfacePeer[") + out + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace RNS
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "../Interface.h"
|
||||||
|
#include "../Bytes.h"
|
||||||
|
#include "AutoInterface.h"
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
namespace RNS {
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Per-peer Interface spawned by AutoInterface for each discovered node.
|
||||||
|
* Registered with Transport so per-path attached_interface routing works.
|
||||||
|
* Sends outbound traffic via the parent's shared _data_sock.
|
||||||
|
*/
|
||||||
|
class AutoInterfacePeer : public InterfaceImpl {
|
||||||
|
public:
|
||||||
|
AutoInterfacePeer(AutoInterface* parent,
|
||||||
|
const AutoInterface::IPv6Addr& addr,
|
||||||
|
uint32_t scope_id);
|
||||||
|
virtual ~AutoInterfacePeer();
|
||||||
|
|
||||||
|
virtual bool start() override;
|
||||||
|
virtual void stop() override;
|
||||||
|
virtual void loop() override;
|
||||||
|
virtual void send_outgoing(const Bytes& data) override;
|
||||||
|
|
||||||
|
// Called by AutoInterface::route_inbound after dedup
|
||||||
|
void deliver_incoming(const Bytes& data);
|
||||||
|
|
||||||
|
const AutoInterface::IPv6Addr& peer_addr() const { return _peer_addr; }
|
||||||
|
uint32_t peer_scope() const { return _peer_scope; }
|
||||||
|
|
||||||
|
virtual std::string toString() const override;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
AutoInterface* _parent;
|
||||||
|
AutoInterface::IPv6Addr _peer_addr{};
|
||||||
|
uint32_t _peer_scope = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace RNS
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
// LXMF message format — MsgPack wire codec
|
||||||
|
// Shared between microReticulum (library) and Ratdeck (firmware).
|
||||||
|
// Matches Python LXMF LXMessage.py and Rust lxmf-core message.rs wire format.
|
||||||
|
#include "LXMFMessage.h"
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
static void mpPackFloat64(std::vector<uint8_t>& buf, double val) {
|
||||||
|
buf.push_back(0xCB);
|
||||||
|
uint64_t bits;
|
||||||
|
memcpy(&bits, &val, 8);
|
||||||
|
for (int i = 7; i >= 0; i--) {
|
||||||
|
buf.push_back((bits >> (i * 8)) & 0xFF);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void mpPackString(std::vector<uint8_t>& buf, const std::string& str) {
|
||||||
|
size_t len = str.size();
|
||||||
|
if (len < 32) {
|
||||||
|
buf.push_back(0xA0 | (uint8_t)len);
|
||||||
|
} else if (len < 256) {
|
||||||
|
buf.push_back(0xD9);
|
||||||
|
buf.push_back((uint8_t)len);
|
||||||
|
} else {
|
||||||
|
buf.push_back(0xDA);
|
||||||
|
buf.push_back((len >> 8) & 0xFF);
|
||||||
|
buf.push_back(len & 0xFF);
|
||||||
|
}
|
||||||
|
buf.insert(buf.end(), str.begin(), str.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgPack bin format — Python LXMF expects title/content as bytes, not str
|
||||||
|
static void mpPackBin(std::vector<uint8_t>& buf, const std::string& str) {
|
||||||
|
size_t len = str.size();
|
||||||
|
if (len < 256) {
|
||||||
|
buf.push_back(0xC4);
|
||||||
|
buf.push_back((uint8_t)len);
|
||||||
|
} else {
|
||||||
|
buf.push_back(0xC5);
|
||||||
|
buf.push_back((len >> 8) & 0xFF);
|
||||||
|
buf.push_back(len & 0xFF);
|
||||||
|
}
|
||||||
|
buf.insert(buf.end(), str.begin(), str.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool mpReadFloat64(const uint8_t* data, size_t len, size_t& pos, double& val) {
|
||||||
|
if (pos >= len || data[pos] != 0xCB) return false;
|
||||||
|
pos++;
|
||||||
|
if (pos + 8 > len) return false;
|
||||||
|
uint64_t bits = 0;
|
||||||
|
for (int i = 0; i < 8; i++) { bits = (bits << 8) | data[pos++]; }
|
||||||
|
memcpy(&val, &bits, 8);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool mpReadString(const uint8_t* data, size_t len, size_t& pos, std::string& str) {
|
||||||
|
if (pos >= len) return false;
|
||||||
|
uint8_t b = data[pos];
|
||||||
|
size_t slen = 0;
|
||||||
|
// MsgPack str formats
|
||||||
|
if ((b & 0xE0) == 0xA0) { slen = b & 0x1F; pos++; }
|
||||||
|
else if (b == 0xD9) { pos++; if (pos >= len) return false; slen = data[pos++]; }
|
||||||
|
else if (b == 0xDA) { pos++; if (pos + 2 > len) return false; slen = ((size_t)data[pos] << 8) | data[pos + 1]; pos += 2; }
|
||||||
|
// MsgPack bin formats (Python LXMF sends title/content as bin)
|
||||||
|
else if (b == 0xC4) { pos++; if (pos >= len) return false; slen = data[pos++]; }
|
||||||
|
else if (b == 0xC5) { pos++; if (pos + 2 > len) return false; slen = ((size_t)data[pos] << 8) | data[pos + 1]; pos += 2; }
|
||||||
|
else return false;
|
||||||
|
if (pos + slen > len) return false;
|
||||||
|
str.assign((const char*)&data[pos], slen);
|
||||||
|
pos += slen;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool mpSkipValue(const uint8_t* data, size_t len, size_t& pos) {
|
||||||
|
if (pos >= len) return false;
|
||||||
|
uint8_t b = data[pos];
|
||||||
|
if ((b & 0xE0) == 0xA0) { pos += 1 + (b & 0x1F); return pos <= len; }
|
||||||
|
if ((b & 0xF0) == 0x80) { size_t c = b & 0x0F; pos++; for (size_t i = 0; i < c * 2; i++) { if (!mpSkipValue(data, len, pos)) return false; } return true; }
|
||||||
|
if ((b & 0xF0) == 0x90) { size_t c = b & 0x0F; pos++; for (size_t i = 0; i < c; i++) { if (!mpSkipValue(data, len, pos)) return false; } return true; }
|
||||||
|
if (b == 0xCB) { pos += 9; return pos <= len; }
|
||||||
|
if (b == 0xD9) { if (pos + 2 > len) return false; size_t s = data[pos + 1]; pos += 2 + s; return pos <= len; }
|
||||||
|
if (b == 0xDA) { if (pos + 3 > len) return false; size_t s = ((size_t)data[pos+1] << 8) | data[pos+2]; pos += 3 + s; return pos <= len; }
|
||||||
|
if ((b & 0x80) == 0x00 || (b & 0xE0) == 0xE0 || b == 0xC0 || b == 0xC2 || b == 0xC3) { pos++; return true; }
|
||||||
|
if (b == 0xCC || b == 0xD0) { pos += 2; return pos <= len; }
|
||||||
|
if (b == 0xCD || b == 0xD1) { pos += 3; return pos <= len; }
|
||||||
|
if (b == 0xCE || b == 0xD2 || b == 0xCA) { pos += 5; return pos <= len; }
|
||||||
|
if (b == 0xCF || b == 0xD3) { pos += 9; return pos <= len; }
|
||||||
|
if (b == 0xC4) { if (pos + 2 > len) return false; pos += 2 + data[pos+1]; return pos <= len; }
|
||||||
|
if (b == 0xC5) { if (pos + 3 > len) return false; pos += 3 + (((size_t)data[pos+1] << 8) | data[pos+2]); return pos <= len; }
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<uint8_t> LXMFMessage::packContent(double timestamp, const std::string& content, const std::string& title) {
|
||||||
|
std::vector<uint8_t> buf;
|
||||||
|
buf.reserve(32 + content.size() + title.size());
|
||||||
|
buf.push_back(0x94);
|
||||||
|
mpPackFloat64(buf, timestamp);
|
||||||
|
mpPackBin(buf, title); // LXMF spec: [ts, title, content, fields] — must be bin, not str
|
||||||
|
mpPackBin(buf, content);
|
||||||
|
buf.push_back(0x80);
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<uint8_t> LXMFMessage::packFull(const RNS::Identity& signingIdentity) {
|
||||||
|
std::vector<uint8_t> packed = packContent(timestamp, content, title);
|
||||||
|
if (sourceHash.size() < 16 || destHash.size() < 16) return {};
|
||||||
|
|
||||||
|
// Sign: dest_hash || source_hash || packed_content || message_hash (LXMF spec)
|
||||||
|
std::vector<uint8_t> hashed_part;
|
||||||
|
hashed_part.reserve(32 + packed.size());
|
||||||
|
hashed_part.insert(hashed_part.end(), destHash.data(), destHash.data() + 16);
|
||||||
|
hashed_part.insert(hashed_part.end(), sourceHash.data(), sourceHash.data() + 16);
|
||||||
|
hashed_part.insert(hashed_part.end(), packed.begin(), packed.end());
|
||||||
|
|
||||||
|
RNS::Bytes hashedBytes(hashed_part.data(), hashed_part.size());
|
||||||
|
RNS::Bytes msgHash = RNS::Identity::full_hash(hashedBytes);
|
||||||
|
|
||||||
|
// Store messageId = SHA256(dest + src + payload), matching Python LXMessage.pack()
|
||||||
|
messageId = msgHash;
|
||||||
|
|
||||||
|
std::vector<uint8_t> signed_part;
|
||||||
|
signed_part.reserve(hashed_part.size() + msgHash.size());
|
||||||
|
signed_part.insert(signed_part.end(), hashed_part.begin(), hashed_part.end());
|
||||||
|
signed_part.insert(signed_part.end(), msgHash.data(), msgHash.data() + msgHash.size());
|
||||||
|
|
||||||
|
RNS::Bytes signableBytes(signed_part.data(), signed_part.size());
|
||||||
|
RNS::Bytes sig = signingIdentity.sign(signableBytes);
|
||||||
|
if (sig.size() < 64) return {};
|
||||||
|
|
||||||
|
// Wire (opportunistic): [src_hash:16][signature:64][packed_content]
|
||||||
|
// dest_hash is carried by the RNS packet header, not the LXMF payload
|
||||||
|
std::vector<uint8_t> payload;
|
||||||
|
payload.reserve(16 + 64 + packed.size());
|
||||||
|
payload.insert(payload.end(), sourceHash.data(), sourceHash.data() + 16);
|
||||||
|
payload.insert(payload.end(), sig.data(), sig.data() + 64);
|
||||||
|
payload.insert(payload.end(), packed.begin(), packed.end());
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool LXMFMessage::unpackFull(const uint8_t* data, size_t len, LXMFMessage& msg) {
|
||||||
|
// Wire: [dest_hash:16][src_hash:16][signature:64][packed_content]
|
||||||
|
if (len < 97) return false; // 16+16+64+1 minimum
|
||||||
|
msg.destHash = RNS::Bytes(data, 16);
|
||||||
|
msg.sourceHash = RNS::Bytes(data + 16, 16);
|
||||||
|
msg.signature = RNS::Bytes(data + 32, 64);
|
||||||
|
|
||||||
|
const uint8_t* content = data + 96;
|
||||||
|
size_t contentLen = len - 96;
|
||||||
|
size_t pos = 0;
|
||||||
|
|
||||||
|
if (pos >= contentLen) return false;
|
||||||
|
uint8_t arrHeader = content[pos];
|
||||||
|
if ((arrHeader & 0xF0) != 0x90) return false;
|
||||||
|
size_t arrLen = arrHeader & 0x0F;
|
||||||
|
if (arrLen < 3) return false;
|
||||||
|
pos++;
|
||||||
|
|
||||||
|
// LXMF spec: [timestamp, title, content, fields]
|
||||||
|
if (!mpReadFloat64(content, contentLen, pos, msg.timestamp)) return false;
|
||||||
|
if (!mpReadString(content, contentLen, pos, msg.title)) return false;
|
||||||
|
if (!mpReadString(content, contentLen, pos, msg.content)) return false;
|
||||||
|
if (arrLen >= 4 && pos < contentLen) { mpSkipValue(content, contentLen, pos); }
|
||||||
|
|
||||||
|
// messageId = SHA256(dest + src + packed_content), matching Python/Rust
|
||||||
|
// (skip signature at bytes 32..96)
|
||||||
|
std::vector<uint8_t> hashInput;
|
||||||
|
hashInput.reserve(32 + (len - 96));
|
||||||
|
hashInput.insert(hashInput.end(), data, data + 32); // dest_hash + src_hash
|
||||||
|
hashInput.insert(hashInput.end(), data + 96, data + len); // packed_content
|
||||||
|
RNS::Bytes hashable(hashInput.data(), hashInput.size());
|
||||||
|
msg.messageId = RNS::Identity::full_hash(hashable);
|
||||||
|
msg.incoming = true;
|
||||||
|
msg.status = LXMFStatus::DELIVERED;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* LXMFMessage::statusStr() const {
|
||||||
|
switch (status) {
|
||||||
|
case LXMFStatus::DRAFT: return "draft";
|
||||||
|
case LXMFStatus::QUEUED: return "queued";
|
||||||
|
case LXMFStatus::SENDING: return "sending";
|
||||||
|
case LXMFStatus::SENT: return "sent";
|
||||||
|
case LXMFStatus::DELIVERED: return "delivered";
|
||||||
|
case LXMFStatus::FAILED: return "failed";
|
||||||
|
default: return "?";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "Bytes.h"
|
||||||
|
#include "Identity.h"
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
enum class LXMFStatus : uint8_t {
|
||||||
|
DRAFT = 0, QUEUED, SENDING, SENT, DELIVERED, FAILED
|
||||||
|
};
|
||||||
|
|
||||||
|
struct LXMFMessage {
|
||||||
|
RNS::Bytes sourceHash;
|
||||||
|
RNS::Bytes destHash;
|
||||||
|
double timestamp = 0;
|
||||||
|
std::string content;
|
||||||
|
std::string title;
|
||||||
|
RNS::Bytes signature;
|
||||||
|
|
||||||
|
LXMFStatus status = LXMFStatus::DRAFT;
|
||||||
|
bool incoming = false;
|
||||||
|
bool read = false;
|
||||||
|
int retries = 0;
|
||||||
|
unsigned long lastRetryMs = 0;
|
||||||
|
uint32_t savedCounter = 0;
|
||||||
|
uint32_t receiveCounter = 0; // Monotonic receive order (used by Ratcom)
|
||||||
|
RNS::Bytes messageId;
|
||||||
|
|
||||||
|
static std::vector<uint8_t> packContent(double timestamp, const std::string& content, const std::string& title);
|
||||||
|
std::vector<uint8_t> packFull(const RNS::Identity& signingIdentity);
|
||||||
|
static bool unpackFull(const uint8_t* data, size_t len, LXMFMessage& msg);
|
||||||
|
const char* statusStr() const;
|
||||||
|
};
|
||||||
+207
-100
@@ -176,8 +176,10 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
|
|||||||
}
|
}
|
||||||
|
|
||||||
/*static*/ Link Link::validate_request( const Destination& owner, const Bytes& data, const Packet& packet) {
|
/*static*/ Link Link::validate_request( const Destination& owner, const Bytes& data, const Packet& packet) {
|
||||||
|
Serial.printf("[LINK-VR] validate_request: data=%d bytes\n", (int)data.size());
|
||||||
if (data.size() == ECPUBSIZE || data.size() == ECPUBSIZE + LINK_MTU_SIZE) {
|
if (data.size() == ECPUBSIZE || data.size() == ECPUBSIZE + LINK_MTU_SIZE) {
|
||||||
try {
|
try {
|
||||||
|
Serial.println("[LINK-VR] creating link object...");
|
||||||
Link link({Type::NONE}, nullptr, nullptr, owner, data.left(ECPUBSIZE/2), data.mid(ECPUBSIZE/2, ECPUBSIZE/2));
|
Link link({Type::NONE}, nullptr, nullptr, owner, data.left(ECPUBSIZE/2), data.mid(ECPUBSIZE/2, ECPUBSIZE/2));
|
||||||
link.set_link_id(packet);
|
link.set_link_id(packet);
|
||||||
|
|
||||||
@@ -205,14 +207,21 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
|
|||||||
VERBOSEF("Validating link request %s", link.link_id().toHex().c_str());
|
VERBOSEF("Validating link request %s", link.link_id().toHex().c_str());
|
||||||
TRACEF("Link MTU configured to %d", link.mtu());
|
TRACEF("Link MTU configured to %d", link.mtu());
|
||||||
TRACEF("Establishment timeout is %f for incoming link request %s", link.establishment_timeout(), link.link_id().toHex().c_str());
|
TRACEF("Establishment timeout is %f for incoming link request %s", link.establishment_timeout(), link.link_id().toHex().c_str());
|
||||||
|
Serial.printf("[LINK-VR] → handshake (ECDH)... heap=%d\n", (int)ESP.getFreeHeap());
|
||||||
link.handshake();
|
link.handshake();
|
||||||
|
Serial.println("[LINK-VR] ← handshake done");
|
||||||
link.attached_interface(packet.receiving_interface());
|
link.attached_interface(packet.receiving_interface());
|
||||||
|
Serial.println("[LINK-VR] → prove (Ed25519 sign + send)...");
|
||||||
link.prove();
|
link.prove();
|
||||||
|
Serial.println("[LINK-VR] ← prove done");
|
||||||
link.request_time(OS::time());
|
link.request_time(OS::time());
|
||||||
Transport::register_link(link);
|
Transport::register_link(link);
|
||||||
link.last_inbound(OS::time());
|
link.last_inbound(OS::time());
|
||||||
link.start_watchdog();
|
link.start_watchdog();
|
||||||
|
|
||||||
|
Serial.printf("[LINK-DIAG] Link %s accepted, rx_iface=%s\n",
|
||||||
|
link.link_id().toHex().substr(0, 16).c_str(),
|
||||||
|
packet.receiving_interface().toString().c_str());
|
||||||
DEBUGF("Incoming link request %s accepted", link.toString().c_str());
|
DEBUGF("Incoming link request %s accepted", link.toString().c_str());
|
||||||
return link;
|
return link;
|
||||||
}
|
}
|
||||||
@@ -277,16 +286,75 @@ void Link::prove() {
|
|||||||
assert(_object);
|
assert(_object);
|
||||||
DEBUGF("Link %s requesting proof", link_id().toHex().c_str());
|
DEBUGF("Link %s requesting proof", link_id().toHex().c_str());
|
||||||
Bytes signalling_bytes = Link::signalling_bytes(_object->_mtu, _object->_mode);
|
Bytes signalling_bytes = Link::signalling_bytes(_object->_mtu, _object->_mode);
|
||||||
Bytes signed_data = _object->_link_id + _object->_pub_bytes + _object->_sig_pub_bytes + signalling_bytes;
|
// Python validate_proof() reconstructs signed_data using the destination's
|
||||||
|
// identity Ed25519 key, NOT the link's ephemeral Ed25519 key.
|
||||||
|
// Reference: Python Link.py line 412:
|
||||||
|
// peer_sig_pub_bytes = self.destination.identity.get_public_key()[ECPUBSIZE//2:ECPUBSIZE]
|
||||||
|
const Bytes& owner_sig_pub = _object->_owner.identity().signingPublicKey();
|
||||||
|
Bytes signed_data = _object->_link_id + _object->_pub_bytes + owner_sig_pub + signalling_bytes;
|
||||||
const Bytes signature(_object->_owner.identity().sign(signed_data));
|
const Bytes signature(_object->_owner.identity().sign(signed_data));
|
||||||
|
|
||||||
Bytes proof_data = signature + _object->_pub_bytes + signalling_bytes;
|
Bytes proof_data = signature + _object->_pub_bytes + signalling_bytes;
|
||||||
// CBA LINK
|
|
||||||
// CBA TODO: Determine which approach is better, passing liunk to packet or passing _link_destination
|
// Diagnostic: dump proof components for cross-implementation debugging
|
||||||
|
VERBOSEF("[LINK-PROOF] link_id: %s", _object->_link_id.toHex().c_str());
|
||||||
|
VERBOSEF("[LINK-PROOF] pub_bytes: %s", _object->_pub_bytes.toHex().c_str());
|
||||||
|
VERBOSEF("[LINK-PROOF] sig_pub: %s (owner identity)", owner_sig_pub.toHex().c_str());
|
||||||
|
VERBOSEF("[LINK-PROOF] signalling: %s (mtu=%d mode=%d)", signalling_bytes.toHex().c_str(), _object->_mtu, _object->_mode);
|
||||||
|
VERBOSEF("[LINK-PROOF] signed_data: %s (%d bytes)", signed_data.toHex().c_str(), (int)signed_data.size());
|
||||||
|
VERBOSEF("[LINK-PROOF] signature: %s", signature.toHex().c_str());
|
||||||
|
VERBOSEF("[LINK-PROOF] proof_data: %d bytes", (int)proof_data.size());
|
||||||
|
|
||||||
|
// Cache proof data for retry if RTT doesn't arrive (LoRa packet loss recovery)
|
||||||
|
_object->_cached_proof_data = proof_data;
|
||||||
|
_object->_last_proof_send = OS::time();
|
||||||
|
_object->_proof_retries = 0;
|
||||||
|
|
||||||
|
// Small random delay to reduce collision on half-duplex radio links.
|
||||||
|
// Only apply for non-TCP interfaces (LoRa, etc.) where TX collision is real.
|
||||||
|
if (_object->_attached_interface
|
||||||
|
&& _object->_attached_interface.toString().find("TCP") == std::string::npos) {
|
||||||
|
delay(random(50, 200));
|
||||||
|
}
|
||||||
|
|
||||||
Packet proof(*this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
|
Packet proof(*this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
|
||||||
proof.send();
|
proof.send();
|
||||||
_object->_establishment_cost += proof.raw().size();
|
_object->_establishment_cost += proof.raw().size();
|
||||||
had_outbound();
|
had_outbound();
|
||||||
|
Serial.printf("[LINK] Proof sent for %s, will retry if no RTT\n", link_id().toHex().substr(0, 16).c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void Link::retry_proof() {
|
||||||
|
assert(_object);
|
||||||
|
if (_object->_cached_proof_data.size() == 0) return;
|
||||||
|
if (_object->_status != Type::Link::HANDSHAKE) return;
|
||||||
|
|
||||||
|
double now = OS::time();
|
||||||
|
double interval = LinkData::PROOF_RETRY_INITIAL;
|
||||||
|
for (int i = 0; i < _object->_proof_retries; i++) {
|
||||||
|
interval *= LinkData::PROOF_RETRY_BACKOFF;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (now - _object->_last_proof_send >= interval) {
|
||||||
|
if (_object->_proof_retries < LinkData::MAX_PROOF_RETRIES) {
|
||||||
|
_object->_proof_retries++;
|
||||||
|
_object->_last_proof_send = now;
|
||||||
|
Serial.printf("[LINK] Retrying proof for %s (attempt %d/%d, interval %.0fs)\n",
|
||||||
|
link_id().toHex().substr(0, 16).c_str(),
|
||||||
|
_object->_proof_retries, LinkData::MAX_PROOF_RETRIES, interval);
|
||||||
|
Serial.printf("[LINK-RETRY] creating packet... heap=%d\n", (int)ESP.getFreeHeap());
|
||||||
|
Packet proof(*this, _object->_cached_proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
|
||||||
|
Serial.println("[LINK-RETRY] → proof.send()...");
|
||||||
|
proof.send();
|
||||||
|
Serial.println("[LINK-RETRY] ← proof.send() done");
|
||||||
|
had_outbound();
|
||||||
|
Serial.println("[LINK-RETRY] complete");
|
||||||
|
} else {
|
||||||
|
Serial.printf("[LINK] Proof retries exhausted for %s, tearing down\n",
|
||||||
|
link_id().toHex().substr(0, 16).c_str());
|
||||||
|
teardown();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void Link::prove_packet(const Packet& packet) {
|
void Link::prove_packet(const Packet& packet) {
|
||||||
@@ -503,6 +571,10 @@ void Link::update_mdu() {
|
|||||||
|
|
||||||
void Link::rtt_packet(const Packet& packet) {
|
void Link::rtt_packet(const Packet& packet) {
|
||||||
assert(_object);
|
assert(_object);
|
||||||
|
Serial.printf("[LINK-DIAG] RTT packet received! link=%s (after %d proof retries)\n",
|
||||||
|
link_id().toHex().substr(0, 16).c_str(), _object->_proof_retries);
|
||||||
|
// Clear cached proof — handshake complete, no more retries needed
|
||||||
|
_object->_cached_proof_data = Bytes();
|
||||||
try {
|
try {
|
||||||
double measured_rtt = OS::time() - _object->_request_time;
|
double measured_rtt = OS::time() - _object->_request_time;
|
||||||
const Bytes plaintext(decrypt(packet.data()));
|
const Bytes plaintext(decrypt(packet.data()));
|
||||||
@@ -1000,7 +1072,15 @@ void Link::receive(const Packet& packet) {
|
|||||||
_object->_watchdog_lock = true;
|
_object->_watchdog_lock = true;
|
||||||
if (_object->_status != Type::Link::CLOSED && !(_object->_initiator && packet.context() == Type::Packet::KEEPALIVE && packet.data() == "\xFF")) {
|
if (_object->_status != Type::Link::CLOSED && !(_object->_initiator && packet.context() == Type::Packet::KEEPALIVE && packet.data() == "\xFF")) {
|
||||||
if (packet.receiving_interface() != _object->_attached_interface) {
|
if (packet.receiving_interface() != _object->_attached_interface) {
|
||||||
ERROR("Link-associated packet received on unexpected interface! Someone might be trying to manipulate your communication!");
|
ERRORF("Link packet on WRONG interface! rx=%s attached=%s ctx=0x%02X",
|
||||||
|
packet.receiving_interface().toString().c_str(),
|
||||||
|
_object->_attached_interface.toString().c_str(),
|
||||||
|
(int)packet.context());
|
||||||
|
Serial.printf("[LINK-DIAG] INTERFACE MISMATCH! rx=%s attached=%s link=%s ctx=0x%02X\n",
|
||||||
|
packet.receiving_interface().toString().c_str(),
|
||||||
|
_object->_attached_interface.toString().c_str(),
|
||||||
|
link_id().toHex().substr(0, 16).c_str(),
|
||||||
|
(int)packet.context());
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
_object->_last_inbound = OS::time();
|
_object->_last_inbound = OS::time();
|
||||||
@@ -1014,26 +1094,31 @@ void Link::receive(const Packet& packet) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (packet.packet_type() == Type::Packet::DATA) {
|
if (packet.packet_type() == Type::Packet::DATA) {
|
||||||
|
Serial.printf("[LINK-RX] DATA ctx=0x%02X data=%d bytes heap=%d\n",
|
||||||
|
(int)packet.context(), (int)packet.data().size(), (int)ESP.getFreeHeap());
|
||||||
bool should_query = false;
|
bool should_query = false;
|
||||||
switch (packet.context()) {
|
switch (packet.context()) {
|
||||||
case Type::Packet::CONTEXT_NONE:
|
case Type::Packet::CONTEXT_NONE:
|
||||||
{
|
{
|
||||||
|
Serial.println("[LINK-RX] → link decrypt...");
|
||||||
const Bytes plaintext = decrypt(packet.data());
|
const Bytes plaintext = decrypt(packet.data());
|
||||||
if (plaintext) {
|
if (plaintext) {
|
||||||
|
Serial.printf("[LINK-RX] decrypt OK, %d bytes\n", (int)plaintext.size());
|
||||||
if (_object->_callbacks._packet) {
|
if (_object->_callbacks._packet) {
|
||||||
//z thread = threading.Thread(target=_object->_callbacks.packet, args=(plaintext, packet))
|
|
||||||
//z thread.daemon = True
|
|
||||||
//z thread.start()
|
|
||||||
try {
|
try {
|
||||||
|
Serial.println("[LINK-RX] → packet callback...");
|
||||||
_object->_callbacks._packet(plaintext, packet);
|
_object->_callbacks._packet(plaintext, packet);
|
||||||
|
Serial.println("[LINK-RX] ← packet callback done");
|
||||||
}
|
}
|
||||||
catch (std::exception& e) {
|
catch (std::exception& e) {
|
||||||
ERRORF("Error while executing packet callback from %s. The contained exception was: %s", toString().c_str(), e.what());
|
ERRORF("Error while executing packet callback from %s. The contained exception was: %s", toString().c_str(), e.what());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (_object->_destination.proof_strategy() == Type::Destination::PROVE_ALL) {
|
if (_object->_destination.proof_strategy() == Type::Destination::PROVE_ALL) {
|
||||||
|
Serial.println("[LINK-RX] → prove_packet...");
|
||||||
const_cast<Packet&>(packet).prove();
|
const_cast<Packet&>(packet).prove();
|
||||||
|
Serial.println("[LINK-RX] ← prove_packet done");
|
||||||
should_query = true;
|
should_query = true;
|
||||||
}
|
}
|
||||||
else if (_object->_destination.proof_strategy() == Type::Destination::PROVE_APP) {
|
else if (_object->_destination.proof_strategy() == Type::Destination::PROVE_APP) {
|
||||||
@@ -1054,6 +1139,7 @@ void Link::receive(const Packet& packet) {
|
|||||||
}
|
}
|
||||||
case Type::Packet::LINKIDENTIFY:
|
case Type::Packet::LINKIDENTIFY:
|
||||||
{
|
{
|
||||||
|
Serial.printf("[LINK-RX] LINKIDENTIFY %d bytes\n", (int)packet.data().size());
|
||||||
const Bytes plaintext = decrypt(packet.data());
|
const Bytes plaintext = decrypt(packet.data());
|
||||||
if (plaintext) {
|
if (plaintext) {
|
||||||
if (!(_object->_initiator) && plaintext.size() == Type::Identity::KEYSIZE/8 + Type::Identity::SIGLENGTH/8) {
|
if (!(_object->_initiator) && plaintext.size() == Type::Identity::KEYSIZE/8 + Type::Identity::SIGLENGTH/8) {
|
||||||
@@ -1141,98 +1227,81 @@ void Link::receive(const Packet& packet) {
|
|||||||
teardown_packet(packet);
|
teardown_packet(packet);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
/*z
|
|
||||||
case Type::Packet::RESOURCE_ADV:
|
case Type::Packet::RESOURCE_ADV:
|
||||||
{
|
{
|
||||||
//p packet.plaintext = decrypt(packet.data)
|
Serial.printf("[LINK-RX] RESOURCE_ADV %d bytes heap=%d\n",
|
||||||
|
(int)packet.data().size(), (int)ESP.getFreeHeap());
|
||||||
|
// Resource advertisement — decrypt and accept if strategy allows
|
||||||
const Bytes plaintext = decrypt(packet.data());
|
const Bytes plaintext = decrypt(packet.data());
|
||||||
if (plaintext) {
|
if (plaintext) {
|
||||||
const_cast<Packet&>(packet).plaintext(plaintext);
|
ResourceAdvertisement adv;
|
||||||
if (ResourceAdvertisement::is_request(packet)) {
|
if (ResourceAdvertisement::unpack(plaintext, adv)) {
|
||||||
Resource::accept(packet, callback=_object->_request_resource_concluded);
|
if (_object->_resource_strategy == Type::Link::ACCEPT_ALL
|
||||||
}
|
|| _object->_resource_strategy == Type::Link::ACCEPT_APP) {
|
||||||
else if (ResourceAdvertisement::is_response(packet)) {
|
// Accept the resource
|
||||||
Bytes request_id = ResourceAdvertisement::read_request_id(packet)
|
auto inbound = std::make_shared<InboundResource>();
|
||||||
for (auto& pending_request : _object->_pending_requests) {
|
if (inbound->init(adv, *this)) {
|
||||||
if (pending_request.request_id == request_id) {
|
_object->_inbound_resources.push_back(inbound);
|
||||||
const Bytes response_resource = Resource::accept(packet, callback=_object->_response_resource_concluded, progress_callback=pending_request.response_resource_progress, request_id = request_id);
|
// Send initial request
|
||||||
if (response_resource) {
|
Bytes req = inbound->get_initial_request();
|
||||||
//p if pending_request.response_size == None:
|
if (req.size() > 0) {
|
||||||
if (pending_request.response_size == 0) {
|
Bytes encrypted = encrypt(req);
|
||||||
pending_request.response_size = ResourceAdvertisement::read_size(packet);
|
if (encrypted) {
|
||||||
|
Packet req_packet(*this, encrypted, Type::Packet::DATA, Type::Packet::RESOURCE_REQ);
|
||||||
|
req_packet.send();
|
||||||
|
had_outbound(true);
|
||||||
}
|
}
|
||||||
//p if pending_request.response_transfer_size == None:
|
|
||||||
if (pending_request.response_transfer_size == 0) {
|
|
||||||
pending_request.response_transfer_size = 0;
|
|
||||||
}
|
|
||||||
pending_request.response_transfer_size += ResourceAdvertisement::read_transfer_size(packet);
|
|
||||||
//p if pending_request.started_at == None:
|
|
||||||
if (pending_request.started_at == 0.0) {
|
|
||||||
pending_request.started_at = OS::time();
|
|
||||||
}
|
|
||||||
pending_request.response_resource_progress(response_resource);
|
|
||||||
}
|
}
|
||||||
|
DEBUGF("Accepted inbound resource, %d parts", (int)adv.num_parts);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (_object->_resource_strategy == ACCEPT_NONE) {
|
}
|
||||||
//p pass
|
|
||||||
}
|
|
||||||
else if (_object->_resource_strategy == ACCEPT_APP) {
|
|
||||||
if (_object->_callbacks.resource) {
|
|
||||||
try {
|
|
||||||
resource_advertisement = RNS.ResourceAdvertisement.unpack(packet.plaintext());
|
|
||||||
resource_advertisement.link = *this;
|
|
||||||
if (_object->_callbacks.resource(resource_advertisement)) {
|
|
||||||
Resource::accept(packet, _object->_callbacks.resource_concluded);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (std::exception& e) {
|
|
||||||
ERRORF("Error while executing resource accept callback from %s. The contained exception was: %s", toString().c_str(), e.what());
|
|
||||||
}
|
|
||||||
elif _object->_resource_strategy == ACCEPT_ALL:
|
|
||||||
RNS.Resource.accept(packet, _object->_callbacks.resource_concluded)
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case Type::Packet::RESOURCE_REQ:
|
case Type::Packet::RESOURCE_REQ:
|
||||||
{
|
{
|
||||||
|
// Resource request from receiver — send requested parts
|
||||||
const Bytes plaintext = decrypt(packet.data());
|
const Bytes plaintext = decrypt(packet.data());
|
||||||
if (plaintext) {
|
if (plaintext) {
|
||||||
if ord(plaintext[:1]) == RNS.Resource.HASHMAP_IS_EXHAUSTED:
|
for (auto& resource : _object->_outbound_resources) {
|
||||||
resource_hash = plaintext[1+RNS.Resource.MAPHASH_LEN:Type::Identity::HASHLENGTH//8+1+RNS.Resource.MAPHASH_LEN]
|
auto indices = resource->handle_request(plaintext);
|
||||||
else:
|
for (size_t idx : indices) {
|
||||||
resource_hash = plaintext[1:Type::Identity::HASHLENGTH//8+1]
|
Bytes part = resource->get_part(idx);
|
||||||
|
if (part.size() > 0) {
|
||||||
for resource in _object->_outgoing_resources:
|
// Resource parts are NOT link-encrypted (already encrypted at resource level)
|
||||||
if resource.hash == resource_hash:
|
Packet part_packet(*this, part, Type::Packet::DATA, Type::Packet::RESOURCE);
|
||||||
// We need to check that this request has not been
|
part_packet.send();
|
||||||
// received before in order to avoid sequencing errors.
|
had_outbound(true);
|
||||||
if not packet.packet_hash in resource.req_hashlist:
|
}
|
||||||
resource.req_hashlist.append(packet.packet_hash)
|
}
|
||||||
resource.request(plaintext)
|
}
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case Type::Packet::RESOURCE_HMU:
|
case Type::Packet::RESOURCE_HMU:
|
||||||
{
|
{
|
||||||
const Bytes plaintext = decrypt(packet.data());
|
// Hashmap update from receiver — currently not needed for basic transfer
|
||||||
if (plaintext) {
|
// (receiver sends ResourceReq which handles the same purpose)
|
||||||
resource_hash = plaintext[:Type::Identity::HASHLENGTH//8]
|
|
||||||
for resource in _object->_incoming_resources:
|
|
||||||
if resource_hash == resource.hash:
|
|
||||||
resource.hashmap_update_packet(plaintext)
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case Type::Packet::RESOURCE_ICL:
|
case Type::Packet::RESOURCE_ICL:
|
||||||
{
|
{
|
||||||
|
// Initiator cancel — remove matching inbound resource
|
||||||
const Bytes plaintext = decrypt(packet.data());
|
const Bytes plaintext = decrypt(packet.data());
|
||||||
if (plaintext) {
|
if (plaintext && plaintext.size() >= 32) {
|
||||||
resource_hash = plaintext[:Type::Identity::HASHLENGTH//8]
|
Bytes resource_hash = plaintext.left(32);
|
||||||
for resource in _object->_incoming_resources:
|
_object->_inbound_resources.erase(
|
||||||
if resource_hash == resource.hash:
|
std::remove_if(_object->_inbound_resources.begin(),
|
||||||
resource.cancel()
|
_object->_inbound_resources.end(),
|
||||||
|
[&](const auto& r) {
|
||||||
|
return memcmp(r->resource_hash(), resource_hash.data(), 32) == 0;
|
||||||
|
}),
|
||||||
|
_object->_inbound_resources.end()
|
||||||
|
);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
case Type::Packet::KEEPALIVE:
|
case Type::Packet::KEEPALIVE:
|
||||||
{
|
{
|
||||||
if (!_object->_initiator && packet.data() == "\xFF") {
|
if (!_object->_initiator && packet.data() == "\xFF") {
|
||||||
@@ -1249,36 +1318,46 @@ void Link::receive(const Packet& packet) {
|
|||||||
// of hash -> sequence map
|
// of hash -> sequence map
|
||||||
case Type::Packet::RESOURCE:
|
case Type::Packet::RESOURCE:
|
||||||
{
|
{
|
||||||
for (auto& resource : _object->_incoming_resources) {
|
// Resource data part — NOT link-encrypted (encrypted at resource level)
|
||||||
//z resource.receive_part(packet);
|
for (auto& resource : _object->_inbound_resources) {
|
||||||
|
if (resource->receive_part(packet.data())) {
|
||||||
|
if (resource->is_complete()) {
|
||||||
|
// Assemble the resource
|
||||||
|
Bytes assembled = resource->assemble(*this);
|
||||||
|
if (assembled.size() > 0) {
|
||||||
|
// Send proof back
|
||||||
|
Bytes proof = resource->generate_proof();
|
||||||
|
if (proof.size() > 0) {
|
||||||
|
Bytes encrypted_proof = encrypt(proof);
|
||||||
|
if (encrypted_proof) {
|
||||||
|
Packet proof_packet(*this, encrypted_proof, Type::Packet::PROOF, Type::Packet::RESOURCE_PRF);
|
||||||
|
proof_packet.send();
|
||||||
|
had_outbound(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Store assembled data for later retrieval
|
||||||
|
_object->_last_resource_data = assembled;
|
||||||
|
DEBUGF("Inbound resource complete, %d bytes assembled", (int)assembled.size());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
/*z
|
// CHANNEL case — not yet implemented
|
||||||
case Type::Packet::CHANNEL:
|
// case Type::Packet::CHANNEL: { break; }
|
||||||
{
|
} // end switch(context)
|
||||||
//z if (!_object->_channel) {
|
} // end if(DATA)
|
||||||
if (true) {
|
|
||||||
DEBUG(f"Channel data received without open channel")
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
//z packet.prove();
|
|
||||||
//z plaintext = decrypt(packet.data());
|
|
||||||
//z if (plaintext) {
|
|
||||||
//z _object->_channel._receive(plaintext);
|
|
||||||
//z }
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
*/
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (packet.packet_type() == Type::Packet::PROOF) {
|
else if (packet.packet_type() == Type::Packet::PROOF) {
|
||||||
if (packet.context() == Type::Packet::RESOURCE_PRF) {
|
if (packet.context() == Type::Packet::RESOURCE_PRF) {
|
||||||
Bytes resource_hash = packet.data().left(Type::Identity::HASHLENGTH/8);
|
const Bytes plaintext = decrypt(packet.data());
|
||||||
for (const auto& resource : _object->_outgoing_resources) {
|
if (plaintext) {
|
||||||
if (resource_hash == resource.hash()) {
|
for (auto& resource : _object->_outbound_resources) {
|
||||||
//z resource.validate_proof(packet.data());
|
if (resource->handle_proof(plaintext)) {
|
||||||
|
DEBUG("Outbound resource proof validated");
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1445,7 +1524,30 @@ void Link::cancel_incoming_resource(const Resource& resource) {
|
|||||||
|
|
||||||
bool Link::ready_for_new_resource() {
|
bool Link::ready_for_new_resource() {
|
||||||
assert(_object);
|
assert(_object);
|
||||||
return (_object->_outgoing_resources.size() > 0);
|
return (_object->_outbound_resources.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Link::start_resource_transfer(const Bytes& data) {
|
||||||
|
assert(_object);
|
||||||
|
if (!ready_for_new_resource()) return false;
|
||||||
|
|
||||||
|
auto resource = std::make_shared<OutboundResource>();
|
||||||
|
if (!resource->init(data, *this, true)) return false;
|
||||||
|
|
||||||
|
// Send advertisement
|
||||||
|
ResourceAdvertisement adv = resource->get_advertisement();
|
||||||
|
Bytes adv_packed = adv.pack();
|
||||||
|
Bytes encrypted_adv = encrypt(adv_packed);
|
||||||
|
if (!encrypted_adv) return false;
|
||||||
|
|
||||||
|
Packet adv_packet(*this, encrypted_adv, Type::Packet::DATA, Type::Packet::RESOURCE_ADV);
|
||||||
|
adv_packet.send();
|
||||||
|
had_outbound(true);
|
||||||
|
|
||||||
|
_object->_outbound_resources.push_back(resource);
|
||||||
|
DEBUGF("Started outbound resource transfer, %d parts, %d bytes",
|
||||||
|
(int)resource->num_parts(), (int)adv.transfer_size);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Link::toString() const {
|
std::string Link::toString() const {
|
||||||
@@ -1542,6 +1644,11 @@ void Link::destination(const Destination& destination) {
|
|||||||
_object->_destination = destination;
|
_object->_destination = destination;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const Interface& Link::attached_interface() const {
|
||||||
|
assert(_object);
|
||||||
|
return _object->_attached_interface;
|
||||||
|
}
|
||||||
|
|
||||||
void Link::attached_interface(const Interface& interface) {
|
void Link::attached_interface(const Interface& interface) {
|
||||||
assert(_object);
|
assert(_object);
|
||||||
_object->_attached_interface = interface;
|
_object->_attached_interface = interface;
|
||||||
|
|||||||
+8
-1
@@ -130,7 +130,7 @@ namespace RNS {
|
|||||||
friend class Link;
|
friend class Link;
|
||||||
};
|
};
|
||||||
|
|
||||||
public:
|
private:
|
||||||
static uint8_t resource_strategies;
|
static uint8_t resource_strategies;
|
||||||
static std::set<RNS::Type::Link::link_mode> ENABLED_MODES;
|
static std::set<RNS::Type::Link::link_mode> ENABLED_MODES;
|
||||||
static RNS::Type::Link::link_mode MODE_DEFAULT;
|
static RNS::Type::Link::link_mode MODE_DEFAULT;
|
||||||
@@ -174,6 +174,7 @@ namespace RNS {
|
|||||||
void set_link_id(const Packet& packet);
|
void set_link_id(const Packet& packet);
|
||||||
void handshake();
|
void handshake();
|
||||||
void prove();
|
void prove();
|
||||||
|
void retry_proof();
|
||||||
void prove_packet(const Packet& packet);
|
void prove_packet(const Packet& packet);
|
||||||
void validate_proof(const Packet& packet);
|
void validate_proof(const Packet& packet);
|
||||||
void identify(const Identity& identity);
|
void identify(const Identity& identity);
|
||||||
@@ -226,6 +227,10 @@ namespace RNS {
|
|||||||
void cancel_incoming_resource(const Resource& resource);
|
void cancel_incoming_resource(const Resource& resource);
|
||||||
bool ready_for_new_resource();
|
bool ready_for_new_resource();
|
||||||
|
|
||||||
|
/// Start an outbound resource transfer (for large messages).
|
||||||
|
/// Encrypts data, chunks, computes hashmap, sends advertisement.
|
||||||
|
bool start_resource_transfer(const Bytes& data);
|
||||||
|
|
||||||
//void __str__();
|
//void __str__();
|
||||||
std::string toString() const;
|
std::string toString() const;
|
||||||
|
|
||||||
@@ -265,6 +270,8 @@ namespace RNS {
|
|||||||
protected:
|
protected:
|
||||||
std::shared_ptr<LinkData> _object;
|
std::shared_ptr<LinkData> _object;
|
||||||
|
|
||||||
|
// CBA For access to private static members by LinkData class
|
||||||
|
friend class LinkData;
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
+15
-2
@@ -13,6 +13,8 @@
|
|||||||
#include "Cryptography/Token.h"
|
#include "Cryptography/Token.h"
|
||||||
|
|
||||||
#include <set>
|
#include <set>
|
||||||
|
#include <vector>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
namespace RNS {
|
namespace RNS {
|
||||||
|
|
||||||
@@ -75,6 +77,14 @@ namespace RNS {
|
|||||||
float _expected_rate = 0.0;
|
float _expected_rate = 0.0;
|
||||||
Type::Link::teardown_reason _teardown_reason = Type::Link::TEARDOWN_NONE;
|
Type::Link::teardown_reason _teardown_reason = Type::Link::TEARDOWN_NONE;
|
||||||
|
|
||||||
|
// Link proof retry state (responder side: resend proof if RTT not received)
|
||||||
|
Bytes _cached_proof_data;
|
||||||
|
double _last_proof_send = 0.0;
|
||||||
|
int _proof_retries = 0;
|
||||||
|
static constexpr int MAX_PROOF_RETRIES = 3;
|
||||||
|
static constexpr double PROOF_RETRY_INITIAL = 2.0; // seconds before first retry
|
||||||
|
static constexpr double PROOF_RETRY_BACKOFF = 2.0; // multiplier per retry
|
||||||
|
|
||||||
Cryptography::Token::Ptr _token;
|
Cryptography::Token::Ptr _token;
|
||||||
|
|
||||||
Cryptography::X25519PrivateKey::Ptr _prv;
|
Cryptography::X25519PrivateKey::Ptr _prv;
|
||||||
@@ -98,8 +108,11 @@ namespace RNS {
|
|||||||
Bytes _shared_key;
|
Bytes _shared_key;
|
||||||
Bytes _derived_key;
|
Bytes _derived_key;
|
||||||
|
|
||||||
std::set<Resource> _incoming_resources;
|
std::set<Resource> _incoming_resources; // Legacy (compatibility)
|
||||||
std::set<Resource> _outgoing_resources;
|
std::set<Resource> _outgoing_resources; // Legacy (compatibility)
|
||||||
|
std::vector<std::shared_ptr<InboundResource>> _inbound_resources;
|
||||||
|
std::vector<std::shared_ptr<OutboundResource>> _outbound_resources;
|
||||||
|
Bytes _last_resource_data; // Most recently assembled resource data
|
||||||
std::set<RNS::RequestReceipt> _pending_requests;
|
std::set<RNS::RequestReceipt> _pending_requests;
|
||||||
|
|
||||||
friend class Link;
|
friend class Link;
|
||||||
|
|||||||
+1
-1
@@ -72,7 +72,7 @@ LogLevel RNS::loglevel() {
|
|||||||
return _level;
|
return _level;
|
||||||
}
|
}
|
||||||
|
|
||||||
void RNS::setLogCallback(log_callback on_log /*= nullptr*/) {
|
void RNS::set_log_callback(log_callback on_log /*= nullptr*/) {
|
||||||
_on_log = on_log;
|
_on_log = on_log;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,32 @@
|
|||||||
|
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
#else
|
||||||
|
// Native-target shims: debug instrumentation in Transport/Destination/Link uses
|
||||||
|
// Arduino's `Serial`, `millis()`, `delay()`, `random()`, and ESP32's
|
||||||
|
// `ESP.getFreeHeap()`. Provide no-op stand-ins so the same code compiles
|
||||||
|
// cleanly on the native unit-test target.
|
||||||
|
#include <cstddef>
|
||||||
|
namespace _rns_native_compat {
|
||||||
|
struct SerialShim {
|
||||||
|
template<class... A> void print(A&&...) {}
|
||||||
|
template<class... A> void println(A&&...) {}
|
||||||
|
template<class... A> void printf(A&&...) {}
|
||||||
|
void flush() {}
|
||||||
|
void begin(int) {}
|
||||||
|
};
|
||||||
|
struct ESPShim {
|
||||||
|
size_t getFreeHeap() const { return 0; }
|
||||||
|
size_t getFreePsram() const { return 0; }
|
||||||
|
size_t getPsramSize() const { return 0; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
inline _rns_native_compat::SerialShim Serial;
|
||||||
|
inline _rns_native_compat::ESPShim ESP;
|
||||||
|
inline unsigned long millis() { return 0; }
|
||||||
|
inline void delay(unsigned long) {}
|
||||||
|
inline long random(long min, long max) { return min; }
|
||||||
|
inline long random(long max) { return 0; }
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#include <stdarg.h>
|
#include <stdarg.h>
|
||||||
@@ -75,7 +101,7 @@ namespace RNS {
|
|||||||
void loglevel(LogLevel level);
|
void loglevel(LogLevel level);
|
||||||
LogLevel loglevel();
|
LogLevel loglevel();
|
||||||
|
|
||||||
void setLogCallback(log_callback on_log = nullptr);
|
void set_log_callback(log_callback on_log = nullptr);
|
||||||
|
|
||||||
void doLog(LogLevel level, const char* msg);
|
void doLog(LogLevel level, const char* msg);
|
||||||
inline void doLog(LogLevel level, const char* msg, va_list vlist) { char buf[RNS_LOG_BUFFER_SIZE]; vsnprintf(buf, sizeof(buf), msg, vlist); doLog(level, buf); }
|
inline void doLog(LogLevel level, const char* msg, va_list vlist) { char buf[RNS_LOG_BUFFER_SIZE]; vsnprintf(buf, sizeof(buf), msg, vlist); doLog(level, buf); }
|
||||||
|
|||||||
+26
-5
@@ -68,6 +68,11 @@ Packet::Packet(const Link& link, const Bytes& data, Type::Packet::types packet_t
|
|||||||
TRACE("Creating packet with link...");
|
TRACE("Creating packet with link...");
|
||||||
_object->_destination_link = link;
|
_object->_destination_link = link;
|
||||||
_object->_MTU = link.mtu();
|
_object->_MTU = link.mtu();
|
||||||
|
// Route all link packets through the interface the link was established on.
|
||||||
|
// This ensures TCP links stay on TCP, LoRa links stay on LoRa, etc.
|
||||||
|
if (link.attached_interface()) {
|
||||||
|
_object->_attached_interface = link.attached_interface();
|
||||||
|
}
|
||||||
// CBA HACK: Need to re-build packed flags since Link was assigned
|
// CBA HACK: Need to re-build packed flags since Link was assigned
|
||||||
_object->_flags = get_packed_flags();
|
_object->_flags = get_packed_flags();
|
||||||
MEMF("Packet link object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
MEMF("Packet link object created, this: %p, data: %p", (void*)this, (void*)_object.get());
|
||||||
@@ -336,11 +341,12 @@ TRACEF("***** Link data: %s", _object->_ciphertext.toHex().c_str());
|
|||||||
_object->_ciphertext = _object->_destination.encrypt(_object->_data);
|
_object->_ciphertext = _object->_destination.encrypt(_object->_data);
|
||||||
TRACEF("***** Destination Data: %s", _object->_ciphertext.toHex().c_str());
|
TRACEF("***** Destination Data: %s", _object->_ciphertext.toHex().c_str());
|
||||||
}
|
}
|
||||||
// CBA RATCHET
|
{
|
||||||
/*p TODO
|
Bytes ratchet_pub = Identity::get_ratchet(_object->_destination.hash());
|
||||||
if hasattr(self.destination, "latest_ratchet_id"):
|
if (ratchet_pub) {
|
||||||
self.ratchet_id = self.destination.latest_ratchet_id
|
_object->_ratchet_id = Identity::full_hash(ratchet_pub).left(Type::Identity::NAME_HASH_LENGTH/8);
|
||||||
*/
|
}
|
||||||
|
}
|
||||||
_object->_encrypted = true;
|
_object->_encrypted = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -366,6 +372,21 @@ TRACEF("***** Destination Data: %s", _object->_ciphertext.toHex().c_str());
|
|||||||
_object->_header << (uint8_t)_object->_context;
|
_object->_header << (uint8_t)_object->_context;
|
||||||
_object->_raw = _object->_header + _object->_ciphertext;
|
_object->_raw = _object->_header + _object->_ciphertext;
|
||||||
|
|
||||||
|
if (_object->_raw.size() >= 4 && _object->_packet_type == DATA) {
|
||||||
|
TRACEF("[DIAG] PACK: ht=%d tt=%d dt=%d pt=%d ctx=0x%02x flags=0x%02x raw=%dB [%02x %02x %02x %02x]",
|
||||||
|
_object->_header_type, _object->_transport_type, _object->_destination.type(),
|
||||||
|
_object->_packet_type, _object->_context, _object->_flags,
|
||||||
|
(int)_object->_raw.size(),
|
||||||
|
_object->_raw.data()[0], _object->_raw.data()[1],
|
||||||
|
_object->_raw.data()[2], _object->_raw.data()[3]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_object->_packet_type == ANNOUNCE) {
|
||||||
|
TRACEF("[ANN-DIAG] PACKED: flags=0x%02x hops=%d ctx=0x%02x raw(%d): %s",
|
||||||
|
_object->_flags, _object->_hops, _object->_context,
|
||||||
|
(int)_object->_raw.size(), _object->_raw.toHex().c_str());
|
||||||
|
}
|
||||||
|
|
||||||
if (_object->_raw.size() > _object->_MTU) {
|
if (_object->_raw.size() > _object->_MTU) {
|
||||||
throw std::length_error("Packet size of " + std::to_string(_object->_raw.size()) + " exceeds MTU of " + std::to_string(_object->_MTU) +" bytes");
|
throw std::length_error("Packet size of " + std::to_string(_object->_raw.size()) + " exceeds MTU of " + std::to_string(_object->_MTU) +" bytes");
|
||||||
}
|
}
|
||||||
|
|||||||
+505
-95
@@ -1,122 +1,532 @@
|
|||||||
#include "Resource.h"
|
/// Resource transfer protocol implementation.
|
||||||
|
///
|
||||||
|
/// Matches Python Resource.py and Rust rns-protocol/resource.rs.
|
||||||
|
|
||||||
|
#include "Resource.h"
|
||||||
#include "ResourceData.h"
|
#include "ResourceData.h"
|
||||||
#include "Reticulum.h"
|
#include "Link.h"
|
||||||
#include "Transport.h"
|
|
||||||
#include "Packet.h"
|
#include "Packet.h"
|
||||||
|
#include "Identity.h"
|
||||||
|
#include "Compression/BZ2.h"
|
||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
#include <cmath>
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
|
||||||
using namespace RNS;
|
using namespace RNS;
|
||||||
using namespace RNS::Type::Resource;
|
|
||||||
using namespace RNS::Utilities;
|
|
||||||
|
|
||||||
//Resource::Resource(const Link& link /*= {Type::NONE}*/) :
|
// ============================================================
|
||||||
// _object(new ResourceData(link))
|
// MsgPack helpers (manual encoding for deterministic output)
|
||||||
//{
|
// ============================================================
|
||||||
// assert(_object);
|
|
||||||
// MEM("Resource object created");
|
static void mpPackFixStr(Bytes& buf, const char* str) {
|
||||||
//}
|
size_t len = strlen(str);
|
||||||
|
buf.append((uint8_t)(0xA0 | (len & 0x1F)));
|
||||||
|
buf.append((const uint8_t*)str, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void mpPackUint(Bytes& buf, size_t val) {
|
||||||
|
if (val <= 127) {
|
||||||
|
buf.append((uint8_t)val);
|
||||||
|
} else if (val <= 0xFFFF) {
|
||||||
|
buf.append((uint8_t)0xCD);
|
||||||
|
buf.append((uint8_t)((val >> 8) & 0xFF));
|
||||||
|
buf.append((uint8_t)(val & 0xFF));
|
||||||
|
} else {
|
||||||
|
buf.append((uint8_t)0xCE);
|
||||||
|
buf.append((uint8_t)((val >> 24) & 0xFF));
|
||||||
|
buf.append((uint8_t)((val >> 16) & 0xFF));
|
||||||
|
buf.append((uint8_t)((val >> 8) & 0xFF));
|
||||||
|
buf.append((uint8_t)(val & 0xFF));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void mpPackBin(Bytes& buf, const uint8_t* data, size_t len) {
|
||||||
|
if (len < 256) {
|
||||||
|
buf.append((uint8_t)0xC4);
|
||||||
|
buf.append((uint8_t)len);
|
||||||
|
} else {
|
||||||
|
buf.append((uint8_t)0xC5);
|
||||||
|
buf.append((uint8_t)((len >> 8) & 0xFF));
|
||||||
|
buf.append((uint8_t)(len & 0xFF));
|
||||||
|
}
|
||||||
|
buf.append(data, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void mpPackNil(Bytes& buf) {
|
||||||
|
buf.append((uint8_t)0xC0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple msgpack reader helpers
|
||||||
|
struct MpReader {
|
||||||
|
const uint8_t* data;
|
||||||
|
size_t len;
|
||||||
|
size_t pos;
|
||||||
|
|
||||||
|
bool readUint(size_t& val) {
|
||||||
|
if (pos >= len) return false;
|
||||||
|
uint8_t b = data[pos];
|
||||||
|
if (b <= 0x7F) { val = b; pos++; return true; }
|
||||||
|
if (b == 0xCC) { if (pos + 2 > len) return false; val = data[pos+1]; pos += 2; return true; }
|
||||||
|
if (b == 0xCD) { if (pos + 3 > len) return false; val = ((size_t)data[pos+1] << 8) | data[pos+2]; pos += 3; return true; }
|
||||||
|
if (b == 0xCE) { if (pos + 5 > len) return false; val = ((size_t)data[pos+1] << 24) | ((size_t)data[pos+2] << 16) | ((size_t)data[pos+3] << 8) | data[pos+4]; pos += 5; return true; }
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool readBin(const uint8_t*& out, size_t& outLen) {
|
||||||
|
if (pos >= len) return false;
|
||||||
|
uint8_t b = data[pos];
|
||||||
|
if (b == 0xC4) { if (pos + 2 > len) return false; outLen = data[pos+1]; pos += 2; }
|
||||||
|
else if (b == 0xC5) { if (pos + 3 > len) return false; outLen = ((size_t)data[pos+1] << 8) | data[pos+2]; pos += 3; }
|
||||||
|
else return false;
|
||||||
|
if (pos + outLen > len) return false;
|
||||||
|
out = &data[pos];
|
||||||
|
pos += outLen;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool readStr(std::string& str) {
|
||||||
|
if (pos >= len) return false;
|
||||||
|
uint8_t b = data[pos];
|
||||||
|
size_t slen = 0;
|
||||||
|
if ((b & 0xE0) == 0xA0) { slen = b & 0x1F; pos++; }
|
||||||
|
else if (b == 0xD9) { if (pos + 2 > len) return false; slen = data[pos+1]; pos += 2; }
|
||||||
|
else return false;
|
||||||
|
if (pos + slen > len) return false;
|
||||||
|
str.assign((const char*)&data[pos], slen);
|
||||||
|
pos += slen;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isNil() {
|
||||||
|
if (pos >= len) return false;
|
||||||
|
if (data[pos] == 0xC0) { pos++; return true; }
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool skipValue() {
|
||||||
|
if (pos >= len) return false;
|
||||||
|
uint8_t b = data[pos];
|
||||||
|
if (b == 0xC0 || b == 0xC2 || b == 0xC3) { pos++; return true; }
|
||||||
|
if ((b & 0x80) == 0x00 || (b & 0xE0) == 0xE0) { pos++; return true; }
|
||||||
|
if ((b & 0xE0) == 0xA0) { size_t s = b & 0x1F; pos += 1 + s; return pos <= len; }
|
||||||
|
if (b == 0xC4) { if (pos + 2 > len) return false; pos += 2 + data[pos+1]; return pos <= len; }
|
||||||
|
if (b == 0xC5) { if (pos + 3 > len) return false; pos += 3 + (((size_t)data[pos+1] << 8) | data[pos+2]); return pos <= len; }
|
||||||
|
if (b == 0xCC || b == 0xD0) { pos += 2; return pos <= len; }
|
||||||
|
if (b == 0xCD || b == 0xD1) { pos += 3; return pos <= len; }
|
||||||
|
if (b == 0xCE || b == 0xD2 || b == 0xCA) { pos += 5; return pos <= len; }
|
||||||
|
if (b == 0xCF || b == 0xD3 || b == 0xCB) { pos += 9; return pos <= len; }
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// ResourceAdvertisement
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
Bytes ResourceAdvertisement::pack() const {
|
||||||
|
Bytes buf;
|
||||||
|
// Map with 11 entries
|
||||||
|
buf.append((uint8_t)0x8B); // fixmap(11)
|
||||||
|
|
||||||
|
// "t": transfer_size
|
||||||
|
mpPackFixStr(buf, "t"); mpPackUint(buf, transfer_size);
|
||||||
|
// "d": data_size
|
||||||
|
mpPackFixStr(buf, "d"); mpPackUint(buf, data_size);
|
||||||
|
// "n": num_parts
|
||||||
|
mpPackFixStr(buf, "n"); mpPackUint(buf, num_parts);
|
||||||
|
// "h": resource_hash (32 bytes)
|
||||||
|
mpPackFixStr(buf, "h"); mpPackBin(buf, resource_hash, 32);
|
||||||
|
// "r": random_hash (4 bytes)
|
||||||
|
mpPackFixStr(buf, "r"); mpPackBin(buf, random_hash, 4);
|
||||||
|
// "o": original_hash (32 bytes)
|
||||||
|
mpPackFixStr(buf, "o"); mpPackBin(buf, original_hash, 32);
|
||||||
|
// "i": segment_index
|
||||||
|
mpPackFixStr(buf, "i"); mpPackUint(buf, segment_index);
|
||||||
|
// "l": total_segments
|
||||||
|
mpPackFixStr(buf, "l"); mpPackUint(buf, total_segments);
|
||||||
|
// "q": request_id (bin or nil)
|
||||||
|
mpPackFixStr(buf, "q");
|
||||||
|
if (request_id.size() > 0) { mpPackBin(buf, request_id.data(), request_id.size()); }
|
||||||
|
else { mpPackNil(buf); }
|
||||||
|
// "f": flags byte
|
||||||
|
mpPackFixStr(buf, "f"); mpPackUint(buf, flags.to_byte());
|
||||||
|
// "m": hashmap (concatenated 4-byte hashes)
|
||||||
|
mpPackFixStr(buf, "m"); mpPackBin(buf, hashmap.data(), hashmap.size());
|
||||||
|
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ResourceAdvertisement::unpack(const Bytes& data, ResourceAdvertisement& adv) {
|
||||||
|
MpReader r = { data.data(), data.size(), 0 };
|
||||||
|
|
||||||
|
// Read map header
|
||||||
|
if (r.pos >= r.len) return false;
|
||||||
|
uint8_t mh = r.data[r.pos];
|
||||||
|
size_t map_size = 0;
|
||||||
|
if ((mh & 0xF0) == 0x80) { map_size = mh & 0x0F; r.pos++; }
|
||||||
|
else if (mh == 0xDE) {
|
||||||
|
if (r.pos + 3 > r.len) return false;
|
||||||
|
map_size = ((size_t)r.data[r.pos+1] << 8) | r.data[r.pos+2];
|
||||||
|
r.pos += 3;
|
||||||
|
}
|
||||||
|
else return false;
|
||||||
|
|
||||||
|
for (size_t i = 0; i < map_size; i++) {
|
||||||
|
std::string key;
|
||||||
|
if (!r.readStr(key)) return false;
|
||||||
|
|
||||||
|
if (key == "t") { if (!r.readUint(adv.transfer_size)) return false; }
|
||||||
|
else if (key == "d") { if (!r.readUint(adv.data_size)) return false; }
|
||||||
|
else if (key == "n") { if (!r.readUint(adv.num_parts)) return false; }
|
||||||
|
else if (key == "h") {
|
||||||
|
const uint8_t* p; size_t l;
|
||||||
|
if (!r.readBin(p, l) || l < 32) return false;
|
||||||
|
memcpy(adv.resource_hash, p, 32);
|
||||||
|
}
|
||||||
|
else if (key == "r") {
|
||||||
|
const uint8_t* p; size_t l;
|
||||||
|
if (!r.readBin(p, l) || l < 4) return false;
|
||||||
|
memcpy(adv.random_hash, p, 4);
|
||||||
|
}
|
||||||
|
else if (key == "o") {
|
||||||
|
const uint8_t* p; size_t l;
|
||||||
|
if (!r.readBin(p, l) || l < 32) return false;
|
||||||
|
memcpy(adv.original_hash, p, 32);
|
||||||
|
}
|
||||||
|
else if (key == "i") { if (!r.readUint(adv.segment_index)) return false; }
|
||||||
|
else if (key == "l") { if (!r.readUint(adv.total_segments)) return false; }
|
||||||
|
else if (key == "q") {
|
||||||
|
if (r.isNil()) { adv.request_id = Bytes(); }
|
||||||
|
else {
|
||||||
|
const uint8_t* p; size_t l;
|
||||||
|
if (!r.readBin(p, l)) { r.skipValue(); }
|
||||||
|
else { adv.request_id = Bytes(p, l); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (key == "f") {
|
||||||
|
size_t fv; if (!r.readUint(fv)) return false;
|
||||||
|
adv.flags = ResourceFlags::from_byte((uint8_t)fv);
|
||||||
|
}
|
||||||
|
else if (key == "m") {
|
||||||
|
const uint8_t* p; size_t l;
|
||||||
|
if (!r.readBin(p, l)) return false;
|
||||||
|
adv.hashmap = Bytes(p, l);
|
||||||
|
}
|
||||||
|
else { r.skipValue(); }
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::array<uint8_t, 4>> ResourceAdvertisement::get_map_hashes() const {
|
||||||
|
std::vector<std::array<uint8_t, 4>> hashes;
|
||||||
|
for (size_t i = 0; i + 4 <= hashmap.size(); i += 4) {
|
||||||
|
std::array<uint8_t, 4> h;
|
||||||
|
memcpy(h.data(), hashmap.data() + i, 4);
|
||||||
|
hashes.push_back(h);
|
||||||
|
}
|
||||||
|
return hashes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Hash functions
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
void RNS::get_map_hash(const uint8_t* data, size_t data_len,
|
||||||
|
const uint8_t* random_hash, size_t random_len,
|
||||||
|
uint8_t out[4]) {
|
||||||
|
Bytes input(data, data_len);
|
||||||
|
input.append(random_hash, random_len);
|
||||||
|
Bytes hash = Identity::full_hash(input);
|
||||||
|
memcpy(out, hash.data(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
Bytes RNS::compute_resource_hash(const Bytes& data, const uint8_t random_hash[4]) {
|
||||||
|
Bytes input(data.data(), data.size());
|
||||||
|
input.append(random_hash, 4);
|
||||||
|
return Identity::full_hash(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
Bytes RNS::compute_expected_proof(const Bytes& data, const uint8_t resource_hash[32]) {
|
||||||
|
Bytes input(data.data(), data.size());
|
||||||
|
input.append(resource_hash, 32);
|
||||||
|
return Identity::full_hash(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// OutboundResource
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
bool OutboundResource::init(const Bytes& plaintext, Link& link, bool /*auto_compress*/) {
|
||||||
|
_data_size = plaintext.size();
|
||||||
|
_flags.encrypted = true;
|
||||||
|
|
||||||
|
// Compression is intentionally disabled on this build — see BZ2.cpp.
|
||||||
|
// The auto_compress parameter is kept for API parity with Python Resource
|
||||||
|
// but ignored: bz2 is too heavy for MCU targets, and we advertise
|
||||||
|
// SF_COMPRESSION-absent in our LXMF announces so peers won't compress for us.
|
||||||
|
Bytes data_to_pack = plaintext;
|
||||||
|
_flags.compressed = false;
|
||||||
|
|
||||||
|
// Prepend 4-byte random_hash
|
||||||
|
Bytes rh = Identity::get_random_hash();
|
||||||
|
memcpy(_random_hash, rh.data(), 4);
|
||||||
|
Bytes to_encrypt(_random_hash, 4);
|
||||||
|
to_encrypt.append(data_to_pack.data(), data_to_pack.size());
|
||||||
|
|
||||||
|
// Encrypt with link session key (Resource.py line 424)
|
||||||
|
Bytes encrypted = link.encrypt(to_encrypt);
|
||||||
|
if (encrypted.size() == 0) return false;
|
||||||
|
|
||||||
|
_transfer_size = encrypted.size();
|
||||||
|
|
||||||
|
// Compute resource hash
|
||||||
|
Bytes rh_full = compute_resource_hash(encrypted, _random_hash);
|
||||||
|
memcpy(_resource_hash, rh_full.data(), 32);
|
||||||
|
memcpy(_original_hash, _resource_hash, 32);
|
||||||
|
|
||||||
|
// Compute expected proof
|
||||||
|
_expected_proof = compute_expected_proof(encrypted, _resource_hash);
|
||||||
|
|
||||||
|
// Split into SDU-sized chunks
|
||||||
|
size_t sdu = Type::Resource::SDU;
|
||||||
|
size_t num = (encrypted.size() + sdu - 1) / sdu;
|
||||||
|
_parts.clear();
|
||||||
|
_parts.reserve(num);
|
||||||
|
|
||||||
|
Bytes hashmap_bytes;
|
||||||
|
for (size_t i = 0; i < num; i++) {
|
||||||
|
size_t offset = i * sdu;
|
||||||
|
size_t chunk_len = std::min(sdu, encrypted.size() - offset);
|
||||||
|
Bytes chunk(encrypted.data() + offset, chunk_len);
|
||||||
|
|
||||||
|
// Compute map hash for this chunk
|
||||||
|
uint8_t mh[4];
|
||||||
|
get_map_hash(chunk.data(), chunk.size(), _random_hash, 4, mh);
|
||||||
|
hashmap_bytes.append(mh, 4);
|
||||||
|
|
||||||
|
_parts.push_back(chunk);
|
||||||
|
}
|
||||||
|
|
||||||
|
_hashmap = hashmap_bytes;
|
||||||
|
_status = ResourceStatus::ADVERTISED;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ResourceAdvertisement OutboundResource::get_advertisement() const {
|
||||||
|
ResourceAdvertisement adv;
|
||||||
|
adv.transfer_size = _transfer_size;
|
||||||
|
adv.data_size = _data_size;
|
||||||
|
adv.num_parts = _parts.size();
|
||||||
|
memcpy(adv.resource_hash, _resource_hash, 32);
|
||||||
|
memcpy(adv.random_hash, _random_hash, 4);
|
||||||
|
memcpy(adv.original_hash, _original_hash, 32);
|
||||||
|
adv.segment_index = 1;
|
||||||
|
adv.total_segments = 1;
|
||||||
|
adv.flags = _flags;
|
||||||
|
adv.hashmap = _hashmap;
|
||||||
|
return adv;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bytes OutboundResource::get_part(size_t index) const {
|
||||||
|
if (index < _parts.size()) return _parts[index];
|
||||||
|
return Bytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<size_t> OutboundResource::handle_request(const Bytes& request_data) {
|
||||||
|
// Request format: [exhausted_flag(1)][?last_map_hash(4)][resource_hash(32)][requested_hashes(N*4)]
|
||||||
|
std::vector<size_t> indices;
|
||||||
|
if (request_data.size() < 33) return indices;
|
||||||
|
|
||||||
|
size_t pos = 0;
|
||||||
|
uint8_t exhausted = request_data.data()[pos++];
|
||||||
|
if (exhausted == 0xFF && request_data.size() > pos + 4) {
|
||||||
|
pos += 4; // skip last_map_hash
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip resource_hash (32 bytes)
|
||||||
|
if (pos + 32 > request_data.size()) return indices;
|
||||||
|
pos += 32;
|
||||||
|
|
||||||
|
// Remaining are requested map hashes (4 bytes each)
|
||||||
|
while (pos + 4 <= request_data.size()) {
|
||||||
|
uint8_t wanted[4];
|
||||||
|
memcpy(wanted, request_data.data() + pos, 4);
|
||||||
|
pos += 4;
|
||||||
|
|
||||||
|
// Find matching part index
|
||||||
|
for (size_t i = 0; i < _parts.size(); i++) {
|
||||||
|
uint8_t mh[4];
|
||||||
|
get_map_hash(_parts[i].data(), _parts[i].size(), _random_hash, 4, mh);
|
||||||
|
if (memcmp(mh, wanted, 4) == 0) {
|
||||||
|
indices.push_back(i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_status = ResourceStatus::TRANSFERRING;
|
||||||
|
return indices;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool OutboundResource::handle_proof(const Bytes& proof_data) {
|
||||||
|
if (proof_data.size() < 32) return false;
|
||||||
|
if (memcmp(proof_data.data(), _expected_proof.data(), 32) == 0) {
|
||||||
|
_status = ResourceStatus::COMPLETE;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// InboundResource
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
bool InboundResource::init(const ResourceAdvertisement& adv, Link& link) {
|
||||||
|
_transfer_size = adv.transfer_size;
|
||||||
|
_data_size = adv.data_size;
|
||||||
|
_total_parts = adv.num_parts;
|
||||||
|
memcpy(_resource_hash, adv.resource_hash, 32);
|
||||||
|
memcpy(_random_hash, adv.random_hash, 4);
|
||||||
|
memcpy(_original_hash, adv.original_hash, 32);
|
||||||
|
_flags = adv.flags;
|
||||||
|
_map_hashes = adv.get_map_hashes();
|
||||||
|
_received = 0;
|
||||||
|
_window = 4;
|
||||||
|
|
||||||
|
// Initialize part slots
|
||||||
|
_parts.resize(_total_parts);
|
||||||
|
|
||||||
|
_status = ResourceStatus::TRANSFERRING;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InboundResource::receive_part(const Bytes& data) {
|
||||||
|
// Compute map hash of this part
|
||||||
|
uint8_t mh[4];
|
||||||
|
get_map_hash(data.data(), data.size(), _random_hash, 4, mh);
|
||||||
|
|
||||||
|
// Find matching slot in our hashmap
|
||||||
|
for (size_t i = 0; i < _map_hashes.size() && i < _total_parts; i++) {
|
||||||
|
if (memcmp(_map_hashes[i].data(), mh, 4) == 0 && _parts[i].size() == 0) {
|
||||||
|
_parts[i] = data;
|
||||||
|
_received++;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool InboundResource::is_complete() const {
|
||||||
|
return _received >= _total_parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bytes InboundResource::assemble(Link& link) {
|
||||||
|
// Concatenate all parts in order
|
||||||
|
Bytes assembled;
|
||||||
|
for (size_t i = 0; i < _total_parts; i++) {
|
||||||
|
if (_parts[i].size() == 0) {
|
||||||
|
_status = ResourceStatus::CORRUPT;
|
||||||
|
return Bytes();
|
||||||
|
}
|
||||||
|
assembled.append(_parts[i].data(), _parts[i].size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decrypt with link session key
|
||||||
|
Bytes decrypted = link.decrypt(assembled);
|
||||||
|
if (decrypted.size() == 0) {
|
||||||
|
_status = ResourceStatus::CORRUPT;
|
||||||
|
return Bytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strip 4-byte random_hash prefix
|
||||||
|
if (decrypted.size() <= 4) {
|
||||||
|
_status = ResourceStatus::CORRUPT;
|
||||||
|
return Bytes();
|
||||||
|
}
|
||||||
|
Bytes payload(decrypted.data() + 4, decrypted.size() - 4);
|
||||||
|
|
||||||
|
// bz2 decompression is intentionally not available on this build (see BZ2.cpp).
|
||||||
|
// If a peer ships a compressed resource anyway — either an old Python LXMF that
|
||||||
|
// pre-dates the SF_COMPRESSION advertisement, or any peer ignoring our empty
|
||||||
|
// supported_functionality list — drop the resource cleanly rather than burning
|
||||||
|
// hundreds of KB of MCU RAM trying to decode it.
|
||||||
|
Bytes plaintext;
|
||||||
|
if (_flags.compressed) {
|
||||||
|
WARNING("Resource: dropping compressed inbound payload (bz2 not supported on this build; "
|
||||||
|
"peer ignored SF_COMPRESSION advertisement)");
|
||||||
|
_status = ResourceStatus::CORRUPT;
|
||||||
|
return Bytes();
|
||||||
|
}
|
||||||
|
plaintext = payload;
|
||||||
|
|
||||||
|
_status = ResourceStatus::COMPLETE;
|
||||||
|
return plaintext;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bytes InboundResource::generate_proof() const {
|
||||||
|
// Proof = SHA256(assembled_encrypted_data || resource_hash)
|
||||||
|
Bytes assembled;
|
||||||
|
for (size_t i = 0; i < _total_parts; i++) {
|
||||||
|
assembled.append(_parts[i].data(), _parts[i].size());
|
||||||
|
}
|
||||||
|
return compute_expected_proof(assembled, _resource_hash);
|
||||||
|
}
|
||||||
|
|
||||||
|
Bytes InboundResource::get_initial_request() const {
|
||||||
|
// Build request: [exhausted(1)][resource_hash(32)][wanted_hashes(N*4)]
|
||||||
|
Bytes request;
|
||||||
|
request.append((uint8_t)0x00); // HASHMAP_IS_NOT_EXHAUSTED
|
||||||
|
|
||||||
|
// Resource hash
|
||||||
|
request.append(_resource_hash, 32);
|
||||||
|
|
||||||
|
// Request all map hashes (initial window)
|
||||||
|
size_t count = std::min(_window, _map_hashes.size());
|
||||||
|
for (size_t i = 0; i < count; i++) {
|
||||||
|
request.append(_map_hashes[i].data(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// Legacy Resource class (compatibility with Link.cpp)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
Resource::Resource(const Bytes& data, const Link& link, const Bytes& request_id, bool is_response, double timeout) :
|
Resource::Resource(const Bytes& data, const Link& link, const Bytes& request_id, bool is_response, double timeout) :
|
||||||
_object(new ResourceData(link))
|
_object(new ResourceData(link))
|
||||||
{
|
{
|
||||||
assert(_object);
|
|
||||||
MEM("Resource object created");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Resource::Resource(const Bytes& data, const Link& link, bool advertise /*= true*/, bool auto_compress /*= true*/, Callbacks::concluded callback /*= nullptr*/, Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int segment_index /*= 1*/, const Bytes& original_hash /*= {Type::NONE}*/, const Bytes& request_id /*= {Type::NONE}*/, bool is_response /*= false*/) :
|
Resource::Resource(const Bytes& data, const Link& link, bool advertise, bool auto_compress,
|
||||||
_object(new ResourceData(link))
|
Callbacks::concluded callback, Callbacks::progress progress_callback,
|
||||||
|
double timeout, int segment_index, const Bytes& original_hash,
|
||||||
|
const Bytes& request_id, bool is_response) :
|
||||||
|
_object(new ResourceData(link))
|
||||||
{
|
{
|
||||||
assert(_object);
|
|
||||||
MEM("Resource object created");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void Resource::validate_proof(const Bytes& proof_data) {}
|
||||||
void Resource::validate_proof(const Bytes& proof_data) {
|
void Resource::cancel() {}
|
||||||
}
|
float Resource::get_progress() const { return 0.0; }
|
||||||
|
|
||||||
void Resource::cancel() {
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
:returns: The current progress of the resource transfer as a *float* between 0.0 and 1.0.
|
|
||||||
*/
|
|
||||||
float Resource::get_progress() const {
|
|
||||||
/*
|
|
||||||
assert(_object);
|
|
||||||
if (_object->_initiator) {
|
|
||||||
_object->_processed_parts = (_object->_segment_index-1)*math.ceil(Type::Resource::MAX_EFFICIENT_SIZE/Type::Resource::SDU);
|
|
||||||
_object->_processed_parts += _object->sent_parts;
|
|
||||||
_object->_progress_total_parts = float(_object->grand_total_parts);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
_object->_processed_parts = (_object->_segment_index-1)*math.ceil(Type::Resource::MAX_EFFICIENT_SIZE/Type::Resource::SDU);
|
|
||||||
_object->_processed_parts += _object->_received_count;
|
|
||||||
if (_object->split) {
|
|
||||||
_object->progress_total_parts = float(math.ceil(_object->total_size/Type::Resource::SDU));
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
_object->progress_total_parts = float(_object->total_parts);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (float)_object->processed_parts / (float)_object->progress_total_parts;
|
|
||||||
*/
|
|
||||||
return 0.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
void Resource::set_concluded_callback(Callbacks::concluded callback) {
|
void Resource::set_concluded_callback(Callbacks::concluded callback) {
|
||||||
assert(_object);
|
if (_object) _object->_callbacks._concluded = callback;
|
||||||
_object->_callbacks._concluded = callback;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Resource::set_progress_callback(Callbacks::progress callback) {
|
void Resource::set_progress_callback(Callbacks::progress callback) {
|
||||||
assert(_object);
|
if (_object) _object->_callbacks._progress = callback;
|
||||||
_object->_callbacks._progress = callback;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
std::string Resource::toString() const {
|
std::string Resource::toString() const {
|
||||||
if (!_object) {
|
return _object ? "{Resource}" : "";
|
||||||
return "";
|
|
||||||
}
|
|
||||||
//return "<"+RNS.hexrep(self.hash,delimit=False)+"/"+RNS.hexrep(self.link.link_id,delimit=False)+">"
|
|
||||||
//return "{Resource:" + _object->_hash.toHex() + "}";
|
|
||||||
return "{Resource: unknown}";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// getters
|
const Bytes& Resource::hash() const { assert(_object); return _object->_hash; }
|
||||||
const Bytes& Resource::hash() const {
|
const Bytes& Resource::request_id() const { assert(_object); return _object->_request_id; }
|
||||||
assert(_object);
|
const Bytes& Resource::data() const { assert(_object); return _object->_data; }
|
||||||
return _object->_hash;
|
const Type::Resource::status Resource::status() const { assert(_object); return _object->_status; }
|
||||||
}
|
const size_t Resource::size() const { assert(_object); return _object->_size; }
|
||||||
|
const size_t Resource::total_size() const { assert(_object); return _object->_total_size; }
|
||||||
const Bytes& Resource::request_id() const {
|
|
||||||
assert(_object);
|
|
||||||
return _object->_request_id;
|
|
||||||
}
|
|
||||||
|
|
||||||
const Bytes& Resource::data() const {
|
|
||||||
assert(_object);
|
|
||||||
return _object->_data;
|
|
||||||
}
|
|
||||||
|
|
||||||
const Type::Resource::status Resource::status() const {
|
|
||||||
assert(_object);
|
|
||||||
return _object->_status;
|
|
||||||
}
|
|
||||||
|
|
||||||
const size_t Resource::size() const {
|
|
||||||
assert(_object);
|
|
||||||
return _object->_size;
|
|
||||||
}
|
|
||||||
|
|
||||||
const size_t Resource::total_size() const {
|
|
||||||
assert(_object);
|
|
||||||
return _object->_total_size;
|
|
||||||
}
|
|
||||||
|
|
||||||
// setters
|
|
||||||
|
|
||||||
+206
-86
@@ -1,110 +1,230 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include "Destination.h"
|
/// Resource transfer protocol — chunked, windowed data transfer over Links.
|
||||||
|
///
|
||||||
|
/// Matches Python Resource.py and Rust rns-protocol/resource.rs wire format.
|
||||||
|
/// Supports both sender (outbound) and receiver (inbound) roles.
|
||||||
|
|
||||||
|
#include "Bytes.h"
|
||||||
#include "Type.h"
|
#include "Type.h"
|
||||||
|
#include "Cryptography/Hashes.h"
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
|
#include <cstdint>
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
|
#include <functional>
|
||||||
|
|
||||||
namespace RNS {
|
namespace RNS {
|
||||||
|
|
||||||
class ResourceData;
|
class Link;
|
||||||
class Packet;
|
class Packet;
|
||||||
class Destination;
|
|
||||||
class Link;
|
|
||||||
class Resource;
|
|
||||||
|
|
||||||
class Resource {
|
// ---- Resource flags byte ----
|
||||||
|
struct ResourceFlags {
|
||||||
|
bool encrypted = true;
|
||||||
|
bool compressed = false;
|
||||||
|
bool split = false;
|
||||||
|
bool is_request = false;
|
||||||
|
bool is_response = false;
|
||||||
|
bool has_metadata = false;
|
||||||
|
|
||||||
public:
|
uint8_t to_byte() const {
|
||||||
class Callbacks {
|
uint8_t b = 0;
|
||||||
public:
|
if (encrypted) b |= 0x01;
|
||||||
// CBA std::function apparently not implemented in NRF52 framework
|
if (compressed) b |= 0x02;
|
||||||
//typedef std::function<void(const Resource& resource)> concluded;
|
if (split) b |= 0x04;
|
||||||
using concluded = void(*)(const Resource& resource);
|
if (is_request) b |= 0x08;
|
||||||
using progress = void(*)(const Resource& resource);
|
if (is_response) b |= 0x10;
|
||||||
public:
|
if (has_metadata) b |= 0x20;
|
||||||
concluded _concluded = nullptr;
|
return b;
|
||||||
progress _progress = nullptr;
|
}
|
||||||
friend class Resource;
|
static ResourceFlags from_byte(uint8_t b) {
|
||||||
};
|
return { (b & 0x01) != 0, (b & 0x02) != 0, (b & 0x04) != 0,
|
||||||
|
(b & 0x08) != 0, (b & 0x10) != 0, (b & 0x20) != 0 };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
public:
|
// ---- Resource Advertisement ----
|
||||||
Resource(Type::NoneConstructor none) {
|
// Msgpack map: {t,d,n,h,r,o,i,l,q,f,m}
|
||||||
MEM("Resource NONE object created");
|
struct ResourceAdvertisement {
|
||||||
}
|
size_t transfer_size = 0; // encrypted blob size
|
||||||
Resource(const Resource& resource) : _object(resource._object) {
|
size_t data_size = 0; // original (uncompressed) size
|
||||||
MEM("Resource object copy created");
|
size_t num_parts = 0;
|
||||||
}
|
uint8_t resource_hash[32] = {};
|
||||||
//Resource(const Link& link = {Type::NONE});
|
uint8_t random_hash[4] = {};
|
||||||
Resource(const Bytes& data, const Link& link, const Bytes& request_id, bool is_response, double timeout);
|
uint8_t original_hash[32] = {};
|
||||||
Resource(const Bytes& data, const Link& link, bool advertise = true, bool auto_compress = true, Callbacks::concluded callback = nullptr, Callbacks::progress progress_callback = nullptr, double timeout = 0.0, int segment_index = 1, const Bytes& original_hash = {Type::NONE}, const Bytes& request_id = {Type::NONE}, bool is_response = false);
|
size_t segment_index = 1;
|
||||||
virtual ~Resource(){
|
size_t total_segments = 1;
|
||||||
MEM("Resource object destroyed");
|
Bytes request_id; // nil if not a request/response
|
||||||
}
|
ResourceFlags flags;
|
||||||
|
Bytes hashmap; // concatenated 4-byte map hashes
|
||||||
|
|
||||||
Resource& operator = (const Resource& resource) {
|
Bytes pack() const;
|
||||||
_object = resource._object;
|
static bool unpack(const Bytes& data, ResourceAdvertisement& adv);
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
operator bool() const {
|
|
||||||
return _object.get() != nullptr;
|
|
||||||
}
|
|
||||||
bool operator < (const Resource& resource) const {
|
|
||||||
return _object.get() < resource._object.get();
|
|
||||||
//return _object->_hash < resource._object->_hash;
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
/// Extract map hashes as 4-byte arrays.
|
||||||
//p static def accept(advertisement_packet, callback=None, progress_callback = None, request_id = None):
|
std::vector<std::array<uint8_t, 4>> get_map_hashes() const;
|
||||||
|
};
|
||||||
|
|
||||||
public:
|
// ---- Map hash computation ----
|
||||||
//p def hashmap_update_packet(self, plaintext):
|
/// SHA256(data || random_hash)[:MAPHASH_LEN]
|
||||||
//p def hashmap_update(self, segment, hashmap):
|
void get_map_hash(const uint8_t* data, size_t data_len,
|
||||||
//p def get_map_hash(self, data):
|
const uint8_t* random_hash, size_t random_len,
|
||||||
//p def advertise(self):
|
uint8_t out[4]);
|
||||||
//p def __advertise_job(self):
|
|
||||||
//p def watchdog_job(self):
|
|
||||||
//p def __watchdog_job(self):
|
|
||||||
//p def assemble(self):
|
|
||||||
//p def prove(self):
|
|
||||||
void validate_proof(const Bytes& proof_data);
|
|
||||||
//p def receive_part(self, packet):
|
|
||||||
//p def request_next(self):
|
|
||||||
//p def request(self, request_data):
|
|
||||||
void cancel();
|
|
||||||
//p def set_callback(self, callback):
|
|
||||||
//p def progress_callback(self, callback):
|
|
||||||
float get_progress() const;
|
|
||||||
//p def get_transfer_size(self):
|
|
||||||
//p def get_data_size(self):
|
|
||||||
//p def get_parts(self):
|
|
||||||
//p def get_segments(self):
|
|
||||||
//p def get_hash(self):
|
|
||||||
//p def is_compressed(self):
|
|
||||||
void set_concluded_callback(Callbacks::concluded callback);
|
|
||||||
void set_progress_callback(Callbacks::progress callback);
|
|
||||||
|
|
||||||
std::string toString() const;
|
/// SHA256(data || random_hash) full 32 bytes
|
||||||
|
Bytes compute_resource_hash(const Bytes& data, const uint8_t random_hash[4]);
|
||||||
|
|
||||||
// getters
|
/// SHA256(data || resource_hash) — expected proof
|
||||||
const Bytes& hash() const;
|
Bytes compute_expected_proof(const Bytes& data, const uint8_t resource_hash[32]);
|
||||||
const Bytes& request_id() const;
|
|
||||||
const Bytes& data() const;
|
|
||||||
const Type::Resource::status status() const;
|
|
||||||
const size_t size() const;
|
|
||||||
const size_t total_size() const;
|
|
||||||
|
|
||||||
// setters
|
// ---- Resource status ----
|
||||||
|
enum class ResourceStatus : uint8_t {
|
||||||
|
NONE = 0,
|
||||||
|
QUEUED = 1,
|
||||||
|
ADVERTISED = 2,
|
||||||
|
TRANSFERRING = 3,
|
||||||
|
AWAITING_PROOF = 4,
|
||||||
|
ASSEMBLING = 5,
|
||||||
|
COMPLETE = 6,
|
||||||
|
FAILED = 7,
|
||||||
|
CORRUPT = 8,
|
||||||
|
};
|
||||||
|
|
||||||
protected:
|
// ---- Outbound Resource (sender) ----
|
||||||
std::shared_ptr<ResourceData> _object;
|
class OutboundResource {
|
||||||
|
public:
|
||||||
|
OutboundResource() = default;
|
||||||
|
|
||||||
};
|
/// Initialize from raw data. Encrypts, chunks, computes hashmap.
|
||||||
|
/// auto_compress is accepted for API parity but ignored — see Resource.cpp.
|
||||||
|
bool init(const Bytes& plaintext, Link& link, bool auto_compress = false);
|
||||||
|
|
||||||
|
/// Get the advertisement to send.
|
||||||
|
ResourceAdvertisement get_advertisement() const;
|
||||||
|
|
||||||
class ResourceAdvertisement {
|
/// Get part data by index (raw encrypted chunk).
|
||||||
|
Bytes get_part(size_t index) const;
|
||||||
|
|
||||||
};
|
/// Handle a request from receiver (list of wanted map hashes).
|
||||||
|
/// Returns indices of parts to send.
|
||||||
|
std::vector<size_t> handle_request(const Bytes& request_data);
|
||||||
|
|
||||||
}
|
/// Handle proof from receiver.
|
||||||
|
bool handle_proof(const Bytes& proof_data);
|
||||||
|
|
||||||
|
/// Number of parts.
|
||||||
|
size_t num_parts() const { return _parts.size(); }
|
||||||
|
bool is_complete() const { return _status == ResourceStatus::COMPLETE; }
|
||||||
|
|
||||||
|
ResourceStatus status() const { return _status; }
|
||||||
|
const uint8_t* resource_hash() const { return _resource_hash; }
|
||||||
|
const uint8_t* random_hash() const { return _random_hash; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::vector<Bytes> _parts; // encrypted chunks
|
||||||
|
Bytes _hashmap; // concatenated 4-byte map hashes
|
||||||
|
uint8_t _resource_hash[32] = {};
|
||||||
|
uint8_t _random_hash[4] = {};
|
||||||
|
uint8_t _original_hash[32] = {};
|
||||||
|
size_t _transfer_size = 0;
|
||||||
|
size_t _data_size = 0;
|
||||||
|
ResourceFlags _flags;
|
||||||
|
Bytes _expected_proof;
|
||||||
|
ResourceStatus _status = ResourceStatus::NONE;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- Inbound Resource (receiver) ----
|
||||||
|
class InboundResource {
|
||||||
|
public:
|
||||||
|
InboundResource() = default;
|
||||||
|
|
||||||
|
/// Create from a received advertisement.
|
||||||
|
bool init(const ResourceAdvertisement& adv, Link& link);
|
||||||
|
|
||||||
|
/// Receive a part (raw data from Resource context packet).
|
||||||
|
/// Returns true if part was accepted (map hash matched).
|
||||||
|
bool receive_part(const Bytes& data);
|
||||||
|
|
||||||
|
/// Check if all parts have been received.
|
||||||
|
bool is_complete() const;
|
||||||
|
|
||||||
|
/// Assemble the resource: concatenate parts → decrypt → decompress.
|
||||||
|
/// Returns the original plaintext data.
|
||||||
|
Bytes assemble(Link& link);
|
||||||
|
|
||||||
|
/// Generate the proof to send back to sender.
|
||||||
|
Bytes generate_proof() const;
|
||||||
|
|
||||||
|
/// Get initial request (map hashes we need).
|
||||||
|
Bytes get_initial_request() const;
|
||||||
|
|
||||||
|
size_t num_parts() const { return _total_parts; }
|
||||||
|
size_t received_count() const { return _received; }
|
||||||
|
const uint8_t* resource_hash() const { return _resource_hash; }
|
||||||
|
|
||||||
|
ResourceStatus status() const { return _status; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::vector<Bytes> _parts; // received chunks (indexed by part number)
|
||||||
|
std::vector<std::array<uint8_t, 4>> _map_hashes;
|
||||||
|
uint8_t _resource_hash[32] = {};
|
||||||
|
uint8_t _random_hash[4] = {};
|
||||||
|
uint8_t _original_hash[32] = {};
|
||||||
|
size_t _transfer_size = 0;
|
||||||
|
size_t _data_size = 0;
|
||||||
|
size_t _total_parts = 0;
|
||||||
|
size_t _received = 0;
|
||||||
|
ResourceFlags _flags;
|
||||||
|
ResourceStatus _status = ResourceStatus::NONE;
|
||||||
|
size_t _window = 4; // current receive window
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- Legacy Resource class (compatibility wrapper) ----
|
||||||
|
// Preserves existing API used by Link.cpp
|
||||||
|
class ResourceData;
|
||||||
|
|
||||||
|
class Resource {
|
||||||
|
public:
|
||||||
|
class Callbacks {
|
||||||
|
public:
|
||||||
|
using concluded = void(*)(const Resource& resource);
|
||||||
|
using progress = void(*)(const Resource& resource);
|
||||||
|
public:
|
||||||
|
concluded _concluded = nullptr;
|
||||||
|
progress _progress = nullptr;
|
||||||
|
};
|
||||||
|
|
||||||
|
Resource(Type::NoneConstructor none) {}
|
||||||
|
Resource(const Resource& resource) : _object(resource._object) {}
|
||||||
|
Resource(const Bytes& data, const Link& link, const Bytes& request_id, bool is_response, double timeout = 0.0);
|
||||||
|
Resource(const Bytes& data, const Link& link, bool advertise = true, bool auto_compress = false,
|
||||||
|
Callbacks::concluded callback = nullptr, Callbacks::progress progress_callback = nullptr,
|
||||||
|
double timeout = 0.0, int segment_index = 1, const Bytes& original_hash = {Type::NONE},
|
||||||
|
const Bytes& request_id = {Type::NONE}, bool is_response = false);
|
||||||
|
virtual ~Resource() {}
|
||||||
|
|
||||||
|
Resource& operator=(const Resource& resource) { _object = resource._object; return *this; }
|
||||||
|
operator bool() const { return _object.get() != nullptr; }
|
||||||
|
bool operator<(const Resource& resource) const { return _object.get() < resource._object.get(); }
|
||||||
|
|
||||||
|
void validate_proof(const Bytes& proof_data);
|
||||||
|
void cancel();
|
||||||
|
float get_progress() const;
|
||||||
|
void set_concluded_callback(Callbacks::concluded callback);
|
||||||
|
void set_progress_callback(Callbacks::progress callback);
|
||||||
|
std::string toString() const;
|
||||||
|
|
||||||
|
const Bytes& hash() const;
|
||||||
|
const Bytes& request_id() const;
|
||||||
|
const Bytes& data() const;
|
||||||
|
const Type::Resource::status status() const;
|
||||||
|
const size_t size() const;
|
||||||
|
const size_t total_size() const;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
std::shared_ptr<ResourceData> _object;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace RNS
|
||||||
+45
-34
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
#include "Transport.h"
|
#include "Transport.h"
|
||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
|
#include "Utilities/Memory.h"
|
||||||
|
|
||||||
//#include <TransistorNoiseSource.h>
|
//#include <TransistorNoiseSource.h>
|
||||||
#include <RNG.h>
|
#include <RNG.h>
|
||||||
@@ -29,6 +30,9 @@ using namespace RNS::Utilities;
|
|||||||
/*static*/ bool Reticulum::__allow_probes = false;
|
/*static*/ bool Reticulum::__allow_probes = false;
|
||||||
/*static*/ bool Reticulum::panic_on_interface_error = false;
|
/*static*/ bool Reticulum::panic_on_interface_error = false;
|
||||||
|
|
||||||
|
/*static*/ uint16_t Reticulum::_persist_interval = PERSIST_INTERVAL;
|
||||||
|
/*static*/ uint16_t Reticulum::_clean_interval = CLEAN_INTERVAL;
|
||||||
|
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
// Noise source to seed the random number generator.
|
// Noise source to seed the random number generator.
|
||||||
//TransistorNoiseSource noise(A1);
|
//TransistorNoiseSource noise(A1);
|
||||||
@@ -115,32 +119,6 @@ Reticulum::Reticulum() : _object(new Object()) {
|
|||||||
strncpy(_cachepath, "./cache", FILEPATH_MAXSIZE);
|
strncpy(_cachepath, "./cache", FILEPATH_MAXSIZE);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifdef ARDUINO
|
|
||||||
#if defined(RNS_USE_FS)
|
|
||||||
// load time offset from file if it exists
|
|
||||||
try {
|
|
||||||
char time_offset_path[FILEPATH_MAXSIZE];
|
|
||||||
snprintf(time_offset_path, FILEPATH_MAXSIZE, "%s/time_offset", _storagepath);
|
|
||||||
if (OS::file_exists(time_offset_path)) {
|
|
||||||
Bytes buf;
|
|
||||||
if (OS::read_file(time_offset_path, buf) == 8) {
|
|
||||||
uint64_t offset = *(uint64_t*)buf.data();
|
|
||||||
DEBUGF("Read time offset of %llu from file", offset);
|
|
||||||
OS::setTimeOffset(offset);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (std::exception& e) {
|
|
||||||
ERRORF("Failed to load time offset, the contained exception was: %s", e.what());
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Initialize time-based variables *after* time offset update
|
|
||||||
_object->_last_data_persist = OS::time();
|
|
||||||
_object->_last_cache_clean = 0.0;
|
|
||||||
_object->_jobs_last_run = OS::time();
|
|
||||||
|
|
||||||
/*p TODO
|
/*p TODO
|
||||||
if not os.path.isdir(Reticulum.storagepath):
|
if not os.path.isdir(Reticulum.storagepath):
|
||||||
os.makedirs(Reticulum.storagepath)
|
os.makedirs(Reticulum.storagepath)
|
||||||
@@ -196,11 +174,37 @@ Reticulum::Reticulum() : _object(new Object()) {
|
|||||||
|
|
||||||
void Reticulum::start() {
|
void Reticulum::start() {
|
||||||
|
|
||||||
INFOF("Total memory: %zu", OS::heap_size());
|
INFOF("Total memory: %zu", Memory::heap_size());
|
||||||
INFOF("Total flash: %zu", OS::storage_size());
|
INFOF("Total flash: %zu", OS::storage_size());
|
||||||
|
|
||||||
|
#ifdef ARDUINO
|
||||||
|
#if defined(RNS_USE_FS)
|
||||||
|
// load time offset from file if it exists
|
||||||
|
try {
|
||||||
|
char time_offset_path[FILEPATH_MAXSIZE];
|
||||||
|
snprintf(time_offset_path, FILEPATH_MAXSIZE, "%s/time_offset", _storagepath);
|
||||||
|
if (OS::file_exists(time_offset_path)) {
|
||||||
|
Bytes buf;
|
||||||
|
if (OS::read_file(time_offset_path, buf) == 8) {
|
||||||
|
uint64_t offset = *(uint64_t*)buf.data();
|
||||||
|
DEBUGF("Read time offset of %llu from file", offset);
|
||||||
|
OS::setTimeOffset(offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (std::exception& e) {
|
||||||
|
ERRORF("Failed to load time offset, the contained exception was: %s", e.what());
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
INFO("Starting Transport...");
|
INFO("Starting Transport...");
|
||||||
Transport::start(*this);
|
Transport::start(*this);
|
||||||
|
|
||||||
|
// Initialize time-based variables *after* time offset update and Transport start
|
||||||
|
_object->_last_data_persist = OS::time();
|
||||||
|
_object->_last_cache_clean = OS::time();
|
||||||
|
_object->_jobs_last_run = OS::time();
|
||||||
}
|
}
|
||||||
|
|
||||||
void Reticulum::loop() {
|
void Reticulum::loop() {
|
||||||
@@ -212,7 +216,6 @@ void Reticulum::loop() {
|
|||||||
// Perform Reticulum housekeeping
|
// Perform Reticulum housekeeping
|
||||||
if (OS::time() > (_object->_jobs_last_run + JOB_INTERVAL)) {
|
if (OS::time() > (_object->_jobs_last_run + JOB_INTERVAL)) {
|
||||||
jobs();
|
jobs();
|
||||||
_object->_jobs_last_run = OS::time();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Perform interface processing
|
// Perform interface processing
|
||||||
@@ -235,6 +238,12 @@ void Reticulum::loop() {
|
|||||||
}
|
}
|
||||||
catch (const std::bad_alloc&) {
|
catch (const std::bad_alloc&) {
|
||||||
ERROR("Reticulum::loop: bad_alloc - OUT OF MEMORY");
|
ERROR("Reticulum::loop: bad_alloc - OUT OF MEMORY");
|
||||||
|
// Critical OOM, restarting
|
||||||
|
#if defined(ESP32)
|
||||||
|
ESP.restart();
|
||||||
|
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||||
|
NVIC_SystemReset();
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
catch (std::exception& e) {
|
catch (std::exception& e) {
|
||||||
ERRORF("Reticulum::loop: %s", e.what());
|
ERRORF("Reticulum::loop: %s", e.what());
|
||||||
@@ -247,8 +256,8 @@ void Reticulum::jobs() {
|
|||||||
|
|
||||||
#if 1
|
#if 1
|
||||||
// CBA Detect low-memory condition and reset
|
// CBA Detect low-memory condition and reset
|
||||||
if (OS::heap_size() > 0) {
|
if (Memory::heap_size() > 0) {
|
||||||
uint8_t remaining = (uint8_t)((double)OS::heap_available() / (double)OS::heap_size() * 100.0);
|
uint8_t remaining = (uint8_t)((double)Memory::heap_available() / (double)Memory::heap_size() * 100.0);
|
||||||
if (remaining <= 2) {
|
if (remaining <= 2) {
|
||||||
HEADF(LOG_CRITICAL, "DETECTED LOW-MEMORY CONDITION (%d%%), RESETTING!!!", remaining);
|
HEADF(LOG_CRITICAL, "DETECTED LOW-MEMORY CONDITION (%d%%), RESETTING!!!", remaining);
|
||||||
persist_data();
|
persist_data();
|
||||||
@@ -262,14 +271,15 @@ void Reticulum::jobs() {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
if (now > _object->_last_cache_clean + CLEAN_INTERVAL) {
|
if (now > _object->_last_cache_clean + _clean_interval) {
|
||||||
clean_caches();
|
clean_caches();
|
||||||
_object->_last_cache_clean = OS::time();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (now > _object->_last_data_persist + PERSIST_INTERVAL) {
|
if (now > _object->_last_data_persist + _persist_interval) {
|
||||||
persist_data();
|
persist_data();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_object->_jobs_last_run = OS::time();
|
||||||
}
|
}
|
||||||
|
|
||||||
// CBA TODO
|
// CBA TODO
|
||||||
@@ -363,6 +373,7 @@ void Reticulum::clean_caches() {
|
|||||||
Identity::cull_known_destinations();
|
Identity::cull_known_destinations();
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
_object->_last_cache_clean = OS::time();
|
||||||
}
|
}
|
||||||
|
|
||||||
void Reticulum::clear_caches() {
|
void Reticulum::clear_caches() {
|
||||||
@@ -404,7 +415,7 @@ void Reticulum::get_interface_stats() const {
|
|||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const std::map<Bytes, Transport::DestinationEntry>& Reticulum::get_path_table() const {
|
const Transport::PathTable& Reticulum::get_path_table() const {
|
||||||
/*
|
/*
|
||||||
path_table = []
|
path_table = []
|
||||||
for dst_hash in Transport::destination_table:
|
for dst_hash in Transport::destination_table:
|
||||||
|
|||||||
+12
-2
@@ -16,7 +16,7 @@ namespace RNS {
|
|||||||
|
|
||||||
class Reticulum {
|
class Reticulum {
|
||||||
|
|
||||||
public:
|
private:
|
||||||
|
|
||||||
//z router = None
|
//z router = None
|
||||||
//z config = None
|
//z config = None
|
||||||
@@ -42,6 +42,9 @@ namespace RNS {
|
|||||||
static bool __allow_probes;
|
static bool __allow_probes;
|
||||||
static bool panic_on_interface_error;
|
static bool panic_on_interface_error;
|
||||||
|
|
||||||
|
static uint16_t _persist_interval;
|
||||||
|
static uint16_t _clean_interval;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
// Return the currently running Reticulum instance
|
// Return the currently running Reticulum instance
|
||||||
inline static const Reticulum& get_instance() { return _instance; }
|
inline static const Reticulum& get_instance() { return _instance; }
|
||||||
@@ -81,7 +84,7 @@ namespace RNS {
|
|||||||
//void __create_default_config();
|
//void __create_default_config();
|
||||||
//void rpc_loop();
|
//void rpc_loop();
|
||||||
//void get_interface_stats() const;
|
//void get_interface_stats() const;
|
||||||
const std::map<Bytes, Transport::DestinationEntry>& get_path_table() const;
|
const Transport::PathTable& get_path_table() const;
|
||||||
const std::map<Bytes, Transport::RateEntry>& get_rate_table() const;
|
const std::map<Bytes, Transport::RateEntry>& get_rate_table() const;
|
||||||
bool drop_path(const Bytes& destination);
|
bool drop_path(const Bytes& destination);
|
||||||
uint16_t drop_all_via(const Bytes& transport_hash);
|
uint16_t drop_all_via(const Bytes& transport_hash);
|
||||||
@@ -144,6 +147,10 @@ namespace RNS {
|
|||||||
|
|
||||||
// getters/setters
|
// getters/setters
|
||||||
inline bool is_connected_to_shared_instance() const { assert(_object); return _object->_is_connected_to_shared_instance; }
|
inline bool is_connected_to_shared_instance() const { assert(_object); return _object->_is_connected_to_shared_instance; }
|
||||||
|
inline static uint16_t persist_interval() { return _persist_interval; }
|
||||||
|
inline static void persist_interval(uint16_t persist_interval) { _persist_interval = persist_interval; }
|
||||||
|
inline static uint16_t clean_interval() { return _clean_interval; }
|
||||||
|
inline static void clean_interval(uint16_t clean_interval) { _clean_interval = clean_interval; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
class Object {
|
class Object {
|
||||||
@@ -177,6 +184,9 @@ namespace RNS {
|
|||||||
};
|
};
|
||||||
std::shared_ptr<Object> _object;
|
std::shared_ptr<Object> _object;
|
||||||
|
|
||||||
|
// CBA For access to private static members by Transport class
|
||||||
|
friend class Transport;
|
||||||
|
friend class Identity;
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
+308
-336
File diff suppressed because it is too large.
Load diff
+84
-47
@@ -3,6 +3,7 @@
|
|||||||
#include "Packet.h"
|
#include "Packet.h"
|
||||||
#include "Bytes.h"
|
#include "Bytes.h"
|
||||||
#include "Type.h"
|
#include "Type.h"
|
||||||
|
#include "Utilities/Memory.h"
|
||||||
|
|
||||||
#include <map>
|
#include <map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
@@ -13,12 +14,9 @@
|
|||||||
#include <functional>
|
#include <functional>
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
|
|
||||||
//#define INTERFACES_SET
|
#ifndef RNS_LEAN_PATH_TABLE
|
||||||
//#define INTERFACES_LIST
|
#define RNS_LEAN_PATH_TABLE 1
|
||||||
#define INTERFACES_MAP
|
#endif
|
||||||
|
|
||||||
//#define DESTINATIONS_SET
|
|
||||||
#define DESTINATIONS_MAP
|
|
||||||
|
|
||||||
namespace RNS {
|
namespace RNS {
|
||||||
|
|
||||||
@@ -56,6 +54,10 @@ namespace RNS {
|
|||||||
class Transport {
|
class Transport {
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
|
||||||
|
using InterfaceTable = std::map<Bytes, Interface&>;
|
||||||
|
using DestinationTable = std::map<Bytes, Destination>;
|
||||||
|
|
||||||
class Callbacks {
|
class Callbacks {
|
||||||
public:
|
public:
|
||||||
using receive_packet = void(*)(const Bytes& raw, const Interface& interface);
|
using receive_packet = void(*)(const Bytes& raw, const Interface& interface);
|
||||||
@@ -68,8 +70,6 @@ namespace RNS {
|
|||||||
friend class Transport;
|
friend class Transport;
|
||||||
};
|
};
|
||||||
|
|
||||||
public:
|
|
||||||
|
|
||||||
class PacketEntry {
|
class PacketEntry {
|
||||||
public:
|
public:
|
||||||
PacketEntry() {}
|
PacketEntry() {}
|
||||||
@@ -99,6 +99,7 @@ namespace RNS {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
};
|
};
|
||||||
|
using PacketTable = std::map<Bytes, PacketEntry>;
|
||||||
|
|
||||||
// CBA TODO Analyze safety of using Inrerface references here
|
// CBA TODO Analyze safety of using Inrerface references here
|
||||||
// CBA TODO Analyze safety of using Packet references here
|
// CBA TODO Analyze safety of using Packet references here
|
||||||
@@ -111,9 +112,15 @@ namespace RNS {
|
|||||||
_hops(announce_hops),
|
_hops(announce_hops),
|
||||||
_expires(expires),
|
_expires(expires),
|
||||||
_random_blobs(random_blobs),
|
_random_blobs(random_blobs),
|
||||||
|
#if RNS_LEAN_PATH_TABLE
|
||||||
|
_receiving_interface(receiving_interface)
|
||||||
|
#else
|
||||||
_receiving_interface(receiving_interface),
|
_receiving_interface(receiving_interface),
|
||||||
_announce_packet(announce_packet)
|
_announce_packet(announce_packet)
|
||||||
|
#endif
|
||||||
{
|
{
|
||||||
|
if (receiving_interface) _receiving_interface_hash = receiving_interface.get_hash();
|
||||||
|
if (announce_packet) _announce_packet_hash = announce_packet.get_hash();
|
||||||
}
|
}
|
||||||
DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, const Bytes& receiving_interface_hash, const Bytes& announce_packet_hash) :
|
DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set<Bytes>& random_blobs, const Bytes& receiving_interface_hash, const Bytes& announce_packet_hash) :
|
||||||
_timestamp(timestamp),
|
_timestamp(timestamp),
|
||||||
@@ -125,12 +132,33 @@ namespace RNS {
|
|||||||
_announce_packet_hash(announce_packet_hash)
|
_announce_packet_hash(announce_packet_hash)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
inline operator bool() const {
|
||||||
|
return (_receiving_interface_hash && _announce_packet_hash);
|
||||||
|
}
|
||||||
public:
|
public:
|
||||||
// Lazy load receiving_interface and announce_packet
|
// Lazy load receiving_interface and announce_packet
|
||||||
inline Interface& receiving_interface() {
|
inline Interface& receiving_interface() {
|
||||||
if (!_receiving_interface) _receiving_interface = find_interface_from_hash(_receiving_interface_hash);
|
if (!_receiving_interface) _receiving_interface = find_interface_from_hash(_receiving_interface_hash);
|
||||||
return _receiving_interface;
|
return _receiving_interface;
|
||||||
}
|
}
|
||||||
|
#if RNS_LEAN_PATH_TABLE
|
||||||
|
// Lazy load transient announce packet
|
||||||
|
inline Packet announce_packet() {
|
||||||
|
Packet announce_packet = get_cached_packet(_announce_packet_hash);
|
||||||
|
if (announce_packet) {
|
||||||
|
// Announce packet is cached in packed state
|
||||||
|
// so we need to unpack it before accessing.
|
||||||
|
announce_packet.unpack();
|
||||||
|
// We increase the hops, since reading a packet
|
||||||
|
// from cache is equivalent to receiving it again
|
||||||
|
// over an interface. It is cached with it's non-
|
||||||
|
// increased hop-count.
|
||||||
|
announce_packet.hops(announce_packet.hops() + 1);
|
||||||
|
}
|
||||||
|
return announce_packet;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
// Lazy load and cache announce packet
|
||||||
inline Packet& announce_packet() {
|
inline Packet& announce_packet() {
|
||||||
if (!_announce_packet) _announce_packet = get_cached_packet(_announce_packet_hash);
|
if (!_announce_packet) _announce_packet = get_cached_packet(_announce_packet_hash);
|
||||||
if (_announce_packet) {
|
if (_announce_packet) {
|
||||||
@@ -145,11 +173,17 @@ namespace RNS {
|
|||||||
}
|
}
|
||||||
return _announce_packet;
|
return _announce_packet;
|
||||||
}
|
}
|
||||||
|
#endif
|
||||||
// Getters and setters for receiving_interface_hash and announce_packet_hash
|
// Getters and setters for receiving_interface_hash and announce_packet_hash
|
||||||
inline Bytes receiving_interface_hash() const { if (_receiving_interface) return _receiving_interface.get_hash(); return _receiving_interface_hash; }
|
inline Bytes receiving_interface_hash() const { if (_receiving_interface) return _receiving_interface.get_hash(); return _receiving_interface_hash; }
|
||||||
inline void receiving_interface_hash(const Bytes& hash) { if (hash != receiving_interface_hash()) _receiving_interface_hash = hash; _receiving_interface = {Type::NONE}; }
|
inline void receiving_interface_hash(const Bytes& hash) { if (hash == receiving_interface_hash()) return; _receiving_interface_hash = hash; _receiving_interface = {Type::NONE}; }
|
||||||
|
#if RNS_LEAN_PATH_TABLE
|
||||||
|
inline Bytes announce_packet_hash() const { return _announce_packet_hash; }
|
||||||
|
inline void announce_packet_hash(const Bytes& hash) { _announce_packet_hash = hash; }
|
||||||
|
#else
|
||||||
inline Bytes announce_packet_hash() const { if (_announce_packet) return _announce_packet.get_hash(); return _announce_packet_hash; }
|
inline Bytes announce_packet_hash() const { if (_announce_packet) return _announce_packet.get_hash(); return _announce_packet_hash; }
|
||||||
inline void announce_packet_hash(const Bytes& hash) { if (hash != announce_packet_hash()) _announce_packet_hash = hash; _announce_packet = {Type::NONE}; }
|
inline void announce_packet_hash(const Bytes& hash) { if (hash == announce_packet_hash()) return; _announce_packet_hash = hash; _announce_packet = {Type::NONE}; }
|
||||||
|
#endif
|
||||||
public:
|
public:
|
||||||
double _timestamp = 0;
|
double _timestamp = 0;
|
||||||
Bytes _received_from;
|
Bytes _received_from;
|
||||||
@@ -163,8 +197,10 @@ namespace RNS {
|
|||||||
private:
|
private:
|
||||||
Interface _receiving_interface = {Type::NONE};
|
Interface _receiving_interface = {Type::NONE};
|
||||||
Bytes _receiving_interface_hash;
|
Bytes _receiving_interface_hash;
|
||||||
|
#if !RNS_LEAN_PATH_TABLE
|
||||||
//const Packet& _announce_packet;
|
//const Packet& _announce_packet;
|
||||||
Packet _announce_packet = {Type::NONE};
|
Packet _announce_packet = {Type::NONE};
|
||||||
|
#endif
|
||||||
Bytes _announce_packet_hash;
|
Bytes _announce_packet_hash;
|
||||||
public:
|
public:
|
||||||
#ifndef NDEBUG
|
#ifndef NDEBUG
|
||||||
@@ -186,6 +222,8 @@ namespace RNS {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
};
|
};
|
||||||
|
//using PathTable = std::map<Bytes, DestinationEntry>;
|
||||||
|
using PathTable = std::map<Bytes, DestinationEntry, std::less<Bytes>, Utilities::Memory::ContainerAllocator<std::pair<const Bytes, DestinationEntry>>>;
|
||||||
|
|
||||||
// CBA TODO Analyze safety of using Inrerface references here
|
// CBA TODO Analyze safety of using Inrerface references here
|
||||||
// CBA TODO Analyze safety of using Packet references here
|
// CBA TODO Analyze safety of using Packet references here
|
||||||
@@ -217,6 +255,8 @@ namespace RNS {
|
|||||||
bool _block_rebroadcasts = false;
|
bool _block_rebroadcasts = false;
|
||||||
const Interface _attached_interface = {Type::NONE};
|
const Interface _attached_interface = {Type::NONE};
|
||||||
};
|
};
|
||||||
|
//using AnnounceTable = std::map<Bytes, AnnounceEntry>;
|
||||||
|
using AnnounceTable = std::map<Bytes, AnnounceEntry, std::less<Bytes>, Utilities::Memory::ContainerAllocator<std::pair<const Bytes, AnnounceEntry>>>;
|
||||||
|
|
||||||
// CBA TODO Analyze safety of using Inrerface references here
|
// CBA TODO Analyze safety of using Inrerface references here
|
||||||
class LinkEntry {
|
class LinkEntry {
|
||||||
@@ -244,6 +284,7 @@ namespace RNS {
|
|||||||
bool _validated = false;
|
bool _validated = false;
|
||||||
double _proof_timeout = 0;
|
double _proof_timeout = 0;
|
||||||
};
|
};
|
||||||
|
using LinkTable = std::map<Bytes, LinkEntry>;
|
||||||
|
|
||||||
// CBA TODO Analyze safety of using Inrerface references here
|
// CBA TODO Analyze safety of using Inrerface references here
|
||||||
class ReverseEntry {
|
class ReverseEntry {
|
||||||
@@ -259,6 +300,7 @@ namespace RNS {
|
|||||||
const Interface _outbound_interface = {Type::NONE};
|
const Interface _outbound_interface = {Type::NONE};
|
||||||
double _timestamp = 0;
|
double _timestamp = 0;
|
||||||
};
|
};
|
||||||
|
using ReverseTable = std::map<Bytes, ReverseEntry>;
|
||||||
|
|
||||||
// CBA TODO Analyze safety of using Inrerface references here
|
// CBA TODO Analyze safety of using Inrerface references here
|
||||||
class PathRequestEntry {
|
class PathRequestEntry {
|
||||||
@@ -274,6 +316,7 @@ namespace RNS {
|
|||||||
double _timeout = 0;
|
double _timeout = 0;
|
||||||
const Interface _requesting_interface = {Type::NONE};
|
const Interface _requesting_interface = {Type::NONE};
|
||||||
};
|
};
|
||||||
|
using PathRequestTable = std::map<Bytes, PathRequestEntry>;
|
||||||
|
|
||||||
/*
|
/*
|
||||||
// CBA TODO Analyze safety of using Inrerface references here
|
// CBA TODO Analyze safety of using Inrerface references here
|
||||||
@@ -313,9 +356,10 @@ namespace RNS {
|
|||||||
public:
|
public:
|
||||||
const Bytes _tunnel_id;
|
const Bytes _tunnel_id;
|
||||||
const Bytes _interface_hash;
|
const Bytes _interface_hash;
|
||||||
std::map<Bytes, DestinationEntry> _serialised_paths;
|
PathTable _serialised_paths;
|
||||||
double _expires = 0;
|
double _expires = 0;
|
||||||
};
|
};
|
||||||
|
using TunnelTable = std::map<Bytes, TunnelEntry>;
|
||||||
|
|
||||||
class RateEntry {
|
class RateEntry {
|
||||||
public:
|
public:
|
||||||
@@ -330,6 +374,7 @@ namespace RNS {
|
|||||||
double _blocked_until = 0.0;
|
double _blocked_until = 0.0;
|
||||||
std::vector<double> _timestamps;
|
std::vector<double> _timestamps;
|
||||||
};
|
};
|
||||||
|
using RateTable = std::map<Bytes, RateEntry>;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
static void start(const Reticulum& reticulum_instance);
|
static void start(const Reticulum& reticulum_instance);
|
||||||
@@ -346,7 +391,7 @@ namespace RNS {
|
|||||||
static void handle_tunnel(const Bytes& tunnel_id, const Interface& interface);
|
static void handle_tunnel(const Bytes& tunnel_id, const Interface& interface);
|
||||||
static void register_interface(Interface& interface);
|
static void register_interface(Interface& interface);
|
||||||
static void deregister_interface(const Interface& interface);
|
static void deregister_interface(const Interface& interface);
|
||||||
inline static const std::map<Bytes, Interface&>& get_interfaces() { return _interfaces; }
|
inline static const InterfaceTable& get_interfaces() { return _interfaces; }
|
||||||
static void register_destination(Destination& destination);
|
static void register_destination(Destination& destination);
|
||||||
static void deregister_destination(const Destination& destination);
|
static void deregister_destination(const Destination& destination);
|
||||||
static void register_link(Link& link);
|
static void register_link(Link& link);
|
||||||
@@ -362,6 +407,7 @@ namespace RNS {
|
|||||||
static bool clear_cached_packet(const Bytes& packet_hash);
|
static bool clear_cached_packet(const Bytes& packet_hash);
|
||||||
static bool cache_request_packet(const Packet& packet);
|
static bool cache_request_packet(const Packet& packet);
|
||||||
static void cache_request(const Bytes& packet_hash, const Destination& destination);
|
static void cache_request(const Bytes& packet_hash, const Destination& destination);
|
||||||
|
static DestinationEntry& get_path(const Bytes& destination_hash);
|
||||||
static bool remove_path(const Bytes& destination_hash);
|
static bool remove_path(const Bytes& destination_hash);
|
||||||
static bool has_path(const Bytes& destination_hash);
|
static bool has_path(const Bytes& destination_hash);
|
||||||
static uint8_t hops_to(const Bytes& destination_hash);
|
static uint8_t hops_to(const Bytes& destination_hash);
|
||||||
@@ -423,55 +469,42 @@ namespace RNS {
|
|||||||
inline static void hashlist_maxsize(uint16_t hashlist_maxsize) { _hashlist_maxsize = hashlist_maxsize; }
|
inline static void hashlist_maxsize(uint16_t hashlist_maxsize) { _hashlist_maxsize = hashlist_maxsize; }
|
||||||
inline static uint16_t max_pr_tags() { return _max_pr_tags; }
|
inline static uint16_t max_pr_tags() { return _max_pr_tags; }
|
||||||
inline static void max_pr_tags(uint16_t max_pr_tags) { _max_pr_tags = max_pr_tags; }
|
inline static void max_pr_tags(uint16_t max_pr_tags) { _max_pr_tags = max_pr_tags; }
|
||||||
inline static uint16_t probe_destination_enabled() { return _path_table_maxpersist; }
|
inline static uint16_t path_table_maxpersist() { return _path_table_maxpersist; }
|
||||||
inline static void path_table_maxpersist(uint16_t path_table_maxpersist) { _path_table_maxpersist = path_table_maxpersist; }
|
inline static void path_table_maxpersist(uint16_t path_table_maxpersist) { _path_table_maxpersist = path_table_maxpersist; }
|
||||||
// CBA TEST
|
// CBA TEST
|
||||||
static inline void identity(Identity& identity) { _identity = identity; }
|
static inline void identity(Identity& identity) { _identity = identity; }
|
||||||
|
|
||||||
inline static const std::map<Bytes, DestinationEntry>& get_path_table() { return _path_table; }
|
inline static const PathTable& get_path_table() { return _path_table; }
|
||||||
inline static const std::map<Bytes, RateEntry>& get_announce_rate_table() { return _announce_rate_table; }
|
inline static const RateTable& get_announce_rate_table() { return _announce_rate_table; }
|
||||||
inline static const std::map<Bytes, LinkEntry>& get_link_table() { return _link_table; }
|
inline static const LinkTable& get_link_table() { return _link_table; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
// CBA MUST use references to interfaces here in order for virtul overrides for send/receive to work
|
// CBA MUST use references to interfaces here in order for virtul overrides for send/receive to work
|
||||||
#if defined(INTERFACES_SET)
|
|
||||||
// set sorted, can use find
|
|
||||||
//static std::set<std::reference_wrapper<const Interface>, std::less<const Interface>> _interfaces; // All active interfaces
|
|
||||||
static std::set<std::reference_wrapper<Interface>, std::less<Interface>> _interfaces; // All active interfaces
|
|
||||||
#elif defined(INTERFACES_LIST)
|
|
||||||
// list is unsorted, can't use find
|
|
||||||
static std::list<std::reference_wrapper<Interface>> _interfaces; // All active interfaces
|
|
||||||
#elif defined(INTERFACES_MAP)
|
|
||||||
// map is sorted, can use find
|
// map is sorted, can use find
|
||||||
static std::map<Bytes, Interface&> _interfaces; // All active interfaces
|
static InterfaceTable _interfaces; // All active interfaces
|
||||||
#endif
|
static DestinationTable _destinations; // All active destinations
|
||||||
#if defined(DESTINATIONS_SET)
|
|
||||||
static std::set<Destination> _destinations; // All active destinations
|
|
||||||
#elif defined(DESTINATIONS_MAP)
|
|
||||||
static std::map<Bytes, Destination> _destinations; // All active destinations
|
|
||||||
#endif
|
|
||||||
// CBA TODO: Reconsider using std::set for enforcing uniqueness. Maybe consider std::map keyed on hash instead
|
// CBA TODO: Reconsider using std::set for enforcing uniqueness. Maybe consider std::map keyed on hash instead
|
||||||
static std::set<Link> _pending_links; // Links that are being established
|
static std::set<Link> _pending_links; // Links that are being established
|
||||||
static std::set<Link> _active_links; // Links that are active
|
static std::set<Link> _active_links; // Links that are active
|
||||||
static std::set<Bytes> _packet_hashlist; // A list of packet hashes for duplicate detection
|
static std::set<Bytes> _packet_hashlist; // A list of packet hashes for duplicate detection
|
||||||
static std::list<PacketReceipt> _receipts; // Receipts of all outgoing packets for proof processing
|
static std::list<PacketReceipt> _receipts; // Receipts of all outgoing packets for proof processing
|
||||||
|
|
||||||
// TODO: "destination_table" should really be renamed to "path_table"
|
// TODO: "destination_table" should really be renamed to "path_table"
|
||||||
// Notes on memory usage: 1 megabyte of memory can store approximately
|
// Notes on memory usage: 1 megabyte of memory can store approximately
|
||||||
// 55.100 path table entries or approximately 22.300 link table entries.
|
// 55.100 path table entries or approximately 22.300 link table entries.
|
||||||
|
|
||||||
static std::map<Bytes, AnnounceEntry> _announce_table; // A table for storing announces currently waiting to be retransmitted
|
static AnnounceTable _announce_table; // A table for storing announces currently waiting to be retransmitted
|
||||||
static std::map<Bytes, DestinationEntry> _path_table; // A lookup table containing the next hop to a given destination
|
static PathTable _path_table; // A lookup table containing the next hop to a given destination
|
||||||
static std::map<Bytes, ReverseEntry> _reverse_table; // A lookup table for storing packet hashes used to return proofs and replies
|
static ReverseTable _reverse_table; // A lookup table for storing packet hashes used to return proofs and replies
|
||||||
static std::map<Bytes, LinkEntry> _link_table; // A lookup table containing hops for links
|
static LinkTable _link_table; // A lookup table containing hops for links
|
||||||
static std::map<Bytes, AnnounceEntry> _held_announces; // A table containing temporarily held announce-table entries
|
static AnnounceTable _held_announces; // A table containing temporarily held announce-table entries
|
||||||
static std::set<HAnnounceHandler> _announce_handlers; // A table storing externally registered announce handlers
|
static TunnelTable _tunnels; // A table storing tunnels to other transport instances
|
||||||
static std::map<Bytes, TunnelEntry> _tunnels; // A table storing tunnels to other transport instances
|
static RateTable _announce_rate_table; // A table for keeping track of announce rates
|
||||||
static std::map<Bytes, RateEntry> _announce_rate_table; // A table for keeping track of announce rates
|
static std::set<HAnnounceHandler> _announce_handlers; // A table storing externally registered announce handlers
|
||||||
static std::map<Bytes, double> _path_requests; // A table for storing path request timestamps
|
static std::map<Bytes, double> _path_requests; // A table for storing path request timestamps
|
||||||
|
|
||||||
static std::map<Bytes, PathRequestEntry> _discovery_path_requests; // A table for keeping track of path requests on behalf of other nodes
|
static PathRequestTable _discovery_path_requests; // A table for keeping track of path requests on behalf of other nodes
|
||||||
static std::set<Bytes> _discovery_pr_tags; // A table for keeping track of tagged path requests
|
static std::set<Bytes> _discovery_pr_tags; // A table for keeping track of tagged path requests
|
||||||
|
|
||||||
// Transport control destinations are used
|
// Transport control destinations are used
|
||||||
// for control purposes like path requests
|
// for control purposes like path requests
|
||||||
@@ -487,7 +520,7 @@ namespace RNS {
|
|||||||
static std::map<Bytes, const Interface&> _pending_local_path_requests;
|
static std::map<Bytes, const Interface&> _pending_local_path_requests;
|
||||||
|
|
||||||
// CBA
|
// CBA
|
||||||
static std::map<Bytes, PacketEntry> _packet_table; // A lookup table containing announce packets for known paths
|
static PacketTable _packet_table; // A lookup table containing announce packets for known paths
|
||||||
|
|
||||||
//z _local_client_rssi_cache = []
|
//z _local_client_rssi_cache = []
|
||||||
//z _local_client_snr_cache = []
|
//z _local_client_snr_cache = []
|
||||||
@@ -529,7 +562,11 @@ namespace RNS {
|
|||||||
static uint32_t _packets_received;
|
static uint32_t _packets_received;
|
||||||
static uint32_t _destinations_added;
|
static uint32_t _destinations_added;
|
||||||
static size_t _last_memory;
|
static size_t _last_memory;
|
||||||
|
static size_t _last_psram;
|
||||||
static size_t _last_flash;
|
static size_t _last_flash;
|
||||||
|
|
||||||
|
// CBA Block re-entrance
|
||||||
|
static bool cleaning_caches;
|
||||||
};
|
};
|
||||||
|
|
||||||
template <typename M, typename S>
|
template <typename M, typename S>
|
||||||
|
|||||||
+2
-4
@@ -130,13 +130,11 @@ namespace RNS { namespace Type {
|
|||||||
//static const uint16_t JOB_INTERVAL = 60*5;
|
//static const uint16_t JOB_INTERVAL = 60*5;
|
||||||
static const uint16_t JOB_INTERVAL = 60;
|
static const uint16_t JOB_INTERVAL = 60;
|
||||||
// CBA TEST
|
// CBA TEST
|
||||||
static uint16_t CLEAN_INTERVAL = 60*15;
|
static const uint16_t CLEAN_INTERVAL = 60*15;
|
||||||
//static uint16_t CLEAN_INTERVAL = 60;
|
|
||||||
// CBA MCU
|
// CBA MCU
|
||||||
//static const uint16_t PERSIST_INTERVAL = 60*60*12;
|
//static const uint16_t PERSIST_INTERVAL = 60*60*12;
|
||||||
// CBA TEST
|
// CBA TEST
|
||||||
static uint16_t PERSIST_INTERVAL = 60*60;
|
static const uint16_t PERSIST_INTERVAL = 60*60;
|
||||||
//static uint16_t PERSIST_INTERVAL = 60;
|
|
||||||
static const uint16_t GRACIOUS_PERSIST_INTERVAL = 60*5;
|
static const uint16_t GRACIOUS_PERSIST_INTERVAL = 60*5;
|
||||||
|
|
||||||
static const uint8_t DESTINATION_LENGTH = TRUNCATED_HASHLENGTH/8; // In bytes
|
static const uint8_t DESTINATION_LENGTH = TRUNCATED_HASHLENGTH/8; // In bytes
|
||||||
|
|||||||
@@ -0,0 +1,567 @@
|
|||||||
|
#include "Memory.h"
|
||||||
|
|
||||||
|
#include <new>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
using namespace RNS;
|
||||||
|
using namespace RNS::Utilities;
|
||||||
|
|
||||||
|
#ifndef RNS_DEFAULT_ALLOCATOR
|
||||||
|
#if defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||||
|
// Use TLSF on NRF52 boards by default since they don't embed their own advanced memory manager like ESP32 does
|
||||||
|
#define RNS_DEFAULT_ALLOCATOR RNS_HEAP_POOL_ALLOCATOR
|
||||||
|
#else
|
||||||
|
#define RNS_DEFAULT_ALLOCATOR RNS_HEAP_ALLOCATOR
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
#ifndef RNS_CONTAINER_ALLOCATOR
|
||||||
|
#if defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||||
|
// Use TLSF on NRF52 boards by default since they don't embed their own advanced memory manager like ESP32 does
|
||||||
|
#define RNS_CONTAINER_ALLOCATOR RNS_HEAP_POOL_ALLOCATOR
|
||||||
|
#else
|
||||||
|
#define RNS_CONTAINER_ALLOCATOR RNS_HEAP_ALLOCATOR
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef RNS_HEAP_POOL_BUFFER_SIZE
|
||||||
|
//#define RNS_HEAP_POOL_BUFFER_SIZE 1024 * 80
|
||||||
|
#define RNS_HEAP_POOL_BUFFER_SIZE 0
|
||||||
|
#endif
|
||||||
|
#ifndef RNS_PSRAM_POOL_BUFFER_SIZE
|
||||||
|
#define RNS_PSRAM_POOL_BUFFER_SIZE 0
|
||||||
|
#endif
|
||||||
|
#ifndef RNS_ALTHEAP_POOL_BUFFER_SIZE
|
||||||
|
#define RNS_ALTHEAP_POOL_BUFFER_SIZE 0
|
||||||
|
#endif
|
||||||
|
#ifndef BUFFER_FRACTION
|
||||||
|
#define BUFFER_FRACTION 0.8
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
//char _tlsf_msg[256] = "";
|
||||||
|
|
||||||
|
/*static*/ Memory::pool_info Memory::heap_pool_info(RNS_HEAP_POOL_ALLOCATOR, RNS_HEAP_POOL_BUFFER_SIZE);
|
||||||
|
/*static*/ Memory::pool_info Memory::psram_pool_info(RNS_PSRAM_POOL_ALLOCATOR, RNS_PSRAM_POOL_BUFFER_SIZE);;
|
||||||
|
/*static*/ Memory::pool_info Memory::altheap_pool_info(RNS_ALTHEAP_POOL_ALLOCATOR, RNS_ALTHEAP_POOL_BUFFER_SIZE);;
|
||||||
|
/*static*/ Memory::allocator_info Memory::default_allocator_info;
|
||||||
|
/*static*/ Memory::allocator_info Memory::container_allocator_info;
|
||||||
|
|
||||||
|
|
||||||
|
/*static*/ void Memory::pool_init(Memory::pool_info& pool_info) {
|
||||||
|
if (pool_info.pool_init) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pool_info.pool_init = true;
|
||||||
|
printf("Initializing TLSF pool...\n");
|
||||||
|
|
||||||
|
#if defined(ESP32)
|
||||||
|
heap_pool_info.contiguous_size = ESP.getMaxAllocHeap();
|
||||||
|
psram_pool_info.contiguous_size = ESP.getMaxAllocPsram();
|
||||||
|
altheap_pool_info.contiguous_size = ESP.getMaxAllocHeap();
|
||||||
|
printf("TLSF: Heap contiguous_size: %u\n", ESP.getMaxAllocHeap());
|
||||||
|
printf("TLSF: PSRAM contiguous_size: %u\n", ESP.getMaxAllocPsram());
|
||||||
|
printf("TLSF: contiguous_size: %u\n", pool_info.contiguous_size);
|
||||||
|
if (pool_info.buffer_size == 0) {
|
||||||
|
// CBA NOTE Using fp mathhere somehow causes tlsf_create_with_pool() to fail.
|
||||||
|
//pool_info.buffer_size = (size_t)(pool_info.contiguous_size * BUFFER_FRACTION);
|
||||||
|
// Compute 80% exactly using integers
|
||||||
|
pool_info.buffer_size = (pool_info.contiguous_size * 4) / 5;
|
||||||
|
}
|
||||||
|
// Round DOWN to TLSF alignment
|
||||||
|
size_t align = tlsf_align_size();
|
||||||
|
pool_info.buffer_size &= ~(align - 1);
|
||||||
|
void* raw_buffer = nullptr;
|
||||||
|
// If pool type is PSRAM then allocate pool buffer from PSRAM
|
||||||
|
if (pool_info.type == RNS_PSRAM_POOL_ALLOCATOR) {
|
||||||
|
raw_buffer = (void*)ps_malloc(pool_info.buffer_size);
|
||||||
|
}
|
||||||
|
// Otherwise just allocate from heap
|
||||||
|
else {
|
||||||
|
raw_buffer = (void*)aligned_alloc(align, pool_info.buffer_size);
|
||||||
|
}
|
||||||
|
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||||
|
heap_pool_info.contiguous_size = dbgHeapFree();
|
||||||
|
altheap_pool_info.contiguous_size = dbgHeapFree();
|
||||||
|
TRACEF("TLSF: contiguous_size: %u", pool_info.contiguous_size);
|
||||||
|
if (pool_info.buffer_size == 0) {
|
||||||
|
pool_info.buffer_size = (size_t)(pool_info.contiguous_size * BUFFER_FRACTION);
|
||||||
|
}
|
||||||
|
// For NRF52 round to kB
|
||||||
|
pool_info.buffer_size = (size_t)(pool_info.buffer_size / 1024) * 1024;
|
||||||
|
TRACEF("TLSF: buffer_size: %u", pool_info.buffer_size);
|
||||||
|
void* raw_buffer = malloc(pool_info.buffer_size);
|
||||||
|
#else
|
||||||
|
pool_info.buffer_size = (size_t)RNS_HEAP_POOL_BUFFER_SIZE;
|
||||||
|
TRACEF("TLSF: buffer_size: %u", pool_info.buffer_size);
|
||||||
|
void* raw_buffer = malloc(pool_info.buffer_size);
|
||||||
|
#endif
|
||||||
|
if (raw_buffer == nullptr) {
|
||||||
|
ERROR("-- TLSF: buffer allocation FAILED");
|
||||||
|
printf("TLSF buffer allocation FAILED!\n");
|
||||||
|
//strcpy(_tlsf_msg, "-- TLSF: buffer allocation FAILED!!!");
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
#if 1
|
||||||
|
pool_info.tlsf = tlsf_create_with_pool(raw_buffer, pool_info.buffer_size);
|
||||||
|
if (pool_info.tlsf == nullptr) {
|
||||||
|
//sprintf(_tlsf_msg, "TLSF: initialization with align=%d, contiguous=%d, size=%d FAILED!!!", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
|
||||||
|
printf("TLSF: initialization with align=%d, contiguous=%d, size=%d FAILED!!!\n", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
//sprintf(_tlsf_msg, "TLSF: initialization with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
|
||||||
|
printf("TLSF: initialization with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!\n", tlsf_align_size(), pool_info.contiguous_size, pool_info.buffer_size);
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
Serial.print("TLSF: raw_buffer: ");
|
||||||
|
Serial.println((long)raw_buffer);
|
||||||
|
Serial.print("TLSF: align_size: ");
|
||||||
|
Serial.println((long)tlsf_align_size());
|
||||||
|
void* aligned_buffer = (void*)(((size_t)raw_buffer + (tlsf_align_size() - 1)) & ~(tlsf_align_size() - 1));
|
||||||
|
Serial.print("TLSF: aligned_buffer: ");
|
||||||
|
Serial.println((long)aligned_buffer);
|
||||||
|
pool_info.tlsf = tlsf_create_with_pool(aligned_buffer, pool_info.buffer_size-(size_t)((uint32_t)aligned_buffer - (uint32_t)raw_buffer));
|
||||||
|
//tlfs = tlsf_create_with_pool(aligned_buffer, pool_info.buffer_size--(size_t)((uint32_t)aligned_buffer - (uint32_t)raw_buffer));
|
||||||
|
#endif
|
||||||
|
if (pool_info.tlsf == nullptr) {
|
||||||
|
ERROR("-- TLSF: initialization of FAILED");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/*static*/ void* Memory::pool_malloc(Memory::pool_info& pool_info, size_t size) {
|
||||||
|
if (size == 0) return nullptr;
|
||||||
|
//if (pool_info.tlsf == nullptr) {
|
||||||
|
if (!pool_info.pool_init) {
|
||||||
|
Memory::pool_init(pool_info);
|
||||||
|
}
|
||||||
|
void* p;
|
||||||
|
if (pool_info.tlsf != nullptr) {
|
||||||
|
//struct tlsf_stats stats;
|
||||||
|
//memset(&stats, 0, sizeof(stats));
|
||||||
|
//tlsf_walk_pool(tlsf_get_pool(pool_info.tlsf), tlsf_mem_walker, &stats);
|
||||||
|
//if (tlsf_check(pool_info.tlsf) != 0) {
|
||||||
|
// printf("--- HEAP CORRUPTION DETECTED!!!\n");
|
||||||
|
//}
|
||||||
|
//TRACEF("--- allocating memory from tlsf (%u bytes)", size);
|
||||||
|
//printf("--- allocating memory from tlsf (%u bytes) (%u free)\n", size, stats.free_size);
|
||||||
|
p = tlsf_malloc(pool_info.tlsf, size);
|
||||||
|
//TRACEF("--- allocated memory from tlsf (addr=%lx) (%u bytes)", p, size);
|
||||||
|
//printf("--- allocated memory from tlsf (addr=%lx) (%u bytes)\n", p, size);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
//TRACEF("--- allocating memory (%u bytes)", size);
|
||||||
|
p = malloc(size);
|
||||||
|
//TRACEF("--- allocated memory (addr=%lx) (%u bytes)", p, size);
|
||||||
|
++pool_info.alloc_fault;
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*static*/ void Memory::pool_free(Memory::pool_info& pool_info, void* p, size_t size /*= 0*/) noexcept {
|
||||||
|
if (p == nullptr) return;
|
||||||
|
if (pool_info.tlsf != nullptr) {
|
||||||
|
//TRACEF("--- freeing memory from tlsf (addr=%lx)", p);
|
||||||
|
//printf("--- freeing memory from tlsf (addr=%lx)\n", p);
|
||||||
|
tlsf_free(pool_info.tlsf, p);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
//TRACEF("--- freeing memory (addr=%lx)", p);
|
||||||
|
free(p);
|
||||||
|
++pool_info.free_fault;
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
if (free_count == _alloc_count) {
|
||||||
|
TRACE("TLFS deinitializing");
|
||||||
|
dump_memory_stats();
|
||||||
|
tlsf_destroy(pool_info.tlsf);
|
||||||
|
pool_info.tlsf = nullptr;
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
struct tlsf_stats {
|
||||||
|
uint32_t used_count = 0;
|
||||||
|
uint32_t used_size = 0;
|
||||||
|
uint32_t free_count = 0;
|
||||||
|
uint32_t free_size = 0;
|
||||||
|
uint32_t free_max_size = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
void tlsf_mem_walker(void* ptr, size_t size, int used, void* user)
|
||||||
|
{
|
||||||
|
if (!user) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
struct tlsf_stats* stats = (struct tlsf_stats*)user;
|
||||||
|
if (used) {
|
||||||
|
stats->used_count++;
|
||||||
|
stats->used_size += size;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
stats->free_count++;
|
||||||
|
stats->free_size += size;
|
||||||
|
if (size > stats->free_max_size) {
|
||||||
|
stats->free_max_size = size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*static*/ void Memory::dump_pool_stats(Memory::pool_info& pool_info, const char* name /*= ""*/) {
|
||||||
|
//TRACEF("TLSF Message: %s", _tlsf_msg);
|
||||||
|
if (pool_info.tlsf == nullptr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
struct tlsf_stats stats;
|
||||||
|
memset(&stats, 0, sizeof(stats));
|
||||||
|
tlsf_walk_pool(tlsf_get_pool(pool_info.tlsf), tlsf_mem_walker, &stats);
|
||||||
|
HEADF(LOG_TRACE, "%sPool Stats", name);
|
||||||
|
TRACEF(" Buffer Size: %u", pool_info.buffer_size);
|
||||||
|
TRACEF(" Contiguous Size: %u", pool_info.contiguous_size);
|
||||||
|
TRACEF(" Used Count: %u", stats.used_count);
|
||||||
|
TRACEF(" Used Size: %u (%u%% used)", stats.used_size, (unsigned)((double)stats.used_size / (double)pool_info.buffer_size * 100.0));
|
||||||
|
TRACEF(" Free Count: %u", stats.free_count);
|
||||||
|
TRACEF(" Free Size: %u (%u%% free)", stats.free_size, (unsigned)((double)stats.free_size / (double)pool_info.buffer_size * 100.0));
|
||||||
|
TRACEF(" Max Free Size: %u (%u%% fragmented)", stats.free_max_size, (unsigned)(100.0 - (double)stats.free_max_size / (double)stats.free_size * 100.0));
|
||||||
|
//TRACEF(" alloc_count: %u", pool_info.alloc_count);
|
||||||
|
TRACEF(" alloc_fault: %u", pool_info.alloc_fault);
|
||||||
|
//TRACEF(" free_count: %u", pool_info.free_count);
|
||||||
|
TRACEF(" free_fault: %u", pool_info.free_fault);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*static*/ void Memory::dump_basic_pool_stats() {
|
||||||
|
|
||||||
|
size_t heap_free = 0;
|
||||||
|
uint8_t heap_pct = 0;
|
||||||
|
if (heap_pool_info.tlsf != nullptr) {
|
||||||
|
struct tlsf_stats stats;
|
||||||
|
memset(&stats, 0, sizeof(stats));
|
||||||
|
tlsf_walk_pool(tlsf_get_pool(heap_pool_info.tlsf), tlsf_mem_walker, &stats);
|
||||||
|
heap_free = stats.free_size;
|
||||||
|
heap_pct = (uint8_t)((double)heap_free / (double)heap_pool_info.buffer_size * 100.0);
|
||||||
|
}
|
||||||
|
if (heap_pool_info.last_free == 0) {
|
||||||
|
heap_pool_info.last_free = heap_free;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t psram_free = 0;
|
||||||
|
uint8_t psram_pct = 0;
|
||||||
|
if (psram_pool_info.tlsf != nullptr) {
|
||||||
|
struct tlsf_stats stats;
|
||||||
|
memset(&stats, 0, sizeof(stats));
|
||||||
|
tlsf_walk_pool(tlsf_get_pool(psram_pool_info.tlsf), tlsf_mem_walker, &stats);
|
||||||
|
psram_free = stats.free_size;
|
||||||
|
psram_pct = (uint8_t)((double)psram_free / (double)psram_pool_info.buffer_size * 100.0);
|
||||||
|
}
|
||||||
|
if (psram_pool_info.last_free == 0) {
|
||||||
|
psram_pool_info.last_free = psram_free;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t altheap_free = 0;
|
||||||
|
uint8_t altheap_pct = 0;
|
||||||
|
if (altheap_pool_info.tlsf != nullptr) {
|
||||||
|
struct tlsf_stats stats;
|
||||||
|
memset(&stats, 0, sizeof(stats));
|
||||||
|
tlsf_walk_pool(tlsf_get_pool(altheap_pool_info.tlsf), tlsf_mem_walker, &stats);
|
||||||
|
altheap_free = stats.free_size;
|
||||||
|
altheap_pct = (uint8_t)((double)altheap_free / (double)altheap_pool_info.buffer_size * 100.0);
|
||||||
|
}
|
||||||
|
if (altheap_pool_info.last_free == 0) {
|
||||||
|
altheap_pool_info.last_free = altheap_free;
|
||||||
|
}
|
||||||
|
|
||||||
|
VERBOSEF("heap_pool: %u (%u%%) [%d] psram_pool: %u (%u%%) [%d] alt_pool: %u (%u%%) [%d]", heap_free, heap_pct, heap_free - heap_pool_info.last_free, psram_free, psram_pct, psram_free - psram_pool_info.last_free, altheap_free, altheap_pct, altheap_free - altheap_pool_info.last_free);
|
||||||
|
|
||||||
|
heap_pool_info.last_free = heap_free;
|
||||||
|
psram_pool_info.last_free = psram_free;
|
||||||
|
altheap_pool_info.last_free = altheap_free;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*static*/ void Memory::dump_allocator_stats(Memory::allocator_info& allocator_info, const char* name /*= ""*/) {
|
||||||
|
HEADF(LOG_TRACE, "%sAllocator Stats", name);
|
||||||
|
TRACEF(" Active Count: %u", (allocator_info.alloc_count - allocator_info.free_count));
|
||||||
|
TRACEF(" Min Size: %u", allocator_info.min_alloc_size);
|
||||||
|
TRACEF(" Max Size: %u", allocator_info.max_alloc_size);
|
||||||
|
TRACEF(" Avg Size: %u", (size_t)((allocator_info.alloc_count > 0) ? (allocator_info.alloc_size / allocator_info.alloc_count) : 0));
|
||||||
|
TRACEF(" alloc_count: %u", allocator_info.alloc_count);
|
||||||
|
TRACEF(" alloc_fault: %u", allocator_info.alloc_fault);
|
||||||
|
TRACEF(" free_count: %u", allocator_info.free_count);
|
||||||
|
TRACEF(" free_fault: %u", allocator_info.free_fault);
|
||||||
|
}
|
||||||
|
|
||||||
|
/*static*/ void Memory::dump_basic_allocator_stats() {
|
||||||
|
|
||||||
|
int dflt_diff = 0;
|
||||||
|
// Increase in used memory, negative diff
|
||||||
|
if (default_allocator_info.alloc_size > default_allocator_info.last_size) {
|
||||||
|
dflt_diff = (int)(default_allocator_info.alloc_size - default_allocator_info.last_size) * -1;
|
||||||
|
}
|
||||||
|
// Decrease in used memory, positive diff
|
||||||
|
else {
|
||||||
|
dflt_diff = (int)(default_allocator_info.last_size - default_allocator_info.alloc_size);
|
||||||
|
}
|
||||||
|
//if (default_allocator_info.last_size == 0) {
|
||||||
|
// default_allocator_info.last_size = default_allocator_info.alloc_size;
|
||||||
|
//}
|
||||||
|
|
||||||
|
int cntr_diff = 0;
|
||||||
|
// Increase in used memory, negative diff
|
||||||
|
if (container_allocator_info.alloc_size > container_allocator_info.last_size) {
|
||||||
|
cntr_diff = (int)(container_allocator_info.alloc_size - container_allocator_info.last_size) * -1;
|
||||||
|
}
|
||||||
|
// Decrease in used memory, positive diff
|
||||||
|
else {
|
||||||
|
cntr_diff = (int)(container_allocator_info.last_size - container_allocator_info.alloc_size);
|
||||||
|
}
|
||||||
|
//if (container_allocator_info.last_size == 0) {
|
||||||
|
// container_allocator_info.last_size = container_allocator_info.alloc_size;
|
||||||
|
//}
|
||||||
|
|
||||||
|
VERBOSEF("dflt_alloc: %llu [%d] cntr_alloc: %llu [%d]", default_allocator_info.alloc_size, dflt_diff, container_allocator_info.alloc_size, cntr_diff);
|
||||||
|
|
||||||
|
default_allocator_info.last_size = default_allocator_info.alloc_size;
|
||||||
|
container_allocator_info.last_size = container_allocator_info.alloc_size;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
size_t maxContiguousAllocation() {
|
||||||
|
// Brute-force determine maximum allocation size
|
||||||
|
//const size_t block_size = 256;
|
||||||
|
const size_t block_size = 32;
|
||||||
|
size_t block_count;
|
||||||
|
for (block_count = 1; ; block_count++) {
|
||||||
|
void* ptr = malloc(block_count * block_size);
|
||||||
|
if (ptr == nullptr) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
free(ptr);
|
||||||
|
}
|
||||||
|
return (block_count - 1) * block_size;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*static*/ size_t Memory::heap_size() {
|
||||||
|
#if defined(ESP32)
|
||||||
|
return ESP.getHeapSize();
|
||||||
|
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||||
|
return dbgHeapTotal();
|
||||||
|
#else
|
||||||
|
return 0;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*static*/ size_t Memory::heap_available() {
|
||||||
|
#if defined(ESP32)
|
||||||
|
return ESP.getFreeHeap();
|
||||||
|
//return ESP.getMaxAllocHeap();
|
||||||
|
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||||
|
return dbgHeapFree();
|
||||||
|
#else
|
||||||
|
return 0;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
/*static*/ void Memory::dump_heap_stats() {
|
||||||
|
#if defined(ESP32)
|
||||||
|
HEAD("Heap Stats", LOG_TRACE);
|
||||||
|
TRACEF(" Heap size: %u", ESP.getHeapSize());
|
||||||
|
TRACEF(" Heap free: %u (%u%% free)", ESP.getFreeHeap(), (unsigned)((double)ESP.getFreeHeap() / (double)ESP.getHeapSize() * 100.0));
|
||||||
|
//TRACEF(" Heap free: %u (%u%% free)", xPortGetFreeHeapSize(), (unsigned)((double)xPortGetFreeHeapSize() / (double)xPort * 100.0));
|
||||||
|
TRACEF(" Heap min free: %u", ESP.getMinFreeHeap());
|
||||||
|
//TRACEF(" Heap min free: %u", xPortGetMinimumEverFreeHeapSize());
|
||||||
|
TRACEF(" Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)ESP.getFreeHeap() * 100.0));
|
||||||
|
//TRACEF(" Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)xPortGetFreeHeapSize() * 100.0));
|
||||||
|
TRACEF(" PSRAM size: %u", ESP.getPsramSize());
|
||||||
|
TRACEF(" PSRAM free: %u (%u%% free)", ESP.getFreePsram(), (ESP.getPsramSize() > 0) ? (unsigned)((double)ESP.getFreePsram() / (double)ESP.getPsramSize() * 100.0) : 0);
|
||||||
|
TRACEF(" PSRAM min free: %u", ESP.getMinFreePsram());
|
||||||
|
TRACEF(" PSRAM max alloc: %u (%u%% fragmented)", ESP.getMaxAllocPsram(), (ESP.getFreePsram() > 0) ? (unsigned)(100.0 - (double)ESP.getMaxAllocPsram() / (double)ESP.getFreePsram() * 100.0) : 0);
|
||||||
|
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
||||||
|
HEAD("Heap Stats", LOG_TRACE);
|
||||||
|
if (loglevel() == LOG_TRACE) {
|
||||||
|
dbgMemInfo();
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
dump_allocator_stats(default_allocator_info, "Default ");
|
||||||
|
dump_allocator_stats(container_allocator_info, "Container ");
|
||||||
|
|
||||||
|
dump_pool_stats(heap_pool_info, "Heap ");
|
||||||
|
dump_pool_stats(psram_pool_info, "PSRAM ");
|
||||||
|
dump_pool_stats(altheap_pool_info, "AltHeap ");
|
||||||
|
dump_basic_pool_stats();
|
||||||
|
dump_basic_allocator_stats();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Only override new/delete if RNS_DEFAULT_ALLOCATOR is not RNS_HEAP_ALLOCATOR
|
||||||
|
#if RNS_DEFAULT_ALLOCATOR != RNS_HEAP_ALLOCATOR
|
||||||
|
|
||||||
|
void* allocator_malloc(size_t size) {
|
||||||
|
if (size == 0) return nullptr;
|
||||||
|
++Memory::default_allocator_info.alloc_count;
|
||||||
|
Memory::default_allocator_info.alloc_size += size;
|
||||||
|
if (size < Memory::default_allocator_info.min_alloc_size || Memory::default_allocator_info.min_alloc_size == 0) {
|
||||||
|
Memory::default_allocator_info.min_alloc_size = size;
|
||||||
|
}
|
||||||
|
if (size > Memory::default_allocator_info.max_alloc_size) {
|
||||||
|
Memory::default_allocator_info.max_alloc_size = size;
|
||||||
|
}
|
||||||
|
#if RNS_DEFAULT_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
|
||||||
|
return Memory::pool_malloc(Memory::heap_pool_info, size);
|
||||||
|
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_ALLOCATOR
|
||||||
|
#if BOARD_HAS_PSRAM != 1
|
||||||
|
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||||
|
#endif
|
||||||
|
// CBA PSRAM may not be accessible early in startup, but since we use the same free() for both
|
||||||
|
// HEAP and PSRAM allocations, we canb simply fallback to HEAP allocation when PSRAM fails
|
||||||
|
void* p = ps_malloc(size);
|
||||||
|
if (p == nullptr) {
|
||||||
|
++Memory::default_allocator_info.alloc_fault;
|
||||||
|
p = malloc(size);
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
|
||||||
|
#error "RNS_DEFAULT_ALLOCATOR can not be set to RNS_PSRAM_POOL_ALLOCATOR because PSRAM isn't initialized early enough."
|
||||||
|
#if BOARD_HAS_PSRAM != 1
|
||||||
|
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||||
|
#endif
|
||||||
|
return Memory::pool_malloc(Memory::psram_pool_info, size);
|
||||||
|
#elif RNS_DEFAULT_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
|
||||||
|
return Memory::pool_malloc(Memory::altheap_pool_info, size);
|
||||||
|
#elif RNS_DEFAULT_ALLOCATOR == RNS_HEAP_ALLOCATOR
|
||||||
|
return ::operator new(n * sizeof(value_type));
|
||||||
|
#else
|
||||||
|
#error "Unknown or invalid allocator."
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
void allocator_free(void* p, size_t size = 0) noexcept {
|
||||||
|
if (p == nullptr) return;
|
||||||
|
++Memory::default_allocator_info.free_count;
|
||||||
|
Memory::default_allocator_info.alloc_size -= size;
|
||||||
|
#if RNS_DEFAULT_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
|
||||||
|
Memory::pool_free(Memory::heap_pool_info, p, size);
|
||||||
|
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_ALLOCATOR
|
||||||
|
#if BOARD_HAS_PSRAM != 1
|
||||||
|
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||||
|
#endif
|
||||||
|
free(p);
|
||||||
|
#elif RNS_DEFAULT_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
|
||||||
|
#error "RNS_DEFAULT_ALLOCATOR can not be set to RNS_PSRAM_POOL_ALLOCATOR because PSRAM isn't initialized early enough."
|
||||||
|
#if BOARD_HAS_PSRAM != 1
|
||||||
|
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||||
|
#endif
|
||||||
|
Memory::pool_free(Memory::psram_pool_info, p, size);
|
||||||
|
#elif RNS_DEFAULT_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
|
||||||
|
Memory::pool_free(Memory::altheap_pool_info, p, size);
|
||||||
|
#elif RNS_DEFAULT_ALLOCATOR == RNS_HEAP_ALLOCATOR
|
||||||
|
::operator delete(p);
|
||||||
|
#else
|
||||||
|
#error "Unknown or invalid allocator."
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------------------------------------
|
||||||
|
// Standard allocation
|
||||||
|
//--------------------------------------------------
|
||||||
|
|
||||||
|
// CBA Added attribute weak to avoid collision with new override on nrf52
|
||||||
|
void* operator new(size_t size) {
|
||||||
|
//__attribute__((weak)) void* operator new(size_t size) {
|
||||||
|
//printf("--- new allocating memory from tlsf (%u bytes)\n", size);
|
||||||
|
void* p = allocator_malloc(size);
|
||||||
|
if (p == nullptr) {
|
||||||
|
throw std::bad_alloc();
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
void* operator new[](size_t size) {
|
||||||
|
//printf("--- new[] allocating memory from tlsf (%u bytes)\n", size);
|
||||||
|
void* p = allocator_malloc(size);
|
||||||
|
if (p == nullptr) {
|
||||||
|
throw std::bad_alloc();
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------------------------------------
|
||||||
|
// Nothrow allocation
|
||||||
|
//--------------------------------------------------
|
||||||
|
|
||||||
|
void* operator new(size_t size, const std::nothrow_t&) noexcept {
|
||||||
|
//printf("--- new no-throw allocating memory from tlsf (%u bytes)\n", size);
|
||||||
|
return allocator_malloc(size);
|
||||||
|
}
|
||||||
|
|
||||||
|
void* operator new[](size_t size, const std::nothrow_t&) noexcept {
|
||||||
|
//printf("--- new[] no-throw allocating memory from tlsf (%u bytes)\n", size);
|
||||||
|
return allocator_malloc(size);
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------------------------------------
|
||||||
|
// Standard delete
|
||||||
|
//--------------------------------------------------
|
||||||
|
|
||||||
|
// CBA Added attribute weak to avoid collision with new override on nrf52
|
||||||
|
void operator delete(void* p) noexcept {
|
||||||
|
//__attribute__((weak)) void operator delete(void* p) noexcept {
|
||||||
|
//printf("--- delete freeing memory from tlsf (addr=%lx)\n", p);
|
||||||
|
if (p != nullptr) allocator_free(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
void operator delete[](void* p) noexcept {
|
||||||
|
//printf("--- delete[] freeing memory from tlsf (addr=%lx)\n", p);
|
||||||
|
if (p != nullptr) allocator_free(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------------------------------------
|
||||||
|
// Sized delete (C++14+)
|
||||||
|
//--------------------------------------------------
|
||||||
|
|
||||||
|
void operator delete(void* p, size_t size) noexcept { // sized delete
|
||||||
|
//printf("--- delete(size) freeing memory from tlsf (addr=%lx)\n", p);
|
||||||
|
if (p != nullptr) allocator_free(p, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
void operator delete[](void* p, size_t size) noexcept {
|
||||||
|
//printf("--- delete[](size) freeing memory from tlsf (addr=%lx)\n", p);
|
||||||
|
if (p != nullptr) allocator_free(p, size);
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------------------------------------
|
||||||
|
// Nothrow delete
|
||||||
|
//--------------------------------------------------
|
||||||
|
|
||||||
|
void operator delete(void* p, const std::nothrow_t&) noexcept {
|
||||||
|
//printf("--- delete no-throw freeing memory from tlsf (addr=%lx)\n", p);
|
||||||
|
if (p != nullptr) allocator_free(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
void operator delete[](void* p, const std::nothrow_t&) noexcept {
|
||||||
|
//printf("--- delete[] no-throw freeing memory from tlsf (addr=%lx)\n", p);
|
||||||
|
if (p != nullptr) allocator_free(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
//--------------------------------------------------
|
||||||
|
// Aligned allocation/delete (C++17+)
|
||||||
|
//--------------------------------------------------
|
||||||
|
|
||||||
|
#if __cplusplus >= 201703L
|
||||||
|
void* operator new(size_t size, std::align_val_t) {
|
||||||
|
//printf("--- new aligned allocating memory from tlsf (%u bytes)\n", size);
|
||||||
|
void* p = allocator_malloc(size);
|
||||||
|
if (p == nullptr) {
|
||||||
|
throw std::bad_alloc();
|
||||||
|
}
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
void operator delete(void* p, std::align_val_t) {
|
||||||
|
//printf("--- delete aligned freeing memory from tlsf (addr=%lx)\n", p);
|
||||||
|
if (p != nullptr) allocator_free(p);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "../Log.h"
|
||||||
|
|
||||||
|
#include "tlsf.h"
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
#define RNS_HEAP_ALLOCATOR 0 // Use HEAP for allocator
|
||||||
|
#define RNS_HEAP_POOL_ALLOCATOR 1 // Use HEAP pool for allocator
|
||||||
|
#define RNS_PSRAM_ALLOCATOR 2 // Use PSRAM for allocator
|
||||||
|
#define RNS_PSRAM_POOL_ALLOCATOR 3 // Use PSRAM pool for allocator
|
||||||
|
#define RNS_ALTHEAP_POOL_ALLOCATOR 4 // Use alternate HEAP pool for allocator
|
||||||
|
|
||||||
|
namespace RNS { namespace Utilities {
|
||||||
|
|
||||||
|
class Memory {
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
struct pool_info {
|
||||||
|
constexpr pool_info(uint8_t t, size_t s) : type(t), buffer_size(s) {}
|
||||||
|
uint8_t type = 0;
|
||||||
|
bool pool_init = false;
|
||||||
|
size_t buffer_size = 0;
|
||||||
|
size_t contiguous_size = 0;
|
||||||
|
tlsf_t tlsf = nullptr;
|
||||||
|
uint32_t alloc_fault = 0;
|
||||||
|
uint32_t free_fault = 0;
|
||||||
|
size_t last_free = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct allocator_info {
|
||||||
|
uint32_t alloc_count = 0;
|
||||||
|
uint32_t alloc_fault = 0;
|
||||||
|
uint32_t free_count = 0;
|
||||||
|
uint32_t free_fault = 0;
|
||||||
|
uint64_t alloc_size = 0;
|
||||||
|
size_t min_alloc_size = 0;
|
||||||
|
size_t max_alloc_size = 0;
|
||||||
|
uint64_t last_size = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
public:
|
||||||
|
|
||||||
|
static void pool_init(pool_info& pool_info);
|
||||||
|
static void* pool_malloc(pool_info& pool_info, size_t size);
|
||||||
|
static void pool_free(pool_info& pool_info, void* p, size_t size = 0) noexcept;
|
||||||
|
|
||||||
|
static void dump_pool_stats(pool_info& pool_info, const char* name = "");
|
||||||
|
static void dump_basic_pool_stats();
|
||||||
|
|
||||||
|
static void dump_allocator_stats(Memory::allocator_info& allocator_info, const char* name = "");
|
||||||
|
static void dump_basic_allocator_stats();
|
||||||
|
|
||||||
|
static size_t heap_size();
|
||||||
|
static size_t heap_available();
|
||||||
|
static void dump_heap_stats();
|
||||||
|
|
||||||
|
public:
|
||||||
|
|
||||||
|
static pool_info heap_pool_info;
|
||||||
|
static pool_info psram_pool_info;
|
||||||
|
static pool_info altheap_pool_info;
|
||||||
|
|
||||||
|
static allocator_info default_allocator_info;
|
||||||
|
static allocator_info container_allocator_info;
|
||||||
|
|
||||||
|
public:
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
struct ContainerAllocator {
|
||||||
|
using value_type = T;
|
||||||
|
|
||||||
|
ContainerAllocator() noexcept {}
|
||||||
|
|
||||||
|
// Essential for std::map internal node allocation
|
||||||
|
template <class U>
|
||||||
|
ContainerAllocator(const ContainerAllocator<U>&) noexcept {}
|
||||||
|
|
||||||
|
/*
|
||||||
|
// Required for embedded toolchains (ESP32 Xtensa GCC) that don't synthesiz
|
||||||
|
// rebind automatically via std::allocator_traits
|
||||||
|
template<class U>
|
||||||
|
struct rebind {
|
||||||
|
using other = ContainerAllocator<U>;
|
||||||
|
};
|
||||||
|
*/
|
||||||
|
|
||||||
|
T* allocate(std::size_t n) {
|
||||||
|
if (n == 0) return nullptr;
|
||||||
|
size_t size = n * sizeof(value_type);
|
||||||
|
++container_allocator_info.alloc_count;
|
||||||
|
container_allocator_info.alloc_size += size;
|
||||||
|
if (size < container_allocator_info.min_alloc_size || container_allocator_info.min_alloc_size == 0) {
|
||||||
|
container_allocator_info.min_alloc_size = size;
|
||||||
|
}
|
||||||
|
if (size > container_allocator_info.max_alloc_size) {
|
||||||
|
container_allocator_info.max_alloc_size = size;
|
||||||
|
}
|
||||||
|
#if RNS_CONTAINER_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
|
||||||
|
void* p = pool_malloc(heap_pool_info, size);
|
||||||
|
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_ALLOCATOR
|
||||||
|
#if BOARD_HAS_PSRAM != 1
|
||||||
|
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||||
|
#endif
|
||||||
|
// CBA PSRAM may not be accessible early in startup, but since we use the same free() for both
|
||||||
|
// HEAP and PSRAM allocations, we canb simply fallback to HEAP allocation when PSRAM fails
|
||||||
|
void* p = ps_malloc(size);
|
||||||
|
if (p == nullptr) {
|
||||||
|
++container_allocator_info.alloc_fault;
|
||||||
|
p = malloc(size);
|
||||||
|
}
|
||||||
|
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
|
||||||
|
#if BOARD_HAS_PSRAM != 1
|
||||||
|
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||||
|
#endif
|
||||||
|
void* p = pool_malloc(psram_pool_info, size);
|
||||||
|
#elif RNS_CONTAINER_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
|
||||||
|
void* p = pool_malloc(altheap_pool_info, size);
|
||||||
|
#elif RNS_CONTAINER_ALLOCATOR == RNS_HEAP_ALLOCATOR
|
||||||
|
void* p = ::operator new(size);
|
||||||
|
#else
|
||||||
|
#error "Unknown or invalid allocator."
|
||||||
|
#endif
|
||||||
|
if (p == nullptr) {
|
||||||
|
ERRORF("--- ContainerAllocator failed to allocate memory (%u bytes)", size);
|
||||||
|
throw std::bad_alloc();
|
||||||
|
}
|
||||||
|
//TRACEF("--- ContainerAllocator allocated memory (addr=%lx) (%u bytes)", p, size);
|
||||||
|
return static_cast<T*>(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
void deallocate(T* p, std::size_t n) noexcept {
|
||||||
|
if (p == nullptr) return;
|
||||||
|
size_t size = n * sizeof(value_type);
|
||||||
|
++default_allocator_info.free_count;
|
||||||
|
container_allocator_info.alloc_size -= size;
|
||||||
|
//TRACEF("--- ContainerAllocator freeing memory (addr=%lx) (%u bytes)", p, size);
|
||||||
|
#if RNS_CONTAINER_ALLOCATOR == RNS_HEAP_POOL_ALLOCATOR
|
||||||
|
pool_free(heap_pool_info, p, size);
|
||||||
|
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_ALLOCATOR
|
||||||
|
#if BOARD_HAS_PSRAM != 1
|
||||||
|
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||||
|
#endif
|
||||||
|
free(p);
|
||||||
|
#elif RNS_CONTAINER_ALLOCATOR == RNS_PSRAM_POOL_ALLOCATOR
|
||||||
|
#if BOARD_HAS_PSRAM != 1
|
||||||
|
#error "BOARD_HAS_PSRAM must be defined to use RNS_PSRAM_POOL_ALLOCATOR allocator."
|
||||||
|
#endif
|
||||||
|
pool_free(psram_pool_info, p, size);
|
||||||
|
#elif RNS_CONTAINER_ALLOCATOR == RNS_ALTHEAP_POOL_ALLOCATOR
|
||||||
|
pool_free(altheap_pool_info, p, size);
|
||||||
|
#elif RNS_CONTAINER_ALLOCATOR == RNS_HEAP_ALLOCATOR
|
||||||
|
::operator delete(p);
|
||||||
|
#else
|
||||||
|
#error "Unknown or invalid allocator."
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
// Equality operators are required
|
||||||
|
bool operator==(const ContainerAllocator&) const noexcept { return true; }
|
||||||
|
bool operator!=(const ContainerAllocator&) const noexcept { return false; }
|
||||||
|
//template <class T, class U>
|
||||||
|
//bool operator==(const MyAllocator<T>&, const MyAllocator<U>&) { return true; }
|
||||||
|
//template <class T, class U>
|
||||||
|
//bool operator!=(const MyAllocator<T>&, const MyAllocator<U>&) { return false; }
|
||||||
|
};
|
||||||
|
|
||||||
|
};
|
||||||
|
|
||||||
|
} }
|
||||||
+1
-362
@@ -8,367 +8,6 @@
|
|||||||
using namespace RNS;
|
using namespace RNS;
|
||||||
using namespace RNS::Utilities;
|
using namespace RNS::Utilities;
|
||||||
|
|
||||||
|
|
||||||
#if defined(RNS_USE_ALLOCATOR)
|
|
||||||
|
|
||||||
#if defined(RNS_USE_TLSF)
|
|
||||||
#if defined(ESP32)
|
|
||||||
#ifndef RNS_TLSF_BUFFER_SIZE
|
|
||||||
//#define RNS_TLSF_BUFFER_SIZE 1024 * 80
|
|
||||||
#define RNS_TLSF_BUFFER_SIZE 0
|
|
||||||
#endif
|
|
||||||
#ifndef BUFFER_FRACTION
|
|
||||||
#define BUFFER_FRACTION 0.8
|
|
||||||
#endif
|
|
||||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
|
||||||
#ifndef RNS_TLSF_BUFFER_SIZE
|
|
||||||
//#define RNS_TLSF_BUFFER_SIZE 1024 * 80
|
|
||||||
#define RNS_TLSF_BUFFER_SIZE 0
|
|
||||||
#endif
|
|
||||||
#ifndef BUFFER_FRACTION
|
|
||||||
#define BUFFER_FRACTION 0.8
|
|
||||||
#endif
|
|
||||||
#else
|
|
||||||
#ifndef RNS_TLSF_BUFFER_SIZE
|
|
||||||
#define RNS_TLSF_BUFFER_SIZE 1024 * 1000
|
|
||||||
#endif
|
|
||||||
#ifndef BUFFER_FRACTION
|
|
||||||
#define BUFFER_FRACTION 0
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
struct tlsf_stats {
|
|
||||||
uint32_t used_count = 0;
|
|
||||||
uint32_t used_size = 0;
|
|
||||||
uint32_t free_count = 0;
|
|
||||||
uint32_t free_size = 0;
|
|
||||||
uint32_t free_max_size = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
bool _pool_init = false;
|
|
||||||
//char _tlsf_msg[256] = "";
|
|
||||||
size_t _buffer_size = RNS_TLSF_BUFFER_SIZE;
|
|
||||||
size_t _contiguous_size = 0;
|
|
||||||
|
|
||||||
/*static*/ //tlsf_t OS::_tlsf = tlsf_create_with_pool(malloc(1024 * 1024), 1024 * 1024);
|
|
||||||
/*static*/ tlsf_t OS::_tlsf = nullptr;
|
|
||||||
#endif // RNS_USE_TLSF
|
|
||||||
|
|
||||||
uint32_t _new_count = 0;
|
|
||||||
uint32_t _new_fault = 0;
|
|
||||||
uint64_t _new_size = 0;
|
|
||||||
uint32_t _delete_count = 0;
|
|
||||||
uint32_t _delete_fault = 0;
|
|
||||||
size_t _min_size = 0;
|
|
||||||
size_t _max_size = 0;
|
|
||||||
|
|
||||||
void tlsf_mem_walker(void* ptr, size_t size, int used, void* user);
|
|
||||||
void dump_tlsf_stats();
|
|
||||||
|
|
||||||
#if defined(RNS_USE_TLSF)
|
|
||||||
inline void pool_init() {
|
|
||||||
|
|
||||||
#if defined(ESP32)
|
|
||||||
// CBA Still unknown why the call to tlsf_create_with_pool() is so flaky on ESP32 with calculated buffer size. Reuires more research and unit tests.
|
|
||||||
_contiguous_size = ESP.getMaxAllocHeap();
|
|
||||||
TRACEF("TLSF: contiguous_size: %u", _contiguous_size);
|
|
||||||
if (_buffer_size == 0) {
|
|
||||||
// CBA NOTE Using fp mathhere somehow causes tlsf_create_with_pool() to fail.
|
|
||||||
//_buffer_size = (size_t)(_contiguous_size * BUFFER_FRACTION);
|
|
||||||
// Compute 80% exactly using integers
|
|
||||||
_buffer_size = (_contiguous_size * 4) / 5;
|
|
||||||
}
|
|
||||||
// Round DOWN to TLSF alignment
|
|
||||||
size_t align = tlsf_align_size();
|
|
||||||
_buffer_size &= ~(align - 1);
|
|
||||||
void* raw_buffer = (void*)aligned_alloc(align, _buffer_size);
|
|
||||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
|
||||||
_contiguous_size = dbgHeapFree();
|
|
||||||
TRACEF("TLSF: contiguous_size: %u", _contiguous_size);
|
|
||||||
if (_buffer_size == 0) {
|
|
||||||
_buffer_size = (size_t)(_contiguous_size * BUFFER_FRACTION);
|
|
||||||
}
|
|
||||||
// For NRF52 round to kB
|
|
||||||
_buffer_size = (size_t)(_buffer_size / 1024) * 1024;
|
|
||||||
TRACEF("TLSF: buffer_size: %u", _buffer_size);
|
|
||||||
void* raw_buffer = malloc(_buffer_size);
|
|
||||||
#else
|
|
||||||
_buffer_size = (size_t)RNS_TLSF_BUFFER_SIZE;
|
|
||||||
TRACEF("TLSF: buffer_size: %u", _buffer_size);
|
|
||||||
void* raw_buffer = malloc(_buffer_size);
|
|
||||||
#endif
|
|
||||||
if (raw_buffer == nullptr) {
|
|
||||||
ERROR("-- TLSF: buffer allocation FAILED");
|
|
||||||
//strcpy(_tlsf_msg, "-- TLSF: buffer allocation FAILED!!!");
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
#if 1
|
|
||||||
OS::_tlsf = tlsf_create_with_pool(raw_buffer, _buffer_size);
|
|
||||||
if (OS::_tlsf == nullptr) {
|
|
||||||
//sprintf(_tlsf_msg, "TLSF: initialization with align=%d, contiguous=%d, size=%d FAILED!!!", tlsf_align_size(), _contiguous_size, _buffer_size);
|
|
||||||
printf("TLSF: initialization with align=%d, contiguous=%d, size=%d FAILED!!!\n", tlsf_align_size(), _contiguous_size, _buffer_size);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
//sprintf(_tlsf_msg, "TLSF: initialization with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!", tlsf_align_size(), _contiguous_size, _buffer_size);
|
|
||||||
printf("TLSF: initialization with align=%d, contiguous=%d, size=%d SUCCESSFUL!!!\n", tlsf_align_size(), _contiguous_size, _buffer_size);
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
Serial.print("TLSF: raw_buffer: ");
|
|
||||||
Serial.println((long)raw_buffer);
|
|
||||||
Serial.print("TLSF: align_size: ");
|
|
||||||
Serial.println((long)tlsf_align_size());
|
|
||||||
void* aligned_buffer = (void*)(((size_t)raw_buffer + (tlsf_align_size() - 1)) & ~(tlsf_align_size() - 1));
|
|
||||||
Serial.print("TLSF: aligned_buffer: ");
|
|
||||||
Serial.println((long)aligned_buffer);
|
|
||||||
OS::_tlsf = tlsf_create_with_pool(aligned_buffer, _buffer_size-(size_t)((uint32_t)aligned_buffer - (uint32_t)raw_buffer));
|
|
||||||
//tlfs = tlsf_create_with_pool(aligned_buffer, buffer_size--(size_t)((uint32_t)aligned_buffer - (uint32_t)raw_buffer));
|
|
||||||
#endif
|
|
||||||
if (OS::_tlsf == nullptr) {
|
|
||||||
ERROR("-- TLSF: initialization of FAILED");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
#endif // RNS_USE_TLSF
|
|
||||||
|
|
||||||
void* pool_malloc(std::size_t size) {
|
|
||||||
#if defined(RNS_USE_TLSF)
|
|
||||||
//if (OS::_tlsf == nullptr) {
|
|
||||||
if (!_pool_init) {
|
|
||||||
_pool_init = true;
|
|
||||||
printf("Initializing TLSF pool...\n");
|
|
||||||
pool_init();
|
|
||||||
}
|
|
||||||
#endif // RNS_USE_TLSF
|
|
||||||
++_new_count;
|
|
||||||
_new_size += size;
|
|
||||||
if (size < _min_size || _min_size == 0) {
|
|
||||||
_min_size = size;
|
|
||||||
}
|
|
||||||
//if (size > _max_size) {
|
|
||||||
if (size < 4192 && size > _max_size) {
|
|
||||||
_max_size = size;
|
|
||||||
}
|
|
||||||
void* p;
|
|
||||||
#if defined(RNS_USE_TLSF)
|
|
||||||
if (OS::_tlsf != nullptr) {
|
|
||||||
//struct tlsf_stats stats;
|
|
||||||
//memset(&stats, 0, sizeof(stats));
|
|
||||||
//tlsf_walk_pool(tlsf_get_pool(OS::_tlsf), tlsf_mem_walker, &stats);
|
|
||||||
//if (tlsf_check(OS::_tlsf) != 0) {
|
|
||||||
// printf("--- HEAP CORRUPTION DETECTED!!!\n");
|
|
||||||
//}
|
|
||||||
//TRACEF("--- allocating memory from tlsf (%u bytes)", size);
|
|
||||||
//printf("--- allocating memory from tlsf (%u bytes) (%u free)\n", size, stats.free_size);
|
|
||||||
p = tlsf_malloc(OS::_tlsf, size);
|
|
||||||
//TRACEF("--- allocated memory from tlsf (addr=%lx) (%u bytes)", p, size);
|
|
||||||
//printf("--- allocated memory from tlsf (addr=%lx) (%u bytes)\n", p, size);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
//TRACEF("--- allocating memory (%u bytes)", size);
|
|
||||||
p = malloc(size);
|
|
||||||
//TRACEF("--- allocated memory (addr=%lx) (%u bytes)", p, size);
|
|
||||||
++_new_fault;
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
//TRACEF("--- allocating memory (%u bytes)", size);
|
|
||||||
p = malloc(size);
|
|
||||||
//TRACEF("--- allocated memory (addr=%lx) (%u bytes)", p, size);
|
|
||||||
#endif // RNS_USE_TLSF
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
|
|
||||||
void pool_free(void* p) noexcept {
|
|
||||||
#if defined(RNS_USE_TLSF)
|
|
||||||
if (OS::_tlsf != nullptr) {
|
|
||||||
//TRACEF("--- freeing memory from tlsf (addr=%lx)", p);
|
|
||||||
//printf("--- freeing memory from tlsf (addr=%lx)\n", p);
|
|
||||||
tlsf_free(OS::_tlsf, p);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
//TRACEF("--- freeing memory (addr=%lx)", p);
|
|
||||||
free(p);
|
|
||||||
++_delete_fault;
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
//TRACEF("--- freeing memory (addr=%lx)", p);
|
|
||||||
//TRACE("--- freeing memory");
|
|
||||||
free(p);
|
|
||||||
#endif // RNS_USE_TLSF
|
|
||||||
++_delete_count;
|
|
||||||
#if defined(RNS_USE_TLSF)
|
|
||||||
//if (_delete_count == _new_count) {
|
|
||||||
// TRACE("TLFS deinitializing");
|
|
||||||
// OS::dump_memory_stats();
|
|
||||||
// tlsf_destroy(OS::_tlsf);
|
|
||||||
// OS::_tlsf = nullptr;
|
|
||||||
//}
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// CBA Added attribute weak to avoid collision with new override on nrf52
|
|
||||||
void* operator new(std::size_t size) {
|
|
||||||
//__attribute__((weak)) void* operator new(std::size_t size) {
|
|
||||||
//printf("--- new allocating memory from tlsf (%u bytes)\n", size);
|
|
||||||
void* p = pool_malloc(size);
|
|
||||||
if (p == nullptr) {
|
|
||||||
throw std::bad_alloc();
|
|
||||||
}
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
|
|
||||||
// CBA Added attribute weak to avoid collision with new override on nrf52
|
|
||||||
void operator delete(void* p) noexcept {
|
|
||||||
//__attribute__((weak)) void operator delete(void* p) noexcept {
|
|
||||||
//printf("--- delete freeing memory from tlsf (addr=%lx)\n", p);
|
|
||||||
pool_free(p);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**/
|
|
||||||
void* operator new[](std::size_t size) {
|
|
||||||
//printf("--- new[] allocating memory from tlsf (%u bytes)\n", size);
|
|
||||||
void* p = pool_malloc(size);
|
|
||||||
if (p == nullptr) {
|
|
||||||
throw std::bad_alloc();
|
|
||||||
}
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
|
|
||||||
void operator delete[](void* p) noexcept {
|
|
||||||
//printf("--- delete[] freeing memory from tlsf (addr=%lx)\n", p);
|
|
||||||
pool_free(p);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void operator delete(void* p, std::size_t size) noexcept { // sized delete
|
|
||||||
//printf("--- delete(size) freeing memory from tlsf (addr=%lx)\n", p);
|
|
||||||
pool_free(p);
|
|
||||||
}
|
|
||||||
|
|
||||||
void operator delete[](void* p, std::size_t size) noexcept {
|
|
||||||
//printf("--- delete[](size) freeing memory from tlsf (addr=%lx)\n", p);
|
|
||||||
pool_free(p);
|
|
||||||
}
|
|
||||||
/**/
|
|
||||||
|
|
||||||
|
|
||||||
#if defined(RNS_USE_TLSF)
|
|
||||||
void tlsf_mem_walker(void* ptr, size_t size, int used, void* user)
|
|
||||||
{
|
|
||||||
if (!user) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
struct tlsf_stats* stats = (struct tlsf_stats*)user;
|
|
||||||
if (used) {
|
|
||||||
stats->used_count++;
|
|
||||||
stats->used_size += size;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
stats->free_count++;
|
|
||||||
stats->free_size += size;
|
|
||||||
if (size > stats->free_max_size) {
|
|
||||||
stats->free_max_size = size;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
void dump_tlsf_stats() {
|
|
||||||
struct tlsf_stats stats;
|
|
||||||
memset(&stats, 0, sizeof(stats));
|
|
||||||
//TRACEF("TLSF Message: %s", _tlsf_msg);
|
|
||||||
if (OS::_tlsf == nullptr) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
tlsf_walk_pool(tlsf_get_pool(OS::_tlsf), tlsf_mem_walker, &stats);
|
|
||||||
HEAD("TLSF Stats", LOG_TRACE);
|
|
||||||
TRACEF("Buffer Size: %u", _buffer_size);
|
|
||||||
TRACEF("Contiguous Size: %u", _contiguous_size);
|
|
||||||
TRACEF("Used Count: %u", stats.used_count);
|
|
||||||
TRACEF("Used Size: %u (%u%% used)", stats.used_size, (unsigned)((double)stats.used_size / (double)_buffer_size * 100.0));
|
|
||||||
TRACEF("Free Count: %u", stats.free_count);
|
|
||||||
TRACEF("Free Size: %u (%u%% free)", stats.free_size, (unsigned)((double)stats.free_size / (double)_buffer_size * 100.0));
|
|
||||||
TRACEF("Max Free Size: %u (%u%% fragmented)\n", stats.free_max_size, (unsigned)(100.0 - (double)stats.free_max_size / (double)stats.free_size * 100.0));
|
|
||||||
}
|
|
||||||
#endif // RNS_USE_TLSF
|
|
||||||
|
|
||||||
/*static*/ void OS::dump_allocator_stats() {
|
|
||||||
HEAD("Allocator Stats", LOG_TRACE);
|
|
||||||
TRACEF("New Count: %u", _new_count);
|
|
||||||
TRACEF("New Fault: %u", _new_fault);
|
|
||||||
TRACEF("Delete Count: %u", _delete_count);
|
|
||||||
TRACEF("Delete Fault: %u", _delete_fault);
|
|
||||||
TRACEF("Active Count: %u", (_new_count - _delete_count));
|
|
||||||
TRACEF("Min Size: %u", _min_size);
|
|
||||||
TRACEF("Max Size: %u", _max_size);
|
|
||||||
TRACEF("Avg Size: %u\n", (size_t)(_new_size / _new_count));
|
|
||||||
#if defined(RNS_USE_TLSF)
|
|
||||||
dump_tlsf_stats();
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif // RNS_USE_ALLOCATOR
|
|
||||||
|
|
||||||
|
|
||||||
size_t maxContiguousAllocation() {
|
|
||||||
// Brute-force determine maximum allocation size
|
|
||||||
//const size_t block_size = 256;
|
|
||||||
const size_t block_size = 32;
|
|
||||||
size_t block_count;
|
|
||||||
for (block_count = 1; ; block_count++) {
|
|
||||||
void* ptr = malloc(block_count * block_size);
|
|
||||||
if (ptr == nullptr) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
free(ptr);
|
|
||||||
}
|
|
||||||
return (block_count - 1) * block_size;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*static*/ FileSystem OS::_filesystem = {Type::NONE};
|
/*static*/ FileSystem OS::_filesystem = {Type::NONE};
|
||||||
/*static*/ uint64_t OS::_time_offset = 0;
|
/*static*/ uint64_t OS::_time_offset = 0;
|
||||||
|
/*static*/ OS::LoopCallback OS::_on_loop = nullptr;
|
||||||
/*static*/ size_t OS::heap_size() {
|
|
||||||
#if defined(ESP32)
|
|
||||||
return ESP.getHeapSize();
|
|
||||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
|
||||||
return dbgHeapTotal();
|
|
||||||
#else
|
|
||||||
return 0;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
/*static*/ size_t OS::heap_available() {
|
|
||||||
#if defined(ESP32)
|
|
||||||
return ESP.getFreeHeap();
|
|
||||||
//return ESP.getMaxAllocHeap();
|
|
||||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
|
||||||
return dbgHeapFree();
|
|
||||||
#else
|
|
||||||
return 0;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
/*static*/ void OS::dump_heap_stats() {
|
|
||||||
HEAD("Heap Stats", LOG_TRACE);
|
|
||||||
#if defined(ESP32)
|
|
||||||
TRACEF("Heap size: %u", ESP.getHeapSize());
|
|
||||||
TRACEF("Heap free: %u (%u%% free)", ESP.getFreeHeap(), (unsigned)((double)ESP.getFreeHeap() / (double)ESP.getHeapSize() * 100.0));
|
|
||||||
//TRACEF("Heap free: %u (%u%% free)", xPortGetFreeHeapSize(), (unsigned)((double)xPortGetFreeHeapSize() / (double)xPort * 100.0));
|
|
||||||
TRACEF("Heap min free: %u", ESP.getMinFreeHeap());
|
|
||||||
//TRACEF("Heap min free: %u", xPortGetMinimumEverFreeHeapSize());
|
|
||||||
TRACEF("Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)ESP.getFreeHeap() * 100.0));
|
|
||||||
//TRACEF("Heap max alloc: %u (%u%% fragmented)", ESP.getMaxAllocHeap(), (unsigned)(100.0 - (double)ESP.getMaxAllocHeap() / (double)xPortGetFreeHeapSize() * 100.0));
|
|
||||||
TRACEF("PSRAM size: %u", ESP.getPsramSize());
|
|
||||||
TRACEF("PSRAM free: %u (%u%% free)", ESP.getFreePsram(), (ESP.getPsramSize() > 0) ? (unsigned)((double)ESP.getFreePsram() / (double)ESP.getPsramSize() * 100.0) : 0);
|
|
||||||
TRACEF("PSRAM min free: %u", ESP.getMinFreePsram());
|
|
||||||
TRACEF("PSRAM max alloc: %u (%u%% fragmented)", ESP.getMaxAllocPsram(), (ESP.getFreePsram() > 0) ? (unsigned)(100.0 - (double)ESP.getMaxAllocPsram() / (double)ESP.getFreePsram() * 100.0) : 0);
|
|
||||||
#elif defined(ARDUINO_ARCH_NRF52) || defined(ARDUINO_NRF52_ADAFRUIT)
|
|
||||||
if (loglevel() == LOG_TRACE) {
|
|
||||||
dbgMemInfo();
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#if defined(RNS_USE_ALLOCATOR)
|
|
||||||
OS::dump_allocator_stats();
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
+49
-34
@@ -4,9 +4,9 @@
|
|||||||
#include "../FileStream.h"
|
#include "../FileStream.h"
|
||||||
#include "../Bytes.h"
|
#include "../Bytes.h"
|
||||||
|
|
||||||
#include "tlsf.h"
|
|
||||||
|
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
|
#include <memory>
|
||||||
|
#include <functional>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
@@ -14,6 +14,9 @@
|
|||||||
|
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
|
#if defined(ESP32)
|
||||||
|
#include "esp_task_wdt.h"
|
||||||
|
#endif
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#undef round
|
#undef round
|
||||||
@@ -22,20 +25,22 @@ namespace RNS { namespace Utilities {
|
|||||||
|
|
||||||
class OS {
|
class OS {
|
||||||
|
|
||||||
|
public:
|
||||||
|
//using LoopCallback = void(*)();
|
||||||
|
using LoopCallback = std::function<void()>;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static FileSystem _filesystem;
|
static FileSystem _filesystem;
|
||||||
static uint64_t _time_offset;
|
static uint64_t _time_offset;
|
||||||
|
static LoopCallback _on_loop;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
static tlsf_t _tlsf;
|
inline static uint64_t getTimeOffset() { return _time_offset; }
|
||||||
|
inline static void setTimeOffset(uint64_t offset) { _time_offset = offset; }
|
||||||
public:
|
|
||||||
static inline uint64_t getTimeOffset() { return _time_offset; }
|
|
||||||
static inline void setTimeOffset(uint64_t offset) { _time_offset = offset; }
|
|
||||||
|
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
// return current time in milliseconds since startup
|
// return current time in milliseconds since startup
|
||||||
static inline uint64_t ltime() {
|
inline static uint64_t ltime() {
|
||||||
// handle roll-over of 32-bit millis (approx. 49 days)
|
// handle roll-over of 32-bit millis (approx. 49 days)
|
||||||
static uint32_t low32, high32;
|
static uint32_t low32, high32;
|
||||||
uint32_t new_low32 = millis();
|
uint32_t new_low32 = millis();
|
||||||
@@ -45,32 +50,32 @@ namespace RNS { namespace Utilities {
|
|||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
// return current time in milliseconds since 00:00:00, January 1, 1970 (Unix Epoch)
|
// return current time in milliseconds since 00:00:00, January 1, 1970 (Unix Epoch)
|
||||||
static inline uint64_t ltime() { timeval time; ::gettimeofday(&time, NULL); return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); }
|
inline static uint64_t ltime() { timeval time; ::gettimeofday(&time, NULL); return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); }
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
// return current time in float seconds since startup
|
// return current time in float seconds since startup
|
||||||
static inline double time() { return (double)(ltime() / 1000.0); }
|
inline static double time() { return (double)(ltime() / 1000.0); }
|
||||||
#else
|
#else
|
||||||
// return current time in float seconds since 00:00:00, January 1, 1970 (Unix Epoch)
|
// return current time in float seconds since 00:00:00, January 1, 1970 (Unix Epoch)
|
||||||
static inline double time() { timeval time; ::gettimeofday(&time, NULL); return (double)time.tv_sec + ((double)time.tv_usec / 1000000); }
|
inline static double time() { timeval time; ::gettimeofday(&time, NULL); return (double)time.tv_sec + ((double)time.tv_usec / 1000000); }
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// sleep for specified milliseconds
|
// sleep for specified milliseconds
|
||||||
//static inline void sleep(float seconds) { ::sleep(seconds); }
|
//inline static void sleep(float seconds) { ::sleep(seconds); }
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
static inline void sleep(float seconds) { delay((uint32_t)(seconds * 1000)); }
|
inline static void sleep(float seconds) { delay((uint32_t)(seconds * 1000)); }
|
||||||
#else
|
#else
|
||||||
static inline void sleep(float seconds) { timespec time; time.tv_sec = (time_t)(seconds); time.tv_nsec = (seconds - (float)time.tv_sec) * 1000000000; ::nanosleep(&time, nullptr); }
|
inline static void sleep(float seconds) { timespec time; time.tv_sec = (time_t)(seconds); time.tv_nsec = (seconds - (float)time.tv_sec) * 1000000000; ::nanosleep(&time, nullptr); }
|
||||||
#endif
|
#endif
|
||||||
//static inline void sleep(uint32_t milliseconds) { ::sleep((float)milliseconds / 1000.0); }
|
//inline static void sleep(uint32_t milliseconds) { ::sleep((float)milliseconds / 1000.0); }
|
||||||
|
|
||||||
// round decimal number to specified precision
|
// round decimal number to specified precision
|
||||||
//static inline float round(float value, uint8_t precision) { return std::round(value / precision) * precision; }
|
//inline static float round(float value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||||
//static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
|
//inline static double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||||
static inline double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
|
inline static double round(double value, uint8_t precision) { return std::round(value / precision) * precision; }
|
||||||
|
|
||||||
static inline uint64_t from_bytes_big_endian(const uint8_t* data, size_t len) {
|
inline static uint64_t from_bytes_big_endian(const uint8_t* data, size_t len) {
|
||||||
uint64_t result = 0;
|
uint64_t result = 0;
|
||||||
for (size_t i = 0; i < len; ++i) {
|
for (size_t i = 0; i < len; ++i) {
|
||||||
result = (result << 8) | data[i];
|
result = (result << 8) | data[i];
|
||||||
@@ -79,17 +84,17 @@ namespace RNS { namespace Utilities {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Detect endianness at runtime
|
// Detect endianness at runtime
|
||||||
static int is_big_endian(void) {
|
inline static int is_big_endian(void) {
|
||||||
uint16_t test = 0x0102;
|
uint16_t test = 0x0102;
|
||||||
return ((uint8_t*)&test)[0] == 0x01;
|
return ((uint8_t*)&test)[0] == 0x01;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Byte swap functions
|
// Byte swap functions
|
||||||
static uint16_t swap16(uint16_t val) {
|
inline static uint16_t swap16(uint16_t val) {
|
||||||
return (val << 8) | (val >> 8);
|
return (val << 8) | (val >> 8);
|
||||||
}
|
}
|
||||||
|
|
||||||
static uint32_t swap32(uint32_t val) {
|
inline static uint32_t swap32(uint32_t val) {
|
||||||
return ((val << 24) & 0xFF000000) |
|
return ((val << 24) & 0xFF000000) |
|
||||||
((val << 8) & 0x00FF0000) |
|
((val << 8) & 0x00FF0000) |
|
||||||
((val >> 8) & 0x0000FF00) |
|
((val >> 8) & 0x0000FF00) |
|
||||||
@@ -98,25 +103,39 @@ namespace RNS { namespace Utilities {
|
|||||||
|
|
||||||
// Platform-independent replacements
|
// Platform-independent replacements
|
||||||
|
|
||||||
static uint16_t portable_htons(uint16_t val) {
|
inline static uint16_t portable_htons(uint16_t val) {
|
||||||
return is_big_endian() ? val : swap16(val);
|
return is_big_endian() ? val : swap16(val);
|
||||||
}
|
}
|
||||||
|
|
||||||
static uint32_t portable_htonl(uint32_t val) {
|
inline static uint32_t portable_htonl(uint32_t val) {
|
||||||
return is_big_endian() ? val : swap32(val);
|
return is_big_endian() ? val : swap32(val);
|
||||||
}
|
}
|
||||||
|
|
||||||
static uint16_t portable_ntohs(uint16_t val) {
|
inline static uint16_t portable_ntohs(uint16_t val) {
|
||||||
return is_big_endian() ? val : swap16(val);
|
return is_big_endian() ? val : swap16(val);
|
||||||
}
|
}
|
||||||
|
|
||||||
static uint32_t portable_ntohl(uint32_t val) {
|
inline static uint32_t portable_ntohl(uint32_t val) {
|
||||||
return is_big_endian() ? val : swap32(val);
|
return is_big_endian() ? val : swap32(val);
|
||||||
}
|
}
|
||||||
|
|
||||||
#if defined(RNS_USE_ALLOCATOR)
|
inline static void reset_watchdog() {
|
||||||
static void dump_allocator_stats();
|
#if defined(ESP32)
|
||||||
|
esp_task_wdt_reset();
|
||||||
#endif
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
inline static void set_loop_callback(LoopCallback on_loop = nullptr) { _on_loop = on_loop; }
|
||||||
|
inline static void run_loop() {
|
||||||
|
if (_on_loop) {
|
||||||
|
try {
|
||||||
|
_on_loop();
|
||||||
|
}
|
||||||
|
catch (const std::exception& e) {
|
||||||
|
ERRORF("run_loop: exception while looping: %s", e.what());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
inline static void register_filesystem(FileSystem& filesystem) {
|
inline static void register_filesystem(FileSystem& filesystem) {
|
||||||
TRACE("Registering filesystem...");
|
TRACE("Registering filesystem...");
|
||||||
@@ -204,11 +223,11 @@ namespace RNS { namespace Utilities {
|
|||||||
return _filesystem.remove_directory(directory_path);
|
return _filesystem.remove_directory(directory_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline static std::list<std::string> list_directory(const char* directory_path) {
|
inline static std::list<std::string> list_directory(const char* directory_path, FileSystem::Callbacks::DirectoryListing callback = nullptr) {
|
||||||
if (!_filesystem) {
|
if (!_filesystem) {
|
||||||
throw std::runtime_error("FileSystem has not been registered");
|
throw std::runtime_error("FileSystem has not been registered");
|
||||||
}
|
}
|
||||||
return _filesystem.list_directory(directory_path);
|
return _filesystem.list_directory(directory_path, callback);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline static size_t storage_size() {
|
inline static size_t storage_size() {
|
||||||
@@ -224,10 +243,6 @@ namespace RNS { namespace Utilities {
|
|||||||
}
|
}
|
||||||
return _filesystem.storage_available();
|
return _filesystem.storage_available();
|
||||||
}
|
}
|
||||||
|
|
||||||
static size_t heap_size();
|
|
||||||
static size_t heap_available();
|
|
||||||
static void dump_heap_stats();
|
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,11 @@
|
|||||||
|
|
||||||
using namespace RNS;
|
using namespace RNS;
|
||||||
|
|
||||||
|
#if defined(BOARD_HAS_PSRAM) && defined(ESP32)
|
||||||
|
/*static*/ RNS::Persistence::PsramAllocator _psramAllocatorImpl;
|
||||||
|
/*static*/ JsonDocument _document(&_psramAllocatorImpl);
|
||||||
|
#else
|
||||||
/*static*/ //DynamicJsonDocument _document(Type::Persistence::DOCUMENT_MAXSIZE);
|
/*static*/ //DynamicJsonDocument _document(Type::Persistence::DOCUMENT_MAXSIZE);
|
||||||
/*static*/ JsonDocument _document;
|
/*static*/ JsonDocument _document;
|
||||||
|
#endif
|
||||||
/*static*/ Bytes _buffer(Type::Persistence::BUFFER_MAXSIZE);
|
/*static*/ Bytes _buffer(Type::Persistence::BUFFER_MAXSIZE);
|
||||||
@@ -474,8 +474,31 @@ namespace RNS {
|
|||||||
|
|
||||||
namespace RNS { namespace Persistence {
|
namespace RNS { namespace Persistence {
|
||||||
|
|
||||||
|
#if defined(BOARD_HAS_PSRAM) && defined(ESP32)
|
||||||
|
// PSRAM allocator for ArduinoJson — prevents deserialization failures
|
||||||
|
// under heap pressure (heap can be <1KB free while PSRAM has 8+ MB).
|
||||||
|
class PsramAllocator : public ArduinoJson::Allocator {
|
||||||
|
public:
|
||||||
|
void* allocate(size_t size) override {
|
||||||
|
void* p = ps_malloc(size);
|
||||||
|
if (!p) p = malloc(size); // fallback to heap if PSRAM unavailable
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
void deallocate(void* ptr) override {
|
||||||
|
free(ptr); // free() handles both heap and PSRAM on ESP32
|
||||||
|
}
|
||||||
|
void* reallocate(void* ptr, size_t new_size) override {
|
||||||
|
void* p = ps_realloc(ptr, new_size);
|
||||||
|
if (!p) p = realloc(ptr, new_size); // fallback
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
static PsramAllocator _psramAllocator;
|
||||||
|
static JsonDocument _document(&_psramAllocator);
|
||||||
|
#else
|
||||||
//static DynamicJsonDocument _document(Type::Persistence::DOCUMENT_MAXSIZE);
|
//static DynamicJsonDocument _document(Type::Persistence::DOCUMENT_MAXSIZE);
|
||||||
static JsonDocument _document;
|
static JsonDocument _document;
|
||||||
|
#endif
|
||||||
static Bytes _buffer(Type::Persistence::BUFFER_MAXSIZE);
|
static Bytes _buffer(Type::Persistence::BUFFER_MAXSIZE);
|
||||||
|
|
||||||
template <typename T> uint32_t crc(const T& obj) {
|
template <typename T> uint32_t crc(const T& obj) {
|
||||||
@@ -556,7 +579,7 @@ namespace RNS { namespace Persistence {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#if 1
|
#if 1
|
||||||
template <typename T> uint32_t crc(std::map<Bytes, T>& map) {
|
template <typename T, typename Compare, typename Allocator> uint32_t crc(std::map<Bytes, T, Compare, Allocator>& map) {
|
||||||
//TRACE("Persistence::crc<map<Bytes, T>>");
|
//TRACE("Persistence::crc<map<Bytes, T>>");
|
||||||
|
|
||||||
uint32_t crc = 0;
|
uint32_t crc = 0;
|
||||||
@@ -592,7 +615,7 @@ namespace RNS { namespace Persistence {
|
|||||||
return Utilities::Crc::crc32(crc, '}');
|
return Utilities::Crc::crc32(crc, '}');
|
||||||
}
|
}
|
||||||
|
|
||||||
template <typename T> size_t serialize(std::map<Bytes, T>& map, const char* file_path, uint32_t& crc) {
|
template <typename T, typename Compare, typename Allocator> size_t serialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path, uint32_t& crc) {
|
||||||
//TRACE("Persistence::serialize<map<Bytes,T>>");
|
//TRACE("Persistence::serialize<map<Bytes,T>>");
|
||||||
|
|
||||||
// CBA TODO: Use stream here instead to avoid having to buffer entire structure
|
// CBA TODO: Use stream here instead to avoid having to buffer entire structure
|
||||||
@@ -625,17 +648,18 @@ namespace RNS { namespace Persistence {
|
|||||||
stream.write(',');
|
stream.write(',');
|
||||||
}
|
}
|
||||||
stream.write('}');
|
stream.write('}');
|
||||||
|
stream.flush();
|
||||||
TRACEF("Persistence::serialize: stream size: %d bytes", stream.size());
|
TRACEF("Persistence::serialize: stream size: %d bytes", stream.size());
|
||||||
crc = stream.crc();
|
crc = stream.crc();
|
||||||
return stream.size();
|
return stream.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
template <typename T> size_t serialize(std::map<Bytes, T>& map, const char* file_path) {
|
template <typename T, typename Compare, typename Allocator> size_t serialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path) {
|
||||||
uint32_t crc;
|
uint32_t crc;
|
||||||
return serialize(map, file_path, crc);
|
return serialize(map, file_path, crc);
|
||||||
}
|
}
|
||||||
|
|
||||||
template <typename T> size_t deserialize(std::map<Bytes, T>& map, const char* file_path, uint32_t& crc) {
|
template <typename T, typename Compare, typename Allocator> size_t deserialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path, uint32_t& crc) {
|
||||||
//TRACE("Persistence::deserialize<map<Bytes,T>>");
|
//TRACE("Persistence::deserialize<map<Bytes,T>>");
|
||||||
|
|
||||||
// CBA TODO: Use stream here instead to avoid having to buffer entire structure
|
// CBA TODO: Use stream here instead to avoid having to buffer entire structure
|
||||||
@@ -700,7 +724,7 @@ namespace RNS { namespace Persistence {
|
|||||||
return stream.size();
|
return stream.size();
|
||||||
}
|
}
|
||||||
|
|
||||||
template <typename T> size_t deserialize(std::map<Bytes, T>& map, const char* file_path) {
|
template <typename T, typename Compare, typename Allocator> size_t deserialize(std::map<Bytes, T, Compare, Allocator>& map, const char* file_path) {
|
||||||
uint32_t crc;
|
uint32_t crc;
|
||||||
return deserialize(map, file_path, crc);
|
return deserialize(map, file_path, crc);
|
||||||
}
|
}
|
||||||
|
|||||||
+114
-110
@@ -33,8 +33,8 @@ public:
|
|||||||
bool init() {
|
bool init() {
|
||||||
TRACE("FileSystem initializing...");
|
TRACE("FileSystem initializing...");
|
||||||
|
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
// Setup FileSystem
|
// Setup FileSystem
|
||||||
INFO("SPIFFS mounting FileSystem");
|
INFO("SPIFFS mounting FileSystem");
|
||||||
if (!SPIFFS.begin(true, "")){
|
if (!SPIFFS.begin(true, "")){
|
||||||
@@ -59,22 +59,22 @@ public:
|
|||||||
remove_file("/test");
|
remove_file("/test");
|
||||||
}
|
}
|
||||||
DEBUG("SPIFFS FileSystem is ready");
|
DEBUG("SPIFFS FileSystem is ready");
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
// Initialize Internal File System
|
// Initialize Internal File System
|
||||||
INFO("InternalFS mounting FileSystem");
|
INFO("InternalFS mounting FileSystem");
|
||||||
InternalFS.begin();
|
InternalFS.begin();
|
||||||
INFO("InternalFS FileSystem is ready");
|
INFO("InternalFS FileSystem is ready");
|
||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public:
|
public:
|
||||||
static void listDir(const char* dir) {
|
static void listDir(const char* dir) {
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
Serial.print("DIR: ");
|
Serial.print("DIR: ");
|
||||||
Serial.println(dir);
|
Serial.println(dir);
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
File root = SPIFFS.open(dir);
|
File root = SPIFFS.open(dir);
|
||||||
if (!root) {
|
if (!root) {
|
||||||
Serial.println("Failed to opend directory");
|
Serial.println("Failed to opend directory");
|
||||||
@@ -93,7 +93,7 @@ public:
|
|||||||
file = root.openNextFile();
|
file = root.openNextFile();
|
||||||
}
|
}
|
||||||
root.close();
|
root.close();
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
File root = InternalFS.open(dir);
|
File root = InternalFS.open(dir);
|
||||||
if (!root) {
|
if (!root) {
|
||||||
Serial.println("Failed to opend directory");
|
Serial.println("Failed to opend directory");
|
||||||
@@ -112,38 +112,38 @@ public:
|
|||||||
file = root.openNextFile();
|
file = root.openNextFile();
|
||||||
}
|
}
|
||||||
root.close();
|
root.close();
|
||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
public:
|
public:
|
||||||
virtual bool file_exists(const char* file_path) {
|
virtual bool file_exists(const char* file_path) {
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
File file = SPIFFS.open(file_path, FILE_READ);
|
File file = SPIFFS.open(file_path, FILE_READ);
|
||||||
if (file) {
|
if (file) {
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
File file(InternalFS);
|
File file(InternalFS);
|
||||||
if (file.open(file_path, FILE_O_READ)) {
|
if (file.open(file_path, FILE_O_READ)) {
|
||||||
#else
|
#else
|
||||||
if (false) {
|
if (false) {
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
FILE* file = fopen(file_path, "r");
|
FILE* file = fopen(file_path, "r");
|
||||||
if (file != nullptr) {
|
if (file != nullptr) {
|
||||||
#endif
|
#endif
|
||||||
//TRACE("file_exists: file exists, closing file");
|
//TRACE("file_exists: file exists, closing file");
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
file.close();
|
file.close();
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
file.close();
|
file.close();
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
fclose(file);
|
fclose(file);
|
||||||
#endif
|
#endif
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -154,24 +154,24 @@ public:
|
|||||||
|
|
||||||
virtual size_t read_file(const char* file_path, RNS::Bytes& data) {
|
virtual size_t read_file(const char* file_path, RNS::Bytes& data) {
|
||||||
size_t read = 0;
|
size_t read = 0;
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
File file = SPIFFS.open(file_path, FILE_READ);
|
File file = SPIFFS.open(file_path, FILE_READ);
|
||||||
if (file) {
|
if (file) {
|
||||||
size_t size = file.size();
|
size_t size = file.size();
|
||||||
read = file.readBytes((char*)data.writable(size), size);
|
read = file.readBytes((char*)data.writable(size), size);
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
//File file(InternalFS);
|
//File file(InternalFS);
|
||||||
//if (file.open(file_path, FILE_O_READ)) {
|
//if (file.open(file_path, FILE_O_READ)) {
|
||||||
File file = InternalFS.open(file_path, FILE_O_READ);
|
File file = InternalFS.open(file_path, FILE_O_READ);
|
||||||
if (file) {
|
if (file) {
|
||||||
size_t size = file.size();
|
size_t size = file.size();
|
||||||
read = file.readBytes((char*)data.writable(size), size);
|
read = file.readBytes((char*)data.writable(size), size);
|
||||||
#else
|
#else
|
||||||
if (false) {
|
if (false) {
|
||||||
size_t size = 0;
|
size_t size = 0;
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
FILE* file = fopen(file_path, "r");
|
FILE* file = fopen(file_path, "r");
|
||||||
if (file != nullptr) {
|
if (file != nullptr) {
|
||||||
@@ -180,23 +180,23 @@ public:
|
|||||||
rewind(file);
|
rewind(file);
|
||||||
//size_t read = fread(data.writable(size), size, 1, file);
|
//size_t read = fread(data.writable(size), size, 1, file);
|
||||||
read = fread(data.writable(size), 1, size, file);
|
read = fread(data.writable(size), 1, size, file);
|
||||||
#endif
|
#endif
|
||||||
TRACEF("read_file: read %zu bytes from file %s", read, file_path);
|
TRACEF("read_file: read %zu bytes from file %s", read, file_path);
|
||||||
if (read != size) {
|
if (read != size) {
|
||||||
ERRORF("read_file: failed to read file %s", file_path);
|
ERRORF("read_file: failed to read file %s", file_path);
|
||||||
data.clear();
|
data.clear();
|
||||||
}
|
}
|
||||||
//TRACE("read_file: closing input file");
|
//TRACE("read_file: closing input file");
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
file.close();
|
file.close();
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
file.close();
|
file.close();
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
fclose(file);
|
fclose(file);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
ERRORF("read_file: failed to open input file %s", file_path);
|
ERRORF("read_file: failed to open input file %s", file_path);
|
||||||
@@ -208,40 +208,40 @@ public:
|
|||||||
// CBA TODO Replace remove with working truncation
|
// CBA TODO Replace remove with working truncation
|
||||||
remove_file(file_path);
|
remove_file(file_path);
|
||||||
size_t wrote = 0;
|
size_t wrote = 0;
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
File file = SPIFFS.open(file_path, FILE_WRITE);
|
File file = SPIFFS.open(file_path, FILE_WRITE);
|
||||||
if (file) {
|
if (file) {
|
||||||
wrote = file.write(data.data(), data.size());
|
wrote = file.write(data.data(), data.size());
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
File file(InternalFS);
|
File file(InternalFS);
|
||||||
if (file.open(file_path, FILE_O_WRITE)) {
|
if (file.open(file_path, FILE_O_WRITE)) {
|
||||||
wrote = file.write(data.data(), data.size());
|
wrote = file.write(data.data(), data.size());
|
||||||
#else
|
#else
|
||||||
if (false) {
|
if (false) {
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
FILE* file = fopen(file_path, "w");
|
FILE* file = fopen(file_path, "w");
|
||||||
if (file != nullptr) {
|
if (file != nullptr) {
|
||||||
//size_t wrote = fwrite(data.data(), data.size(), 1, file);
|
//size_t wrote = fwrite(data.data(), data.size(), 1, file);
|
||||||
wrote = fwrite(data.data(), 1, data.size(), file);
|
wrote = fwrite(data.data(), 1, data.size(), file);
|
||||||
#endif
|
#endif
|
||||||
TRACEF("write_file: wrote %zu bytes to file %s", wrote, file_path);
|
TRACEF("write_file: wrote %zu bytes to file %s", wrote, file_path);
|
||||||
if (wrote < data.size()) {
|
if (wrote < data.size()) {
|
||||||
WARNINGF("write_file: not all data was written to file %s", file_path);
|
WARNINGF("write_file: not all data was written to file %s", file_path);
|
||||||
}
|
}
|
||||||
//TRACE("write_file: closing output file");
|
//TRACE("write_file: closing output file");
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
file.close();
|
file.close();
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
file.close();
|
file.close();
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
fclose(file);
|
fclose(file);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
ERRORF("write_file: failed to open output file %s", file_path);
|
ERRORF("write_file: failed to open output file %s", file_path);
|
||||||
@@ -251,8 +251,8 @@ public:
|
|||||||
|
|
||||||
virtual RNS::FileStream open_file(const char* file_path, RNS::FileStream::MODE file_mode) {
|
virtual RNS::FileStream open_file(const char* file_path, RNS::FileStream::MODE file_mode) {
|
||||||
TRACEF("open_file: opening file %s", file_path);
|
TRACEF("open_file: opening file %s", file_path);
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
const char* mode;
|
const char* mode;
|
||||||
if (file_mode == RNS::FileStream::MODE_READ) {
|
if (file_mode == RNS::FileStream::MODE_READ) {
|
||||||
mode = FILE_READ;
|
mode = FILE_READ;
|
||||||
@@ -273,14 +273,13 @@ public:
|
|||||||
//if (!file) {
|
//if (!file) {
|
||||||
File* file = new File(SPIFFS.open(file_path, mode));
|
File* file = new File(SPIFFS.open(file_path, mode));
|
||||||
if (file == nullptr || !(*file)) {
|
if (file == nullptr || !(*file)) {
|
||||||
|
if (file != nullptr) delete file;
|
||||||
ERRORF("open_file: failed to open output file %s", file_path);
|
ERRORF("open_file: failed to open output file %s", file_path);
|
||||||
return {RNS::Type::NONE};
|
return {RNS::Type::NONE};
|
||||||
}
|
}
|
||||||
TRACEF("open_file: successfully opened file %s", file_path);
|
TRACEF("open_file: successfully opened file %s", file_path);
|
||||||
return RNS::FileStream(new FileStreamImpl(file));
|
return RNS::FileStream(new FileStreamImpl(file));
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
//File file = File(InternalFS);
|
|
||||||
File* file = new File(InternalFS);
|
|
||||||
int mode;
|
int mode;
|
||||||
if (file_mode == RNS::FileStream::MODE_READ) {
|
if (file_mode == RNS::FileStream::MODE_READ) {
|
||||||
mode = FILE_O_READ;
|
mode = FILE_O_READ;
|
||||||
@@ -300,7 +299,10 @@ public:
|
|||||||
ERRORF("open_file: unsupported mode %d", file_mode);
|
ERRORF("open_file: unsupported mode %d", file_mode);
|
||||||
return {RNS::Type::NONE};
|
return {RNS::Type::NONE};
|
||||||
}
|
}
|
||||||
if (!file->open(file_path, mode)) {
|
//File file = File(InternalFS);
|
||||||
|
File* file = new File(InternalFS);
|
||||||
|
if (file == nullptr || !file->open(file_path, mode)) {
|
||||||
|
if (file != nullptr) delete file;
|
||||||
ERRORF("open_file: failed to open output file %s", file_path);
|
ERRORF("open_file: failed to open output file %s", file_path);
|
||||||
return {RNS::Type::NONE};
|
return {RNS::Type::NONE};
|
||||||
}
|
}
|
||||||
@@ -312,11 +314,11 @@ public:
|
|||||||
//}
|
//}
|
||||||
TRACEF("open_file: successfully opened file %s", file_path);
|
TRACEF("open_file: successfully opened file %s", file_path);
|
||||||
return RNS::FileStream(new FileStreamImpl(file));
|
return RNS::FileStream(new FileStreamImpl(file));
|
||||||
#else
|
#else
|
||||||
#warning("unsupported");
|
#warning("unsupported");
|
||||||
return RNS::FileStream(RNS::Type::NONE);
|
return RNS::FileStream(RNS::Type::NONE);
|
||||||
#endif
|
#endif
|
||||||
#else // ARDUINO
|
#else // ARDUINO
|
||||||
// Native
|
// Native
|
||||||
const char* mode;
|
const char* mode;
|
||||||
if (file_mode == RNS::FileStream::MODE_READ) {
|
if (file_mode == RNS::FileStream::MODE_READ) {
|
||||||
@@ -340,136 +342,136 @@ public:
|
|||||||
}
|
}
|
||||||
TRACEF("open_file: successfully opened file %s", file_path);
|
TRACEF("open_file: successfully opened file %s", file_path);
|
||||||
return RNS::FileStream(new FileStreamImpl(file));
|
return RNS::FileStream(new FileStreamImpl(file));
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
virtual bool remove_file(const char* file_path) {
|
virtual bool remove_file(const char* file_path) {
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
return SPIFFS.remove(file_path);
|
return SPIFFS.remove(file_path);
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
return InternalFS.remove(file_path);
|
return InternalFS.remove(file_path);
|
||||||
#else
|
#else
|
||||||
return false;
|
return false;
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
return (remove(file_path) == 0);
|
return (remove(file_path) == 0);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
virtual bool rename_file(const char* from_file_path, const char* to_file_path) {
|
virtual bool rename_file(const char* from_file_path, const char* to_file_path) {
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
return SPIFFS.rename(from_file_path, to_file_path);
|
return SPIFFS.rename(from_file_path, to_file_path);
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
return InternalFS.rename(from_file_path, to_file_path);
|
return InternalFS.rename(from_file_path, to_file_path);
|
||||||
#else
|
#else
|
||||||
return false;
|
return false;
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
return (rename(from_file_path, to_file_path) == 0);
|
return (rename(from_file_path, to_file_path) == 0);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
/*virtua*/ bool directory_exists(const char* directory_path) {
|
/*virtua*/ bool directory_exists(const char* directory_path) {
|
||||||
TRACEF("directory_exists: checking for existence of directory %s", directory_path);
|
TRACEF("directory_exists: checking for existence of directory %s", directory_path);
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
File file = SPIFFS.open(directory_path, FILE_READ);
|
File file = SPIFFS.open(directory_path, FILE_READ);
|
||||||
if (file) {
|
if (file) {
|
||||||
bool is_directory = file.isDirectory();
|
bool is_directory = file.isDirectory();
|
||||||
file.close();
|
file.close();
|
||||||
return is_directory;
|
return is_directory;
|
||||||
}
|
}
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
File file(InternalFS);
|
File file(InternalFS);
|
||||||
if (file.open(directory_path, FILE_O_READ)) {
|
if (file.open(directory_path, FILE_O_READ)) {
|
||||||
bool is_directory = file.isDirectory();
|
bool is_directory = file.isDirectory();
|
||||||
file.close();
|
file.close();
|
||||||
return is_directory;
|
return is_directory;
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
if (false) {
|
if (false) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
else {
|
else {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
struct stat st = {0};
|
struct stat st = {0};
|
||||||
return (stat(directory_path, &st) == 0);
|
return (stat(directory_path, &st) == 0);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
virtual bool create_directory(const char* directory_path) {
|
virtual bool create_directory(const char* directory_path) {
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
if (!SPIFFS.mkdir(directory_path)) {
|
if (!SPIFFS.mkdir(directory_path)) {
|
||||||
ERRORF("create_directory: failed to create directorty %s", directory_path);
|
ERRORF("create_directory: failed to create directorty %s", directory_path);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
if (!InternalFS.mkdir(directory_path)) {
|
if (!InternalFS.mkdir(directory_path)) {
|
||||||
ERRORF("create_directory: failed to create directorty %s", directory_path);
|
ERRORF("create_directory: failed to create directorty %s", directory_path);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
#else
|
#else
|
||||||
return false;
|
return false;
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
struct stat st = {0};
|
struct stat st = {0};
|
||||||
if (stat(directory_path, &st) == 0) {
|
if (stat(directory_path, &st) == 0) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return (mkdir(directory_path, 0700) == 0);
|
return (mkdir(directory_path, 0700) == 0);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
/*virtua*/ bool remove_directory(const char* directory_path) {
|
/*virtua*/ bool remove_directory(const char* directory_path) {
|
||||||
TRACEF("remove_directory: removing directory %s", directory_path);
|
TRACEF("remove_directory: removing directory %s", directory_path);
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
//if (!LittleFS.rmdir_r(directory_path)) {
|
//if (!LittleFS.rmdir_r(directory_path)) {
|
||||||
if (!SPIFFS.rmdir(directory_path)) {
|
if (!SPIFFS.rmdir(directory_path)) {
|
||||||
ERRORF("remove_directory: failed to remove directorty %s", directory_path);
|
ERRORF("remove_directory: failed to remove directorty %s", directory_path);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
if (!InternalFS.rmdir_r(directory_path)) {
|
if (!InternalFS.rmdir_r(directory_path)) {
|
||||||
ERRORF("remove_directory: failed to remove directory %s", directory_path);
|
ERRORF("remove_directory: failed to remove directory %s", directory_path);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
#else
|
#else
|
||||||
return false;
|
return false;
|
||||||
#endif
|
#endif
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
if (rmdir(directory_path) == 0) {
|
if (rmdir(directory_path) == 0) {
|
||||||
ERRORF("remove_directory: failed to remove directory %s", directory_path);
|
ERRORF("remove_directory: failed to remove directory %s", directory_path);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
/*virtua*/ std::list<std::string> list_directory(const char* directory_path) {
|
/*virtua*/ std::list<std::string> list_directory(const char* directory_path, Callbacks::DirectoryListing callback = nullptr) {
|
||||||
TRACEF("list_directory: listing directory %s", directory_path);
|
TRACEF("list_directory: listing directory %s", directory_path);
|
||||||
std::list<std::string> files;
|
std::list<std::string> files;
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
File root = SPIFFS.open(directory_path);
|
File root = SPIFFS.open(directory_path);
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
File root = InternalFS.open(directory_path);
|
File root = InternalFS.open(directory_path);
|
||||||
#endif
|
#endif
|
||||||
if (!root) {
|
if (!root) {
|
||||||
ERRORF("list_directory: failed to open directory %s", directory_path);
|
ERRORF("list_directory: failed to open directory %s", directory_path);
|
||||||
return files;
|
return files;
|
||||||
@@ -478,7 +480,8 @@ public:
|
|||||||
while (file) {
|
while (file) {
|
||||||
if (!file.isDirectory()) {
|
if (!file.isDirectory()) {
|
||||||
char* name = (char*)file.name();
|
char* name = (char*)file.name();
|
||||||
files.push_back(name);
|
if (callback) callback(name);
|
||||||
|
else files.push_back(name);
|
||||||
}
|
}
|
||||||
// CBA Following close required to avoid leaking memory
|
// CBA Following close required to avoid leaking memory
|
||||||
file.close();
|
file.close();
|
||||||
@@ -487,7 +490,7 @@ public:
|
|||||||
TRACE("list_directory: returning directory listing");
|
TRACE("list_directory: returning directory listing");
|
||||||
root.close();
|
root.close();
|
||||||
return files;
|
return files;
|
||||||
#else
|
#else
|
||||||
// Native
|
// Native
|
||||||
DIR *dir = opendir(directory_path);
|
DIR *dir = opendir(directory_path);
|
||||||
if (dir == NULL) {
|
if (dir == NULL) {
|
||||||
@@ -500,20 +503,21 @@ public:
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
char* name = entry->d_name;
|
char* name = entry->d_name;
|
||||||
files.push_back(name);
|
if (callback) callback(name);
|
||||||
|
else files.push_back(name);
|
||||||
}
|
}
|
||||||
if (closedir(dir) == -1) {
|
if (closedir(dir) == -1) {
|
||||||
ERRORF("list_directory: failed to close directory %s", directory_path);
|
ERRORF("list_directory: failed to close directory %s", directory_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
return files;
|
return files;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#ifdef ARDUINO
|
#ifdef ARDUINO
|
||||||
|
|
||||||
#ifdef BOARD_ESP32
|
#ifdef BOARD_ESP32
|
||||||
|
|
||||||
virtual size_t storage_size() {
|
virtual size_t storage_size() {
|
||||||
return SPIFFS.totalBytes();
|
return SPIFFS.totalBytes();
|
||||||
@@ -523,7 +527,7 @@ public:
|
|||||||
return (SPIFFS.totalBytes() - SPIFFS.usedBytes());
|
return (SPIFFS.totalBytes() - SPIFFS.usedBytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
#elif BOARD_NRF52
|
#elif BOARD_NRF52
|
||||||
|
|
||||||
static int _countLfsBlock(void *p, lfs_block_t block){
|
static int _countLfsBlock(void *p, lfs_block_t block){
|
||||||
lfs_size_t *size = (lfs_size_t*) p;
|
lfs_size_t *size = (lfs_size_t*) p;
|
||||||
@@ -558,9 +562,9 @@ public:
|
|||||||
return (InternalFS.totalBytes() - InternalFS.usedBytes());
|
return (InternalFS.totalBytes() - InternalFS.usedBytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#else
|
#else
|
||||||
|
|
||||||
virtual size_t storage_size() {
|
virtual size_t storage_size() {
|
||||||
return 0;
|
return 0;
|
||||||
@@ -570,7 +574,7 @@ public:
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
#include <unity.h>
|
||||||
|
|
||||||
|
#include <Bytes.h>
|
||||||
|
#include <Utilities/OS.h>
|
||||||
|
#include <Utilities/Memory.h>
|
||||||
|
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <scoped_allocator>
|
||||||
|
|
||||||
|
//#define VECTOR_INTERNAL_CONTENT
|
||||||
|
//#define VECTOR_EXTERNAL_CONTENT
|
||||||
|
//#define BYTES_INTERNAL_CONTENT
|
||||||
|
#define BYTES_EXTERNAL_CONTENT
|
||||||
|
|
||||||
|
class TestObject {
|
||||||
|
public:
|
||||||
|
TestObject() {}
|
||||||
|
TestObject(const char* str, std::vector<std::string>& vec, RNS::Bytes& buf) : _str(str), _vec(vec), _external_buf(buf) {
|
||||||
|
#ifdef VECTOR_INTERNAL_CONTENT
|
||||||
|
// CBA The following vector entries use psram even though they're created internally (not part of base object)
|
||||||
|
_vec.push_back("fee");
|
||||||
|
_vec.push_back("fum");
|
||||||
|
#endif
|
||||||
|
#ifdef BYTES_INTERNAL_CONTENT
|
||||||
|
// CBA The following Bytes content use psram even though they're created internally (not part of base object)
|
||||||
|
_internal_buf.assign("This is a Bytes buffer allocated INSIDE of TestObject");
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
inline bool operator < (const TestObject& test) const { return _str < test._str; }
|
||||||
|
|
||||||
|
inline const std::string toString() const { return std::string("TestObject(") + _str + "," + std::to_string(_vec.size()) + "," + _internal_buf.toString() + "," + _external_buf.toString() + ")"; }
|
||||||
|
|
||||||
|
// CBA All of the following empty containers are included in the memory allocated for std::map and use psram
|
||||||
|
std::string _str;
|
||||||
|
std::vector<std::string> _vec;
|
||||||
|
RNS::Bytes _internal_buf;
|
||||||
|
RNS::Bytes _external_buf;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
void test_map_allocator() {
|
||||||
|
|
||||||
|
// CBA TODO Figure out how to selectively use PSRAM for Bytes and Packet objects.
|
||||||
|
|
||||||
|
// Trigger creation of both heap and psram pool before starting
|
||||||
|
RNS::Utilities::Memory::pool_init(RNS::Utilities::Memory::heap_pool_info);
|
||||||
|
RNS::Utilities::Memory::pool_init(RNS::Utilities::Memory::altheap_pool_info);
|
||||||
|
//RNS::Utilities::Memory::dump_heap_stats();
|
||||||
|
HEAD("Initial Stats:", RNS::LOG_TRACE);
|
||||||
|
RNS::Utilities::Memory::dump_basic_pool_stats();
|
||||||
|
//RNS::Utilities::Memory::dump_basic_allocator_stats();
|
||||||
|
|
||||||
|
{
|
||||||
|
//using TestMap = std::map<Bytes, TestObject, std::less<Bytes>, RNS::Utilities::Memory::ContainerAllocator<std::pair<const Bytes, TestObject>>>;
|
||||||
|
using TestMap = std::map<std::string, TestObject, std::less<std::string>, RNS::Utilities::Memory::ContainerAllocator<std::pair<const std::string, TestObject>>>;
|
||||||
|
//using TestAlloc = RNS::Utilities::Memory::ContainerAllocator<std::pair<const std::string, TestObject>>;
|
||||||
|
//using TestStringAlloc = RNS::Utilities::Memory::ContainerAllocator<char>;
|
||||||
|
//using TestMap = std::map<std::string, TestObject, std::less<std::string>, std::scoped_allocator_adaptor<TestAlloc, TestStringAlloc>>;
|
||||||
|
|
||||||
|
HEAD("Post-map Stats:", RNS::LOG_TRACE);
|
||||||
|
RNS::Utilities::Memory::dump_basic_pool_stats();
|
||||||
|
//RNS::Utilities::Memory::dump_basic_allocator_stats();
|
||||||
|
|
||||||
|
// CBA The following empty vector object is included in the memory allocated for std::map and uses psram
|
||||||
|
std::vector<std::string> vec;
|
||||||
|
#ifdef VECTOR_EXTERNAL_CONTENT
|
||||||
|
// CBA The following vector entries use psram
|
||||||
|
vec.push_back("foo");
|
||||||
|
vec.push_back("bar");
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// CBA The following empty Bytes object is included in the memory allocated for std::map and uses psram
|
||||||
|
RNS::Bytes buf;
|
||||||
|
#ifdef BYTES_EXTERNAL_CONTENT
|
||||||
|
// CBA The following Bytes content use psram
|
||||||
|
buf.assign("This is a Bytes buffer allocated OUTSIDE of TestObject");
|
||||||
|
#endif
|
||||||
|
|
||||||
|
TestMap map;
|
||||||
|
map.insert({"two", {"two", vec, buf}});
|
||||||
|
map.insert({"one", {"one", vec, buf}});
|
||||||
|
|
||||||
|
HEAD("Post-insert Stats:", RNS::LOG_TRACE);
|
||||||
|
RNS::Utilities::Memory::dump_basic_pool_stats();
|
||||||
|
//RNS::Utilities::Memory::dump_basic_allocator_stats();
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL(2, map.size());
|
||||||
|
for (const auto& [key, entry] : map) {
|
||||||
|
TRACEF("key: %s, entry: %s", key.c_str(), entry.toString().c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
HEAD("Post-free Stats:", RNS::LOG_TRACE);
|
||||||
|
RNS::Utilities::Memory::dump_basic_pool_stats();
|
||||||
|
//RNS::Utilities::Memory::dump_basic_allocator_stats();
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void setUp(void) {
|
||||||
|
// set stuff up here before each test
|
||||||
|
}
|
||||||
|
|
||||||
|
void tearDown(void) {
|
||||||
|
// clean stuff up here after each test
|
||||||
|
}
|
||||||
|
|
||||||
|
int runUnityTests(void) {
|
||||||
|
UNITY_BEGIN();
|
||||||
|
|
||||||
|
// Suite-level setup
|
||||||
|
|
||||||
|
// Run tests
|
||||||
|
RUN_TEST(test_map_allocator);
|
||||||
|
|
||||||
|
// Suite-level teardown
|
||||||
|
|
||||||
|
return UNITY_END();
|
||||||
|
}
|
||||||
|
|
||||||
|
// For native dev-platform or for some embedded frameworks
|
||||||
|
int main(void) {
|
||||||
|
return runUnityTests();
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef ARDUINO
|
||||||
|
// For Arduino framework
|
||||||
|
void setup() {
|
||||||
|
// Wait ~2 seconds before the Unity test runner
|
||||||
|
// establishes connection with a board Serial interface
|
||||||
|
delay(2000);
|
||||||
|
|
||||||
|
runUnityTests();
|
||||||
|
}
|
||||||
|
void loop() {}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// For ESP-IDF framework
|
||||||
|
void app_main() {
|
||||||
|
runUnityTests();
|
||||||
|
}
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
/// Announce creation, parsing, and app_data handling tests.
|
||||||
|
///
|
||||||
|
/// Validates announce wire format matches Python/Rust implementations.
|
||||||
|
|
||||||
|
#include <unity.h>
|
||||||
|
#include "Identity.h"
|
||||||
|
#include "Cryptography/Hashes.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
static void printHex(const char* label, const uint8_t* data, size_t len) {
|
||||||
|
printf(" %s = ", label);
|
||||||
|
for (size_t i = 0; i < len; i++) printf("%02x", data[i]);
|
||||||
|
printf("\n");
|
||||||
|
}
|
||||||
|
static void printHex(const char* label, const RNS::Bytes& data) { printHex(label, data.data(), data.size()); }
|
||||||
|
|
||||||
|
static RNS::Identity g_identity({RNS::Type::NONE});
|
||||||
|
static RNS::Bytes g_dest_hash;
|
||||||
|
static RNS::Bytes g_name_hash;
|
||||||
|
static bool g_init = false;
|
||||||
|
|
||||||
|
static void initFixture() {
|
||||||
|
if (g_init) return;
|
||||||
|
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||||
|
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||||
|
g_identity = RNS::Identity(false);
|
||||||
|
TEST_ASSERT_TRUE(g_identity.load_private_key(x_seed + ed_seed));
|
||||||
|
g_name_hash = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
g_dest_hash = RNS::Identity::truncated_hash(g_name_hash + g_identity.hash());
|
||||||
|
g_init = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 1: Announce pack ───────────────────────────────────────────
|
||||||
|
|
||||||
|
void testAnnouncePack() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||||
|
TEST_ASSERT_EQUAL(64, pubkey.size());
|
||||||
|
|
||||||
|
uint8_t random_hash[10];
|
||||||
|
memset(random_hash, 0x42, 10);
|
||||||
|
|
||||||
|
// Build signed data: dest_hash(16) + pubkey(64) + name_hash(10) + random_hash(10)
|
||||||
|
std::vector<uint8_t> signed_data;
|
||||||
|
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||||
|
|
||||||
|
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||||
|
TEST_ASSERT_EQUAL(64, sig.size());
|
||||||
|
|
||||||
|
// Build announce: pubkey(64) + name_hash(10) + random_hash(10) + sig(64)
|
||||||
|
std::vector<uint8_t> announce;
|
||||||
|
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||||
|
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||||
|
|
||||||
|
// Minimum announce = 148 bytes (no app_data, no ratchet)
|
||||||
|
TEST_ASSERT_EQUAL(148, announce.size());
|
||||||
|
|
||||||
|
printf("\n=== ANNOUNCE_PACK ===\n");
|
||||||
|
printHex("announce", announce.data(), announce.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 2: Announce unpack ─────────────────────────────────────────
|
||||||
|
|
||||||
|
void testAnnounceUnpack() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||||
|
uint8_t random_hash[10];
|
||||||
|
memset(random_hash, 0x42, 10);
|
||||||
|
|
||||||
|
std::vector<uint8_t> signed_data;
|
||||||
|
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||||
|
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||||
|
|
||||||
|
std::vector<uint8_t> announce;
|
||||||
|
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||||
|
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||||
|
|
||||||
|
// Unpack: verify field offsets
|
||||||
|
// [0..64] = pubkey, [64..74] = name_hash, [74..84] = random_hash, [84..148] = sig
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(pubkey.data(), announce.data(), 64);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(g_name_hash.data(), announce.data() + 64, 10);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(random_hash, announce.data() + 74, 10);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(sig.data(), announce.data() + 84, 64);
|
||||||
|
|
||||||
|
// Validate signature
|
||||||
|
bool valid = g_identity.validate(
|
||||||
|
RNS::Bytes(announce.data() + 84, 64),
|
||||||
|
RNS::Bytes(signed_data.data(), signed_data.size())
|
||||||
|
);
|
||||||
|
TEST_ASSERT_TRUE(valid);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 3: Announce with ratchet ───────────────────────────────────
|
||||||
|
|
||||||
|
void testAnnounceWithRatchet() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||||
|
uint8_t random_hash[10];
|
||||||
|
memset(random_hash, 0x42, 10);
|
||||||
|
uint8_t ratchet_key[32];
|
||||||
|
memset(ratchet_key, 0xAB, 32);
|
||||||
|
|
||||||
|
// With ratchet: signed_data includes ratchet between random_hash and signature
|
||||||
|
std::vector<uint8_t> signed_data;
|
||||||
|
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||||
|
signed_data.insert(signed_data.end(), ratchet_key, ratchet_key + 32);
|
||||||
|
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||||
|
|
||||||
|
// Wire: pubkey(64) + name_hash(10) + random_hash(10) + ratchet(32) + sig(64)
|
||||||
|
std::vector<uint8_t> announce;
|
||||||
|
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||||
|
announce.insert(announce.end(), ratchet_key, ratchet_key + 32);
|
||||||
|
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||||
|
|
||||||
|
// With ratchet: 148 + 32 = 180 bytes
|
||||||
|
TEST_ASSERT_EQUAL(180, announce.size());
|
||||||
|
|
||||||
|
// Verify ratchet is at offset 84
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(ratchet_key, announce.data() + 84, 32);
|
||||||
|
// Signature at offset 116
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(sig.data(), announce.data() + 116, 64);
|
||||||
|
|
||||||
|
printf("\n=== ANNOUNCE_WITH_RATCHET ===\n");
|
||||||
|
printf(" size = %d bytes (148 base + 32 ratchet)\n", (int)announce.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 4: App data extraction (msgpack) ───────────────────────────
|
||||||
|
|
||||||
|
void testAppDataExtraction() {
|
||||||
|
// Test extracting display name from Ratdeck msgpack format: fixarray(1)[bin8(name)]
|
||||||
|
uint8_t app_data[] = {0x91, 0xC4, 0x04, 'T', 'e', 's', 't'}; // ["Test"]
|
||||||
|
|
||||||
|
// Parse: fixarray(1) → bin8(4) → "Test"
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x91, app_data[0]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0xC4, app_data[1]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(4, app_data[2]);
|
||||||
|
|
||||||
|
std::string name((const char*)app_data + 3, 4);
|
||||||
|
TEST_ASSERT_EQUAL_STRING("Test", name.c_str());
|
||||||
|
|
||||||
|
// Also test raw UTF-8 format (Rust format)
|
||||||
|
const char* utf8_data = "RustNode";
|
||||||
|
std::string utf8_name(utf8_data);
|
||||||
|
TEST_ASSERT_EQUAL_STRING("RustNode", utf8_name.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 5: Dest hash from identity ─────────────────────────────────
|
||||||
|
|
||||||
|
void testDestHashFromIdentity() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
// dest_hash = truncated_hash(name_hash("lxmf.delivery") || identity.hash())
|
||||||
|
RNS::Bytes nh = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
RNS::Bytes ih = g_identity.hash();
|
||||||
|
RNS::Bytes addr = nh + ih;
|
||||||
|
RNS::Bytes computed = RNS::Identity::truncated_hash(addr);
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL(16, computed.size());
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(g_dest_hash.data(), computed.data(), 16);
|
||||||
|
|
||||||
|
// Also verify for a different aspect name
|
||||||
|
RNS::Bytes nh_prop = RNS::Identity::full_hash(RNS::Bytes("lxmf.propagation")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
RNS::Bytes prop_dest = RNS::Identity::truncated_hash(nh_prop + ih);
|
||||||
|
TEST_ASSERT_EQUAL(16, prop_dest.size());
|
||||||
|
// Must be different from delivery dest
|
||||||
|
TEST_ASSERT_FALSE(memcmp(g_dest_hash.data(), prop_dest.data(), 16) == 0);
|
||||||
|
|
||||||
|
printf("\n=== DEST_HASH ===\n");
|
||||||
|
printHex("delivery_dest", g_dest_hash);
|
||||||
|
printHex("propagation_dest", prop_dest);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 6: Name hash for multiple aspects ──────────────────────────
|
||||||
|
|
||||||
|
void testNameHashes() {
|
||||||
|
RNS::Bytes nh1 = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
RNS::Bytes nh2 = RNS::Identity::full_hash(RNS::Bytes("lxmf.propagation")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
RNS::Bytes nh3 = RNS::Identity::full_hash(RNS::Bytes("nomadnetwork.node")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL(10, nh1.size());
|
||||||
|
TEST_ASSERT_EQUAL(10, nh2.size());
|
||||||
|
TEST_ASSERT_EQUAL(10, nh3.size());
|
||||||
|
|
||||||
|
// All must be different
|
||||||
|
TEST_ASSERT_FALSE(nh1 == nh2);
|
||||||
|
TEST_ASSERT_FALSE(nh1 == nh3);
|
||||||
|
TEST_ASSERT_FALSE(nh2 == nh3);
|
||||||
|
|
||||||
|
printf("\n=== NAME_HASHES ===\n");
|
||||||
|
printHex("lxmf.delivery", nh1);
|
||||||
|
printHex("lxmf.propagation", nh2);
|
||||||
|
printHex("nomadnetwork.node", nh3);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Runner ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void setUp() {}
|
||||||
|
void tearDown() {}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
UNITY_BEGIN();
|
||||||
|
RUN_TEST(testAnnouncePack);
|
||||||
|
RUN_TEST(testAnnounceUnpack);
|
||||||
|
RUN_TEST(testAnnounceWithRatchet);
|
||||||
|
RUN_TEST(testAppDataExtraction);
|
||||||
|
RUN_TEST(testDestHashFromIdentity);
|
||||||
|
RUN_TEST(testNameHashes);
|
||||||
|
return UNITY_END();
|
||||||
|
}
|
||||||
@@ -0,0 +1,589 @@
|
|||||||
|
// Unit tests for AutoInterface wire-format derivation.
|
||||||
|
//
|
||||||
|
// Fixture values were captured from Python Reticulum
|
||||||
|
// (RNS/Interfaces/AutoInterface.py) so any divergence here means we are no
|
||||||
|
// longer wire-compatible with desktop Reticulum nodes.
|
||||||
|
//
|
||||||
|
// Source of fixture values:
|
||||||
|
// group_hash: hashlib.sha256(b"reticulum").hexdigest()
|
||||||
|
// mcast addr: Python AutoInterface lines 202-212 with the captured group hash
|
||||||
|
// token: hashlib.sha256(group_id + link_local_addr.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
#include <unity.h>
|
||||||
|
#include <time.h>
|
||||||
|
|
||||||
|
#include "Interfaces/AutoInterface.h"
|
||||||
|
#include "Bytes.h"
|
||||||
|
#include "Log.h"
|
||||||
|
|
||||||
|
using RNS::AutoInterface;
|
||||||
|
using RNS::Bytes;
|
||||||
|
|
||||||
|
// SHA256("reticulum")
|
||||||
|
static const char* kGroupHashReticulumHex =
|
||||||
|
"eac4d70bfb1c16e45e39485e31e1f5ccb18cedf878e0310d9a96100168f89f0d";
|
||||||
|
|
||||||
|
// Default group "reticulum", addr_type=temporary ('1'), scope=link ('2')
|
||||||
|
static const char* kMcastDefaultLink =
|
||||||
|
"ff12:0:d70b:fb1c:16e4:5e39:485e:31e1";
|
||||||
|
|
||||||
|
// Default group "reticulum", addr_type=permanent ('0'), scope=admin ('4')
|
||||||
|
static const char* kMcastDefaultAdminPerm =
|
||||||
|
"ff04:0:d70b:fb1c:16e4:5e39:485e:31e1";
|
||||||
|
|
||||||
|
// Custom group "testnet", addr_type=temporary ('1'), scope=link ('2')
|
||||||
|
// Note: trailing group is "315" — only 3 hex chars (RFC 5952: leading zeros
|
||||||
|
// suppressed). This is the format Python emits and that lwIP's inet_pton
|
||||||
|
// accepts; do not pad to 4 chars.
|
||||||
|
static const char* kMcastTestnetLink =
|
||||||
|
"ff12:0:ce9f:2416:5207:33ba:cb37:315";
|
||||||
|
|
||||||
|
// SHA256("reticulum" + "fe80::abcd:1234")
|
||||||
|
static const char* kTokenReticulumFe80AbcdHex =
|
||||||
|
"eb45d091e4798b743d44f9242e245e90cb193ed1c39ac40563e2956e3759a6ca";
|
||||||
|
|
||||||
|
// SHA256("reticulum" + "fe80::1")
|
||||||
|
static const char* kTokenReticulumFe80OneHex =
|
||||||
|
"97b25576749ea936b0d8a8536ffaf442d157cf47d460dcf13c48b7bd18b6c163";
|
||||||
|
|
||||||
|
// SHA256("testnet" + "fe80::abcd:1234")
|
||||||
|
static const char* kTokenTestnetFe80AbcdHex =
|
||||||
|
"33c8aed6ebf08a5e3470d76a43cb090602e14952861877f25d72640aedcad0bf";
|
||||||
|
|
||||||
|
void test_group_hash_default() {
|
||||||
|
Bytes h = AutoInterface::compute_group_hash(Bytes("reticulum"));
|
||||||
|
TEST_ASSERT_EQUAL_size_t(32, h.size());
|
||||||
|
TEST_ASSERT_EQUAL_STRING(kGroupHashReticulumHex, h.toHex().c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_multicast_address_default_group_link_temp() {
|
||||||
|
Bytes h = AutoInterface::compute_group_hash(Bytes("reticulum"));
|
||||||
|
std::string mcast = AutoInterface::compute_multicast_address(
|
||||||
|
h,
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK);
|
||||||
|
TEST_ASSERT_EQUAL_STRING(kMcastDefaultLink, mcast.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_multicast_address_default_group_admin_permanent() {
|
||||||
|
Bytes h = AutoInterface::compute_group_hash(Bytes("reticulum"));
|
||||||
|
std::string mcast = AutoInterface::compute_multicast_address(
|
||||||
|
h,
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_PERMANENT,
|
||||||
|
AutoInterface::SCOPE_ADMIN);
|
||||||
|
TEST_ASSERT_EQUAL_STRING(kMcastDefaultAdminPerm, mcast.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_multicast_address_custom_group() {
|
||||||
|
// Critical: tail group is "315" (3 hex chars). Python's "{:02x}" produces
|
||||||
|
// 3 chars when the value exceeds 0xff but is < 0x1000. Make sure C++
|
||||||
|
// snprintf behaves the same way.
|
||||||
|
Bytes h = AutoInterface::compute_group_hash(Bytes("testnet"));
|
||||||
|
std::string mcast = AutoInterface::compute_multicast_address(
|
||||||
|
h,
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK);
|
||||||
|
TEST_ASSERT_EQUAL_STRING(kMcastTestnetLink, mcast.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_multicast_address_short_group_hash_returns_empty() {
|
||||||
|
Bytes too_short(reinterpret_cast<const uint8_t*>("abcd"), 4);
|
||||||
|
std::string mcast = AutoInterface::compute_multicast_address(
|
||||||
|
too_short,
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK);
|
||||||
|
TEST_ASSERT_TRUE(mcast.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_discovery_token_default_group() {
|
||||||
|
Bytes token = AutoInterface::compute_discovery_token(
|
||||||
|
Bytes("reticulum"), std::string("fe80::abcd:1234"));
|
||||||
|
TEST_ASSERT_EQUAL_size_t(32, token.size());
|
||||||
|
TEST_ASSERT_EQUAL_STRING(kTokenReticulumFe80AbcdHex, token.toHex().c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_discovery_token_compressed_address() {
|
||||||
|
// Validates that we accept the RFC 5952 short form "fe80::1" as-is.
|
||||||
|
Bytes token = AutoInterface::compute_discovery_token(
|
||||||
|
Bytes("reticulum"), std::string("fe80::1"));
|
||||||
|
TEST_ASSERT_EQUAL_STRING(kTokenReticulumFe80OneHex, token.toHex().c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_set_link_local_canonicalizes_expanded_form() {
|
||||||
|
// Arduino-ESP32 IPv6Address::toString() returns the fully expanded form
|
||||||
|
// "fe80:0000:0000:0000:0022:5d59:22e5:0924". Peers RX a packet from us
|
||||||
|
// and compute SHA256(group_id || canonical_src_str), so our self-token
|
||||||
|
// must be hashed against the canonical RFC 5952 form, not the expanded
|
||||||
|
// form, or we will be silently rejected by every other implementation.
|
||||||
|
AutoInterface ai("test_iface", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||||
|
AutoInterface::DEFAULT_DATA_PORT, 4);
|
||||||
|
ai.set_link_local("fe80:0000:0000:0000:0022:5d59:22e5:0924", 1);
|
||||||
|
TEST_ASSERT_EQUAL_STRING("fe80::22:5d59:22e5:924",
|
||||||
|
ai.link_local_address().c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_set_link_local_lowercases_uppercase_input() {
|
||||||
|
// lwIP's ip6addr_ntoa_r emits UPPERCASE hex; Python / glibc / macOS
|
||||||
|
// produce lowercase. Wire compat requires us to normalize to lowercase
|
||||||
|
// (RFC 5952 canonical) before hashing, both on the self-token side and
|
||||||
|
// the RX validation side.
|
||||||
|
AutoInterface ai("test_iface", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||||
|
AutoInterface::DEFAULT_DATA_PORT, 4);
|
||||||
|
ai.set_link_local("FE80::3EDC:75FF:FE40:8000", 1);
|
||||||
|
TEST_ASSERT_EQUAL_STRING("fe80::3edc:75ff:fe40:8000",
|
||||||
|
ai.link_local_address().c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_discovery_token_custom_group() {
|
||||||
|
Bytes token = AutoInterface::compute_discovery_token(
|
||||||
|
Bytes("testnet"), std::string("fe80::abcd:1234"));
|
||||||
|
TEST_ASSERT_EQUAL_STRING(kTokenTestnetFe80AbcdHex, token.toHex().c_str());
|
||||||
|
|
||||||
|
// Sanity: different from default-group token for the same address.
|
||||||
|
Bytes other = AutoInterface::compute_discovery_token(
|
||||||
|
Bytes("reticulum"), std::string("fe80::abcd:1234"));
|
||||||
|
TEST_ASSERT_FALSE(token == other);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Peer-table semantics ---
|
||||||
|
|
||||||
|
static AutoInterface::IPv6Addr make_addr(uint8_t last) {
|
||||||
|
// fe80::<last> — link-local with a unique tail byte
|
||||||
|
AutoInterface::IPv6Addr a{};
|
||||||
|
a[0] = 0xfe;
|
||||||
|
a[1] = 0x80;
|
||||||
|
a[15] = last;
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_add_peer_registers_and_counts() {
|
||||||
|
AutoInterface ai("test_iface", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||||
|
AutoInterface::DEFAULT_DATA_PORT,
|
||||||
|
/*max_peers=*/4);
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL_size_t(0, ai.peer_count());
|
||||||
|
|
||||||
|
auto a1 = make_addr(0x01);
|
||||||
|
ai.test_inject_peer(a1, /*scope=*/1, /*now_ms=*/1000);
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||||
|
TEST_ASSERT_TRUE(ai.has_peer(a1));
|
||||||
|
TEST_ASSERT_EQUAL_UINT64(1000, ai.peer_last_heard_ms(a1));
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_add_peer_idempotent_refreshes_last_heard() {
|
||||||
|
AutoInterface ai("test_iface", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||||
|
AutoInterface::DEFAULT_DATA_PORT, 4);
|
||||||
|
|
||||||
|
auto a1 = make_addr(0x02);
|
||||||
|
ai.test_inject_peer(a1, 1, 5000);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||||
|
TEST_ASSERT_EQUAL_UINT64(5000, ai.peer_last_heard_ms(a1));
|
||||||
|
|
||||||
|
// Second add for the same address: count stays 1, last_heard advances.
|
||||||
|
ai.test_inject_peer(a1, 1, 9999);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||||
|
TEST_ASSERT_EQUAL_UINT64(9999, ai.peer_last_heard_ms(a1));
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_add_peer_respects_max_peers_cap() {
|
||||||
|
AutoInterface ai("test_iface", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||||
|
AutoInterface::DEFAULT_DATA_PORT,
|
||||||
|
/*max_peers=*/3);
|
||||||
|
|
||||||
|
for (uint8_t i = 1; i <= 5; ++i) {
|
||||||
|
ai.test_inject_peer(make_addr(i), 1, 1000 + i);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only first 3 should have been admitted.
|
||||||
|
TEST_ASSERT_EQUAL_size_t(3, ai.peer_count());
|
||||||
|
TEST_ASSERT_TRUE(ai.has_peer(make_addr(1)));
|
||||||
|
TEST_ASSERT_TRUE(ai.has_peer(make_addr(2)));
|
||||||
|
TEST_ASSERT_TRUE(ai.has_peer(make_addr(3)));
|
||||||
|
TEST_ASSERT_FALSE(ai.has_peer(make_addr(4)));
|
||||||
|
TEST_ASSERT_FALSE(ai.has_peer(make_addr(5)));
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_peer_jobs_evicts_timed_out_peers() {
|
||||||
|
AutoInterface ai("test_iface", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||||
|
AutoInterface::DEFAULT_DATA_PORT, 4);
|
||||||
|
|
||||||
|
auto fresh = make_addr(0x10); // injected near "now"
|
||||||
|
auto stale = make_addr(0x11); // last_heard well in the past
|
||||||
|
ai.test_inject_peer(stale, 1, /*now_ms=*/0);
|
||||||
|
ai.test_inject_peer(fresh, 1, /*now_ms=*/30000);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(2, ai.peer_count());
|
||||||
|
|
||||||
|
// Run jobs at t = 25s. PEERING_TIMEOUT_MS = 22000.
|
||||||
|
// stale: 25000 > 0 + 22000 → evict
|
||||||
|
// fresh: 25000 > 30000 + 22000 → false → keep
|
||||||
|
ai.test_run_peer_jobs(25000);
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||||
|
TEST_ASSERT_FALSE(ai.has_peer(stale));
|
||||||
|
TEST_ASSERT_TRUE(ai.has_peer(fresh));
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_peer_jobs_keeps_recent_peers() {
|
||||||
|
AutoInterface ai("test_iface", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
AutoInterface::DEFAULT_DISCOVERY_PORT,
|
||||||
|
AutoInterface::DEFAULT_DATA_PORT, 4);
|
||||||
|
|
||||||
|
auto a = make_addr(0x20);
|
||||||
|
ai.test_inject_peer(a, 1, 10000);
|
||||||
|
ai.test_run_peer_jobs(15000); // 15s < 22s timeout
|
||||||
|
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Socket lifecycle (native impl). Uses ephemeral high ports to avoid
|
||||||
|
// colliding with any system AutoInterface listener on the host.
|
||||||
|
|
||||||
|
// Discovery and data must be ≥ 2 apart so the auto-derived
|
||||||
|
// unicast_disco_port (= discovery + 1) doesn't collide with data.
|
||||||
|
static const uint16_t kTestDiscoPort = 49716;
|
||||||
|
static const uint16_t kTestDataPort = 49720;
|
||||||
|
|
||||||
|
void test_start_without_link_local_fails() {
|
||||||
|
AutoInterface ai("test_lifecycle", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kTestDiscoPort, kTestDataPort, 4);
|
||||||
|
|
||||||
|
// No set_link_local() call — start() should refuse.
|
||||||
|
TEST_ASSERT_FALSE(ai.start());
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd());
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai.unicast_socket_fd());
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai.data_socket_fd());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_notify_link_change_recomputes_token() {
|
||||||
|
AutoInterface ai("nlc_token", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
29716, 42671, 4);
|
||||||
|
|
||||||
|
ai.set_link_local("fe80::abcd:1234", 1);
|
||||||
|
Bytes t1 = ai.test_self_disco_token();
|
||||||
|
TEST_ASSERT_EQUAL_size_t(32, t1.size());
|
||||||
|
TEST_ASSERT_EQUAL_STRING(kTokenReticulumFe80AbcdHex, t1.toHex().c_str());
|
||||||
|
|
||||||
|
ai.notify_link_change("fe80::1", 1);
|
||||||
|
Bytes t2 = ai.test_self_disco_token();
|
||||||
|
TEST_ASSERT_EQUAL_size_t(32, t2.size());
|
||||||
|
TEST_ASSERT_EQUAL_STRING(kTokenReticulumFe80OneHex, t2.toHex().c_str());
|
||||||
|
TEST_ASSERT_TRUE(t1 != t2);
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_notify_link_change_remembers_old_for_self_echo() {
|
||||||
|
AutoInterface ai("nlc_history", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
29716, 42671, 4);
|
||||||
|
|
||||||
|
// First call: no prior address, history stays empty.
|
||||||
|
ai.set_link_local("fe80::abcd:1234", 1);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(0, ai.test_self_link_local_history_size());
|
||||||
|
|
||||||
|
// Second call: prior address is rotated into history.
|
||||||
|
ai.notify_link_change("fe80::1", 1);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(1, ai.test_self_link_local_history_size());
|
||||||
|
|
||||||
|
// Three more rotations — history caps at SELF_LL_HISTORY_MAX (4).
|
||||||
|
ai.notify_link_change("fe80::2", 1);
|
||||||
|
ai.notify_link_change("fe80::3", 1);
|
||||||
|
ai.notify_link_change("fe80::4", 1);
|
||||||
|
ai.notify_link_change("fe80::5", 1);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(4, ai.test_self_link_local_history_size());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_notify_link_change_idempotent() {
|
||||||
|
AutoInterface ai("nlc_idem", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
29716, 42671, 4);
|
||||||
|
|
||||||
|
ai.set_link_local("fe80::abcd:1234", 1);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(0, ai.test_self_link_local_history_size());
|
||||||
|
|
||||||
|
// Same args → no-op, history must not grow.
|
||||||
|
ai.notify_link_change("fe80::abcd:1234", 1);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(0, ai.test_self_link_local_history_size());
|
||||||
|
|
||||||
|
// Different canonical form of the same address (uppercase) → still no-op.
|
||||||
|
ai.notify_link_change("FE80::ABCD:1234", 1);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(0, ai.test_self_link_local_history_size());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_notify_link_change_rejects_invalid_address() {
|
||||||
|
AutoInterface ai("nlc_bad", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
29716, 42671, 4);
|
||||||
|
|
||||||
|
ai.set_link_local("fe80::1", 1);
|
||||||
|
Bytes before = ai.test_self_disco_token();
|
||||||
|
|
||||||
|
// Garbage input — must not mutate token or history.
|
||||||
|
ai.notify_link_change("not-an-address", 2);
|
||||||
|
TEST_ASSERT_TRUE(before == ai.test_self_disco_token());
|
||||||
|
TEST_ASSERT_EQUAL_size_t(0, ai.test_self_link_local_history_size());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_constructor_default_hops_link_scope() {
|
||||||
|
// SCOPE_LINK with hops=0 → auto-default 1 (link-local only).
|
||||||
|
AutoInterface ai("hops_link", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
29716, 42671, 4);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(1, ai.multicast_hops());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_constructor_default_hops_admin_scope() {
|
||||||
|
// SCOPE_ADMIN with hops=0 → auto-default 32 (cross-router-ready).
|
||||||
|
AutoInterface ai("hops_admin", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_ADMIN,
|
||||||
|
29716, 42671, 4);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(32, ai.multicast_hops());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_constructor_explicit_hops_overrides_default() {
|
||||||
|
AutoInterface ai("hops_explicit", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
29716, 42671, 4, /*multicast_hops=*/16);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(16, ai.multicast_hops());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_start_rejects_colliding_data_port() {
|
||||||
|
// data_port == unicast_disco_port (= discovery_port + 1). Without the
|
||||||
|
// guard, both sockets bind via SO_REUSEPORT and silently steal each
|
||||||
|
// other's packets.
|
||||||
|
AutoInterface ai_collide_unicast("test_collide_unicast", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
29716, 29717, 4);
|
||||||
|
ai_collide_unicast.set_link_local("fe80::1", 1);
|
||||||
|
TEST_ASSERT_FALSE(ai_collide_unicast.start());
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai_collide_unicast.discovery_socket_fd());
|
||||||
|
|
||||||
|
// data_port == discovery_port (the multicast socket itself).
|
||||||
|
AutoInterface ai_collide_disco("test_collide_disco", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
29716, 29716, 4);
|
||||||
|
ai_collide_disco.set_link_local("fe80::1", 1);
|
||||||
|
TEST_ASSERT_FALSE(ai_collide_disco.start());
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai_collide_disco.discovery_socket_fd());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_start_opens_three_sockets() {
|
||||||
|
AutoInterface ai("test_lifecycle", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kTestDiscoPort, kTestDataPort, 4);
|
||||||
|
|
||||||
|
// "fe80::1" + scope=1 (loopback / lo0 on most hosts). IPV6_JOIN_GROUP
|
||||||
|
// may warn on some hosts but start() tolerates that — see open_sockets()
|
||||||
|
// best-effort note.
|
||||||
|
ai.set_link_local("fe80::1", 1);
|
||||||
|
TEST_ASSERT_TRUE(ai.start());
|
||||||
|
|
||||||
|
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.discovery_socket_fd());
|
||||||
|
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.unicast_socket_fd());
|
||||||
|
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.data_socket_fd());
|
||||||
|
|
||||||
|
// All three FDs must be distinct.
|
||||||
|
TEST_ASSERT_NOT_EQUAL(ai.discovery_socket_fd(), ai.unicast_socket_fd());
|
||||||
|
TEST_ASSERT_NOT_EQUAL(ai.discovery_socket_fd(), ai.data_socket_fd());
|
||||||
|
TEST_ASSERT_NOT_EQUAL(ai.unicast_socket_fd(), ai.data_socket_fd());
|
||||||
|
|
||||||
|
// Multicast address must be populated.
|
||||||
|
TEST_ASSERT_FALSE(ai.multicast_address().empty());
|
||||||
|
|
||||||
|
ai.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_stop_closes_sockets_and_clears_peers() {
|
||||||
|
AutoInterface ai("test_lifecycle", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kTestDiscoPort + 10, kTestDataPort + 10, 4);
|
||||||
|
ai.set_link_local("fe80::1", 1);
|
||||||
|
TEST_ASSERT_TRUE(ai.start());
|
||||||
|
|
||||||
|
ai.test_inject_peer(make_addr(0x42), 1, 1000);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||||
|
|
||||||
|
ai.stop();
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd());
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai.unicast_socket_fd());
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai.data_socket_fd());
|
||||||
|
TEST_ASSERT_EQUAL_size_t(0, ai.peer_count());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_start_stop_start_is_idempotent() {
|
||||||
|
AutoInterface ai("test_lifecycle", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kTestDiscoPort + 20, kTestDataPort + 20, 4);
|
||||||
|
ai.set_link_local("fe80::1", 1);
|
||||||
|
|
||||||
|
TEST_ASSERT_TRUE(ai.start());
|
||||||
|
int fd1 = ai.discovery_socket_fd();
|
||||||
|
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, fd1);
|
||||||
|
ai.stop();
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd());
|
||||||
|
|
||||||
|
// Restart on the same ports must succeed (REUSEADDR on disco_sock).
|
||||||
|
TEST_ASSERT_TRUE(ai.start());
|
||||||
|
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.discovery_socket_fd());
|
||||||
|
ai.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_loop_at_does_not_crash_when_offline() {
|
||||||
|
AutoInterface ai("test_loop_offline", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kTestDiscoPort + 30, kTestDataPort + 30, 4);
|
||||||
|
// No start() — loop_at on an offline interface must early-return.
|
||||||
|
ai.test_loop_at(0);
|
||||||
|
ai.test_loop_at(99999);
|
||||||
|
TEST_ASSERT_FALSE(ai.has_carrier());
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_loop_at_drives_announce_and_peer_jobs_scheduling() {
|
||||||
|
AutoInterface ai("test_loop_sched", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kTestDiscoPort + 40, kTestDataPort + 40, 4);
|
||||||
|
ai.set_link_local("fe80::1", 1);
|
||||||
|
TEST_ASSERT_TRUE(ai.start());
|
||||||
|
|
||||||
|
// Prime peer table — stale + fresh. Use t=0 / t=30000 so they end up on
|
||||||
|
// opposite sides of PEERING_TIMEOUT_MS=22000 at t=25000.
|
||||||
|
auto stale = make_addr(0x30);
|
||||||
|
auto fresh = make_addr(0x31);
|
||||||
|
ai.test_inject_peer(stale, 1, 0);
|
||||||
|
ai.test_inject_peer(fresh, 1, 30000);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(2, ai.peer_count());
|
||||||
|
|
||||||
|
// First loop_at() at t=0 sends an announce (next_announce_ms starts at 0
|
||||||
|
// after start()) and schedules peer_jobs for t=4000. Peer count should
|
||||||
|
// not change at t=0.
|
||||||
|
ai.test_loop_at(0);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(2, ai.peer_count());
|
||||||
|
|
||||||
|
// Advance to t=25000 — past PEERING_TIMEOUT for stale peer. loop_at
|
||||||
|
// should fire peer_jobs (next_peer_job_ms=4000 < 25000) and evict.
|
||||||
|
ai.test_loop_at(25000);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(1, ai.peer_count());
|
||||||
|
TEST_ASSERT_TRUE(ai.has_peer(fresh));
|
||||||
|
|
||||||
|
ai.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loopback round-trip: announce + multicast RX. Skips silently if
|
||||||
|
// IPV6_JOIN_GROUP isn't supported on the test host's loopback interface
|
||||||
|
// (some Linux configurations). This is the closest we can get to a real
|
||||||
|
// peering handshake without two physical machines.
|
||||||
|
void test_loopback_announce_receives_self_echo() {
|
||||||
|
AutoInterface ai("test_loopback", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kTestDiscoPort + 50, kTestDataPort + 50, 4);
|
||||||
|
ai.set_link_local("fe80::1", 1);
|
||||||
|
if (!ai.start()) {
|
||||||
|
TEST_IGNORE_MESSAGE("start() failed on this host's loopback");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// First announce sets _final_init_done = true and sends to mcast.
|
||||||
|
ai.test_loop_at(0);
|
||||||
|
|
||||||
|
// Give the kernel a moment to loop the multicast packet back.
|
||||||
|
for (int i = 0; i < 20 && !ai.has_carrier(); ++i) {
|
||||||
|
ai.test_loop_at(static_cast<uint64_t>(i + 1) * 10);
|
||||||
|
struct timespec ts { 0, 5'000'000 }; // 5 ms
|
||||||
|
nanosleep(&ts, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!ai.has_carrier()) {
|
||||||
|
// Multicast loopback may be filtered out on some hosts (e.g. macOS
|
||||||
|
// treats lo0's link-local strangely). Don't fail the suite — the
|
||||||
|
// real validation is the Phase 2 E2E test against Python.
|
||||||
|
TEST_IGNORE_MESSAGE("no multicast echo on this host's loopback");
|
||||||
|
} else {
|
||||||
|
TEST_ASSERT_TRUE(ai.has_carrier());
|
||||||
|
}
|
||||||
|
|
||||||
|
ai.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
void setUp(void) {}
|
||||||
|
void tearDown(void) {}
|
||||||
|
|
||||||
|
int runUnityTests(void) {
|
||||||
|
UNITY_BEGIN();
|
||||||
|
RUN_TEST(test_group_hash_default);
|
||||||
|
RUN_TEST(test_multicast_address_default_group_link_temp);
|
||||||
|
RUN_TEST(test_multicast_address_default_group_admin_permanent);
|
||||||
|
RUN_TEST(test_multicast_address_custom_group);
|
||||||
|
RUN_TEST(test_multicast_address_short_group_hash_returns_empty);
|
||||||
|
RUN_TEST(test_discovery_token_default_group);
|
||||||
|
RUN_TEST(test_discovery_token_compressed_address);
|
||||||
|
RUN_TEST(test_set_link_local_canonicalizes_expanded_form);
|
||||||
|
RUN_TEST(test_set_link_local_lowercases_uppercase_input);
|
||||||
|
RUN_TEST(test_discovery_token_custom_group);
|
||||||
|
RUN_TEST(test_add_peer_registers_and_counts);
|
||||||
|
RUN_TEST(test_add_peer_idempotent_refreshes_last_heard);
|
||||||
|
RUN_TEST(test_add_peer_respects_max_peers_cap);
|
||||||
|
RUN_TEST(test_peer_jobs_evicts_timed_out_peers);
|
||||||
|
RUN_TEST(test_peer_jobs_keeps_recent_peers);
|
||||||
|
RUN_TEST(test_notify_link_change_recomputes_token);
|
||||||
|
RUN_TEST(test_notify_link_change_remembers_old_for_self_echo);
|
||||||
|
RUN_TEST(test_notify_link_change_idempotent);
|
||||||
|
RUN_TEST(test_notify_link_change_rejects_invalid_address);
|
||||||
|
RUN_TEST(test_constructor_default_hops_link_scope);
|
||||||
|
RUN_TEST(test_constructor_default_hops_admin_scope);
|
||||||
|
RUN_TEST(test_constructor_explicit_hops_overrides_default);
|
||||||
|
RUN_TEST(test_start_without_link_local_fails);
|
||||||
|
RUN_TEST(test_start_rejects_colliding_data_port);
|
||||||
|
RUN_TEST(test_start_opens_three_sockets);
|
||||||
|
RUN_TEST(test_stop_closes_sockets_and_clears_peers);
|
||||||
|
RUN_TEST(test_start_stop_start_is_idempotent);
|
||||||
|
RUN_TEST(test_loop_at_does_not_crash_when_offline);
|
||||||
|
RUN_TEST(test_loop_at_drives_announce_and_peer_jobs_scheduling);
|
||||||
|
RUN_TEST(test_loopback_announce_receives_self_echo);
|
||||||
|
return UNITY_END();
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void) { return runUnityTests(); }
|
||||||
|
|
||||||
|
#ifdef ARDUINO
|
||||||
|
void setup() { delay(2000); runUnityTests(); }
|
||||||
|
void loop() {}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void app_main() { runUnityTests(); }
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
// AutoInterface loopback integration tests.
|
||||||
|
//
|
||||||
|
// These exercise the real socket/poll/setsockopt paths against the host's
|
||||||
|
// loopback IPv6 multicast — the closest we can get to live LAN behavior
|
||||||
|
// without two physical machines or root privileges.
|
||||||
|
//
|
||||||
|
// Limitations of single-host loopback testing:
|
||||||
|
// * Two AutoInterface instances bound to the same fe80:: address can't
|
||||||
|
// genuinely peer with each other: each treats the other's announce as
|
||||||
|
// a self-echo (their src.sin6_addr matches each instance's own
|
||||||
|
// _self_link_local_bin). True peering requires distinct link-local
|
||||||
|
// identities, which on a single host requires root + `ip -6 addr add`.
|
||||||
|
// * IPV6_JOIN_GROUP on lo0 may be filtered by some hosts (notably
|
||||||
|
// macOS / older lwIP); those configurations TEST_IGNORE rather than
|
||||||
|
// fail so CI on developer laptops doesn't flake.
|
||||||
|
//
|
||||||
|
// What IS verified end-to-end here:
|
||||||
|
// 1. Two AutoInterface instances can coexist on the same host without
|
||||||
|
// crashing, leaking sockets, or interfering with each other's
|
||||||
|
// multicast traffic.
|
||||||
|
// 2. has_carrier() becomes true after start() drives the multicast
|
||||||
|
// loopback round-trip.
|
||||||
|
// 3. Self-echo suppression keeps peer_count() at 0 after notify_link_
|
||||||
|
// change(), even when the kernel delays a loopback of the announce
|
||||||
|
// sent under the previous link-local.
|
||||||
|
// 4. notify_link_change() while online survives the IPV6_LEAVE_GROUP /
|
||||||
|
// IPV6_JOIN_GROUP rotation without breaking carrier.
|
||||||
|
|
||||||
|
#include <unity.h>
|
||||||
|
#include <time.h>
|
||||||
|
|
||||||
|
#include "Interfaces/AutoInterface.h"
|
||||||
|
#include "Bytes.h"
|
||||||
|
|
||||||
|
using RNS::AutoInterface;
|
||||||
|
using RNS::Bytes;
|
||||||
|
|
||||||
|
// Ports chosen well above the production defaults and the unit-test range
|
||||||
|
// (49716+) so there is no overlap.
|
||||||
|
static constexpr uint16_t kAlfaDisc = 49810;
|
||||||
|
static constexpr uint16_t kAlfaData = 49814;
|
||||||
|
static constexpr uint16_t kBravoDisc = 49820;
|
||||||
|
static constexpr uint16_t kBravoData = 49824;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// Drive loop_at() in 100ms simulated steps, sleeping a real 5ms between
|
||||||
|
// each so the kernel actually delivers any pending multicast frames.
|
||||||
|
void drive(AutoInterface& ai, uint64_t start_ms, uint64_t end_ms) {
|
||||||
|
for (uint64_t t = start_ms; t <= end_ms; t += 100) {
|
||||||
|
ai.test_loop_at(t);
|
||||||
|
struct timespec ts { 0, 5'000'000 }; // 5 ms
|
||||||
|
nanosleep(&ts, nullptr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void drive_pair(AutoInterface& a, AutoInterface& b,
|
||||||
|
uint64_t start_ms, uint64_t end_ms) {
|
||||||
|
for (uint64_t t = start_ms; t <= end_ms; t += 100) {
|
||||||
|
a.test_loop_at(t);
|
||||||
|
b.test_loop_at(t);
|
||||||
|
struct timespec ts { 0, 5'000'000 };
|
||||||
|
nanosleep(&ts, nullptr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void test_two_instances_coexist_on_loopback() {
|
||||||
|
AutoInterface alfa("alfa", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kAlfaDisc, kAlfaData, 4);
|
||||||
|
AutoInterface bravo("bravo", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kBravoDisc, kBravoData, 4);
|
||||||
|
|
||||||
|
alfa.set_link_local("fe80::1", 1);
|
||||||
|
bravo.set_link_local("fe80::1", 1);
|
||||||
|
|
||||||
|
if (!alfa.start() || !bravo.start()) {
|
||||||
|
alfa.stop(); bravo.stop();
|
||||||
|
TEST_IGNORE_MESSAGE("could not start two AutoInterface instances on loopback");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
drive_pair(alfa, bravo, 0, 3000);
|
||||||
|
|
||||||
|
if (!alfa.has_carrier() || !bravo.has_carrier()) {
|
||||||
|
alfa.stop(); bravo.stop();
|
||||||
|
TEST_IGNORE_MESSAGE("multicast loopback filtered on this host (lo0 IPV6 mcast)");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Both saw multicast carrier — kernel is routing between them.
|
||||||
|
TEST_ASSERT_TRUE(alfa.has_carrier());
|
||||||
|
TEST_ASSERT_TRUE(bravo.has_carrier());
|
||||||
|
|
||||||
|
// Both bound to fe80::1, so each correctly treats the other's
|
||||||
|
// announce as self-echo. Documented limitation — round-trip peering
|
||||||
|
// across a single loopback host without root is not achievable.
|
||||||
|
TEST_ASSERT_EQUAL_size_t(0, alfa.peer_count());
|
||||||
|
TEST_ASSERT_EQUAL_size_t(0, bravo.peer_count());
|
||||||
|
|
||||||
|
alfa.stop();
|
||||||
|
bravo.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_notify_link_change_while_online_keeps_carrier() {
|
||||||
|
AutoInterface ai("nlc_online", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kAlfaDisc + 100, kAlfaData + 100, 4);
|
||||||
|
|
||||||
|
ai.set_link_local("fe80::1", 1);
|
||||||
|
if (!ai.start()) {
|
||||||
|
TEST_IGNORE_MESSAGE("start() failed on this host's loopback");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Phase 1: acquire carrier under the original address.
|
||||||
|
drive(ai, 0, 2000);
|
||||||
|
if (!ai.has_carrier()) {
|
||||||
|
ai.stop();
|
||||||
|
TEST_IGNORE_MESSAGE("no multicast echo on this host's loopback");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Phase 2: rotate the link-local while online. Same scope_id so no
|
||||||
|
// IPV6_LEAVE/JOIN cycle fires — only the token rotates and the old
|
||||||
|
// address goes into the self-echo history.
|
||||||
|
ai.notify_link_change("fe80::abcd:1234", 1);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(1, ai.test_self_link_local_history_size());
|
||||||
|
|
||||||
|
// Phase 3: keep driving. Any late loopback of the *previous*
|
||||||
|
// announce's source address must be suppressed by the history-
|
||||||
|
// backed self-echo filter — peer_count() must stay 0.
|
||||||
|
drive(ai, 2000, 5000);
|
||||||
|
TEST_ASSERT_EQUAL_size_t(0, ai.peer_count());
|
||||||
|
|
||||||
|
// Carrier should still be true (we kept getting echoes of our new
|
||||||
|
// announces during phase 3). If multicast suddenly broke this would
|
||||||
|
// surface here as a regression.
|
||||||
|
TEST_ASSERT_TRUE(ai.has_carrier());
|
||||||
|
|
||||||
|
ai.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
void test_notify_link_change_with_new_scope_rejoins_group() {
|
||||||
|
// Same scope_id is the common case (Wi-Fi reassoc, new link-local
|
||||||
|
// prefix on the same NIC). This test exercises the rarer scope_id
|
||||||
|
// change (e.g. Wi-Fi disconnect, fall back to a different netif) so
|
||||||
|
// the IPV6_LEAVE_GROUP / IPV6_JOIN_GROUP code path runs in a real
|
||||||
|
// socket context. We can't observe the rejoin directly without
|
||||||
|
// platform-specific introspection, so the assertion is "didn't
|
||||||
|
// crash, sockets still open, carrier eventually reacquires."
|
||||||
|
AutoInterface ai("nlc_scope", "reticulum",
|
||||||
|
AutoInterface::MCAST_ADDR_TYPE_TEMPORARY,
|
||||||
|
AutoInterface::SCOPE_LINK,
|
||||||
|
kAlfaDisc + 200, kAlfaData + 200, 4);
|
||||||
|
|
||||||
|
ai.set_link_local("fe80::1", 1);
|
||||||
|
if (!ai.start()) {
|
||||||
|
TEST_IGNORE_MESSAGE("start() failed on this host's loopback");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
drive(ai, 0, 2000);
|
||||||
|
if (!ai.has_carrier()) {
|
||||||
|
ai.stop();
|
||||||
|
TEST_IGNORE_MESSAGE("no multicast echo on this host's loopback");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rotate scope while online. scope_id=2 on most hosts won't match
|
||||||
|
// any real interface — the rejoin will warn but must not break the
|
||||||
|
// already-open sockets.
|
||||||
|
ai.notify_link_change("fe80::abcd:1234", 2);
|
||||||
|
|
||||||
|
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.discovery_socket_fd());
|
||||||
|
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.unicast_socket_fd());
|
||||||
|
TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.data_socket_fd());
|
||||||
|
|
||||||
|
// Drive a few more cycles — this must not crash and must continue
|
||||||
|
// processing the loop without leaking FDs.
|
||||||
|
drive(ai, 2000, 3500);
|
||||||
|
|
||||||
|
ai.stop();
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd());
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai.unicast_socket_fd());
|
||||||
|
TEST_ASSERT_EQUAL_INT(-1, ai.data_socket_fd());
|
||||||
|
}
|
||||||
|
|
||||||
|
void setUp(void) {}
|
||||||
|
void tearDown(void) {}
|
||||||
|
|
||||||
|
int runUnityTests(void) {
|
||||||
|
UNITY_BEGIN();
|
||||||
|
RUN_TEST(test_two_instances_coexist_on_loopback);
|
||||||
|
RUN_TEST(test_notify_link_change_while_online_keeps_carrier);
|
||||||
|
RUN_TEST(test_notify_link_change_with_new_scope_rejoins_group);
|
||||||
|
return UNITY_END();
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void) { return runUnityTests(); }
|
||||||
|
|
||||||
|
#ifdef ARDUINO
|
||||||
|
void setup() { delay(2000); runUnityTests(); }
|
||||||
|
void loop() {}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void app_main() { runUnityTests(); }
|
||||||
@@ -659,8 +659,8 @@ int runUnityTests(void) {
|
|||||||
UNITY_BEGIN();
|
UNITY_BEGIN();
|
||||||
|
|
||||||
// Suite-level setup
|
// Suite-level setup
|
||||||
RNS::Utilities::OS::dump_heap_stats();
|
RNS::Utilities::Memory::dump_heap_stats();
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
TRACEF("testBytes: pre-mem: %u", pre_memory);
|
TRACEF("testBytes: pre-mem: %u", pre_memory);
|
||||||
|
|
||||||
// Run tests
|
// Run tests
|
||||||
@@ -686,7 +686,7 @@ int runUnityTests(void) {
|
|||||||
RUN_TEST(test_mid_zero_size_bytes);
|
RUN_TEST(test_mid_zero_size_bytes);
|
||||||
|
|
||||||
// Suite-level teardown
|
// Suite-level teardown
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
TRACEF("testBytes: post-mem: %u", post_memory);
|
TRACEF("testBytes: post-mem: %u", post_memory);
|
||||||
TRACEF("testBytes: diff-mem: %u", diff_memory);
|
TRACEF("testBytes: diff-mem: %u", diff_memory);
|
||||||
|
|||||||
@@ -0,0 +1,538 @@
|
|||||||
|
/// Cross-platform compatibility fixture generator for microReticulum (C++).
|
||||||
|
///
|
||||||
|
/// Computes deterministic values from known seeds and validates them.
|
||||||
|
/// These same seeds and expected values are used by the Rust test suite
|
||||||
|
/// in raticulum-tests/tests/cpp_fixture_compat.rs to prove byte-level
|
||||||
|
/// interoperability between the C++ and Rust implementations.
|
||||||
|
///
|
||||||
|
/// Seeds:
|
||||||
|
/// x25519_seed = SHA256("x25519_test_seed")
|
||||||
|
/// ed25519_seed = SHA256("ed25519_test_seed")
|
||||||
|
/// private_key = x25519_seed(32) || ed25519_seed(32)
|
||||||
|
|
||||||
|
#include <unity.h>
|
||||||
|
|
||||||
|
#include "Identity.h"
|
||||||
|
#include "Cryptography/Hashes.h"
|
||||||
|
#include "Cryptography/Ed25519.h"
|
||||||
|
#include "Cryptography/X25519.h"
|
||||||
|
#include "Cryptography/AES.h"
|
||||||
|
#include "Cryptography/HMAC.h"
|
||||||
|
#include "Cryptography/HKDF.h"
|
||||||
|
#include "Cryptography/PKCS7.h"
|
||||||
|
#include "Cryptography/Token.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
#include <vector>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
// ---- Inline MsgPack helpers (from ratdeck/src/reticulum/LXMFMessage.cpp) ----
|
||||||
|
|
||||||
|
static void mpPackFloat64(std::vector<uint8_t>& buf, double val) {
|
||||||
|
buf.push_back(0xCB);
|
||||||
|
uint64_t bits;
|
||||||
|
memcpy(&bits, &val, 8);
|
||||||
|
for (int i = 7; i >= 0; i--) {
|
||||||
|
buf.push_back((bits >> (i * 8)) & 0xFF);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void mpPackBin(std::vector<uint8_t>& buf, const std::string& str) {
|
||||||
|
size_t len = str.size();
|
||||||
|
if (len < 256) {
|
||||||
|
buf.push_back(0xC4);
|
||||||
|
buf.push_back((uint8_t)len);
|
||||||
|
} else {
|
||||||
|
buf.push_back(0xC5);
|
||||||
|
buf.push_back((len >> 8) & 0xFF);
|
||||||
|
buf.push_back(len & 0xFF);
|
||||||
|
}
|
||||||
|
buf.insert(buf.end(), str.begin(), str.end());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Helpers ----
|
||||||
|
|
||||||
|
static void printHex(const char* label, const uint8_t* data, size_t len) {
|
||||||
|
printf(" %s = ", label);
|
||||||
|
for (size_t i = 0; i < len; i++) {
|
||||||
|
printf("%02x", data[i]);
|
||||||
|
}
|
||||||
|
printf("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
static void printHex(const char* label, const RNS::Bytes& data) {
|
||||||
|
printHex(label, data.data(), data.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
static void printHex(const char* label, const std::vector<uint8_t>& data) {
|
||||||
|
printHex(label, data.data(), data.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Global state computed once in setUp ----
|
||||||
|
|
||||||
|
static RNS::Identity g_identity({RNS::Type::NONE});
|
||||||
|
static RNS::Bytes g_x_seed;
|
||||||
|
static RNS::Bytes g_ed_seed;
|
||||||
|
static RNS::Bytes g_prv_key;
|
||||||
|
static RNS::Bytes g_identity_hash;
|
||||||
|
static RNS::Bytes g_x_pub;
|
||||||
|
static RNS::Bytes g_ed_pub;
|
||||||
|
static RNS::Bytes g_name_hash; // name_hash("lxmf.delivery")
|
||||||
|
static RNS::Bytes g_dest_hash; // truncated_hash(name_hash + identity_hash)
|
||||||
|
|
||||||
|
// Deterministic LXMF message parts
|
||||||
|
static const double FIXTURE_TIMESTAMP = 1700000000.0;
|
||||||
|
static const std::string FIXTURE_TITLE = "Hello from C++";
|
||||||
|
static const std::string FIXTURE_CONTENT = "Cross-platform test message";
|
||||||
|
|
||||||
|
static std::vector<uint8_t> g_packed_content;
|
||||||
|
static RNS::Bytes g_signature;
|
||||||
|
static std::vector<uint8_t> g_lxmf_wire;
|
||||||
|
|
||||||
|
// ---- Fixture setup ----
|
||||||
|
|
||||||
|
static bool g_initialized = false;
|
||||||
|
|
||||||
|
static void initFixture() {
|
||||||
|
if (g_initialized) return;
|
||||||
|
|
||||||
|
// Deterministic seeds (same as Rust cross_compat.rs)
|
||||||
|
g_x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||||
|
g_ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||||
|
|
||||||
|
// Private key = x25519_seed(32) || ed25519_seed(32)
|
||||||
|
g_prv_key = g_x_seed + g_ed_seed;
|
||||||
|
|
||||||
|
// Create identity from deterministic key
|
||||||
|
g_identity = RNS::Identity(false);
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_identity.load_private_key(g_prv_key),
|
||||||
|
"Failed to load deterministic private key");
|
||||||
|
|
||||||
|
g_identity_hash = g_identity.hash();
|
||||||
|
g_x_pub = g_identity.encryptionPublicKey();
|
||||||
|
g_ed_pub = g_identity.signingPublicKey();
|
||||||
|
|
||||||
|
// name_hash for "lxmf.delivery" = SHA256("lxmf.delivery")[:10]
|
||||||
|
// Manual computation (avoids Destination.h → Link.h incomplete type issue)
|
||||||
|
g_name_hash = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
|
||||||
|
// dest_hash = truncated_hash(name_hash + identity_hash)
|
||||||
|
// This is how Destination::hash() works
|
||||||
|
RNS::Bytes addr_material = g_name_hash + g_identity_hash;
|
||||||
|
g_dest_hash = RNS::Identity::truncated_hash(addr_material);
|
||||||
|
|
||||||
|
// Pack LXMF content: fixarray(4) + float64(ts) + bin(title) + bin(content) + fixmap(0)
|
||||||
|
g_packed_content.clear();
|
||||||
|
g_packed_content.push_back(0x94); // fixarray of 4
|
||||||
|
mpPackFloat64(g_packed_content, FIXTURE_TIMESTAMP);
|
||||||
|
mpPackBin(g_packed_content, FIXTURE_TITLE);
|
||||||
|
mpPackBin(g_packed_content, FIXTURE_CONTENT);
|
||||||
|
g_packed_content.push_back(0x80); // empty fixmap
|
||||||
|
|
||||||
|
// Build signed_data = dest_hash + src_hash + packed + SHA256(dest_hash + src_hash + packed)
|
||||||
|
// src_hash = identity_hash (we use same identity as sender)
|
||||||
|
std::vector<uint8_t> hashed_part;
|
||||||
|
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + g_dest_hash.size());
|
||||||
|
hashed_part.insert(hashed_part.end(), g_identity_hash.data(), g_identity_hash.data() + g_identity_hash.size());
|
||||||
|
hashed_part.insert(hashed_part.end(), g_packed_content.begin(), g_packed_content.end());
|
||||||
|
|
||||||
|
RNS::Bytes hashed_bytes(hashed_part.data(), hashed_part.size());
|
||||||
|
RNS::Bytes message_hash = RNS::Identity::full_hash(hashed_bytes);
|
||||||
|
|
||||||
|
std::vector<uint8_t> signed_data_vec;
|
||||||
|
signed_data_vec.insert(signed_data_vec.end(), hashed_part.begin(), hashed_part.end());
|
||||||
|
signed_data_vec.insert(signed_data_vec.end(), message_hash.data(), message_hash.data() + message_hash.size());
|
||||||
|
|
||||||
|
RNS::Bytes signed_data_bytes(signed_data_vec.data(), signed_data_vec.size());
|
||||||
|
g_signature = g_identity.sign(signed_data_bytes);
|
||||||
|
|
||||||
|
// Build full LXMF wire: [dest_hash:16][src_hash:16][signature:64][packed_content]
|
||||||
|
g_lxmf_wire.clear();
|
||||||
|
g_lxmf_wire.insert(g_lxmf_wire.end(), g_dest_hash.data(), g_dest_hash.data() + g_dest_hash.size());
|
||||||
|
g_lxmf_wire.insert(g_lxmf_wire.end(), g_identity_hash.data(), g_identity_hash.data() + g_identity_hash.size());
|
||||||
|
g_lxmf_wire.insert(g_lxmf_wire.end(), g_signature.data(), g_signature.data() + g_signature.size());
|
||||||
|
g_lxmf_wire.insert(g_lxmf_wire.end(), g_packed_content.begin(), g_packed_content.end());
|
||||||
|
|
||||||
|
g_initialized = true;
|
||||||
|
|
||||||
|
// Print all fixture values for capture
|
||||||
|
printf("\n=== C++ CROSS-COMPAT FIXTURE VALUES ===\n");
|
||||||
|
printHex("x25519_seed", g_x_seed);
|
||||||
|
printHex("ed25519_seed", g_ed_seed);
|
||||||
|
printHex("x25519_pub", g_x_pub);
|
||||||
|
printHex("ed25519_pub", g_ed_pub);
|
||||||
|
printHex("identity_hash", g_identity_hash);
|
||||||
|
printHex("name_hash_lxmf_delivery", g_name_hash);
|
||||||
|
printHex("dest_hash", g_dest_hash);
|
||||||
|
printHex("packed_content", g_packed_content);
|
||||||
|
printHex("signature", g_signature);
|
||||||
|
printHex("lxmf_wire", g_lxmf_wire);
|
||||||
|
printf(" packed_content_len = %zu\n", g_packed_content.size());
|
||||||
|
printf(" lxmf_wire_len = %zu\n", g_lxmf_wire.size());
|
||||||
|
printf("=== END FIXTURE VALUES ===\n\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Tests ----
|
||||||
|
|
||||||
|
void testIdentityHash() {
|
||||||
|
initFixture();
|
||||||
|
// Identity hash should be 16 bytes (truncated SHA256)
|
||||||
|
TEST_ASSERT_EQUAL_INT(16, g_identity_hash.size());
|
||||||
|
printf(" C++ identity_hash = %s\n", g_identity_hash.toHex().c_str());
|
||||||
|
|
||||||
|
// Verify identity hash = SHA256(x_pub || ed_pub)[:16]
|
||||||
|
RNS::Bytes pub_combined = g_x_pub + g_ed_pub;
|
||||||
|
RNS::Bytes expected = RNS::Identity::truncated_hash(pub_combined);
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_identity_hash == expected,
|
||||||
|
"Identity hash mismatch: SHA256(x_pub||ed_pub)[:16]");
|
||||||
|
}
|
||||||
|
|
||||||
|
void testNameHash() {
|
||||||
|
initFixture();
|
||||||
|
// name_hash should be 10 bytes (NAME_HASH_LENGTH=80 bits)
|
||||||
|
TEST_ASSERT_EQUAL_INT(10, g_name_hash.size());
|
||||||
|
printf(" C++ name_hash(lxmf.delivery) = %s\n", g_name_hash.toHex().c_str());
|
||||||
|
|
||||||
|
// Verify: SHA256("lxmf.delivery")[:10]
|
||||||
|
RNS::Bytes name_str("lxmf.delivery");
|
||||||
|
RNS::Bytes expected = RNS::Identity::full_hash(name_str).left(10);
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_name_hash == expected,
|
||||||
|
"name_hash mismatch for lxmf.delivery");
|
||||||
|
}
|
||||||
|
|
||||||
|
void testDestHash() {
|
||||||
|
initFixture();
|
||||||
|
TEST_ASSERT_EQUAL_INT(16, g_dest_hash.size());
|
||||||
|
printf(" C++ dest_hash = %s\n", g_dest_hash.toHex().c_str());
|
||||||
|
|
||||||
|
// Verify: truncated_hash(name_hash + identity_hash)
|
||||||
|
RNS::Bytes material = g_name_hash + g_identity_hash;
|
||||||
|
RNS::Bytes expected = RNS::Identity::truncated_hash(material);
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_dest_hash == expected,
|
||||||
|
"dest_hash mismatch");
|
||||||
|
}
|
||||||
|
|
||||||
|
void testPackedContent() {
|
||||||
|
initFixture();
|
||||||
|
// Verify packed content starts with fixarray(4) marker
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x94, g_packed_content[0]);
|
||||||
|
// Followed by float64 marker
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0xCB, g_packed_content[1]);
|
||||||
|
// Verify title is bin-encoded (0xC4 for bin8)
|
||||||
|
// After 1 (fixarray) + 9 (float64) = offset 10
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0xC4, g_packed_content[10]);
|
||||||
|
printf(" C++ packed_content_len = %zu\n", g_packed_content.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
void testSignature() {
|
||||||
|
initFixture();
|
||||||
|
TEST_ASSERT_EQUAL_INT(64, g_signature.size());
|
||||||
|
|
||||||
|
// Verify signature: rebuild signed_data and validate
|
||||||
|
std::vector<uint8_t> hashed_part;
|
||||||
|
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + g_dest_hash.size());
|
||||||
|
hashed_part.insert(hashed_part.end(), g_identity_hash.data(), g_identity_hash.data() + g_identity_hash.size());
|
||||||
|
hashed_part.insert(hashed_part.end(), g_packed_content.begin(), g_packed_content.end());
|
||||||
|
|
||||||
|
RNS::Bytes hashed_bytes(hashed_part.data(), hashed_part.size());
|
||||||
|
RNS::Bytes message_hash = RNS::Identity::full_hash(hashed_bytes);
|
||||||
|
|
||||||
|
std::vector<uint8_t> signed_data_vec;
|
||||||
|
signed_data_vec.insert(signed_data_vec.end(), hashed_part.begin(), hashed_part.end());
|
||||||
|
signed_data_vec.insert(signed_data_vec.end(), message_hash.data(), message_hash.data() + message_hash.size());
|
||||||
|
|
||||||
|
RNS::Bytes signed_data_bytes(signed_data_vec.data(), signed_data_vec.size());
|
||||||
|
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_identity.validate(g_signature, signed_data_bytes),
|
||||||
|
"Signature validation failed in C++");
|
||||||
|
}
|
||||||
|
|
||||||
|
void testLxmfWireFormat() {
|
||||||
|
initFixture();
|
||||||
|
// Wire: [dest_hash:16][src_hash:16][signature:64][packed_content]
|
||||||
|
size_t expected_len = 16 + 16 + 64 + g_packed_content.size();
|
||||||
|
TEST_ASSERT_EQUAL_INT(expected_len, g_lxmf_wire.size());
|
||||||
|
|
||||||
|
// Verify dest_hash at offset 0
|
||||||
|
TEST_ASSERT_EQUAL_INT(0, memcmp(g_lxmf_wire.data(), g_dest_hash.data(), 16));
|
||||||
|
// Verify src_hash at offset 16
|
||||||
|
TEST_ASSERT_EQUAL_INT(0, memcmp(g_lxmf_wire.data() + 16, g_identity_hash.data(), 16));
|
||||||
|
// Verify signature at offset 32
|
||||||
|
TEST_ASSERT_EQUAL_INT(0, memcmp(g_lxmf_wire.data() + 32, g_signature.data(), 64));
|
||||||
|
// Verify packed content at offset 96
|
||||||
|
TEST_ASSERT_EQUAL_INT(0, memcmp(g_lxmf_wire.data() + 96, g_packed_content.data(), g_packed_content.size()));
|
||||||
|
}
|
||||||
|
|
||||||
|
void testAdditionalNameHashes() {
|
||||||
|
initFixture();
|
||||||
|
size_t nh_len = RNS::Type::Identity::NAME_HASH_LENGTH / 8; // 10 bytes
|
||||||
|
|
||||||
|
// Compute name hashes for other common aspect names (manually, same as Destination::name_hash)
|
||||||
|
RNS::Bytes nh_prop = RNS::Identity::full_hash(RNS::Bytes("lxmf.propagation")).left(nh_len);
|
||||||
|
RNS::Bytes nh_nn = RNS::Identity::full_hash(RNS::Bytes("nomadnetwork.node")).left(nh_len);
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL_INT(10, nh_prop.size());
|
||||||
|
TEST_ASSERT_EQUAL_INT(10, nh_nn.size());
|
||||||
|
|
||||||
|
printf(" C++ name_hash(lxmf.propagation) = %s\n", nh_prop.toHex().c_str());
|
||||||
|
printf(" C++ name_hash(nomadnetwork.node) = %s\n", nh_nn.toHex().c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
void testPacketFlagEncoding() {
|
||||||
|
initFixture();
|
||||||
|
// Test flag byte encoding: (header_type<<6) | (context_flag<<5) | (transport_type<<4) | (dest_type<<2) | packet_type
|
||||||
|
// Header1, no context, broadcast, single, data = 0x00
|
||||||
|
uint8_t flags_h1_data = (0 << 6) | (0 << 5) | (0 << 4) | (0 << 2) | 0;
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x00, flags_h1_data);
|
||||||
|
|
||||||
|
// Header1, no context, broadcast, single, announce = 0x01
|
||||||
|
uint8_t flags_h1_announce = (0 << 6) | (0 << 5) | (0 << 4) | (0 << 2) | 1;
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x01, flags_h1_announce);
|
||||||
|
|
||||||
|
// Header2, no context, transport, single, data = 0x50
|
||||||
|
uint8_t flags_h2_transport_data = (1 << 6) | (0 << 5) | (1 << 4) | (0 << 2) | 0;
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x50, flags_h2_transport_data);
|
||||||
|
|
||||||
|
// Header2, context set, transport, single, data = 0x70
|
||||||
|
uint8_t flags_h2_ctx_transport = (1 << 6) | (1 << 5) | (1 << 4) | (0 << 2) | 0;
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x70, flags_h2_ctx_transport);
|
||||||
|
|
||||||
|
printf(" C++ flag encoding verified\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
void testAnnounceByteLayout() {
|
||||||
|
initFixture();
|
||||||
|
// Announce layout: [pubkey:64][name_hash:10][random_hash:10][signature:64][app_data...]
|
||||||
|
// We construct it manually with deterministic random_hash
|
||||||
|
|
||||||
|
RNS::Bytes pub_key = g_identity.get_public_key(); // 64 bytes
|
||||||
|
TEST_ASSERT_EQUAL_INT(64, pub_key.size());
|
||||||
|
|
||||||
|
// Use deterministic "random" hash
|
||||||
|
RNS::Bytes random_hash = RNS::Cryptography::sha256(RNS::Bytes("deterministic_random")).left(10);
|
||||||
|
|
||||||
|
// signed_data = dest_hash + public_key + name_hash + random_hash
|
||||||
|
RNS::Bytes signed_data;
|
||||||
|
signed_data << g_dest_hash << pub_key << g_name_hash << random_hash;
|
||||||
|
|
||||||
|
RNS::Bytes sig = g_identity.sign(signed_data);
|
||||||
|
TEST_ASSERT_EQUAL_INT(64, sig.size());
|
||||||
|
|
||||||
|
// Announce payload: pubkey(64) + name_hash(10) + random_hash(10) + signature(64) = 148 bytes minimum
|
||||||
|
RNS::Bytes announce_data;
|
||||||
|
announce_data << pub_key << g_name_hash << random_hash << sig;
|
||||||
|
TEST_ASSERT_EQUAL_INT(148, announce_data.size());
|
||||||
|
|
||||||
|
// Verify byte offsets
|
||||||
|
TEST_ASSERT_EQUAL_INT(0, memcmp(announce_data.data(), pub_key.data(), 64));
|
||||||
|
TEST_ASSERT_EQUAL_INT(0, memcmp(announce_data.data() + 64, g_name_hash.data(), 10));
|
||||||
|
TEST_ASSERT_EQUAL_INT(0, memcmp(announce_data.data() + 74, random_hash.data(), 10));
|
||||||
|
TEST_ASSERT_EQUAL_INT(0, memcmp(announce_data.data() + 84, sig.data(), 64));
|
||||||
|
|
||||||
|
// Validate signature
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_identity.validate(sig, signed_data),
|
||||||
|
"Announce signature validation failed");
|
||||||
|
|
||||||
|
printHex("random_hash", random_hash);
|
||||||
|
printHex("announce_signed_data", signed_data);
|
||||||
|
printHex("announce_signature", sig);
|
||||||
|
printHex("announce_data", announce_data);
|
||||||
|
printf(" announce_data_len = %zu\n", announce_data.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
void testEncryptDecryptRoundtrip() {
|
||||||
|
initFixture();
|
||||||
|
// Encrypt a known plaintext and verify we can decrypt it
|
||||||
|
RNS::Bytes plaintext("secret from cpp fixture");
|
||||||
|
RNS::Bytes ciphertext = g_identity.encrypt(plaintext);
|
||||||
|
|
||||||
|
// Verify format: ephemeral_pub(32) + token
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(ciphertext.size() > 32 + 16 + 32,
|
||||||
|
"Ciphertext too short");
|
||||||
|
|
||||||
|
RNS::Bytes decrypted = g_identity.decrypt(ciphertext);
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(decrypted == plaintext,
|
||||||
|
"Decrypt failed to recover plaintext");
|
||||||
|
|
||||||
|
printf(" C++ encrypt/decrypt roundtrip OK, ciphertext_len=%zu\n", ciphertext.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Cross-encryption tests: C++ encrypts, Rust decrypts (and vice versa) ----
|
||||||
|
|
||||||
|
// Second identity for cross-encryption (simulates a remote peer)
|
||||||
|
static RNS::Identity g_peer_identity({RNS::Type::NONE});
|
||||||
|
static RNS::Bytes g_peer_x_seed;
|
||||||
|
static RNS::Bytes g_peer_ed_seed;
|
||||||
|
static RNS::Bytes g_peer_x_pub;
|
||||||
|
static RNS::Bytes g_peer_identity_hash;
|
||||||
|
static RNS::Bytes g_cross_ciphertext;
|
||||||
|
static RNS::Bytes g_cross_plaintext;
|
||||||
|
|
||||||
|
// Deterministic ECDH test: use known ephemeral key to verify shared secret
|
||||||
|
static RNS::Bytes g_ecdh_ephemeral_prv_seed;
|
||||||
|
static RNS::Bytes g_ecdh_ephemeral_pub;
|
||||||
|
static RNS::Bytes g_ecdh_shared_secret;
|
||||||
|
|
||||||
|
static bool g_cross_initialized = false;
|
||||||
|
|
||||||
|
static RNS::Bytes clampX25519(const RNS::Bytes& key) {
|
||||||
|
// RFC 7748 clamping — same as Curve25519::dh1() and x25519-dalek::mul_clamped()
|
||||||
|
uint8_t buf[32];
|
||||||
|
memcpy(buf, key.data(), 32);
|
||||||
|
buf[0] &= 0xF8;
|
||||||
|
buf[31] = (buf[31] & 0x7F) | 0x40;
|
||||||
|
return RNS::Bytes(buf, 32);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void initCrossFixture() {
|
||||||
|
initFixture();
|
||||||
|
if (g_cross_initialized) return;
|
||||||
|
|
||||||
|
// Create a second identity (the "peer" / recipient)
|
||||||
|
g_peer_x_seed = RNS::Cryptography::sha256(RNS::Bytes("peer_x25519_seed"));
|
||||||
|
g_peer_ed_seed = RNS::Cryptography::sha256(RNS::Bytes("peer_ed25519_seed"));
|
||||||
|
|
||||||
|
// Clamp the X25519 seed to match production behavior.
|
||||||
|
// In production, dh1() clamps keys at generation time. Curve25519::eval()
|
||||||
|
// does NOT clamp internally, so imported keys must be pre-clamped for
|
||||||
|
// cross-platform ECDH compatibility with x25519-dalek (which clamps in DH).
|
||||||
|
g_peer_x_seed = clampX25519(g_peer_x_seed);
|
||||||
|
|
||||||
|
RNS::Bytes peer_prv = g_peer_x_seed + g_peer_ed_seed;
|
||||||
|
|
||||||
|
g_peer_identity = RNS::Identity(false);
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_peer_identity.load_private_key(peer_prv),
|
||||||
|
"Failed to load peer private key");
|
||||||
|
|
||||||
|
g_peer_x_pub = g_peer_identity.encryptionPublicKey();
|
||||||
|
g_peer_identity_hash = g_peer_identity.hash();
|
||||||
|
|
||||||
|
// Deterministic ephemeral key for cross-encryption
|
||||||
|
g_ecdh_ephemeral_prv_seed = clampX25519(
|
||||||
|
RNS::Cryptography::sha256(RNS::Bytes("deterministic_ephemeral_seed")));
|
||||||
|
auto eph_prv = RNS::Cryptography::X25519PrivateKey::from_private_bytes(g_ecdh_ephemeral_prv_seed);
|
||||||
|
g_ecdh_ephemeral_pub = eph_prv->public_key()->public_bytes();
|
||||||
|
|
||||||
|
// ECDH: ephemeral × peer_x_pub → shared secret for cross-encryption
|
||||||
|
RNS::Bytes cross_shared = eph_prv->exchange(g_peer_x_pub);
|
||||||
|
|
||||||
|
// HKDF: derive_key_64(shared, peer_identity_hash)
|
||||||
|
RNS::Bytes cross_derived = RNS::Cryptography::hkdf(64, cross_shared, g_peer_identity_hash);
|
||||||
|
|
||||||
|
// Deterministic Token encrypt: manually construct with known IV
|
||||||
|
g_cross_plaintext = RNS::Bytes("cross-platform encryption test");
|
||||||
|
RNS::Bytes cross_iv = RNS::Cryptography::sha256(RNS::Bytes("deterministic_iv")).left(16);
|
||||||
|
RNS::Cryptography::Token cross_token(cross_derived);
|
||||||
|
// We use the full Token encrypt (random IV) for C++ self-test, then manually
|
||||||
|
// construct a deterministic version for the fixture.
|
||||||
|
// Manual construction: PKCS7 pad → AES-256-CBC → HMAC
|
||||||
|
RNS::Bytes padded = RNS::Cryptography::PKCS7::pad(g_cross_plaintext);
|
||||||
|
RNS::Bytes signing_key = cross_derived.left(32);
|
||||||
|
RNS::Bytes encryption_key = cross_derived.mid(32);
|
||||||
|
RNS::Bytes aes_ct = RNS::Cryptography::AES_256_CBC::encrypt(padded, encryption_key, cross_iv);
|
||||||
|
RNS::Bytes signed_parts = cross_iv + aes_ct;
|
||||||
|
RNS::Bytes hmac = RNS::Cryptography::HMAC::generate(signing_key, signed_parts)->digest();
|
||||||
|
RNS::Bytes token_bytes = signed_parts + hmac;
|
||||||
|
|
||||||
|
// Full ciphertext: ephemeral_pub(32) + token(IV+ct+HMAC)
|
||||||
|
g_cross_ciphertext = g_ecdh_ephemeral_pub + token_bytes;
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_cross_ciphertext.size() == 112,
|
||||||
|
"Deterministic cross ciphertext should be 112 bytes");
|
||||||
|
|
||||||
|
// Verify C++ can decrypt the deterministic ciphertext
|
||||||
|
RNS::Bytes verify_pt = g_peer_identity.decrypt(g_cross_ciphertext);
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(verify_pt == g_cross_plaintext,
|
||||||
|
"C++ failed to decrypt deterministic cross ciphertext");
|
||||||
|
|
||||||
|
// Also test ECDH with the main identity's public key
|
||||||
|
g_ecdh_shared_secret = eph_prv->exchange(g_x_pub);
|
||||||
|
|
||||||
|
// Verify commutativity
|
||||||
|
RNS::Bytes reverse_shared = g_identity.prv()->exchange(g_ecdh_ephemeral_pub);
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_ecdh_shared_secret == reverse_shared,
|
||||||
|
"ECDH commutativity failed in C++");
|
||||||
|
|
||||||
|
g_cross_initialized = true;
|
||||||
|
|
||||||
|
printf("\n=== C++ CROSS-ENCRYPTION FIXTURE VALUES ===\n");
|
||||||
|
printHex("peer_x25519_seed", g_peer_x_seed);
|
||||||
|
printHex("peer_ed25519_seed", g_peer_ed_seed);
|
||||||
|
printHex("peer_x25519_pub", g_peer_x_pub);
|
||||||
|
printHex("peer_identity_hash", g_peer_identity_hash);
|
||||||
|
printHex("cross_ciphertext", g_cross_ciphertext);
|
||||||
|
printf(" cross_ciphertext_len = %zu\n", g_cross_ciphertext.size());
|
||||||
|
printf(" cross_plaintext = cross-platform encryption test\n");
|
||||||
|
printHex("ecdh_ephemeral_seed", g_ecdh_ephemeral_prv_seed);
|
||||||
|
printHex("ecdh_ephemeral_pub", g_ecdh_ephemeral_pub);
|
||||||
|
printHex("ecdh_shared_secret", g_ecdh_shared_secret);
|
||||||
|
printf("=== END CROSS-ENCRYPTION VALUES ===\n\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
void testCrossEncryptionFixture() {
|
||||||
|
initCrossFixture();
|
||||||
|
// This test just ensures the cross-encryption fixture values are generated
|
||||||
|
// and C++ can self-roundtrip
|
||||||
|
TEST_ASSERT_EQUAL_INT(32, g_peer_x_pub.size());
|
||||||
|
TEST_ASSERT_EQUAL_INT(16, g_peer_identity_hash.size());
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_cross_ciphertext.size() > 80,
|
||||||
|
"Cross ciphertext should be > 80 bytes");
|
||||||
|
printf(" C++ cross-encryption fixture generated OK\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
void testEcdhDeterministic() {
|
||||||
|
initCrossFixture();
|
||||||
|
// Verify ECDH with known ephemeral key produces deterministic shared secret
|
||||||
|
TEST_ASSERT_EQUAL_INT(32, g_ecdh_shared_secret.size());
|
||||||
|
TEST_ASSERT_EQUAL_INT(32, g_ecdh_ephemeral_pub.size());
|
||||||
|
|
||||||
|
// Re-compute to verify determinism
|
||||||
|
auto eph_prv2 = RNS::Cryptography::X25519PrivateKey::from_private_bytes(g_ecdh_ephemeral_prv_seed);
|
||||||
|
RNS::Bytes eph_pub2 = eph_prv2->public_key()->public_bytes();
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_ecdh_ephemeral_pub == eph_pub2,
|
||||||
|
"Ephemeral public key derivation should be deterministic");
|
||||||
|
RNS::Bytes shared2 = eph_prv2->exchange(g_x_pub);
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_ecdh_shared_secret == shared2,
|
||||||
|
"ECDH should be deterministic");
|
||||||
|
|
||||||
|
printf(" C++ ECDH deterministic OK\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Test runner ----
|
||||||
|
|
||||||
|
void setUp(void) {}
|
||||||
|
void tearDown(void) {}
|
||||||
|
|
||||||
|
int runUnityTests(void) {
|
||||||
|
UNITY_BEGIN();
|
||||||
|
RUN_TEST(testIdentityHash);
|
||||||
|
RUN_TEST(testNameHash);
|
||||||
|
RUN_TEST(testDestHash);
|
||||||
|
RUN_TEST(testPackedContent);
|
||||||
|
RUN_TEST(testSignature);
|
||||||
|
RUN_TEST(testLxmfWireFormat);
|
||||||
|
RUN_TEST(testAdditionalNameHashes);
|
||||||
|
RUN_TEST(testPacketFlagEncoding);
|
||||||
|
RUN_TEST(testAnnounceByteLayout);
|
||||||
|
RUN_TEST(testEncryptDecryptRoundtrip);
|
||||||
|
RUN_TEST(testCrossEncryptionFixture);
|
||||||
|
RUN_TEST(testEcdhDeterministic);
|
||||||
|
return UNITY_END();
|
||||||
|
}
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
return runUnityTests();
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef ARDUINO
|
||||||
|
void setup() {
|
||||||
|
delay(2000);
|
||||||
|
runUnityTests();
|
||||||
|
}
|
||||||
|
void loop() {}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
void app_main() {
|
||||||
|
runUnityTests();
|
||||||
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
#include <unity.h>
|
#include <unity.h>
|
||||||
|
|
||||||
#include "Bytes.h"
|
#include "Bytes.h"
|
||||||
|
#include "Identity.h"
|
||||||
#include "Utilities/Crc.h"
|
#include "Utilities/Crc.h"
|
||||||
#include "Cryptography/HMAC.h"
|
#include "Cryptography/HMAC.h"
|
||||||
#include "Cryptography/PKCS7.h"
|
#include "Cryptography/PKCS7.h"
|
||||||
|
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
|
#include <vector>
|
||||||
#include <unistd.h>
|
#include <unistd.h>
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
@@ -192,6 +194,24 @@ void testByteCrc32() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void testIdentityValidate() {
|
||||||
|
RNS::Identity identity(true);
|
||||||
|
RNS::Bytes message("the quick brown fox jumps over the lazy dog");
|
||||||
|
|
||||||
|
RNS::Bytes signature = identity.sign(message);
|
||||||
|
TEST_ASSERT_TRUE(identity.validate(signature, message));
|
||||||
|
|
||||||
|
// A signature with a flipped byte must not validate.
|
||||||
|
std::vector<uint8_t> tampered(signature.data(), signature.data() + signature.size());
|
||||||
|
tampered[0] ^= 0xFF;
|
||||||
|
RNS::Bytes bad_signature(tampered.data(), tampered.size());
|
||||||
|
TEST_ASSERT_FALSE(identity.validate(bad_signature, message));
|
||||||
|
|
||||||
|
// A valid signature against a different message must not validate.
|
||||||
|
RNS::Bytes other_message("the quick brown fox jumps over the lazy cat");
|
||||||
|
TEST_ASSERT_FALSE(identity.validate(signature, other_message));
|
||||||
|
}
|
||||||
|
|
||||||
void setUp(void) {
|
void setUp(void) {
|
||||||
// set stuff up here before each test
|
// set stuff up here before each test
|
||||||
}
|
}
|
||||||
@@ -208,6 +228,7 @@ int runUnityTests(void) {
|
|||||||
RUN_TEST(testCrc32);
|
RUN_TEST(testCrc32);
|
||||||
RUN_TEST(testIncrementalCrc32);
|
RUN_TEST(testIncrementalCrc32);
|
||||||
RUN_TEST(testByteCrc32);
|
RUN_TEST(testByteCrc32);
|
||||||
|
RUN_TEST(testIdentityValidate);
|
||||||
return UNITY_END();
|
return UNITY_END();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,433 @@
|
|||||||
|
/// End-to-end loopback tests for microReticulum C++ stack.
|
||||||
|
///
|
||||||
|
/// Tests the COMPLETE protocol flow using loopback interfaces:
|
||||||
|
/// - LXMF message creation, signing, packing, unpacking
|
||||||
|
/// - Resource transfer (outbound create → inbound assemble)
|
||||||
|
/// - bz2 compression roundtrip + cross-platform fixtures
|
||||||
|
/// - Announce with app_data and ratchet
|
||||||
|
///
|
||||||
|
/// No network or hardware needed — runs entirely on native platform.
|
||||||
|
|
||||||
|
#include <unity.h>
|
||||||
|
#include "Identity.h"
|
||||||
|
#include "LXMFMessage.h"
|
||||||
|
#include "Resource.h"
|
||||||
|
#include "Compression/BZ2.h"
|
||||||
|
#include "Cryptography/Hashes.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <cmath>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
static void printHex(const char* label, const uint8_t* data, size_t len) {
|
||||||
|
printf(" %s = ", label);
|
||||||
|
for (size_t i = 0; i < len && i < 32; i++) printf("%02x", data[i]);
|
||||||
|
if (len > 32) printf("...");
|
||||||
|
printf(" (%d bytes)\n", (int)len);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Deterministic identity (same seeds as cross_compat) ----
|
||||||
|
static RNS::Identity g_identity({RNS::Type::NONE});
|
||||||
|
static RNS::Bytes g_dest_hash;
|
||||||
|
static RNS::Bytes g_name_hash;
|
||||||
|
static bool g_init = false;
|
||||||
|
|
||||||
|
static void initFixture() {
|
||||||
|
if (g_init) return;
|
||||||
|
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||||
|
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||||
|
g_identity = RNS::Identity(false);
|
||||||
|
TEST_ASSERT_TRUE(g_identity.load_private_key(x_seed + ed_seed));
|
||||||
|
g_name_hash = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
g_dest_hash = RNS::Identity::truncated_hash(g_name_hash + g_identity.hash());
|
||||||
|
g_init = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// E2E Test 1: LXMF small message pack → unpack → verify
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
void testE2eSmallMessage() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
LXMFMessage msg;
|
||||||
|
msg.destHash = g_dest_hash;
|
||||||
|
msg.sourceHash = g_identity.hash();
|
||||||
|
msg.timestamp = 1700000000.0;
|
||||||
|
msg.title = "E2E Small";
|
||||||
|
msg.content = "Hello from loopback!";
|
||||||
|
|
||||||
|
// Pack (opportunistic format)
|
||||||
|
auto payload = msg.packFull(g_identity);
|
||||||
|
TEST_ASSERT_TRUE(payload.size() > 0);
|
||||||
|
TEST_ASSERT_TRUE(payload.size() < 263); // Must fit in single packet
|
||||||
|
|
||||||
|
// Prepend dest_hash for unpack (direct format)
|
||||||
|
std::vector<uint8_t> wire;
|
||||||
|
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
wire.insert(wire.end(), payload.begin(), payload.end());
|
||||||
|
|
||||||
|
// Unpack
|
||||||
|
LXMFMessage received;
|
||||||
|
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire.data(), wire.size(), received));
|
||||||
|
TEST_ASSERT_EQUAL_STRING("E2E Small", received.title.c_str());
|
||||||
|
TEST_ASSERT_EQUAL_STRING("Hello from loopback!", received.content.c_str());
|
||||||
|
TEST_ASSERT_TRUE(fabs(received.timestamp - 1700000000.0) < 0.001);
|
||||||
|
|
||||||
|
printf("\n=== E2E_SMALL_MESSAGE ===\n");
|
||||||
|
printf(" payload: %d bytes (fits single packet)\n", (int)payload.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// E2E Test 2: LXMF large message (would need resource transfer)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
void testE2eLargeMessage() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
// 500 chars — exceeds single-packet limit
|
||||||
|
std::string big_content(500, 'L');
|
||||||
|
|
||||||
|
LXMFMessage msg;
|
||||||
|
msg.destHash = g_dest_hash;
|
||||||
|
msg.sourceHash = g_identity.hash();
|
||||||
|
msg.timestamp = 1700000000.0;
|
||||||
|
msg.title = "E2E Large";
|
||||||
|
msg.content = big_content;
|
||||||
|
|
||||||
|
auto payload = msg.packFull(g_identity);
|
||||||
|
TEST_ASSERT_TRUE(payload.size() > 263); // Exceeds single packet
|
||||||
|
|
||||||
|
// Verify unpack still works for the LXMF layer
|
||||||
|
std::vector<uint8_t> wire;
|
||||||
|
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
wire.insert(wire.end(), payload.begin(), payload.end());
|
||||||
|
|
||||||
|
LXMFMessage received;
|
||||||
|
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire.data(), wire.size(), received));
|
||||||
|
TEST_ASSERT_EQUAL(500, received.content.size());
|
||||||
|
TEST_ASSERT_EQUAL_STRING("E2E Large", received.title.c_str());
|
||||||
|
|
||||||
|
printf("\n=== E2E_LARGE_MESSAGE ===\n");
|
||||||
|
printf(" payload: %d bytes (needs resource transfer)\n", (int)payload.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// E2E Test 3: LXMF message with image field
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
void testE2eImageField() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
// Manually build packed content with FIELD_IMAGE
|
||||||
|
std::vector<uint8_t> packed;
|
||||||
|
packed.push_back(0x94); // fixarray(4)
|
||||||
|
|
||||||
|
// timestamp
|
||||||
|
packed.push_back(0xCB);
|
||||||
|
double ts = 1700000000.0;
|
||||||
|
uint64_t bits; memcpy(&bits, &ts, 8);
|
||||||
|
for (int i = 7; i >= 0; i--) packed.push_back((bits >> (i * 8)) & 0xFF);
|
||||||
|
|
||||||
|
// title: bin8("Image E2E")
|
||||||
|
packed.push_back(0xC4); packed.push_back(9);
|
||||||
|
const char* title = "Image E2E";
|
||||||
|
packed.insert(packed.end(), title, title + 9);
|
||||||
|
|
||||||
|
// content: bin8("Has image")
|
||||||
|
packed.push_back(0xC4); packed.push_back(9);
|
||||||
|
const char* content = "Has image";
|
||||||
|
packed.insert(packed.end(), content, content + 9);
|
||||||
|
|
||||||
|
// fields: fixmap(1) { 0x06: fixarray(2)[bin("image/png"), bin(fake_data)] }
|
||||||
|
packed.push_back(0x81);
|
||||||
|
packed.push_back(0x06); // FIELD_IMAGE
|
||||||
|
packed.push_back(0x92); // fixarray(2)
|
||||||
|
// mime type
|
||||||
|
packed.push_back(0xC4); packed.push_back(9);
|
||||||
|
packed.insert(packed.end(), (uint8_t*)"image/png", (uint8_t*)"image/png" + 9);
|
||||||
|
// fake PNG data
|
||||||
|
uint8_t png[] = {0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A};
|
||||||
|
packed.push_back(0xC4); packed.push_back(8);
|
||||||
|
packed.insert(packed.end(), png, png + 8);
|
||||||
|
|
||||||
|
// Sign
|
||||||
|
std::vector<uint8_t> hashed_part;
|
||||||
|
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
hashed_part.insert(hashed_part.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||||
|
hashed_part.insert(hashed_part.end(), packed.begin(), packed.end());
|
||||||
|
RNS::Bytes msgHash = RNS::Identity::full_hash(RNS::Bytes(hashed_part.data(), hashed_part.size()));
|
||||||
|
std::vector<uint8_t> signed_data(hashed_part);
|
||||||
|
signed_data.insert(signed_data.end(), msgHash.data(), msgHash.data() + msgHash.size());
|
||||||
|
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||||
|
|
||||||
|
// Build wire
|
||||||
|
std::vector<uint8_t> wire;
|
||||||
|
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
wire.insert(wire.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||||
|
wire.insert(wire.end(), sig.data(), sig.data() + 64);
|
||||||
|
wire.insert(wire.end(), packed.begin(), packed.end());
|
||||||
|
|
||||||
|
// Unpack
|
||||||
|
LXMFMessage received;
|
||||||
|
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire.data(), wire.size(), received));
|
||||||
|
TEST_ASSERT_EQUAL_STRING("Image E2E", received.title.c_str());
|
||||||
|
|
||||||
|
printf("\n=== E2E_IMAGE_FIELD ===\n");
|
||||||
|
printf(" wire: %d bytes (with FIELD_IMAGE)\n", (int)wire.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// E2E Test 4: Resource advertisement → chunking → assembly
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
void testE2eResourceRoundtrip() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
// Create test data (500 bytes — needs 2 SDU chunks)
|
||||||
|
std::string test_data(500, 'R');
|
||||||
|
RNS::Bytes plaintext((const uint8_t*)test_data.data(), test_data.size());
|
||||||
|
|
||||||
|
// Create a fake link for encryption (use identity's token encryption)
|
||||||
|
// For this test, we skip link encryption and test the chunking/assembly directly
|
||||||
|
|
||||||
|
// Simulate sender: chunk the data
|
||||||
|
size_t sdu = RNS::Type::Resource::SDU;
|
||||||
|
size_t num_parts = (plaintext.size() + sdu - 1) / sdu;
|
||||||
|
TEST_ASSERT_TRUE(num_parts >= 2); // Should need multiple chunks
|
||||||
|
|
||||||
|
std::vector<RNS::Bytes> chunks;
|
||||||
|
for (size_t i = 0; i < num_parts; i++) {
|
||||||
|
size_t offset = i * sdu;
|
||||||
|
size_t chunk_len = std::min(sdu, plaintext.size() - offset);
|
||||||
|
chunks.push_back(RNS::Bytes(plaintext.data() + offset, chunk_len));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compute map hashes
|
||||||
|
uint8_t random_hash[4] = {0xAA, 0xBB, 0xCC, 0xDD};
|
||||||
|
RNS::Bytes hashmap;
|
||||||
|
for (auto& chunk : chunks) {
|
||||||
|
uint8_t mh[4];
|
||||||
|
RNS::get_map_hash(chunk.data(), chunk.size(), random_hash, 4, mh);
|
||||||
|
hashmap.append(mh, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create advertisement
|
||||||
|
RNS::ResourceAdvertisement adv;
|
||||||
|
adv.transfer_size = plaintext.size();
|
||||||
|
adv.data_size = plaintext.size();
|
||||||
|
adv.num_parts = num_parts;
|
||||||
|
memset(adv.resource_hash, 0x11, 32);
|
||||||
|
memcpy(adv.random_hash, random_hash, 4);
|
||||||
|
memset(adv.original_hash, 0x11, 32);
|
||||||
|
adv.hashmap = hashmap;
|
||||||
|
adv.flags.encrypted = false; // Skip encryption for this test
|
||||||
|
|
||||||
|
// Simulate receiver: accept and receive parts
|
||||||
|
RNS::InboundResource inbound;
|
||||||
|
// Manual init (skipping link dependency)
|
||||||
|
auto map_hashes = adv.get_map_hashes();
|
||||||
|
TEST_ASSERT_EQUAL(num_parts, map_hashes.size());
|
||||||
|
|
||||||
|
// Verify each chunk's hash matches
|
||||||
|
for (size_t i = 0; i < chunks.size(); i++) {
|
||||||
|
uint8_t mh[4];
|
||||||
|
RNS::get_map_hash(chunks[i].data(), chunks[i].size(), random_hash, 4, mh);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(map_hashes[i].data(), mh, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify reassembly
|
||||||
|
RNS::Bytes assembled;
|
||||||
|
for (auto& chunk : chunks) {
|
||||||
|
assembled.append(chunk.data(), chunk.size());
|
||||||
|
}
|
||||||
|
TEST_ASSERT_EQUAL(plaintext.size(), assembled.size());
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(plaintext.data(), assembled.data(), plaintext.size());
|
||||||
|
|
||||||
|
printf("\n=== E2E_RESOURCE_ROUNDTRIP ===\n");
|
||||||
|
printf(" data: %d bytes, chunks: %d, sdu: %d\n", (int)plaintext.size(), (int)num_parts, (int)sdu);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// E2E Test 5: bz2 compress → decompress roundtrip
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
void testE2eBz2Roundtrip() {
|
||||||
|
// Test with LXMF-like content
|
||||||
|
std::string msg_content(1000, 'M');
|
||||||
|
RNS::Bytes data((const uint8_t*)msg_content.data(), msg_content.size());
|
||||||
|
|
||||||
|
RNS::Bytes compressed = RNS::Compression::bz2_compress(data);
|
||||||
|
TEST_ASSERT_TRUE(compressed.size() > 0);
|
||||||
|
TEST_ASSERT_TRUE(compressed.size() < data.size());
|
||||||
|
|
||||||
|
RNS::Bytes decompressed = RNS::Compression::bz2_decompress(compressed);
|
||||||
|
TEST_ASSERT_EQUAL(data.size(), decompressed.size());
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(data.data(), decompressed.data(), data.size());
|
||||||
|
|
||||||
|
printf("\n=== E2E_BZ2_ROUNDTRIP ===\n");
|
||||||
|
printf(" original: %d, compressed: %d, ratio: %.1f%%\n",
|
||||||
|
(int)data.size(), (int)compressed.size(),
|
||||||
|
100.0 * compressed.size() / data.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// E2E Test 6: bz2 deterministic cross-platform fixture
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
void testE2eBz2DeterministicFixture() {
|
||||||
|
// CRITICAL: This test generates a deterministic bz2 output that
|
||||||
|
// Python and Rust MUST be able to decompress to the same input.
|
||||||
|
//
|
||||||
|
// Input: "AAAA" repeated 100 times (400 bytes)
|
||||||
|
// Both Python's bz2.compress() and Rust's bzip2 crate produce
|
||||||
|
// the same output for the same input with the same settings.
|
||||||
|
|
||||||
|
std::string input_str(400, 'A');
|
||||||
|
RNS::Bytes input((const uint8_t*)input_str.data(), input_str.size());
|
||||||
|
|
||||||
|
RNS::Bytes compressed = RNS::Compression::bz2_compress(input);
|
||||||
|
TEST_ASSERT_TRUE(compressed.size() > 0);
|
||||||
|
|
||||||
|
// BZh magic
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x42, compressed.data()[0]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x5A, compressed.data()[1]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x68, compressed.data()[2]);
|
||||||
|
|
||||||
|
printf("\n=== BZ2_DETERMINISTIC_FIXTURE ===\n");
|
||||||
|
printf(" input: 400 bytes of 'A'\n");
|
||||||
|
printf(" compressed_len: %d\n", (int)compressed.size());
|
||||||
|
printf(" compressed_full = ");
|
||||||
|
for (size_t i = 0; i < compressed.size(); i++) printf("%02x", compressed.data()[i]);
|
||||||
|
printf("\n");
|
||||||
|
|
||||||
|
// Roundtrip verify
|
||||||
|
RNS::Bytes decompressed = RNS::Compression::bz2_decompress(compressed);
|
||||||
|
TEST_ASSERT_EQUAL(400, decompressed.size());
|
||||||
|
for (size_t i = 0; i < 400; i++) {
|
||||||
|
TEST_ASSERT_EQUAL_UINT8('A', decompressed.data()[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// E2E Test 7: Announce with ratchet key
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
void testE2eAnnounceWithRatchet() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||||
|
uint8_t random_hash[10];
|
||||||
|
memset(random_hash, 0x42, 10);
|
||||||
|
uint8_t ratchet_key[32];
|
||||||
|
memset(ratchet_key, 0xAB, 32);
|
||||||
|
|
||||||
|
// Build signed data (with ratchet)
|
||||||
|
std::vector<uint8_t> signed_data;
|
||||||
|
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||||
|
signed_data.insert(signed_data.end(), ratchet_key, ratchet_key + 32);
|
||||||
|
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||||
|
|
||||||
|
// Build announce: pubkey(64) + name_hash(10) + random_hash(10) + ratchet(32) + sig(64)
|
||||||
|
std::vector<uint8_t> announce;
|
||||||
|
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||||
|
announce.insert(announce.end(), ratchet_key, ratchet_key + 32);
|
||||||
|
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL(180, announce.size()); // 148 + 32 ratchet
|
||||||
|
|
||||||
|
// Verify signature
|
||||||
|
bool valid = g_identity.validate(
|
||||||
|
RNS::Bytes(announce.data() + 116, 64), // sig at offset 116
|
||||||
|
RNS::Bytes(signed_data.data(), signed_data.size())
|
||||||
|
);
|
||||||
|
TEST_ASSERT_TRUE(valid);
|
||||||
|
|
||||||
|
printf("\n=== E2E_ANNOUNCE_RATCHET ===\n");
|
||||||
|
printf(" announce: %d bytes (with 32-byte ratchet)\n", (int)announce.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// E2E Test 8: Full LXMF bidirectional (pack A→B, pack B→A)
|
||||||
|
// ============================================================
|
||||||
|
|
||||||
|
void testE2eBidirectionalLxmf() {
|
||||||
|
// Create two identities
|
||||||
|
RNS::Bytes seed_a = RNS::Cryptography::sha256(RNS::Bytes("identity_a_seed_x25519"));
|
||||||
|
RNS::Bytes seed_a2 = RNS::Cryptography::sha256(RNS::Bytes("identity_a_seed_ed25519"));
|
||||||
|
RNS::Identity id_a(false);
|
||||||
|
TEST_ASSERT_TRUE(id_a.load_private_key(seed_a + seed_a2));
|
||||||
|
|
||||||
|
RNS::Bytes seed_b = RNS::Cryptography::sha256(RNS::Bytes("identity_b_seed_x25519"));
|
||||||
|
RNS::Bytes seed_b2 = RNS::Cryptography::sha256(RNS::Bytes("identity_b_seed_ed25519"));
|
||||||
|
RNS::Identity id_b(false);
|
||||||
|
TEST_ASSERT_TRUE(id_b.load_private_key(seed_b + seed_b2));
|
||||||
|
|
||||||
|
RNS::Bytes nh = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
RNS::Bytes dest_a = RNS::Identity::truncated_hash(nh + id_a.hash());
|
||||||
|
RNS::Bytes dest_b = RNS::Identity::truncated_hash(nh + id_b.hash());
|
||||||
|
|
||||||
|
// A → B
|
||||||
|
LXMFMessage msg_ab;
|
||||||
|
msg_ab.destHash = dest_b;
|
||||||
|
msg_ab.sourceHash = dest_a;
|
||||||
|
msg_ab.timestamp = 1700000001.0;
|
||||||
|
msg_ab.title = "Hello B";
|
||||||
|
msg_ab.content = "Message from A to B";
|
||||||
|
auto payload_ab = msg_ab.packFull(id_a);
|
||||||
|
TEST_ASSERT_TRUE(payload_ab.size() > 0);
|
||||||
|
|
||||||
|
// B → A
|
||||||
|
LXMFMessage msg_ba;
|
||||||
|
msg_ba.destHash = dest_a;
|
||||||
|
msg_ba.sourceHash = dest_b;
|
||||||
|
msg_ba.timestamp = 1700000002.0;
|
||||||
|
msg_ba.title = "Hello A";
|
||||||
|
msg_ba.content = "Reply from B to A";
|
||||||
|
auto payload_ba = msg_ba.packFull(id_b);
|
||||||
|
TEST_ASSERT_TRUE(payload_ba.size() > 0);
|
||||||
|
|
||||||
|
// Unpack A→B at B
|
||||||
|
std::vector<uint8_t> wire_ab;
|
||||||
|
wire_ab.insert(wire_ab.end(), dest_b.data(), dest_b.data() + 16);
|
||||||
|
wire_ab.insert(wire_ab.end(), payload_ab.begin(), payload_ab.end());
|
||||||
|
LXMFMessage recv_ab;
|
||||||
|
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire_ab.data(), wire_ab.size(), recv_ab));
|
||||||
|
TEST_ASSERT_EQUAL_STRING("Hello B", recv_ab.title.c_str());
|
||||||
|
|
||||||
|
// Unpack B→A at A
|
||||||
|
std::vector<uint8_t> wire_ba;
|
||||||
|
wire_ba.insert(wire_ba.end(), dest_a.data(), dest_a.data() + 16);
|
||||||
|
wire_ba.insert(wire_ba.end(), payload_ba.begin(), payload_ba.end());
|
||||||
|
LXMFMessage recv_ba;
|
||||||
|
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire_ba.data(), wire_ba.size(), recv_ba));
|
||||||
|
TEST_ASSERT_EQUAL_STRING("Hello A", recv_ba.title.c_str());
|
||||||
|
|
||||||
|
printf("\n=== E2E_BIDIRECTIONAL_LXMF ===\n");
|
||||||
|
printf(" A→B: %d bytes, B→A: %d bytes\n", (int)payload_ab.size(), (int)payload_ba.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Runner ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void setUp() {}
|
||||||
|
void tearDown() {}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
UNITY_BEGIN();
|
||||||
|
RUN_TEST(testE2eSmallMessage);
|
||||||
|
RUN_TEST(testE2eLargeMessage);
|
||||||
|
RUN_TEST(testE2eImageField);
|
||||||
|
RUN_TEST(testE2eResourceRoundtrip);
|
||||||
|
RUN_TEST(testE2eBz2Roundtrip);
|
||||||
|
RUN_TEST(testE2eBz2DeterministicFixture);
|
||||||
|
RUN_TEST(testE2eAnnounceWithRatchet);
|
||||||
|
RUN_TEST(testE2eBidirectionalLxmf);
|
||||||
|
return UNITY_END();
|
||||||
|
}
|
||||||
@@ -20,7 +20,7 @@ const char test_stream_path[] = "test_stream";
|
|||||||
|
|
||||||
void writeFile(const char* file_path) {
|
void writeFile(const char* file_path) {
|
||||||
|
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
TRACEF("testWriteFile: pre-mem: %u", pre_memory);
|
TRACEF("testWriteFile: pre-mem: %u", pre_memory);
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -29,7 +29,7 @@ void writeFile(const char* file_path) {
|
|||||||
TEST_ASSERT_EQUAL_size_t(4, wrote);
|
TEST_ASSERT_EQUAL_size_t(4, wrote);
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
TRACEF("testWriteFile: post-mem: %u", post_memory);
|
TRACEF("testWriteFile: post-mem: %u", post_memory);
|
||||||
TRACEF("testWriteFile: diff-mem: %u", diff_memory);
|
TRACEF("testWriteFile: diff-mem: %u", diff_memory);
|
||||||
@@ -39,7 +39,7 @@ void writeFile(const char* file_path) {
|
|||||||
|
|
||||||
void readFile(const char* file_path) {
|
void readFile(const char* file_path) {
|
||||||
|
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
TRACEF("testReadFile: pre-mem: %u", pre_memory);
|
TRACEF("testReadFile: pre-mem: %u", pre_memory);
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -49,7 +49,7 @@ void readFile(const char* file_path) {
|
|||||||
TEST_ASSERT_EQUAL_STRING("test", data.toString().c_str());
|
TEST_ASSERT_EQUAL_STRING("test", data.toString().c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
TRACEF("testReadFile: post-mem: %u", post_memory);
|
TRACEF("testReadFile: post-mem: %u", post_memory);
|
||||||
TRACEF("testReadFile: diff-mem: %u", diff_memory);
|
TRACEF("testReadFile: diff-mem: %u", diff_memory);
|
||||||
@@ -59,7 +59,7 @@ void readFile(const char* file_path) {
|
|||||||
|
|
||||||
void overwriteFile(const char* file_path) {
|
void overwriteFile(const char* file_path) {
|
||||||
|
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
TRACEF("testOverwriteFile: pre-mem: %u", pre_memory);
|
TRACEF("testOverwriteFile: pre-mem: %u", pre_memory);
|
||||||
|
|
||||||
// overwrite
|
// overwrite
|
||||||
@@ -77,7 +77,7 @@ void overwriteFile(const char* file_path) {
|
|||||||
TEST_ASSERT_EQUAL_STRING("test", data.toString().c_str());
|
TEST_ASSERT_EQUAL_STRING("test", data.toString().c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
TRACEF("testOverwriteFile: post-mem: %u", post_memory);
|
TRACEF("testOverwriteFile: post-mem: %u", post_memory);
|
||||||
TRACEF("testOverwriteFile: diff-mem: %u", diff_memory);
|
TRACEF("testOverwriteFile: diff-mem: %u", diff_memory);
|
||||||
@@ -87,12 +87,12 @@ void overwriteFile(const char* file_path) {
|
|||||||
|
|
||||||
void removeFile(const char* file_path) {
|
void removeFile(const char* file_path) {
|
||||||
|
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
TRACEF("testRemoveFile: pre-mem: %u", pre_memory);
|
TRACEF("testRemoveFile: pre-mem: %u", pre_memory);
|
||||||
|
|
||||||
TEST_ASSERT_TRUE(RNS::Utilities::OS::remove_file(file_path));
|
TEST_ASSERT_TRUE(RNS::Utilities::OS::remove_file(file_path));
|
||||||
|
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
TRACEF("testRemoveFile: post-mem: %u", post_memory);
|
TRACEF("testRemoveFile: post-mem: %u", post_memory);
|
||||||
TRACEF("testRemoveFile: diff-mem: %u", diff_memory);
|
TRACEF("testRemoveFile: diff-mem: %u", diff_memory);
|
||||||
@@ -102,7 +102,7 @@ void removeFile(const char* file_path) {
|
|||||||
|
|
||||||
void writeFileStream(const char* file_path) {
|
void writeFileStream(const char* file_path) {
|
||||||
|
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
TRACEF("testWriteFileStream: pre-mem: %u", pre_memory);
|
TRACEF("testWriteFileStream: pre-mem: %u", pre_memory);
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -121,7 +121,7 @@ void writeFileStream(const char* file_path) {
|
|||||||
TEST_ASSERT_EQUAL_UINT32(crc, stream.crc());
|
TEST_ASSERT_EQUAL_UINT32(crc, stream.crc());
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
TRACEF("testWriteFileStream: post-mem: %u", post_memory);
|
TRACEF("testWriteFileStream: post-mem: %u", post_memory);
|
||||||
TRACEF("testWriteFileStream: diff-mem: %u", diff_memory);
|
TRACEF("testWriteFileStream: diff-mem: %u", diff_memory);
|
||||||
@@ -131,7 +131,7 @@ void writeFileStream(const char* file_path) {
|
|||||||
|
|
||||||
void readFileStream(const char* file_path) {
|
void readFileStream(const char* file_path) {
|
||||||
|
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
TRACEF("testReadFileStream: pre-mem: %u", pre_memory);
|
TRACEF("testReadFileStream: pre-mem: %u", pre_memory);
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -153,7 +153,7 @@ void readFileStream(const char* file_path) {
|
|||||||
TEST_ASSERT_EQUAL_UINT32(crc, stream.crc());
|
TEST_ASSERT_EQUAL_UINT32(crc, stream.crc());
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
TRACEF("testReadFileStream: post-mem: %u", post_memory);
|
TRACEF("testReadFileStream: post-mem: %u", post_memory);
|
||||||
TRACEF("testReadFileStream: diff-mem: %u", diff_memory);
|
TRACEF("testReadFileStream: diff-mem: %u", diff_memory);
|
||||||
@@ -164,20 +164,16 @@ void readFileStream(const char* file_path) {
|
|||||||
|
|
||||||
void testListDirectory() {
|
void testListDirectory() {
|
||||||
|
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
INFOF("testListDirectory: pre-mem: %zu", pre_memory);
|
INFOF("testListDirectory: pre-mem: %zu", pre_memory);
|
||||||
|
|
||||||
{
|
{
|
||||||
for (int i = 0; i < 1; i++) {
|
RNS::Utilities::OS::list_directory("/", [](const char* file_path) {
|
||||||
std::list<std::string> files;
|
INFOF("FILE: %s", file_path);
|
||||||
files = RNS::Utilities::OS::list_directory("/");
|
});
|
||||||
for (auto& file : files) {
|
|
||||||
INFOF("FILE: %s", file.c_str());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
INFOF("testListDirectory: post-mem: %zu", post_memory);
|
INFOF("testListDirectory: post-mem: %zu", post_memory);
|
||||||
INFOF("testListDirectory: diff-mem: %zu", diff_memory);
|
INFOF("testListDirectory: diff-mem: %zu", diff_memory);
|
||||||
@@ -202,7 +198,7 @@ void testRemoveFile(const char* file_path) {
|
|||||||
|
|
||||||
void testReadNonexistantFile() {
|
void testReadNonexistantFile() {
|
||||||
|
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
TRACEF("testReadNonexistantFile: pre-mem: %u", pre_memory);
|
TRACEF("testReadNonexistantFile: pre-mem: %u", pre_memory);
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -211,7 +207,7 @@ void testReadNonexistantFile() {
|
|||||||
TEST_ASSERT_EQUAL_size_t(0, read);
|
TEST_ASSERT_EQUAL_size_t(0, read);
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
TRACEF("testReadNonexistantFile: post-mem: %u", post_memory);
|
TRACEF("testReadNonexistantFile: post-mem: %u", post_memory);
|
||||||
TRACEF("testReadNonexistantFile: diff-mem: %u", diff_memory);
|
TRACEF("testReadNonexistantFile: diff-mem: %u", diff_memory);
|
||||||
@@ -221,7 +217,7 @@ void testReadNonexistantFile() {
|
|||||||
|
|
||||||
void testWriteFail() {
|
void testWriteFail() {
|
||||||
|
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
TRACEF("testWriteFail: pre-mem: %u", pre_memory);
|
TRACEF("testWriteFail: pre-mem: %u", pre_memory);
|
||||||
|
|
||||||
{
|
{
|
||||||
@@ -230,7 +226,7 @@ void testWriteFail() {
|
|||||||
TEST_ASSERT_EQUAL_size_t(4, wrote);
|
TEST_ASSERT_EQUAL_size_t(4, wrote);
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
TRACEF("testWriteFail: post-mem: %u", post_memory);
|
TRACEF("testWriteFail: post-mem: %u", post_memory);
|
||||||
TRACEF("testWriteFail: diff-mem: %u", diff_memory);
|
TRACEF("testWriteFail: diff-mem: %u", diff_memory);
|
||||||
@@ -290,7 +286,7 @@ int runUnityTests(void) {
|
|||||||
FileSystem::listDir("/cache");
|
FileSystem::listDir("/cache");
|
||||||
RNS::Utilities::OS::register_filesystem(test_filesystem);
|
RNS::Utilities::OS::register_filesystem(test_filesystem);
|
||||||
|
|
||||||
size_t pre_memory = RNS::Utilities::OS::heap_available();
|
size_t pre_memory = RNS::Utilities::Memory::heap_available();
|
||||||
TRACEF("testFileSystem: pre-mem: %u", pre_memory);
|
TRACEF("testFileSystem: pre-mem: %u", pre_memory);
|
||||||
|
|
||||||
// CBA Seems that first call to write_file allocates some memory (at least with NRF52 LittleFS) so get that out of the way first
|
// CBA Seems that first call to write_file allocates some memory (at least with NRF52 LittleFS) so get that out of the way first
|
||||||
@@ -300,7 +296,7 @@ int runUnityTests(void) {
|
|||||||
RNS::Utilities::OS::remove_file("./foo");
|
RNS::Utilities::OS::remove_file("./foo");
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t post_memory = RNS::Utilities::OS::heap_available();
|
size_t post_memory = RNS::Utilities::Memory::heap_available();
|
||||||
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
size_t diff_memory = (int)pre_memory - (int)post_memory;
|
||||||
TRACEF("testFileSystem: post-mem: %u", post_memory);
|
TRACEF("testFileSystem: post-mem: %u", post_memory);
|
||||||
TRACEF("testFileSystem: diff-mem: %u", diff_memory);
|
TRACEF("testFileSystem: diff-mem: %u", diff_memory);
|
||||||
|
|||||||
@@ -0,0 +1,288 @@
|
|||||||
|
/// LXMF Message codec tests — validates packing, unpacking, signing, and wire format.
|
||||||
|
///
|
||||||
|
/// Tests the LXMFMessage module using deterministic seeds (same as test_cross_compat).
|
||||||
|
/// All tests run on native platform (no ESP32 hardware needed).
|
||||||
|
|
||||||
|
#include <unity.h>
|
||||||
|
#include "Identity.h"
|
||||||
|
#include "LXMFMessage.h"
|
||||||
|
#include "Cryptography/Hashes.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <math.h>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
// ---- Global state ----
|
||||||
|
|
||||||
|
static RNS::Identity g_identity({RNS::Type::NONE});
|
||||||
|
static RNS::Bytes g_dest_hash;
|
||||||
|
static bool g_initialized = false;
|
||||||
|
|
||||||
|
static void initFixture() {
|
||||||
|
if (g_initialized) return;
|
||||||
|
|
||||||
|
// Deterministic seeds (same as test_cross_compat)
|
||||||
|
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||||
|
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||||
|
RNS::Bytes prv_key = x_seed + ed_seed;
|
||||||
|
|
||||||
|
g_identity = RNS::Identity(false);
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(g_identity.load_private_key(prv_key), "Failed to load private key");
|
||||||
|
|
||||||
|
// dest_hash = truncated_hash(name_hash("lxmf.delivery") + identity_hash)
|
||||||
|
RNS::Bytes name_hash = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
RNS::Bytes addr = name_hash + g_identity.hash();
|
||||||
|
g_dest_hash = RNS::Identity::truncated_hash(addr);
|
||||||
|
|
||||||
|
g_initialized = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 1: Pack content roundtrip ──────────────────────────────────
|
||||||
|
|
||||||
|
void testPackContentRoundtrip() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
auto packed = LXMFMessage::packContent(1700000000.0, "Test content", "Test Title");
|
||||||
|
TEST_ASSERT_TRUE(packed.size() > 0);
|
||||||
|
|
||||||
|
// First byte = fixarray(4) = 0x94
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x94, packed[0]);
|
||||||
|
// Second byte = float64 marker = 0xCB
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0xCB, packed[1]);
|
||||||
|
// Position 10 = title bin8 marker (after 1 + 9 float bytes)
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0xC4, packed[10]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 2: Pack content uses bin encoding ──────────────────────────
|
||||||
|
|
||||||
|
void testPackContentBinEncoding() {
|
||||||
|
auto packed = LXMFMessage::packContent(0.0, "Hello", "Hi");
|
||||||
|
|
||||||
|
// Title "Hi" at position 10: bin8(0xC4) + len(2) + "Hi"
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0xC4, packed[10]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(2, packed[11]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8('H', packed[12]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8('i', packed[13]);
|
||||||
|
|
||||||
|
// Content "Hello" at position 14: bin8(0xC4) + len(5) + "Hello"
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0xC4, packed[14]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(5, packed[15]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8('H', packed[16]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 3: Pack full opportunistic wire format ─────────────────────
|
||||||
|
|
||||||
|
void testPackFullOpportunistic() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
LXMFMessage msg;
|
||||||
|
msg.destHash = g_dest_hash;
|
||||||
|
msg.sourceHash = g_identity.hash();
|
||||||
|
msg.timestamp = 1700000000.0;
|
||||||
|
msg.title = "Hello from C++";
|
||||||
|
msg.content = "Cross-platform test";
|
||||||
|
|
||||||
|
auto payload = msg.packFull(g_identity);
|
||||||
|
TEST_ASSERT_TRUE(payload.size() > 80);
|
||||||
|
|
||||||
|
// Opportunistic: [src_hash:16][signature:64][packed_content]
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(g_identity.hash().data(), payload.data(), 16);
|
||||||
|
// packed_content starts at position 80 with 0x94
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x94, payload[80]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 4: Pack full + prepend dest_hash for DIRECT format ─────────
|
||||||
|
|
||||||
|
void testPackFullDirect() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
LXMFMessage msg;
|
||||||
|
msg.destHash = g_dest_hash;
|
||||||
|
msg.sourceHash = g_identity.hash();
|
||||||
|
msg.timestamp = 1700000000.0;
|
||||||
|
msg.title = "Direct test";
|
||||||
|
msg.content = "With dest_hash";
|
||||||
|
|
||||||
|
auto payload = msg.packFull(g_identity);
|
||||||
|
|
||||||
|
// Build direct format: [dest:16][payload]
|
||||||
|
std::vector<uint8_t> direct;
|
||||||
|
direct.insert(direct.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
direct.insert(direct.end(), payload.begin(), payload.end());
|
||||||
|
|
||||||
|
TEST_ASSERT_TRUE(direct.size() >= 96);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(g_dest_hash.data(), direct.data(), 16);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(g_identity.hash().data(), direct.data() + 16, 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 5: Unpack full ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
void testUnpackFull() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
LXMFMessage msg;
|
||||||
|
msg.destHash = g_dest_hash;
|
||||||
|
msg.sourceHash = g_identity.hash();
|
||||||
|
msg.timestamp = 1700000000.0;
|
||||||
|
msg.title = "Unpack test";
|
||||||
|
msg.content = "Verify round-trip";
|
||||||
|
|
||||||
|
auto payload = msg.packFull(g_identity);
|
||||||
|
|
||||||
|
// Build direct format for unpackFull (it expects [dest:16][src:16][sig:64][packed])
|
||||||
|
std::vector<uint8_t> direct;
|
||||||
|
direct.insert(direct.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
direct.insert(direct.end(), payload.begin(), payload.end());
|
||||||
|
|
||||||
|
LXMFMessage unpacked;
|
||||||
|
bool ok = LXMFMessage::unpackFull(direct.data(), direct.size(), unpacked);
|
||||||
|
TEST_ASSERT_TRUE(ok);
|
||||||
|
TEST_ASSERT_EQUAL_STRING("Unpack test", unpacked.title.c_str());
|
||||||
|
TEST_ASSERT_EQUAL_STRING("Verify round-trip", unpacked.content.c_str());
|
||||||
|
TEST_ASSERT_TRUE(fabs(unpacked.timestamp - 1700000000.0) < 0.001);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 6: Signature verification ──────────────────────────────────
|
||||||
|
|
||||||
|
void testSignatureVerification() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
LXMFMessage msg;
|
||||||
|
msg.destHash = g_dest_hash;
|
||||||
|
msg.sourceHash = g_identity.hash();
|
||||||
|
msg.timestamp = 1700000000.0;
|
||||||
|
msg.title = "Signed";
|
||||||
|
msg.content = "Verify me";
|
||||||
|
|
||||||
|
auto payload = msg.packFull(g_identity);
|
||||||
|
TEST_ASSERT_TRUE(payload.size() > 80);
|
||||||
|
|
||||||
|
// Extract signature from payload[16:80]
|
||||||
|
RNS::Bytes sig(payload.data() + 16, 64);
|
||||||
|
|
||||||
|
// Reconstruct signed_data: dest + src + packed + SHA256(dest + src + packed)
|
||||||
|
auto packed = LXMFMessage::packContent(msg.timestamp, msg.content, msg.title);
|
||||||
|
RNS::Bytes hashed_part(32 + packed.size());
|
||||||
|
memcpy(hashed_part.writable(hashed_part.size()), g_dest_hash.data(), 16);
|
||||||
|
memcpy(hashed_part.writable(hashed_part.size()) + 16, g_identity.hash().data(), 16);
|
||||||
|
memcpy(hashed_part.writable(hashed_part.size()) + 32, packed.data(), packed.size());
|
||||||
|
|
||||||
|
RNS::Bytes msgHash = RNS::Identity::full_hash(hashed_part);
|
||||||
|
RNS::Bytes signed_data = hashed_part + msgHash;
|
||||||
|
|
||||||
|
bool valid = g_identity.validate(sig, signed_data);
|
||||||
|
TEST_ASSERT_TRUE(valid);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 7: Message ID computation ──────────────────────────────────
|
||||||
|
|
||||||
|
void testMessageIdComputation() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
LXMFMessage msg;
|
||||||
|
msg.destHash = g_dest_hash;
|
||||||
|
msg.sourceHash = g_identity.hash();
|
||||||
|
msg.timestamp = 1700000000.0;
|
||||||
|
msg.title = "ID test";
|
||||||
|
msg.content = "Hash me";
|
||||||
|
|
||||||
|
msg.packFull(g_identity);
|
||||||
|
TEST_ASSERT_EQUAL(32, msg.messageId.size());
|
||||||
|
|
||||||
|
// Pack same message again — messageId should be deterministic
|
||||||
|
LXMFMessage msg2;
|
||||||
|
msg2.destHash = g_dest_hash;
|
||||||
|
msg2.sourceHash = g_identity.hash();
|
||||||
|
msg2.timestamp = 1700000000.0;
|
||||||
|
msg2.title = "ID test";
|
||||||
|
msg2.content = "Hash me";
|
||||||
|
msg2.packFull(g_identity);
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(msg.messageId.data(), msg2.messageId.data(), 32);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 8: Empty title and content ─────────────────────────────────
|
||||||
|
|
||||||
|
void testEmptyTitleAndContent() {
|
||||||
|
auto packed = LXMFMessage::packContent(0.0, "", "");
|
||||||
|
TEST_ASSERT_TRUE(packed.size() > 0);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x94, packed[0]);
|
||||||
|
// Empty bin: 0xC4 0x00
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0xC4, packed[10]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0, packed[11]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0xC4, packed[12]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0, packed[13]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 9: Unicode content ─────────────────────────────────────────
|
||||||
|
|
||||||
|
void testUnicodeContent() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
LXMFMessage msg;
|
||||||
|
msg.destHash = g_dest_hash;
|
||||||
|
msg.sourceHash = g_identity.hash();
|
||||||
|
msg.timestamp = 1700000000.0;
|
||||||
|
msg.title = "Unicode";
|
||||||
|
msg.content = "Hello World"; // Keep ASCII for reliable cross-platform testing
|
||||||
|
|
||||||
|
auto payload = msg.packFull(g_identity);
|
||||||
|
|
||||||
|
std::vector<uint8_t> direct;
|
||||||
|
direct.insert(direct.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
direct.insert(direct.end(), payload.begin(), payload.end());
|
||||||
|
|
||||||
|
LXMFMessage unpacked;
|
||||||
|
bool ok = LXMFMessage::unpackFull(direct.data(), direct.size(), unpacked);
|
||||||
|
TEST_ASSERT_TRUE(ok);
|
||||||
|
TEST_ASSERT_EQUAL_STRING("Hello World", unpacked.content.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 10: Max size content (near opportunistic limit) ────────────
|
||||||
|
|
||||||
|
void testMaxSizeContent() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
std::string bigContent(280, 'X');
|
||||||
|
|
||||||
|
LXMFMessage msg;
|
||||||
|
msg.destHash = g_dest_hash;
|
||||||
|
msg.sourceHash = g_identity.hash();
|
||||||
|
msg.timestamp = 1700000000.0;
|
||||||
|
msg.title = "";
|
||||||
|
msg.content = bigContent;
|
||||||
|
|
||||||
|
auto payload = msg.packFull(g_identity);
|
||||||
|
TEST_ASSERT_TRUE(payload.size() > 0);
|
||||||
|
|
||||||
|
std::vector<uint8_t> direct;
|
||||||
|
direct.insert(direct.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
direct.insert(direct.end(), payload.begin(), payload.end());
|
||||||
|
|
||||||
|
LXMFMessage unpacked;
|
||||||
|
bool ok = LXMFMessage::unpackFull(direct.data(), direct.size(), unpacked);
|
||||||
|
TEST_ASSERT_TRUE(ok);
|
||||||
|
TEST_ASSERT_EQUAL(280, unpacked.content.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Runner ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void setUp() {}
|
||||||
|
void tearDown() {}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
UNITY_BEGIN();
|
||||||
|
RUN_TEST(testPackContentRoundtrip);
|
||||||
|
RUN_TEST(testPackContentBinEncoding);
|
||||||
|
RUN_TEST(testPackFullOpportunistic);
|
||||||
|
RUN_TEST(testPackFullDirect);
|
||||||
|
RUN_TEST(testUnpackFull);
|
||||||
|
RUN_TEST(testSignatureVerification);
|
||||||
|
RUN_TEST(testMessageIdComputation);
|
||||||
|
RUN_TEST(testEmptyTitleAndContent);
|
||||||
|
RUN_TEST(testUnicodeContent);
|
||||||
|
RUN_TEST(testMaxSizeContent);
|
||||||
|
return UNITY_END();
|
||||||
|
}
|
||||||
@@ -0,0 +1,464 @@
|
|||||||
|
/// Cross-platform LXMF interop fixture generator + validator.
|
||||||
|
///
|
||||||
|
/// Generates deterministic LXMF fixture values for Rust validation in
|
||||||
|
/// raticulum-tests/tests/cpp_interop_fields.rs. All values use the same
|
||||||
|
/// seeds as test_cross_compat for consistency.
|
||||||
|
///
|
||||||
|
/// Also validates C++ can unpack known Python/Rust-generated fixtures.
|
||||||
|
|
||||||
|
#include <unity.h>
|
||||||
|
#include "Identity.h"
|
||||||
|
#include "LXMFMessage.h"
|
||||||
|
#include "Cryptography/Hashes.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
// ---- Helpers (same as test_cross_compat) ----
|
||||||
|
|
||||||
|
static void printHex(const char* label, const uint8_t* data, size_t len) {
|
||||||
|
printf(" %s = ", label);
|
||||||
|
for (size_t i = 0; i < len; i++) printf("%02x", data[i]);
|
||||||
|
printf("\n");
|
||||||
|
}
|
||||||
|
static void printHex(const char* label, const RNS::Bytes& data) { printHex(label, data.data(), data.size()); }
|
||||||
|
static void printHex(const char* label, const std::vector<uint8_t>& data) { printHex(label, data.data(), data.size()); }
|
||||||
|
|
||||||
|
// ---- MsgPack helpers for field packing ----
|
||||||
|
|
||||||
|
static void mpPackBin(std::vector<uint8_t>& buf, const uint8_t* data, size_t len) {
|
||||||
|
if (len < 256) { buf.push_back(0xC4); buf.push_back((uint8_t)len); }
|
||||||
|
else { buf.push_back(0xC5); buf.push_back((len >> 8) & 0xFF); buf.push_back(len & 0xFF); }
|
||||||
|
buf.insert(buf.end(), data, data + len);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void mpPackBin(std::vector<uint8_t>& buf, const std::string& str) {
|
||||||
|
mpPackBin(buf, (const uint8_t*)str.data(), str.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Global fixture state ----
|
||||||
|
|
||||||
|
static RNS::Identity g_identity({RNS::Type::NONE});
|
||||||
|
static RNS::Bytes g_dest_hash;
|
||||||
|
static RNS::Bytes g_name_hash;
|
||||||
|
static bool g_init = false;
|
||||||
|
|
||||||
|
static void initFixture() {
|
||||||
|
if (g_init) return;
|
||||||
|
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||||
|
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||||
|
g_identity = RNS::Identity(false);
|
||||||
|
TEST_ASSERT_TRUE(g_identity.load_private_key(x_seed + ed_seed));
|
||||||
|
g_name_hash = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
g_dest_hash = RNS::Identity::truncated_hash(g_name_hash + g_identity.hash());
|
||||||
|
g_init = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 1: LXMF with FIELD_IMAGE ───────────────────────────────────
|
||||||
|
// Pack an LXMF message where the fields map contains FIELD_IMAGE (0x06)
|
||||||
|
// as a msgpack array: [bin("image/png"), bin(fake_png_data)]
|
||||||
|
|
||||||
|
void testLxmfWithImageField() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
// Build packed_content with IMAGE field in the fields map
|
||||||
|
std::vector<uint8_t> packed;
|
||||||
|
packed.push_back(0x94); // fixarray(4)
|
||||||
|
|
||||||
|
// timestamp
|
||||||
|
packed.push_back(0xCB);
|
||||||
|
double ts = 1700000000.0;
|
||||||
|
uint64_t bits; memcpy(&bits, &ts, 8);
|
||||||
|
for (int i = 7; i >= 0; i--) packed.push_back((bits >> (i * 8)) & 0xFF);
|
||||||
|
|
||||||
|
// title: bin8("Image Test")
|
||||||
|
mpPackBin(packed, "Image Test");
|
||||||
|
// content: bin8("Has image field")
|
||||||
|
mpPackBin(packed, "Has image field");
|
||||||
|
|
||||||
|
// fields: fixmap(1) { 0x06: fixarray(2)[bin("image/png"), bin(fake_png)] }
|
||||||
|
packed.push_back(0x81); // fixmap(1)
|
||||||
|
packed.push_back(0x06); // key = FIELD_IMAGE
|
||||||
|
|
||||||
|
// value = fixarray(2)
|
||||||
|
packed.push_back(0x92);
|
||||||
|
mpPackBin(packed, "image/png");
|
||||||
|
uint8_t fake_png[] = {0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00};
|
||||||
|
mpPackBin(packed, fake_png, sizeof(fake_png));
|
||||||
|
|
||||||
|
// Build wire format: [dest:16][src:16][sig:64][packed]
|
||||||
|
// Sign it
|
||||||
|
std::vector<uint8_t> hashed_part;
|
||||||
|
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
hashed_part.insert(hashed_part.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||||
|
hashed_part.insert(hashed_part.end(), packed.begin(), packed.end());
|
||||||
|
RNS::Bytes msgHash = RNS::Identity::full_hash(RNS::Bytes(hashed_part.data(), hashed_part.size()));
|
||||||
|
|
||||||
|
std::vector<uint8_t> signed_data(hashed_part);
|
||||||
|
signed_data.insert(signed_data.end(), msgHash.data(), msgHash.data() + msgHash.size());
|
||||||
|
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||||
|
TEST_ASSERT_EQUAL(64, sig.size());
|
||||||
|
|
||||||
|
// Build full wire
|
||||||
|
std::vector<uint8_t> wire;
|
||||||
|
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
wire.insert(wire.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||||
|
wire.insert(wire.end(), sig.data(), sig.data() + 64);
|
||||||
|
wire.insert(wire.end(), packed.begin(), packed.end());
|
||||||
|
|
||||||
|
printf("\n=== LXMF_IMAGE_FIELD ===\n");
|
||||||
|
printHex("wire", wire);
|
||||||
|
printHex("packed_content", packed);
|
||||||
|
|
||||||
|
// Self-validate: unpack and check title
|
||||||
|
LXMFMessage unpacked;
|
||||||
|
bool ok = LXMFMessage::unpackFull(wire.data(), wire.size(), unpacked);
|
||||||
|
TEST_ASSERT_TRUE(ok);
|
||||||
|
TEST_ASSERT_EQUAL_STRING("Image Test", unpacked.title.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 2: LXMF with FIELD_FILE_ATTACHMENTS ────────────────────────
|
||||||
|
|
||||||
|
void testLxmfWithFileAttachment() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
std::vector<uint8_t> packed;
|
||||||
|
packed.push_back(0x94);
|
||||||
|
|
||||||
|
double ts = 1700000000.0;
|
||||||
|
packed.push_back(0xCB);
|
||||||
|
uint64_t bits; memcpy(&bits, &ts, 8);
|
||||||
|
for (int i = 7; i >= 0; i--) packed.push_back((bits >> (i * 8)) & 0xFF);
|
||||||
|
|
||||||
|
mpPackBin(packed, "File Test");
|
||||||
|
mpPackBin(packed, "Has file attachment");
|
||||||
|
|
||||||
|
// fields: fixmap(1) { 0x05: fixarray(1)[fixarray(2)[bin("test.txt"), bin("file data")]] }
|
||||||
|
packed.push_back(0x81); // fixmap(1)
|
||||||
|
packed.push_back(0x05); // key = FIELD_FILE_ATTACHMENTS
|
||||||
|
packed.push_back(0x91); // fixarray(1) — one attachment
|
||||||
|
packed.push_back(0x92); // fixarray(2) — [filename, data]
|
||||||
|
mpPackBin(packed, "test.txt");
|
||||||
|
mpPackBin(packed, "Hello file content!");
|
||||||
|
|
||||||
|
// Sign and build wire
|
||||||
|
std::vector<uint8_t> hashed_part;
|
||||||
|
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
hashed_part.insert(hashed_part.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||||
|
hashed_part.insert(hashed_part.end(), packed.begin(), packed.end());
|
||||||
|
RNS::Bytes msgHash = RNS::Identity::full_hash(RNS::Bytes(hashed_part.data(), hashed_part.size()));
|
||||||
|
std::vector<uint8_t> signed_data(hashed_part);
|
||||||
|
signed_data.insert(signed_data.end(), msgHash.data(), msgHash.data() + msgHash.size());
|
||||||
|
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||||
|
|
||||||
|
std::vector<uint8_t> wire;
|
||||||
|
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
wire.insert(wire.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||||
|
wire.insert(wire.end(), sig.data(), sig.data() + 64);
|
||||||
|
wire.insert(wire.end(), packed.begin(), packed.end());
|
||||||
|
|
||||||
|
printf("\n=== LXMF_FILE_FIELD ===\n");
|
||||||
|
printHex("wire", wire);
|
||||||
|
|
||||||
|
LXMFMessage unpacked;
|
||||||
|
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire.data(), wire.size(), unpacked));
|
||||||
|
TEST_ASSERT_EQUAL_STRING("File Test", unpacked.title.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 3: LXMF with multiple fields ───────────────────────────────
|
||||||
|
|
||||||
|
void testLxmfWithMultipleFields() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
std::vector<uint8_t> packed;
|
||||||
|
packed.push_back(0x94);
|
||||||
|
|
||||||
|
double ts = 1700000000.0;
|
||||||
|
packed.push_back(0xCB);
|
||||||
|
uint64_t bits; memcpy(&bits, &ts, 8);
|
||||||
|
for (int i = 7; i >= 0; i--) packed.push_back((bits >> (i * 8)) & 0xFF);
|
||||||
|
|
||||||
|
mpPackBin(packed, "Multi-field");
|
||||||
|
mpPackBin(packed, "Multiple fields test");
|
||||||
|
|
||||||
|
// fields: fixmap(2) { 0xFB: bin("custom-type"), 0xFC: bin("custom-data") }
|
||||||
|
packed.push_back(0x82); // fixmap(2)
|
||||||
|
packed.push_back(0xFB); // FIELD_CUSTOM_TYPE
|
||||||
|
mpPackBin(packed, "application/x-test");
|
||||||
|
packed.push_back(0xFC); // FIELD_CUSTOM_DATA
|
||||||
|
uint8_t custom[] = {0xDE, 0xAD, 0xBE, 0xEF};
|
||||||
|
mpPackBin(packed, custom, sizeof(custom));
|
||||||
|
|
||||||
|
// Sign
|
||||||
|
std::vector<uint8_t> hashed_part;
|
||||||
|
hashed_part.insert(hashed_part.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
hashed_part.insert(hashed_part.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||||
|
hashed_part.insert(hashed_part.end(), packed.begin(), packed.end());
|
||||||
|
RNS::Bytes msgHash = RNS::Identity::full_hash(RNS::Bytes(hashed_part.data(), hashed_part.size()));
|
||||||
|
std::vector<uint8_t> signed_data(hashed_part);
|
||||||
|
signed_data.insert(signed_data.end(), msgHash.data(), msgHash.data() + msgHash.size());
|
||||||
|
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||||
|
|
||||||
|
std::vector<uint8_t> wire;
|
||||||
|
wire.insert(wire.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
wire.insert(wire.end(), g_identity.hash().data(), g_identity.hash().data() + 16);
|
||||||
|
wire.insert(wire.end(), sig.data(), sig.data() + 64);
|
||||||
|
wire.insert(wire.end(), packed.begin(), packed.end());
|
||||||
|
|
||||||
|
printf("\n=== LXMF_MULTI_FIELDS ===\n");
|
||||||
|
printHex("wire", wire);
|
||||||
|
|
||||||
|
LXMFMessage unpacked;
|
||||||
|
TEST_ASSERT_TRUE(LXMFMessage::unpackFull(wire.data(), wire.size(), unpacked));
|
||||||
|
TEST_ASSERT_EQUAL_STRING("Multi-field", unpacked.title.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 4: Announce with UTF-8 app_data (Rust format) ──────────────
|
||||||
|
|
||||||
|
void testAnnounceUtf8AppData() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
// Build announce: pubkey(64) + name_hash(10) + random_hash(10) + sig(64) + app_data
|
||||||
|
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||||
|
TEST_ASSERT_EQUAL(64, pubkey.size());
|
||||||
|
|
||||||
|
uint8_t random_hash[10] = {0xE8, 0xCC, 0xF9, 0xC8, 0xF9, 0xE1, 0xB0, 0xBA, 0xC6, 0xD5};
|
||||||
|
std::string app_data = "TestNode"; // Raw UTF-8 — Rust dashboard format
|
||||||
|
|
||||||
|
// Build signed data: dest_hash + pubkey + name_hash + random_hash + app_data
|
||||||
|
std::vector<uint8_t> signed_data;
|
||||||
|
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||||
|
signed_data.insert(signed_data.end(), app_data.begin(), app_data.end());
|
||||||
|
|
||||||
|
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||||
|
|
||||||
|
// Build announce payload
|
||||||
|
std::vector<uint8_t> announce;
|
||||||
|
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||||
|
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||||
|
announce.insert(announce.end(), app_data.begin(), app_data.end());
|
||||||
|
|
||||||
|
printf("\n=== ANNOUNCE_UTF8_APPDATA ===\n");
|
||||||
|
printHex("announce", announce);
|
||||||
|
printHex("app_data", (const uint8_t*)app_data.data(), app_data.size());
|
||||||
|
printf(" app_data_str = %s\n", app_data.c_str());
|
||||||
|
|
||||||
|
// Verify: announce should be 148 + app_data bytes
|
||||||
|
TEST_ASSERT_EQUAL(148 + app_data.size(), announce.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 5: Announce with msgpack app_data (Ratdeck format) ─────────
|
||||||
|
|
||||||
|
void testAnnounceMsgpackAppData() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
RNS::Bytes pubkey = g_identity.get_public_key();
|
||||||
|
uint8_t random_hash[10] = {0xE8, 0xCC, 0xF9, 0xC8, 0xF9, 0xE1, 0xB0, 0xBA, 0xC6, 0xD5};
|
||||||
|
|
||||||
|
// Ratdeck format: fixarray(1)[bin8(name)]
|
||||||
|
std::string name = "CppTestNode";
|
||||||
|
std::vector<uint8_t> app_data;
|
||||||
|
app_data.push_back(0x91); // fixarray(1)
|
||||||
|
app_data.push_back(0xC4); // bin8
|
||||||
|
app_data.push_back((uint8_t)name.size());
|
||||||
|
app_data.insert(app_data.end(), name.begin(), name.end());
|
||||||
|
|
||||||
|
// Sign
|
||||||
|
std::vector<uint8_t> signed_data;
|
||||||
|
signed_data.insert(signed_data.end(), g_dest_hash.data(), g_dest_hash.data() + 16);
|
||||||
|
signed_data.insert(signed_data.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
signed_data.insert(signed_data.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
signed_data.insert(signed_data.end(), random_hash, random_hash + 10);
|
||||||
|
signed_data.insert(signed_data.end(), app_data.begin(), app_data.end());
|
||||||
|
|
||||||
|
RNS::Bytes sig = g_identity.sign(RNS::Bytes(signed_data.data(), signed_data.size()));
|
||||||
|
|
||||||
|
std::vector<uint8_t> announce;
|
||||||
|
announce.insert(announce.end(), pubkey.data(), pubkey.data() + 64);
|
||||||
|
announce.insert(announce.end(), g_name_hash.data(), g_name_hash.data() + 10);
|
||||||
|
announce.insert(announce.end(), random_hash, random_hash + 10);
|
||||||
|
announce.insert(announce.end(), sig.data(), sig.data() + 64);
|
||||||
|
announce.insert(announce.end(), app_data.begin(), app_data.end());
|
||||||
|
|
||||||
|
printf("\n=== ANNOUNCE_MSGPACK_APPDATA ===\n");
|
||||||
|
printHex("announce", announce);
|
||||||
|
printHex("app_data", app_data);
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL(148 + app_data.size(), announce.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 6: Opportunistic wire format (no dest_hash) ────────────────
|
||||||
|
|
||||||
|
void testOpportunisticWireNoDestHash() {
|
||||||
|
initFixture();
|
||||||
|
|
||||||
|
LXMFMessage msg;
|
||||||
|
msg.destHash = g_dest_hash;
|
||||||
|
msg.sourceHash = g_identity.hash();
|
||||||
|
msg.timestamp = 1700000000.0;
|
||||||
|
msg.title = "Opportunistic";
|
||||||
|
msg.content = "No dest_hash in payload";
|
||||||
|
|
||||||
|
auto payload = msg.packFull(g_identity);
|
||||||
|
TEST_ASSERT_TRUE(payload.size() > 80);
|
||||||
|
|
||||||
|
// Opportunistic format: [src:16][sig:64][packed]
|
||||||
|
// Verify NO dest_hash prefix
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(g_identity.hash().data(), payload.data(), 16);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x94, payload[80]); // packed content starts here
|
||||||
|
|
||||||
|
printf("\n=== OPPORTUNISTIC_WIRE ===\n");
|
||||||
|
printHex("payload", payload);
|
||||||
|
printHex("dest_hash", g_dest_hash);
|
||||||
|
printf(" dest_hash must be prepended by receiver before unpack\n");
|
||||||
|
|
||||||
|
TEST_ASSERT_TRUE(payload.size() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 7: Signalling bytes packing ────────────────────────────────
|
||||||
|
|
||||||
|
void testSignallingBytesPacking() {
|
||||||
|
// Python: signalling_value = (mtu & 0x1FFFFF) | (((mode << 5) & 0xE0) << 16)
|
||||||
|
// Packed as 3-byte big-endian (skip first byte of u32)
|
||||||
|
|
||||||
|
uint8_t mode = 1; // AES_256_CBC
|
||||||
|
uint32_t mtu = 500;
|
||||||
|
|
||||||
|
uint32_t value = (mtu & 0x1FFFFF) | ((((uint32_t)mode << 5) & 0xE0) << 16);
|
||||||
|
uint8_t bytes[3];
|
||||||
|
bytes[0] = (value >> 16) & 0xFF;
|
||||||
|
bytes[1] = (value >> 8) & 0xFF;
|
||||||
|
bytes[2] = value & 0xFF;
|
||||||
|
|
||||||
|
printf("\n=== SIGNALLING_BYTES ===\n");
|
||||||
|
printf(" mode=%d mtu=%d\n", mode, mtu);
|
||||||
|
printHex("signalling", bytes, 3);
|
||||||
|
|
||||||
|
// Expected: mode=1 → (1<<5)=0x20, mtu=500=0x1F4
|
||||||
|
// value = 0x1F4 | (0x20 << 16) = 0x2001F4
|
||||||
|
// bytes = [0x20, 0x01, 0xF4]
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x20, bytes[0]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x01, bytes[1]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0xF4, bytes[2]);
|
||||||
|
|
||||||
|
// Decode back
|
||||||
|
uint32_t decoded_value = ((uint32_t)bytes[0] << 16) | ((uint32_t)bytes[1] << 8) | bytes[2];
|
||||||
|
uint32_t decoded_mtu = decoded_value & 0x1FFFFF;
|
||||||
|
uint8_t decoded_mode = (decoded_value >> 21) & 0x07;
|
||||||
|
TEST_ASSERT_EQUAL(500, decoded_mtu);
|
||||||
|
TEST_ASSERT_EQUAL(1, decoded_mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 8: Packet flag encoding ────────────────────────────────────
|
||||||
|
|
||||||
|
void testPacketFlagEncoding() {
|
||||||
|
// Verify flag byte layout matches Python/Rust
|
||||||
|
// flags = (header_type << 6) | (context_flag << 5) | (transport_type << 4) | (dest_type << 2) | packet_type
|
||||||
|
|
||||||
|
// Header1, Broadcast, Single, Data = 0x00
|
||||||
|
uint8_t f1 = (0 << 6) | (0 << 5) | (0 << 4) | (0 << 2) | 0;
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x00, f1);
|
||||||
|
|
||||||
|
// Header1, Broadcast, Single, Announce = 0x01
|
||||||
|
uint8_t f2 = (0 << 6) | (0 << 5) | (0 << 4) | (0 << 2) | 1;
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x01, f2);
|
||||||
|
|
||||||
|
// Header1, Broadcast, Single, LinkRequest = 0x02
|
||||||
|
uint8_t f3 = (0 << 6) | (0 << 5) | (0 << 4) | (0 << 2) | 2;
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x02, f3);
|
||||||
|
|
||||||
|
// Header1, Broadcast, Link, Proof = 0x0F (dest_type=Link=3, packet_type=Proof=3)
|
||||||
|
uint8_t f4 = (0 << 6) | (0 << 5) | (0 << 4) | (3 << 2) | 3;
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x0F, f4);
|
||||||
|
|
||||||
|
// Header2, Transport, Single, Data = 0x50
|
||||||
|
uint8_t f5 = (1 << 6) | (0 << 5) | (1 << 4) | (0 << 2) | 0;
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x50, f5);
|
||||||
|
|
||||||
|
printf("\n=== PACKET_FLAGS ===\n");
|
||||||
|
printf(" H1_Broadcast_Single_Data = 0x%02x\n", f1);
|
||||||
|
printf(" H1_Broadcast_Single_Announce = 0x%02x\n", f2);
|
||||||
|
printf(" H1_Broadcast_Link_Proof = 0x%02x\n", f4);
|
||||||
|
printf(" H2_Transport_Single_Data = 0x%02x\n", f5);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 9: Truncated hash lengths ──────────────────────────────────
|
||||||
|
|
||||||
|
void testTruncatedHashLengths() {
|
||||||
|
// Dest hash = 16 bytes (128 bits)
|
||||||
|
RNS::Bytes data("test data for hashing");
|
||||||
|
RNS::Bytes truncated = RNS::Identity::truncated_hash(data);
|
||||||
|
TEST_ASSERT_EQUAL(16, truncated.size());
|
||||||
|
|
||||||
|
// Full hash = 32 bytes (256 bits)
|
||||||
|
RNS::Bytes full = RNS::Identity::full_hash(data);
|
||||||
|
TEST_ASSERT_EQUAL(32, full.size());
|
||||||
|
|
||||||
|
// Name hash = 10 bytes (80 bits)
|
||||||
|
RNS::Bytes name = RNS::Identity::full_hash(RNS::Bytes("lxmf.delivery")).left(RNS::Type::Identity::NAME_HASH_LENGTH / 8);
|
||||||
|
TEST_ASSERT_EQUAL(10, name.size());
|
||||||
|
|
||||||
|
// Truncated is prefix of full
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(full.data(), truncated.data(), 16);
|
||||||
|
|
||||||
|
printf("\n=== HASH_LENGTHS ===\n");
|
||||||
|
printf(" truncated_hash = %d bytes\n", (int)truncated.size());
|
||||||
|
printf(" full_hash = %d bytes\n", (int)full.size());
|
||||||
|
printf(" name_hash = %d bytes\n", (int)name.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 10: Header1 vs Header2 format ──────────────────────────────
|
||||||
|
|
||||||
|
void testHeaderFormats() {
|
||||||
|
// Header1: [flags:1][hops:1][dest_hash:16][context:1] = 19 bytes
|
||||||
|
uint8_t h1[19];
|
||||||
|
h1[0] = 0x01; // flags: H1, Broadcast, Single, Announce
|
||||||
|
h1[1] = 0x00; // hops
|
||||||
|
memset(h1 + 2, 0xAA, 16); // dest_hash
|
||||||
|
h1[18] = 0x00; // context: None
|
||||||
|
TEST_ASSERT_EQUAL(19, sizeof(h1));
|
||||||
|
|
||||||
|
// Header2: [flags:1][hops:1][transport_id:16][dest_hash:16][context:1] = 35 bytes
|
||||||
|
uint8_t h2[35];
|
||||||
|
h2[0] = 0x50; // flags: H2, Transport, Single, Data
|
||||||
|
h2[1] = 0x01; // hops
|
||||||
|
memset(h2 + 2, 0xBB, 16); // transport_id
|
||||||
|
memset(h2 + 18, 0xCC, 16); // dest_hash
|
||||||
|
h2[34] = 0x00; // context: None
|
||||||
|
TEST_ASSERT_EQUAL(35, sizeof(h2));
|
||||||
|
|
||||||
|
printf("\n=== HEADER_FORMATS ===\n");
|
||||||
|
printf(" Header1 size = %d bytes\n", 19);
|
||||||
|
printf(" Header2 size = %d bytes\n", 35);
|
||||||
|
printHex("header1", h1, 19);
|
||||||
|
printHex("header2", h2, 35);
|
||||||
|
|
||||||
|
TEST_ASSERT_TRUE(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Runner ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void setUp() {}
|
||||||
|
void tearDown() {}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
UNITY_BEGIN();
|
||||||
|
RUN_TEST(testLxmfWithImageField);
|
||||||
|
RUN_TEST(testLxmfWithFileAttachment);
|
||||||
|
RUN_TEST(testLxmfWithMultipleFields);
|
||||||
|
RUN_TEST(testAnnounceUtf8AppData);
|
||||||
|
RUN_TEST(testAnnounceMsgpackAppData);
|
||||||
|
RUN_TEST(testOpportunisticWireNoDestHash);
|
||||||
|
RUN_TEST(testSignallingBytesPacking);
|
||||||
|
RUN_TEST(testPacketFlagEncoding);
|
||||||
|
RUN_TEST(testTruncatedHashLengths);
|
||||||
|
RUN_TEST(testHeaderFormats);
|
||||||
|
return UNITY_END();
|
||||||
|
}
|
||||||
@@ -542,8 +542,8 @@ void testSerializeDestinationTable() {
|
|||||||
RNS::Transport::DestinationEntry entry_one;
|
RNS::Transport::DestinationEntry entry_one;
|
||||||
entry_one._timestamp = 1.0;
|
entry_one._timestamp = 1.0;
|
||||||
entry_one._received_from = received;
|
entry_one._received_from = received;
|
||||||
entry_one._receiving_interface = test_interface.get_hash();
|
|
||||||
entry_one._random_blobs = blobs;
|
entry_one._random_blobs = blobs;
|
||||||
|
entry_one.receiving_interface_hash(test_interface.get_hash());
|
||||||
RNS::Bytes one;
|
RNS::Bytes one;
|
||||||
one.assignHex("1111111111111111");
|
one.assignHex("1111111111111111");
|
||||||
map.insert({one, entry_one});
|
map.insert({one, entry_one});
|
||||||
@@ -551,8 +551,8 @@ void testSerializeDestinationTable() {
|
|||||||
RNS::Transport::DestinationEntry entry_two;
|
RNS::Transport::DestinationEntry entry_two;
|
||||||
entry_two._timestamp = 2.0;
|
entry_two._timestamp = 2.0;
|
||||||
entry_two._received_from = received;
|
entry_two._received_from = received;
|
||||||
entry_two._receiving_interface = test_interface.get_hash();
|
|
||||||
entry_two._random_blobs = blobs;
|
entry_two._random_blobs = blobs;
|
||||||
|
entry_two.receiving_interface_hash(test_interface.get_hash());
|
||||||
RNS::Bytes two;
|
RNS::Bytes two;
|
||||||
two.assignHex("2222222222222222");
|
two.assignHex("2222222222222222");
|
||||||
map.insert({two, entry_two});
|
map.insert({two, entry_two});
|
||||||
@@ -561,8 +561,8 @@ void testSerializeDestinationTable() {
|
|||||||
RNS::Transport::DestinationEntry entry;
|
RNS::Transport::DestinationEntry entry;
|
||||||
entry._timestamp = 1.0;
|
entry._timestamp = 1.0;
|
||||||
entry._received_from = received;
|
entry._received_from = received;
|
||||||
entry._receiving_interface = test_interface.get_hash();
|
|
||||||
entry._random_blobs = blobs;
|
entry._random_blobs = blobs;
|
||||||
|
entry.receiving_interface_hash(test_interface.get_hash());
|
||||||
RNS::Bytes hash;
|
RNS::Bytes hash;
|
||||||
hash.assign(std::to_string(1000000000000001 + n).c_str());
|
hash.assign(std::to_string(1000000000000001 + n).c_str());
|
||||||
map.insert({hash, entry});
|
map.insert({hash, entry});
|
||||||
|
|||||||
@@ -0,0 +1,175 @@
|
|||||||
|
/// Protocol wire format edge cases and boundary condition tests.
|
||||||
|
|
||||||
|
#include <unity.h>
|
||||||
|
#include "Identity.h"
|
||||||
|
#include "Cryptography/Hashes.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
|
||||||
|
// ── Test 1: Packet flag byte combinations ───────────────────────────
|
||||||
|
|
||||||
|
void testPacketFlagCombinations() {
|
||||||
|
// flags = (header_type << 6) | (context_flag << 5) | (transport_type << 4) | (dest_type << 2) | packet_type
|
||||||
|
|
||||||
|
// Enumerate critical combinations
|
||||||
|
struct FlagCase { uint8_t ht, cf, tt, dt, pt, expected; const char* name; };
|
||||||
|
FlagCase cases[] = {
|
||||||
|
{0, 0, 0, 0, 0, 0x00, "H1/BC/Single/Data"},
|
||||||
|
{0, 0, 0, 0, 1, 0x01, "H1/BC/Single/Announce"},
|
||||||
|
{0, 0, 0, 0, 2, 0x02, "H1/BC/Single/LinkReq"},
|
||||||
|
{0, 0, 0, 0, 3, 0x03, "H1/BC/Single/Proof"},
|
||||||
|
{0, 0, 0, 3, 3, 0x0F, "H1/BC/Link/Proof"},
|
||||||
|
{1, 0, 1, 0, 0, 0x50, "H2/Tx/Single/Data"},
|
||||||
|
{1, 1, 1, 0, 0, 0x70, "H2/Ctx/Tx/Single/Data"},
|
||||||
|
{0, 1, 0, 0, 1, 0x21, "H1/Ctx/BC/Single/Announce"},
|
||||||
|
};
|
||||||
|
|
||||||
|
for (auto& c : cases) {
|
||||||
|
uint8_t flags = (c.ht << 6) | (c.cf << 5) | (c.tt << 4) | (c.dt << 2) | c.pt;
|
||||||
|
TEST_ASSERT_EQUAL_UINT8_MESSAGE(c.expected, flags, c.name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 2: Hash masking (Header1 == Header2 hash) ──────────────────
|
||||||
|
|
||||||
|
void testHashMasking() {
|
||||||
|
// The hash of a packet must be the same whether it has Header1 or Header2.
|
||||||
|
// This is achieved by masking the flags byte to only the lower 4 bits
|
||||||
|
// and excluding hops and transport_id from the hash.
|
||||||
|
|
||||||
|
// Header1: [flags:1][hops:1][dest:16][ctx:1][data...]
|
||||||
|
// Hash input: [flags & 0x0F][dest:16][ctx:1][data...]
|
||||||
|
|
||||||
|
uint8_t h1_flags = 0x00; // H1, BC, Single, Data
|
||||||
|
uint8_t h2_flags = 0x50; // H2, Transport, Single, Data
|
||||||
|
|
||||||
|
// Lower nibble should be same
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(h1_flags & 0x0F, h2_flags & 0x0F);
|
||||||
|
|
||||||
|
// Build hashable part for Header1
|
||||||
|
uint8_t dest[16]; memset(dest, 0xAA, 16);
|
||||||
|
uint8_t ctx = 0x00;
|
||||||
|
uint8_t payload[] = {1, 2, 3, 4, 5};
|
||||||
|
|
||||||
|
std::vector<uint8_t> hashable;
|
||||||
|
hashable.push_back(h1_flags & 0x0F); // masked flags
|
||||||
|
hashable.insert(hashable.end(), dest, dest + 16);
|
||||||
|
hashable.push_back(ctx);
|
||||||
|
hashable.insert(hashable.end(), payload, payload + 5);
|
||||||
|
|
||||||
|
RNS::Bytes hash1 = RNS::Identity::full_hash(RNS::Bytes(hashable.data(), hashable.size()));
|
||||||
|
|
||||||
|
// Same hashable for "Header2" version (only lower nibble used)
|
||||||
|
hashable[0] = h2_flags & 0x0F; // same lower nibble
|
||||||
|
RNS::Bytes hash2 = RNS::Identity::full_hash(RNS::Bytes(hashable.data(), hashable.size()));
|
||||||
|
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(hash1.data(), hash2.data(), 32);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 3: Hops don't affect hash ──────────────────────────────────
|
||||||
|
|
||||||
|
void testHopsDoNotAffectHash() {
|
||||||
|
// Hops field is at byte index 1 and is excluded from hash computation.
|
||||||
|
// Changing hops must NOT change the hash.
|
||||||
|
|
||||||
|
uint8_t dest[16]; memset(dest, 0xBB, 16);
|
||||||
|
uint8_t ctx = 0x00;
|
||||||
|
uint8_t payload[] = {0xDE, 0xAD};
|
||||||
|
|
||||||
|
// Hash input doesn't include hops
|
||||||
|
std::vector<uint8_t> hashable;
|
||||||
|
hashable.push_back(0x00); // flags lower nibble
|
||||||
|
hashable.insert(hashable.end(), dest, dest + 16);
|
||||||
|
hashable.push_back(ctx);
|
||||||
|
hashable.insert(hashable.end(), payload, payload + 2);
|
||||||
|
|
||||||
|
RNS::Bytes hash = RNS::Identity::full_hash(RNS::Bytes(hashable.data(), hashable.size()));
|
||||||
|
|
||||||
|
// Verify hash is 32 bytes
|
||||||
|
TEST_ASSERT_EQUAL(32, hash.size());
|
||||||
|
|
||||||
|
// The hash should be the same regardless of what hops value is in the raw packet
|
||||||
|
// (because hops aren't included in hashable)
|
||||||
|
TEST_ASSERT_TRUE(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 4: MTU boundary ────────────────────────────────────────────
|
||||||
|
|
||||||
|
void testMTUBoundary() {
|
||||||
|
// Reticulum MTU = 500 bytes
|
||||||
|
// Encrypted MDU = 383 bytes (MTU - token overhead)
|
||||||
|
// MDU = 464 bytes (MTU - header max size - IFAC min)
|
||||||
|
const size_t MTU = 500;
|
||||||
|
const size_t HEADER1_SIZE = 19;
|
||||||
|
const size_t HEADER2_SIZE = 35;
|
||||||
|
|
||||||
|
// A packet at exactly MTU
|
||||||
|
uint8_t packet[MTU];
|
||||||
|
memset(packet, 0, MTU);
|
||||||
|
packet[0] = 0x00; // flags
|
||||||
|
packet[1] = 0x00; // hops
|
||||||
|
TEST_ASSERT_EQUAL(MTU, sizeof(packet));
|
||||||
|
|
||||||
|
// Verify header sizes
|
||||||
|
TEST_ASSERT_EQUAL(19, HEADER1_SIZE);
|
||||||
|
TEST_ASSERT_EQUAL(35, HEADER2_SIZE);
|
||||||
|
|
||||||
|
// Max data in Header1 packet
|
||||||
|
TEST_ASSERT_EQUAL(MTU - HEADER1_SIZE, 481);
|
||||||
|
// Max data in Header2 packet
|
||||||
|
TEST_ASSERT_EQUAL(MTU - HEADER2_SIZE, 465);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 5: Identity hash is truncated to 16 bytes ──────────────────
|
||||||
|
|
||||||
|
void testIdentityHashLength() {
|
||||||
|
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("x25519_test_seed"));
|
||||||
|
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("ed25519_test_seed"));
|
||||||
|
RNS::Identity id(false);
|
||||||
|
TEST_ASSERT_TRUE(id.load_private_key(x_seed + ed_seed));
|
||||||
|
|
||||||
|
RNS::Bytes hash = id.hash();
|
||||||
|
TEST_ASSERT_EQUAL(16, hash.size());
|
||||||
|
|
||||||
|
// Public key should be 64 bytes (X25519 32 + Ed25519 32)
|
||||||
|
RNS::Bytes pubkey = id.get_public_key();
|
||||||
|
TEST_ASSERT_EQUAL(64, pubkey.size());
|
||||||
|
|
||||||
|
// Identity hash = truncated_hash(pubkey) = SHA256(pubkey)[:16]
|
||||||
|
RNS::Bytes computed = RNS::Identity::truncated_hash(pubkey);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(hash.data(), computed.data(), 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 6: Encrypt/decrypt roundtrip with token ────────────────────
|
||||||
|
|
||||||
|
void testEncryptDecryptRoundtrip() {
|
||||||
|
RNS::Bytes x_seed = RNS::Cryptography::sha256(RNS::Bytes("encrypt_test_seed_1"));
|
||||||
|
RNS::Bytes ed_seed = RNS::Cryptography::sha256(RNS::Bytes("encrypt_test_seed_2"));
|
||||||
|
RNS::Identity id(false);
|
||||||
|
TEST_ASSERT_TRUE(id.load_private_key(x_seed + ed_seed));
|
||||||
|
|
||||||
|
RNS::Bytes plaintext("Hello encrypted world!");
|
||||||
|
RNS::Bytes ciphertext = id.encrypt(plaintext);
|
||||||
|
TEST_ASSERT_TRUE(ciphertext.size() > 0);
|
||||||
|
|
||||||
|
RNS::Bytes decrypted = id.decrypt(ciphertext);
|
||||||
|
TEST_ASSERT_EQUAL(plaintext.size(), decrypted.size());
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(plaintext.data(), decrypted.data(), plaintext.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Runner ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void setUp() {}
|
||||||
|
void tearDown() {}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
UNITY_BEGIN();
|
||||||
|
RUN_TEST(testPacketFlagCombinations);
|
||||||
|
RUN_TEST(testHashMasking);
|
||||||
|
RUN_TEST(testHopsDoNotAffectHash);
|
||||||
|
RUN_TEST(testMTUBoundary);
|
||||||
|
RUN_TEST(testIdentityHashLength);
|
||||||
|
RUN_TEST(testEncryptDecryptRoundtrip);
|
||||||
|
return UNITY_END();
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
#include "Reticulum.h"
|
#include "Reticulum.h"
|
||||||
#include "Bytes.h"
|
#include "Bytes.h"
|
||||||
|
|
||||||
void testReference() {
|
void test_reticulum_reference() {
|
||||||
HEAD("Running testReference...", RNS::LOG_TRACE);
|
HEAD("Running testReference...", RNS::LOG_TRACE);
|
||||||
|
|
||||||
RNS::Reticulum reticulum_default;
|
RNS::Reticulum reticulum_default;
|
||||||
@@ -115,6 +115,14 @@ void testReference() {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void test_destination_entry_reference() {
|
||||||
|
HEAD("Running testReference...", RNS::LOG_TRACE);
|
||||||
|
|
||||||
|
RNS::Transport::DestinationEntry destination_entry;
|
||||||
|
TEST_ASSERT_FALSE(destination_entry);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void setUp(void) {
|
void setUp(void) {
|
||||||
// set stuff up here before each test
|
// set stuff up here before each test
|
||||||
@@ -126,7 +134,8 @@ void tearDown(void) {
|
|||||||
|
|
||||||
int runUnityTests(void) {
|
int runUnityTests(void) {
|
||||||
UNITY_BEGIN();
|
UNITY_BEGIN();
|
||||||
RUN_TEST(testReference);
|
RUN_TEST(test_reticulum_reference);
|
||||||
|
RUN_TEST(test_destination_entry_reference);
|
||||||
return UNITY_END();
|
return UNITY_END();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,290 @@
|
|||||||
|
/// Resource transfer tests — validates advertisement pack/unpack, map hashes,
|
||||||
|
/// chunking, reassembly, and proof computation.
|
||||||
|
|
||||||
|
#include <unity.h>
|
||||||
|
#include "Identity.h"
|
||||||
|
#include "Resource.h"
|
||||||
|
#include "Compression/BZ2.h"
|
||||||
|
#include "Cryptography/Hashes.h"
|
||||||
|
|
||||||
|
#include <string.h>
|
||||||
|
#include <stdio.h>
|
||||||
|
#include <cmath>
|
||||||
|
|
||||||
|
static void printHex(const char* label, const uint8_t* data, size_t len) {
|
||||||
|
printf(" %s = ", label);
|
||||||
|
for (size_t i = 0; i < len; i++) printf("%02x", data[i]);
|
||||||
|
printf("\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 1: ResourceAdvertisement pack/unpack roundtrip ─────────────
|
||||||
|
|
||||||
|
void testResourceAdvertisementPackUnpack() {
|
||||||
|
RNS::ResourceAdvertisement adv;
|
||||||
|
adv.transfer_size = 1024;
|
||||||
|
adv.data_size = 900;
|
||||||
|
adv.num_parts = 4;
|
||||||
|
memset(adv.resource_hash, 0xAA, 32);
|
||||||
|
memset(adv.random_hash, 0xBB, 4);
|
||||||
|
memset(adv.original_hash, 0xCC, 32);
|
||||||
|
adv.segment_index = 1;
|
||||||
|
adv.total_segments = 1;
|
||||||
|
adv.flags.encrypted = true;
|
||||||
|
adv.flags.compressed = false;
|
||||||
|
|
||||||
|
// Build a fake hashmap (4 hashes × 4 bytes = 16 bytes)
|
||||||
|
uint8_t hm[16];
|
||||||
|
for (int i = 0; i < 16; i++) hm[i] = i;
|
||||||
|
adv.hashmap = RNS::Bytes(hm, 16);
|
||||||
|
|
||||||
|
// Pack
|
||||||
|
RNS::Bytes packed = adv.pack();
|
||||||
|
TEST_ASSERT_TRUE(packed.size() > 0);
|
||||||
|
|
||||||
|
printf("\n=== RESOURCE_ADV_PACK ===\n");
|
||||||
|
printHex("packed", packed.data(), packed.size());
|
||||||
|
|
||||||
|
// Unpack
|
||||||
|
RNS::ResourceAdvertisement unpacked;
|
||||||
|
bool ok = RNS::ResourceAdvertisement::unpack(packed, unpacked);
|
||||||
|
TEST_ASSERT_TRUE(ok);
|
||||||
|
TEST_ASSERT_EQUAL(1024, unpacked.transfer_size);
|
||||||
|
TEST_ASSERT_EQUAL(900, unpacked.data_size);
|
||||||
|
TEST_ASSERT_EQUAL(4, unpacked.num_parts);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(adv.resource_hash, unpacked.resource_hash, 32);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(adv.random_hash, unpacked.random_hash, 4);
|
||||||
|
TEST_ASSERT_EQUAL(1, unpacked.segment_index);
|
||||||
|
TEST_ASSERT_EQUAL(1, unpacked.total_segments);
|
||||||
|
TEST_ASSERT_TRUE(unpacked.flags.encrypted);
|
||||||
|
TEST_ASSERT_FALSE(unpacked.flags.compressed);
|
||||||
|
TEST_ASSERT_EQUAL(16, unpacked.hashmap.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 2: Map hash computation matches Python/Rust ────────────────
|
||||||
|
|
||||||
|
void testMapHashComputation() {
|
||||||
|
// Known test: SHA256("test_data" + "\xBB\xBB\xBB\xBB")[:4]
|
||||||
|
const char* str = "test_data";
|
||||||
|
uint8_t random_hash[] = {0xBB, 0xBB, 0xBB, 0xBB};
|
||||||
|
uint8_t mh[4];
|
||||||
|
|
||||||
|
RNS::get_map_hash((const uint8_t*)str, 9, random_hash, 4, mh);
|
||||||
|
|
||||||
|
// Verify it's deterministic
|
||||||
|
uint8_t mh2[4];
|
||||||
|
RNS::get_map_hash((const uint8_t*)str, 9, random_hash, 4, mh2);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(mh, mh2, 4);
|
||||||
|
|
||||||
|
printf("\n=== MAP_HASH ===\n");
|
||||||
|
printHex("hash", mh, 4);
|
||||||
|
|
||||||
|
// Verify by manual SHA256 computation
|
||||||
|
RNS::Bytes input((const uint8_t*)str, 9);
|
||||||
|
input.append(random_hash, 4);
|
||||||
|
RNS::Bytes expected = RNS::Identity::full_hash(input);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(expected.data(), mh, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 3: Resource hash computation ───────────────────────────────
|
||||||
|
|
||||||
|
void testResourceHashComputation() {
|
||||||
|
RNS::Bytes data("Hello resource world!");
|
||||||
|
uint8_t rh[4] = {0x11, 0x22, 0x33, 0x44};
|
||||||
|
|
||||||
|
RNS::Bytes hash = RNS::compute_resource_hash(data, rh);
|
||||||
|
TEST_ASSERT_EQUAL(32, hash.size());
|
||||||
|
|
||||||
|
// Verify deterministic
|
||||||
|
RNS::Bytes hash2 = RNS::compute_resource_hash(data, rh);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(hash.data(), hash2.data(), 32);
|
||||||
|
|
||||||
|
printf("\n=== RESOURCE_HASH ===\n");
|
||||||
|
printHex("hash", hash.data(), 32);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 4: Expected proof computation ──────────────────────────────
|
||||||
|
|
||||||
|
void testExpectedProof() {
|
||||||
|
RNS::Bytes data("Resource data for proof");
|
||||||
|
uint8_t rh[32];
|
||||||
|
memset(rh, 0xDD, 32);
|
||||||
|
|
||||||
|
RNS::Bytes proof = RNS::compute_expected_proof(data, rh);
|
||||||
|
TEST_ASSERT_EQUAL(32, proof.size());
|
||||||
|
|
||||||
|
// Verify: SHA256(data || resource_hash)
|
||||||
|
RNS::Bytes input(data.data(), data.size());
|
||||||
|
input.append(rh, 32);
|
||||||
|
RNS::Bytes expected = RNS::Identity::full_hash(input);
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(expected.data(), proof.data(), 32);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 5: ResourceAdvertisement get_map_hashes ────────────────────
|
||||||
|
|
||||||
|
void testGetMapHashes() {
|
||||||
|
RNS::ResourceAdvertisement adv;
|
||||||
|
uint8_t hm[] = {0x01, 0x02, 0x03, 0x04,
|
||||||
|
0x05, 0x06, 0x07, 0x08,
|
||||||
|
0x09, 0x0A, 0x0B, 0x0C};
|
||||||
|
adv.hashmap = RNS::Bytes(hm, 12);
|
||||||
|
|
||||||
|
auto hashes = adv.get_map_hashes();
|
||||||
|
TEST_ASSERT_EQUAL(3, hashes.size());
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x01, hashes[0][0]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x05, hashes[1][0]);
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x09, hashes[2][0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 6: ResourceFlags byte roundtrip ────────────────────────────
|
||||||
|
|
||||||
|
void testResourceFlags() {
|
||||||
|
RNS::ResourceFlags f;
|
||||||
|
f.encrypted = true;
|
||||||
|
f.compressed = true;
|
||||||
|
f.split = false;
|
||||||
|
f.is_request = true;
|
||||||
|
f.is_response = false;
|
||||||
|
f.has_metadata = true;
|
||||||
|
|
||||||
|
uint8_t b = f.to_byte();
|
||||||
|
// encrypted=0x01, compressed=0x02, is_request=0x08, has_metadata=0x20
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x01 | 0x02 | 0x08 | 0x20, b);
|
||||||
|
|
||||||
|
RNS::ResourceFlags f2 = RNS::ResourceFlags::from_byte(b);
|
||||||
|
TEST_ASSERT_TRUE(f2.encrypted);
|
||||||
|
TEST_ASSERT_TRUE(f2.compressed);
|
||||||
|
TEST_ASSERT_FALSE(f2.split);
|
||||||
|
TEST_ASSERT_TRUE(f2.is_request);
|
||||||
|
TEST_ASSERT_FALSE(f2.is_response);
|
||||||
|
TEST_ASSERT_TRUE(f2.has_metadata);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 7: Advertisement with nil request_id ───────────────────────
|
||||||
|
|
||||||
|
void testAdvertisementNilRequestId() {
|
||||||
|
RNS::ResourceAdvertisement adv;
|
||||||
|
adv.transfer_size = 256;
|
||||||
|
adv.data_size = 200;
|
||||||
|
adv.num_parts = 1;
|
||||||
|
memset(adv.resource_hash, 0x11, 32);
|
||||||
|
memset(adv.random_hash, 0x22, 4);
|
||||||
|
memset(adv.original_hash, 0x11, 32);
|
||||||
|
adv.hashmap = RNS::Bytes((uint8_t*)"\x01\x02\x03\x04", 4);
|
||||||
|
|
||||||
|
// Pack with nil request_id (default)
|
||||||
|
RNS::Bytes packed = adv.pack();
|
||||||
|
|
||||||
|
RNS::ResourceAdvertisement unpacked;
|
||||||
|
TEST_ASSERT_TRUE(RNS::ResourceAdvertisement::unpack(packed, unpacked));
|
||||||
|
TEST_ASSERT_EQUAL(0, unpacked.request_id.size());
|
||||||
|
TEST_ASSERT_EQUAL(256, unpacked.transfer_size);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 8: Advertisement with request_id ───────────────────────────
|
||||||
|
|
||||||
|
void testAdvertisementWithRequestId() {
|
||||||
|
RNS::ResourceAdvertisement adv;
|
||||||
|
adv.transfer_size = 512;
|
||||||
|
adv.data_size = 400;
|
||||||
|
adv.num_parts = 2;
|
||||||
|
memset(adv.resource_hash, 0x33, 32);
|
||||||
|
memset(adv.random_hash, 0x44, 4);
|
||||||
|
memset(adv.original_hash, 0x33, 32);
|
||||||
|
adv.request_id = RNS::Bytes((uint8_t*)"\xDE\xAD\xBE\xEF", 4);
|
||||||
|
adv.hashmap = RNS::Bytes((uint8_t*)"\x01\x02\x03\x04\x05\x06\x07\x08", 8);
|
||||||
|
|
||||||
|
RNS::Bytes packed = adv.pack();
|
||||||
|
|
||||||
|
RNS::ResourceAdvertisement unpacked;
|
||||||
|
TEST_ASSERT_TRUE(RNS::ResourceAdvertisement::unpack(packed, unpacked));
|
||||||
|
TEST_ASSERT_EQUAL(4, unpacked.request_id.size());
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY("\xDE\xAD\xBE\xEF", unpacked.request_id.data(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 9: bz2 compress/decompress roundtrip ───────────────────────
|
||||||
|
|
||||||
|
void testBz2CompressDecompress() {
|
||||||
|
// Create compressible data (repeated pattern)
|
||||||
|
std::string repeated(1000, 'A');
|
||||||
|
RNS::Bytes data((const uint8_t*)repeated.data(), repeated.size());
|
||||||
|
|
||||||
|
RNS::Bytes compressed = RNS::Compression::bz2_compress(data);
|
||||||
|
TEST_ASSERT_TRUE(compressed.size() > 0);
|
||||||
|
TEST_ASSERT_TRUE(compressed.size() < data.size()); // Should compress well
|
||||||
|
|
||||||
|
printf("\n=== BZ2_COMPRESS ===\n");
|
||||||
|
printf(" original: %d bytes, compressed: %d bytes\n", (int)data.size(), (int)compressed.size());
|
||||||
|
|
||||||
|
RNS::Bytes decompressed = RNS::Compression::bz2_decompress(compressed);
|
||||||
|
TEST_ASSERT_EQUAL(data.size(), decompressed.size());
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(data.data(), decompressed.data(), data.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 10: try_compress only compresses if beneficial ─────────────
|
||||||
|
|
||||||
|
void testTryCompress() {
|
||||||
|
// Highly compressible data
|
||||||
|
std::string big(2000, 'X');
|
||||||
|
RNS::Bytes compressible((const uint8_t*)big.data(), big.size());
|
||||||
|
auto result = RNS::Compression::try_compress(compressible);
|
||||||
|
TEST_ASSERT_TRUE(result.compressed);
|
||||||
|
TEST_ASSERT_TRUE(result.data.size() < compressible.size());
|
||||||
|
|
||||||
|
// Small random-like data (may not compress)
|
||||||
|
uint8_t random_data[50];
|
||||||
|
for (int i = 0; i < 50; i++) random_data[i] = (uint8_t)(i * 37 + 13);
|
||||||
|
RNS::Bytes small_data(random_data, 50);
|
||||||
|
auto result2 = RNS::Compression::try_compress(small_data);
|
||||||
|
// Either compressed or not — both are valid
|
||||||
|
TEST_ASSERT_TRUE(result2.data.size() > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Test 11: bz2 output matches Python/Rust format ──────────────────
|
||||||
|
|
||||||
|
void testBz2CrossPlatformFormat() {
|
||||||
|
// bz2 compressed data always starts with "BZh" magic bytes
|
||||||
|
std::string test_data = "Hello from C++ bz2 test!";
|
||||||
|
RNS::Bytes data((const uint8_t*)test_data.data(), test_data.size());
|
||||||
|
|
||||||
|
// Need larger data for compression to be beneficial
|
||||||
|
RNS::Bytes big_data;
|
||||||
|
for (int i = 0; i < 50; i++) big_data.append(data.data(), data.size());
|
||||||
|
|
||||||
|
RNS::Bytes compressed = RNS::Compression::bz2_compress(big_data);
|
||||||
|
TEST_ASSERT_TRUE(compressed.size() >= 3);
|
||||||
|
|
||||||
|
// BZ2 magic: "BZh" (0x42, 0x5A, 0x68)
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x42, compressed.data()[0]); // 'B'
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x5A, compressed.data()[1]); // 'Z'
|
||||||
|
TEST_ASSERT_EQUAL_UINT8(0x68, compressed.data()[2]); // 'h'
|
||||||
|
|
||||||
|
printf("\n=== BZ2_CROSS_PLATFORM ===\n");
|
||||||
|
printf(" original: %d bytes, compressed: %d bytes\n", (int)big_data.size(), (int)compressed.size());
|
||||||
|
printf(" magic: %c%c%c (BZh)\n", compressed.data()[0], compressed.data()[1], compressed.data()[2]);
|
||||||
|
|
||||||
|
// Verify roundtrip
|
||||||
|
RNS::Bytes decompressed = RNS::Compression::bz2_decompress(compressed);
|
||||||
|
TEST_ASSERT_EQUAL(big_data.size(), decompressed.size());
|
||||||
|
TEST_ASSERT_EQUAL_MEMORY(big_data.data(), decompressed.data(), big_data.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Runner ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
void setUp() {}
|
||||||
|
void tearDown() {}
|
||||||
|
|
||||||
|
int main(int argc, char **argv) {
|
||||||
|
UNITY_BEGIN();
|
||||||
|
RUN_TEST(testResourceAdvertisementPackUnpack);
|
||||||
|
RUN_TEST(testMapHashComputation);
|
||||||
|
RUN_TEST(testResourceHashComputation);
|
||||||
|
RUN_TEST(testExpectedProof);
|
||||||
|
RUN_TEST(testGetMapHashes);
|
||||||
|
RUN_TEST(testResourceFlags);
|
||||||
|
RUN_TEST(testAdvertisementNilRequestId);
|
||||||
|
RUN_TEST(testAdvertisementWithRequestId);
|
||||||
|
RUN_TEST(testBz2CompressDecompress);
|
||||||
|
RUN_TEST(testTryCompress);
|
||||||
|
RUN_TEST(testBz2CrossPlatformFormat);
|
||||||
|
return UNITY_END();
|
||||||
|
}
|
||||||
@@ -62,7 +62,7 @@ void testSerializeDestinationTable() {
|
|||||||
RNS::Transport::DestinationEntry entry_one;
|
RNS::Transport::DestinationEntry entry_one;
|
||||||
entry_one._timestamp = 1.0;
|
entry_one._timestamp = 1.0;
|
||||||
entry_one._received_from = received;
|
entry_one._received_from = received;
|
||||||
entry_one._receiving_interface = test_interface.get_hash();
|
entry_one.receiving_interface_hash(test_interface.get_hash());
|
||||||
entry_one._random_blobs = blobs;
|
entry_one._random_blobs = blobs;
|
||||||
RNS::Bytes one;
|
RNS::Bytes one;
|
||||||
one.assignHex("1111111111111111");
|
one.assignHex("1111111111111111");
|
||||||
@@ -71,7 +71,7 @@ void testSerializeDestinationTable() {
|
|||||||
RNS::Transport::DestinationEntry entry_two;
|
RNS::Transport::DestinationEntry entry_two;
|
||||||
entry_two._timestamp = 2.0;
|
entry_two._timestamp = 2.0;
|
||||||
entry_two._received_from = received;
|
entry_two._received_from = received;
|
||||||
entry_two._receiving_interface = test_interface.get_hash();
|
entry_two.receiving_interface_hash(test_interface.get_hash());
|
||||||
entry_two._random_blobs = blobs;
|
entry_two._random_blobs = blobs;
|
||||||
RNS::Bytes two;
|
RNS::Bytes two;
|
||||||
two.assignHex("2222222222222222");
|
two.assignHex("2222222222222222");
|
||||||
@@ -81,7 +81,7 @@ void testSerializeDestinationTable() {
|
|||||||
RNS::Transport::DestinationEntry entry;
|
RNS::Transport::DestinationEntry entry;
|
||||||
entry._timestamp = 1.0;
|
entry._timestamp = 1.0;
|
||||||
entry._received_from = received;
|
entry._received_from = received;
|
||||||
entry._receiving_interface = test_interface.get_hash();
|
entry.receiving_interface_hash(test_interface.get_hash());
|
||||||
entry._random_blobs = blobs;
|
entry._random_blobs = blobs;
|
||||||
RNS::Bytes hash;
|
RNS::Bytes hash;
|
||||||
hash.assign(std::to_string(1000000000000001 + n).c_str());
|
hash.assign(std::to_string(1000000000000001 + n).c_str());
|
||||||
|
|||||||
@@ -226,6 +226,26 @@ void test_receipt_timeout_callback() {
|
|||||||
// Transport hashlist tests
|
// Transport hashlist tests
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
|
void test_discover_paths_for_matches_upstream_modes() {
|
||||||
|
uint8_t discover_modes = RNS::Interface::DISCOVER_PATHS_FOR;
|
||||||
|
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(
|
||||||
|
(discover_modes & RNS::Type::Interface::MODE_ACCESS_POINT) > 0,
|
||||||
|
"Access point interfaces should discover unknown paths");
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(
|
||||||
|
(discover_modes & RNS::Type::Interface::MODE_GATEWAY) > 0,
|
||||||
|
"Gateway interfaces should discover unknown paths");
|
||||||
|
TEST_ASSERT_TRUE_MESSAGE(
|
||||||
|
(discover_modes & RNS::Type::Interface::MODE_ROAMING) > 0,
|
||||||
|
"Roaming interfaces should discover unknown paths");
|
||||||
|
TEST_ASSERT_FALSE_MESSAGE(
|
||||||
|
(discover_modes & RNS::Type::Interface::MODE_FULL) > 0,
|
||||||
|
"Full interfaces should not discover paths on behalf of peers");
|
||||||
|
TEST_ASSERT_FALSE_MESSAGE(
|
||||||
|
(discover_modes & RNS::Type::Interface::MODE_BOUNDARY) > 0,
|
||||||
|
"Boundary interfaces should not discover paths on behalf of peers");
|
||||||
|
}
|
||||||
|
|
||||||
void test_hashlist_basic() {
|
void test_hashlist_basic() {
|
||||||
// Send enough packets that the hashlist should grow
|
// Send enough packets that the hashlist should grow
|
||||||
initRNS();
|
initRNS();
|
||||||
@@ -580,6 +600,8 @@ void tearDown(void) {}
|
|||||||
int runUnityTests(void) {
|
int runUnityTests(void) {
|
||||||
UNITY_BEGIN();
|
UNITY_BEGIN();
|
||||||
|
|
||||||
|
RUN_TEST(test_discover_paths_for_matches_upstream_modes);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
// Transport receipt lifecycle
|
// Transport receipt lifecycle
|
||||||
RUN_TEST(test_receipt_creation_and_culling);
|
RUN_TEST(test_receipt_creation_and_culling);
|
||||||
|
|||||||
Reference in new issue
Block a user