Author SHA1 Message Date
DeFiDude 1acd840182 Fix known_destinations LRU cull, revert endpoint caching regression, add proof diagnostics
Identity.cpp: OS::time() on Arduino returns seconds since boot, not epoch.
Persisted known_destinations entries carried timestamps from the previous
session (e.g., 5000s). On a fresh boot at 31s uptime, new announces got
timestamp 31.0 — the LRU cull saw this as "oldest" and removed it
immediately. Identity::recall() could never find the destination, breaking
all outbound LXMF messaging. Fix: normalize loaded timestamps to [1, now-1]
preserving relative order, so fresh announces are always newest.

Transport.cpp: Revert b44d374's endpoint caching skip — Ratdeck runs as
endpoint and needs cached announces for path table persistence across
reboots. Restore immediate cull behavior. Add DIAG-PROOF logging for
tracing link proof broadcast routing across interfaces.
2026-03-20 19:36:06 -06:00
DeFiDude b44d3743ec Fix announce flood performance: skip endpoint caching, defer culls, fix clean_caches
- Guard announce cache_packet(force=true) with transport_enabled() so
  endpoints skip 300-900ms flash writes per announce
- Defer cull_path_table/cull_announce_table until 10% over capacity
  instead of after every insert
- Rewrite clean_caches: endpoints just wipe stale files in one pass;
  transport nodes use std::set for O(N+M) instead of O(N*M) lookups
2026-03-19 15:24:10 -06:00
DeFiDude 813d9095d7 Fix PKCS7 padding, identity persistence, and packet routing 2026-03-13 04:20:04 -06:00
DeFiDude bb291795da Fix TCP outbound: stop get_path() from destroying valid routes + PSRAM allocator
- get_path(): Remove announce_packet null check that destroyed valid path
  entries when cache deserialization failed under heap pressure. Routing
  fields (_received_from, _hops, receiving_interface) are valid without it.
- hops_to(): Direct path table lookup instead of get_path() to avoid
  triggering expensive announce_packet lazy load from flash cache.
- path_request_handler(): Guard against null announce_packet gracefully.
- Persistence: Add PSRAM allocator for ArduinoJson JsonDocument on ESP32
  boards with PSRAM, preventing deserialization failures when heap is low.
2026-03-11 14:48:19 -06:00
DeFiDude bc33c0af64 Revert hops >= 1 to > 1 in Transport::outbound()
The >= 1 change made the hops==1 branch (hub topology) convert
packets to Header2 with potentially wrong transport_id before
send_outgoing() could apply the correct learned hub transport_id.
Reverting to > 1 matches the original Python logic and lets
hops==1 packets fall through as Header1 for proper wrapping.
2026-03-11 13:43:11 -06:00
DeFiDude 184e6b0250 Skip announce packet caching on non-transport endpoints
Only cache announce packets when transport is enabled, preventing
unnecessary storage on endpoint-only nodes that don't rebroadcast.
2026-03-10 22:40:57 -06:00
DeFiDude af9fbab780 Fix boot loop: Identity::remember() stale timestamp causes cull crash
std::map::insert() is a no-op for existing keys, so identities loaded
from persisted known_destinations kept their old timestamps. When
cull_known_destinations() ran after insert, it removed the "stale"
entry that was just validated — causing Identity::recall() to fail
and hexhash() to assert on a null identity.

Fix: use insert_or_assign() to always refresh the timestamp.

Also reverts the dead-code needs_transport_headers() virtual method
(the else-if at Transport.cpp:826 is unreachable because hops>=1
already catches hops==1 in the preceding if block).
2026-03-10 11:22:05 -06:00
DeFiDude 79271a018b Add needs_transport_headers() for TCP hub messaging fix
TCP interfaces behind a hub need HEADER_2 transport wrapping even at
hops==1, since the hub can't forward raw HEADER_1 packets. Added virtual
needs_transport_headers() to InterfaceImpl (defaults to false) so TCP
subclasses can override it without setting is_connected_to_shared_instance
(which would brick the device by skipping all Reticulum::loop processing).
2026-03-10 00:49:56 -06:00
DeFiDude 3bc64abbde Add Identity as friend of Reticulum for storagepath access 2026-03-08 22:42:34 -06:00
DeFiDude 425c2a9907 Fix TCP messaging via transport nodes and implement known_destinations persistence 2026-03-08 21:56:30 -06:00
Chad Attermann 392363c1b0 Added another missing header for Linux builds 2026-03-06 17:40:55 -07:00
Chad Attermann 491fbd034e Fixed unit test failures in Linux. 2026-03-06 17:25:41 -07:00
Chad Attermann c69087ba40 Merge pull request #31 from attermann/psram_allocator
Introduces a flexible two-class allocator architecture (RNS_DEFAULT_ALLOCATOR and RNS_CONTAINER_ALLOCATOR) supporting heap, PSRAM, and TLSF pool variants for fine-grained control over embedded memory layout.

New Memory.h/cpp with ContainerAllocator, heap/PSRAM/pool allocator types, and heap stats reporting
IdentityTable and PathTable now use ContainerAllocator
Replaced RNS_USE_TLSF/RNS_USE_ALLOCATOR/RNS_USE_PSRAM flags with per-class allocator flags (RNS_DEFAULT_ALLOCATOR, RNS_CONTAINER_ALLOCATOR)
Added ESP32 PSRAM allocator support (RNS_PSRAM_ALLOCATOR, RNS_PSRAM_POOL_ALLOCATOR)
Added Transport::get_path()/remove_path() helpers
Added loop callback (set_loop_callback) to enable more responsive app during long operations (like clean_cache)
Aded guard against re-entrancy to clean_cache()
Added callback option to list_directory() to avoid heap allocation
Added OOM auto-restart (ESP.restart/NVIC_SystemReset) in Interface send/receive and Reticulum loop.
Renamed setLogCallback to set_log_callback
Made Link/Identity static members private
Added native14 env to CI and platformio.ini
Bumped version to 0.2.10
2026-03-06 17:10:37 -07:00
Chad Attermann 4d6f0b9de2 Added dual-class PSRAM/TLSF allocator system and refactored memory management
Introduces a flexible two-class allocator architecture (RNS_DEFAULT_ALLOCATOR and RNS_CONTAINER_ALLOCATOR) supporting heap, PSRAM, and TLSF pool variants for fine-grained control over embedded memory layout.

- New Memory.h/cpp with ContainerAllocator<T>, heap/PSRAM/pool allocator types, and heap stats reporting
- IdentityTable and PathTable now use ContainerAllocator
- Replaced RNS_USE_TLSF/RNS_USE_ALLOCATOR/RNS_USE_PSRAM flags with per-class allocator flags (RNS_DEFAULT_ALLOCATOR, RNS_CONTAINER_ALLOCATOR)
- Added ESP32 PSRAM allocator support (RNS_PSRAM_ALLOCATOR, RNS_PSRAM_POOL_ALLOCATOR)
- Added Transport::get_path()/remove_path() helpers
- Added loop callback (set_loop_callback) to enable more responsive app during long operations (like clean_cache)
- Aded guard against re-entrancy to clean_cache()
- Added callback option to list_directory() to avoid heap allocation
- Added OOM auto-restart (ESP.restart/NVIC_SystemReset) in Interface send/receive and Reticulum loop.
- Renamed setLogCallback to set_log_callback
- Made Link/Identity static members private
- Added native14 env to CI and platformio.ini
- Bumped version to 0.2.10
2026-03-06 16:43:04 -07:00
38 changed files with 2376 additions and 1077 deletions

No files matched your search

