diff --git a/examples/test/Filesystem.cpp b/examples/test/Filesystem.cpp new file mode 100644 index 0000000..127b3d0 --- /dev/null +++ b/examples/test/Filesystem.cpp @@ -0,0 +1,433 @@ +#include "Filesystem.h" + +#include +#include + +#ifdef ARDUINO +#ifdef BOARD_ESP32 +#include +#include +#elif BOARD_NRF52 +#include +#include +using namespace Adafruit_LittleFS_Namespace; +#endif +#else +#include +#include +#include +#include +#endif + +#ifdef ARDUINO +void listDir(const char* dir){ + Serial.print("DIR: "); + Serial.println(dir); +#ifdef BOARD_ESP32 + File root = SPIFFS.open(dir); + if (!root) { + Serial.println("Failed to opend directory"); + return; + } + File file = root.openNextFile(); + while(file){ + Serial.print(" FILE: "); + Serial.println(file.name()); + file.close(); + file = root.openNextFile(); + } + root.close(); +#elif BOARD_NRF52 + File root = InternalFS.open(dir); + if (!root) { + Serial.println("Failed to opend directory"); + return; + } + File file = root.openNextFile(); + while(file){ + Serial.print(" FILE: "); + Serial.println(file.name()); + file.close(); + file = root.openNextFile(); + } + root.close(); +#endif +} +#endif + +bool Filesystem::init() { + TRACE("Filesystem initializing..."); + +#ifdef ARDUINO +#ifdef BOARD_ESP32 + // Setup filesystem + RNS::info("SPIFFS mounting filesystem"); + if (!SPIFFS.begin(true, "")){ + RNS::error("SPIFFS filesystem mount failed"); + return false; + } + uint32_t size = SPIFFS.totalBytes() / (1024 * 1024); + Serial.print("size: "); + Serial.print(size); + Serial.println(" MB"); + uint32_t used = SPIFFS.usedBytes() / (1024 * 1024); + Serial.print("used: "); + Serial.print(used); + Serial.println(" MB"); + // ensure filesystem is writable and format if not + RNS::Bytes test; + if (!OS::write_file("/test", test)) { + RNS::info("SPIFFS filesystem is being formatted, please wait..."); + SPIFFS.format(); + } + else { + OS::remove_file("/test"); + } + DEBUG("SPIFFS filesystem is ready"); +#elif BOARD_NRF52 + // Initialize Internal File System + RNS::info("InternalFS mounting filesystem"); + InternalFS.begin(); + RNS::info("InternalFS filesystem is ready"); +#endif + listDir("/"); +#endif + return true; +} + +/*virtual*/ bool Filesystem::file_exists(const char* file_path) { +#ifdef ARDUINO +#ifdef BOARD_ESP32 + File file = SPIFFS.open(file_path, FILE_READ); + if (file) { +#elif BOARD_NRF52 + File file(InternalFS); + if (file.open(file_path, FILE_O_READ)) { +#else + if (false) { +#endif +#else + // Native + FILE* file = fopen(file_path, "r"); + if (file != nullptr) { +#endif + //TRACE("file_exists: file exists, closing file"); +#ifdef ARDUINO +#ifdef BOARD_ESP32 + file.close(); +#elif BOARD_NRF52 + file.close(); +#endif +#else + // Native + fclose(file); +#endif + return true; + } + else { + RNS::error("file_exists: failed to open file " + std::string(file_path)); + return false; + } +} + +/*virtual*/ size_t Filesystem::read_file(const char* file_path, RNS::Bytes& data) { + size_t read = 0; +#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 + File file(InternalFS); + if (file.open(file_path, FILE_O_READ)) { + size_t size = file.size(); + read = file.readBytes((char*)data.writable(size), size); +#else + if (false) { + size_t size = 0; +#endif +#else + // Native + FILE* file = fopen(file_path, "r"); + if (file != nullptr) { + fseek(file, 0, SEEK_END); + size_t size = ftell(file); + rewind(file); + //size_t read = fread(data.writable(size), size, 1, file); + size_t read = fread(data.writable(size), 1, size, file); +#endif + TRACE("read_file: read " + std::to_string(read) + " RNS::Bytes from file " + std::string(file_path)); + if (read != size) { + RNS::error("read_file: failed to read file " + std::string(file_path)); + data.clear(); + } + //TRACE("read_file: closing input file"); +#ifdef ARDUINO +#ifdef BOARD_ESP32 + file.close(); +#elif BOARD_NRF52 + file.close(); +#endif +#else + // Native + fclose(file); +#endif + } + else { + RNS::error("read_file: failed to open input file " + std::string(file_path)); + } + return read; +} + +/*virtual*/ size_t Filesystem::write_file(const char* file_path, const RNS::Bytes& data) { + size_t wrote = 0; +#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 + File file(InternalFS); + if (file.open(file_path, FILE_O_WRITE)) { + wrote = file.write(data.data(), data.size()); +#else + if (false) { +#endif +#else + // Native + FILE* file = fopen(file_path, "w"); + if (file != nullptr) { + //size_t wrote = fwrite(data.data(), data.size(), 1, file); + size_t wrote = fwrite(data.data(), 1, data.size(), file); +#endif + TRACE("write_file: wrote " + std::to_string(wrote) + " RNS::Bytes to file " + std::string(file_path)); + if (wrote < data.size()) { + RNS::warning("write_file: not all data was written to file " + std::string(file_path)); + } + //TRACE("write_file: closing output file"); +#ifdef ARDUINO +#ifdef BOARD_ESP32 + file.close(); +#elif BOARD_NRF52 + file.close(); +#endif +#else + // Native + fclose(file); +#endif + } + else { + RNS::error("write_file: failed to open output file " + std::string(file_path)); + } + return wrote; +} + +/*virtual*/ bool Filesystem::remove_file(const char* file_path) { +#ifdef ARDUINO +#ifdef BOARD_ESP32 + return SPIFFS.remove(file_path); +#elif BOARD_NRF52 + return InternalFS.remove(file_path); +#else + return false; +#endif +#else + // Native + return (remove(file_path) == 0); +#endif +} + +/*virtual*/ bool Filesystem::rename_file(const char* from_file_path, const char* to_file_path) { +#ifdef ARDUINO +#ifdef BOARD_ESP32 + return SPIFFS.rename(from_file_path, to_file_path); +#elif BOARD_NRF52 + return InternalFS.rename(from_file_path, to_file_path); +#else + return false; +#endif +#else + // Native + return (rename(from_file_path, to_file_path) == 0); +#endif +} + +/*virtua*/ bool Filesystem::directory_exists(const char* directory_path) { + RNS::extreme("directory_exists: checking for existence of directory " + std::string(directory_path)); +#ifdef ARDUINO +#ifdef BOARD_ESP32 + File file = LittleFS.open(directory_path, FILE_READ); + if (file) { + bool is_directory = file.isDirectory(); + file.close(); + return is_directory; + } +#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 + if (false) { + return false; + } +#endif + else { + return false; + } +#else + // Native + return false; +#endif +} + +/*virtual*/ bool Filesystem::create_directory(const char* directory_path) { +#ifdef ARDUINO +#ifdef BOARD_ESP32 + if (!SPIFFS.mkdir(directory_path)) { + RNS::error("create_directory: failed to create directorty " + std::string(directory_path)); + return false; + } + return true; +#elif BOARD_NRF52 + if (!InternalFS.mkdir(directory_path)) { + RNS::error("create_directory: failed to create directorty " + std::string(directory_path)); + return false; + } + return true; +#else + return false; +#endif +#else + // Native + struct stat st = {0}; + if (stat(directory_path, &st) == 0) { + return true; + } + return (mkdir(directory_path, 0700) == 0); +#endif +} + +/*virtua*/ bool Filesystem::remove_directory(const char* directory_path) { + RNS::extreme("remove_directory: removing directory " + std::string(directory_path)); +#ifdef ARDUINO +#ifdef BOARD_ESP32 + //if (!LittleFS.rmdir_r(directory_path)) { + if (!LittleFS.rmdir(directory_path)) { + RNS::error("remove_directory: failed to remove directorty " + std::string(directory_path)); + return false; + } + return true; +#elif BOARD_NRF52 + if (!InternalFS.rmdir_r(directory_path)) { + RNS::error("remove_directory: failed to remove directory " + std::string(directory_path)); + return false; + } + return true; +#else + return false; +#endif +#else + // Native + return false; +#endif +} + +/*virtua*/ std::list Filesystem::list_directory(const char* directory_path) { + RNS::extreme("list_directory: listing directory " + std::string(directory_path)); + std::list files; +#ifdef ARDUINO +#ifdef BOARD_ESP32 + File root = LittleFS.open(dir); +#elif BOARD_NRF52 + File root = InternalFS.open(directory_path); +#endif + if (!root) { + RNS::error("list_directory: failed to open directory " + std::string(directory_path)); + return files; + } + File file = root.openNextFile(); + while (file) { + if (!file.isDirectory()) { + char* name = (char*)file.name(); + // CBA Adafruit LittleFS appears to returning improperly terminated file name at max size + if (strlen(name) >= LFS_NAME_MAX) { + name[LFS_NAME_MAX] = 0; + } + files.push_back(name); + } + // CBA Following close required to avoid leaking memory + file.close(); + file = root.openNextFile(); + } + RNS::extreme("list_directory: returning directory listing"); + root.close(); + return files; +#else + // Native + return files; +#endif +} + + +#ifdef ARDUINO + +#ifdef BOARD_ESP32 + +/*virtual*/ size_t Filesystem::storage_size() { + return 0; +} + +/*virtual*/ size_t Filesystem::storage_available() { + return 0; +} + +#elif BOARD_NRF52 + +static int _countLfsBlock(void *p, lfs_block_t block){ + lfs_size_t *size = (lfs_size_t*) p; + *size += 1; + return 0; +} + +static lfs_ssize_t getUsedBlockCount() { + lfs_size_t size = 0; + lfs_traverse(InternalFS._getFS(), _countLfsBlock, &size); + return size; +} + +static int totalBytes() { + const lfs_config* config = InternalFS._getFS()->cfg; + return config->block_size * config->block_count; +} + +static int usedBytes() { + const lfs_config* config = InternalFS._getFS()->cfg; + const int usedBlockCount = getUsedBlockCount(); + return config->block_size * usedBlockCount; +} + +/*virtual*/ size_t Filesystem::storage_size() { + return totalBytes(); +} + +/*virtual*/ size_t Filesystem::storage_available() { + return (totalBytes() - usedBytes()); +} + +#endif + +#else + +/*virtual*/ size_t Filesystem::storage_size() { + return 0; +} + +/*virtual*/ size_t Filesystem::storage_available() { + return 0; +} + +#endif diff --git a/examples/test/TestFilesystem.h b/examples/test/Filesystem.h similarity index 59% rename from examples/test/TestFilesystem.h rename to examples/test/Filesystem.h index 7f971b9..add917c 100644 --- a/examples/test/TestFilesystem.h +++ b/examples/test/Filesystem.h @@ -3,11 +3,10 @@ #include #include -class TestFilesystem : public RNS::Filesystem { +class Filesystem : public RNS::Filesystem { public: - TestFilesystem(); - virtual ~TestFilesystem(); + bool init(); protected: virtual bool file_exists(const char* file_path); @@ -15,6 +14,11 @@ protected: virtual size_t write_file(const char* file_path, const RNS::Bytes& data); virtual bool remove_file(const char* file_path); virtual bool rename_file(const char* from_file_path, const char* to_file_path); + 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 list_directory(const char* directory_path); + virtual size_t storage_size(); + virtual size_t storage_available(); }; diff --git a/examples/test/Test.cpp b/examples/test/Test.cpp index de6ecba..16bcb93 100644 --- a/examples/test/Test.cpp +++ b/examples/test/Test.cpp @@ -8,5 +8,7 @@ void test() { testReference(); testCrypto(); testPersistence(); + testFilesystem(); + testReticulum(); } diff --git a/examples/test/Test.h b/examples/test/Test.h index c7b861f..34a631f 100644 --- a/examples/test/Test.h +++ b/examples/test/Test.h @@ -7,3 +7,5 @@ void testCollections(); void testReference(); void testCrypto(); void testPersistence(); +void testFilesystem(); +void testReticulum(); diff --git a/examples/test/TestBytes.cpp b/examples/test/TestBytes.cpp index 3b89fca..cfbecb7 100644 --- a/examples/test/TestBytes.cpp +++ b/examples/test/TestBytes.cpp @@ -1,5 +1,6 @@ //#include +#include #include "Bytes.h" #include "Log.h" @@ -363,10 +364,20 @@ void testBytesResize() { void testBytes() { RNS::head("Running testBytes...", RNS::LOG_EXTREME); + + size_t pre_memory = RNS::Utilities::OS::memory_available(); + TRACE("testBytes: pre-mem: " + std::to_string(pre_memory)); + testBytesMain(); testCowBytes(); testBytesConversion(); testBytesResize(); + + size_t post_memory = RNS::Utilities::OS::memory_available(); + size_t diff_memory = (int)pre_memory - (int)post_memory; + TRACE("testBytes: post-mem: " + std::to_string(post_memory)); + TRACE("testBytes: diff-mem: " + std::to_string(diff_memory)); + assert(diff_memory == 0); } /* diff --git a/examples/test/TestFilesystem.cpp b/examples/test/TestFilesystem.cpp index ef76813..b14f59f 100644 --- a/examples/test/TestFilesystem.cpp +++ b/examples/test/TestFilesystem.cpp @@ -1,265 +1,75 @@ -#include "TestFilesystem.h" +//#include #include -#include +#include "Log.h" -#ifdef ARDUINO -#ifdef ESP32 -#include -#include -#elif NRF52 -#include -#include -using namespace Adafruit_LittleFS_Namespace; -#endif -#else -#include -#include -#include -#include -#endif +#include using namespace RNS; +using namespace RNS::Utilities; -#ifdef ARDUINO -void listDir(char * dir){ - Serial.print("DIR: "); - Serial.println(dir); -#ifdef ESP32 - File root = SPIFFS.open(dir); - File file = root.openNextFile(); - while(file){ - Serial.print(" FILE: "); - Serial.println(file.name()); - file = root.openNextFile(); - } -#elif NRF52 - File root = InternalFS.open(dir); - File file = root.openNextFile(); - while(file){ - Serial.print(" FILE: "); - Serial.println(file.name()); - file = root.openNextFile(); - } -#endif -} -#endif +void testListDirectory() { -TestFilesystem::TestFilesystem() : Filesystem() { - TRACE("TestFilesystem initializing..."); + size_t pre_memory = OS::memory_available(); + info("testListDirectory: pre-mem: " + std::to_string(pre_memory)); -#ifdef ARDUINO -#ifdef ESP32 - // Setup filesystem - info("SPIFFS mounting filesystem"); - if (!SPIFFS.begin(true, "")){ - error("SPIFFS filesystem mount failed"); - return; - } - uint32_t size = SPIFFS.totalBytes() / (1024 * 1024); - Serial.print("size: "); - Serial.print(size); - Serial.println(" MB"); - uint32_t used = SPIFFS.usedBytes() / (1024 * 1024); - Serial.print("used: "); - Serial.print(used); - Serial.println(" MB"); - // ensure filesystem is writable and format if not - Bytes test; - if (!OS::write_file("/test", test)) { - info("SPIFFS filesystem is being formatted, please wait..."); - SPIFFS.format(); - } - else { - OS::remove_file("/test"); - } - DEBUG("SPIFFS filesystem is ready"); -#elif NRF52 - // Initialize Internal File System - info("InternalFS mounting filesystem"); - InternalFS.begin(); - info("InternalFS filesystem is ready"); -#endif - listDir("/"); -#endif - -} - -/*virtual*/ TestFilesystem::~TestFilesystem() { -} - -/*virtual*/ bool TestFilesystem::file_exists(const char* file_path) { -#ifdef ARDUINO -#ifdef ESP32 - File file = SPIFFS.open(file_path, FILE_READ); - if (file) { -#elif NRF52 - File file(InternalFS); - if (file.open(file_path, FILE_O_READ)) { -#else - if (false) { -#endif -#else - FILE* file = fopen(file_path, "r"); - if (file != nullptr) { -#endif - //TRACE("file_exists: file exists, closing file"); -#ifdef ARDUINO -#ifdef ESP32 - file.close(); -#elif NRF52 - file.close(); -#endif -#else - fclose(file); -#endif - return true; - } - else { - error("file_exists: failed to open file " + std::string(file_path)); - return false; - } -} - -/*virtual*/ size_t TestFilesystem::read_file(const char* file_path, Bytes& data) { - size_t read = 0; -#ifdef ARDUINO -#ifdef 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 NRF52 - File file(InternalFS); - if (file.open(file_path, FILE_O_READ)) { - size_t size = file.size(); - read = file.readBytes((char*)data.writable(size), size); -#else - if (false) { - size_t size = 0; -#endif -#else - FILE* file = fopen(file_path, "r"); - if (file != nullptr) { - fseek(file, 0, SEEK_END); - size_t size = ftell(file); - rewind(file); - //size_t read = fread(data.writable(size), size, 1, file); - size_t read = fread(data.writable(size), 1, size, file); -#endif - TRACE("read_file: read " + std::to_string(read) + " Bytes from file " + std::string(file_path)); - if (read != size) { - error("read_file: failed to read file " + std::string(file_path)); - data.clear(); + for (int i = 0; i < 1; i++) { + std::list files; + files = OS::list_directory("/"); + for (auto& file : files) { + info("FILE: " + file); } - //TRACE("read_file: closing input file"); -#ifdef ARDUINO -#ifdef ESP32 - file.close(); -#elif NRF52 - file.close(); -#endif -#else - fclose(file); -#endif } - else { - error("read_file: failed to open input file " + std::string(file_path)); - } - return read; + + size_t post_memory = OS::memory_available(); + size_t diff_memory = (int)pre_memory - (int)post_memory; + info("testListDirectory: post-mem: " + std::to_string(post_memory)); + info("testListDirectory: diff-mem: " + std::to_string(diff_memory)); + assert(diff_memory == 0); } -/*virtual*/ size_t TestFilesystem::write_file(const char* file_path, const Bytes& data) { - size_t wrote = 0; -#ifdef ARDUINO -#ifdef ESP32 - File file = SPIFFS.open(file_path, FILE_WRITE); - if (file) { - wrote = file.write(data.data(), data.size()); -#elif NRF52 - File file(InternalFS); - if (file.open(file_path, FILE_O_WRITE)) { - wrote = file.write(data.data(), data.size()); -#else - if (false) { -#endif -#else - FILE* file = fopen(file_path, "w"); - if (file != nullptr) { - //size_t wrote = fwrite(data.data(), data.size(), 1, file); - size_t wrote = fwrite(data.data(), 1, data.size(), file); -#endif - TRACE("write_file: wrote " + std::to_string(wrote) + " Bytes to file " + std::string(file_path)); - if (wrote < data.size()) { - warning("write_file: not all data was written to file " + std::string(file_path)); - } - //TRACE("write_file: closing output file"); -#ifdef ARDUINO -#ifdef ESP32 - file.close(); -#elif NRF52 - file.close(); -#endif -#else - fclose(file); -#endif - } - else { - error("write_file: failed to open output file " + std::string(file_path)); - } - return wrote; +void testFilesystem() { + RNS::head("Running testFilesystem...", RNS::LOG_EXTREME); + + testListDirectory(); + } -/*virtual*/ bool TestFilesystem::remove_file(const char* file_path) { -#ifdef ARDUINO -#ifdef ESP32 - return SPIFFS.remove(file_path); -#elif NRF52 - return InternalFS.remove(file_path); -#else - return false; -#endif -#else - return (remove(file_path) == 0); -#endif +/* +void setUp(void) { + // set stuff up here } -/*virtual*/ bool TestFilesystem::rename_file(const char* from_file_path, const char* to_file_path) { -#ifdef ARDUINO -#ifdef ESP32 - return SPIFFS.rename(from_file_path, to_file_path); -#elif NRF52 - return InternalFS.rename(from_file_path, to_file_path); -#else - return false; -#endif -#else - return (rename(from_file_path, to_file_path) == 0); -#endif +void tearDown(void) { + // clean stuff up here } -/*virtual*/ bool TestFilesystem::create_directory(const char* directory_path) { -#ifdef ARDUINO -#ifdef ESP32 - if (!SPIFFS.mkdir(directory_path)) { - error("create_directory: failed to create directorty " + std::string(directory_path)); - return false; - } - return true; -#elif NRF52 - if (!InternalFS.mkdir(directory_path)) { - error("create_directory: failed to create directorty " + std::string(directory_path)); - return false; - } - return true; -#else - return false; -#endif -#else - struct stat st = {0}; - if (stat(directory_path, &st) == 0) { - return true; - } - return (mkdir(directory_path, 0700) == 0); -#endif +int runUnityTests(void) { + UNITY_BEGIN(); + RUN_TEST(testBytes); + RUN_TEST(testCowBytes); + RUN_TEST(testBytesConversion); + RUN_TEST(testMap); + return UNITY_END(); } + +// For native dev-platform or for some embedded frameworks +int main(void) { + return runUnityTests(); +} + +// 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() {} + +// For ESP-IDF framework +void app_main() { + runUnityTests(); +} +*/ diff --git a/examples/test/TestPersistence.cpp b/examples/test/TestPersistence.cpp index ca50e1a..126beed 100644 --- a/examples/test/TestPersistence.cpp +++ b/examples/test/TestPersistence.cpp @@ -559,7 +559,7 @@ void testSerializeDestinationTable() { RNS::Transport::DestinationEntry entry_one; entry_one._timestamp = 1.0; entry_one._received_from = received; - entry_one._receiving_interface = test_interface; + entry_one._receiving_interface = test_interface.get_hash(); entry_one._random_blobs = blobs; RNS::Bytes one; one.assignHex("1111111111111111"); @@ -568,7 +568,7 @@ void testSerializeDestinationTable() { RNS::Transport::DestinationEntry entry_two; entry_two._timestamp = 2.0; entry_two._received_from = received; - entry_two._receiving_interface = test_interface; + entry_two._receiving_interface = test_interface.get_hash(); entry_two._random_blobs = blobs; RNS::Bytes two; two.assignHex("2222222222222222"); @@ -578,7 +578,7 @@ void testSerializeDestinationTable() { RNS::Transport::DestinationEntry entry; entry._timestamp = 1.0; entry._received_from = received; - entry._receiving_interface = test_interface; + entry._receiving_interface = test_interface.get_hash(); entry._random_blobs = blobs; RNS::Bytes hash; hash.assign(std::to_string(1000000000000001 + n).c_str()); diff --git a/examples/test/TestReticulum.cpp b/examples/test/TestReticulum.cpp new file mode 100644 index 0000000..ddec622 --- /dev/null +++ b/examples/test/TestReticulum.cpp @@ -0,0 +1,65 @@ +//#include + +#include "Reticulum.h" +#include "Transport.h" +#include "Log.h" + +#include + +RNS::Reticulum reticulum = {RNS::Type::NONE}; + +void testDestinationTable() { + +} + +void testReticulum() { + RNS::head("Running testReticulum...", RNS::LOG_EXTREME); + + reticulum = RNS::Reticulum(); + reticulum.transport_enabled(true); + reticulum.probe_destination_enabled(true); + reticulum.start(); + + testDestinationTable(); + + reticulum = {RNS::Type::NONE}; +} + +/* +void setUp(void) { + // set stuff up here +} + +void tearDown(void) { + // clean stuff up here +} + +int runUnityTests(void) { + UNITY_BEGIN(); + RUN_TEST(testBytes); + RUN_TEST(testCowBytes); + RUN_TEST(testBytesConversion); + RUN_TEST(testMap); + return UNITY_END(); +} + +// For native dev-platform or for some embedded frameworks +int main(void) { + return runUnityTests(); +} + +// 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() {} + +// For ESP-IDF framework +void app_main() { + runUnityTests(); +} +*/ diff --git a/examples/test/main.cpp b/examples/test/main.cpp index c87705c..a5a3c23 100644 --- a/examples/test/main.cpp +++ b/examples/test/main.cpp @@ -1,6 +1,6 @@ //#define NDEBUG -#include "TestFilesystem.h" +#include "Filesystem.h" #include "Test.h" @@ -22,20 +22,25 @@ #include #include -TestFilesystem filesystem; +Filesystem filesystem; void setup() { #ifdef ARDUINO Serial.begin(115200); - Serial.print("Hello from T-Beam on PlatformIO!\n"); + while (!Serial) { + if (millis() > 2000) + break; + } + Serial.print("Hello from T-Beam on PlatformIO!\n"); #endif RNS::loglevel(RNS::LOG_EXTREME); //RNS::loglevel(RNS::LOG_MEM); if (filesystem) { - RNS::info("TestFilesystem exists"); + RNS::info("Filesystem exists"); + filesystem.init(); } RNS::Utilities::OS::register_filesystem(filesystem); @@ -54,6 +59,8 @@ void setup() { //testCrypto(); //testPersistence(); testBytes(); + //testFilesystem(); + //testReticulum(); RNS::loglevel(loglevel); TRACE("Finished running tests"); diff --git a/examples/test/platformio.ini b/examples/test/platformio.ini index 83ded4b..2c8533e 100644 --- a/examples/test/platformio.ini +++ b/examples/test/platformio.ini @@ -15,6 +15,11 @@ include_dir = . src_dir = . +[env] +framework = arduino +monitor_speed = 115200 +upload_speed = 921600 + [env:native] platform = native build_flags = @@ -61,8 +66,6 @@ lib_compat_mode = off [env:cubecell-gps] platform = heltec-cubecell board = cubecell_gps -framework = arduino -monitor_speed = 115200 ;build_flags = -Wl,-Map,output.map build_flags = -std=c++11 @@ -84,8 +87,6 @@ board = heltec_wireless_tracker upload_protocol = esp-builtin ;board_build.partitions = no_ota.csv ;board_build.partitions = huge_app.csv -framework = arduino -monitor_speed = 115200 build_flags = -Wall -Wextra @@ -93,7 +94,7 @@ build_flags = -Wno-format -I variants/heltec_wireless_tracker -I. - -DESP32 + -DBOARD_ESP32 lib_deps = lovyan03/LovyanGFX@^1.1.8 ArduinoJson@^6.21.3 @@ -104,15 +105,13 @@ lib_deps = platform = espressif32 board = ttgo-lora32-v21 board_build.partitions = no_ota.csv -framework = arduino -monitor_speed = 115200 build_flags = -Wall -Wextra -Wno-missing-field-initializers -Wno-format -I. - -DESP32 + -DBOARD_ESP32 lib_deps = ArduinoJson@^6.21.3 https://github.com/attermann/arduinolibs.git @@ -123,15 +122,13 @@ platform = espressif32 board = ttgo-t-beam board_build.partitions = no_ota.csv ;board_build.partitions = huge_app.csv -framework = arduino -monitor_speed = 115200 build_flags = -Wall -Wextra -Wno-missing-field-initializers -Wno-format -I. - -DESP32 + -DBOARD_ESP32 lib_deps = ArduinoJson@^6.21.3 https://github.com/attermann/arduinolibs.git @@ -141,8 +138,7 @@ lib_deps = platform = nordicnrf52 board = wiscore_rak4631 board_build.partitions = no_ota.csv -framework = arduino -monitor_speed = 115200 +board_build.filesystem = littlefs build_flags = -fexceptions -Wall @@ -150,7 +146,8 @@ build_flags = -Wno-missing-field-initializers -Wno-format -I. - ;-DNRF52 + -DBOARD_NRF52 +build_unflags = -fno-exceptions lib_deps = ArduinoJson@^6.21.3 https://github.com/attermann/arduinolibs.git diff --git a/src/Destination.cpp b/src/Destination.cpp index 51d64b7..b6a1982 100644 --- a/src/Destination.cpp +++ b/src/Destination.cpp @@ -283,6 +283,7 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In announce_data << new_app_data; } + // CBA ACCUMULATES _object->_path_responses.insert({tag, {OS::time(), announce_data}}); } //TRACE("Destination::announce: announce_data:" + announce_data.toHex()); diff --git a/src/Destination.h b/src/Destination.h index ec4bf56..ea7c0f3 100644 --- a/src/Destination.h +++ b/src/Destination.h @@ -173,6 +173,7 @@ namespace RNS { inline Type::Link::status status() const { assert(_object); return _object->_status; } inline const Callbacks& callbacks() const { assert(_object); return _object->_callbacks; } inline const Identity& identity() const { assert(_object); return _object->_identity; } + inline const std::map& path_responses() { assert(_object); return _object->_path_responses; } inline std::string toString() const { if (!_object) return ""; return "{Destination:" + _object->_hash.toHex() + "}"; } diff --git a/src/Filesystem.h b/src/Filesystem.h index 90d5f64..0de6216 100644 --- a/src/Filesystem.h +++ b/src/Filesystem.h @@ -77,6 +77,8 @@ namespace RNS { virtual bool create_directory(const char* directory_path) { return false; } virtual bool remove_directory(const char* directory_path) { return false; } virtual std::list list_directory(const char* directory_path) { TRACE("list_directory: empty"); return _empty; } + virtual size_t storage_size() { return 0; } + virtual size_t storage_available() { return 0; } public: inline bool do_file_exists(const char* file_path) { assert(_object); return _object->do_file_exists(file_path); } @@ -87,7 +89,9 @@ namespace RNS { inline bool do_directory_exists(const char* directory_path) { assert(_object); return _object->do_directory_exists(directory_path); } inline bool do_create_directory(const char* directory_path) { assert(_object); return _object->do_create_directory(directory_path); } inline bool do_remove_directory(const char* directory_path) { assert(_object); return _object->do_remove_directory(directory_path); } - virtual std::list do_list_directory(const char* directory_path) { assert(_object); return _object->do_list_directory(directory_path); } + inline std::list do_list_directory(const char* directory_path) { assert(_object); return _object->do_list_directory(directory_path); } + inline size_t do_storage_size() { assert(_object); return _object->do_storage_size(); } + inline size_t do_storage_available() { assert(_object); return _object->do_storage_available(); } private: std::list _empty; @@ -111,15 +115,17 @@ namespace RNS { Object(Filesystem* parent, const char* name) : _parent(parent) { MEM("Filesystem::Data object created, this: " + std::to_string((uintptr_t)this)); } virtual ~Object() { MEM("Filesystem::Data object destroyed, this: " + std::to_string((uintptr_t)this)); } private: - virtual inline bool do_file_exists(const char* file_path) { if (_parent == nullptr) return false; return _parent->file_exists(file_path); } - virtual inline size_t do_read_file(const char* file_path, Bytes& data) { if (_parent == nullptr) return {Bytes::NONE}; return _parent->read_file(file_path, data); } - virtual inline size_t do_write_file(const char* file_path, const Bytes& data) { if (_parent == nullptr) return false; return _parent->write_file(file_path, data); } - virtual inline bool do_remove_file(const char* file_path) { if (_parent == nullptr) return false; return _parent->remove_file(file_path); } - virtual inline bool do_rename_file(const char* from_file_path, const char* to_file_path) { if (_parent == nullptr) return false; return _parent->rename_file(from_file_path, to_file_path); } - virtual inline bool do_directory_exists(const char* directory_path) { if (_parent == nullptr) return false; return _parent->directory_exists(directory_path); } - virtual inline bool do_create_directory(const char* directory_path) { if (_parent == nullptr) return false; return _parent->create_directory(directory_path); } - virtual inline bool do_remove_directory(const char* directory_path) { if (_parent == nullptr) return false; return _parent->remove_directory(directory_path); } - virtual inline std::list do_list_directory(const char* directory_path) { if (_parent == nullptr) return _empty; return _parent->list_directory(directory_path); } + inline bool do_file_exists(const char* file_path) { if (_parent == nullptr) return false; return _parent->file_exists(file_path); } + inline size_t do_read_file(const char* file_path, Bytes& data) { if (_parent == nullptr) return {Bytes::NONE}; return _parent->read_file(file_path, data); } + inline size_t do_write_file(const char* file_path, const Bytes& data) { if (_parent == nullptr) return false; return _parent->write_file(file_path, data); } + inline bool do_remove_file(const char* file_path) { if (_parent == nullptr) return false; return _parent->remove_file(file_path); } + inline bool do_rename_file(const char* from_file_path, const char* to_file_path) { if (_parent == nullptr) return false; return _parent->rename_file(from_file_path, to_file_path); } + inline bool do_directory_exists(const char* directory_path) { if (_parent == nullptr) return false; return _parent->directory_exists(directory_path); } + inline bool do_create_directory(const char* directory_path) { if (_parent == nullptr) return false; return _parent->create_directory(directory_path); } + inline bool do_remove_directory(const char* directory_path) { if (_parent == nullptr) return false; return _parent->remove_directory(directory_path); } + inline std::list do_list_directory(const char* directory_path) { if (_parent == nullptr) return _empty; return _parent->list_directory(directory_path); } + inline size_t do_storage_size() { if (_parent == nullptr) return false; return _parent->storage_size(); } + inline size_t do_storage_available() { if (_parent == nullptr) return false; return _parent->storage_available(); } private: Filesystem* _parent = nullptr; std::list _empty; diff --git a/src/Identity.cpp b/src/Identity.cpp index 0342a98..a35adcd 100644 --- a/src/Identity.cpp +++ b/src/Identity.cpp @@ -11,6 +11,7 @@ #include "Cryptography/Fernet.h" #include "Cryptography/Random.h" +#include #include using namespace RNS; @@ -20,6 +21,9 @@ using namespace RNS::Utilities; /*static*/ std::map Identity::_known_destinations; /*static*/ bool Identity::_saving_known_destinations = false; +// CBA +/*static*/ //uint16_t Identity::_known_destinations_maxsize = 100; +/*static*/ uint16_t Identity::_known_destinations_maxsize = 20; Identity::Identity(bool create_keys /*= true*/) : _object(new Object()) { if (create_keys) { @@ -185,7 +189,8 @@ Can be used to load previously created and saved identities into Reticulum. throw std::invalid_argument("Can't remember " + destination_hash.toHex() + ", the public key size of " + std::to_string(public_key.size()) + " is not valid."); } else { - //_known_destinations[destination_hash] = {OS::time(), packet_hash, public_key, app_data}; + //p _known_destinations[destination_hash] = {OS::time(), packet_hash, public_key, app_data}; + // CBA ACCUMULATES _known_destinations.insert({destination_hash, {OS::time(), packet_hash, public_key, app_data}}); } } @@ -283,6 +288,7 @@ Recall last heard app_data for a destination hash. 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}); } } @@ -340,6 +346,36 @@ Recall last heard app_data for a destination hash. } +/*static*/ void Identity::cull_known_destinations() { + TRACE("Transport::cull_path_table()"); + if (_known_destinations.size() > _known_destinations_maxsize) { + // prune by age + uint16_t count = 0; + std::vector> sorted_pairs; + // Copy key/value pairs from map into vector + std::for_each(_known_destinations.begin(), _known_destinations.end(), [&](const std::pair& ref) { + sorted_pairs.push_back(ref); + }); + // Sort vector using specified comparator + std::sort(sorted_pairs.begin(), sorted_pairs.end(), [](const std::pair &left, const std::pair &right) { + return left.second._timestamp < right.second._timestamp; + }); + // Iterate vector of sorted values + for (auto& [destination_hash, identity_entry] : sorted_pairs) { + TRACE("Transport::cull_path_table: Removing destination " + destination_hash.toHex() + " from known destinations"); + // Remove destination from known destinations + if (_known_destinations.erase(destination_hash) < 1) { + warning("Failed to remove destination " + destination_hash.toHex() + " from known destinations"); + } + ++count; + if (_known_destinations.size() <= _known_destinations_maxsize) { + break; + } + } + DEBUG("Removed " + std::to_string(count) + " path(s) from known destinations"); + } +} + /*static*/ bool Identity::validate_announce(const Packet& packet) { try { if (packet.packet_type() == Type::Packet::ANNOUNCE) { diff --git a/src/Identity.h b/src/Identity.h index 84a180f..82b4c15 100644 --- a/src/Identity.h +++ b/src/Identity.h @@ -40,6 +40,8 @@ namespace RNS { public: static std::map _known_destinations; static bool _saving_known_destinations; + // CBA + static uint16_t _known_destinations_maxsize; public: Identity(Type::NoneConstructor none) { @@ -111,6 +113,9 @@ namespace RNS { static Bytes recall_app_data(const Bytes& destination_hash); static bool save_known_destinations(); static void load_known_destinations(); + // CBA + static void cull_known_destinations(); + /* Get a SHA-256 hash of passed data. @@ -120,6 +125,7 @@ namespace RNS { static inline const Bytes full_hash(const Bytes& data) { return Cryptography::sha256(data); } + /* Get a truncated SHA-256 hash of passed data. @@ -130,6 +136,7 @@ namespace RNS { //p return Identity.full_hash(data)[:(Identity.TRUNCATED_HASHLENGTH//8)] return full_hash(data).left(Type::Identity::TRUNCATED_HASHLENGTH/8); } + /* Get a random SHA-256 hash. diff --git a/src/Interface.cpp b/src/Interface.cpp index 6d6393a..071241d 100644 --- a/src/Interface.cpp +++ b/src/Interface.cpp @@ -9,12 +9,16 @@ using namespace RNS::Type::Interface; /*static*/ uint8_t Interface::DISCOVER_PATHS_FOR = MODE_ACCESS_POINT | MODE_GATEWAY; Interface::Interface() : _object(new Object(this)), _creator(true) { - _object->_hash = Identity::full_hash({toString()}); + // CBA MCU + //_object->_hash = Identity::full_hash({toString()}); + _object->_hash = Identity::truncated_hash({toString()}); MEM("Interface object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); } Interface::Interface(const char* name) : _object(new Object(this, name)), _creator(true) { - _object->_hash = Identity::full_hash({toString()}); + // CBA MCU + //_object->_hash = Identity::full_hash({toString()}); + _object->_hash = Identity::truncated_hash({toString()}); MEM("Interface object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); } @@ -37,7 +41,9 @@ Interface::Interface(const char* name) : _object(new Object(this, name)), _creat const Bytes Interface::get_hash() const { assert(_object); - //return Identity::full_hash({toString()}); + // CBA MCU + ////return Identity::full_hash({toString()}); + //return Identity::truncated_hash({toString()}); return _object->_hash; } diff --git a/src/Interface.h b/src/Interface.h index 1f350a3..c4b687e 100644 --- a/src/Interface.h +++ b/src/Interface.h @@ -95,6 +95,7 @@ namespace RNS { void process_announce_queue(); inline void detach() {} + // CBA ACCUMULATES inline void add_announce(AnnounceEntry& entry) { assert(_object); _object->_announce_queue.push_back(entry); } protected: diff --git a/src/Log.cpp b/src/Log.cpp index 2892bb5..c9b7867 100644 --- a/src/Log.cpp +++ b/src/Log.cpp @@ -107,3 +107,6 @@ void RNS::head(const char* msg, LogLevel level) { #endif doLog(msg, level); } + +void RNS::doLog(LogLevel level, const char* msg, ...) { +} diff --git a/src/Log.h b/src/Log.h index 0c1c0aa..2844065 100644 --- a/src/Log.h +++ b/src/Log.h @@ -43,6 +43,7 @@ namespace RNS { void setLogCallback(log_callback on_log = nullptr); void doLog(const char* msg, LogLevel level); + void doLog(LogLevel level, const char* msg, ...); inline void log(const char* msg, LogLevel level = LOG_NOTICE) { doLog(msg, level); } #ifdef ARDUINO diff --git a/src/Packet.cpp b/src/Packet.cpp index 4616196..3000af5 100644 --- a/src/Packet.cpp +++ b/src/Packet.cpp @@ -506,7 +506,9 @@ void Packet::update_hash() { const Bytes Packet::get_hash() const { assert(_object); Bytes hashable_part = get_hashable_part(); - return Identity::full_hash(hashable_part); + // CBA MCU + //return Identity::full_hash(hashable_part); + return Identity::truncated_hash(hashable_part); } const Bytes Packet::getTruncatedHash() const { diff --git a/src/Reticulum.cpp b/src/Reticulum.cpp index 404de2d..49839b3 100644 --- a/src/Reticulum.cpp +++ b/src/Reticulum.cpp @@ -292,6 +292,9 @@ void Reticulum::clean_caches() { Transport::clean_caches(); + // CBA + Identity::cull_known_destinations(); + } void Reticulum::clear_caches() { diff --git a/src/Transport.cpp b/src/Transport.cpp index 8af9246..a9ec491 100644 --- a/src/Transport.cpp +++ b/src/Transport.cpp @@ -82,14 +82,15 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); /*static*/ bool Transport::_saving_path_table = false; // CBA MCU /*static*/ //uint16_t Transport::_hashlist_maxsize = 1000000; -/*static*/ uint16_t Transport::_hashlist_maxsize = 10000; +/*static*/ //uint16_t Transport::_hashlist_maxsize = 100; +/*static*/ uint16_t Transport::_hashlist_maxsize = 20; // CBA MCU /*static*/ //uint16_t Transport::_max_pr_tags = 32000; -/*static*/ uint16_t Transport::_max_pr_tags = 320; +/*static*/ uint16_t Transport::_max_pr_tags = 32; // CBA -/*static*/ uint16_t Transport::_path_table_maxsize = 10; -/*static*/ uint16_t Transport::_path_table_maxpersist = 10; +/*static*/ uint16_t Transport::_path_table_maxsize = 20; +/*static*/ uint16_t Transport::_path_table_maxpersist = 20; /*static*/ double Transport::_last_saved = 0.0; /*static*/ float Transport::_save_interval = 3600.0; /*static*/ uint8_t Transport::_destination_table_crc = 0; @@ -104,6 +105,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); /*static*/ uint32_t Transport::_packets_sent = 0; /*static*/ uint32_t Transport::_packets_received = 0; /*static*/ uint32_t Transport::_destinations_added = 0; +/*static*/ size_t Transport::_last_memory = 0; /*static*/ void Transport::start(const Reticulum& reticulum_instance) { info("Transport starting..."); @@ -128,8 +130,6 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); std::string transport_identity_path = Reticulum::_storagepath + "/transport_identity"; DEBUG("Checking for transport identity..."); try { -// CBA TEST -//OS::remove_file(transport_identity_path.c_str()); if (OS::file_exists(transport_identity_path.c_str())) { _identity = Identity::from_file(transport_identity_path.c_str()); } @@ -168,7 +168,9 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); // Create transport-specific destination for path request Destination path_request_destination({Type::NONE}, Type::Destination::IN, Type::Destination::PLAIN, APP_NAME, "path.request"); path_request_destination.set_packet_callback(path_request_handler); + // CBA ACCUMULATES _control_destinations.insert(path_request_destination); + // CBA ACCUMULATES _control_hashes.insert(path_request_destination.hash()); DEBUG("Created transport-specific path request destination " + path_request_destination.hash().toHex()); @@ -177,7 +179,9 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); tunnel_synthesize_destination.set_packet_callback(tunnel_synthesize_handler); // CBA BUG? //p Transport.control_destinations.append(Transport.tunnel_synthesize_handler) + // CBA ACCUMULATES _control_destinations.insert(tunnel_synthesize_destination); + // CBA ACCUMULATES _control_hashes.insert(tunnel_synthesize_destination.hash()); DEBUG("Created transport-specific tunnel synthesize destination " + tunnel_synthesize_destination.hash().toHex()); @@ -220,10 +224,10 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); Transport.synthesize_tunnel(interface) */ -#ifndef NDEBUG +//#ifndef NDEBUG // CBA DEBUG dump_stats(); -#endif +//#endif } /*static*/ void Transport::loop() { @@ -234,6 +238,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); } /*static*/ void Transport::jobs() { + //TRACE("Transport::jobs()"); std::vector outgoing; std::set path_requests; @@ -267,6 +272,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); DEBUG("Trying to rediscover path for " + link.destination().hash().toHex() + " since an attempted link was never established"); //if (path_requests.find(link.destination().hash()) == path_requests.end()) { if (path_requests.count(link.destination().hash()) == 0) { + // CBA ACCUMULATES path_requests.insert(link.destination().hash()); } } @@ -390,6 +396,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); //_announce_table[destination_hash] = held_entry; //_announce_table.insert_or_assign({destination_hash, held_entry}); _announce_table.erase(destination_hash); + // CBA ACCUMULATES _announce_table.insert({destination_hash, held_entry}); DEBUG("Reinserting held announce into table"); } @@ -414,11 +421,12 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); _discovery_pr_tags.erase(_discovery_pr_tags.begin(), iter); } - // Cull the path table if it has reached its max size - cull_path_table(); - if (OS::time() > (_tables_last_culled + _tables_cull_interval)) { + // CBA Disabled following since we're calling immediately after adding to path table now + // Cull the path table if it has reached its max size + //cull_path_table(); + // Cull the reverse table according to timeout std::vector stale_reverse_entries; for (const auto& [packet_hash, reverse_entry] : _reverse_table) { @@ -485,6 +493,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); if (path_request_conditions) { if (path_requests.count(link_entry._destination_hash) == 0) { + // CBA ACCUMULATES path_requests.insert(link_entry._destination_hash); } @@ -607,9 +616,9 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); TRACE("Removed " + std::to_string(count) + " tunnels"); } -#ifndef NDEBUG +//#ifndef NDEBUG dump_stats(); -#endif +//#endif _tables_last_culled = OS::time(); } @@ -996,6 +1005,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); #if defined(INTERFACES_SET) const_cast(interface).add_announce(entry); #else + // CBA ACCUMULATES interface.add_announce(entry); #endif @@ -1039,6 +1049,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); if (should_transmit) { TRACE("Transport::outbound: Packet transmission allowed"); if (!stored_hash) { + // CBA ACCUMULATES _packet_hashlist.insert(packet.packet_hash()); stored_hash = true; } @@ -1081,6 +1092,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); PacketReceipt receipt(packet); packet.receipt(receipt); + // CBA ACCUMULATES _receipts.push_back(receipt); } @@ -1321,6 +1333,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); } if (accept) { TRACE("Transport::inbound: Packet accepted by filter"); + // CBA ACCUMULATES _packet_hashlist.insert(packet.packet_hash()); cache_packet(packet); @@ -1504,6 +1517,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); false, proof_timeout ); + // CBA ACCUMULATES _link_table.insert({packet.getTruncatedHash(), link_entry}); } else { @@ -1513,6 +1527,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); outbound_interface, OS::time() ); + // CBA ACCUMULATES _reverse_table.insert({packet.getTruncatedHash(), reverse_entry}); } TRACE("Transport::outbound: Sending packet to next hop..."); @@ -1846,6 +1861,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); block_rebroadcasts, attached_interface ); + // CBA ACCUMULATES _announce_table.insert({packet.destination_hash(), announce_entry}); } } @@ -1873,6 +1889,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); block_rebroadcasts, attached_interface ); + // CBA ACCUMULATES _announce_table.insert({packet.destination_hash(), announce_entry}); } } @@ -1968,6 +1985,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); } //TRACE("Adding packet " + packet.get_hash().toHex() + " to packet table"); //PacketEntry packet_entry(packet); + // CBA ACCUMULATES //_packet_table.insert({packet.get_hash(), packet_entry}); TRACE("Adding destination " + packet.destination_hash().toHex() + " to path table"); DestinationEntry destination_table_entry( @@ -1982,6 +2000,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); //packet packet.get_hash() ); + // CBA ACCUMULATES if (_destination_table.insert({packet.destination_hash(), destination_table_entry}).second) { ++_destinations_added; cull_path_table(); @@ -2440,6 +2459,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); } } + // CBA ACCUMULATES _destinations.insert(destination); #elif defined(DESTINATIONS_MAP) auto iter = _destinations.find(destination.hash()); @@ -2448,6 +2468,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); throw std::runtime_error("Attempt to register an already registered destination."); } + // CBA ACCUMULATES _destinations.insert({destination.hash(), destination}); #endif @@ -2495,9 +2516,11 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); /* TRACE("Transport: Registering link " + link.toString()); if (link.initiator()) { + // CBA ACCUMULATES _pending_links.insert(link); } else { + // CBA ACCUMULATES _active_links.insert(link); } */ @@ -2512,6 +2535,7 @@ extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); throw std::runtime_error("Invalid link state for link activation: " + link.status_string()); } _pending_links.erase(link); + // CBA ACCUMULATES _active_links.insert(link); link.status(Type::Link::ACTIVE); } @@ -2626,8 +2650,9 @@ Deregisters an announce handler. std::string packet_cache_path = Reticulum::_cachepath + "/" + packet_hash.toHex(); //return Persistence::deserialize(packet_cache_path.c_str()); Packet packet({Type::NONE}); - Persistence::deserialize(packet, packet_cache_path.c_str()); - packet.update_hash(); + if (Persistence::deserialize(packet, packet_cache_path.c_str())) { + packet.update_hash(); + } return packet; } catch (std::exception& e) { @@ -2882,6 +2907,7 @@ will announce it. //TRACE("Transport::path_request_handler: unique_tag: " + unique_tag.toHex()); if (_discovery_pr_tags.find(unique_tag) == _discovery_pr_tags.end()) { + // CBA ACCUMULATES _discovery_pr_tags.insert(unique_tag); path_request( @@ -2930,6 +2956,7 @@ will announce it. DestinationEntry& destination_entry = (*iter).second; if (is_local_client_interface(destination_entry.receiving_interface())) { destination_exists_on_local_client = true; + // CBA ACCUMULATES _pending_local_path_requests.insert({destination_hash, attached_interface}); } } @@ -3008,10 +3035,12 @@ will announce it. auto announce_iter = _announce_table.find(announce_packet.destination_hash()); if (announce_iter != _announce_table.end()) { AnnounceEntry& held_entry = (*announce_iter).second; + // CBA ACCUMULATES _held_announces.insert({announce_packet.destination_hash(), held_entry}); } /* + // CBA ACCUMULATES _announce_table.insert({announce_packet.destination_hash(), { now, retransmit_timeout, @@ -3039,6 +3068,7 @@ will announce it. block_rebroadcasts, attached_interface ); + // CBA ACCUMULATES _announce_table.insert({announce_packet.destination_hash(), announce_entry}); } } @@ -3071,6 +3101,7 @@ will announce it. DEBUG("Attempting to discover unknown path to destination " + destination_hash.toHex() + " on behalf of path request" + interface_str); //p pr_entry = { "destination_hash": destination_hash, "timeout": time.time()+Transport.PATH_REQUEST_TIMEOUT, "requesting_interface": attached_interface } //p _discovery_path_requests[destination_hash] = pr_entry; + // CBA ACCUMULATES _discovery_path_requests.insert({destination_hash, { destination_hash, OS::time() + Type::Transport::PATH_REQUEST_TIMEOUT, @@ -3339,10 +3370,16 @@ TRACE("Transport::start: buffer size " + std::to_string(Persistence::_buffer.siz #ifndef NDEBUG TRACE("Transport::start: entry: " + destination_hash.toHex() + " = " + destination_entry.debugString()); #endif - // CBA TODO If announce packet load fails then remove destination entry (it's useless without announce packet) + // CBA If announce packet load fails then remove destination entry (it's useless without announce packet) if (!destination_entry.announce_packet()) { // remove destination - RNS::warning("Transport::start: removing invalid path to " + destination_hash.toHex()); + RNS::warning("Transport::start: removing invalid path to " + destination_hash.toHex() + " due to missing announce packet"); + invalid_paths.push_back(destination_hash); + } + // CBA If receiving interface is not found then remove destination entry (it's useless without interface) + if (!destination_entry.receiving_interface()) { + // remove destination + RNS::warning("Transport::start: removing invalid path to " + destination_hash.toHex() + " due to missing receiving interface"); invalid_paths.push_back(destination_hash); } } @@ -3358,7 +3395,7 @@ TRACE("Transport::start: buffer size " + std::to_string(Persistence::_buffer.siz else { TRACE("Transport::start: destination table read failed"); } - verbose("Loaded " + std::to_string(_destination_table.size()) + " path table entries from storage"); + verbose("Loaded " + std::to_string(_destination_table.size()) + " valid path table entries from storage"); } catch (std::exception& e) { @@ -3656,7 +3693,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: /*static*/ void Transport::clean_caches() { TRACE("Transport::clean_caches()"); // CBA Remove cached packets no longer in path list - std::list files = OS::list_directory(Reticulum::_cachepath.c_str()); + std::list files = OS::list_directory(Reticulum::_cachepath.c_str()); for (auto& file : files) { TRACE("Transport::clean_caches: Checking for use of cached packet " + file); bool found = false; @@ -3676,7 +3713,13 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: /*static*/ void Transport::dump_stats() { -#ifndef NDEBUG + size_t memory = OS::memory_available(); + size_t flash = OS::storage_available(); + + if (_last_memory == 0) { + _last_memory = memory; + } + // memory // storage // _destinations @@ -3684,23 +3727,34 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: // _reverse_table // _announce_table // _held_announces - head("mem: " + std::to_string(OS::memory_available()) + " flash: " + std::to_string(OS::storage_available()) + " paths: " + std::to_string(_destination_table.size()) + " dsts: " + std::to_string(_destinations.size()) + " revr: " + std::to_string(_reverse_table.size()) + " annc: " + std::to_string(_announce_table.size()) + " held: " + std::to_string(_held_announces.size()), LOG_EXTREME); + head("mem: " + std::to_string(memory) + " (" + std::to_string((int)memory - (int)_last_memory) + ") flash: " + std::to_string(flash) + " paths: " + std::to_string(_destination_table.size()) + " dsts: " + std::to_string(_destinations.size()) + " revr: " + std::to_string(_reverse_table.size()) + " annc: " + std::to_string(_announce_table.size()) + " held: " + std::to_string(_held_announces.size()), LOG_VERBOSE); + // _path_requests // _discovery_path_requests // _pending_local_path_requests // _discovery_pr_tags // _control_destinations // _control_hashes - TRACE("preqs: " + std::to_string(_path_requests.size()) + " dpreqs: " + std::to_string(_discovery_path_requests.size()) + " ppreqs: " + std::to_string(_pending_local_path_requests.size()) + " dprt: " + std::to_string(_discovery_pr_tags.size()) + " cdsts: " + std::to_string(_control_destinations.size()) + " chshs: " + std::to_string(_control_hashes.size())); + verbose("preqs: " + std::to_string(_path_requests.size()) + " dpreqs: " + std::to_string(_discovery_path_requests.size()) + " ppreqs: " + std::to_string(_pending_local_path_requests.size()) + " dprt: " + std::to_string(_discovery_pr_tags.size()) + " cdsts: " + std::to_string(_control_destinations.size()) + " chshs: " + std::to_string(_control_hashes.size())); + // _packet_hashlist // _receipts // _link_table // _pending_links // _active_links // _tunnels - TRACE("phl: " + std::to_string(_packet_hashlist.size()) + " rcp: " + std::to_string(_receipts.size()) + " lt: " + std::to_string(_link_table.size()) + " pl: " + std::to_string(_pending_links.size()) + " al: " + std::to_string(_active_links.size()) + " tun: " + std::to_string(_tunnels.size())); - TRACE("pin: " + std::to_string(_packets_received) + " pout: " + std::to_string(_packets_sent) + " dadd: " + std::to_string(_destinations_added) + "\r\n"); -#endif + uint32_t destination_path_responses = 0; + for (auto& [destination_hash, destination] : _destinations) { + destination_path_responses += destination.path_responses().size(); + } + uint32_t interface_announces = 0; + for (auto& [interface_hash, interface] : _interfaces) { + interface_announces += interface.announce_queue().size(); + } + verbose("phl: " + std::to_string(_packet_hashlist.size()) + " rcp: " + std::to_string(_receipts.size()) + " lt: " + std::to_string(_link_table.size()) + " pl: " + std::to_string(_pending_links.size()) + " al: " + std::to_string(_active_links.size()) + " tun: " + std::to_string(_tunnels.size())); + verbose("pin: " + std::to_string(_packets_received) + " pout: " + std::to_string(_packets_sent) + " dadd: " + std::to_string(_destinations_added) + " dpr: " + std::to_string(destination_path_responses) + " ikd: " + std::to_string(Identity::_known_destinations.size()) + " ia: " + std::to_string(interface_announces) + "\r\n"); + + _last_memory = memory; } @@ -3732,6 +3786,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: } /*static*/ void Transport::cull_path_table() { + TRACE("Transport::cull_path_table()"); if (_destination_table.size() > _path_table_maxsize) { // TODO prune by age, or better yet by last use /* diff --git a/src/Transport.h b/src/Transport.h index 611bcea..b357f41 100644 --- a/src/Transport.h +++ b/src/Transport.h @@ -450,6 +450,7 @@ namespace RNS { static uint32_t _packets_sent; static uint32_t _packets_received; static uint32_t _destinations_added; + static size_t _last_memory; }; template diff --git a/src/Type.h b/src/Type.h index 7bdc513..d6d8d1e 100644 --- a/src/Type.h +++ b/src/Type.h @@ -80,16 +80,15 @@ namespace RNS { namespace Type { static const uint32_t RESOURCE_CACHE = 60*60*24; // CBA TEST - //static const uint16_t JOB_INTERVAL = 60*5; - static const uint16_t JOB_INTERVAL = 60; + static const uint16_t JOB_INTERVAL = 60*5; + //static const uint16_t JOB_INTERVAL = 60; + // CBA TEST + static const uint16_t CLEAN_INTERVAL = 60*15; + //static const uint16_t CLEAN_INTERVAL = 60; // CBA TEST - //static const uint16_t CLEAN_INTERVAL = 60*15; - static const uint16_t CLEAN_INTERVAL = 60; - // CBA //static const uint16_t PERSIST_INTERVAL = 60*60*12; - // CBA TEST - //static const uint16_t PERSIST_INTERVAL = 60*60; - static const uint16_t PERSIST_INTERVAL = 60; + static const uint16_t PERSIST_INTERVAL = 60*60; + //static const uint16_t PERSIST_INTERVAL = 60; static const uint16_t GRACIOUS_PERSIST_INTERVAL = 60*5; static const uint8_t DESTINATION_LENGTH = TRUNCATED_HASHLENGTH/8; // In bytes @@ -327,7 +326,9 @@ namespace RNS { namespace Type { static constexpr const float LINK_TIMEOUT = Link::STALE_TIME * 1.25; static const uint16_t REVERSE_TIMEOUT = 30*60; // Reverse table entries are removed after 30 minutes - static const uint16_t MAX_RECEIPTS = 1024; // Maximum number of receipts to keep track of + // CBA MCU + //static const uint16_t MAX_RECEIPTS = 1024; // Maximum number of receipts to keep track of + static const uint16_t MAX_RECEIPTS = 20; // Maximum number of receipts to keep track of static const uint8_t MAX_RATE_TIMESTAMPS = 16; // Maximum number of announce timestamps to keep per destination // CBA MCU diff --git a/src/Utilities/OS.cpp b/src/Utilities/OS.cpp index 614ea17..e72dc79 100644 --- a/src/Utilities/OS.cpp +++ b/src/Utilities/OS.cpp @@ -91,3 +91,38 @@ using namespace RNS::Utilities; } return filesystem.do_list_directory(directory_path); } + +/*static*/ size_t OS::storage_size() { + if (!filesystem) { + throw std::runtime_error("Filesystem has not been registered"); + } + return filesystem.do_storage_size(); +} + +/*static*/ size_t OS::storage_available() { + if (!filesystem) { + throw std::runtime_error("Filesystem has not been registered"); + } + return filesystem.do_storage_available(); +} + + +/*static*/ size_t OS::memory_size() { + return 0; +} + +/*static*/ size_t OS::memory_available() { + //const size_t block_size = 256; + const size_t block_size = 32; + // Limit avuialable memory check (in case run on something larger than an MCU) + const size_t blocks_max = 1024 * 2000 / block_size; + size_t block_count; + for(block_count = 1; block_count <= blocks_max; block_count++) { + void* ptr = malloc(block_count * block_size); + if (ptr == nullptr) { + break; + } + free(ptr); + } + return (block_count - 1) * block_size; +} diff --git a/src/Utilities/OS.h b/src/Utilities/OS.h index f57e601..67c2cde 100644 --- a/src/Utilities/OS.h +++ b/src/Utilities/OS.h @@ -76,53 +76,11 @@ namespace RNS { namespace Utilities { static bool create_directory(const char* directory_path); static bool remove_directory(const char* directory_path); static std::list list_directory(const char* directory_path); + static size_t storage_size(); + static size_t storage_available(); - static inline int storage_size() { - return -1; - } - - static inline int storage_available() { - return -1; - } - - static inline uint32_t memory_size() { - } - -/* - static inline uint32_t memory_available() - { - uint32_t i; - uint32_t len; - uint8_t* ptr; - - for(i=1;;i++) { - len = i * 512; - ptr = (uint8_t*)malloc(len); - if (ptr == nullptr) { - break; - } - free(ptr); - } - - len -= 512; //(i-1)*512 is aviliable size - - return len; - } -*/ - - static inline size_t memory_available() - { - const size_t block_size = 256; - 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_size(); + static size_t memory_available(); }; diff --git a/src/Utilities/Persistence.h b/src/Utilities/Persistence.h index c3a4609..66cf901 100644 --- a/src/Utilities/Persistence.h +++ b/src/Utilities/Persistence.h @@ -384,7 +384,10 @@ namespace RNS { namespace Persistence { if (!error) { TRACE("Persistence::deserialize: successfully deserialized"); obj = _document.as(); - return true; + if (obj) { + return true; + } + TRACE("Persistence::deserialize: failed to compose object"); } else { TRACE("Persistence::deserialize: failed to deserialize");