+1 -1
View File
@@ -11,7 +11,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
env: [native, native17, native20]
env: [native, native14, native17, native20]
steps:
- uses: actions/checkout@v4
+27 -3
View File
@@ -18,9 +18,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_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_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)
- `-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).
## Memory Management Build Options
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
@@ -247,14 +247,13 @@ void UniversalFileSystem::listDir(const char* dir) {
//if (!file) {
File* file = new File(SPIFFS.open(file_path, mode));
if (file == nullptr || !(*file)) {
if (file != nullptr) delete file;
ERRORF("open_file: failed to open output file %s", file_path);
return {RNS::Type::NONE};
}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new UniversalFileStream(file));
#elif BOARD_NRF52
//File file = File(InternalFS);
File* file = new File(InternalFS);
int mode;
if (file_mode == RNS::FileStream::MODE_READ) {
mode = FILE_O_READ;
@@ -274,7 +273,10 @@ void UniversalFileSystem::listDir(const char* dir) {
ERRORF("open_file: unsupported mode %d", file_mode);
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);
return {RNS::Type::NONE};
}
@@ -430,7 +432,7 @@ void UniversalFileSystem::listDir(const char* dir) {
#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);
std::list<std::string> files;
#ifdef ARDUINO
@@ -447,7 +449,8 @@ void UniversalFileSystem::listDir(const char* dir) {
while (file) {
if (!file.isDirectory()) {
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
file.close();
@@ -42,7 +42,7 @@ public:
virtual bool directory_exists(const char* directory_path);
virtual bool create_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_available();
+1 -1
View File
@@ -1,6 +1,6 @@
{
"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",
"keywords": "reticulum, rns, mesh, embedded, mcu, esp32, nrf52, native",
"repository":
+1 -1
View File
@@ -1,5 +1,5 @@
name=microReticulum
version=0.2.9
version=0.2.10
author=Chad Attermann <attermann@gmail.com>
maintainer=Chad Attermann <attermann@gmail.com>
sentence=Port of Reticulum Network Stack to C++
+45 -16
View File
@@ -45,6 +45,19 @@ lib_deps =
${env.lib_deps}
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]
platform = native
build_unflags =
@@ -73,9 +86,13 @@ lib_compat_mode = off
[env:native_debug]
platform = native
build_unflags =
${env.build_unflags}
-std=gnu++11
build_flags =
${env.build_flags}
-std=gnu++11
;-std=gnu++11
-std=gnu++17
-DNATIVE
; CBA TEST
;-fsanitize=address
@@ -83,31 +100,36 @@ build_flags =
-g
;-O1
-O0
;-DRNS_MEM_LOG
-DRNS_USE_ALLOCATOR=1
-DRNS_USE_TLSF=1
;-DBOARD_HAS_PSRAM=1
;-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_ALLOCATOR
-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
;-DRNS_TLSF_BUFFER_SIZE=81920
;-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
;-DRNS_MEM_LOG
lib_deps =
${env.lib_deps}
lib_compat_mode = off
test_flags = -vvv
[env:embedded]
framework = arduino
upload_speed = 460800
build_unflags =
${env.build_unflags}
;-std=gnu++11
-std=gnu++11
;-fno-rtti
build_flags =
${env.build_flags}
;-std=gnu++17
-std=gnu++17
lib_deps =
${env.lib_deps}
@@ -168,6 +190,13 @@ build_flags =
-DBOARD_ESP32
-DMSGPACK_USE_BOOST=OFF
-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 =
${env:embedded.lib_deps}
monitor_filters = esp32_exception_decoder
@@ -184,8 +213,8 @@ build_flags =
-I variants/rak4630
-fexceptions
-DBOARD_NRF52
-DRNS_USE_ALLOCATOR=1
-DRNS_USE_TLSF=1
-DRNS_DEFAULT_ALLOCATOR=RNS_HEAP_POOL_ALLOCATOR
-DRNS_HEAP_POOL_BUFFER_SIZE=204800
-DMSGPACK_USE_BOOST=OFF
lib_deps =
${env:embedded.lib_deps}
+4 -2
View File
@@ -1,6 +1,7 @@
#pragma once
#include "Log.h"
#include "Utilities/Memory.h"
#include <ArduinoJson.h>
@@ -40,9 +41,9 @@ namespace RNS {
class Bytes {
private:
//typedef std::vector<uint8_t> Data;
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>;
public:
@@ -433,6 +434,7 @@ inline RNS::Bytes& operator << (RNS::Bytes& lhbytes, const char* rhstr) {
return lhbytes;
}
//CBA TODO Standardize where custom object de/serialization lives
namespace ArduinoJson {
// Serialize
inline bool convertToJson(const RNS::Bytes& src, JsonVariant dst) {
+2 -5
View File
@@ -31,13 +31,10 @@ namespace RNS { namespace Cryptography {
//DEBUGF("PKCS7::pad: len: %zu", len);
size_t padlen = bs - (len % bs);
//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])
//uint8_t pad[padlen] = {0};
uint8_t pad[padlen];
memset(pad, 0, padlen);
// set last byte of padding array to size of padding
pad[padlen-1] = (uint8_t)padlen;
memset(pad, (uint8_t)padlen, padlen);
// concatenate data with padding
//p return data+v*padlen
data.append(pad, padlen);
+22 -5
View File
@@ -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) {
//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
std::string expanded = expand_name({Type::NONE}, 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) {
TRACEF("[DIAG] Dest::hash: identity_hash=%s", identity.hash().toHex().c_str());
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]
// CBA TODO valid alternative?
//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,17 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
}
else {
Bytes destination_hash = _object->_hash;
//p random_hash = Identity::get_random_hash()[0:5] << int(time.time()).to_bytes(5, "big")
// CBA TODO add in time to random hash
Bytes random_hash = Cryptography::random(Type::Identity::RANDOM_HASH_LENGTH/8);
//p random_hash = Identity::get_random_hash()[0:5] + int(time.time()).to_bytes(5, "big")
// 5 random bytes + 5 big-endian timestamp bytes (matches Python reference)
Bytes random_part = Cryptography::random(5);
uint64_t ts = (uint64_t)OS::time();
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);
if (new_app_data.empty() && !_object->_default_app_data.empty()) {
@@ -431,7 +447,8 @@ Encrypts information for ``RNS.Destination.SINGLE`` or ``RNS.Destination.GROUP``
}
if (_object->_type == SINGLE && _object->_identity) {
return _object->_identity.encrypt(data);
Bytes ratchet = Identity::get_ratchet(_object->_hash);
return _object->_identity.encrypt(data, ratchet);
}
// TODO
+12 -2
View File
@@ -8,12 +8,19 @@
#include <list>
#include <memory>
#include <cassert>
#include <functional>
#include <stdint.h>
namespace RNS {
class FileSystemImpl {
public:
struct Callbacks {
//using DirectoryListing = void(*)(const char* file_name);
using DirectoryListing = std::function<void(const char*)>;
};
protected:
FileSystemImpl() { MEMF("FileSystem::FileSystemImpl object created, this: 0x%X", this); }
public:
@@ -31,7 +38,7 @@ namespace RNS {
virtual bool directory_exists(const char* directory_path) = 0;
virtual bool create_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_available() = 0;
@@ -40,6 +47,9 @@ namespace RNS {
class FileSystem {
public:
using Callbacks = FileSystemImpl::Callbacks;
public:
FileSystem(Type::NoneConstructor none) {
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 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 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_available() { assert(_impl); return _impl->storage_available(); }
+243 -76
View File
@@ -23,11 +23,12 @@ using namespace RNS::Utilities;
#define RNS_KNOWN_DESTINATIONS_MAX 100
#endif
/*static*/ std::map<Bytes, Identity::IdentityEntry> Identity::_known_destinations;
/*static*/ Identity::IdentityTable Identity::_known_destinations;
/*static*/ bool Identity::_saving_known_destinations = false;
// CBA
// CBA ACCUMULATES
/*static*/ uint16_t Identity::_known_destinations_maxsize = RNS_KNOWN_DESTINATIONS_MAX;
/*static*/ Identity::RatchetTable Identity::_known_ratchets;
Identity::Identity(bool create_keys /*= true*/) : _object(new Object()) {
if (create_keys) {
@@ -200,7 +201,10 @@ 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};
// CBA ACCUMULATES
try {
_known_destinations.insert({destination_hash, {OS::time(), packet_hash, public_key, app_data}});
// Use insert_or_assign so the timestamp is always refreshed.
// Plain insert() is a no-op for existing keys, leaving the old
// timestamp — cull then removes the "stale" entry we just validated.
_known_destinations.insert_or_assign(destination_hash, IdentityEntry{OS::time(), packet_hash, public_key, app_data});
// CBA IMMEDIATE CULL
cull_known_destinations();
}
@@ -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
// deserialize and serialize the entire table on every
// save, but the only changes. It might be possible to
// simply overwrite on exit now that every local client
// disconnect triggers a data persist.
/*
Binary format for known_destinations persistence:
[uint16_t entry_count]
For each entry:
[uint16_t dest_hash_len][dest_hash bytes]
[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;
try {
if (_saving_known_destinations) {
@@ -290,39 +299,47 @@ Recall last heard app_data for a destination hash.
_saving_known_destinations = true;
double save_start = OS::time();
std::map<Bytes, IdentityEntry> storage_known_destinations;
// TODO
/*
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();
}
if (_known_destinations.empty()) {
_saving_known_destinations = false;
return true;
}
// TODO
/*
DEBUGF("Saving %zu known destinations to storage...", _known_destinations.size());
file = open(RNS.Reticulum.storagepath+"/known_destinations","wb")
umsgpack.dump(Identity.known_destinations, file)
file.close()
DEBUGF("Saved known destinations to storage in %.3f seconds", OS::round(OS::time() - save_start, 3));
*/
// Serialize to binary buffer
Bytes buf(1024);
uint16_t count = (uint16_t)_known_destinations.size();
buf.append((const uint8_t*)&count, sizeof(count));
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) {
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() {
// TODO
/*
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()
char filepath[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(filepath, Type::Reticulum::FILEPATH_MAXSIZE, "%s/known_destinations", Reticulum::_storagepath);
Identity.known_destinations = {}
for known_destination in loaded_known_destinations:
if len(known_destination) == RNS.Reticulum.TRUNCATED_HASHLENGTH//8:
Identity.known_destinations[known_destination] = loaded_known_destinations[known_destination]
if (!OS::file_exists(filepath)) {
VERBOSE("Destinations file does not exist, no known destinations loaded");
return;
}
RNS.log("Loaded "+str(len(Identity.known_destinations))+" known destination from storage", RNS.LOG_VERBOSE)
except:
RNS.log("Error loading known destinations from disk, file will be recreated on exit", RNS.LOG_ERROR)
else:
RNS.log("Destinations file does not exist, no known destinations loaded", RNS.LOG_VERBOSE)
*/
try {
Bytes buf;
if (OS::read_file(filepath, buf) == 0) {
ERROR("Failed to read known destinations file");
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(&timestamp, 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() {
@@ -407,27 +512,42 @@ Recall last heard app_data for a destination hash.
try {
if (packet.packet_type() == Type::Packet::ANNOUNCE) {
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);
//TRACEF("Identity::validate_announce: public_key: %s", public_key.toHex().c_str());
Bytes name_hash = packet.data().mid(KEYSIZE/8, NAME_HASH_LENGTH/8);
//TRACEF("Identity::validate_announce: name_hash: %s", name_hash.toHex().c_str());
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 signature = packet.data().mid(KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8, SIGLENGTH/8);
//TRACEF("Identity::validate_announce: signature: %s", signature.toHex().c_str());
size_t keysize = KEYSIZE/8;
size_t ratchetsize = Type::Identity::RATCHETSIZE/8;
size_t name_hash_len = NAME_HASH_LENGTH/8;
size_t sig_len = SIGLENGTH/8;
Bytes public_key = packet.data().left(keysize);
Bytes name_hash = packet.data().mid(keysize, name_hash_len);
Bytes random_hash = packet.data().mid(keysize + name_hash_len, 10);
Bytes ratchet;
Bytes signature;
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;
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());
signed_data << destination_hash << public_key << name_hash << random_hash << ratchet << app_data;
if (packet.data().size() <= KEYSIZE/8 + NAME_HASH_LENGTH/8 + RANDOM_HASH_LENGTH/8 + SIGLENGTH/8) {
if (!ratchet && packet.data().size() <= keysize + name_hash_len + 10 + sig_len) {
app_data.clear();
}
else if (ratchet && packet.data().size() <= keysize + name_hash_len + 10 + ratchetsize + sig_len) {
app_data.clear();
}
@@ -435,8 +555,13 @@ Recall last heard app_data for a destination hash.
announced_identity.load_public_key(public_key);
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 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: expected_hash: %s", expected_hash.toHex().c_str());
@@ -456,7 +581,10 @@ Recall last heard app_data for a destination hash.
}
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;
// TODO
@@ -481,14 +609,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("[DIAG] ANNOUNCE VALID: dest=%s hops=%d ratchet=%s",
packet.destination_hash().toHex().c_str(), packet.hops(),
ratchet ? "YES" : "NO");
return true;
}
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());
return false;
}
}
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());
//p del announced_identity
return false;
@@ -502,6 +639,27 @@ Recall last heard app_data for a destination hash.
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() {
if (!Transport::reticulum() || !Transport::reticulum().is_connected_to_shared_instance()) {
save_known_destinations();
@@ -519,7 +677,7 @@ Encrypts information for the identity.
:returns: Ciphertext token as *bytes*.
: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);
TRACE("Identity::encrypt: encrypting data...");
if (!_object->_pub) {
@@ -529,9 +687,18 @@ const Bytes Identity::encrypt(const Bytes& plaintext) const {
Bytes ephemeral_pub_bytes = ephemeral_key->public_key()->public_bytes();
TRACEF("Identity::encrypt: ephemeral public key: %s", ephemeral_pub_bytes.toHex().c_str());
// CRYPTO: create shared key for key exchange using own public key
//shared_key = ephemeral_key.exchange(self.pub)
Bytes shared_key = ephemeral_key->exchange(_object->_pub_bytes);
// CRYPTO: create shared key for key exchange
// Use ratchet public key if available for forward secrecy, otherwise identity public key
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());
Bytes derived_key = Cryptography::hkdf(
+13 -3
View File
@@ -7,6 +7,7 @@
#include "Cryptography/Ed25519.h"
#include "Cryptography/X25519.h"
#include "Cryptography/Token.h"
#include "Utilities/Memory.h"
#include <map>
#include <string>
@@ -36,12 +37,17 @@ namespace RNS {
Bytes _public_key;
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:
static std::map<Bytes, IdentityEntry> _known_destinations;
using RatchetTable = std::map<Bytes, Bytes>;
private:
static IdentityTable _known_destinations;
static bool _saving_known_destinations;
// CBA
static uint16_t _known_destinations_maxsize;
static RatchetTable _known_ratchets;
public:
Identity(bool create_keys = true);
@@ -98,7 +104,7 @@ namespace RNS {
inline const Bytes& get_salt() const { assert(_object); return _object->_hash; }
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 sign(const Bytes& message) const;
bool validate(const Bytes& signature, const Bytes& message) const;
@@ -148,6 +154,8 @@ namespace RNS {
}
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 exit_handler();
@@ -197,6 +205,8 @@ namespace RNS {
};
std::shared_ptr<Object> _object;
// CBA For access to private static members by Transport class
friend class Transport;
};
}
+12
View File
@@ -35,6 +35,12 @@ void Interface::send_outgoing(const Bytes& data) {
}
catch (const std::bad_alloc&) {
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) {
ERRORF("Interface::send_outgoing: %s", e.what());
@@ -56,6 +62,12 @@ void Interface::handle_incoming(const Bytes& data) {
}
catch (const std::bad_alloc&) {
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) {
ERRORF("Interface::handle_incoming: %s", e.what());
+1
View File
@@ -82,6 +82,7 @@ namespace RNS {
std::list<AnnounceEntry> _announce_queue;
bool _is_connected_to_shared_instance = false;
bool _is_local_shared_instance = false;
//Bytes _hash;
HInterface _parent_interface;
//Transport& _owner;
+3 -1
View File
@@ -130,7 +130,7 @@ namespace RNS {
friend class Link;
};
public:
private:
static uint8_t resource_strategies;
static std::set<RNS::Type::Link::link_mode> ENABLED_MODES;
static RNS::Type::Link::link_mode MODE_DEFAULT;
@@ -265,6 +265,8 @@ namespace RNS {
protected:
std::shared_ptr<LinkData> _object;
// CBA For access to private static members by LinkData class
friend class LinkData;
};
}
+1 -1
View File
@@ -72,7 +72,7 @@ LogLevel RNS::loglevel() {
return _level;
}
void RNS::setLogCallback(log_callback on_log /*= nullptr*/) {
void RNS::set_log_callback(log_callback on_log /*= nullptr*/) {
_on_log = on_log;
}
+1 -1
View File
@@ -75,7 +75,7 @@ namespace RNS {
void loglevel(LogLevel level);
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);
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); }
+15 -5
View File
@@ -336,11 +336,12 @@ TRACEF("***** Link data: %s", _object->_ciphertext.toHex().c_str());
_object->_ciphertext = _object->_destination.encrypt(_object->_data);
TRACEF("***** Destination Data: %s", _object->_ciphertext.toHex().c_str());
}
// CBA RATCHET
/*p TODO
if hasattr(self.destination, "latest_ratchet_id"):
self.ratchet_id = self.destination.latest_ratchet_id
*/
{
Bytes ratchet_pub = Identity::get_ratchet(_object->_destination.hash());
if (ratchet_pub) {
_object->_ratchet_id = Identity::full_hash(ratchet_pub).left(Type::Identity::NAME_HASH_LENGTH/8);
}
}
_object->_encrypted = true;
}
}
@@ -366,6 +367,15 @@ TRACEF("***** Destination Data: %s", _object->_ciphertext.toHex().c_str());
_object->_header << (uint8_t)_object->_context;
_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->_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");
}
+45 -34
View File
@@ -2,6 +2,7 @@
#include "Transport.h"
#include "Log.h"
#include "Utilities/Memory.h"
//#include <TransistorNoiseSource.h>
#include <RNG.h>
@@ -29,6 +30,9 @@ using namespace RNS::Utilities;
/*static*/ bool Reticulum::__allow_probes = 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
// Noise source to seed the random number generator.
//TransistorNoiseSource noise(A1);
@@ -115,32 +119,6 @@ Reticulum::Reticulum() : _object(new Object()) {
strncpy(_cachepath, "./cache", FILEPATH_MAXSIZE);
#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
if not os.path.isdir(Reticulum.storagepath):
os.makedirs(Reticulum.storagepath)
@@ -196,11 +174,37 @@ Reticulum::Reticulum() : _object(new Object()) {
void Reticulum::start() {
INFOF("Total memory: %zu", OS::heap_size());
INFOF("Total memory: %zu", Memory::heap_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...");
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() {
@@ -212,7 +216,6 @@ void Reticulum::loop() {
// Perform Reticulum housekeeping
if (OS::time() > (_object->_jobs_last_run + JOB_INTERVAL)) {
jobs();
_object->_jobs_last_run = OS::time();
}
// Perform interface processing
@@ -235,6 +238,12 @@ void Reticulum::loop() {
}
catch (const std::bad_alloc&) {
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) {
ERRORF("Reticulum::loop: %s", e.what());
@@ -247,8 +256,8 @@ void Reticulum::jobs() {
#if 1
// CBA Detect low-memory condition and reset
if (OS::heap_size() > 0) {
uint8_t remaining = (uint8_t)((double)OS::heap_available() / (double)OS::heap_size() * 100.0);
if (Memory::heap_size() > 0) {
uint8_t remaining = (uint8_t)((double)Memory::heap_available() / (double)Memory::heap_size() * 100.0);
if (remaining <= 2) {
HEADF(LOG_CRITICAL, "DETECTED LOW-MEMORY CONDITION (%d%%), RESETTING!!!", remaining);
persist_data();
@@ -262,14 +271,15 @@ void Reticulum::jobs() {
}
#endif
if (now > _object->_last_cache_clean + CLEAN_INTERVAL) {
if (now > _object->_last_cache_clean + _clean_interval) {
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();
}
_object->_jobs_last_run = OS::time();
}
// CBA TODO
@@ -363,6 +373,7 @@ void Reticulum::clean_caches() {
Identity::cull_known_destinations();
#endif
_object->_last_cache_clean = OS::time();
}
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 = []
for dst_hash in Transport::destination_table:
+12 -2
View File
@@ -16,7 +16,7 @@ namespace RNS {
class Reticulum {
public:
private:
//z router = None
//z config = None
@@ -42,6 +42,9 @@ namespace RNS {
static bool __allow_probes;
static bool panic_on_interface_error;
static uint16_t _persist_interval;
static uint16_t _clean_interval;
public:
// Return the currently running Reticulum instance
inline static const Reticulum& get_instance() { return _instance; }
@@ -81,7 +84,7 @@ namespace RNS {
//void __create_default_config();
//void rpc_loop();
//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;
bool drop_path(const Bytes& destination);
uint16_t drop_all_via(const Bytes& transport_hash);
@@ -144,6 +147,10 @@ namespace RNS {
// getters/setters
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:
class Object {
@@ -177,6 +184,9 @@ namespace RNS {
};
std::shared_ptr<Object> _object;
// CBA For access to private static members by Transport class
friend class Transport;
friend class Identity;
};
}
+160 -312
View File
@@ -35,29 +35,18 @@ using namespace RNS::Utilities;
#define RNS_PR_TAGS_MAX 32
#endif
#if defined(INTERFACES_SET)
///*static*/ std::set<std::reference_wrapper<const Interface>, std::less<const Interface>> Transport::_interfaces;
/*static*/ std::set<std::reference_wrapper<Interface>, std::less<Interface>> Transport::_interfaces;
#elif defined(INTERFACES_LIST)
/*static*/ std::list<std::reference_wrapper<Interface>> Transport::_interfaces;
#elif defined(INTERFACES_MAP)
/*static*/ std::map<Bytes, Interface&> Transport::_interfaces;
#endif
#if defined(DESTINATIONS_SET)
/*static*/ std::set<Destination> Transport::_destinations;
#elif defined(DESTINATIONS_MAP)
/*static*/ std::map<Bytes, Destination> Transport::_destinations;
#endif
/*static*/ std::set<Link> Transport::_pending_links;
/*static*/ std::set<Link> Transport::_active_links;
/*static*/ std::set<Bytes> Transport::_packet_hashlist;
/*static*/ std::list<PacketReceipt> Transport::_receipts;
/*static*/ std::map<Bytes, Transport::AnnounceEntry> Transport::_announce_table;
/*static*/ std::map<Bytes, Transport::DestinationEntry> Transport::_path_table;
/*static*/ Transport::AnnounceTable Transport::_announce_table;
/*static*/ Transport::PathTable Transport::_path_table;
/*static*/ std::map<Bytes, Transport::ReverseEntry> Transport::_reverse_table;
/*static*/ std::map<Bytes, Transport::LinkEntry> Transport::_link_table;
/*static*/ std::map<Bytes, Transport::AnnounceEntry> Transport::_held_announces;
/*static*/ Transport::AnnounceTable Transport::_held_announces;
/*static*/ std::set<HAnnounceHandler> Transport::_announce_handlers;
/*static*/ std::map<Bytes, Transport::TunnelEntry> Transport::_tunnels;
/*static*/ std::map<Bytes, Transport::RateEntry> Transport::_announce_rate_table;
@@ -123,8 +112,13 @@ using namespace RNS::Utilities;
/*static*/ uint32_t Transport::_packets_received = 0;
/*static*/ uint32_t Transport::_destinations_added = 0;
/*static*/ size_t Transport::_last_memory = 0;
/*static*/ size_t Transport::_last_psram = 0;
/*static*/ size_t Transport::_last_flash = 0;
/*static*/ bool Transport::cleaning_caches = false;
Transport::DestinationEntry empty_destination_entry;
/*static*/ void Transport::start(const Reticulum& reticulum_instance) {
INFO("Transport starting...");
_jobs_running = true;
@@ -216,11 +210,15 @@ using namespace RNS::Utilities;
if (Reticulum::transport_enabled()) {
INFO("Transport mode is enabled");
// Read in path table and then write and clean in case any entries are invalid
// Read in path table
read_path_table();
DEBUG("Writing path table and cleaning caches to clean-up any orphaned paths/files");
write_path_table();
clean_caches();
// CBA The following write and clean is very resource intensive so skip at startup
// and let a later (optimized) scheduled write and clean take care of it.
// Write path table back and clean caches in case any entries are invalid
//DEBUG("Writing path table and cleaning caches to clean-up any orphaned paths/files");
//write_path_table();
//clean_caches();
// Read in tunnel table
read_tunnel_table();
@@ -781,10 +779,14 @@ using namespace RNS::Utilities;
// Check if we have a known path for the destination in the path table
//if packet.packet_type != RNS.Packet.ANNOUNCE and packet.destination.type != RNS.Destination.PLAIN and packet.destination.type != RNS.Destination.GROUP and packet.destination_hash in Transport.destination_table:
if (packet.packet_type() != Type::Packet::ANNOUNCE && packet.destination().type() != Type::Destination::PLAIN && packet.destination().type() != Type::Destination::GROUP && _path_table.find(packet.destination_hash()) != _path_table.end()) {
auto& destination_entry = get_path(packet.destination_hash());
if (packet.packet_type() != Type::Packet::ANNOUNCE && packet.destination().type() != Type::Destination::PLAIN && packet.destination().type() != Type::Destination::GROUP && destination_entry) {
TRACE("Transport::outbound: Path to destination is known");
TRACEF("[DIAG] OUTBOUND: path found dest=%.16s hops=%d rf=%.16s iface=%s",
packet.destination_hash().toHex().c_str(), destination_entry._hops,
destination_entry._received_from.toHex().c_str(),
destination_entry.receiving_interface().toString().c_str());
//outbound_interface = Transport.destination_table[packet.destination_hash][5]
DestinationEntry destination_entry = (*_path_table.find(packet.destination_hash())).second;
Interface outbound_interface = destination_entry.receiving_interface();
// If there's more than one hop to the destination, and we know
@@ -810,6 +812,8 @@ using namespace RNS::Utilities;
new_raw << destination_entry._received_from;
//new_raw += packet.raw[2:]
new_raw << packet.raw().mid(2);
TRACEF("[DIAG] OUTBOUND: H1->H2 wrap (transport hops>1) flags=0x%02x ti=%.16s",
new_flags, destination_entry._received_from.toHex().c_str());
transmit(outbound_interface, new_raw);
//_path_table[packet.destination_hash][0] = time.time()
destination_entry._timestamp = OS::time();
@@ -854,6 +858,8 @@ using namespace RNS::Utilities;
// simply transmit the packet directly on that one.
else {
TRACE("Transport::outbound: Sending packet over directly connected interface...");
TRACEF("[DIAG] OUTBOUND: direct H1 send flags=0x%02x size=%d dest=%.16s",
packet.flags(), (int)packet.raw().size(), packet.destination_hash().toHex().c_str());
transmit(outbound_interface, packet.raw());
sent = true;
}
@@ -864,14 +870,15 @@ using namespace RNS::Utilities;
// interface, or belongs to a link.
else {
TRACE("Transport::outbound: Path to destination is unknown");
TRACEF("[DIAG] OUTBOUND: NO PATH for dest=%.16s, broadcasting H1",
packet.destination_hash().toHex().c_str());
if (packet.packet_type() == Type::Packet::PROOF) {
VERBOSEF("[DIAG-PROOF] Proof entering broadcast: dest=%s iface_count=%d attached=%s",
packet.destination_hash().toHex().c_str(), (int)_interfaces.size(),
packet.attached_interface() ? packet.attached_interface().toString().c_str() : "NONE");
}
bool stored_hash = false;
#if defined(INTERFACES_SET)
for (const Interface& interface : _interfaces) {
#elif defined(INTERFACES_LIST)
for (Interface& interface : _interfaces) {
#elif defined(INTERFACES_MAP)
for (auto& [hash, interface] : _interfaces) {
#endif
TRACEF("Transport::outbound: Checking interface %s", interface.toString().c_str());
if (interface.OUT()) {
bool should_transmit = true;
@@ -903,25 +910,11 @@ using namespace RNS::Utilities;
else if (interface.mode() == Type::Interface::MODE_ROAMING) {
//local_destination = next((d for d in Transport.destinations if d.hash == packet.destination_hash), None)
//Destination local_destination({Type::NONE});
#if defined(DESTINATIONS_SET)
bool found_local = false;
for (auto& destination : _destinations) {
if (destination.hash() == packet.destination_hash()) {
//local_destination = destination;
found_local = true;
break;
}
}
//if local_destination != None:
//if (local_destination) {
if (found_local) {
#elif defined(DESTINATIONS_MAP)
auto iter = _destinations.find(packet.destination_hash());
//if (iter != _destinations.end()) {
// local_destination = (*iter).second;
//}
if (iter != _destinations.end()) {
#endif
TRACE("Allowing announce broadcast on roaming-mode interface from instance-local destination");
}
else {
@@ -954,23 +947,8 @@ using namespace RNS::Utilities;
// next(iterable, default)
// list comprehension: [x for x in xyz if x in a]
// CBA TODO confirm that above pattern just selects the first matching destination
#if defined(DESTINATIONS_SET)
//Destination local_destination({Type::Destination::NONE});
bool found_local = false;
for (auto& destination : _destinations) {
if (destination.hash() == packet.destination_hash()) {
//local_destination = destination;
found_local = true;
break;
}
}
//if local_destination != None:
//if (local_destination) {
if (found_local) {
#elif defined(DESTINATIONS_MAP)
auto iter = _destinations.find(packet.destination_hash());
if (iter != _destinations.end()) {
#endif
TRACE("Allowing announce broadcast on boundary-mode interface from instance-local destination");
}
else {
@@ -1017,11 +995,7 @@ using namespace RNS::Utilities;
uint16_t tx_time = (packet.raw().size() * 8) / interface.bitrate();
wait_time = (tx_time / interface.announce_cap());
}
#if defined(INTERFACES_SET)
const_cast<Interface&>(interface).announce_allowed_at(outbound_time + wait_time);
#else
interface.announce_allowed_at(outbound_time + wait_time);
#endif
}
else {
should_transmit = false;
@@ -1050,12 +1024,8 @@ using namespace RNS::Utilities;
);
queued_announces = (interface.announce_queue().size() > 0);
#if defined(INTERFACES_SET)
const_cast<Interface&>(interface).add_announce(entry);
#else
// CBA ACCUMULATES
interface.add_announce(entry);
#endif
if (!queued_announces) {
double wait_time = std::max(interface.announce_allowed_at() - OS::time(), (double)0);
@@ -1096,6 +1066,10 @@ using namespace RNS::Utilities;
if (should_transmit) {
TRACE("Transport::outbound: Packet transmission allowed");
if (packet.packet_type() == Type::Packet::PROOF) {
VERBOSEF("[DIAG-PROOF] TRANSMITTING proof on %s (%d bytes)",
interface.toString().c_str(), (int)packet.raw().size());
}
if (!stored_hash) {
// CBA ACCUMULATES
_packet_hashlist.insert(packet.packet_hash());
@@ -1109,15 +1083,15 @@ using namespace RNS::Utilities;
// thread.daemon = True
// thread.start()
#if defined(INTERFACES_SET)
transmit(const_cast<Interface&>(interface), packet.raw());
#else
transmit(interface, packet.raw());
#endif
sent = true;
}
else {
TRACE("Transport::outbound: Packet transmission refused");
if (packet.packet_type() == Type::Packet::PROOF) {
VERBOSEF("[DIAG-PROOF] REFUSED proof on %s (should_transmit=false)",
interface.toString().c_str());
}
}
}
}
@@ -1397,9 +1371,8 @@ using namespace RNS::Utilities;
bool for_local_client = false;
bool for_local_client_link = false;
if (packet.packet_type() != Type::Packet::ANNOUNCE) {
auto destination_iter = _path_table.find(packet.destination_hash());
if (destination_iter != _path_table.end()) {
DestinationEntry destination_entry = (*destination_iter).second;
auto& destination_entry = get_path(packet.destination_hash());
if (destination_entry) {
if (destination_entry._hops == 0) {
// Destined for a local destination
for_local_client = true;
@@ -1441,20 +1414,10 @@ using namespace RNS::Utilities;
if (packet.destination_type() == Type::Destination::PLAIN && packet.transport_type() == Type::Transport::BROADCAST) {
// Send to all interfaces except the one the packet was recieved on
if (from_local_client) {
#if defined(INTERFACES_SET)
for (const Interface& interface : _interfaces) {
#elif defined(INTERFACES_LIST)
for (Interface& interface : _interfaces) {
#elif defined(INTERFACES_MAP)
for (auto& [hash, interface] : _interfaces) {
#endif
if (interface != packet.receiving_interface()) {
TRACEF("Transport::inbound: Broadcasting packet on %s", interface.toString().c_str());
#if defined(INTERFACES_SET)
transmit(const_cast<Interface&>(interface), packet.raw());
#else
transmit(interface, packet.raw());
#endif
}
}
}
@@ -1508,10 +1471,9 @@ using namespace RNS::Utilities;
TRACE("Transport::inbound: Packet is in transport...");
if (packet.transport_id() == _identity.hash()) {
TRACE("Transport::inbound: We are designated next-hop");
auto destination_iter = _path_table.find(packet.destination_hash());
if (destination_iter != _path_table.end()) {
auto& destination_entry = get_path(packet.destination_hash());
if (destination_entry) {
TRACE("Transport::inbound: Found next-hop path to destination");
DestinationEntry destination_entry = (*destination_iter).second;
Bytes next_hop = destination_entry._received_from;
uint8_t remaining_hops = destination_entry._hops;
@@ -1615,11 +1577,7 @@ using namespace RNS::Utilities;
_reverse_table.insert({packet.getTruncatedHash(), reverse_entry});
}
TRACE("Transport::outbound: Sending packet to next hop...");
#if defined(INTERFACES_SET)
transmit(const_cast<Interface&>(outbound_interface), new_raw);
#else
transmit(outbound_interface, new_raw);
#endif
destination_entry._timestamp = OS::time();
}
else {
@@ -1709,23 +1667,8 @@ using namespace RNS::Utilities;
TRACE("Transport::inbound: Packet is ANNOUNCE");
Bytes received_from;
//p local_destination = next((d for d in Transport.destinations if d.hash == packet.destination_hash), None)
#if defined(DESTINATIONS_SET)
//Destination local_destination({Type::NONE});
bool found_local = false;
for (auto& destination : _destinations) {
if (destination.hash() == packet.destination_hash()) {
//local_destination = destination;
found_local = true;
break;
}
}
//if local_destination == None and RNS.Identity.validate_announce(packet):
//if (!local_destination && Identity::validate_announce(packet)) {
if (!found_local && Identity::validate_announce(packet)) {
#elif defined(DESTINATIONS_MAP)
auto iter = _destinations.find(packet.destination_hash());
if (iter == _destinations.end() && Identity::validate_announce(packet)) {
#endif
TRACE("Transport::inbound: Packet is announce for non-local destination, processing...");
if (packet.transport_id()) {
received_from = packet.transport_id();
@@ -1771,19 +1714,8 @@ using namespace RNS::Utilities;
// local to this system, and that hops are less than the max
// CBA TODO determine why packet destination hash is being searched in destinations again since we entered this logic becuase it did not exist above
//if (not any(packet.destination_hash == d.hash for d in Transport.destinations) and packet.hops < Transport.PATHFINDER_M+1):
#if defined(DESTINATIONS_SET)
bool found_local = false;
for (auto& destination : _destinations) {
if (destination.hash() == packet.destination_hash()) {
found_local = true;
break;
}
}
if (!found_local && packet.hops() < (PATHFINDER_M+1)) {
#elif defined(DESTINATIONS_MAP)
auto iter = _destinations.find(packet.destination_hash());
if (iter == _destinations.end() && packet.hops() < (PATHFINDER_M+1)) {
#endif
uint64_t announce_emitted = Transport::announce_emitted(packet);
//p random_blob = packet.data[RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8:RNS.Identity.KEYSIZE//8+RNS.Identity.NAME_HASH_LENGTH//8+10]
@@ -1791,9 +1723,8 @@ using namespace RNS::Utilities;
//p random_blobs = []
std::set<Bytes> empty_random_blobs;
std::set<Bytes>& random_blobs = empty_random_blobs;
auto iter = _path_table.find(packet.destination_hash());
if (iter != _path_table.end()) {
DestinationEntry destination_entry = (*iter).second;
auto& destination_entry = get_path(packet.destination_hash());
if (destination_entry) {
//p random_blobs = Transport.destination_table[packet.destination_hash][4]
random_blobs = destination_entry._random_blobs;
@@ -2077,7 +2008,8 @@ using namespace RNS::Utilities;
new_announce.send();
}
// CBA Culling before adding to esnure table does not exceed maxsize
// Cache announce packet for path persistence (all nodes, not just transport)
// Endpoints need cached announces so path table entries survive reboot
TRACEF("Caching packet %s", packet.get_hash().toHex().c_str());
if (RNS::Transport::cache_packet(packet, true)) {
packet.cached(true);
@@ -2191,24 +2123,15 @@ using namespace RNS::Utilities;
TRACE("Transport::inbound: Packet is LINKREQUEST");
if (!packet.transport_id() || packet.transport_id() == _identity.hash()) {
TRACE("Transport::inbound: Checking if LINKREQUEST is for local destination");
#if defined(DESTINATIONS_SET)
for (auto& destination : _destinations) {
if (destination.hash() == packet.destination_hash() && destination.type() == packet.destination_type()) {
#elif defined(DESTINATIONS_MAP)
auto iter = _destinations.find(packet.destination_hash());
if (iter != _destinations.end()) {
auto& destination = (*iter).second;
if (destination.type() == packet.destination_type()) {
#endif
TRACE("Transport::inbound: Found local destination for LINKREQUEST");
packet.destination(destination);
// CBA iterator over std::set is always const so need to make temporarily mutable
//destination.receive(packet);
#if defined(DESTINATIONS_SET)
const_cast<Destination&>(destination).receive(packet);
#else
destination.receive(packet);
#endif
}
}
}
@@ -2231,10 +2154,6 @@ using namespace RNS::Utilities;
}
else {
// Data is basic (not destined for a link)
#if defined(DESTINATIONS_SET)
for (auto& destination : _destinations) {
if (destination.hash() == packet.destination_hash() && destination.type() == packet.destination_type()) {
#elif defined(DESTINATIONS_MAP)
auto iter = _destinations.find(packet.destination_hash());
if (iter != _destinations.end()) {
// Data is for a local destination
@@ -2242,13 +2161,8 @@ using namespace RNS::Utilities;
auto& destination = (*iter).second;
if (destination.type() == packet.destination_type()) {
TRACEF("Transport::inbound: Packet destination type %d matched, processing", packet.destination_type());
#endif
packet.destination(destination);
#if defined(DESTINATIONS_SET)
const_cast<Destination&>(destination).receive(packet);
#else
destination.receive(packet);
#endif
if (destination.proof_strategy() == Type::Destination::PROVE_ALL) {
packet.prove();
@@ -2536,47 +2450,17 @@ using namespace RNS::Utilities;
/*static*/ void Transport::register_interface(Interface& interface) {
TRACEF("Transport: Registering interface %s %s", interface.get_hash().toHex().c_str(), interface.toString().c_str());
#if defined(INTERFACES_SET)
_interfaces.insert(interface);
#elif defined(INTERFACES_LIST)
_interfaces.push_back(interface);
#elif defined(INTERFACES_MAP)
_interfaces.insert({interface.get_hash(), interface});
#endif
// CBA TODO set or add transport as listener on interface to receive incoming packets?
}
/*static*/ void Transport::deregister_interface(const Interface& interface) {
TRACEF("Transport: Deregistering interface %s", interface.toString().c_str());
#if defined(INTERFACES_SET)
//for (auto iter = _interfaces.begin(); iter != _interfaces.end(); ++iter) {
// if ((*iter).get() == interface) {
// TRACEF("Transport::deregister_interface: Found and removing interface %s", (*iter).get().toString().c_str());
// _interfaces.erase(iter);
// break;
// }
//}
//auto iter = _interfaces.find(interface);
auto iter = _interfaces.find(const_cast<Interface&>(interface));
if (iter != _interfaces.end()) {
TRACEF("Transport::deregister_interface: Found and removing interface %s", (*iter).get().toString().c_str());
_interfaces.erase(iter);
}
#elif defined(INTERFACES_LIST)
for (auto iter = _interfaces.begin(); iter != _interfaces.end(); ++iter) {
if ((*iter).get() == interface) {
TRACEF("Transport::deregister_interface: Found and removing interface %s", (*iter).get().toString().c_str());
_interfaces.erase(iter);
break;
}
}
#elif defined(INTERFACES_MAP)
auto iter = _interfaces.find(interface.get_hash());
if (iter != _interfaces.end()) {
TRACEF("Transport::deregister_interface: Found and removing interface %s", (*iter).second.toString().c_str());
_interfaces.erase(iter);
}
#endif
}
/*static*/ void Transport::register_destination(Destination& destination) {
@@ -2584,17 +2468,6 @@ using namespace RNS::Utilities;
TRACEF("Transport: Registering destination %s", destination.toString().c_str());
destination.mtu(Type::Reticulum::MTU);
if (destination.direction() == Type::Destination::IN) {
#if defined(DESTINATIONS_SET)
for (auto& registered_destination : _destinations) {
if (destination.hash() == registered_destination.hash()) {
//p raise KeyError("Attempt to register an already registered destination.")
throw std::runtime_error("Attempt to register an already registered destination.");
}
}
// CBA ACCUMULATES
_destinations.insert(destination);
#elif defined(DESTINATIONS_MAP)
auto iter = _destinations.find(destination.hash());
if (iter != _destinations.end()) {
//p raise KeyError("Attempt to register an already registered destination.")
@@ -2603,7 +2476,6 @@ using namespace RNS::Utilities;
// CBA ACCUMULATES
_destinations.insert({destination.hash(), destination});
#endif
if (_owner && _owner.is_connected_to_shared_instance()) {
if (destination.type() == Type::Destination::SINGLE) {
@@ -2617,11 +2489,7 @@ using namespace RNS::Utilities;
}
/*
#if defined(DESTINATIONS_SET)
for (const Destination& destination : _destinations) {
#elif defined(DESTINATIONS_MAP)
for (auto& [hash, destination] : _destinations) {
#endif
TRACEF("Transport::register_destination: Listed destination %s", destination.toString().c_str());
}
*/
@@ -2630,18 +2498,11 @@ using namespace RNS::Utilities;
/*static*/ void Transport::deregister_destination(const Destination& destination) {
TRACEF("Transport: Deregistering destination %s", destination.toString().c_str());
#if defined(DESTINATIONS_SET)
if (_destinations.find(destination) != _destinations.end()) {
TRACEF("Transport::deregister_destination: Found and removing destination %s", destination.toString().c_str());
_destinations.erase(destination);
}
#elif defined(DESTINATIONS_MAP)
auto iter = _destinations.find(destination.hash());
if (iter != _destinations.end()) {
TRACEF("Transport::deregister_destination: Found and removing destination %s", (*iter).second.toString().c_str());
_destinations.erase(iter);
}
#endif
}
/*static*/ void Transport::register_link(Link& link) {
@@ -2696,50 +2557,20 @@ Deregisters an announce handler.
}
/*static*/ bool Transport::is_interface_from_hash(const Bytes& interface_hash) {
#if defined(INTERFACES_SET)
for (const Interface& interface : _interfaces) {
if (interface.get_hash() == interface_hash) {
return true;
}
}
#elif defined(INTERFACES_LIST)
for (Interface& interface : _interfaces) {
if (interface.get_hash() == interface_hash) {
return true;
}
}
#elif defined(INTERFACES_MAP)
auto iter = _interfaces.find(interface_hash);
if (iter != _interfaces.end()) {
return true;
}
#endif
return false;
}
/*static*/ Interface Transport::find_interface_from_hash(const Bytes& interface_hash) {
#if defined(INTERFACES_SET)
for (const Interface& interface : _interfaces) {
if (interface.get_hash() == interface_hash) {
//TRACEF("Transport::find_interface_from_hash: Found interface %s", interface.toString().c_str());
return interface;
}
}
#elif defined(INTERFACES_LIST)
for (Interface& interface : _interfaces) {
if (interface.get_hash() == interface_hash) {
//TRACEF("Transport::find_interface_from_hash: Found interface %s", interface.toString().c_str());
return interface;
}
}
#elif defined(INTERFACES_MAP)
auto iter = _interfaces.find(interface_hash);
if (iter != _interfaces.end()) {
//TRACEF("Transport::find_interface_from_hash: Found interface %s", (*iter).second.toString().c_str());
return (*iter).second;
}
#endif
return {Type::NONE};
}
@@ -2870,21 +2701,36 @@ Deregisters an announce handler.
}
}
/*static*/ Transport::DestinationEntry& Transport::get_path(const Bytes& destination_hash) {
auto iter = _path_table.find(destination_hash);
if (iter == _path_table.end()) return empty_destination_entry;
DestinationEntry& destination_entry = (*iter).second;
// Don't require announce_packet for basic routing — it's only needed for
// path response forwarding. The routing fields (_received_from, _hops,
// receiving_interface) are valid without it, and removing the path here
// when deserialization fails under memory pressure breaks TCP outbound.
if (!destination_entry.receiving_interface()) {
DEBUGF("Entry for destination %s found but is missing receiving interface, discarding", destination_hash.toHex().c_str());
remove_path(destination_hash);
return empty_destination_entry;
}
return destination_entry;
}
/*static*/ bool Transport::remove_path(const Bytes& destination_hash) {
auto iter = _path_table.find(destination_hash);
if (iter != _path_table.end()) {
// Remove cached packet file associated with this destination
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, iter->second.announce_packet_hash().toHex().c_str());
if (OS::file_exists(packet_cache_path)) {
OS::remove_file(packet_cache_path);
}
if (_path_table.erase(destination_hash) < 1) {
WARNINGF("Failed to remove destination %s from path table", destination_hash.toHex().c_str());
}
return true;
if (iter == _path_table.end()) return false;
// Remove cached packet file associated with this destination
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, iter->second.announce_packet_hash().toHex().c_str());
if (OS::file_exists(packet_cache_path)) {
OS::remove_file(packet_cache_path);
}
return false;
if (_path_table.erase(destination_hash) < 1) {
WARNINGF("Failed to remove destination %s from path table", destination_hash.toHex().c_str());
return false;
}
return true;
}
/*
@@ -2892,12 +2738,7 @@ Deregisters an announce handler.
:returns: *True* if a path to the destination is known, otherwise *False*.
*/
/*static*/ bool Transport::has_path(const Bytes& destination_hash) {
if (_path_table.find(destination_hash) != _path_table.end()) {
return true;
}
else {
return false;
}
return (_path_table.find(destination_hash) != _path_table.end());
}
/*
@@ -2905,14 +2746,14 @@ Deregisters an announce handler.
:returns: The number of hops to the specified destination, or ``RNS.Transport.PATHFINDER_M`` if the number of hops is unknown.
*/
/*static*/ uint8_t Transport::hops_to(const Bytes& destination_hash) {
// Direct path table lookup — avoids get_path() which triggers
// expensive announce_packet lazy load from flash cache.
// hops_to() only needs _hops which is already in memory.
auto iter = _path_table.find(destination_hash);
if (iter != _path_table.end()) {
DestinationEntry destination_entry = (*iter).second;
return destination_entry._hops;
}
else {
return PATHFINDER_M;
return (*iter).second._hops;
}
return PATHFINDER_M;
}
/*
@@ -2920,9 +2761,8 @@ Deregisters an announce handler.
:returns: The destination hash as *bytes* for the next hop to the specified destination, or *None* if the next hop is unknown.
*/
/*static*/ Bytes Transport::next_hop(const Bytes& destination_hash) {
auto iter = _path_table.find(destination_hash);
if (iter != _path_table.end()) {
DestinationEntry destination_entry = (*iter).second;
auto& destination_entry = get_path(destination_hash);
if (destination_entry) {
return destination_entry._received_from;
}
else {
@@ -2935,9 +2775,8 @@ Deregisters an announce handler.
:returns: The interface for the next hop to the specified destination, or *None* if the interface is unknown.
*/
/*static*/ Interface Transport::next_hop_interface(const Bytes& destination_hash) {
auto iter = _path_table.find(destination_hash);
if (iter != _path_table.end()) {
DestinationEntry destination_entry = (*iter).second;
auto& destination_entry = get_path(destination_hash);
if (destination_entry) {
return destination_entry.receiving_interface();
}
else {
@@ -3006,9 +2845,8 @@ Deregisters an announce handler.
}
/*static*/ bool Transport::expire_path(const Bytes& destination_hash) {
auto iter = _path_table.find(destination_hash);
if (iter != _path_table.end()) {
DestinationEntry destination_entry = (*iter).second;
auto& destination_entry = get_path(destination_hash);
if (destination_entry) {
destination_entry._timestamp = 0;
_tables_last_culled = 0;
return true;
@@ -3207,10 +3045,9 @@ will announce it.
bool destination_exists_on_local_client = false;
if (_local_client_interfaces.size() > 0) {
auto iter = _path_table.find(destination_hash);
if (iter != _path_table.end()) {
auto& destination_entry = get_path(destination_hash);
if (destination_entry) {
TRACEF("Transport::path_request_handler: entry found for destination %s", destination_hash.toHex().c_str());
DestinationEntry& destination_entry = (*iter).second;
if (is_local_client_interface(destination_entry.receiving_interface())) {
destination_exists_on_local_client = true;
// CBA ACCUMULATES
@@ -3222,31 +3059,22 @@ will announce it.
}
}
auto destination_iter = _path_table.find(destination_hash);
DestinationEntry& destination_entry = get_path(destination_hash);
//local_destination = next((d for d in Transport.destinations if d.hash == destination_hash), None)
#if defined(DESTINATIONS_SET)
Destination local_destination({Type::NONE});
for (auto& destination : _destinations) {
if (destination.hash() == destination_hash) {
local_destination = destination;
break;
}
}
//if local_destination != None:
if (local_destination) {
#elif defined(DESTINATIONS_MAP)
auto iter = _destinations.find(destination_hash);
if (iter != _destinations.end()) {
auto& local_destination = (*iter).second;
#endif
auto destinations_iter = _destinations.find(destination_hash);
if (destinations_iter != _destinations.end()) {
auto& local_destination = (*destinations_iter).second;
local_destination.announce({Bytes::NONE}, true, attached_interface, tag);
DEBUGF("Answering path request for destination %s%s, destination is local to this system", destination_hash.toHex().c_str(), interface_str.c_str());
}
//p elif (RNS.Reticulum.transport_enabled() or is_from_local_client) and (destination_hash in Transport.destination_table):
else if ((Reticulum::transport_enabled() || is_from_local_client) && destination_iter != _path_table.end()) {
else if ((Reticulum::transport_enabled() || is_from_local_client) && destination_entry) {
TRACEF("Transport::path_request_handler: entry found for destination %s", destination_hash.toHex().c_str());
DestinationEntry& destination_entry = (*destination_iter).second;
const Packet& announce_packet = destination_entry.announce_packet();
const Packet announce_packet = destination_entry.announce_packet();
if (!announce_packet) {
DEBUGF("Path entry for %s exists but announce packet unavailable (cache miss), cannot answer path request", destination_hash.toHex().c_str());
}
else {
TRACEF("announce_packet destination_hash: %s", announce_packet.destination_hash().toHex().c_str());
TRACEF("announce_packet hops: %u", announce_packet.hops());
TRACEF("announce_packet str: %s", announce_packet.toString().c_str());
@@ -3333,19 +3161,14 @@ TRACEF("announce_packet str: %s", announce_packet.toString().c_str());
cull_announce_table();
}
}
} // else (announce_packet valid)
}
else if (is_from_local_client) {
// Forward path request on all interfaces
// except the local client
DEBUGF("Forwarding path request from local client for destination %s%s to all other interfaces", destination_hash.toHex().c_str(), interface_str.c_str());
Bytes request_tag = Identity::get_random_hash();
#if defined(INTERFACES_SET)
for (const Interface& interface : _interfaces) {
#elif defined(INTERFACES_LIST)
for (Interface& interface : _interfaces) {
#elif defined(INTERFACES_MAP)
for (auto& [hash, interface] : _interfaces) {
#endif
if (interface != attached_interface) {
request_path(destination_hash, interface, request_tag);
}
@@ -3369,13 +3192,7 @@ TRACEF("announce_packet str: %s", announce_packet.toString().c_str());
attached_interface
}});
#if defined(INTERFACES_SET)
for (const Interface& interface : _interfaces) {
#elif defined(INTERFACES_LIST)
for (Interface& interface : _interfaces) {
#elif defined(INTERFACES_MAP)
for (auto& [hash, interface] : _interfaces) {
#endif
// CBA EXPERIMENTAL forwarding path requests even on requestor interface in order to support
// path-finding over LoRa mesh
//if (interface != attached_interface) {
@@ -3588,7 +3405,7 @@ TRACEF("Transport::read_path_table: buffer size %d bytes", Persistence::_buffer.
if (!error) {
// Calculate crc for dirty-checking before write
_path_table_crc = Crc::crc32(0, Persistence::_buffer.data(), Persistence::_buffer.size());
_path_table = Persistence::_document.as<std::map<Bytes, DestinationEntry>>();
_path_table = Persistence::_document.as<PathTable>();
#else // CUSTOM
// Calculate crc for dirty-checking before later write
if (Persistence::deserialize(_path_table, destination_table_path, _path_table_crc) > 0) {
@@ -3603,6 +3420,9 @@ TRACEF("Transport::read_path_table: buffer size %d bytes", Persistence::_buffer.
// CBA Avoid accessing announce_packet() and receiving_interface() until actually needed in order to
// take advantage of lazy loading and avoid incurring memory hit to store if not actually needed.
// CBA Optimized to not check for a valid cached announce packet,
// and instead checking if/when the path is actually used.
/*
// CBA If announce packet is not cached then remove destination entry (it's useless without announce packet)
if (!is_cached_packet(destination_entry.announce_packet_hash())) {
// remove destination
@@ -3610,6 +3430,7 @@ TRACEF("Transport::read_path_table: buffer size %d bytes", Persistence::_buffer.
invalid_paths.push_back(destination_hash);
continue;
}
*/
// CBA If receiving interface is not present then remove destination entry (it's useless without receiving interface)
if (!is_interface_from_hash(destination_entry.receiving_interface_hash())) {
// remove destination
@@ -3618,6 +3439,7 @@ TRACEF("Transport::read_path_table: buffer size %d bytes", Persistence::_buffer.
continue;
}
DEBUGF("Loaded path table entry for %s from storage", destination_hash.toHex().c_str());
OS::reset_watchdog();
}
for (const auto& destination_hash : invalid_paths) {
_path_table.erase(destination_hash);
@@ -3780,8 +3602,9 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe
DEBUGF("Saving %d path table entries to storage...", _path_table.size());
char destination_table_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(destination_table_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/destination_table", Reticulum::_storagepath);
if (Persistence::serialize(_path_table, destination_table_path, _path_table_crc) > 0) {
TRACEF("Transport::write_path_table: wrote %d entries, %d bytes", _path_table.size(), Persistence::_buffer.size());
size_t len = Persistence::serialize(_path_table, destination_table_path, _path_table_crc);
if (len > 0) {
TRACEF("Transport::write_path_table: wrote %d entries, %d bytes", _path_table.size(), len);
success = true;
}
else {
@@ -3945,42 +3768,75 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe
}
/*static*/ void Transport::clean_caches() {
// If currently cleaning caches then disregard
if (cleaning_caches) {
WARNING("Transport::clean_caches: already cleaning!");
return;
}
cleaning_caches = true;
TRACE("Transport::clean_caches()");
#if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS)
// CBA Remove cached packets no longer in path list
std::list<std::string> files = OS::list_directory(Reticulum::_cachepath);
for (auto& file : files) {
TRACEF("Transport::clean_caches: Checking for use of cached packet %s", file.c_str());
std::list<std::string> remove_list;
OS::list_directory(Reticulum::_cachepath, [&remove_list](const char* file_name) {
TRACEF("Transport::clean_caches: Checking for use of cached packet %s", file_name);
bool found = false;
for (auto& [destination_hash, destination_entry] : _path_table) {
if (file.compare(destination_entry.announce_packet_hash().toHex()) == 0) {
if (strcasecmp(file_name, destination_entry.announce_packet_hash().toHex().c_str()) == 0) {
found = true;
break;
}
}
if (!found) {
TRACEF("Transport::clean_caches: No matching path found, removing cached packet %s", file.c_str());
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, file.c_str());
OS::remove_file(packet_cache_path);
remove_list.push_back(file_name);
}
//OS::reset_watchdog();
OS::run_loop();
});
for (auto& file_name : remove_list) {
TRACEF("Transport::clean_caches: No matching path found, removing cached packet %s", file_name.c_str());
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, file_name.c_str());
OS::remove_file(packet_cache_path);
//OS::reset_watchdog();
OS::run_loop();
}
#endif
cleaning_caches = false;
}
/*static*/ void Transport::dump_stats() {
OS::dump_heap_stats();
size_t memory = OS::heap_available();
size_t flash = OS::storage_available();
Memory::dump_heap_stats();
size_t memory = Memory::heap_available();
uint8_t memory_pct = (uint8_t)((double)memory / (double)Memory::heap_size() * 100.0);
if (_last_memory == 0) {
_last_memory = memory;
}
#if defined(ESP32)
// CBA NOTE It appears that ESP.getFreePsram() may not accurately reflect available availabe PSRAM
// because it appears to always decrease (even to zero) as if PSRAM is being leaked. Maybe it doesn't
// accurately reflect PSRAM freed with calls to free()???
size_t psram = ESP.getFreePsram();
uint8_t psram_pct = (uint8_t)((double)psram / (double)ESP.getPsramSize() * 100.0);
if (_last_psram == 0) {
_last_psram = psram;
}
#else
size_t psram = 0;
uint8_t psram_pct = 0;
#endif
size_t flash = OS::storage_available();
if (_last_flash == 0) {
_last_flash = flash;
}
uint8_t flash_pct = (uint8_t)((double)flash / (double)OS::storage_size() * 100.0);
// memory
// storage
@@ -3989,7 +3845,7 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe
// _reverse_table
// _announce_table
// _held_announces
HEADF(LOG_VERBOSE, "mem: %u (%u%%) [%d] flash: %u (%u%%) [%d] paths: %u dsts: %u revr: %u annc: %u held: %u", memory, (int)((double)memory / (double)OS::heap_size() * 100.0), memory - _last_memory, flash, (int)((double)flash / (double)OS::storage_size() * 100.0), flash - _last_flash, _path_table.size(), _destinations.size(), _reverse_table.size(), _announce_table.size(), _held_announces.size());
HEADF(LOG_VERBOSE, "mem: %u (%u%%) [%d] psram: %u (%u%%) [%d] flash: %u (%u%%) [%d] paths: %u dsts: %u revr: %u annc: %u held: %u", memory, memory_pct, memory - _last_memory, psram, psram_pct, psram - _last_psram, flash, flash_pct, flash - _last_flash, _path_table.size(), _destinations.size(), _reverse_table.size(), _announce_table.size(), _held_announces.size());
// _path_requests
// _discovery_path_requests
@@ -4017,6 +3873,7 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe
VERBOSEF("pin: %u pout: %u padd: %u dpr: %u ikd: %u ia: %u\r\n", _packets_received, _packets_sent, _destinations_added, destination_path_responses, Identity::_known_destinations.size(), interface_announces);
_last_memory = memory;
_last_psram = psram;
_last_flash = flash;
}
@@ -4030,20 +3887,11 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe
/*static*/ Destination Transport::find_destination_from_hash(const Bytes& destination_hash) {
TRACEF("Transport::find_destination_from_hash: Searching for destination %s", destination_hash.toHex().c_str());
#if defined(DESTINATIONS_SET)
for (const Destination& destination : _destinations) {
if (destination.get_hash() == destination_hash) {
TRACEF("Transport::find_destination_from_hash: Found destination %s", destination.toString().c_str());
return destination;
}
}
#elif defined(DESTINATIONS_MAP)
auto iter = _destinations.find(destination_hash);
if (iter != _destinations.end()) {
TRACEF("Transport::find_destination_from_hash: Found destination %s", (*iter).second.toString().c_str());
return (*iter).second;
}
#endif
return {Type::NONE};
}
@@ -4067,11 +3915,11 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe
for (const auto& [timestamp, destination_hash] : sorted_keys) {
TRACEF("Transport::cull_path_table: Removing destination %s from path table", destination_hash.toHex().c_str());
#if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS)
auto it = _path_table.find(destination_hash);
if (it != _path_table.end()) {
auto& destination_entry = get_path(destination_hash);
if (destination_entry) {
// Remove cached packet file associated with this destination
char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE];
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, it->second.announce_packet_hash().toHex().c_str());
snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, destination_entry.announce_packet_hash().toHex().c_str());
if (OS::file_exists(packet_cache_path)) {
OS::remove_file(packet_cache_path);
}
+84 -47
View File
@@ -3,6 +3,7 @@
#include "Packet.h"
#include "Bytes.h"
#include "Type.h"
#include "Utilities/Memory.h"
#include <map>
#include <vector>
@@ -13,12 +14,9 @@
#include <functional>
#include <stdint.h>
//#define INTERFACES_SET
//#define INTERFACES_LIST
#define INTERFACES_MAP
//#define DESTINATIONS_SET
#define DESTINATIONS_MAP
#ifndef RNS_LEAN_PATH_TABLE
#define RNS_LEAN_PATH_TABLE 1
#endif
namespace RNS {
@@ -56,6 +54,10 @@ namespace RNS {
class Transport {
public:
using InterfaceTable = std::map<Bytes, Interface&>;
using DestinationTable = std::map<Bytes, Destination>;
class Callbacks {
public:
using receive_packet = void(*)(const Bytes& raw, const Interface& interface);
@@ -68,8 +70,6 @@ namespace RNS {
friend class Transport;
};
public:
class PacketEntry {
public:
PacketEntry() {}
@@ -99,6 +99,7 @@ namespace RNS {
}
#endif
};
using PacketTable = std::map<Bytes, PacketEntry>;
// CBA TODO Analyze safety of using Inrerface references here
// CBA TODO Analyze safety of using Packet references here
@@ -111,9 +112,15 @@ namespace RNS {
_hops(announce_hops),
_expires(expires),
_random_blobs(random_blobs),
#if RNS_LEAN_PATH_TABLE
_receiving_interface(receiving_interface)
#else
_receiving_interface(receiving_interface),
_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) :
_timestamp(timestamp),
@@ -125,12 +132,33 @@ namespace RNS {
_announce_packet_hash(announce_packet_hash)
{
}
inline operator bool() const {
return (_receiving_interface_hash && _announce_packet_hash);
}
public:
// Lazy load receiving_interface and announce_packet
inline Interface& receiving_interface() {
if (!_receiving_interface) _receiving_interface = find_interface_from_hash(_receiving_interface_hash);
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() {
if (!_announce_packet) _announce_packet = get_cached_packet(_announce_packet_hash);
if (_announce_packet) {
@@ -145,11 +173,17 @@ namespace RNS {
}
return _announce_packet;
}
#endif
// 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 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 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:
double _timestamp = 0;
Bytes _received_from;
@@ -163,8 +197,10 @@ namespace RNS {
private:
Interface _receiving_interface = {Type::NONE};
Bytes _receiving_interface_hash;
#if !RNS_LEAN_PATH_TABLE
//const Packet& _announce_packet;
Packet _announce_packet = {Type::NONE};
#endif
Bytes _announce_packet_hash;
public:
#ifndef NDEBUG
@@ -186,6 +222,8 @@ namespace RNS {
}
#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 Packet references here
@@ -217,6 +255,8 @@ namespace RNS {
bool _block_rebroadcasts = false;
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
class LinkEntry {
@@ -244,6 +284,7 @@ namespace RNS {
bool _validated = false;
double _proof_timeout = 0;
};
using LinkTable = std::map<Bytes, LinkEntry>;
// CBA TODO Analyze safety of using Inrerface references here
class ReverseEntry {
@@ -259,6 +300,7 @@ namespace RNS {
const Interface _outbound_interface = {Type::NONE};
double _timestamp = 0;
};
using ReverseTable = std::map<Bytes, ReverseEntry>;
// CBA TODO Analyze safety of using Inrerface references here
class PathRequestEntry {
@@ -274,6 +316,7 @@ namespace RNS {
double _timeout = 0;
const Interface _requesting_interface = {Type::NONE};
};
using PathRequestTable = std::map<Bytes, PathRequestEntry>;
/*
// CBA TODO Analyze safety of using Inrerface references here
@@ -313,9 +356,10 @@ namespace RNS {
public:
const Bytes _tunnel_id;
const Bytes _interface_hash;
std::map<Bytes, DestinationEntry> _serialised_paths;
PathTable _serialised_paths;
double _expires = 0;
};
using TunnelTable = std::map<Bytes, TunnelEntry>;
class RateEntry {
public:
@@ -330,6 +374,7 @@ namespace RNS {
double _blocked_until = 0.0;
std::vector<double> _timestamps;
};
using RateTable = std::map<Bytes, RateEntry>;
public:
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 register_interface(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 deregister_destination(const Destination& destination);
static void register_link(Link& link);
@@ -362,6 +407,7 @@ namespace RNS {
static bool clear_cached_packet(const Bytes& packet_hash);
static bool cache_request_packet(const Packet& packet);
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 has_path(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 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 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; }
// CBA TEST
static inline void identity(Identity& identity) { _identity = identity; }
inline static const std::map<Bytes, DestinationEntry>& get_path_table() { return _path_table; }
inline static const std::map<Bytes, RateEntry>& get_announce_rate_table() { return _announce_rate_table; }
inline static const std::map<Bytes, LinkEntry>& get_link_table() { return _link_table; }
inline static const PathTable& get_path_table() { return _path_table; }
inline static const RateTable& get_announce_rate_table() { return _announce_rate_table; }
inline static const LinkTable& get_link_table() { return _link_table; }
private:
// 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
static std::map<Bytes, Interface&> _interfaces; // All active interfaces
#endif
#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
static InterfaceTable _interfaces; // All active interfaces
static DestinationTable _destinations; // All active destinations
// 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> _active_links; // Links that are active
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::set<Link> _pending_links; // Links that are being established
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::list<PacketReceipt> _receipts; // Receipts of all outgoing packets for proof processing
// TODO: "destination_table" should really be renamed to "path_table"
// Notes on memory usage: 1 megabyte of memory can store approximately
// 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 std::map<Bytes, DestinationEntry> _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 std::map<Bytes, LinkEntry> _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 std::set<HAnnounceHandler> _announce_handlers; // A table storing externally registered announce handlers
static std::map<Bytes, TunnelEntry> _tunnels; // A table storing tunnels to other transport instances
static std::map<Bytes, RateEntry> _announce_rate_table; // A table for keeping track of announce rates
static std::map<Bytes, double> _path_requests; // A table for storing path request timestamps
static AnnounceTable _announce_table; // A table for storing announces currently waiting to be retransmitted
static PathTable _path_table; // A lookup table containing the next hop to a given destination
static ReverseTable _reverse_table; // A lookup table for storing packet hashes used to return proofs and replies
static LinkTable _link_table; // A lookup table containing hops for links
static AnnounceTable _held_announces; // A table containing temporarily held announce-table entries
static TunnelTable _tunnels; // A table storing tunnels to other transport instances
static RateTable _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, PathRequestEntry> _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 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
// Transport control destinations are used
// for control purposes like path requests
@@ -487,7 +520,7 @@ namespace RNS {
static std::map<Bytes, const Interface&> _pending_local_path_requests;
// 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_snr_cache = []
@@ -529,7 +562,11 @@ namespace RNS {
static uint32_t _packets_received;
static uint32_t _destinations_added;
static size_t _last_memory;
static size_t _last_psram;
static size_t _last_flash;
// CBA Block re-entrance
static bool cleaning_caches;
};
template <typename M, typename S>
+2 -4
View File
@@ -130,13 +130,11 @@ namespace RNS { namespace Type {
//static const uint16_t JOB_INTERVAL = 60*5;
static const uint16_t JOB_INTERVAL = 60;
// CBA TEST
static uint16_t CLEAN_INTERVAL = 60*15;
//static uint16_t CLEAN_INTERVAL = 60;
static const uint16_t CLEAN_INTERVAL = 60*15;
// CBA MCU
//static const uint16_t PERSIST_INTERVAL = 60*60*12;
// CBA TEST
static uint16_t PERSIST_INTERVAL = 60*60;
//static uint16_t PERSIST_INTERVAL = 60;
static const uint16_t PERSIST_INTERVAL = 60*60;
static const uint16_t GRACIOUS_PERSIST_INTERVAL = 60*5;
static const uint8_t DESTINATION_LENGTH = TRUNCATED_HASHLENGTH/8; // In bytes
+567
View File
@@ -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.buffer_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
+172
View File
@@ -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 {
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
View File
@@ -8,367 +8,6 @@
using namespace RNS;
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*/ uint64_t OS::_time_offset = 0;
/*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
}
/*static*/ OS::LoopCallback OS::_on_loop = nullptr;
+49 -34
View File
@@ -4,9 +4,9 @@
#include "../FileStream.h"
#include "../Bytes.h"
#include "tlsf.h"
#include <cmath>
#include <memory>
#include <functional>
#include <unistd.h>
#include <time.h>
#include <stdint.h>
@@ -14,6 +14,9 @@
#ifdef ARDUINO
#include <Arduino.h>
#if defined(ESP32)
#include "esp_task_wdt.h"
#endif
#endif
#undef round
@@ -22,20 +25,22 @@ namespace RNS { namespace Utilities {
class OS {
public:
//using LoopCallback = void(*)();
using LoopCallback = std::function<void()>;
private:
static FileSystem _filesystem;
static uint64_t _time_offset;
static LoopCallback _on_loop;
public:
static tlsf_t _tlsf;
public:
static inline uint64_t getTimeOffset() { return _time_offset; }
static inline void setTimeOffset(uint64_t offset) { _time_offset = offset; }
inline static uint64_t getTimeOffset() { return _time_offset; }
inline static void setTimeOffset(uint64_t offset) { _time_offset = offset; }
#ifdef ARDUINO
// 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)
static uint32_t low32, high32;
uint32_t new_low32 = millis();
@@ -45,32 +50,32 @@ namespace RNS { namespace Utilities {
}
#else
// 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
#ifdef ARDUINO
// 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
// 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
// sleep for specified milliseconds
//static inline void sleep(float seconds) { ::sleep(seconds); }
//inline static void sleep(float seconds) { ::sleep(seconds); }
#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
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
//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
//static inline 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; }
static inline double round(double 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; }
//inline static 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;
for (size_t i = 0; i < len; ++i) {
result = (result << 8) | data[i];
@@ -79,17 +84,17 @@ namespace RNS { namespace Utilities {
}
// Detect endianness at runtime
static int is_big_endian(void) {
inline static int is_big_endian(void) {
uint16_t test = 0x0102;
return ((uint8_t*)&test)[0] == 0x01;
}
// Byte swap functions
static uint16_t swap16(uint16_t val) {
inline static uint16_t swap16(uint16_t val) {
return (val << 8) | (val >> 8);
}
static uint32_t swap32(uint32_t val) {
inline static uint32_t swap32(uint32_t val) {
return ((val << 24) & 0xFF000000) |
((val << 8) & 0x00FF0000) |
((val >> 8) & 0x0000FF00) |
@@ -98,25 +103,39 @@ namespace RNS { namespace Utilities {
// 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);
}
static uint32_t portable_htonl(uint32_t val) {
inline static uint32_t portable_htonl(uint32_t 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);
}
static uint32_t portable_ntohl(uint32_t val) {
inline static uint32_t portable_ntohl(uint32_t val) {
return is_big_endian() ? val : swap32(val);
}
#if defined(RNS_USE_ALLOCATOR)
static void dump_allocator_stats();
inline static void reset_watchdog() {
#if defined(ESP32)
esp_task_wdt_reset();
#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) {
TRACE("Registering filesystem...");
@@ -204,11 +223,11 @@ namespace RNS { namespace Utilities {
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) {
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() {
@@ -224,10 +243,6 @@ namespace RNS { namespace Utilities {
}
return _filesystem.storage_available();
}
static size_t heap_size();
static size_t heap_available();
static void dump_heap_stats();
};
+5
View File
@@ -4,6 +4,11 @@
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*/ JsonDocument _document;
#endif
/*static*/ Bytes _buffer(Type::Persistence::BUFFER_MAXSIZE);
+29 -5
View File
@@ -474,8 +474,31 @@ namespace RNS {
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 JsonDocument _document;
#endif
static Bytes _buffer(Type::Persistence::BUFFER_MAXSIZE);
template <typename T> uint32_t crc(const T& obj) {
@@ -556,7 +579,7 @@ namespace RNS { namespace Persistence {
}
#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>>");
uint32_t crc = 0;
@@ -592,7 +615,7 @@ namespace RNS { namespace Persistence {
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>>");
// 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.flush();
TRACEF("Persistence::serialize: stream size: %d bytes", stream.size());
crc = stream.crc();
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;
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>>");
// CBA TODO: Use stream here instead to avoid having to buffer entire structure
@@ -700,7 +724,7 @@ namespace RNS { namespace Persistence {
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;
return deserialize(map, file_path, crc);
}
+114 -110
View File
@@ -33,8 +33,8 @@ public:
bool init() {
TRACE("FileSystem initializing...");
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
// Setup FileSystem
INFO("SPIFFS mounting FileSystem");
if (!SPIFFS.begin(true, "")){
@@ -59,22 +59,22 @@ public:
remove_file("/test");
}
DEBUG("SPIFFS FileSystem is ready");
#elif BOARD_NRF52
#elif BOARD_NRF52
// Initialize Internal File System
INFO("InternalFS mounting FileSystem");
InternalFS.begin();
INFO("InternalFS FileSystem is ready");
#endif
#endif
#endif
#endif
return true;
}
public:
static void listDir(const char* dir) {
#ifdef ARDUINO
#ifdef ARDUINO
Serial.print("DIR: ");
Serial.println(dir);
#ifdef BOARD_ESP32
#ifdef BOARD_ESP32
File root = SPIFFS.open(dir);
if (!root) {
Serial.println("Failed to opend directory");
@@ -93,7 +93,7 @@ public:
file = root.openNextFile();
}
root.close();
#elif BOARD_NRF52
#elif BOARD_NRF52
File root = InternalFS.open(dir);
if (!root) {
Serial.println("Failed to opend directory");
@@ -112,38 +112,38 @@ public:
file = root.openNextFile();
}
root.close();
#endif
#endif
#endif
#endif
}
public:
virtual bool file_exists(const char* file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(file_path, FILE_READ);
if (file) {
#elif BOARD_NRF52
#elif BOARD_NRF52
File file(InternalFS);
if (file.open(file_path, FILE_O_READ)) {
#else
#else
if (false) {
#endif
#else
#endif
#else
// Native
FILE* file = fopen(file_path, "r");
if (file != nullptr) {
#endif
#endif
//TRACE("file_exists: file exists, closing file");
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
file.close();
#elif BOARD_NRF52
#elif BOARD_NRF52
file.close();
#endif
#else
#endif
#else
// Native
fclose(file);
#endif
#endif
return true;
}
else {
@@ -154,24 +154,24 @@ public:
virtual size_t read_file(const char* file_path, RNS::Bytes& data) {
size_t read = 0;
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(file_path, FILE_READ);
if (file) {
size_t size = file.size();
read = file.readBytes((char*)data.writable(size), size);
#elif BOARD_NRF52
#elif BOARD_NRF52
//File file(InternalFS);
//if (file.open(file_path, FILE_O_READ)) {
File file = InternalFS.open(file_path, FILE_O_READ);
if (file) {
size_t size = file.size();
read = file.readBytes((char*)data.writable(size), size);
#else
#else
if (false) {
size_t size = 0;
#endif
#else
#endif
#else
// Native
FILE* file = fopen(file_path, "r");
if (file != nullptr) {
@@ -180,23 +180,23 @@ public:
rewind(file);
//size_t read = fread(data.writable(size), size, 1, file);
read = fread(data.writable(size), 1, size, file);
#endif
#endif
TRACEF("read_file: read %zu bytes from file %s", read, file_path);
if (read != size) {
ERRORF("read_file: failed to read file %s", file_path);
data.clear();
}
//TRACE("read_file: closing input file");
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
file.close();
#elif BOARD_NRF52
#elif BOARD_NRF52
file.close();
#endif
#else
#endif
#else
// Native
fclose(file);
#endif
#endif
}
else {
ERRORF("read_file: failed to open input file %s", file_path);
@@ -208,40 +208,40 @@ public:
// CBA TODO Replace remove with working truncation
remove_file(file_path);
size_t wrote = 0;
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(file_path, FILE_WRITE);
if (file) {
wrote = file.write(data.data(), data.size());
#elif BOARD_NRF52
#elif BOARD_NRF52
File file(InternalFS);
if (file.open(file_path, FILE_O_WRITE)) {
wrote = file.write(data.data(), data.size());
#else
#else
if (false) {
#endif
#else
#endif
#else
// Native
FILE* file = fopen(file_path, "w");
if (file != nullptr) {
//size_t wrote = fwrite(data.data(), data.size(), 1, file);
wrote = fwrite(data.data(), 1, data.size(), file);
#endif
#endif
TRACEF("write_file: wrote %zu bytes to file %s", wrote, file_path);
if (wrote < data.size()) {
WARNINGF("write_file: not all data was written to file %s", file_path);
}
//TRACE("write_file: closing output file");
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
file.close();
#elif BOARD_NRF52
#elif BOARD_NRF52
file.close();
#endif
#else
#endif
#else
// Native
fclose(file);
#endif
#endif
}
else {
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) {
TRACEF("open_file: opening file %s", file_path);
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
const char* mode;
if (file_mode == RNS::FileStream::MODE_READ) {
mode = FILE_READ;
@@ -273,14 +273,13 @@ public:
//if (!file) {
File* file = new File(SPIFFS.open(file_path, mode));
if (file == nullptr || !(*file)) {
if (file != nullptr) delete file;
ERRORF("open_file: failed to open output file %s", file_path);
return {RNS::Type::NONE};
}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
#elif BOARD_NRF52
//File file = File(InternalFS);
File* file = new File(InternalFS);
#elif BOARD_NRF52
int mode;
if (file_mode == RNS::FileStream::MODE_READ) {
mode = FILE_O_READ;
@@ -300,7 +299,10 @@ public:
ERRORF("open_file: unsupported mode %d", file_mode);
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);
return {RNS::Type::NONE};
}
@@ -312,11 +314,11 @@ public:
//}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
#else
#warning("unsupported");
#else
#warning("unsupported");
return RNS::FileStream(RNS::Type::NONE);
#endif
#else // ARDUINO
#endif
#else // ARDUINO
// Native
const char* mode;
if (file_mode == RNS::FileStream::MODE_READ) {
@@ -340,136 +342,136 @@ public:
}
TRACEF("open_file: successfully opened file %s", file_path);
return RNS::FileStream(new FileStreamImpl(file));
#endif
#endif
}
virtual bool remove_file(const char* file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
return SPIFFS.remove(file_path);
#elif BOARD_NRF52
#elif BOARD_NRF52
return InternalFS.remove(file_path);
#else
#else
return false;
#endif
#else
#endif
#else
// Native
return (remove(file_path) == 0);
#endif
#endif
}
virtual bool rename_file(const char* from_file_path, const char* to_file_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
return SPIFFS.rename(from_file_path, to_file_path);
#elif BOARD_NRF52
#elif BOARD_NRF52
return InternalFS.rename(from_file_path, to_file_path);
#else
#else
return false;
#endif
#else
#endif
#else
// Native
return (rename(from_file_path, to_file_path) == 0);
#endif
#endif
}
/*virtua*/ bool directory_exists(const char* directory_path) {
TRACEF("directory_exists: checking for existence of directory %s", directory_path);
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
File file = SPIFFS.open(directory_path, FILE_READ);
if (file) {
bool is_directory = file.isDirectory();
file.close();
return is_directory;
}
#elif BOARD_NRF52
#elif BOARD_NRF52
File file(InternalFS);
if (file.open(directory_path, FILE_O_READ)) {
bool is_directory = file.isDirectory();
file.close();
return is_directory;
}
#else
#else
if (false) {
return false;
}
#endif
#endif
else {
return false;
}
#else
#else
// Native
struct stat st = {0};
return (stat(directory_path, &st) == 0);
#endif
#endif
}
virtual bool create_directory(const char* directory_path) {
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
if (!SPIFFS.mkdir(directory_path)) {
ERRORF("create_directory: failed to create directorty %s", directory_path);
return false;
}
return true;
#elif BOARD_NRF52
#elif BOARD_NRF52
if (!InternalFS.mkdir(directory_path)) {
ERRORF("create_directory: failed to create directorty %s", directory_path);
return false;
}
return true;
#else
#else
return false;
#endif
#else
#endif
#else
// Native
struct stat st = {0};
if (stat(directory_path, &st) == 0) {
return true;
}
return (mkdir(directory_path, 0700) == 0);
#endif
#endif
}
/*virtua*/ bool remove_directory(const char* directory_path) {
TRACEF("remove_directory: removing directory %s", directory_path);
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
//if (!LittleFS.rmdir_r(directory_path)) {
if (!SPIFFS.rmdir(directory_path)) {
ERRORF("remove_directory: failed to remove directorty %s", directory_path);
return false;
}
return true;
#elif BOARD_NRF52
#elif BOARD_NRF52
if (!InternalFS.rmdir_r(directory_path)) {
ERRORF("remove_directory: failed to remove directory %s", directory_path);
return false;
}
return true;
#else
#else
return false;
#endif
#else
#endif
#else
// Native
if (rmdir(directory_path) == 0) {
ERRORF("remove_directory: failed to remove directory %s", directory_path);
return false;
}
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);
std::list<std::string> files;
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef ARDUINO
#ifdef BOARD_ESP32
File root = SPIFFS.open(directory_path);
#elif BOARD_NRF52
#elif BOARD_NRF52
File root = InternalFS.open(directory_path);
#endif
#endif
if (!root) {
ERRORF("list_directory: failed to open directory %s", directory_path);
return files;
@@ -478,7 +480,8 @@ public:
while (file) {
if (!file.isDirectory()) {
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
file.close();
@@ -487,7 +490,7 @@ public:
TRACE("list_directory: returning directory listing");
root.close();
return files;
#else
#else
// Native
DIR *dir = opendir(directory_path);
if (dir == NULL) {
@@ -500,20 +503,21 @@ public:
continue;
}
char* name = entry->d_name;
files.push_back(name);
if (callback) callback(name);
else files.push_back(name);
}
if (closedir(dir) == -1) {
ERRORF("list_directory: failed to close directory %s", directory_path);
}
return files;
#endif
#endif
}
#ifdef ARDUINO
#ifdef ARDUINO
#ifdef BOARD_ESP32
#ifdef BOARD_ESP32
virtual size_t storage_size() {
return SPIFFS.totalBytes();
@@ -523,7 +527,7 @@ public:
return (SPIFFS.totalBytes() - SPIFFS.usedBytes());
}
#elif BOARD_NRF52
#elif BOARD_NRF52
static int _countLfsBlock(void *p, lfs_block_t block){
lfs_size_t *size = (lfs_size_t*) p;
@@ -558,9 +562,9 @@ public:
return (InternalFS.totalBytes() - InternalFS.usedBytes());
}
#endif
#endif
#else
#else
virtual size_t storage_size() {
return 0;
@@ -570,7 +574,7 @@ public:
return 0;
}
#endif
#endif
protected:
+142
View File
@@ -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();
}
+3 -3
View File
@@ -659,8 +659,8 @@ int runUnityTests(void) {
UNITY_BEGIN();
// Suite-level setup
RNS::Utilities::OS::dump_heap_stats();
size_t pre_memory = RNS::Utilities::OS::heap_available();
RNS::Utilities::Memory::dump_heap_stats();
size_t pre_memory = RNS::Utilities::Memory::heap_available();
TRACEF("testBytes: pre-mem: %u", pre_memory);
// Run tests
@@ -686,7 +686,7 @@ int runUnityTests(void) {
RUN_TEST(test_mid_zero_size_bytes);
// 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;
TRACEF("testBytes: post-mem: %u", post_memory);
TRACEF("testBytes: diff-mem: %u", diff_memory);
+538
View File
@@ -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();
}
+23 -27
View File
@@ -20,7 +20,7 @@ const char test_stream_path[] = "test_stream";
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);
{
@@ -29,7 +29,7 @@ void writeFile(const char* file_path) {
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;
TRACEF("testWriteFile: post-mem: %u", post_memory);
TRACEF("testWriteFile: diff-mem: %u", diff_memory);
@@ -39,7 +39,7 @@ void writeFile(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);
{
@@ -49,7 +49,7 @@ void readFile(const char* file_path) {
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;
TRACEF("testReadFile: post-mem: %u", post_memory);
TRACEF("testReadFile: diff-mem: %u", diff_memory);
@@ -59,7 +59,7 @@ void readFile(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);
// overwrite
@@ -77,7 +77,7 @@ void overwriteFile(const char* file_path) {
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;
TRACEF("testOverwriteFile: post-mem: %u", post_memory);
TRACEF("testOverwriteFile: diff-mem: %u", diff_memory);
@@ -87,12 +87,12 @@ void overwriteFile(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);
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;
TRACEF("testRemoveFile: post-mem: %u", post_memory);
TRACEF("testRemoveFile: diff-mem: %u", diff_memory);
@@ -102,7 +102,7 @@ void removeFile(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);
{
@@ -121,7 +121,7 @@ void writeFileStream(const char* file_path) {
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;
TRACEF("testWriteFileStream: post-mem: %u", post_memory);
TRACEF("testWriteFileStream: diff-mem: %u", diff_memory);
@@ -131,7 +131,7 @@ void writeFileStream(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);
{
@@ -153,7 +153,7 @@ void readFileStream(const char* file_path) {
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;
TRACEF("testReadFileStream: post-mem: %u", post_memory);
TRACEF("testReadFileStream: diff-mem: %u", diff_memory);
@@ -164,20 +164,16 @@ void readFileStream(const char* file_path) {
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);
{
for (int i = 0; i < 1; i++) {
std::list<std::string> files;
files = RNS::Utilities::OS::list_directory("/");
for (auto& file : files) {
INFOF("FILE: %s", file.c_str());
}
}
RNS::Utilities::OS::list_directory("/", [](const char* file_path) {
INFOF("FILE: %s", 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;
INFOF("testListDirectory: post-mem: %zu", post_memory);
INFOF("testListDirectory: diff-mem: %zu", diff_memory);
@@ -202,7 +198,7 @@ void testRemoveFile(const char* file_path) {
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);
{
@@ -211,7 +207,7 @@ void testReadNonexistantFile() {
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;
TRACEF("testReadNonexistantFile: post-mem: %u", post_memory);
TRACEF("testReadNonexistantFile: diff-mem: %u", diff_memory);
@@ -221,7 +217,7 @@ void testReadNonexistantFile() {
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);
{
@@ -230,7 +226,7 @@ void testWriteFail() {
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;
TRACEF("testWriteFail: post-mem: %u", post_memory);
TRACEF("testWriteFail: diff-mem: %u", diff_memory);
@@ -290,7 +286,7 @@ int runUnityTests(void) {
FileSystem::listDir("/cache");
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);
// 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");
}
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;
TRACEF("testFileSystem: post-mem: %u", post_memory);
TRACEF("testFileSystem: diff-mem: %u", diff_memory);
+3 -3
View File
@@ -542,8 +542,8 @@ void testSerializeDestinationTable() {
RNS::Transport::DestinationEntry entry_one;
entry_one._timestamp = 1.0;
entry_one._received_from = received;
entry_one._receiving_interface = test_interface.get_hash();
entry_one._random_blobs = blobs;
entry_one.receiving_interface_hash(test_interface.get_hash());
RNS::Bytes one;
one.assignHex("1111111111111111");
map.insert({one, entry_one});
@@ -551,8 +551,8 @@ void testSerializeDestinationTable() {
RNS::Transport::DestinationEntry entry_two;
entry_two._timestamp = 2.0;
entry_two._received_from = received;
entry_two._receiving_interface = test_interface.get_hash();
entry_two._random_blobs = blobs;
entry_two.receiving_interface_hash(test_interface.get_hash());
RNS::Bytes two;
two.assignHex("2222222222222222");
map.insert({two, entry_two});
@@ -561,8 +561,8 @@ void testSerializeDestinationTable() {
RNS::Transport::DestinationEntry entry;
entry._timestamp = 1.0;
entry._received_from = received;
entry._receiving_interface = test_interface.get_hash();
entry._random_blobs = blobs;
entry.receiving_interface_hash(test_interface.get_hash());
RNS::Bytes hash;
hash.assign(std::to_string(1000000000000001 + n).c_str());
map.insert({hash, entry});
+11 -2
View File
@@ -3,7 +3,7 @@
#include "Reticulum.h"
#include "Bytes.h"
void testReference() {
void test_reticulum_reference() {
HEAD("Running testReference...", RNS::LOG_TRACE);
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) {
// set stuff up here before each test
@@ -126,7 +134,8 @@ void tearDown(void) {
int runUnityTests(void) {
UNITY_BEGIN();
RUN_TEST(testReference);
RUN_TEST(test_reticulum_reference);
RUN_TEST(test_destination_entry_reference);
return UNITY_END();
}
+3 -3
View File
@@ -62,7 +62,7 @@ void testSerializeDestinationTable() {
RNS::Transport::DestinationEntry entry_one;
entry_one._timestamp = 1.0;
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;
RNS::Bytes one;
one.assignHex("1111111111111111");
@@ -71,7 +71,7 @@ void testSerializeDestinationTable() {
RNS::Transport::DestinationEntry entry_two;
entry_two._timestamp = 2.0;
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;
RNS::Bytes two;
two.assignHex("2222222222222222");
@@ -81,7 +81,7 @@ void testSerializeDestinationTable() {
RNS::Transport::DestinationEntry entry;
entry._timestamp = 1.0;
entry._received_from = received;
entry._receiving_interface = test_interface.get_hash();
entry.receiving_interface_hash(test_interface.get_hash());
entry._random_blobs = blobs;
RNS::Bytes hash;
hash.assign(std::to_string(1000000000000001 + n).c_str());