diff --git a/examples/lora_announce/.gitignore b/examples/lora_announce/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/examples/lora_announce/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/examples/lora_announce/.vscode/extensions.json b/examples/lora_announce/.vscode/extensions.json new file mode 100644 index 0000000..080e70d --- /dev/null +++ b/examples/lora_announce/.vscode/extensions.json @@ -0,0 +1,10 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ], + "unwantedRecommendations": [ + "ms-vscode.cpptools-extension-pack" + ] +} diff --git a/examples/lora_announce/FileSystem.cpp b/examples/lora_announce/FileSystem.cpp new file mode 100644 index 0000000..ecc741d --- /dev/null +++ b/examples/lora_announce/FileSystem.cpp @@ -0,0 +1,525 @@ +#include "FileSystem.h" + +#include +#include + +bool FileSystem::init() { + TRACE("FileSystem initializing..."); + +#ifdef ARDUINO +#ifdef BOARD_ESP32 + // Setup FileSystem + INFO("SPIFFS mounting FileSystem"); + if (!SPIFFS.begin(true, "")){ + 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("test"); + if (write_file("/test", test) < 4) { + INFO("SPIFFS FileSystem is being formatted, please wait..."); + SPIFFS.format(); + } + else { + remove_file("/test"); + } + DEBUG("SPIFFS FileSystem is ready"); +#elif BOARD_NRF52 + // Initialize Internal File System + INFO("InternalFS mounting FileSystem"); + InternalFS.begin(); + INFO("InternalFS FileSystem is ready"); +#endif +#endif + return true; +} + +#ifdef ARDUINO +void FileSystem::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) { + if (file.isDirectory()) { + Serial.print(" DIR: "); + } + else { + 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) { + if (file.isDirectory()) { + Serial.print(" DIR: "); + } + else { + Serial.print(" FILE: "); + } + Serial.println(file.name()); + file.close(); + file = root.openNextFile(); + } + root.close(); +#endif +} +#else +void FileSystem::listDir(const char* dir) { +} +#endif + +/*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 { + 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)) { + 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 + 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); + 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(); + } + //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 { + 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) { + // CBA TODO Replace remove with working truncation + remove_file(file_path); + 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); + 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 BOARD_ESP32 + file.close(); +#elif BOARD_NRF52 + file.close(); +#endif +#else + // Native + fclose(file); +#endif + } + else { + ERROR("write_file: failed to open output file " + std::string(file_path)); + } + return wrote; +} + +/*virtual*/ RNS::FileStream FileSystem::open_file(const char* file_path, RNS::FileStream::MODE file_mode) { + TRACEF("open_file: opening file %s", file_path); +#ifdef ARDUINO +#ifdef BOARD_ESP32 + const char* mode; + if (file_mode == RNS::FileStream::MODE_READ) { + mode = FILE_READ; + } + else if (file_mode == RNS::FileStream::MODE_WRITE) { + mode = FILE_WRITE; + } + else if (file_mode == RNS::FileStream::MODE_APPEND) { + mode = FILE_APPEND; + } + else { + ERRORF("open_file: unsupported mode %d", file_mode); + return {RNS::Type::NONE}; + } + TRACEF("open_file: opening file %s in mode %s", file_path, mode); + //// Using copy constructor to create a File* instead of local + //File file = SPIFFS.open(file_path, mode); + //if (!file) { + File* file = new File(SPIFFS.open(file_path, mode)); + if (file == null || !(*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); + int mode; + if (file_mode == RNS::FileStream::MODE_READ) { + mode = FILE_O_READ; + } + else if (file_mode == RNS::FileStream::MODE_WRITE) { + mode = FILE_O_WRITE; + // CBA TODO Replace remove with working truncation + if (InternalFS.exists(file_path)) { + InternalFS.remove(file_path); + } + } + else if (file_mode == RNS::FileStream::MODE_APPEND) { + // CBA This is the default write mode for nrf52 littlefs + mode = FILE_O_WRITE; + } + else { + ERRORF("open_file: unsupported mode %d", file_mode); + return {RNS::Type::NONE}; + } + if (!file->open(file_path, mode)) { + ERRORF("open_file: failed to open output file %s", file_path); + return {RNS::Type::NONE}; + } + + // Seek to beginning to overwrite (this is failing on nrf52) + //if (file_mode == RNS::FileStream::MODE_WRITE) { + // file->seek(0); + // file->truncate(0); + //} + TRACEF("open_file: successfully opened file %s", file_path); + return RNS::FileStream(new FileStreamImpl(file)); +#else + #warning("unsuppoprted"); + return RNS::FileStream(RNS::Type::NONE); +#endif +#else // ARDUINO + // Native + const char* mode; + if (file_mode == RNS::FileStream::MODE_READ) { + mode = "r"; + } + else if (file_mode == RNS::FileStream::MODE_WRITE) { + mode = "w"; + } + else if (file_mode == RNS::FileStream::MODE_APPEND) { + mode = "a"; + } + else { + ERRORF("open_file: unsupported mode %d", file_mode); + return {RNS::Type::NONE}; + } + TRACEF("open_file: opening file %s in mode %s", file_path, mode); + FILE* file = fopen(file_path, mode); + if (file == nullptr) { + 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)); +#endif +} + +/*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) { + TRACE("directory_exists: checking for existence of directory " + std::string(directory_path)); +#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 + 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)) { + ERROR("create_directory: failed to create directorty " + std::string(directory_path)); + return false; + } + return true; +#elif BOARD_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 + // 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) { + TRACE("remove_directory: removing directory " + std::string(directory_path)); +#ifdef ARDUINO +#ifdef BOARD_ESP32 + //if (!LittleFS.rmdir_r(directory_path)) { + if (!SPIFFS.rmdir(directory_path)) { + ERROR("remove_directory: failed to remove directorty " + std::string(directory_path)); + return false; + } + return true; +#elif BOARD_NRF52 + if (!InternalFS.rmdir_r(directory_path)) { + 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) { + TRACE("list_directory: listing directory " + std::string(directory_path)); + std::list files; +#ifdef ARDUINO +#ifdef BOARD_ESP32 + File root = SPIFFS.open(directory_path); +#elif BOARD_NRF52 + File root = InternalFS.open(directory_path); +#endif + if (!root) { + 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(); + files.push_back(name); + } + // CBA Following close required to avoid leaking memory + file.close(); + file = root.openNextFile(); + } + TRACE("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 SPIFFS.totalBytes(); +} + +/*virtual*/ size_t FileSystem::storage_available() { + return (SPIFFS.totalBytes() - SPIFFS.usedBytes()); +} + +#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(); + return InternalFS.totalBytes(); +} + +/*virtual*/ size_t FileSystem::storage_available() { + //return (totalBytes() - usedBytes()); + return (InternalFS.totalBytes() - InternalFS.usedBytes()); +} + +#endif + +#else + +/*virtual*/ size_t FileSystem::storage_size() { + return 0; +} + +/*virtual*/ size_t FileSystem::storage_available() { + return 0; +} + +#endif diff --git a/examples/lora_announce/FileSystem.h b/examples/lora_announce/FileSystem.h new file mode 100644 index 0000000..b696371 --- /dev/null +++ b/examples/lora_announce/FileSystem.h @@ -0,0 +1,184 @@ +#pragma once + +#include +#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 +#include +#include +#endif + +class FileSystem : public RNS::FileSystemImpl { + +public: + FileSystem() {} + + bool init(); + +public: + static void listDir(const char* dir); + +public: + virtual bool file_exists(const char* file_path); + virtual size_t read_file(const char* file_path, RNS::Bytes& data); + virtual size_t write_file(const char* file_path, const RNS::Bytes& data); + virtual RNS::FileStream open_file(const char* file_path, RNS::FileStream::MODE file_mode); + 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(); + +protected: + +#if defined(BOARD_ESP32) || defined(BOARD_NRF52) + class FileStreamImpl : public RNS::FileStreamImpl { + + private: + std::unique_ptr _file; + bool _closed = false; + + public: + FileStreamImpl(File* file) : RNS::FileStreamImpl(), _file(file) {} + virtual ~FileStreamImpl() { if (!_closed) close(); } + + public: + inline virtual const char* name() { return _file->name(); } + inline virtual size_t size() { return _file->size(); } + inline virtual void close() { _closed = true; _file->close(); } + + // Print overrides + inline virtual size_t write(uint8_t byte) { return _file->write(byte); } + inline virtual size_t write(const uint8_t *buffer, size_t size) { return _file->write(buffer, size); } + + // Stream overrides + inline virtual int available() { return _file->available(); } + inline virtual int read() { return _file->read(); } + inline virtual int peek() { return _file->peek(); } + inline virtual void flush() { _file->flush(); } + + }; +#else + class FileStreamImpl : public RNS::FileStreamImpl { + + private: + FILE* _file = nullptr; + bool _closed = false; + size_t _available = 0; + char _filename[1024]; + + public: + FileStreamImpl(FILE* file) : RNS::FileStreamImpl(), _file(file) { + _available = size(); + } + virtual ~FileStreamImpl() { if (!_closed) close(); } + + public: + inline virtual const char* name() { + assert(_file); +#if 0 + char proclnk[1024]; + snprintf(proclnk, sizeof(proclnk), "/proc/self/fd/%d", fileno(_file)); + int r = readlink(proclnk, _filename, sizeof(_filename)); + if (r < 0) { + return nullptr); + } + _filename[r] = '\0'; + return _filename; +#elif 0 + if (fcntl(fd, F_GETPATH, _filename) < 0) { + rerturn nullptr; + } + return _filename; +#else + return nullptr; +#endif + } + inline virtual size_t size() { + assert(_file); + struct stat st; + fstat(fileno(_file), &st); + return st.st_size; + } + inline virtual void close() { + assert(_file); + _closed = true; + fclose(_file); + _file = nullptr; + } + + // Print overrides + inline virtual size_t write(uint8_t byte) { + assert(_file); + int ch = fputc(byte, _file); + if (ch == EOF) { + return 0; + } + ++_available; + return 1; + } + inline virtual size_t write(const uint8_t *buffer, size_t size) { + assert(_file); + size_t wrote = fwrite(buffer, sizeof(uint8_t), size, _file); + _available += wrote; + return wrote; + } + + // Stream overrides + inline virtual int available() { +#if 0 + assert(_file); + int size = 0; + ioctl(fileno(_file), FIONREAD, &size); + TRACEF("FileStream::available: %d", size); + return size; +#else + return _available; +#endif + } + inline virtual int read() { + if (_available <= 0) { + return EOF; + } + assert(_file); + int ch = fgetc(_file); + TRACEF("FileStream::read: %c", ch); + return ch; + } + inline virtual int peek() { + if (_available <= 0) { + return EOF; + } + assert(_file); + int ch = fgetc(_file); + ungetc(ch, _file); + TRACEF("FileStream::peek: %c", ch); + return ch; + } + inline virtual void flush() { + assert(_file); + fflush(_file); + TRACE("FileStream::flush"); + } + + }; +#endif + +}; diff --git a/examples/lora_announce/LoRaInterface.cpp b/examples/lora_announce/LoRaInterface.cpp index 7522193..3a4e262 100644 --- a/examples/lora_announce/LoRaInterface.cpp +++ b/examples/lora_announce/LoRaInterface.cpp @@ -6,7 +6,6 @@ #include using namespace RNS; -using namespace RNS::Interfaces; /* @staticmethod @@ -22,12 +21,12 @@ def get_broadcast_for_if(name): return ifaddr[netinfo.AF_INET][0]["broadcast"] */ -LoRaInterface::LoRaInterface(const char* name /*= "LoRaInterface"*/) : Interface(name) { +LoRaInterface::LoRaInterface(const char* name /*= "LoRaInterface"*/) : RNS::InterfaceImpl(name) { - IN(true); - OUT(true); + _IN = true; + _OUT = true; //p self.bitrate = self.r_sf * ( (4.0/self.r_cr) / (math.pow(2,self.r_sf)/(self.r_bandwidth/1000)) ) * 1000 - bitrate((double)spreading * ( (4.0/coding) / (pow(2, spreading)/(bandwidth/1000.0)) ) * 1000.0); + _bitrate = (double)spreading * ( (4.0/coding) / (pow(2, spreading)/(bandwidth/1000.0)) ) * 1000.0; } @@ -36,7 +35,7 @@ LoRaInterface::LoRaInterface(const char* name /*= "LoRaInterface"*/) : Interface } bool LoRaInterface::start() { - online(false); + _online = false; INFO("LoRa initializing..."); #ifdef ARDUINO @@ -61,7 +60,7 @@ bool LoRaInterface::start() { TRACE("LoRa bandwidth is " + std::to_string(Utilities::OS::round(bitrate()/1000.0, 2)) + " Kbps"); #endif - online(true); + _online = true; return true; } @@ -70,12 +69,12 @@ void LoRaInterface::stop() { #ifdef ARDUINO #endif - online(false); + _online = false; } void LoRaInterface::loop() { - if (online()) { + if (_online) { // Check for incoming packet #ifdef ARDUINO int available = LoRa.parsePacket(); @@ -102,15 +101,10 @@ void LoRaInterface::loop() { } } -/*virtual*/ void LoRaInterface::on_incoming(const Bytes& data) { - DEBUG(toString() + ".on_incoming: data: " + data.toHex()); - Interface::on_incoming(data); -} - -/*virtual*/ void LoRaInterface::on_outgoing(const Bytes& data) { +/*virtual*/ void LoRaInterface::send_outgoing(const Bytes& data) { DEBUG(toString() + ".on_outgoing: data: " + data.toHex()); try { - if (online()) { + if (_online) { TRACE("LoRaInterface: sending " + std::to_string(data.size()) + " bytes..."); // Send packet #ifdef ARDUINO @@ -134,9 +128,17 @@ void LoRaInterface::loop() { #endif TRACE("LoRaInterface: sent bytes"); } - Interface::on_outgoing(data); + + // Perform post-send housekeeping + InterfaceImpl::handle_outgoing(data); } catch (std::exception& e) { ERROR("Could not transmit on " + toString() + ". The contained exception was: " + e.what()); } } + +/*virtual*/ void LoRaInterface::on_incoming(const Bytes& data) { + DEBUG(toString() + ".on_incoming: data: " + data.toHex()); + // Pass received data on to transport + InterfaceImpl::handle_incoming(data); +} diff --git a/examples/lora_announce/LoRaInterface.h b/examples/lora_announce/LoRaInterface.h index b5fb4a3..d371e01 100644 --- a/examples/lora_announce/LoRaInterface.h +++ b/examples/lora_announce/LoRaInterface.h @@ -21,43 +21,39 @@ #include -namespace RNS { namespace Interfaces { +class LoRaInterface : public RNS::InterfaceImpl { - class LoRaInterface : public Interface { +public: + //z def get_address_for_if(name): + //z def get_broadcast_for_if(name): - public: - //z def get_address_for_if(name): - //z def get_broadcast_for_if(name): +public: + //p def __init__(self, owner, name, device=None, bindip=None, bindport=None, forwardip=None, forwardport=None): + LoRaInterface(const char* name = "LoRaInterface"); + virtual ~LoRaInterface(); - public: - //p def __init__(self, owner, name, device=None, bindip=None, bindport=None, forwardip=None, forwardport=None): - LoRaInterface(const char* name = "LoRaInterface"); - virtual ~LoRaInterface(); + bool start(); + void stop(); + void loop(); - bool start(); - void stop(); - void loop(); + //virtual inline std::string toString() const { return "LoRaInterface[" + name() + "]"; } - virtual inline std::string toString() const { return "LoRaInterface[" + name() + "]"; } +private: + virtual void send_outgoing(const RNS::Bytes& data); + void on_incoming(const RNS::Bytes& data); - private: - virtual void on_incoming(const Bytes& data); - virtual void on_outgoing(const Bytes& data); +private: + const uint16_t HW_MTU = 508; + //uint8_t buffer[Type::Reticulum::MTU] = {0}; + const uint8_t message_count = 0; + RNS::Bytes buffer; - private: - const uint16_t HW_MTU = 508; - //uint8_t buffer[Type::Reticulum::MTU] = {0}; - const uint8_t message_count = 0; - Bytes buffer; + const long frequency = 915E6; - const long frequency = 915E6; + // Reticulum default + const long bandwidth = 125E3; + const int spreading = 8; + const int coding = 5; + const int power = 17; - // Reticulum default - const long bandwidth = 125E3; - const int spreading = 8; - const int coding = 5; - const int power = 17; - - }; - -} } +}; diff --git a/examples/lora_announce/main.cpp b/examples/lora_announce/main.cpp index 5b38b0c..710c7dd 100644 --- a/examples/lora_announce/main.cpp +++ b/examples/lora_announce/main.cpp @@ -1,17 +1,18 @@ //#define NDEBUG #include "LoRaInterface.h" +#include "FileSystem.h" -#include "Reticulum.h" -#include "Identity.h" -#include "Destination.h" -#include "Packet.h" -#include "Transport.h" -#include "Interface.h" -#include "Log.h" -#include "Bytes.h" -#include "Type.h" -#include "Utilities/OS.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #ifdef ARDUINO #include @@ -86,10 +87,13 @@ void onPingPacket(const RNS::Bytes& data, const RNS::Packet& packet) { RNS::Reticulum reticulum({RNS::Type::NONE}); +RNS::Interface lora_interface(RNS::Type::NONE); +RNS::FileSystem test_filesystem(RNS::Type::NONE); RNS::Identity identity({RNS::Type::NONE}); RNS::Destination destination({RNS::Type::NONE}); -RNS::Interfaces::LoRaInterface lora_interface; +LoRaInterface* lora_interface_impl = nullptr; +FileSystem* test_filesystem_impl = nullptr; //ExampleAnnounceHandler announce_handler((const char*)"example_utilities.announcesample.fruits"); //RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler("example_utilities.announcesample.fruits")); @@ -119,12 +123,21 @@ void reticulum_setup() { // 21.8% baseline here with serial - HEAD("Registering Interface instances with Transport...", RNS::LOG_TRACE); + + HEAD("Registering FileSystem with OS...", RNS::LOG_TRACE); + test_filesystem_impl = new FileSystem(); + test_filesystem = test_filesystem_impl; + ((FileSystem*)test_filesystem.get())->init(); + RNS::Utilities::OS::register_filesystem(test_filesystem); + + HEAD("Registering LoRaInterface instances with Transport...", RNS::LOG_TRACE); + lora_interface_impl = new LoRaInterface(); + lora_interface = lora_interface_impl; lora_interface.mode(RNS::Type::Interface::MODE_GATEWAY); RNS::Transport::register_interface(lora_interface); HEAD("Starting LoRaInterface...", RNS::LOG_TRACE); - lora_interface.start(); + lora_interface_impl->start(); HEAD("Creating Reticulum instance...", RNS::LOG_TRACE); //RNS::Reticulum reticulum; @@ -215,7 +228,7 @@ void reticulum_setup() { void reticulum_teardown() { INFO("Tearing down Reticulum..."); - RNS::Transport::save_path_table(); + RNS::Transport::persist_data(); try { @@ -281,7 +294,7 @@ void setup() { void loop() { reticulum.loop(); - lora_interface.loop(); + lora_interface_impl->loop(); #ifdef ARDUINO /* diff --git a/examples/lora_announce/platformio.ini b/examples/lora_announce/platformio.ini index f66174b..7bbf86f 100644 --- a/examples/lora_announce/platformio.ini +++ b/examples/lora_announce/platformio.ini @@ -20,9 +20,17 @@ monitor_speed = 115200 upload_speed = 921600 build_type = debug build_flags = + ;-DMEM_LOG=1 + -DRNS_USE_ALLOCATOR=1 -DRNS_USE_ALLOCATOR=1 -DRNS_USE_TLSF=1 + ;-DTEST_OBJECT_DATA=1 + -DTEST_OBJECT_IMPL=1 lib_deps = + ArduinoJson@^6.21.3 + https://github.com/attermann/Crypto.git + https://github.com/hideakitai/MsgPack.git + microReticulum=symlink://../.. [env:native] platform = native @@ -41,9 +49,6 @@ build_flags = -DNATIVE lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. lib_extra_dirs = ../ lib_compat_mode = off ;debug_init_break = @@ -67,9 +72,6 @@ build_flags = -DNATIVE lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. lib_extra_dirs = ../ lib_compat_mode = off @@ -89,9 +91,6 @@ build_flags = -DCUBECELL lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. ; CBA NOTE must undef min and max from Arduino.h [env:heltec-tracker] @@ -113,9 +112,6 @@ build_flags = lib_deps = ${env.lib_deps} lovyan03/LovyanGFX@^1.1.8 - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. [env:ttgo-lora32-v21] framework = arduino @@ -133,9 +129,6 @@ build_flags = -DBOARD_ESP32 lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. monitor_filters = esp32_exception_decoder [env:ttgo-t-beam] @@ -154,9 +147,6 @@ build_flags = -DBOARD_ESP32 lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. monitor_filters = esp32_exception_decoder [env:wiscore_rak4631] @@ -178,9 +168,6 @@ build_flags = build_unflags = -fno-exceptions lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. [env:nrf52840_dk_adafruit] framework = arduino @@ -201,4 +188,3 @@ build_flags = ${env.build_flags} lib_deps = ${env.lib_deps} - diff --git a/examples/main.cpp b/examples/main.cpp deleted file mode 100644 index 4b7137d..0000000 --- a/examples/main.cpp +++ /dev/null @@ -1,439 +0,0 @@ -//#define NDEBUG - -#include "Test/Test.h" - -#include "Reticulum.h" -#include "Identity.h" -#include "Destination.h" -#include "Packet.h" -#include "Transport.h" -#include "Interface.h" -#include "Log.h" -#include "Bytes.h" -#include "Type.h" -#include "Interfaces/UDPInterface.h" -#include "Interfaces/LoRaInterface.h" -#include "Utilities/OS.h" - -#ifdef ARDUINO -#include -#include -#else -#include -#include -#include -#endif - -#include -#include -#include -#include -#include -#include -//#include - - -#ifndef NDEBUG -//#define RUN_TESTS -#endif - -#define RUN_RETICULUM -#define UDP_INTERFACE -//#define UDP2_INTERFACE -#define LORA_INTERFACE -//#define RETICULUM_PACKET_TEST - -#define BUTTON_PIN 38 -//#define BUTTON_PIN_MASK GPIO_SEL_38 - -// Let's define an app name. We'll use this for all -// destinations we create. Since this basic example -// is part of a range of example utilities, we'll put -// them all within the app namespace "example_utilities" -const char* APP_NAME = "example_utilities"; - -// We initialise two lists of strings to use as app_data -const char* fruits[] = {"Peach", "Quince", "Date", "Tangerine", "Pomelo", "Carambola", "Grape"}; -const char* noble_gases[] = {"Helium", "Neon", "Argon", "Krypton", "Xenon", "Radon", "Oganesson"}; - -double last_announce = 0.0; -bool send_announce = false; - -// Test AnnounceHandler -class ExampleAnnounceHandler : public RNS::AnnounceHandler { -public: - ExampleAnnounceHandler(const char* aspect_filter = nullptr) : AnnounceHandler(aspect_filter) {} - virtual ~ExampleAnnounceHandler() {} - virtual void received_announce(const RNS::Bytes& destination_hash, const RNS::Identity& announced_identity, const RNS::Bytes& app_data) { - INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); - INFO("ExampleAnnounceHandler: destination hash: " + destination_hash.toHex()); - if (announced_identity) { - INFO("ExampleAnnounceHandler: announced identity hash: " + announced_identity.hash().toHex()); - INFO("ExampleAnnounceHandler: announced identity app data: " + announced_identity.app_data().toHex()); - } - if (app_data) { - INFO("ExampleAnnounceHandler: app data text: \"" + app_data.toString() + "\""); - } - INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); - } -}; - -// Test packet receive callback -void onPacket(const RNS::Bytes& data, const RNS::Packet& packet) { - INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); - INFO("onPacket: data: " + data.toHex()); - INFO("onPacket: text: \"" + data.toString() + "\""); - //TRACE("onPacket: " + packet.debugString()); - INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); -} - -// Ping packet receive callback -void onPingPacket(const RNS::Bytes& data, const RNS::Packet& packet) { - INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); - INFO("onPingPacket: data: " + data.toHex()); - INFO("onPingPacket: text: \"" + data.toString() + "\""); - //TRACE("onPingPacket: " + packet.debugString()); - INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); -} - - -#if defined(RUN_RETICULUM) -RNS::Reticulum reticulum({RNS::Type::NONE}); -RNS::Identity identity({RNS::Type::NONE}); -RNS::Destination destination({RNS::Type::NONE}); - -#ifdef UDP_INTERFACE -RNS::Interfaces::UDPInterface udp_interface("udp"); -#endif -#ifdef UDP2_INTERFACE -RNS::Interfaces::UDPInterface udp2_interface("udp2"); -#endif -#ifdef LORA_INTERFACE -RNS::Interfaces::LoRaInterface lora_interface; -#endif - -//ExampleAnnounceHandler announce_handler((const char*)"example_utilities.announcesample.fruits"); -//RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler("example_utilities.announcesample.fruits")); -RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler()); -#endif - -#if defined(RUN_TESTS) -void run_tests() { - - try { - - TRACE("Running tests..."); - RNS::LogLevel loglevel = RNS::loglevel(); - //RNS::loglevel(RNS::LOG_WARNING); - RNS::loglevel(RNS::LOG_TRACE); - //test(); - //testReference(); - //testCrypto(); - testPersistence(); - RNS::loglevel(loglevel); - TRACE("Finished running tests"); - //return; - } - catch (std::exception& e) { - ERRORF("!!! Exception in test: %s", e.what()); - } - -} -#endif - -#if defined(RUN_RETICULUM) -void reticulum_announce() { - if (destination) { - HEAD("Announcing destination...", RNS::LOG_TRACE); - //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); - // test path - //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7]), true, nullptr, RNS::bytesFromString("test_tag")); - // test packet send - destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); - } -} - -void reticulum_setup() { - INFO("Setting up Reticulum..."); - - try { - - //std::stringstream test; - // !!! just adding this single stringstream alone (not even using it) adds a whopping 17.1% !!! - // !!! JUST SAY NO TO STRINGSTREAM !!! - - // 18.5% completely empty program - - // 21.8% baseline here with serial - - HEAD("Registering Interface instances with Transport...", RNS::LOG_TRACE); -#ifdef UDP_INTERFACE - udp_interface.mode(RNS::Type::Interface::MODE_GATEWAY); - RNS::Transport::register_interface(udp_interface); -#endif -#ifdef UDP2_INTERFACE - udp2_interface.mode(RNS::Type::Interface::MODE_GATEWAY); - RNS::Transport::register_interface(udp2_interface); -#endif -#ifdef LORA_INTERFACE - lora_interface.mode(RNS::Type::Interface::MODE_GATEWAY); - RNS::Transport::register_interface(lora_interface); -#endif - -#ifdef UDP_INTERFACE - HEAD("Starting UDPInterface...", RNS::LOG_TRACE); - udp_interface.start("wifi_ssid", "wifi_password", 4242); -#endif -#ifdef UDP2_INTERFACE - HEAD("Starting UDPInterface...", RNS::LOG_TRACE); - udp_interface.start("wifi_ssid", "wifi_password", 2424); -#endif -#ifdef LORA_INTERFACE - HEAD("Starting LoRaInterface...", RNS::LOG_TRACE); - lora_interface.start(); -#endif - - HEAD("Creating Reticulum instance...", RNS::LOG_TRACE); - //RNS::Reticulum reticulum; - reticulum = RNS::Reticulum(); - reticulum.transport_enabled(true); - reticulum.start(); - //return; - // 21.9% (+0.1%) - - HEAD("Creating Identity instance...", RNS::LOG_TRACE); - // new identity - //RNS::Identity identity; - //identity = RNS::Identity(); - // predefined identity - //RNS::Identity identity(false); - identity = RNS::Identity(false); - RNS::Bytes prv_bytes; -#ifdef ARDUINO - prv_bytes.assignHex("78E7D93E28D55871608FF13329A226CABC3903A357388A035B360162FF6321570B092E0583772AB80BC425F99791DF5CA2CA0A985FF0415DAB419BBC64DDFAE8"); -#else - prv_bytes.assignHex("E0D43398EDC974EBA9F4A83463691A08F4D306D4E56BA6B275B8690A2FBD9852E9EBE7C03BC45CAEC9EF8E78C830037210BFB9986F6CA2DEE2B5C28D7B4DE6B0"); -#endif - identity.load_private_key(prv_bytes); - // 22.6% (+0.7%) - - HEAD("Creating Destination instance...", RNS::LOG_TRACE); - //RNS::Destination destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "app", "aspects"); - destination = RNS::Destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "app", "aspects"); - // 23.0% (+0.4%) - - // Register DATA packet callback - HEAD("Registering packet callback with Destination...", RNS::LOG_TRACE); - destination.set_packet_callback(onPacket); - destination.set_proof_strategy(RNS::Type::Destination::PROVE_ALL); - - { - // Register PING packet callback - HEAD("Creating PING Destination instance...", RNS::LOG_TRACE); - RNS::Destination ping_destination(identity, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "example_utilities", "echo.request"); - - HEAD("Registering packet callback with PING Destination...", RNS::LOG_TRACE); - ping_destination.set_packet_callback(onPingPacket); - ping_destination.set_proof_strategy(RNS::Type::Destination::PROVE_ALL); - } - - HEAD("Registering announce handler with Transport...", RNS::LOG_TRACE); - RNS::Transport::register_announce_handler(announce_handler); - -/* - HEAD("Announcing destination...", RNS::LOG_TRACE); - //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); - // test path - //destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7]), true, nullptr, RNS::bytesFromString("test_tag")); - // test packet send - destination.announce(RNS::bytesFromString(fruits[RNS::Cryptography::randomnum() % 7])); - // 23.9% (+0.8%) -*/ - -#if defined (RETICULUM_PACKET_TEST) - // test data send packet - HEAD("Creating send packet...", RNS::LOG_TRACE); - RNS::Packet send_packet(destination, "The quick brown fox jumps over the lazy dog"); - - HEAD("Sending send packet...", RNS::LOG_TRACE); - send_packet.pack(); -#ifndef NDEBUG - TRACE("Test send_packet: " + send_packet.debugString()); -#endif - - HEAD("Creating recv packet...", RNS::LOG_TRACE); - RNS::Packet recv_packet({RNS::Type::NONE}, send_packet.raw()); - recv_packet.unpack(); -#ifndef NDEBUG - TRACE("Test recv_packet: " + recv_packet.debugString()); -#endif - - HEAD("Spoofing recv packet to destination...", RNS::LOG_TRACE); - destination.receive(recv_packet); -#endif - - HEAD("Ready!", RNS::LOG_TRACE); - } - catch (std::exception& e) { - ERRORF("!!! Exception in reticulum_setup: %s", e.what()); - } -} - -void reticulum_teardown() { - INFO("Tearing down Reticulum..."); - - RNS::Transport::save_path_table(); - - try { - - HEAD("Deregistering announce handler with Transport...", RNS::LOG_TRACE); - RNS::Transport::deregister_announce_handler(announce_handler); - - HEAD("Deregistering Interface instances with Transport...", RNS::LOG_TRACE); -#ifdef UDP_INTERFACE - RNS::Transport::deregister_interface(udp_interface); -#endif -#ifdef UDP2_INTERFACE - RNS::Transport::deregister_interface(udp2_interface); -#endif -#ifdef LORA_INTERFACE - RNS::Transport::deregister_interface(lora_interface); -#endif - - } - catch (std::exception& e) { - ERRORF("!!! Exception in reticulum_teardown: %s", e.what()); - } -} -#endif - -#ifdef ARDUINO -void userKey(void) -{ - //delay(10); - if (digitalRead(BUTTON_PIN) == LOW) { - //Serial.print("T-Beam USER button press\n"); - send_announce = true; - } -} -#endif - -void setup() { - -#ifdef ARDUINO - Serial.begin(115200); - Serial.print("Hello from T-Beam on PlatformIO!\n"); - - // Setup user button - pinMode(BUTTON_PIN, INPUT); - attachInterrupt(BUTTON_PIN, userKey, FALLING); - - // Setup filesystem - if (!SPIFFS.begin(true, "")){ - ERROR("SPIFFS filesystem mount failed"); - } - else { - DEBUG("SPIFFS filesystem is ready"); - } -#endif - - RNS::loglevel(RNS::LOG_TRACE); - //RNS::loglevel(RNS::LOG_MEM); - -/* - { - //RNS::Reticulum reticulum_test; - RNS::Destination destination_test({RNS::Type::NONE}, RNS::Type::Destination::IN, RNS::Type::Destination::SINGLE, "test", "test"); - } -*/ - -#if defined(RUN_TESTS) - run_tests(); -#endif - -#if defined(RUN_RETICULUM) - reticulum_setup(); -#endif - -#ifdef ARDUINO - //Serial.print("Goodbye from T-Beam on PlatformIO!\n"); -#endif -} - -void loop() { - -#if defined(RUN_RETICULUM) - - reticulum.loop(); -#ifdef UDP_INTERFACE - udp_interface.loop(); -#endif -#ifdef UDP2_INTERFACE - udp2_interface.loop(); -#endif -#ifdef LORA_INTERFACE - lora_interface.loop(); -#endif - -#ifdef ARDUINO -/* - if ((RNS::Utilities::OS::time() - last_announce) > 10) { - reticulum_announce(); - last_announce = RNS::Utilities::OS::time(); - } -*/ -#endif - if (send_announce) { - reticulum_announce(); - send_announce = false; - } - -#endif - -} - -#ifndef ARDUINO -int getch( ) { - termios oldt; - termios newt; - tcgetattr( STDIN_FILENO, &oldt ); - newt = oldt; - newt.c_lflag &= ~( ICANON | ECHO ); - tcsetattr( STDIN_FILENO, TCSANOW, &newt ); - fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | O_NONBLOCK); - int ch = getchar(); - tcsetattr( STDIN_FILENO, TCSANOW, &oldt ); - return ch; -} - -int main(void) { - printf("Hello from Native on PlatformIO!\n"); - - setup(); - - bool run = true; - while (run) { - loop(); - int ch = getch(); - if (ch > 0) { - switch (ch) { - case 'a': -#if defined(RUN_RETICULUM) - reticulum_announce(); -#endif - break; - case 'q': - run = false; - break; - } - } - RNS::Utilities::OS::sleep(0.01); - } - -#if defined(RUN_RETICULUM) - reticulum_teardown(); -#endif - - printf("Goodbye from Native on PlatformIO!\n"); -} -#endif diff --git a/examples/udp_announce/.vscode/settings.json b/examples/udp_announce/.vscode/settings.json new file mode 100644 index 0000000..e179302 --- /dev/null +++ b/examples/udp_announce/.vscode/settings.json @@ -0,0 +1,67 @@ +{ + "files.associations": { + "__bit_reference": "cpp", + "__config": "cpp", + "__hash_table": "cpp", + "__locale": "cpp", + "__node_handle": "cpp", + "__split_buffer": "cpp", + "__threading_support": "cpp", + "__tree": "cpp", + "__verbose_abort": "cpp", + "array": "cpp", + "bitset": "cpp", + "cctype": "cpp", + "cfenv": "cpp", + "charconv": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "complex": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "execution": "cpp", + "forward_list": "cpp", + "fstream": "cpp", + "initializer_list": "cpp", + "iomanip": "cpp", + "ios": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "limits": "cpp", + "list": "cpp", + "locale": "cpp", + "map": "cpp", + "mutex": "cpp", + "new": "cpp", + "optional": "cpp", + "ostream": "cpp", + "queue": "cpp", + "ratio": "cpp", + "set": "cpp", + "shared_mutex": "cpp", + "source_location": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "string": "cpp", + "string_view": "cpp", + "strstream": "cpp", + "tuple": "cpp", + "typeindex": "cpp", + "typeinfo": "cpp", + "unordered_map": "cpp", + "unordered_set": "cpp", + "variant": "cpp", + "vector": "cpp", + "algorithm": "cpp" + } +} \ No newline at end of file diff --git a/examples/udp_announce/UDPInterface.cpp b/examples/udp_announce/UDPInterface.cpp index b1d121d..a7cfce6 100644 --- a/examples/udp_announce/UDPInterface.cpp +++ b/examples/udp_announce/UDPInterface.cpp @@ -1,5 +1,6 @@ #include "UDPInterface.h" +#include #include "../src/Log.h" #include @@ -224,11 +225,6 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa } } -/*virtual*/ void UDPInterface::on_incoming(const Bytes& data) { - DEBUG(toString() + ".on_incoming: data: " + data.toHex()); - //Interface::on_incoming(data); -} - /*virtual*/ void UDPInterface::send_outgoing(const Bytes& data) { DEBUG(toString() + ".on_outgoing: data: " + data.toHex()); try { @@ -249,11 +245,16 @@ UDPInterface::UDPInterface(const char* name /*= "UDPInterface"*/) : RNS::Interfa #endif } - //Interface::on_outgoing(data); - // CBA Call base method to handle internal housekeeping - InterfaceImpl::send_outgoing(data); + // Perform post-send housekeeping + InterfaceImpl::handle_outgoing(data); } catch (std::exception& e) { ERROR("Could not transmit on " + toString() + ". The contained exception was: " + e.what()); } } + +void UDPInterface::on_incoming(const Bytes& data) { + DEBUG(toString() + ".on_incoming: data: " + data.toHex()); + // Pass received data on to transport + InterfaceImpl::handle_incoming(data); +} diff --git a/examples/udp_announce/UDPInterface.h b/examples/udp_announce/UDPInterface.h index 4d44444..f70102c 100644 --- a/examples/udp_announce/UDPInterface.h +++ b/examples/udp_announce/UDPInterface.h @@ -40,9 +40,8 @@ public: //virtual inline std::string toString() const { return "UDPInterface[" + name() + "]"; } protected: - virtual void on_incoming(const RNS::Bytes& data); - //virtual void on_outgoing(const RNS::Bytes& data); virtual void send_outgoing(const RNS::Bytes& data); + void on_incoming(const RNS::Bytes& data); private: const uint16_t HW_MTU = 1064; diff --git a/examples/udp_announce/main.cpp b/examples/udp_announce/main.cpp index 09def10..17c3a34 100644 --- a/examples/udp_announce/main.cpp +++ b/examples/udp_announce/main.cpp @@ -3,16 +3,16 @@ #include "UDPInterface.h" #include "FileSystem.h" -#include "Reticulum.h" -#include "Identity.h" -#include "Destination.h" -#include "Packet.h" -#include "Transport.h" -#include "Interface.h" -#include "Log.h" -#include "Bytes.h" -#include "Type.h" -#include "Utilities/OS.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #ifdef ARDUINO #include @@ -124,12 +124,13 @@ void reticulum_setup() { // 21.8% baseline here with serial + HEAD("Registering FileSystem with OS...", RNS::LOG_TRACE); test_filesystem_impl = new FileSystem(); test_filesystem = test_filesystem_impl; ((FileSystem*)test_filesystem.get())->init(); RNS::Utilities::OS::register_filesystem(test_filesystem); - HEAD("Registering Interface instances with Transport...", RNS::LOG_TRACE); + HEAD("Registering UDPInterface instances with Transport...", RNS::LOG_TRACE); udp_interface_impl = new UDPInterface(); udp_interface = udp_interface_impl; udp_interface.mode(RNS::Type::Interface::MODE_GATEWAY); @@ -227,7 +228,7 @@ void reticulum_setup() { void reticulum_teardown() { INFO("Tearing down Reticulum..."); - //zzzCBA RNS::Transport::save_path_table(); + RNS::Transport::persist_data(); try { @@ -273,8 +274,13 @@ void setup() { } #endif - RNS::loglevel(RNS::LOG_TRACE); - //RNS::loglevel(RNS::LOG_MEM); +#if defined(MEM_LOG) + RNS::loglevel(RNS::LOG_MEM); +#else + //RNS::loglevel(RNS::LOG_WARNING); + //RNS::loglevel(RNS::LOG_DEBUG); + RNS::loglevel(RNS::LOG_TRACE); +#endif /* { diff --git a/examples/udp_announce/platformio.ini b/examples/udp_announce/platformio.ini index 12cf92b..d8f6ebb 100644 --- a/examples/udp_announce/platformio.ini +++ b/examples/udp_announce/platformio.ini @@ -22,7 +22,12 @@ build_type = debug build_flags = -DRNS_USE_ALLOCATOR=1 -DRNS_USE_TLSF=1 + ;-DMEM_LOG lib_deps = + ArduinoJson@^6.21.3 + https://github.com/attermann/Crypto.git + https://github.com/hideakitai/MsgPack.git + microReticulum=symlink://../.. [env:native] platform = native @@ -41,9 +46,6 @@ build_flags = -DNATIVE lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. lib_extra_dirs = ../ lib_compat_mode = off ;debug_init_break = @@ -67,9 +69,6 @@ build_flags = -DNATIVE lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. lib_extra_dirs = ../ lib_compat_mode = off @@ -100,9 +99,6 @@ build_flags = -DNATIVE lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. lib_extra_dirs = ../ lib_compat_mode = off @@ -122,9 +118,6 @@ build_flags = -DCUBECELL lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. ; CBA NOTE must undef min and max from Arduino.h [env:heltec-tracker] @@ -146,9 +139,6 @@ build_flags = lib_deps = ${env.lib_deps} lovyan03/LovyanGFX@^1.1.8 - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. [env:ttgo-lora32-v21] framework = arduino @@ -166,9 +156,6 @@ build_flags = -DBOARD_ESP32 lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. monitor_filters = esp32_exception_decoder [env:ttgo-t-beam] @@ -187,9 +174,6 @@ build_flags = -DBOARD_ESP32 lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. monitor_filters = esp32_exception_decoder [env:wiscore_rak4631] @@ -211,9 +195,6 @@ build_flags = build_unflags = -fno-exceptions lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. [env:nrf52840_dk_adafruit] framework = arduino @@ -234,4 +215,3 @@ build_flags = ${env.build_flags} lib_deps = ${env.lib_deps} - diff --git a/examples/unit_tests/.vscode/settings.json b/examples/unit_tests/.vscode/settings.json new file mode 100644 index 0000000..e179302 --- /dev/null +++ b/examples/unit_tests/.vscode/settings.json @@ -0,0 +1,67 @@ +{ + "files.associations": { + "__bit_reference": "cpp", + "__config": "cpp", + "__hash_table": "cpp", + "__locale": "cpp", + "__node_handle": "cpp", + "__split_buffer": "cpp", + "__threading_support": "cpp", + "__tree": "cpp", + "__verbose_abort": "cpp", + "array": "cpp", + "bitset": "cpp", + "cctype": "cpp", + "cfenv": "cpp", + "charconv": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "complex": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "execution": "cpp", + "forward_list": "cpp", + "fstream": "cpp", + "initializer_list": "cpp", + "iomanip": "cpp", + "ios": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "limits": "cpp", + "list": "cpp", + "locale": "cpp", + "map": "cpp", + "mutex": "cpp", + "new": "cpp", + "optional": "cpp", + "ostream": "cpp", + "queue": "cpp", + "ratio": "cpp", + "set": "cpp", + "shared_mutex": "cpp", + "source_location": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "string": "cpp", + "string_view": "cpp", + "strstream": "cpp", + "tuple": "cpp", + "typeindex": "cpp", + "typeinfo": "cpp", + "unordered_map": "cpp", + "unordered_set": "cpp", + "variant": "cpp", + "vector": "cpp", + "algorithm": "cpp" + } +} \ No newline at end of file diff --git a/examples/unit_tests/A.cpp b/examples/unit_tests/A.cpp new file mode 100644 index 0000000..18c811d --- /dev/null +++ b/examples/unit_tests/A.cpp @@ -0,0 +1,88 @@ +#include "A.h" + +#include "B.h" +#include + +#if TEST_OBJECT_DATA + +#include "AData.h" + +A::A() { + printf("A() A=%x\n", getId()); +} + +A::A(const A& ref) : _data(ref._data) { + printf("A(A) A=%x\n", getId()); +} + +A::A(const B& b) : _data(new AData(b)) { + printf("A(B) A=%x B=%x\n", getId(), _data->_b.getId()); +} + +A& A::operator = (const A& ref) { + _data = ref._data; + printf("=(A) A=%x\n", getId()); + return *this; +} + +B A::getB() { + printf("getB() A=%x B=%x\n", getId(), _data->_b.getId()); + return _data->_b; +} + +long A::getId() { + return (long)_data.get(); +} + +#elif TEST_OBJECT_IMPL + +#include "AImpl.h" + +A::A() { +//A::A(AImpl::Ptr impl) : _impl(impl) { + printf("A() A=%x\n", getId()); +} + +A::A(const A& ref) : _impl(ref._impl) { + printf("A(A) A=%x\n", getId()); +} + +A::A(const B& b) : _impl(new AImpl(b)) { + //printf("A(B) A=%x B=%x\n", getId(), _impl->_b.getId()); + printf("A(B) A=%x\n", getId()); +} + +A& A::operator = (const A& ref) { + _impl = ref._impl; + printf("=(A) A=%x\n", getId()); + return *this; +} + +B A::getB() { + //printf("getB() A=%x B=%x\n", getId(), _impl->_b.getId()); + printf("getB() A=%x\n", getId()); + return _impl->getB(); +} + +long A::getId() { + return (long)_impl.get(); +} + +#else + +A::A() { +} + +A::A(const B& b) { + _b = b; +} + +B A::getB() { + return _b; +} + +long A::getId() { + return 0; +} + +#endif diff --git a/examples/unit_tests/A.h b/examples/unit_tests/A.h new file mode 100644 index 0000000..63bea72 --- /dev/null +++ b/examples/unit_tests/A.h @@ -0,0 +1,55 @@ +#pragma once + +#if TEST_OBJECT_DATA + +#include + +class AData; +class B; + +class A { +public: + A(); + A(const B& b); + A(const A& ref); + A& operator = (const A& ref); + B getB(); + long getId(); +protected: + std::shared_ptr _data; +}; + +#elif TEST_OBJECT_IMPL + +#include + +class AImpl; +class B; + +class A { +public: + A(); + A(const B& b); + A(const A& ref); + A& operator = (const A& ref); + B getB(); + long getId(); +protected: + std::shared_ptr _impl; +}; + +#else + +#include "B.h" + +class A { +public: + A(); + A(const B& b); + B getB(); + long getId(); +protected: + B _b; +}; + +#endif diff --git a/examples/unit_tests/AData.h b/examples/unit_tests/AData.h new file mode 100644 index 0000000..660708c --- /dev/null +++ b/examples/unit_tests/AData.h @@ -0,0 +1,12 @@ +#pragma once + +#include "B.h" + +class AData { +protected: + AData() {} + AData(const B& b) : _b(b) {} +protected: + B _b; +friend class A; +}; diff --git a/examples/unit_tests/AImpl.cpp b/examples/unit_tests/AImpl.cpp new file mode 100644 index 0000000..6897b53 --- /dev/null +++ b/examples/unit_tests/AImpl.cpp @@ -0,0 +1,5 @@ +#include "AImpl.h" + +B AImpl::getB() { + return _b; +} diff --git a/examples/unit_tests/AImpl.h b/examples/unit_tests/AImpl.h new file mode 100644 index 0000000..f2489bd --- /dev/null +++ b/examples/unit_tests/AImpl.h @@ -0,0 +1,13 @@ +#pragma once + +#include "B.h" + +class AImpl { +public: + using Ptr = std::shared_ptr; + AImpl() {} + AImpl(const B& b) : _b(b) {} + B getB(); +protected: + B _b; +}; diff --git a/examples/unit_tests/B.cpp b/examples/unit_tests/B.cpp new file mode 100644 index 0000000..b95f54d --- /dev/null +++ b/examples/unit_tests/B.cpp @@ -0,0 +1,87 @@ +#include "B.h" + +#include "A.h" +#include + +#if TEST_OBJECT_DATA + +#include "BData.h" + +B::B() { + printf("B() B=%x\n", getId()); +} + +B::B(const B& ref) : _data(ref._data) { + printf("B(B) B=%x\n", getId()); +} + +B::B(const A& a) : _data(new BData(a)) { + printf("B(A) B=%x A=%x\n", getId(), _data->_a.getId()); +} + +B& B::operator = (const B& ref) { + _data = ref._data; + printf("=(B) B=%x\n", getId()); + return *this; +} + +A B::getA() { + printf("getA() B=%x A=%x\n", getId(), _data->_a.getId()); + return _data->_a; +} + +long B::getId() { + return (long)_data.get(); +} + +#elif TEST_OBJECT_IMPL + +#include "BImpl.h" + +B::B() { + printf("B() B=%x\n", getId()); +} + +B::B(const B& ref) : _impl(ref._impl) { + printf("B(B) B=%x\n", getId()); +} + +B::B(const A& a) : _impl(new BImpl(a)) { + //printf("B(A) B=%x A=%x\n", getId(), _impl->_a.getId()); + printf("B(A) B=%x\n", getId()); +} + +B& B::operator = (const B& ref) { + _impl = ref._impl; + printf("=(B) B=%x\n", getId()); + return *this; +} + +A B::getA() { + //printf("getA() B=%x A=%x\n", getId(), _impl->_a.getId()); + printf("getA() B=%x\n", getId()); + return _impl->getA(); +} + +long B::getId() { + return (long)_impl.get(); +} + +#else + +B::B() { +} + +B::B(const A& a) { + _a = a; +} + +A B::getA() { + return _a; +} + +long B::getId() { + return 0; +} + +#endif diff --git a/examples/unit_tests/B.h b/examples/unit_tests/B.h new file mode 100644 index 0000000..55a542b --- /dev/null +++ b/examples/unit_tests/B.h @@ -0,0 +1,55 @@ +#pragma once + +#if TEST_OBJECT_DATA + +#include + +class BData; +class A; + +class B { +public: + B(); + B(const A& a); + B(const B& ref); + B& operator = (const B& ref); + A getA(); + long getId(); +protected: + std::shared_ptr _data; +}; + +#elif TEST_OBJECT_IMPL + +#include + +class BImpl; +class A; + +class B { +public: + B(); + B(const A& a); + B(const B& ref); + B& operator = (const B& ref); + A getA(); + long getId(); +protected: + std::shared_ptr _impl; +}; + +#else + +#include "A.h" + +class B { +public: + B(); + B(const A& a); + A getA(); + long getId(); +protected: + A _a; +}; + +#endif diff --git a/examples/unit_tests/BData.h b/examples/unit_tests/BData.h new file mode 100644 index 0000000..a9ed43a --- /dev/null +++ b/examples/unit_tests/BData.h @@ -0,0 +1,12 @@ +#pragma once + +#include "A.h" + +class BData { +protected: + BData() {} + BData(const A& a) : _a(a) {} +protected: + A _a; +friend class B; +}; diff --git a/examples/unit_tests/BImpl.cpp b/examples/unit_tests/BImpl.cpp new file mode 100644 index 0000000..baf5500 --- /dev/null +++ b/examples/unit_tests/BImpl.cpp @@ -0,0 +1,5 @@ +#include "BImpl.h" + +A BImpl::getA() { + return _a; +} diff --git a/examples/unit_tests/BImpl.h b/examples/unit_tests/BImpl.h new file mode 100644 index 0000000..27b3ef6 --- /dev/null +++ b/examples/unit_tests/BImpl.h @@ -0,0 +1,13 @@ +#pragma once + +#include "A.h" + +class BImpl { +public: + using Ptr = std::shared_ptr; + BImpl() {} + BImpl(const A& a) : _a(a) {} + A getA(); +protected: + A _a; +}; diff --git a/examples/unit_tests/Test.cpp b/examples/unit_tests/Test.cpp index bb6aa1a..ce44ffd 100644 --- a/examples/unit_tests/Test.cpp +++ b/examples/unit_tests/Test.cpp @@ -10,5 +10,6 @@ void test() { testPersistence(); testFileSystem(); testReticulum(); + testObjects(); } diff --git a/examples/unit_tests/Test.h b/examples/unit_tests/Test.h index 36fb73c..ababa15 100644 --- a/examples/unit_tests/Test.h +++ b/examples/unit_tests/Test.h @@ -9,3 +9,4 @@ void testCrypto(); void testPersistence(); void testFileSystem(); void testReticulum(); +void testObjects(); diff --git a/examples/unit_tests/TestBytes.cpp b/examples/unit_tests/TestBytes.cpp index a784e40..4c556c2 100644 --- a/examples/unit_tests/TestBytes.cpp +++ b/examples/unit_tests/TestBytes.cpp @@ -58,19 +58,20 @@ void testBytesMain() { TRACE("bytess are different"); } - bytes += prebuf + postbuf; - assert(bytes.size() == 11); - assert(memcmp(bytes.data(), "Hello World", bytes.size()) == 0); - TRACE("assign bytes: " + bytes.toString()); - TRACE("assign prebuf: " + prebuf.toString()); - TRACE("assign postbuf: " + postbuf.toString()); - // test string assignment bytes = "Foo"; assert(bytes.size() == 3); assert(memcmp(bytes.data(), "Foo", bytes.size()) == 0); - // test string addition + // test string concat with addition + bytes += prebuf + postbuf; + assert(bytes.size() == 14); + assert(memcmp(bytes.data(), "FooHello World", bytes.size()) == 0); + TRACE("assign bytes: " + bytes.toString()); + TRACE("assign prebuf: " + prebuf.toString()); + TRACE("assign postbuf: " + postbuf.toString()); + + // test string assignment with addition bytes = prebuf + postbuf; assert(bytes.size() == 11); assert(memcmp(bytes.data(), "Hello World", bytes.size()) == 0); @@ -167,7 +168,7 @@ void testBytesMain() { // test creating bytes from NONE { - RNS::Bytes bytes({RNS::Bytes::NONE}); + RNS::Bytes bytes(RNS::Bytes::NONE); assert(!bytes); assert(bytes.size() == 0); assert(bytes.data() == nullptr); @@ -385,7 +386,10 @@ void testBytesStream() { // stream with assignment HEAD("TestBytes: stream with assignment", RNS::LOG_TRACE); - // (side effect of also updating pre - this is a known and correct but perhaps unexpected and non-intuitive side-effect of assignment with stream) + // NOTE: This test demonstrates a side-effect of the stream insertion operator!!! + // When pre is volatile (non-const) then it gets updated in the process of inserting both pre and post. + // This is a known and correct but perhaps unexpected and non-intuitive side-effect of assignment with stream. + // To counter this side-effect, intermediate Bytes in a stream insertion chain must be const to avoid being modified. { // NOTE pre must be volatile in order for below stream with assignment to work (since it gets modified) RNS::Bytes pre("Hello"); @@ -434,6 +438,7 @@ void testBytesReserve() { } void testFind() { + HEAD("testFind:", RNS::LOG_TRACE); RNS::Bytes src("Hello"); assert(0 == src.find("H")); assert(-1 == src.find(1, "H")); @@ -445,6 +450,104 @@ void testFind() { assert(-1 == src.find("foo")); } +void testCompare() { + HEAD("testCompare:", RNS::LOG_TRACE); + RNS::Bytes bytes("Hello\x20World"); + //RNS::Bytes bytes("Hello World"); + TRACEF("testCompare: %s", bytes.toString().c_str()); + assert(bytes == RNS::Bytes("Hello World")); + assert(bytes == RNS::Bytes("Hello\x20World")); + assert(bytes == "Hello World"); + assert(bytes == "Hello\x20World"); +} + +void testConcat() { + HEAD("testConcat:", RNS::LOG_TRACE); + + const RNS::Bytes bytes1("Hello"); + const RNS::Bytes bytes2(" World"); + + { + TRACE("testConcat: prefix"); + RNS::Bytes bytes("Prefix "); + } + + // CBA NOTE: Addition-assignment operator is the only case in this test that involves + // an extra/intermediate object creation and should therfore be avoided. + { + TRACE("testConcat: prefix addition-assignment with addition"); + RNS::Bytes bytes("Prefix "); + bytes += bytes1 + bytes2; + //TRACEF("testConcat: bytes: %s", bytes.toString().c_str()); + assert(bytes.size() == 18); + assert(memcmp(bytes.data(), "Prefix Hello World", bytes.size()) == 0); + assert(memcmp(bytes1.data(), "Hello", bytes1.size()) == 0); + assert(memcmp(bytes2.data(), " World", bytes2.size()) == 0); + } + + // CBA NOTE: Extreme care must be excercised when using stream insertion since intermediate + // Bytes that are volatile (non-const) will be modified in the process!!! + { + TRACE("testConcat: prefix stream"); + RNS::Bytes bytes("Prefix "); + bytes << bytes1 << bytes2; + //TRACEF("testConcat: bytes: %s", bytes.toString().c_str()); + assert(bytes.size() == 18); + assert(memcmp(bytes.data(), "Prefix Hello World", bytes.size()) == 0); + assert(memcmp(bytes1.data(), "Hello", bytes1.size()) == 0); + assert(memcmp(bytes2.data(), " World", bytes2.size()) == 0); + } + + { + TRACE("testConcat: assignment with addition"); + const RNS::Bytes bytes = bytes1 + bytes2; + //TRACEF("testConcat: bytes: %s", bytes.toString().c_str()); + assert(bytes.size() == 11); + assert(memcmp(bytes.data(), "Hello World", bytes.size()) == 0); + assert(memcmp(bytes1.data(), "Hello", bytes1.size()) == 0); + assert(memcmp(bytes2.data(), " World", bytes2.size()) == 0); + } + + // CBA NOTE: Following construct with assignment using stream insertion is NOT WORKING!!! + // Using volatile (non-const) Bytes instead does work in this fashion, but that + // has side-effects as stated above. + // CBA NOTE: Also curious why Bytes constructor with capacity is being invoked here. +/* + { + TRACE("testConcat: assignment with stream"); + const RNS::Bytes bytes = bytes1 << bytes2; + //TRACEF("testConcat: bytes: %s", bytes.toString().c_str()); + assert(bytes.size() == 11); + assert(memcmp(bytes.data(), "Hello World", bytes.size()) == 0); + assert(memcmp(bytes1.data(), "Hello", bytes1.size()) == 0); + assert(memcmp(bytes2.data(), " World", bytes2.size()) == 0); + } +*/ + + { + TRACE("testConcat: empty with separate stream"); + RNS::Bytes bytes; + bytes << bytes1; + bytes << bytes2; + //TRACEF("testConcat: bytes: %s", bytes.toString().c_str()); + assert(bytes.size() == 11); + assert(memcmp(bytes.data(), "Hello World", bytes.size()) == 0); + assert(memcmp(bytes1.data(), "Hello", bytes1.size()) == 0); + assert(memcmp(bytes2.data(), " World", bytes2.size()) == 0); + } + + { + TRACE("testConcat: construct with addition"); + const RNS::Bytes bytes(bytes1 + bytes2); + //TRACEF("testConcat: bytes: %s", bytes.toString().c_str()); + assert(bytes.size() == 11); + assert(memcmp(bytes.data(), "Hello World", bytes.size()) == 0); + assert(memcmp(bytes1.data(), "Hello", bytes1.size()) == 0); + assert(memcmp(bytes2.data(), " World", bytes2.size()) == 0); + } + +} + void testBytes() { HEAD("Running testBytes...", RNS::LOG_TRACE); @@ -460,6 +563,8 @@ void testBytes() { testBytesStream(); testBytesReserve(); testFind(); + testCompare(); + testConcat(); size_t post_memory = RNS::Utilities::OS::heap_available(); size_t diff_memory = (int)pre_memory - (int)post_memory; diff --git a/examples/unit_tests/TestObjects.cpp b/examples/unit_tests/TestObjects.cpp new file mode 100644 index 0000000..5c4ac19 --- /dev/null +++ b/examples/unit_tests/TestObjects.cpp @@ -0,0 +1,30 @@ + +#include "A.h" +#include "B.h" + +#include + +void testObjects() { + + printf("Creating a...\n"); + A a = A(); + printf("Creating b...\n"); + B b = B(); + + // Following assignments are invalid because a and b are empty + //printf("Assigning b1...\n"); + //B b1 = a.getB(); + //printf("Assigning a1...\n"); + //A a1 = b.getA(); + + printf("Creating ab...\n"); + A ab = A(b); + printf("Creating ba...\n"); + B ba = B(a); + + printf("Assigning b2...\n"); + B b2 = ab.getB(); + printf("Assigning a2...\n"); + A a2 = ba.getA(); + +} diff --git a/examples/unit_tests/TestPersistence.cpp b/examples/unit_tests/TestPersistence.cpp index e1ac1cd..5642b0f 100644 --- a/examples/unit_tests/TestPersistence.cpp +++ b/examples/unit_tests/TestPersistence.cpp @@ -2,14 +2,15 @@ #include "FileSystem.h" -#include "Interface.h" -#include "Transport.h" -#include "Log.h" -#include "Bytes.h" -#include "Utilities/OS.h" -#include "Utilities/Persistence.h" +#include +#include +#include +#include +#include +#include //#include +#include #include #include @@ -27,12 +28,15 @@ public: virtual ~TestInterface() {} private: - virtual void handle_incoming(const RNS::Bytes& data) { - DEBUG("TestInterface.handle_incoming: data: " + data.toHex()); - } virtual void send_outgoing(const RNS::Bytes& data) { DEBUG("TestInterface.send_outgoing: data: " + data.toHex()); - InterfaceImpl::send_outgoing(data); + // Perform post-send housekeeping + InterfaceImpl::handle_outgoing(data); + } + void on_incoming(const RNS::Bytes& data) { + DEBUG("TestInterface.on_incoming: data: " + data.toHex()); + // Pass received data on to transport + InterfaceImpl::handle_incoming(data); } }; @@ -107,8 +111,12 @@ void testRead() { #ifdef ARDUINO const char test_object_path[] = "/test_object"; +const char test_array_path[] = "/test_array"; +const char test_series_path[] = "/test_series"; #else const char test_object_path[] = "test_object"; +const char test_array_path[] = "test_array"; +const char test_series_path[] = "test_series"; #endif /* @@ -178,7 +186,7 @@ void testSerializeObject() { std::vector vec({"one", "two"}); TestObject test("test", vec); - TRACE("serializeObject: test: " + test.toString()); + TRACE("testSerializeObject: test: " + test.toString()); StaticJsonDocument<1024> doc; doc = test; @@ -190,18 +198,18 @@ void testSerializeObject() { if (length < size) { data.resize(length); } - TRACE("serialized " + std::to_string(length) + " bytes"); + TRACE("testSerializeObject: serialized " + std::to_string(length) + " bytes"); if (length > 0) { if (RNS::Utilities::OS::write_file(test_object_path, data) == data.size()) { - TRACE("wrote: " + std::to_string(data.size()) + " bytes"); + TRACE("testSerializeObject: wrote: " + std::to_string(data.size()) + " bytes"); } else { - TRACE("write failed"); + TRACE("testSerializeObject: write failed"); assert(false); } } else { - TRACE("failed to serialize"); + TRACE("testSerializeObject: failed to serialize"); assert(false); } @@ -214,7 +222,7 @@ void testDeserializeObject() { RNS::Bytes data; if (RNS::Utilities::OS::read_file(test_object_path, data) > 0) { - TRACE("read: " + std::to_string(data.size()) + " bytes"); + TRACE("testDeserializeObject: read: " + std::to_string(data.size()) + " bytes"); //TRACE("data: " + data.toString()); DeserializationError error = deserializeJson(doc, data.data()); //DeserializationError error = deserializeMsgPack(doc, data.data()); @@ -233,7 +241,7 @@ void testDeserializeObject() { //assert(RNS::Utilities::OS::remove_file(test_object_path)); } else { - TRACE("read failed"); + TRACE("testDeserializeObject: read failed"); assert(false); } @@ -783,6 +791,381 @@ void testSerializeTimeOffset() { } +class TestOtherObject { +public: + TestOtherObject() {} + TestOtherObject(const char* str, std::vector& vec) : _str(str), _vec(vec) {} + inline bool operator < (const TestOtherObject& test) const { return _str < test._str; } + inline const std::string toString() const { return std::string("TestOtherObject(") + _str + "," + std::to_string(_vec.size()) + ")"; } + std::string _str; + std::vector _vec; +}; + +struct TestStruct { + int foo; + int bar; +}; + + +void testJsonMsgpackSerializeObject() { + + std::vector vec({"one", "two"}); + TestObject test("test", vec); + TRACE("testJsonMsgpackSerializeObject: test: " + test.toString()); + + StaticJsonDocument<1024> doc; + doc = test; + + RNS::Bytes data; + size_t size = 1024; + size_t length = serializeMsgPack(doc, data.writable(size), size); + if (length < size) { + data.resize(length); + } + TRACE("testJsonMsgpackSerializeObject: serialized " + std::to_string(length) + " bytes"); + if (length > 0) { + if (RNS::Utilities::OS::write_file(test_object_path, data) == data.size()) { + TRACE("testJsonMsgpackSerializeObject: wrote: " + std::to_string(data.size()) + " bytes"); + } + else { + TRACE("testJsonMsgpackSerializeObject: write failed"); + assert(false); + } + } + else { + TRACE("testJsonMsgpackSerializeObject: failed to serialize"); + assert(false); + } + +} + +void testJsonMsgpackDeserializeObject() { + + //StaticJsonDocument<8192> doc; + DynamicJsonDocument doc(1024); + + RNS::Bytes data; + if (RNS::Utilities::OS::read_file(test_object_path, data) > 0) { + TRACE("testJsonMsgpackDeserializeObject: read: " + std::to_string(data.size()) + " bytes"); + //TRACE("data: " + data.toString()); + DeserializationError error = deserializeMsgPack(doc, data.data()); + if (!error) { + //JsonObject root = doc.as(); + //for (JsonPair kv : root) { + // TRACE("key: " + std::string(kv.key().c_str()) + " value: " + kv.value().as()); + //} + TestObject test = doc.as(); + TRACE("testJsonMsgpackDeserializeObject: test: " + test.toString()); + } + else { + TRACE("testJsonMsgpackDeserializeObject: failed to deserialize"); + assert(false); + } + //assert(RNS::Utilities::OS::remove_file(test_object_path)); + } + else { + TRACE("testJsonMsgpackDeserializeObject: read failed"); + assert(false); + } + +} + +void testJsonMsgpackSerializeArray() { + + // NOTE: Following is creating a msgpack that appears in Python like: + // [123.456, [102, 105, 114, 115, 116, 171], [115, 101, 99, 111, 110, 100, 205]] + + double time = 123.456; + // CBA Need this version writing byte-arrays to match the python version also writing byte-arrays (25 bytes) + const RNS::Bytes one("first\xab"); + const RNS::Bytes two("second\xcd"); + //TRACEF("testJsonMsgpackSerializeArray: time=%f one=%s two=%s", time, one.toString().c_str(), two.toString().c_str()); + // CBA This version writing strings exactly matches the python version also writing strings (23 bytes) + //const std::string one("first"); + //const std::string two("second"); + //TRACEF("testJsonMsgpackSerializeArray: time=%f one=%s two=%s", time, one.c_str(), two.c_str()); + + StaticJsonDocument<1024> doc; + + JsonArray array = doc.to(); + array.add(time); + //array.add(one); + //array.add(two); + const JsonArray a_one = doc.createNestedArray(); + for (uint8_t byte : one.collection()) { + a_one.add(byte); + } + const JsonArray a_two = doc.createNestedArray(); + for (uint8_t byte : two.collection()) { + a_two.add(byte); + } + + RNS::Bytes data; + size_t size = 1024; + size_t length = serializeMsgPack(doc, data.writable(size), size); + if (length < size) { + data.resize(length); + } + TRACE("testJsonMsgpackSerializeArray: serialized " + std::to_string(length) + " bytes"); + if (length > 0) { + if (RNS::Utilities::OS::write_file(test_array_path, data) == data.size()) { + TRACE("testJsonMsgpackSerializeArray: wrote: " + std::to_string(data.size()) + " bytes"); + } + else { + TRACE("testJsonMsgpackSerializeArray: write failed"); + assert(false); + } + } + else { + TRACE("testJsonMsgpackSerializeArray: failed to serialize"); + assert(false); + } + +} + +void testJsonMsgpackDeserializeArray() { + + StaticJsonDocument<1024> doc; + + RNS::Bytes data; + if (RNS::Utilities::OS::read_file(test_array_path, data) > 0) { + TRACE("testJsonMsgpackDeserializeArray: read: " + std::to_string(data.size()) + " bytes"); + //TRACE("data: " + data.toString()); + DeserializationError error = deserializeMsgPack(doc, data.data(), data.size()); + if (!error) { + JsonArray array = doc.as(); + double time = array[0].as(); + //std::string one(array[1].as()); + //RNS::Bytes one(array[1].as()); + RNS::Bytes one(array[1].as>()); + //std::string two(array[2].as()); + //RNS::Bytes two(array[2].as()); + RNS::Bytes two(array[2].as>()); + TRACEF("testJsonMsgpackDeserializeArray: time=%f one=%s two=%s", time, one.toString().c_str(), two.toString().c_str()); + //TRACEF("testJsonMsgpackDeserializeArray: time=%f one=%s two=%s", time, one.c_str(), two.c_str()); + assert(one == "first\xab"); + assert(two == "second\xcd"); + } + else { + TRACE("testJsonMsgpackDeserializeArray: failed to deserialize"); + assert(false); + } + //assert(RNS::Utilities::OS::remove_file(test_array_path)); + } + else { + TRACE("testJsonMsgpackDeserializeArray: read failed"); + assert(false); + } + +} + + +void testMsgpackSerializeObject() { + + std::vector vec({"one", "two"}); + TestObject test("test", vec); + TRACE("testMsgpackSerializeObject: test: " + test.toString()); + + StaticJsonDocument<1024> doc; + doc = test; + + RNS::Bytes data; + size_t size = 1024; + size_t length = serializeMsgPack(doc, data.writable(size), size); + if (length < size) { + data.resize(length); + } + TRACE("testMsgpackSerializeObject: serialized " + std::to_string(length) + " bytes"); + if (length > 0) { + if (RNS::Utilities::OS::write_file(test_object_path, data) == data.size()) { + TRACE("testMsgpackSerializeObject: wrote: " + std::to_string(data.size()) + " bytes"); + } + else { + TRACE("testMsgpackSerializeObject: write failed"); + assert(false); + } + } + else { + TRACE("testMsgpackSerializeObject: failed to serialize"); + assert(false); + } + +} + +void testMsgpackDeserializeObject() { + + //StaticJsonDocument<8192> doc; + DynamicJsonDocument doc(1024); + + RNS::Bytes data; + if (RNS::Utilities::OS::read_file(test_object_path, data) > 0) { + TRACE("testMsgpackDeserializeObject: read: " + std::to_string(data.size()) + " bytes"); + //TRACE("data: " + data.toString()); + DeserializationError error = deserializeMsgPack(doc, data.data()); + if (!error) { + //JsonObject root = doc.as(); + //for (JsonPair kv : root) { + // TRACE("key: " + std::string(kv.key().c_str()) + " value: " + kv.value().as()); + //} + TestObject test = doc.as(); + TRACE("testMsgpackDeserializeObject: test: " + test.toString()); + } + else { + TRACE("testMsgpackDeserializeObject: failed to deserialize"); + assert(false); + } + //assert(RNS::Utilities::OS::remove_file(test_object_path)); + } + else { + TRACE("testMsgpackDeserializeObject: read failed"); + assert(false); + } + +} + +void testMsgpackSerializeArray() { + + // NOTE: Following is creating a msgpack that appears in Python like: + + double time = 123.456; + // CBA Need this version writing byte-arrays to match the python version also writing byte-arrays (27 bytes) + const RNS::Bytes one("first\xab"); + const RNS::Bytes two("second\xcd"); + //MsgPack::bin_t one("first\xab"); + //MsgPack::bin_t two("second\xcd"); + //TRACEF("testMsgpackSerializeArray: time=%f one=%s two=%s", time, one.toString().c_str(), two.toString().c_str()); + // CBA This version writing strings exactly matches the python version also writing strings (23 bytes) + //const std::string one("first"); + //const std::string two("second"); + //TRACEF("testMsgpackSerializeArray: time=%f one=%s two=%s", time, one.c_str(), two.c_str()); + + MsgPack::Packer packer; + //packer.packArraySize(3); + //packer.pack(time); + //packer.pack(one); + //packer.pack(two); + packer.to_array(time, one, two); + //packer.to_array(time, one.collection(), two.collection()); + RNS::Bytes data(packer.data(), packer.size()); + + TRACE("testMsgpackSerializeArray: serialized " + std::to_string(data.size()) + " bytes"); + if (packer.size() > 0) { + if (RNS::Utilities::OS::write_file(test_array_path, data) == data.size()) { + TRACE("testMsgpackSerializeArray: wrote: " + std::to_string(data.size()) + " bytes"); + } + else { + TRACE("testMsgpackSerializeArray: write failed"); + assert(false); + } + } + else { + TRACE("testMsgpackSerializeArray: failed to serialize"); + assert(false); + } + +} + +void testMsgpackDeserializeArray() { + + StaticJsonDocument<1024> doc; + + RNS::Bytes data; + if (RNS::Utilities::OS::read_file(test_array_path, data) > 0) { + TRACE("testMsgpackDeserializeArray: read: " + std::to_string(data.size()) + " bytes"); + //TRACE("data: " + data.toString()); + MsgPack::Unpacker unpacker; + unpacker.feed(data.data(), data.size()); + double time; + // CBA NOTE: Can't currently deserialize directly into Bytes + //RNS::Bytes one; + //RNS::Bytes two; + //unpacker.from_array(time, one, two); + MsgPack::bin_t bin_one; + MsgPack::bin_t bin_two; + unpacker.from_array(time, bin_one, bin_two); + RNS::Bytes one(bin_one); + RNS::Bytes two(bin_two); + TRACEF("testMsgpackDeserializeArray: time=%f one=%s two=%s", time, one.toString().c_str(), two.toString().c_str()); + //TRACEF("testMsgpackDeserializeArray: time=%f one=%s two=%s", time, one.c_str(), two.c_str()); + //assert(RNS::Utilities::OS::remove_file(test_array_path)); + assert(one == "first\xab"); + assert(two == "second\xcd"); + } + else { + TRACE("testMsgpackDeserializeArray: read failed"); + assert(false); + } + +} + +void testMsgpackSerializeSeries() { + + // NOTE: Following is creating a msgpack that appears in Python like: + + double time = 123.456; + // CBA Need this version writing byte-arrays to match the python version also writing byte-arrays (27 bytes) + //const RNS::Bytes one("first\xab"); + //const RNS::Bytes two("second\xcd"); + //MsgPack::bin_t one("first\xab"); + //MsgPack::bin_t two("second\xcd"); + //TRACEF("testMsgpackSerializeSeries: time=%f one=%s two=%s", time, one.toString().c_str(), two.toString().c_str()); + // CBA This version writing strings exactly matches the python version also writing strings (23 bytes) + const std::string one("first"); + const std::string two("second"); + //TRACEF("testMsgpackSerializeSeries: time=%f one=%s two=%s", time, one.c_str(), two.c_str()); + + MsgPack::Packer packer; + packer.serialize(time, one, two); + //packer.serialize(time, one.collection(), two.collection()); + RNS::Bytes data(packer.data(), packer.size()); + + TRACE("testMsgpackSerializeSeries: serialized " + std::to_string(data.size()) + " bytes"); + if (packer.size() > 0) { + if (RNS::Utilities::OS::write_file(test_series_path, data) == data.size()) { + TRACE("testMsgpackSerializeSeries: wrote: " + std::to_string(data.size()) + " bytes"); + } + else { + TRACE("testMsgpackSerializeSeries: write failed"); + assert(false); + } + } + else { + TRACE("testMsgpackSerializeSeries: failed to serialize"); + assert(false); + } + +} + +void testMsgpackDeserializeSeries() { + + StaticJsonDocument<1024> doc; + + RNS::Bytes data; + if (RNS::Utilities::OS::read_file(test_series_path, data) > 0) { + TRACE("testMsgpackDeserializeSeries: read: " + std::to_string(data.size()) + " bytes"); + //TRACE("data: " + data.toString()); + MsgPack::Unpacker unpacker; + unpacker.feed(data.data(), data.size()); + double time; + MsgPack::bin_t bin_one; + MsgPack::bin_t bin_two; + unpacker.deserialize(time, bin_one, bin_two); + RNS::Bytes one(bin_one); + RNS::Bytes two(bin_two); + TRACEF("testMsgpackDeserializeSeries: time=%f one=%s two=%s", time, one.toString().c_str(), two.toString().c_str()); + //TRACEF("testMsgpackDeserializeSeries: time=%f one=%s two=%s", time, one.c_str(), two.c_str()); + //assert(RNS::Utilities::OS::remove_file(test_series_path)); + assert(one == "first\xab"); + assert(two == "second\xcd"); + } + else { + TRACE("testMsgpackDeserializeSeries: read failed"); + assert(false); + } + +} + + void testPersistence() { HEAD("Running testPersistence...", RNS::LOG_TRACE); @@ -803,16 +1186,34 @@ void testPersistence() { testDeserializeMap(); */ +/* testSerializeTimeOffset(); testSerializeDestinationTable(); testDeserializeDestinationTable(); - // CBA Following not currently working on native + // CBA Following not currently working on native due to incomplete streaming implementation +#ifdef ARDUINO testPersistenceSerializeDestinationTable(); +#endif - // CBA Following not currently working on native + // CBA Following not currently working on native due to incomplete streaming implementation +#ifdef ARDUINO testPersistenceDeserializeDestinationTable(); +#endif +*/ + + //testJsonMsgpackSerializeObject(); + //testJsonMsgpackDeserializeObject(); + //testJsonMsgpackSerializeArray(); + //testJsonMsgpackDeserializeArray(); + + //testMsgpackSerializeObject(); + //testMsgpackDeserializeObject(); + testMsgpackSerializeArray(); + testMsgpackDeserializeArray(); + //testMsgpackSerializeSeries(); + //testMsgpackDeserializeSeries(); RNS::Utilities::OS::deregister_filesystem(); diff --git a/examples/unit_tests/TestReticulum.cpp b/examples/unit_tests/TestReticulum.cpp index 0b765de..a46286e 100644 --- a/examples/unit_tests/TestReticulum.cpp +++ b/examples/unit_tests/TestReticulum.cpp @@ -1,11 +1,15 @@ //#include -#include "Reticulum.h" -#include "Transport.h" -#include "Log.h" +#include "FileSystem.h" + +#include +#include +#include #include +RNS::FileSystem reticulum_filesystem(RNS::Type::NONE); + class InInterface : public RNS::InterfaceImpl { public: InInterface(const char *name = "InInterface") : RNS::InterfaceImpl(name) { @@ -15,9 +19,16 @@ public: virtual ~InInterface() { _name = "(deleted)"; } - virtual void handle_incoming(const RNS::Bytes &data) { + // Incoming interface only, send_outgoing not currently implemented + virtual void send_outgoing(const RNS::Bytes &data) {} + // Incoming shoujld be handled automatically by InterfaceImpl::handle_incoming called via Interface::handle_incoming from OutInterface +/* + void on_incoming(const RNS::Bytes &data) { HEAD("InInterface.handle_incoming: data: " + data.toHex(), RNS::LOG_TRACE); + // Pass received data on to transport + InterfaceImpl::handle_incoming(data); } +*/ }; class OutInterface : public RNS::InterfaceImpl { @@ -31,8 +42,12 @@ public: } virtual void send_outgoing(const RNS::Bytes &data) { HEAD("OutInterface.send_outgoing: data: " + data.toHex(), RNS::LOG_TRACE); + + // Loop data back to InInterface for testing _in_interface.handle_incoming(data); - InterfaceImpl::send_outgoing(data); + + // Perform post-send housekeeping + InterfaceImpl::handle_outgoing(data); } private: RNS::Interface& _in_interface; @@ -62,6 +77,7 @@ public: RNS::HAnnounceHandler announce_handler(new ExampleAnnounceHandler()); // Test packet receive callback +//void(*)(const Bytes& data, const Packet& packet) void onPacket(const RNS::Bytes& data, const RNS::Packet& packet) { INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); INFO("onPacket: data: " + data.toHex()); @@ -71,6 +87,7 @@ void onPacket(const RNS::Bytes& data, const RNS::Packet& packet) { } // Ping packet receive callback +//void(*)(const Bytes& data, const Packet& packet) void onPingPacket(const RNS::Bytes& data, const RNS::Packet& packet) { INFO("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); INFO("onPingPacket: data: " + data.toHex()); @@ -89,6 +106,11 @@ RNS::Interface out_interface(new OutInterface(in_interface)); void testReticulum() { HEAD("Running testReticulum...", RNS::LOG_TRACE); + HEAD("Registering Filesystem with OS...", RNS::LOG_TRACE); + reticulum_filesystem = new FileSystem(); + ((FileSystem*)reticulum_filesystem.get())->init(); + RNS::Utilities::OS::register_filesystem(reticulum_filesystem); + HEAD("Registering Interface instances with Transport...", RNS::LOG_TRACE); RNS::Transport::register_interface(in_interface); RNS::Transport::register_interface(out_interface); diff --git a/examples/unit_tests/cache/40fe4ab8105b591cca1ef159d476a7b440fe4ab8105b591cca1ef159d476a7b4 b/examples/unit_tests/cache/40fe4ab8105b591cca1ef159d476a7b440fe4ab8105b591cca1ef159d476a7b4 new file mode 100644 index 0000000..30d74d2 --- /dev/null +++ b/examples/unit_tests/cache/40fe4ab8105b591cca1ef159d476a7b440fe4ab8105b591cca1ef159d476a7b4 @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/examples/unit_tests/cache/426f66f9aadf866933358b71295f59d0426f66f9aadf866933358b71295f59d0 b/examples/unit_tests/cache/426f66f9aadf866933358b71295f59d0426f66f9aadf866933358b71295f59d0 new file mode 100644 index 0000000..30d74d2 --- /dev/null +++ b/examples/unit_tests/cache/426f66f9aadf866933358b71295f59d0426f66f9aadf866933358b71295f59d0 @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/examples/unit_tests/cache/45c50662af11f1b26889efaab547942b45c50662af11f1b26889efaab547942b b/examples/unit_tests/cache/45c50662af11f1b26889efaab547942b45c50662af11f1b26889efaab547942b new file mode 100644 index 0000000..30d74d2 --- /dev/null +++ b/examples/unit_tests/cache/45c50662af11f1b26889efaab547942b45c50662af11f1b26889efaab547942b @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/examples/unit_tests/cache/c755609f4d0ab75b5119905a032eeb33c755609f4d0ab75b5119905a032eeb33 b/examples/unit_tests/cache/c755609f4d0ab75b5119905a032eeb33c755609f4d0ab75b5119905a032eeb33 new file mode 100644 index 0000000..30d74d2 --- /dev/null +++ b/examples/unit_tests/cache/c755609f4d0ab75b5119905a032eeb33c755609f4d0ab75b5119905a032eeb33 @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/examples/unit_tests/cache/test b/examples/unit_tests/cache/test new file mode 100644 index 0000000..30d74d2 --- /dev/null +++ b/examples/unit_tests/cache/test @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/examples/unit_tests/main.cpp b/examples/unit_tests/main.cpp index 942af43..4de3396 100644 --- a/examples/unit_tests/main.cpp +++ b/examples/unit_tests/main.cpp @@ -39,9 +39,12 @@ void setup() { TRACE("Running tests..."); RNS::LogLevel loglevel = RNS::loglevel(); +#if defined(MEM_LOG) + RNS::loglevel(RNS::LOG_MEM); +#else //RNS::loglevel(RNS::LOG_WARNING); RNS::loglevel(RNS::LOG_TRACE); - //RNS::loglevel(RNS::LOG_MEM); +#endif //UNITY_BEGIN(); @@ -56,9 +59,10 @@ void setup() { //testReference(); //testCrypto(); //testBytes(); - testFileSystem(); + //testFileSystem(); //testPersistence(); - //testReticulum(); + testReticulum(); + //testObjects(); HEAD("All tests successful!", RNS::LOG_TRACE); diff --git a/examples/unit_tests/platformio.ini b/examples/unit_tests/platformio.ini index f66174b..7dcae5a 100644 --- a/examples/unit_tests/platformio.ini +++ b/examples/unit_tests/platformio.ini @@ -22,7 +22,13 @@ build_type = debug build_flags = -DRNS_USE_ALLOCATOR=1 -DRNS_USE_TLSF=1 + ;-DMEM_LOG + -DTEST_OBJECT_IMPL lib_deps = + ArduinoJson@^6.21.3 + https://github.com/attermann/Crypto.git + https://github.com/hideakitai/MsgPack.git + microReticulum=symlink://../.. [env:native] platform = native @@ -41,9 +47,6 @@ build_flags = -DNATIVE lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. lib_extra_dirs = ../ lib_compat_mode = off ;debug_init_break = @@ -67,9 +70,6 @@ build_flags = -DNATIVE lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. lib_extra_dirs = ../ lib_compat_mode = off @@ -89,9 +89,6 @@ build_flags = -DCUBECELL lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. ; CBA NOTE must undef min and max from Arduino.h [env:heltec-tracker] @@ -113,9 +110,6 @@ build_flags = lib_deps = ${env.lib_deps} lovyan03/LovyanGFX@^1.1.8 - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. [env:ttgo-lora32-v21] framework = arduino @@ -133,9 +127,6 @@ build_flags = -DBOARD_ESP32 lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. monitor_filters = esp32_exception_decoder [env:ttgo-t-beam] @@ -154,9 +145,6 @@ build_flags = -DBOARD_ESP32 lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. monitor_filters = esp32_exception_decoder [env:wiscore_rak4631] @@ -178,9 +166,6 @@ build_flags = build_unflags = -fno-exceptions lib_deps = ${env.lib_deps} - ArduinoJson@^6.21.3 - https://github.com/attermann/arduinolibs.git - microReticulum=symlink://../.. [env:nrf52840_dk_adafruit] framework = arduino @@ -201,4 +186,3 @@ build_flags = ${env.build_flags} lib_deps = ${env.lib_deps} - diff --git a/examples/unit_tests/test_array b/examples/unit_tests/test_array new file mode 100644 index 0000000..301ee3f --- /dev/null +++ b/examples/unit_tests/test_array @@ -0,0 +1 @@ +“Ë@^Ý/Ÿ¾wÄfirst«ÄsecondÍ \ No newline at end of file diff --git a/examples/unit_tests/test_array_2 b/examples/unit_tests/test_array_2 new file mode 100644 index 0000000..906d092 --- /dev/null +++ b/examples/unit_tests/test_array_2 @@ -0,0 +1 @@ +“Ë@^Ý/Ÿ¾w–firstÌÿ—secondÌÿ \ No newline at end of file diff --git a/examples/unit_tests/test_array_python b/examples/unit_tests/test_array_python new file mode 100644 index 0000000..301ee3f --- /dev/null +++ b/examples/unit_tests/test_array_python @@ -0,0 +1 @@ +“Ë@^Ý/Ÿ¾wÄfirst«ÄsecondÍ \ No newline at end of file diff --git a/examples/unit_tests/test_destination_table b/examples/unit_tests/test_destination_table index ac5809e..627e1e8 100644 --- a/examples/unit_tests/test_destination_table +++ b/examples/unit_tests/test_destination_table @@ -1 +1 @@ -{"1111111111111111":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"2222222222222222":{"timestamp":2,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303031":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303032":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303033":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303034":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303035":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303036":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303037":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303038":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303039":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303130":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303131":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303132":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303133":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303134":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303135":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303136":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303137":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303138":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303139":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303230":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},} \ No newline at end of file +{"1111111111111111":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"2222222222222222":{"timestamp":2,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303031":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303032":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303033":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303034":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303035":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303036":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303037":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303038":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303039":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303130":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303131":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303132":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303133":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303134":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303135":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303136":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303137":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303138":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303139":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""},"31303030303030303030303030303230":{"timestamp":1,"received_from":"deadbeef","announce_hops":0,"expires":0,"random_blobs":["b10bb10b","deadbeef"],"interface_hash":"","packet_hash":""}} \ No newline at end of file diff --git a/examples/unit_tests/test_object b/examples/unit_tests/test_object index 6204578..be461be 100644 --- a/examples/unit_tests/test_object +++ b/examples/unit_tests/test_object @@ -1 +1 @@ -{"str":"test","vec":["one","two"]} \ No newline at end of file +‚£str¤test£vec’£one£two \ No newline at end of file diff --git a/examples/unit_tests/transport_identity b/examples/unit_tests/transport_identity new file mode 100644 index 0000000..41bb523 Binary files /dev/null and b/examples/unit_tests/transport_identity differ diff --git a/platformio.ini b/platformio.ini index c57e871..cef6559 100644 --- a/platformio.ini +++ b/platformio.ini @@ -27,6 +27,7 @@ build_flags = lib_deps = ArduinoJson@^6.21.3 https://github.com/attermann/Crypto.git + https://github.com/hideakitai/MsgPack.git [env:native] platform = native diff --git a/src/Bytes.cpp b/src/Bytes.cpp index e889d9f..0d1e001 100644 --- a/src/Bytes.cpp +++ b/src/Bytes.cpp @@ -6,29 +6,29 @@ using namespace RNS; // - If capacity is specified (>0) then create empty shared data with initial reserved capacity // - If capacity is not specified (<=0) then create empty shared data with no initial capacity void Bytes::newData(size_t capacity /*= 0*/) { - MEMF("Bytes is creating own data with capacity %u", capacity); -MEM("newData: Creating new data..."); +//MEMF("Bytes is creating own data with capacity %u", capacity); +//MEM("newData: Creating new data..."); Data* data = new Data(); if (data == nullptr) { ERROR("Bytes failed to allocate empty data buffer"); throw std::runtime_error("Failed to allocate empty data buffer"); } -MEM("newData: Created new data"); +//MEM("newData: Created new data"); if (capacity > 0) { -MEM("newData: Reserving data capacity..."); +//MEMF("newData: Reserving data capacity of %u...", capacity); data->reserve(capacity); -MEM("newData: Reserved data capacity"); +//MEM("newData: Reserved data capacity"); } -MEM("newData: Assigning data to shared data pointer..."); +//MEM("newData: Assigning data to shared data pointer..."); _data = SharedData(data); -MEM("newData: Assigned data to shared data pointer"); +//MEM("newData: Assigned data to shared data pointer"); _exclusive = true; } // Ensures that instance has exclusive shared data // - If instance has no shared data then create new shared data // - If instance does not have exclusive on shared data that is not empty then make a copy of shared data (if requests) and reserve capacity (if requested) -// - If instance does not have exclusive on shared data that is empty then then create new shared data +// - If instance does not have exclusive on shared data that is empty then create new shared data // - If instance already has exclusive on shared data then do nothing except reserve capacity (if requested) void Bytes::exclusiveData(bool copy /*= true*/, size_t capacity /*= 0*/) { if (!_data) { @@ -38,32 +38,32 @@ void Bytes::exclusiveData(bool copy /*= true*/, size_t capacity /*= 0*/) { if (copy && !_data->empty()) { //TRACE("Bytes is creating a writable copy of its shared data"); //Data* data = new Data(*_data.get()); -MEM("exclusiveData: Creating new data..."); +//MEM("exclusiveData: Creating new data..."); Data* data = new Data(); if (data == nullptr) { ERROR("Bytes failed to duplicate data buffer"); throw std::runtime_error("Failed to duplicate data buffer"); } -MEM("exclusiveData: Created new data"); +//MEM("exclusiveData: Created new data"); if (capacity > 0) { -MEM("exclusiveData: Reserving data capacity..."); +//MEMF("exclusiveData: Reserving data capacity of %u...", capacity); // if requested capacity < existing size then reserve capacity for existing size instead data->reserve((capacity > _data->size()) ? capacity : _data->size()); -MEM("exclusiveData: Reserved data capacity"); +//MEM("exclusiveData: Reserved data capacity"); } else { data->reserve(_data->size()); } -MEM("exclusiveData: Copying existing data..."); +//MEM("exclusiveData: Copying existing data..."); data->insert(data->begin(), _data->begin(), _data->end()); -MEM("exclusiveData: Copied existing data"); -MEM("exclusiveData: Assigning data to shared data pointer..."); +//MEM("exclusiveData: Copied existing data"); +//MEM("exclusiveData: Assigning data to shared data pointer..."); _data = SharedData(data); -MEM("exclusiveData: Assigned data to shared data pointer"); +//MEM("exclusiveData: Assigned data to shared data pointer"); _exclusive = true; } else { - //MEM("Bytes is creating its own data because shared is empty"); +//MEM("Bytes is creating its own data because shared is empty"); //data = new Data(); //if (data == nullptr) { // ERROR("Bytes failed to allocate empty data buffer"); @@ -71,9 +71,9 @@ MEM("exclusiveData: Assigned data to shared data pointer"); //} //_data = SharedData(data); //_exclusive = true; -MEM("exclusiveData: Creating new empty data..."); +//MEM("exclusiveData: Creating new empty data..."); newData(capacity); -MEM("exclusiveData: Created new empty data"); +//MEM("exclusiveData: Created new empty data"); } } else if (capacity > 0 && capacity > size()) { diff --git a/src/Bytes.h b/src/Bytes.h index a52d18a..0060917 100644 --- a/src/Bytes.h +++ b/src/Bytes.h @@ -31,16 +31,28 @@ namespace RNS { public: Bytes() { - MEMF("Bytes object created from defaul, this: %lu, data: %lu", this, _data.get()); + MEMF("Bytes object created from default, this: %lu, data: %lu", this, _data.get()); } Bytes(const NoneConstructor none) { MEMF("Bytes object created from NONE, this: %lu, data: %lu", this, _data.get()); } Bytes(const Bytes& bytes) { - MEM("Bytes is using shared data"); +//MEM("Bytes is using shared data"); assign(bytes); MEMF("Bytes object copy created from bytes \"%s\", this: %lu, data: %lu", toString().c_str(), this, _data.get()); } + // Construct from std::vector + Bytes(const Data& data) { +MEM("Creating from data-copy..."); + assign(data); + MEMF("Bytes object created from data-copy \"%s\", this: %lu, data: %lu", toString().c_str(), this, _data.get()); + } + // Construct from rvalue std::vector (move) + Bytes(Data&& rdata) { +MEM("Creating from data-move..."); + assign(std::move(rdata)); + MEMF("Bytes object created from data-move \"%s\", this: %lu, data: %lu", toString().c_str(), this, _data.get()); + } Bytes(const uint8_t* chunk, size_t size) { assign(chunk, size); MEMF("Bytes object created from chunk \"%s\", this: %lu, data: %lu", toString().c_str(), this, _data.get()); @@ -70,6 +82,24 @@ namespace RNS { return *this; } + // CBA TODO Resolve ambiguity in JsonVariantConst assignments before enabling the following +/* + // Assignment from std::vector + inline const Bytes& operator = (const Data& data) { + assign(data); + return *this; + } + // Move assignment from std::vector + inline const Bytes& operator = (Data&& rdata) { + assign(std::move(rdata)); + return *this; + } +*/ + inline const Bytes& operator += (const Data& data) { + append(data); + return *this; + } + inline Bytes operator + (const Bytes& bytes) const { Bytes newbytes(*this); newbytes.append(bytes); @@ -87,13 +117,19 @@ namespace RNS { inline bool operator > (const Bytes& bytes) const { return compare(bytes) > 0; } + inline operator bool() const { return (_data && !_data->empty()); } + inline operator Data() const { + if (!_data) + return Data(); + return *_data.get(); + } private: inline SharedData shareData() const { - MEM("Bytes is sharing its own data"); +//MEM("Bytes is sharing its own data"); _exclusive = false; return _data; } @@ -118,9 +154,32 @@ namespace RNS { return; } exclusiveData(false, bytes._data->size()); - _data->insert(_data->begin(), bytes._data->begin(), bytes._data->end()); + //_data->insert(_data->begin(), bytes._data->begin(), bytes._data->end()); + //_data->assign(bytes._data->begin(), bytes._data->end()); + *_data = bytes._data; #endif } + inline void assign(const Data& data) { + // if assignment is empty then clear data and don't bother creating new + if (data.size() <= 0) { + _data = nullptr; + _exclusive = true; + return; + } + exclusiveData(false, data.size()); + //_data->assign(data.begin(), data.end()); + *_data = data; + } + inline void assign(Data&& rdata) { + // if assignment is empty then clear data and don't bother creating new + if (rdata.size() <= 0) { + _data = nullptr; + _exclusive = true; + return; + } + exclusiveData(false); + *_data = std::move(rdata); + } inline void assign(const uint8_t* chunk, size_t chunk_size) { // if assignment is empty then clear data and don't bother creating new if (chunk == nullptr || chunk_size <= 0) { @@ -129,7 +188,8 @@ namespace RNS { return; } exclusiveData(false, chunk_size); - _data->insert(_data->begin(), chunk, chunk + chunk_size); + //_data->insert(_data->begin(), chunk, chunk + chunk_size); + _data->assign(chunk, chunk + chunk_size); } inline void assign(const char* string) { // if assignment is empty then clear data and don't bother creating new @@ -140,7 +200,8 @@ namespace RNS { } size_t string_size = strlen(string); exclusiveData(false, string_size); - _data->insert(_data->begin(), (uint8_t* )string, (uint8_t* )string + string_size); + //_data->insert(_data->begin(), (uint8_t* )string, (uint8_t* )string + string_size); + _data->assign((uint8_t* )string, (uint8_t* )string + string_size); } //inline void assign(const std::string& string) { assign(string.c_str()); } inline void assign(const std::string& string) { assign((uint8_t*)string.c_str(), string.length()); } @@ -155,6 +216,14 @@ namespace RNS { exclusiveData(true, size() + bytes.size()); _data->insert(_data->end(), bytes._data->begin(), bytes._data->end()); } + inline void append(const Data& data) { + // if append is empty then do nothing + if (data.size() <= 0) { + return; + } + exclusiveData(true, size() + data.size()); + _data->insert(_data->end(), data.begin(), data.end()); + } inline void append(const uint8_t* chunk, size_t chunk_size) { // if append is empty then do nothing if (chunk == nullptr || chunk_size <= 0) { @@ -221,6 +290,7 @@ namespace RNS { inline size_t capacity() const { if (!_data) return 0; return _data->capacity(); } inline void reserve(size_t capacity) const { if (!_data) return; _data->reserve(capacity); } inline const uint8_t* data() const { if (!_data) return nullptr; return _data->data(); } + inline const Data collection() const { if (!_data) return Data(); return *_data.get(); } inline std::string toString() const { if (!_data) return ""; return {(const char*)data(), size()}; } std::string toHex(bool upper = false) const; @@ -229,7 +299,7 @@ namespace RNS { inline Bytes left(size_t len) const { if (!_data) return NONE; if (len > size()) len = size(); return {data(), len}; } inline Bytes right(size_t len) const { if (!_data) return NONE; if (len > size()) len = size(); return {data() + (size() - len), len}; } inline int find(int pos, const char* str) { - if (!_data || _data->data() == nullptr || pos >= _data->size()) { + if (!_data || _data->data() == nullptr || (size_t)pos >= _data->size()) { return -1; } const char* ptr = strnstr((const char*)(_data->data() + pos), str, (_data->size() - pos)); @@ -283,23 +353,23 @@ namespace RNS { } inline RNS::Bytes& operator << (RNS::Bytes& lhbytes, const RNS::Bytes& rhbytes) { - MEM("Appending right-hand Bytes to left-hand Bytes"); +//MEM("Appending right-hand Bytes to left-hand Bytes"); lhbytes.append(rhbytes); - MEM("Returning left-hand Bytes"); +//MEM("Returning left-hand Bytes"); return lhbytes; } inline RNS::Bytes& operator << (RNS::Bytes& lhbytes, uint8_t rhbyte) { - MEM("Appending right-hand byte to left-hand Bytes"); +//MEM("Appending right-hand byte to left-hand Bytes"); lhbytes.append(rhbyte); - MEM("Returning left-hand Bytes"); +//MEM("Returning left-hand Bytes"); return lhbytes; } inline RNS::Bytes& operator << (RNS::Bytes& lhbytes, const char* rhstr) { - MEM("Appending right-hand str to left-hand Bytes"); +//MEM("Appending right-hand str to left-hand Bytes"); lhbytes.append(rhstr); - MEM("Returning left-hand Bytes"); +//MEM("Returning left-hand Bytes"); return lhbytes; } diff --git a/src/Channel.cpp b/src/Channel.cpp new file mode 100644 index 0000000..ba6e66c --- /dev/null +++ b/src/Channel.cpp @@ -0,0 +1,12 @@ +#include "Channel.h" + +#include "Reticulum.h" +#include "Transport.h" +#include "Packet.h" +#include "Log.h" + +#include + +using namespace RNS; +using namespace RNS::Type::Channel; +using namespace RNS::Utilities; diff --git a/src/Channel.h b/src/Channel.h new file mode 100644 index 0000000..4425be7 --- /dev/null +++ b/src/Channel.h @@ -0,0 +1,57 @@ +#pragma once + +#include "Destination.h" +#include "Type.h" + +#include +#include + +namespace RNS { + + class Channel { + + public: + Channel(Type::NoneConstructor none) { + MEM("Channel NONE object created"); + } + Channel(const Channel& resource) : _object(resource._object) { + MEM("Channel object copy created"); + } + virtual ~Channel(){ + MEM("Channel object destroyed"); + } + + Channel& operator = (const Channel& resource) { + _object = resource._object; + return *this; + } + operator bool() const { + return _object.get() != nullptr; + } + bool operator < (const Channel& resource) const { + return _object.get() < resource._object.get(); + //return _object->_hash < resource._object->_hash; + } + + public: + void _shutdown() {} + + private: + class Object { + public: + Object() { MEM("Channel::Data object created, this: " + std::to_string((uintptr_t)this)); } + virtual ~Object() { MEM("Channel::Data object destroyed, this: " + std::to_string((uintptr_t)this)); } + private: + + friend class Channel; + }; + std::shared_ptr _object; + + }; + + + class ChannelAdvertisement { + + }; + +} diff --git a/src/Cryptography/Ed25519.h b/src/Cryptography/Ed25519.h index fb50853..69cb396 100644 --- a/src/Cryptography/Ed25519.h +++ b/src/Cryptography/Ed25519.h @@ -16,14 +16,15 @@ namespace RNS { namespace Cryptography { class Ed25519PublicKey { + public: + using Ptr = std::shared_ptr; + public: Ed25519PublicKey(const Bytes& publicKey) { _publicKey = publicKey; } ~Ed25519PublicKey() {} - using Ptr = std::shared_ptr; - public: // creates a new instance with specified seed static inline Ptr from_public_bytes(const Bytes& publicKey) { @@ -45,6 +46,9 @@ namespace RNS { namespace Cryptography { class Ed25519PrivateKey { + public: + using Ptr = std::shared_ptr; + public: Ed25519PrivateKey(const Bytes& privateKey) { if (privateKey) { @@ -60,8 +64,6 @@ namespace RNS { namespace Cryptography { } ~Ed25519PrivateKey() {} - using Ptr = std::shared_ptr; - public: // creates a new instance with a random seed static inline Ptr generate() { diff --git a/src/Cryptography/Fernet.h b/src/Cryptography/Fernet.h index cdd8ab7..c348d58 100644 --- a/src/Cryptography/Fernet.h +++ b/src/Cryptography/Fernet.h @@ -21,6 +21,8 @@ namespace RNS { namespace Cryptography { public: static const uint8_t FERNET_OVERHEAD = 48; // Bytes + using Ptr = std::shared_ptr; + public: static inline const Bytes generate_key() { return random(32); } diff --git a/src/Cryptography/X25519.h b/src/Cryptography/X25519.h index f6ae92d..75c009b 100644 --- a/src/Cryptography/X25519.h +++ b/src/Cryptography/X25519.h @@ -13,6 +13,9 @@ namespace RNS { namespace Cryptography { class X25519PublicKey { + public: + using Ptr = std::shared_ptr; + public: /* X25519PublicKey(const Bytes& x) { @@ -24,8 +27,6 @@ namespace RNS { namespace Cryptography { } ~X25519PublicKey() {} - using Ptr = std::shared_ptr; - public: // creates a new instance with specified seed /* @@ -62,6 +63,8 @@ namespace RNS { namespace Cryptography { //z T_CLEAR = None const uint8_t T_MAX = 0; + using Ptr = std::shared_ptr; + public: /* X25519PrivateKey(const Bytes& a) { @@ -87,8 +90,6 @@ namespace RNS { namespace Cryptography { } ~X25519PrivateKey() {} - using Ptr = std::shared_ptr; - public: // creates a new instance with a random seed /* diff --git a/src/Destination.cpp b/src/Destination.cpp index b6a1982..0ea1bc4 100644 --- a/src/Destination.cpp +++ b/src/Destination.cpp @@ -473,3 +473,13 @@ Signs information for ``RNS.Destination.SINGLE`` type destination. } return {Bytes::NONE}; } + +bool Destination::has_link(const Link& link) { + assert(_object); + return (_object->_links.count(link) > 0); +} + +void Destination::remove_link(const Link& link) { + assert(_object); + _object->_links.erase(link); +} diff --git a/src/Destination.h b/src/Destination.h index 1459ae1..e05030c 100644 --- a/src/Destination.h +++ b/src/Destination.h @@ -12,6 +12,7 @@ #include #include #include +#include #include #include @@ -21,6 +22,23 @@ namespace RNS { class Link; class Packet; + class RequestHandler { + public: + //p response_generator(path, data, request_id, link_id, remote_identity, requested_at) + using response_generator = Bytes(*)(const Bytes& path, const Bytes& data, const Bytes& request_id, const Bytes& link_id, const Identity& remote_identity, double requested_at); + public: + RequestHandler(const RequestHandler& handler) { + _path = handler._path; + _response_generator = handler._response_generator; + _allow = handler._allow; + _allowed_list = handler._allowed_list; + } + Bytes _path; + response_generator _response_generator = nullptr; + Type::Destination::request_policies _allow = Type::Destination::ALLOW_NONE; + std::set _allowed_list; + }; + /** * @brief A class used to describe endpoints in a Reticulum Network. Destination * instances are used both to create outgoing and incoming endpoints. The @@ -160,22 +178,34 @@ namespace RNS { virtual const Bytes decrypt(const Bytes& data); virtual const Bytes sign(const Bytes& message); - // getters/setters + // CBA + bool has_link(const Link& link); + void remove_link(const Link& link); + + inline std::string toString() const { if (!_object) return ""; return "{Destination:" + _object->_hash.toHex() + "}"; } + + // getters inline Type::Destination::types type() const { assert(_object); return _object->_type; } inline Type::Destination::directions direction() const { assert(_object); return _object->_direction; } inline Type::Destination::proof_strategies proof_strategy() const { assert(_object); return _object->_proof_strategy; } inline const Bytes& hash() const { assert(_object); return _object->_hash; } - // CBA Don't allow changing destination after construction since it's used as key in collections - //inline void hash(const Bytes& hash) { assert(_object); _object->_hash = hash; _object->_hexhash = _object->_hash.toHex(); } inline const Bytes& link_id() const { assert(_object); return _object->_link_id; } inline uint16_t mtu() const { assert(_object); return _object->_mtu; } - inline void mtu(uint16_t mtu) { assert(_object); _object->_mtu = mtu; } 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 const std::map& path_responses() const { assert(_object); return _object->_path_responses; } + inline const std::map& request_handlers() const { assert(_object); return _object->_request_handlers; } - inline std::string toString() const { if (!_object) return ""; return "{Destination:" + _object->_hash.toHex() + "}"; } + // setters + // CBA Don't allow changing destination after construction since it's used as key in collections + //inline void hash(const Bytes& hash) { assert(_object); _object->_hash = hash; _object->_hexhash = _object->_hash.toHex(); } + inline void type(Type::Destination::types type) { assert(_object); _object->_type = type; } + inline void link_id(const Bytes& id) { assert(_object); _object->_link_id = id; } + inline void mtu(uint16_t mtu) { assert(_object); _object->_mtu = mtu; } + inline void last_outbound(double time) { assert(_object); _object->_last_outbound = time; } + inline void increment_tx() { assert(_object); ++_object->_tx; } + inline void increment_txbytes(uint16_t bytes) { assert(_object); _object->_txbytes += bytes; } private: class Object { @@ -185,14 +215,14 @@ namespace RNS { private: bool _accept_link_requests = true; Callbacks _callbacks; - //z _request_handlers = {} + std::map _request_handlers; Type::Destination::types _type; Type::Destination::directions _direction; Type::Destination::proof_strategies _proof_strategy = Type::Destination::PROVE_NONE; uint16_t _mtu = 0; std::map _path_responses; - //z _links = [] + std::set _links; Identity _identity; std::string _name; @@ -213,6 +243,10 @@ namespace RNS { Type::Link::status _status; + double _last_outbound = 0.0; + uint16_t _tx = 0; + uint32_t _txbytes = 0; + friend class Destination; }; std::shared_ptr _object; diff --git a/src/FileStream.h b/src/FileStream.h index 58ff406..8b12c30 100644 --- a/src/FileStream.h +++ b/src/FileStream.h @@ -55,47 +55,47 @@ namespace RNS { public: FileStream(Type::NoneConstructor none) { - MEMF("FileStream object NONE created, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object NONE created, this: 0x%X, impl: 0x%X", this, _impl.get()); } FileStream(const FileStream& obj) : _impl(obj._impl), _crc(obj._crc) { - MEMF("FileStream object copy created, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object copy created, this: 0x%X, impl: 0x%X", this, _impl.get()); } FileStream(FileStreamImpl* impl) : _impl(impl) { - MEMF("FileStream object impl created, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object impl created, this: 0x%X, impl: 0x%X", this, _impl.get()); } virtual ~FileStream() { - MEMF("FileStream object destroyed, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object destroyed, this: 0x%X, impl: 0x%X", this, _impl.get()); } inline virtual FileStream& operator = (const FileStream& obj) { _impl = obj._impl; _crc = obj._crc; - MEMF("FileStream object copy created by assignment, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object copy created by assignment, this: 0x%X, impl: 0x%X", this, _impl.get()); return *this; } inline FileStream& operator = (FileStreamImpl* impl) { _impl.reset(impl); - MEMF("FileStream object copy created by impl assignment, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object copy created by impl assignment, this: 0x%X, impl: 0x%X", this, _impl.get()); return *this; } inline operator bool() const { - MEMF("FileStream object bool, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object bool, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() != nullptr; } inline bool operator < (const FileStream& obj) const { - MEMF("FileStream object <, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object <, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() < obj._impl.get(); } inline bool operator > (const FileStream& obj) const { - MEMF("FileStream object <, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object <, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() > obj._impl.get(); } inline bool operator == (const FileStream& obj) const { - MEMF("FileStream object ==, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object ==, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() == obj._impl.get(); } inline bool operator != (const FileStream& obj) const { - MEMF("FileStream object !=, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileStream object !=, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() != obj._impl.get(); } inline FileStreamImpl* get() { diff --git a/src/FileSystem.h b/src/FileSystem.h index 951ac6b..2ab253a 100644 --- a/src/FileSystem.h +++ b/src/FileSystem.h @@ -40,46 +40,46 @@ namespace RNS { public: FileSystem(Type::NoneConstructor none) { - MEMF("FileSystem object NONE created, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object NONE created, this: 0x%X, impl: 0x%X", this, _impl.get()); } FileSystem(const FileSystem& obj) : _impl(obj._impl) { - MEMF("FileSystem object copy created, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object copy created, this: 0x%X, impl: 0x%X", this, _impl.get()); } FileSystem(FileSystemImpl* impl) : _impl(impl) { - MEMF("FileSystem object impl created, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object impl created, this: 0x%X, impl: 0x%X", this, _impl.get()); } virtual ~FileSystem() { - MEMF("FileSystem object destroyed, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object destroyed, this: 0x%X, impl: 0x%X", this, _impl.get()); } inline FileSystem& operator = (const FileSystem& obj) { _impl = obj._impl; - MEMF("FileSystem object copy created by assignment, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object copy created by assignment, this: 0x%X, impl: 0x%X", this, _impl.get()); return *this; } inline FileSystem& operator = (FileSystemImpl* impl) { _impl.reset(impl); - MEMF("FileSystem object copy created by impl assignment, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object copy created by impl assignment, this: 0x%X, impl: 0x%X", this, _impl.get()); return *this; } inline operator bool() const { - MEMF("FileSystem object bool, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object bool, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() != nullptr; } inline bool operator < (const FileSystem& obj) const { - MEMF("FileSystem object <, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object <, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() < obj._impl.get(); } inline bool operator > (const FileSystem& obj) const { - MEMF("FileSystem object <, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object <, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() > obj._impl.get(); } inline bool operator == (const FileSystem& obj) const { - MEMF("FileSystem object ==, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object ==, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() == obj._impl.get(); } inline bool operator != (const FileSystem& obj) const { - MEMF("FileSystem object !=, this: 0x%X, data: 0x%X", this, _impl.get()); + MEMF("FileSystem object !=, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() != obj._impl.get(); } inline FileSystemImpl* get() { diff --git a/src/Identity.h b/src/Identity.h index 13245ed..259d37b 100644 --- a/src/Identity.h +++ b/src/Identity.h @@ -95,7 +95,7 @@ namespace RNS { bool load(const char* path); bool to_file(const char* path); - inline const Bytes get_salt() const { assert(_object); return _object->_hash; } + inline const Bytes& get_salt() const { assert(_object); return _object->_hash; } inline const Bytes get_context() const { return {Bytes::NONE}; } const Bytes encrypt(const Bytes& plaintext) const; diff --git a/src/Interface.cpp b/src/Interface.cpp index acb72b7..18bde30 100644 --- a/src/Interface.cpp +++ b/src/Interface.cpp @@ -8,23 +8,33 @@ using namespace RNS::Type::Interface; /*static*/ uint8_t Interface::DISCOVER_PATHS_FOR = MODE_ACCESS_POINT | MODE_GATEWAY; -/*virtual*/ void InterfaceImpl::send_outgoing(const Bytes& data) { - //TRACE("InterfaceImpl.send_outgoing: data: " + data.toHex()); - TRACE("InterfaceImpl.send_outgoing"); +void InterfaceImpl::handle_outgoing(const Bytes& data) { + //TRACE("InterfaceImpl.handle_outgoing: data: " + data.toHex()); + TRACE("InterfaceImpl.handle_outgoing"); _txb += data.size(); } -/*virtual*/ //void InterfaceImpl::handle_incoming(const Bytes& data) { +void InterfaceImpl::handle_incoming(const Bytes& data) { + //TRACE("InterfaceImpl.handle_incoming: data: " + data.toHex()); + TRACE("InterfaceImpl.handle_incoming"); + _rxb += data.size(); + // Create temporary Interface encapsulating our own shared impl + std::shared_ptr self = shared_from_this(); + Interface interface(self); + // Pass data on to transport for handling + Transport::inbound(data, interface); +} + void Interface::handle_incoming(const Bytes& data) { //TRACE("Interface.handle_incoming: data: " + data.toHex()); TRACE("Interface.handle_incoming"); assert(_impl); +/* _impl->_rxb += data.size(); - // CBA TODO implement concept of owner or a callback mechanism for incoming data - //_impl->_owner.inbound(data, *this); + // Pass data on to transport for handling Transport::inbound(data, *this); - // CBA This is no good because it frees impl when Interface is destroyed at end of inbound() - //Transport::inbound(data, Interface(this)); +*/ + _impl->handle_incoming(data); } void Interface::process_announce_queue() { diff --git a/src/Interface.h b/src/Interface.h index 988d335..9bae3d4 100644 --- a/src/Interface.h +++ b/src/Interface.h @@ -1,5 +1,6 @@ #pragma once +#include "Identity.h" #include "Log.h" #include "Bytes.h" #include "Type.h" @@ -33,19 +34,27 @@ namespace RNS { Bytes _raw; }; - class InterfaceImpl { + class InterfaceImpl : public std::enable_shared_from_this { protected: - InterfaceImpl() { MEM("Interface::Data object created, this: " + std::to_string((uintptr_t)this)); } - InterfaceImpl(const char* name) : _name(name) { MEM("Interface::Data object created, this: " + std::to_string((uintptr_t)this)); } + InterfaceImpl() { MEMF("InterfaceImpl object created, this: 0x%X", this); } + InterfaceImpl(const char* name) : _name(name) { MEMF("InterfaceImpl object created, this: 0x%X", this); } public: - virtual ~InterfaceImpl() { MEM("Interface::Data object destroyed, this: " + std::to_string((uintptr_t)this)); } + virtual ~InterfaceImpl() { MEMF("InterfaceImpl object destroyed, this: 0x%X", this); } protected: - // CBA send data out on interface - virtual void send_outgoing(const Bytes& data); - // CBA handle data coming in on interface - //virtual void handle_incoming(const Bytes& data); + + // CBA Virtual override method for custom interface to send outgoing data + virtual void send_outgoing(const Bytes& data) = 0; + + // CBA Internal method to handle housekeeping for data going out on interface + void handle_outgoing(const Bytes& data); + // CBA Internal method to handle data coming in on interface and pass on to transport + void handle_incoming(const Bytes& data); + + virtual const Bytes get_hash() const { + return Identity::full_hash({toString()}); + } virtual inline std::string toString() const { return "Interface[" + _name + "]"; } @@ -67,7 +76,7 @@ namespace RNS { std::list _announce_queue; bool _is_connected_to_shared_instance = false; bool _is_local_shared_instance = false; - Bytes _hash; + //Bytes _hash; HInterface _parent_interface; //Transport& _owner; @@ -83,46 +92,49 @@ namespace RNS { public: Interface(Type::NoneConstructor none) { - MEM("Interface object NONE created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object NONE created, this: 0x%X, impl: 0x%X", this, _impl.get()); } Interface(const Interface& obj) : _impl(obj._impl) { - MEM("Interface object copy created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object copy created, this: 0x%X, impl: 0x%X", this, _impl.get()); + } + Interface(std::shared_ptr& impl) : _impl(impl) { + MEMF("Interface object created with shared impl, this: 0x%X, impl: 0x%X", this, _impl.get()); } Interface(InterfaceImpl* impl) : _impl(impl) { - MEM("Interface object impl created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object created with new impl, this: 0x%X, impl: 0x%X", this, _impl.get()); } virtual ~Interface() { - MEM("Interface object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object destroyed, this: 0x%X, impl: 0x%X", this, _impl.get()); } inline Interface& operator = (const Interface& obj) { _impl = obj._impl; - MEM("Interface object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object copy created by assignment, this: 0x%X, impl: 0x%X", this, _impl.get()); return *this; } inline Interface& operator = (InterfaceImpl* impl) { _impl.reset(impl); - MEM("Interface object copy created by assignment, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object copy created by assignment, this: 0x%X, impl: 0x%X", this, _impl.get()); return *this; } inline operator bool() const { - MEM("Interface object bool, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object bool, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() != nullptr; } inline bool operator < (const Interface& obj) const { - MEM("Interface object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object <, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() < obj._impl.get(); } inline bool operator > (const Interface& obj) const { - MEM("Interface object <, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object <, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() > obj._impl.get(); } inline bool operator == (const Interface& obj) const { - MEM("Interface object ==, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object ==, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() == obj._impl.get(); } inline bool operator != (const Interface& obj) const { - MEM("Interface object !=, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_impl.get())); + MEMF("Interface object !=, this: 0x%X, impl: 0x%X", this, _impl.get()); return _impl.get() != obj._impl.get(); } inline InterfaceImpl* get() { @@ -133,7 +145,7 @@ namespace RNS { } public: - inline const Bytes get_hash() const { assert(_impl); return _impl->_hash; } + inline const Bytes get_hash() const { assert(_impl); return _impl->get_hash(); } void process_announce_queue(); // CBA ACCUMULATES @@ -143,7 +155,7 @@ namespace RNS { inline void send_outgoing(const Bytes& data) { assert(_impl); _impl->send_outgoing(data); } public: //inline void handle_incoming(const Bytes& data) { assert(_impl); _impl->handle_incoming(data); } - // CBA handle data coming in on interface + // Public method to handle data coming in on interface and pass on to impl void handle_incoming(const Bytes& data); // getters/setters diff --git a/src/Link.cpp b/src/Link.cpp index 9abde3a..5ec9187 100644 --- a/src/Link.cpp +++ b/src/Link.cpp @@ -1,20 +1,34 @@ #include "Link.h" +#include "LinkData.h" +#include "Resource.h" #include "Reticulum.h" #include "Transport.h" #include "Packet.h" #include "Log.h" +#include "Cryptography/Ed25519.h" +#include "Cryptography/X25519.h" +#include "Cryptography/HKDF.h" +#include "Cryptography/Fernet.h" +#include "Cryptography/Random.h" + +#define MSGPACK_DEBUGLOG_ENABLE 0 +#include + +#include using namespace RNS; using namespace RNS::Type::Link; +using namespace RNS::Cryptography; +using namespace RNS::Utilities; -/*static*/ uint8_t Link::resource_strategies = Type::Link::ACCEPT_NONE | Type::Link::ACCEPT_APP | Type::Link::ACCEPT_ALL; +/*static*/ uint8_t Link::resource_strategies = ACCEPT_NONE | ACCEPT_APP | ACCEPT_ALL; -Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::established established_callback /*= nullptr*/, Callbacks::closed closed_callback /*= nullptr*/, const Destination& owner /*= {Type::NONE}*/, const Bytes& peer_pub_bytes /*= {Bytes::NONE}*/, const Bytes& peer_sig_pub_bytes /*= {Bytes::NONE}*/) : _object(new Object(destination)) { +Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::established established_callback /*= nullptr*/, Callbacks::closed closed_callback /*= nullptr*/, const Destination& owner /*= {Type::NONE}*/, const Bytes& peer_pub_bytes /*= {Bytes::NONE}*/, const Bytes& peer_sig_pub_bytes /*= {Bytes::NONE}*/) : + _object(new LinkData(destination)) +{ assert(_object); - MEM("Link object created"); -/*p TODO _object->_owner = owner; if (destination && destination.type() != Type::Destination::SINGLE) { @@ -33,82 +47,105 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi _object->_initiator = true; _object->_expected_hops = Transport::hops_to(_object->_destination.hash()); _object->_establishment_timeout = Reticulum::get_instance().get_first_hop_timeout(destination.hash()); - _object->_establishment_timeout += Type::Link::ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, Transport::hops_to(destination.hash())); _object->_prv = Cryptography::X25519PrivateKey::generate(); _object->_sig_prv = Cryptography::Ed25519PrivateKey::generate(); - - self.fernet = None - - self.pub = self.prv.public_key() - self.pub_bytes = self.pub.public_bytes() - - self.sig_pub = self.sig_prv.public_key() - self.sig_pub_bytes = self.sig_pub.public_bytes() - - if peer_pub_bytes == None: - self.peer_pub = None - self.peer_pub_bytes = None - else: - self.load_peer(peer_pub_bytes, peer_sig_pub_bytes) - - if established_callback != None: - self.set_link_established_callback(established_callback) - - if closed_callback != None: - self.set_link_closed_callback(closed_callback) - - if (self.initiator) { - self.request_data = self.pub_bytes+self.sig_pub_bytes - self.packet = RNS.Packet(destination, self.request_data, packet_type=RNS.Packet.LINKREQUEST) - self.packet.pack() - self.establishment_cost += len(self.packet.raw) - self.set_link_id(self.packet) - RNS.Transport.register_link(self) - self.request_time = time.time() - self.start_watchdog() - self.packet.send() - self.had_outbound() - RNS.log("Link request "+RNS.prettyhexrep(self.link_id)+" sent to "+str(self.destination), RNS.LOG_DEBUG) - RNS.log(f"Establishment timeout is {RNS.prettytime(self.establishment_timeout)} for link request "+RNS.prettyhexrep(self.link_id), RNS.LOG_EXTREME) } + _object->_pub = _object->_prv->public_key(); + _object->_pub_bytes = _object->_pub->public_bytes(); + TRACEF("Link::load_private_key: pub bytes: %s", _object->_pub_bytes.toHex().c_str()); + + _object->_sig_pub = _object->_sig_prv->public_key(); + _object->_sig_pub_bytes = _object->_sig_pub->public_bytes(); + TRACEF("Link::load_private_key: sig pub bytes: %s", _object->_sig_pub_bytes.toHex().c_str()); + + if (!peer_pub_bytes) { + _object->_peer_pub = nullptr; + _object->_peer_pub_bytes = nullptr; + } + else { + load_peer(peer_pub_bytes, peer_sig_pub_bytes); + } + + if (established_callback) { + set_link_established_callback(established_callback); + } + + if (closed_callback) { + set_link_closed_callback(closed_callback); + } + + if (_object->_initiator) { + _object->_request_data = _object->_pub_bytes + _object->_sig_pub_bytes; + _object->_packet = Packet(destination, _object->_request_data, RNS::Type::Packet::LINKREQUEST); + _object->_packet.pack(); + _object->_establishment_cost += _object->_packet.raw().size(); + set_link_id(_object->_packet); + Transport::register_link(*this); + _object->_request_time = OS::time(); + start_watchdog(); + _object->_packet.send(); + had_outbound(); + DEBUGF("Link request %s sent to %s", _object->_link_id.toHex().c_str(), _object->_destination.toString().c_str()); + TRACEF("Establishment timeout is %f for link request %s", _object->_establishment_timeout, _object->_link_id.toHex().c_str()); + } + + // CBA LINK + _object->_link_destination = Destination({Type::NONE}, Type::Destination::OUT, Type::Destination::LINK, hash()); + _object->_link_destination.link_id(_object->_link_id); + MEM("Link object created"); -*/ } -/*p TODO -Link::validate_request(owner, data, packet) { - if len(data) == (Link.ECPUBSIZE): - try: - link = Link(owner = owner, peer_pub_bytes=data[:Link.ECPUBSIZE//2], peer_sig_pub_bytes=data[Link.ECPUBSIZE//2:Link.ECPUBSIZE]) - link.set_link_id(packet) - link.destination = packet.destination - link.establishment_timeout = Link.ESTABLISHMENT_TIMEOUT_PER_HOP * max(1, packet.hops) + Link.KEEPALIVE - link.establishment_cost += len(packet.raw) - RNS.log("Validating link request "+RNS.prettyhexrep(link.link_id), RNS.LOG_VERBOSE) - RNS.log(f"Establishment timeout is {RNS.prettytime(link.establishment_timeout)} for incoming link request "+RNS.prettyhexrep(link.link_id), RNS.LOG_EXTREME) - link.handshake() - link.attached_interface = packet.receiving_interface - link.prove() - link.request_time = time.time() - RNS.Transport.register_link(link) - link.last_inbound = time.time() - link.start_watchdog() +/*static*/ Link Link::validate_request( const Destination& owner, const Bytes& data, const Packet& packet) { + if (data.size() == ECPUBSIZE) { + try { + Link link({Type::NONE}, nullptr, nullptr, owner, data.left(ECPUBSIZE/2), data.mid(ECPUBSIZE/2, ECPUBSIZE/2)); + link.set_link_id(packet); + link.destination(packet.destination()); + link.establishment_timeout(ESTABLISHMENT_TIMEOUT_PER_HOP * std::max((uint8_t)1, packet.hops()) + KEEPALIVE); + link.establishment_cost(link.establishment_cost() + packet.raw().size()); + VERBOSEF("Validating link request %s", link.link_id().toHex().c_str()); + TRACEF("Establishment timeout is %f for incoming link request %s", link.establishment_timeout(), link.link_id().toHex().c_str()); + link.handshake(); + link.attached_interface(packet.receiving_interface()); + link.prove(); + link.request_time(OS::time()); + Transport::register_link(link); + link.last_inbound(OS::time()); + link.start_watchdog(); - RNS.log("Incoming link request "+str(link)+" accepted", RNS.LOG_DEBUG) - return link - - except Exception as e: - RNS.log("Validating link request failed", RNS.LOG_VERBOSE) - RNS.log("exc: "+str(e)) - return None - - else: - RNS.log("Invalid link request payload size, dropping request", RNS.LOG_DEBUG) - return None + DEBUGF("Incoming link request %s accepted", link.toString().c_str()); + return link; + } + catch (std::exception& e) { + VERBOSEF("Validating link request failed, exception: %s", e.what()); + return {Type::NONE}; + } + } + else { + DEBUG("Invalid link request payload size, dropping request"); + return {Type::NONE}; + } } + +void Link::load_peer(const Bytes& peer_pub_bytes, const Bytes& peer_sig_pub_bytes) { + assert(_object); + _object->_peer_pub_bytes = peer_pub_bytes; + _object->_peer_pub = Cryptography::X25519PublicKey::from_public_bytes(_object->_peer_pub_bytes); + + _object->_peer_sig_pub_bytes = peer_sig_pub_bytes; + _object->_peer_sig_pub = Cryptography::Ed25519PublicKey::from_public_bytes(_object->_peer_sig_pub_bytes); + + // CBA TODO Determine the purpose of the following. + // X25519PublicKey does not have a member "curve" and this is not accessed anywhere +/* + if not hasattr(self.peer_pub, "curve") { + self.peer_pub.curve = CURVE; + } */ +} void Link::set_link_id(const Packet& packet) { assert(_object); @@ -116,1096 +153,1414 @@ void Link::set_link_id(const Packet& packet) { _object->_hash = _object->_link_id; } -void Link::receive(const Packet& packet) { +void Link::handshake() { + assert(_object); + if (_object->_status == Type::Link::PENDING && _object->_prv) { + _object->_status = Type::Link::HANDSHAKE; + _object->_shared_key = _object->_prv->exchange(_object->_peer_pub_bytes); + + _object->_derived_key = Cryptography::hkdf( + 32, + _object->_shared_key, + get_salt(), + get_context() + ); + } + else { + ERRORF("Handshake attempt on %s with invalid state %d", toString().c_str(), _object->_status); + } } void Link::prove() { -/*p TODO - signed_data = self.link_id+self.pub_bytes+self.sig_pub_bytes - signature = self.owner.identity.sign(signed_data) + assert(_object); + Bytes signed_data =_object->_link_id + _object->_pub_bytes + _object->_sig_pub_bytes; + const Bytes signature(_object->_owner.identity().sign(signed_data)); - proof_data = signature+self.pub_bytes - proof = RNS.Packet(self, proof_data, packet_type=RNS.Packet.PROOF, context=RNS.Packet.LRPROOF) - proof.send() - self.establishment_cost += len(proof.raw) - self.had_outbound() -*/ + Bytes proof_data = signature + _object->_pub_bytes; + // CBA LINK + //Packet proof(_object->_link_destination, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF); + Packet proof(_object->_link_destination, *this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF); + proof.send(); + _object->_establishment_cost += proof.raw().size(); + had_outbound(); } void Link::prove_packet(const Packet& packet) { -/*p TODO - signature = self.sign(packet.packet_hash) - # TODO: Hardcoded as explicit proof for now - # if RNS.Reticulum.should_use_implicit_proof(): - # proof_data = signature - # else: - # proof_data = packet.packet_hash + signature - proof_data = packet.packet_hash + signature + assert(_object); + const Bytes signature(sign(packet.packet_hash())); + // TODO: Hardcoded as explicit proof for now + // if RNS.Reticulum.should_use_implicit_proof(): + // proof_data = signature + // else: + // proof_data = packet.packet_hash + signature + Bytes proof_data = packet.packet_hash() + signature; - proof = RNS.Packet(self, proof_data, RNS.Packet.PROOF) - proof.send() - self.had_outbound() + Packet proof(_object->_link_destination, proof_data, Type::Packet::PROOF); + proof.send(); + had_outbound(); +} + +void Link::validate_proof(const Packet& packet) { + assert(_object); + try { + if (_object->_status == Type::Link::PENDING) { + //p if _object->_initiator and len(packet.data) == RNS.Identity.SIGLENGTH//8+ECPUBSIZE//2: + if (_object->_initiator && packet.data().size() == Type::Identity::SIGLENGTH/8+ECPUBSIZE/2) { + //p peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+ECPUBSIZE//2] + const Bytes peer_pub_bytes(packet.data().mid(Type::Identity::SIGLENGTH/8, ECPUBSIZE/2)); + //p peer_sig_pub_bytes = _object->_destination.identity.get_public_key()[ECPUBSIZE//2:ECPUBSIZE] + const Bytes peer_sig_pub_bytes(_object->_destination.identity().get_public_key().mid(ECPUBSIZE/2, ECPUBSIZE/2)); + load_peer(peer_pub_bytes, peer_sig_pub_bytes); + handshake(); + + _object->_establishment_cost += packet.raw().size(); + Bytes signed_data = _object->_link_id + _object->_peer_pub_bytes + _object->_peer_sig_pub_bytes; + const Bytes signature(packet.data().left(Type::Identity::SIGLENGTH/8)); + + if (_object->_destination.identity().validate(signature, signed_data)) { + if (_object->_status != Type::Link::HANDSHAKE) { + throw std::runtime_error("Invalid link state for proof validation: " + _object->_status); + } + _object->_rtt = OS::time() - _object->_request_time; + _object->_attached_interface = packet.receiving_interface(); + _object->__remote_identity = _object->_destination.identity(); + _object->_status = Type::Link::ACTIVE; + _object->_activated_at = OS::time(); + _object->_last_proof = _object->_activated_at; + Transport::activate_link(*this); + VERBOSEF("Link %s established with %s, RTT is %f s", toString().c_str(), _object->_destination.toString().c_str(), OS::round(_object->_rtt, 3)); + + //p if _object->_rtt != None and _object->_establishment_cost != None and _object->_rtt > 0 and _object->_establishment_cost > 0: + if (_object->_rtt != 0.0 && _object->_establishment_cost != 0 && _object->_rtt > 0 and _object->_establishment_cost > 0) { + _object->_establishment_rate = _object->_establishment_cost / _object->_rtt; + } + + //p rtt_data = umsgpack.packb(self.rtt) + MsgPack::Packer packer; + packer.serialize(_object->_rtt); + Bytes rtt_data(packer.data(), packer.size()); + //p rtt_packet = RNS.Packet(self, rtt_data, context=RNS.Packet.LRRTT) + Packet rtt_packet(_object->_link_destination, rtt_data, Type::Packet::DATA, Type::Packet::LRRTT); + rtt_packet.send(); + had_outbound(); + + if (_object->_callbacks._established != nullptr) { + //p thread = threading.Thread(target=_object->_callbacks.link_established, args=(self,)) + //p thread.daemon = True + //p thread.start() + _object->_callbacks._established(*this); + } + } + else { + DEBUGF("Invalid link proof signature received by %s. Ignoring.", toString().c_str()); + } + } + } + } + catch (std::exception& e) { + _object->_status = Type::Link::CLOSED; + ERRORF("An error ocurred while validating link request proof on %s.", toString().c_str()); + ERRORF("The contained exception was: %s", e.what()); + } +} + + +/* +Identifies the initiator of the link to the remote peer. This can only happen +once the link has been established, and is carried out over the encrypted link. +The identity is only revealed to the remote peer, and initiator anonymity is +thus preserved. This method can be used for authentication. + +:param identity: An RNS.Identity instance to identify as. */ +void Link::identify(const Identity& identity) { + assert(_object); + if (_object->_initiator && _object->_status == Type::Link::ACTIVE) { + const Bytes signed_data(_object->_link_id + identity.get_public_key()); + const Bytes signature(identity.sign(signed_data)); + const Bytes proof_data(identity.get_public_key() + signature); + + Packet proof(_object->_link_destination, proof_data, Type::Packet::DATA, Type::Packet::LINKIDENTIFY); + proof.send(); + had_outbound(); + } +} + +/* +Sends a request to the remote peer. + +:param path: The request path. +:param response_callback: An optional function or method with the signature *response_callback(request_receipt)* to be called when a response is received. See the :ref:`Request Example` for more info. +:param failed_callback: An optional function or method with the signature *failed_callback(request_receipt)* to be called when a request fails. See the :ref:`Request Example` for more info. +:param progress_callback: An optional function or method with the signature *progress_callback(request_receipt)* to be called when progress is made receiving the response. Progress can be accessed as a float between 0.0 and 1.0 by the *request_receipt.progress* property. +:param timeout: An optional timeout in seconds for the request. If *None* is supplied it will be calculated based on link RTT. +:returns: A :ref:`RNS.RequestReceipt` instance if the request was sent, or *False* if it was not. +*/ +const RNS::RequestReceipt Link::request(const Bytes& path, const Bytes& data /*= {Bytes::NONE}*/, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/) { + assert(_object); + const Bytes request_path_hash(Identity::truncated_hash(path)); + + //p unpacked_request = [OS::time(), request_path_hash, data] + //p packed_request = umsgpack.packb(unpacked_request) + MsgPack::Packer packer; + packer.to_array(OS::time(), request_path_hash, data); + Bytes packed_request(packer.data(), packer.size()); + + if (timeout == 0.0) { + timeout = _object->_rtt * _object->_traffic_timeout_factor + Type::Resource::RESPONSE_MAX_GRACE_TIME * 1.125; + } + + if (packed_request.size() <= MDU) { + Packet request_packet(_object->_link_destination, packed_request, Type::Packet::DATA, Type::Packet::REQUEST); + PacketReceipt packet_receipt = request_packet.send(); + + if (!packet_receipt) { + return {Type::NONE}; + } + else { + packet_receipt.set_timeout(timeout); + return RequestReceipt( + *this, + packet_receipt, + {Type::NONE}, + response_callback, + failed_callback, + progress_callback, + timeout, + packed_request.size() + ); + } + } + else { + const Bytes request_id(Identity::truncated_hash(packed_request)); + DEBUGF("Sending request %s as resource.", request_id.toHex().c_str()); + Resource request_resource(packed_request, *this, request_id, false, timeout); + + return RequestReceipt( + *this, + {Type::NONE}, + request_resource, + response_callback, + failed_callback, + progress_callback, + timeout, + packed_request.size() + ); + } +} + + +void Link::rtt_packet(const Packet& packet) { + assert(_object); + try { + double measured_rtt = OS::time() - _object->_request_time; + const Bytes plaintext(decrypt(packet.data())); + if (plaintext) { + //p rtt = umsgpack.unpackb(plaintext) + MsgPack::Unpacker unpacker; + unpacker.feed(plaintext.data(), plaintext.size()); + double rtt = 0.0; + unpacker.deserialize(rtt); + _object->_rtt = std::max(measured_rtt, rtt); + _object->_status = Type::Link::ACTIVE; + _object->_activated_at = OS::time(); + + //p if _object->_rtt != None and _object->_establishment_cost != None and _object->_rtt > 0 and _object->_establishment_cost > 0: + if (_object->_rtt != 0.0 && _object->_establishment_cost != 0.0 && _object->_rtt > 0 and _object->_establishment_cost > 0) { + _object->_establishment_rate = _object->_establishment_cost / _object->_rtt; + } + + try { + if (_object->_owner.callbacks()._link_established != nullptr) { + _object->_owner.callbacks()._link_established(*this); + } + } + catch (std::exception& e) { + ERRORF("Error occurred in external link establishment callback. The contained exception was: %s", e.what()); + } + } + } + catch (std::exception& e) { + ERRORF("Error occurred while processing RTT packet, tearing down link. The contained exception was: %s", e.what()); + teardown(); + } +} + +/* +:returns: The data transfer rate at which the link establishment procedure ocurred, in bits per second. +*/ +float Link::get_establishment_rate() { + assert(_object); + //p if _object->_establishment_rate != None: + //p return _object->_establishment_rate*8 + //p else: + //p return None + return _object->_establishment_rate*8; +} + +const Bytes& Link::get_salt() { + assert(_object); + return _object->_link_id; +} + +const Bytes Link::get_context() { + return {Bytes::NONE}; +} + +/* +:returns: The time in seconds since last inbound packet on the link. This includes keepalive packets. +*/ +double Link::no_inbound_for() { + assert(_object); + //p activated_at = _object->_activated_at if _object->_activated_at != None else 0 + double activated_at = _object->_activated_at; + double last_inbound = std::max(_object->_last_inbound, activated_at); + return (OS::time() - last_inbound); +} + +/* +:returns: The time in seconds since last outbound packet on the link. This includes keepalive packets. +*/ +double Link::no_outbound_for() { + assert(_object); + return OS::time() - _object->_last_outbound; +} + +/* +:returns: The time in seconds since payload data traversed the link. This excludes keepalive packets. +*/ +double Link::no_data_for() { + assert(_object); + return OS::time() - _object->_last_data; +} + +/* +:returns: The time in seconds since activity on the link. This includes keepalive packets. +*/ +double Link::inactive_for() { + assert(_object); + return std::min(no_inbound_for(), no_outbound_for()); +} + +/* +:returns: The identity of the remote peer, if it is known. Calling this method will not query the remote initiator to reveal its identity. Returns ``None`` if the link initiator has not already independently called the ``identify(identity)`` method. +*/ +const Identity& Link::get_remote_identity() { + assert(_object); + return _object->__remote_identity; +} + +void Link::had_outbound(bool is_keepalive /*= false*/) { + assert(_object); + _object->_last_outbound = OS::time(); + if (!is_keepalive) { + _object->_last_data = _object->_last_outbound; + } +} + +/* +Closes the link and purges encryption keys. New keys will +be used if a new link to the same destination is established. +*/ +void Link::teardown() { + assert(_object); + if (_object->_status != Type::Link::PENDING && _object->_status != Type::Link::CLOSED) { + Packet teardown_packet(_object->_link_destination, _object->_link_id, Type::Packet::DATA, Type::Packet::LINKCLOSE); + teardown_packet.send(); + had_outbound(); + } + _object->_status = Type::Link::CLOSED; + if (_object->_initiator) { + _object->_teardown_reason = Type::Link::INITIATOR_CLOSED; + } + else { + _object->_teardown_reason = Type::Link::DESTINATION_CLOSED; + } + link_closed(); +} + +void Link::teardown_packet(const Packet& packet) { + assert(_object); + try { + Bytes plaintext = decrypt(packet.data()); + if (plaintext == _object->_link_id) { + _object->_status = Type::Link::CLOSED; + if (_object->_initiator) { + _object->_teardown_reason = Type::Link::DESTINATION_CLOSED; + } + else { + _object->_teardown_reason = Type::Link::INITIATOR_CLOSED; + } + link_closed(); + } + } + catch (std::exception& e) { + } +} + +void Link::link_closed() { + assert(_object); + for (auto& resource : _object->_incoming_resources) { + const_cast(resource).cancel(); + } + for (auto& resource : _object->_outgoing_resources) { + const_cast(resource).cancel(); + } + if (_object->_channel) { + _object->_channel._shutdown(); + } + + _object->_prv.reset(); + _object->_pub.reset(); + _object->_pub_bytes.clear(); + _object->_shared_key.clear(); + _object->_derived_key.clear(); + + if (_object->_destination) { + if (_object->_destination.direction() == Type::Destination::IN) { + if (_object->_destination.has_link(*this)) { + _object->_destination.remove_link(*this); + } + } + } + + if (_object->_callbacks._closed) { + try { + _object->_callbacks._closed(*this); + } + catch (std::exception& e) { + ERRORF("Error while executing link closed callback from %s. The contained exception was: %s", toString().c_str(), e.what()); + } + } +} + +// CBA TODO Implement watchdog +void Link::start_watchdog() { + //z thread = threading.Thread(target=_object->___watchdog_job) + //z thread.daemon = True + //z thread.start() } /*p TODO -def load_peer(self, peer_pub_bytes, peer_sig_pub_bytes): - self.peer_pub_bytes = peer_pub_bytes - self.peer_pub = X25519PublicKey.from_public_bytes(self.peer_pub_bytes) - - self.peer_sig_pub_bytes = peer_sig_pub_bytes - self.peer_sig_pub = Ed25519PublicKey.from_public_bytes(self.peer_sig_pub_bytes) - - if not hasattr(self.peer_pub, "curve"): - self.peer_pub.curve = Link.CURVE - -def set_link_id(self, packet): - self.link_id = packet.getTruncatedHash() - self.hash = self.link_id - -def handshake(self): - if self.status == Link.PENDING and self.prv != None: - self.status = Link.HANDSHAKE - self.shared_key = self.prv.exchange(self.peer_pub) - - self.derived_key = RNS.Cryptography.hkdf( - length=32, - derive_from=self.shared_key, - salt=self.get_salt(), - context=self.get_context(), - ) - else: - RNS.log("Handshake attempt on "+str(self)+" with invalid state "+str(self.status), RNS.LOG_ERROR) - - -def prove(self): - signed_data = self.link_id+self.pub_bytes+self.sig_pub_bytes - signature = self.owner.identity.sign(signed_data) - - proof_data = signature+self.pub_bytes - proof = RNS.Packet(self, proof_data, packet_type=RNS.Packet.PROOF, context=RNS.Packet.LRPROOF) - proof.send() - self.establishment_cost += len(proof.raw) - self.had_outbound() - - -def prove_packet(self, packet): - signature = self.sign(packet.packet_hash) - # TODO: Hardcoded as explicit proof for now - # if RNS.Reticulum.should_use_implicit_proof(): - # proof_data = signature - # else: - # proof_data = packet.packet_hash + signature - proof_data = packet.packet_hash + signature - - proof = RNS.Packet(self, proof_data, RNS.Packet.PROOF) - proof.send() - self.had_outbound() - -def validate_proof(self, packet): - try: - if self.status == Link.PENDING: - if self.initiator and len(packet.data) == RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2: - peer_pub_bytes = packet.data[RNS.Identity.SIGLENGTH//8:RNS.Identity.SIGLENGTH//8+Link.ECPUBSIZE//2] - peer_sig_pub_bytes = self.destination.identity.get_public_key()[Link.ECPUBSIZE//2:Link.ECPUBSIZE] - self.load_peer(peer_pub_bytes, peer_sig_pub_bytes) - self.handshake() - - self.establishment_cost += len(packet.raw) - signed_data = self.link_id+self.peer_pub_bytes+self.peer_sig_pub_bytes - signature = packet.data[:RNS.Identity.SIGLENGTH//8] - - if self.destination.identity.validate(signature, signed_data): - if self.status != Link.HANDSHAKE: - raise IOError("Invalid link state for proof validation: "+str(self.status)) - - self.rtt = time.time() - self.request_time - self.attached_interface = packet.receiving_interface - self.__remote_identity = self.destination.identity - self.status = Link.ACTIVE - self.activated_at = time.time() - self.last_proof = self.activated_at - RNS.Transport.activate_link(self) - RNS.log("Link "+str(self)+" established with "+str(self.destination)+", RTT is "+str(round(self.rtt, 3))+"s", RNS.LOG_VERBOSE) - - if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0: - self.establishment_rate = self.establishment_cost/self.rtt - - rtt_data = umsgpack.packb(self.rtt) - rtt_packet = RNS.Packet(self, rtt_data, context=RNS.Packet.LRRTT) - rtt_packet.send() - self.had_outbound() - - if self.callbacks.link_established != None: - thread = threading.Thread(target=self.callbacks.link_established, args=(self,)) - thread.daemon = True - thread.start() - else: - RNS.log("Invalid link proof signature received by "+str(self)+". Ignoring.", RNS.LOG_DEBUG) - - except Exception as e: - self.status = Link.CLOSED - RNS.log("An error ocurred while validating link request proof on "+str(self)+".", RNS.LOG_ERROR) - RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR) - - -def identify(self, identity): - """ - Identifies the initiator of the link to the remote peer. This can only happen - once the link has been established, and is carried out over the encrypted link. - The identity is only revealed to the remote peer, and initiator anonymity is - thus preserved. This method can be used for authentication. - - :param identity: An RNS.Identity instance to identify as. - """ - if self.initiator and self.status == Link.ACTIVE: - signed_data = self.link_id + identity.get_public_key() - signature = identity.sign(signed_data) - proof_data = identity.get_public_key() + signature - - proof = RNS.Packet(self, proof_data, RNS.Packet.DATA, context = RNS.Packet.LINKIDENTIFY) - proof.send() - self.had_outbound() - - -def request(self, path, data = None, response_callback = None, failed_callback = None, progress_callback = None, timeout = None): - """ - Sends a request to the remote peer. - - :param path: The request path. - :param response_callback: An optional function or method with the signature *response_callback(request_receipt)* to be called when a response is received. See the :ref:`Request Example` for more info. - :param failed_callback: An optional function or method with the signature *failed_callback(request_receipt)* to be called when a request fails. See the :ref:`Request Example` for more info. - :param progress_callback: An optional function or method with the signature *progress_callback(request_receipt)* to be called when progress is made receiving the response. Progress can be accessed as a float between 0.0 and 1.0 by the *request_receipt.progress* property. - :param timeout: An optional timeout in seconds for the request. If *None* is supplied it will be calculated based on link RTT. - :returns: A :ref:`RNS.RequestReceipt` instance if the request was sent, or *False* if it was not. - """ - request_path_hash = RNS.Identity.truncated_hash(path.encode("utf-8")) - unpacked_request = [time.time(), request_path_hash, data] - packed_request = umsgpack.packb(unpacked_request) - - if timeout == None: - timeout = self.rtt * self.traffic_timeout_factor + RNS.Resource.RESPONSE_MAX_GRACE_TIME*1.125 - - if len(packed_request) <= Link.MDU: - request_packet = RNS.Packet(self, packed_request, RNS.Packet.DATA, context = RNS.Packet.REQUEST) - packet_receipt = request_packet.send() - - if packet_receipt == False: - return False - else: - packet_receipt.set_timeout(timeout) - return RequestReceipt( - self, - packet_receipt = packet_receipt, - response_callback = response_callback, - failed_callback = failed_callback, - progress_callback = progress_callback, - timeout = timeout, - request_size = len(packed_request), - ) - - else: - request_id = RNS.Identity.truncated_hash(packed_request) - RNS.log("Sending request "+RNS.prettyhexrep(request_id)+" as resource.", RNS.LOG_DEBUG) - request_resource = RNS.Resource(packed_request, self, request_id = request_id, is_response = False, timeout = timeout) - - return RequestReceipt( - self, - resource = request_resource, - response_callback = response_callback, - failed_callback = failed_callback, - progress_callback = progress_callback, - timeout = timeout, - request_size = len(packed_request), - ) - - -def rtt_packet(self, packet): - try: - measured_rtt = time.time() - self.request_time - plaintext = self.decrypt(packet.data) - if plaintext != None: - rtt = umsgpack.unpackb(plaintext) - self.rtt = max(measured_rtt, rtt) - self.status = Link.ACTIVE - self.activated_at = time.time() - - if self.rtt != None and self.establishment_cost != None and self.rtt > 0 and self.establishment_cost > 0: - self.establishment_rate = self.establishment_cost/self.rtt - - try: - if self.owner.callbacks.link_established != None: - self.owner.callbacks.link_established(self) - except Exception as e: - RNS.log("Error occurred in external link establishment callback. The contained exception was: "+str(e), RNS.LOG_ERROR) - - except Exception as e: - RNS.log("Error occurred while processing RTT packet, tearing down link. The contained exception was: "+str(e), RNS.LOG_ERROR) - self.teardown() - -def track_phy_stats(self, track): - """ - You can enable physical layer statistics on a per-link basis. If this is enabled, - and the link is running over an interface that supports reporting physical layer - statistics, you will be able to retrieve stats such as *RSSI*, *SNR* and physical - *Link Quality* for the link. - - :param track: Whether or not to keep track of physical layer statistics. Value must be ``True`` or ``False``. - """ - if track: - self.__track_phy_stats = True - else: - self.__track_phy_stats = False - -def get_rssi(self): - """ - :returns: The physical layer *Received Signal Strength Indication* if available, otherwise ``None``. Physical layer statistics must be enabled on the link for this method to return a value. - """ - return self.rssi - -def get_snr(self): - """ - :returns: The physical layer *Signal-to-Noise Ratio* if available, otherwise ``None``. Physical layer statistics must be enabled on the link for this method to return a value. - """ - return self.rssi - -def get_q(self): - """ - :returns: The physical layer *Link Quality* if available, otherwise ``None``. Physical layer statistics must be enabled on the link for this method to return a value. - """ - return self.rssi - -def get_establishment_rate(self): - """ - :returns: The data transfer rate at which the link establishment procedure ocurred, in bits per second. - """ - if self.establishment_rate != None: - return self.establishment_rate*8 - else: - return None - -def get_salt(self): - return self.link_id - -def get_context(self): - return None - -def no_inbound_for(self): - """ - :returns: The time in seconds since last inbound packet on the link. This includes keepalive packets. - """ - activated_at = self.activated_at if self.activated_at != None else 0 - last_inbound = max(self.last_inbound, activated_at) - return time.time() - last_inbound - -def no_outbound_for(self): - """ - :returns: The time in seconds since last outbound packet on the link. This includes keepalive packets. - """ - return time.time() - self.last_outbound - -def no_data_for(self): - """ - :returns: The time in seconds since payload data traversed the link. This excludes keepalive packets. - """ - return time.time() - self.last_data - -def inactive_for(self): - """ - :returns: The time in seconds since activity on the link. This includes keepalive packets. - """ - return min(self.no_inbound_for(), self.no_outbound_for()) - -def get_remote_identity(self): - """ - :returns: The identity of the remote peer, if it is known. Calling this method will not query the remote initiator to reveal its identity. Returns ``None`` if the link initiator has not already independently called the ``identify(identity)`` method. - """ - return self.__remote_identity - -def had_outbound(self, is_keepalive=False): - self.last_outbound = time.time() - if not is_keepalive: - self.last_data = self.last_outbound - -def teardown(self): - """ - Closes the link and purges encryption keys. New keys will - be used if a new link to the same destination is established. - """ - if self.status != Link.PENDING and self.status != Link.CLOSED: - teardown_packet = RNS.Packet(self, self.link_id, context=RNS.Packet.LINKCLOSE) - teardown_packet.send() - self.had_outbound() - self.status = Link.CLOSED - if self.initiator: - self.teardown_reason = Link.INITIATOR_CLOSED - else: - self.teardown_reason = Link.DESTINATION_CLOSED - self.link_closed() - -def teardown_packet(self, packet): - try: - plaintext = self.decrypt(packet.data) - if plaintext == self.link_id: - self.status = Link.CLOSED - if self.initiator: - self.teardown_reason = Link.DESTINATION_CLOSED - else: - self.teardown_reason = Link.INITIATOR_CLOSED - self.__update_phy_stats(packet) - self.link_closed() - except Exception as e: - pass - -def link_closed(self): - for resource in self.incoming_resources: - resource.cancel() - for resource in self.outgoing_resources: - resource.cancel() - if self._channel: - self._channel._shutdown() - - self.prv = None - self.pub = None - self.pub_bytes = None - self.shared_key = None - self.derived_key = None - - if self.destination != None: - if self.destination.direction == RNS.Destination.IN: - if self in self.destination.links: - self.destination.links.remove(self) - - if self.callbacks.link_closed != None: - try: - self.callbacks.link_closed(self) - except Exception as e: - RNS.log("Error while executing link closed callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - - -def start_watchdog(self): - thread = threading.Thread(target=self.__watchdog_job) - thread.daemon = True - thread.start() - -def __watchdog_job(self): - while not self.status == Link.CLOSED: - while (self.watchdog_lock): +void Link::__watchdog_job() { + assert(_object); + while not _object->_status == Type::Link::CLOSED: + while (_object->_watchdog_lock): rtt_wait = 0.025 - if hasattr(self, "rtt") and self.rtt: - rtt_wait = self.rtt + if hasattr(self, "rtt") and _object->_rtt: + rtt_wait = _object->_rtt sleep(max(rtt_wait, 0.025)) - if not self.status == Link.CLOSED: + if not _object->_status == Type::Link::CLOSED: # Link was initiated, but no response # from destination yet - if self.status == Link.PENDING: - next_check = self.request_time + self.establishment_timeout - sleep_time = next_check - time.time() - if time.time() >= self.request_time + self.establishment_timeout: + if _object->_status == PENDING: + next_check = _object->_request_time + _object->_establishment_timeout + sleep_time = next_check - OS::time() + if OS::time() >= _object->_request_time + _object->_establishment_timeout: RNS.log("Link establishment timed out", RNS.LOG_VERBOSE) - self.status = Link.CLOSED - self.teardown_reason = Link.TIMEOUT - self.link_closed() + _object->_status = Type::Link::CLOSED + _object->_teardown_reason = TIMEOUT + link_closed() sleep_time = 0.001 - elif self.status == Link.HANDSHAKE: - next_check = self.request_time + self.establishment_timeout - sleep_time = next_check - time.time() - if time.time() >= self.request_time + self.establishment_timeout: - self.status = Link.CLOSED - self.teardown_reason = Link.TIMEOUT - self.link_closed() + elif _object->_status == Type::Link::HANDSHAKE: + next_check = _object->_request_time + _object->_establishment_timeout + sleep_time = next_check - OS::time() + if OS::time() >= _object->_request_time + _object->_establishment_timeout: + _object->_status = Type::Link::CLOSED + _object->_teardown_reason = TIMEOUT + link_closed() sleep_time = 0.001 - if self.initiator: + if _object->_initiator: RNS.log("Timeout waiting for link request proof", RNS.LOG_DEBUG) else: RNS.log("Timeout waiting for RTT packet from link initiator", RNS.LOG_DEBUG) - elif self.status == Link.ACTIVE: - activated_at = self.activated_at if self.activated_at != None else 0 - last_inbound = max(max(self.last_inbound, self.last_proof), activated_at) + elif _object->_status == Type::Link::ACTIVE: + activated_at = _object->_activated_at if _object->_activated_at != None else 0 + last_inbound = max(max(_object->_last_inbound, _object->_last_proof), activated_at) - if time.time() >= last_inbound + self.keepalive: - if self.initiator: - self.send_keepalive() + if OS::time() >= last_inbound + _object->_keepalive: + if _object->_initiator: + send_keepalive() - if time.time() >= last_inbound + self.stale_time: - sleep_time = self.rtt * self.keepalive_timeout_factor + Link.STALE_GRACE - self.status = Link.STALE + if OS::time() >= last_inbound + _object->_stale_time: + sleep_time = _object->_rtt * _object->_keepalive_timeout_factor + STALE_GRACE + _object->_status = STALE else: - sleep_time = self.keepalive + sleep_time = _object->_keepalive else: - sleep_time = (last_inbound + self.keepalive) - time.time() + sleep_time = (last_inbound + _object->_keepalive) - OS::time() - elif self.status == Link.STALE: + elif _object->_status == STALE: sleep_time = 0.001 - self.status = Link.CLOSED - self.teardown_reason = Link.TIMEOUT - self.link_closed() + _object->_status = Type::Link::CLOSED + _object->_teardown_reason = TIMEOUT + link_closed() if sleep_time == 0: RNS.log("Warning! Link watchdog sleep time of 0!", RNS.LOG_ERROR) if sleep_time == None or sleep_time < 0: RNS.log("Timing error! Tearing down link "+str(self)+" now.", RNS.LOG_ERROR) - self.teardown() + teardown() sleep_time = 0.1 sleep(sleep_time) +*/ -def __update_phy_stats(self, packet, query_shared = True): - if self.__track_phy_stats: - if query_shared: - reticulum = RNS.Reticulum.get_instance() - if packet.rssi == None: packet.rssi = reticulum.get_packet_rssi(packet.packet_hash) - if packet.snr == None: packet.snr = reticulum.get_packet_snr(packet.packet_hash) - if packet.q == None: packet.q = reticulum.get_packet_q(packet.packet_hash) +void Link::send_keepalive() { + assert(_object); + //p keepalive_packet = RNS.Packet(self, bytes([0xFF]), context=RNS.Packet.KEEPALIVE) + RNS::Packet keepalive_packet(_object->_link_destination, Bytes("\xFF"), Type::Packet::DATA, Type::Packet::KEEPALIVE); + keepalive_packet.send(); + had_outbound(true); +} - if packet.rssi != None: - self.rssi = packet.rssi - if packet.snr != None: - self.snr = packet.snr - if packet.q != None: - self.q = packet.q +void Link::handle_request(const Bytes& request_id, const ResourceRequest& resource_request) { + if (_object->_status == Type::Link::ACTIVE) { + //p requested_at = unpacked_request[0] + //p path_hash = unpacked_request[1] + //p request_data = unpacked_request[2] -def send_keepalive(self): - keepalive_packet = RNS.Packet(self, bytes([0xFF]), context=RNS.Packet.KEEPALIVE) - keepalive_packet.send() - self.had_outbound(is_keepalive = True) + auto handler_iter = _object->_destination.request_handlers().find(resource_request._path_hash); + if (handler_iter != _object->_destination.request_handlers().end()) { + TRACE("Link::handle_request: Found handler"); + RequestHandler request_handler = (*handler_iter).second; -def handle_request(self, request_id, unpacked_request): - if self.status == Link.ACTIVE: - requested_at = unpacked_request[0] - path_hash = unpacked_request[1] - request_data = unpacked_request[2] + bool allowed = false; + if (request_handler._allow != Type::Destination::ALLOW_NONE) { + if (request_handler._allow == Type::Destination::ALLOW_LIST) { + if (_object->__remote_identity && request_handler._allowed_list.count(_object->__remote_identity.hash()) > 0) { + allowed = true; + } + } + else if (request_handler._allow == Type::Destination::ALLOW_ALL) { + allowed = true; + } + } - if path_hash in self.destination.request_handlers: - request_handler = self.destination.request_handlers[path_hash] - path = request_handler[0] - response_generator = request_handler[1] - allow = request_handler[2] - allowed_list = request_handler[3] + if (allowed) { + DEBUGF("Handling request %s for: %s", request_id.toHex().c_str(), request_handler._path.toString().c_str()); + //p if len(inspect.signature(response_generator).parameters) == 5: + //p response = response_generator(path, request_data, request_id, _object->__remote_identity, requested_at) + //p elif len(inspect.signature(response_generator).parameters) == 6: + //p response = response_generator(path, request_data, request_id, _object->_link_id, _object->__remote_identity, requested_at) + //p else: + //p raise TypeError("Invalid signature for response generator callback") + Bytes response(request_handler._response_generator(request_handler._path, resource_request._request_data, request_id, _object->_link_id, _object->__remote_identity, resource_request._requested_at)); - allowed = False - if not allow == RNS.Destination.ALLOW_NONE: - if allow == RNS.Destination.ALLOW_LIST: - if self.__remote_identity != None and self.__remote_identity.hash in allowed_list: - allowed = True - elif allow == RNS.Destination.ALLOW_ALL: - allowed = True + if (response) { + //p packed_response = umsgpack.packb([request_id, response]) + MsgPack::Packer packer; + packer.to_array(request_id, response); + Bytes packed_response(packer.data(), packer.size()); - if allowed: - RNS.log("Handling request "+RNS.prettyhexrep(request_id)+" for: "+str(path), RNS.LOG_DEBUG) - if len(inspect.signature(response_generator).parameters) == 5: - response = response_generator(path, request_data, request_id, self.__remote_identity, requested_at) - elif len(inspect.signature(response_generator).parameters) == 6: - response = response_generator(path, request_data, request_id, self.link_id, self.__remote_identity, requested_at) - else: - raise TypeError("Invalid signature for response generator callback") + if (packed_response.size() <= MDU) { + //p RNS.Packet(self, packed_response, Type::Packet::DATA, context = Type::Packet::RESPONSE).send() + RNS::Packet response_packet(_object->_link_destination, packed_response, Type::Packet::DATA, Type::Packet::RESPONSE); + response_packet.send(); + } + else { + // CBA TODO Determine why unused Resource is created here + Resource response_resource = RNS::Resource(packed_response, *this, request_id, true); + } + } + } + else { + std::string identity_string; + if (get_remote_identity()) { + identity_string = get_remote_identity().toString(); + } + else { + identity_string = ""; + } + DEBUGF("Request %s from %s not allowed for: %s", request_id.toHex().c_str(), identity_string.c_str(), request_handler._path.toString().c_str()); + } + } + } +} - if response != None: - packed_response = umsgpack.packb([request_id, response]) +void Link::handle_response(const Bytes& request_id, const Bytes& response_data, size_t response_size, size_t response_transfer_size) { + assert(_object); + if (_object->_status == Type::Link::ACTIVE) { + RNS::RequestReceipt remove = {Type::NONE}; + for (RNS::RequestReceipt pending_request : _object->_pending_requests) { + if (pending_request.request_id() == request_id) { + remove = pending_request; + try { + pending_request.response_size(response_size); + //if (pending_request.response_transfer_size == 0) { + // pending_request.response_transfer_size = 0; + //} + pending_request.response_transfer_size(pending_request.response_transfer_size() + response_transfer_size); + pending_request.response_received(response_data); + } + catch (std::exception& e) { + ERRORF("Error occurred while handling response. The contained exception was: %s", e.what()); + } + break; + } + } + if (remove) { + if (_object->_pending_requests.count(remove) > 0) { + _object->_pending_requests.erase(remove); + } + } + } +} - if len(packed_response) <= Link.MDU: - RNS.Packet(self, packed_response, RNS.Packet.DATA, context = RNS.Packet.RESPONSE).send() - else: - response_resource = RNS.Resource(packed_response, self, request_id = request_id, is_response = True) - else: - identity_string = str(self.get_remote_identity()) if self.get_remote_identity() != None else "" - RNS.log("Request "+RNS.prettyhexrep(request_id)+" from "+identity_string+" not allowed for: "+str(path), RNS.LOG_DEBUG) +void Link::request_resource_concluded(const Resource& resource) { + assert(_object); + if (resource.status() == Type::Resource::COMPLETE) { + //p packed_request = resource.data().read() + Bytes packed_request = resource.data(); + //p unpacked_request = umsgpack.unpackb(packed_request) + MsgPack::Unpacker unpacker; + unpacker.feed(packed_request.data(), packed_request.size()); + // CBA TODO OPTIMIZE MSGPACK + double requested_at; + MsgPack::bin_t path_hash; + MsgPack::bin_t request_data; + unpacker.from_array(requested_at, path_hash, request_data); + ResourceRequest resource_request; + resource_request._requested_at = requested_at; + resource_request._path_hash = path_hash; + resource_request._request_data = request_data; + //p request_id = RNS.Identity.truncated_hash(packed_request) + Bytes request_id(Identity::truncated_hash(resource.data())); + //p request_data = unpacked_request -def handle_response(self, request_id, response_data, response_size, response_transfer_size): - if self.status == Link.ACTIVE: - remove = None - for pending_request in self.pending_requests: - if pending_request.request_id == request_id: - remove = pending_request - try: - pending_request.response_size = response_size - if pending_request.response_transfer_size == None: - pending_request.response_transfer_size = 0 - pending_request.response_transfer_size += response_transfer_size - pending_request.response_received(response_data) - except Exception as e: - RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR) + //p handle_request(request_id, request_data) + handle_request(request_id, resource_request); + } + else { + DEBUGF("Incoming request resource failed with status: %d", resource.status()); + } +} - break +void Link::response_resource_concluded(const Resource& resource) { + assert(_object); + if (resource.status() == Type::Resource::COMPLETE) { + //p packed_response = resource.data.read() + Bytes packed_response = resource.data(); + //p unpacked_response = umsgpack.unpackb(packed_response) + //p request_id = unpacked_response[0] + //p response_data = unpacked_response[1] + MsgPack::Unpacker unpacker; + unpacker.feed(packed_response.data(), packed_response.size()); + MsgPack::bin_t request_id; + MsgPack::bin_t response_data; + unpacker.from_array(request_id, response_data); - if remove != None: - if remove in self.pending_requests: - self.pending_requests.remove(remove) + handle_response(request_id, response_data, resource.total_size(), resource.size()); + } + else { + DEBUGF("Incoming response resource failed with status: %d", resource.status()); + for (RNS::RequestReceipt pending_request : _object->_pending_requests) { + if (pending_request.request_id() == resource.request_id()) { + pending_request.request_timed_out({Type::NONE}); + } + } + } +} -def request_resource_concluded(self, resource): - if resource.status == RNS.Resource.COMPLETE: - packed_request = resource.data.read() - unpacked_request = umsgpack.unpackb(packed_request) - request_id = RNS.Identity.truncated_hash(packed_request) - request_data = unpacked_request - self.handle_request(request_id, request_data) - else: - RNS.log("Incoming request resource failed with status: "+RNS.hexrep([resource.status]), RNS.LOG_DEBUG) +/*z +""" +Get the ``Channel`` for this link. -def response_resource_concluded(self, resource): - if resource.status == RNS.Resource.COMPLETE: - packed_response = resource.data.read() - unpacked_response = umsgpack.unpackb(packed_response) - request_id = unpacked_response[0] - response_data = unpacked_response[1] +:return: ``Channel`` object +""" +void Link::get_channel() { + assert(_object); + if _object->_channel is None: + _object->_channel = Channel(LinkChannelOutlet(self)) + return _object->_channel +*/ - self.handle_response(request_id, response_data, resource.total_size, resource.size) - else: - RNS.log("Incoming response resource failed with status: "+RNS.hexrep([resource.status]), RNS.LOG_DEBUG) - for pending_request in self.pending_requests: - if pending_request.request_id == resource.request_id: - pending_request.request_timed_out(None) +/* +void Link::receive(const Packet& packet) { +} +*/ +void Link::receive(const Packet& packet) { + assert(_object); + _object->_watchdog_lock = true; + if (_object->_status != Type::Link::CLOSED && !(_object->_initiator && packet.context() == Type::Packet::KEEPALIVE && packet.data() == "\xFF")) { + if (packet.receiving_interface() != _object->_attached_interface) { + ERROR("Link-associated packet received on unexpected interface! Someone might be trying to manipulate your communication!"); + } + else { + _object->_last_inbound = OS::time(); + if (packet.context() != Type::Packet::KEEPALIVE) { + _object->_last_data = _object->_last_inbound; + } + _object->_rx += 1; + _object->_rxbytes += packet.data().size(); + if (_object->_status == STALE) { + _object->_status = Type::Link::ACTIVE; + } -def get_channel(self): - """ - Get the ``Channel`` for this link. - - :return: ``Channel`` object - """ - if self._channel is None: - self._channel = Channel(LinkChannelOutlet(self)) - return self._channel - -def receive(self, packet): - self.watchdog_lock = True - if not self.status == Link.CLOSED and not (self.initiator and packet.context == RNS.Packet.KEEPALIVE and packet.data == bytes([0xFF])): - if packet.receiving_interface != self.attached_interface: - RNS.log("Link-associated packet received on unexpected interface! Someone might be trying to manipulate your communication!", RNS.LOG_ERROR) - else: - self.last_inbound = time.time() - if packet.context != RNS.Packet.KEEPALIVE: - self.last_data = self.last_inbound - self.rx += 1 - self.rxbytes += len(packet.data) - if self.status == Link.STALE: - self.status = Link.ACTIVE - - if packet.packet_type == RNS.Packet.DATA: - should_query = False - if packet.context == RNS.Packet.NONE: - plaintext = self.decrypt(packet.data) - if plaintext != None: - if self.callbacks.packet != None: - thread = threading.Thread(target=self.callbacks.packet, args=(plaintext, packet)) - thread.daemon = True - thread.start() + if (packet.packet_type() == Type::Packet::DATA) { + bool should_query = false; + switch (packet.context()) { + case Type::Packet::CONTEXT_NONE: + { + const Bytes plaintext = decrypt(packet.data()); + if (plaintext) { + if (_object->_callbacks._packet) { + //z thread = threading.Thread(target=_object->_callbacks.packet, args=(plaintext, packet)) + //z thread.daemon = True + //z thread.start() + try { + _object->_callbacks._packet(plaintext, packet); + } + catch (std::exception& e) { + ERRORF("Error while executing packet callback from %s. The contained exception was: %s", toString().c_str(), e.what()); + } + } - if self.destination.proof_strategy == RNS.Destination.PROVE_ALL: - packet.prove() - should_query = True + if (_object->_destination.proof_strategy() == Type::Destination::PROVE_ALL) { + const_cast(packet).prove(); + should_query = true; + } + else if (_object->_destination.proof_strategy() == Type::Destination::PROVE_APP) { + if (_object->_destination.callbacks()._proof_requested) { + try { + if (_object->_destination.callbacks()._proof_requested(packet)) { + const_cast(packet).prove(); + should_query = true; + } + } + catch (std::exception& e) { + ERRORF("Error while executing proof request callback from %s. The contained exception was: %s", toString().c_str(), e.what()); + } + } + } + } + break; + } + case Type::Packet::LINKIDENTIFY: + { + const Bytes plaintext = decrypt(packet.data()); + if (plaintext) { + if (_object->_initiator && plaintext.size() == Type::Identity::KEYSIZE/8 + Type::Identity::SIGLENGTH/8) { + const Bytes public_key = plaintext.left(Type::Identity::KEYSIZE/8); + const Bytes signed_data = _object->_link_id + public_key; + const Bytes signature = plaintext.mid(Type::Identity::KEYSIZE/8, Type::Identity::SIGLENGTH/8); + Identity identity(false); + identity.load_public_key(public_key); - elif self.destination.proof_strategy == RNS.Destination.PROVE_APP: - if self.destination.callbacks.proof_requested: - try: - if self.destination.callbacks.proof_requested(packet): - packet.prove() - should_query = True - except Exception as e: - RNS.log("Error while executing proof request callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - - self.__update_phy_stats(packet, query_shared=should_query) - - elif packet.context == RNS.Packet.LINKIDENTIFY: - plaintext = self.decrypt(packet.data) - if plaintext != None: - if not self.initiator and len(plaintext) == RNS.Identity.KEYSIZE//8 + RNS.Identity.SIGLENGTH//8: - public_key = plaintext[:RNS.Identity.KEYSIZE//8] - signed_data = self.link_id+public_key - signature = plaintext[RNS.Identity.KEYSIZE//8:RNS.Identity.KEYSIZE//8+RNS.Identity.SIGLENGTH//8] - identity = RNS.Identity(create_keys=False) - identity.load_public_key(public_key) - - if identity.validate(signature, signed_data): - self.__remote_identity = identity - if self.callbacks.remote_identified != None: - try: - self.callbacks.remote_identified(self, self.__remote_identity) - except Exception as e: - RNS.log("Error while executing remote identified callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - - self.__update_phy_stats(packet, query_shared=True) - - elif packet.context == RNS.Packet.REQUEST: - try: - request_id = packet.getTruncatedHash() - packed_request = self.decrypt(packet.data) - if packed_request != None: - unpacked_request = umsgpack.unpackb(packed_request) - self.handle_request(request_id, unpacked_request) - self.__update_phy_stats(packet, query_shared=True) - except Exception as e: - RNS.log("Error occurred while handling request. The contained exception was: "+str(e), RNS.LOG_ERROR) - - elif packet.context == RNS.Packet.RESPONSE: - try: - packed_response = self.decrypt(packet.data) - if packed_response != None: - unpacked_response = umsgpack.unpackb(packed_response) - request_id = unpacked_response[0] - response_data = unpacked_response[1] - transfer_size = len(umsgpack.packb(response_data))-2 - self.handle_response(request_id, response_data, transfer_size, transfer_size) - self.__update_phy_stats(packet, query_shared=True) - except Exception as e: - RNS.log("Error occurred while handling response. The contained exception was: "+str(e), RNS.LOG_ERROR) - - elif packet.context == RNS.Packet.LRRTT: - if not self.initiator: - self.rtt_packet(packet) - self.__update_phy_stats(packet, query_shared=True) - - elif packet.context == RNS.Packet.LINKCLOSE: - self.teardown_packet(packet) - self.__update_phy_stats(packet, query_shared=True) - - elif packet.context == RNS.Packet.RESOURCE_ADV: - packet.plaintext = self.decrypt(packet.data) - if packet.plaintext != None: - self.__update_phy_stats(packet, query_shared=True) - - if RNS.ResourceAdvertisement.is_request(packet): - RNS.Resource.accept(packet, callback=self.request_resource_concluded) - elif RNS.ResourceAdvertisement.is_response(packet): - request_id = RNS.ResourceAdvertisement.read_request_id(packet) - for pending_request in self.pending_requests: - if pending_request.request_id == request_id: - response_resource = RNS.Resource.accept(packet, callback=self.response_resource_concluded, progress_callback=pending_request.response_resource_progress, request_id = request_id) - if response_resource != None: - if pending_request.response_size == None: - pending_request.response_size = RNS.ResourceAdvertisement.read_size(packet) - if pending_request.response_transfer_size == None: - pending_request.response_transfer_size = 0 - pending_request.response_transfer_size += RNS.ResourceAdvertisement.read_transfer_size(packet) - if pending_request.started_at == None: - pending_request.started_at = time.time() - pending_request.response_resource_progress(response_resource) - - elif self.resource_strategy == Link.ACCEPT_NONE: - pass - elif self.resource_strategy == Link.ACCEPT_APP: - if self.callbacks.resource != None: - try: - resource_advertisement = RNS.ResourceAdvertisement.unpack(packet.plaintext) - resource_advertisement.link = self - if self.callbacks.resource(resource_advertisement): - RNS.Resource.accept(packet, self.callbacks.resource_concluded) - except Exception as e: - RNS.log("Error while executing resource accept callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - elif self.resource_strategy == Link.ACCEPT_ALL: - RNS.Resource.accept(packet, self.callbacks.resource_concluded) - - elif packet.context == RNS.Packet.RESOURCE_REQ: - plaintext = self.decrypt(packet.data) - if plaintext != None: - self.__update_phy_stats(packet, query_shared=True) + if (identity.validate(signature, signed_data)) { + _object->__remote_identity = identity; + if (_object->_callbacks._remote_identified) { + try { + _object->_callbacks._remote_identified(*this, _object->__remote_identity); + } + catch (std::exception& e) { + ERRORF("Error while executing remote identified callback from %s. The contained exception was: %s", toString().c_str(), e.what()); + } + } + } + } + } + break; + } + case Type::Packet::REQUEST: + { + try { + const Bytes request_id = packet.getTruncatedHash(); + const Bytes packed_request = decrypt(packet.data()); + if (packed_request) { + //p unpacked_request = umsgpack.unpackb(packed_request) + MsgPack::Unpacker unpacker; + unpacker.feed(packed_request.data(), packed_request.size()); + // CBA TODO OPTIMIZE MSGPACK + double requested_at; + MsgPack::bin_t path_hash; + MsgPack::bin_t request_data; + unpacker.from_array(requested_at, path_hash, request_data); + ResourceRequest resource_request; + resource_request._requested_at = requested_at; + resource_request._path_hash = path_hash; + resource_request._request_data = request_data; + handle_request(request_id, resource_request); + } + } + catch (std::exception& e) { + ERRORF("Error occurred while handling request. The contained exception was: %s", e.what()); + } + break; + } + case Type::Packet::RESPONSE: + { + try { + const Bytes packed_response = decrypt(packet.data()); + if (packed_response) { + //p unpacked_response = umsgpack.unpackb(packed_response) + //p request_id = unpacked_response[0] + //p response_data = unpacked_response[1] + //p transfer_size = len(umsgpack.packb(response_data))-2 + MsgPack::Unpacker unpacker; + unpacker.feed(packed_response.data(), packed_response.size()); + MsgPack::bin_t request_id; + MsgPack::bin_t response_data; + unpacker.from_array(request_id, response_data); + MsgPack::Packer packer; + packer.serialize(response_data); + size_t transfer_size = packer.size() - 2; + handle_response(Bytes(request_id.data(), request_id.size()), Bytes(response_data.data(), response_data.size()), transfer_size, transfer_size); + } + } + catch (std::exception& e) { + ERRORF("Error occurred while handling response. The contained exception was: %s", e.what()); + } + break; + } + case Type::Packet::LRRTT: + { + if (!_object->_initiator) { + rtt_packet(packet); + } + } + case Type::Packet::LINKCLOSE: + { + teardown_packet(packet); + break; + } +/*z + case Type::Packet::RESOURCE_ADV: + { + //p packet.plaintext = decrypt(packet.data) + const Bytes plaintext = decrypt(packet.data()); + if (plaintext) { + const_cast(packet).plaintext(plaintext); + if (ResourceAdvertisement::is_request(packet)) { + Resource::accept(packet, callback=_object->_request_resource_concluded); + } + else if (ResourceAdvertisement::is_response(packet)) { + Bytes request_id = ResourceAdvertisement::read_request_id(packet) + for (auto& pending_request : _object->_pending_requests) { + if (pending_request.request_id == request_id) { + const Bytes response_resource = Resource::accept(packet, callback=_object->_response_resource_concluded, progress_callback=pending_request.response_resource_progress, request_id = request_id); + if (response_resource) { + //p if pending_request.response_size == None: + if (pending_request.response_size == 0) { + pending_request.response_size = ResourceAdvertisement::read_size(packet); + } + //p if pending_request.response_transfer_size == None: + if (pending_request.response_transfer_size == 0) { + pending_request.response_transfer_size = 0; + } + pending_request.response_transfer_size += ResourceAdvertisement::read_transfer_size(packet); + //p if pending_request.started_at == None: + if (pending_request.started_at == 0.0) { + pending_request.started_at = OS::time(); + } + pending_request.response_resource_progress(response_resource); + } + } + } + } + else if (_object->_resource_strategy == ACCEPT_NONE) { + //p pass + } + else if (_object->_resource_strategy == ACCEPT_APP) { + if (_object->_callbacks.resource) { + try { + resource_advertisement = RNS.ResourceAdvertisement.unpack(packet.plaintext()); + resource_advertisement.link = *this; + if (_object->_callbacks.resource(resource_advertisement)) { + Resource::accept(packet, _object->_callbacks.resource_concluded); + } + } + catch (std::exception& e) { + ERRORF("Error while executing resource accept callback from %s. The contained exception was: %s", toString().c_str(), e.what()); + } + elif _object->_resource_strategy == ACCEPT_ALL: + RNS.Resource.accept(packet, _object->_callbacks.resource_concluded) + break; + } + case Type::Packet::RESOURCE_REQ: + { + const Bytes plaintext = decrypt(packet.data()); + if (plaintext) { if ord(plaintext[:1]) == RNS.Resource.HASHMAP_IS_EXHAUSTED: - resource_hash = plaintext[1+RNS.Resource.MAPHASH_LEN:RNS.Identity.HASHLENGTH//8+1+RNS.Resource.MAPHASH_LEN] + resource_hash = plaintext[1+RNS.Resource.MAPHASH_LEN:Type::Identity::HASHLENGTH//8+1+RNS.Resource.MAPHASH_LEN] else: - resource_hash = plaintext[1:RNS.Identity.HASHLENGTH//8+1] + resource_hash = plaintext[1:Type::Identity::HASHLENGTH//8+1] - for resource in self.outgoing_resources: + for resource in _object->_outgoing_resources: if resource.hash == resource_hash: - # We need to check that this request has not been - # received before in order to avoid sequencing errors. + // We need to check that this request has not been + // received before in order to avoid sequencing errors. if not packet.packet_hash in resource.req_hashlist: resource.req_hashlist.append(packet.packet_hash) resource.request(plaintext) - - elif packet.context == RNS.Packet.RESOURCE_HMU: - plaintext = self.decrypt(packet.data) - if plaintext != None: - self.__update_phy_stats(packet, query_shared=True) - resource_hash = plaintext[:RNS.Identity.HASHLENGTH//8] - for resource in self.incoming_resources: + break; + } + case Type::Packet::RESOURCE_HMU: + { + const Bytes plaintext = decrypt(packet.data()); + if (plaintext) { + resource_hash = plaintext[:Type::Identity::HASHLENGTH//8] + for resource in _object->_incoming_resources: if resource_hash == resource.hash: resource.hashmap_update_packet(plaintext) - - elif packet.context == RNS.Packet.RESOURCE_ICL: - plaintext = self.decrypt(packet.data) - if plaintext != None: - self.__update_phy_stats(packet) - resource_hash = plaintext[:RNS.Identity.HASHLENGTH//8] - for resource in self.incoming_resources: + break; + } + case Type::Packet::RESOURCE_ICL: + { + const Bytes plaintext = decrypt(packet.data()); + if (plaintext) { + resource_hash = plaintext[:Type::Identity::HASHLENGTH//8] + for resource in _object->_incoming_resources: if resource_hash == resource.hash: resource.cancel() - - elif packet.context == RNS.Packet.KEEPALIVE: - if not self.initiator and packet.data == bytes([0xFF]): - keepalive_packet = RNS.Packet(self, bytes([0xFE]), context=RNS.Packet.KEEPALIVE) - keepalive_packet.send() - self.had_outbound(is_keepalive = True) - - - # TODO: find the most efficient way to allow multiple - # transfers at the same time, sending resource hash on - # each packet is a huge overhead. Probably some kind - # of hash -> sequence map - elif packet.context == RNS.Packet.RESOURCE: - for resource in self.incoming_resources: - resource.receive_part(packet) - self.__update_phy_stats(packet) - - elif packet.context == RNS.Packet.CHANNEL: - if not self._channel: - RNS.log(f"Channel data received without open channel", RNS.LOG_DEBUG) - else: - packet.prove() - plaintext = self.decrypt(packet.data) - if plaintext != None: - self.__update_phy_stats(packet) - self._channel._receive(plaintext) - - elif packet.packet_type == RNS.Packet.PROOF: - if packet.context == RNS.Packet.RESOURCE_PRF: - resource_hash = packet.data[0:RNS.Identity.HASHLENGTH//8] - for resource in self.outgoing_resources: - if resource_hash == resource.hash: - resource.validate_proof(packet.data) - self.__update_phy_stats(packet, query_shared=True) - - self.watchdog_lock = False - - -def encrypt(self, plaintext): - try: - if not self.fernet: - try: - self.fernet = Fernet(self.derived_key) - except Exception as e: - RNS.log("Could not instantiate Fernet while performin encryption on link "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - raise e - - return self.fernet.encrypt(plaintext) - - except Exception as e: - RNS.log("Encryption on link "+str(self)+" failed. The contained exception was: "+str(e), RNS.LOG_ERROR) - raise e - - -def decrypt(self, ciphertext): - try: - if not self.fernet: - self.fernet = Fernet(self.derived_key) - - return self.fernet.decrypt(ciphertext) - - except Exception as e: - RNS.log("Decryption failed on link "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - return None - - -def sign(self, message): - return self.sig_prv.sign(message) - -def validate(self, signature, message): - try: - self.peer_sig_pub.verify(signature, message) - return True - except Exception as e: - return False - -def set_link_established_callback(self, callback): - self.callbacks.link_established = callback - -def set_link_closed_callback(self, callback): - """ - Registers a function to be called when a link has been - torn down. - - :param callback: A function or method with the signature *callback(link)* to be called. - """ - self.callbacks.link_closed = callback - -def set_packet_callback(self, callback): - """ - Registers a function to be called when a packet has been - received over this link. - - :param callback: A function or method with the signature *callback(message, packet)* to be called. - """ - self.callbacks.packet = callback - -def set_resource_callback(self, callback): - """ - Registers a function to be called when a resource has been - advertised over this link. If the function returns *True* - the resource will be accepted. If it returns *False* it will - be ignored. - - :param callback: A function or method with the signature *callback(resource)* to be called. Please note that only the basic information of the resource is available at this time, such as *get_transfer_size()*, *get_data_size()*, *get_parts()* and *is_compressed()*. - """ - self.callbacks.resource = callback - -def set_resource_started_callback(self, callback): - """ - Registers a function to be called when a resource has begun - transferring over this link. - - :param callback: A function or method with the signature *callback(resource)* to be called. - """ - self.callbacks.resource_started = callback - -def set_resource_concluded_callback(self, callback): - """ - Registers a function to be called when a resource has concluded - transferring over this link. - - :param callback: A function or method with the signature *callback(resource)* to be called. - """ - self.callbacks.resource_concluded = callback - -def set_remote_identified_callback(self, callback): - """ - Registers a function to be called when an initiating peer has - identified over this link. - - :param callback: A function or method with the signature *callback(link, identity)* to be called. - """ - self.callbacks.remote_identified = callback - -def resource_concluded(self, resource): - if resource in self.incoming_resources: - self.incoming_resources.remove(resource) - if resource in self.outgoing_resources: - self.outgoing_resources.remove(resource) - -def set_resource_strategy(self, resource_strategy): - """ - Sets the resource strategy for the link. - - :param resource_strategy: One of ``RNS.Link.ACCEPT_NONE``, ``RNS.Link.ACCEPT_ALL`` or ``RNS.Link.ACCEPT_APP``. If ``RNS.Link.ACCEPT_APP`` is set, the `resource_callback` will be called to determine whether the resource should be accepted or not. - :raises: *TypeError* if the resource strategy is unsupported. - """ - if not resource_strategy in Link.resource_strategies: - raise TypeError("Unsupported resource strategy") - else: - self.resource_strategy = resource_strategy - -def register_outgoing_resource(self, resource): - self.outgoing_resources.append(resource) - -def register_incoming_resource(self, resource): - self.incoming_resources.append(resource) - -def has_incoming_resource(self, resource): - for incoming_resource in self.incoming_resources: - if incoming_resource.hash == resource.hash: - return True - - return False - -def cancel_outgoing_resource(self, resource): - if resource in self.outgoing_resources: - self.outgoing_resources.remove(resource) - else: - RNS.log("Attempt to cancel a non-existing outgoing resource", RNS.LOG_ERROR) - -def cancel_incoming_resource(self, resource): - if resource in self.incoming_resources: - self.incoming_resources.remove(resource) - else: - RNS.log("Attempt to cancel a non-existing incoming resource", RNS.LOG_ERROR) - -def ready_for_new_resource(self): - if len(self.outgoing_resources) > 0: - return False - else: - return True - -def __str__(self): - return RNS.prettyhexrep(self.link_id) - - -class RequestReceipt(): -""" -An instance of this class is returned by the ``request`` method of ``RNS.Link`` -instances. It should never be instantiated manually. It provides methods to -check status, response time and response data when the request concludes. -""" - -FAILED = 0x00 -SENT = 0x01 -DELIVERED = 0x02 -RECEIVING = 0x03 -READY = 0x04 - -def __init__(self, link, packet_receipt = None, resource = None, response_callback = None, failed_callback = None, progress_callback = None, timeout = None, request_size = None): - self.packet_receipt = packet_receipt - self.resource = resource - self.started_at = None - - if self.packet_receipt != None: - self.hash = packet_receipt.truncated_hash - self.packet_receipt.set_timeout_callback(self.request_timed_out) - self.started_at = time.time() - - elif self.resource != None: - self.hash = resource.request_id - resource.set_callback(self.request_resource_concluded) - - self.link = link - self.request_id = self.hash - self.request_size = request_size - - self.response = None - self.response_transfer_size = None - self.response_size = None - self.status = RequestReceipt.SENT - self.sent_at = time.time() - self.progress = 0 - self.concluded_at = None - self.response_concluded_at = None - - if timeout != None: - self.timeout = timeout - else: - raise ValueError("No timeout specified for request receipt") - - self.callbacks = RequestReceiptCallbacks() - self.callbacks.response = response_callback - self.callbacks.failed = failed_callback - self.callbacks.progress = progress_callback - - self.link.pending_requests.append(self) - - -def request_resource_concluded(self, resource): - if resource.status == RNS.Resource.COMPLETE: - RNS.log("Request "+RNS.prettyhexrep(self.request_id)+" successfully sent as resource.", RNS.LOG_DEBUG) - if self.started_at == None: - self.started_at = time.time() - self.status = RequestReceipt.DELIVERED - self.__resource_response_timeout = time.time()+self.timeout - response_timeout_thread = threading.Thread(target=self.__response_timeout_job) - response_timeout_thread.daemon = True - response_timeout_thread.start() - else: - RNS.log("Sending request "+RNS.prettyhexrep(self.request_id)+" as resource failed with status: "+RNS.hexrep([resource.status]), RNS.LOG_DEBUG) - self.status = RequestReceipt.FAILED - self.concluded_at = time.time() - self.link.pending_requests.remove(self) - - if self.callbacks.failed != None: - try: - self.callbacks.failed(self) - except Exception as e: - RNS.log("Error while executing request failed callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - - -def __response_timeout_job(self): - while self.status == RequestReceipt.DELIVERED: - now = time.time() - if now > self.__resource_response_timeout: - self.request_timed_out(None) - - time.sleep(0.1) - - -def request_timed_out(self, packet_receipt): - self.status = RequestReceipt.FAILED - self.concluded_at = time.time() - self.link.pending_requests.remove(self) - - if self.callbacks.failed != None: - try: - self.callbacks.failed(self) - except Exception as e: - RNS.log("Error while executing request timed out callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - - -def response_resource_progress(self, resource): - if resource != None: - if not self.status == RequestReceipt.FAILED: - self.status = RequestReceipt.RECEIVING - if self.packet_receipt != None: - if self.packet_receipt.status != RNS.PacketReceipt.DELIVERED: - self.packet_receipt.status = RNS.PacketReceipt.DELIVERED - self.packet_receipt.proved = True - self.packet_receipt.concluded_at = time.time() - if self.packet_receipt.callbacks.delivery != None: - self.packet_receipt.callbacks.delivery(self.packet_receipt) - - self.progress = resource.get_progress() - - if self.callbacks.progress != None: - try: - self.callbacks.progress(self) - except Exception as e: - RNS.log("Error while executing response progress callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - else: - resource.cancel() - - -def response_received(self, response): - if not self.status == RequestReceipt.FAILED: - self.progress = 1.0 - self.response = response - self.status = RequestReceipt.READY - self.response_concluded_at = time.time() - - if self.packet_receipt != None: - self.packet_receipt.status = RNS.PacketReceipt.DELIVERED - self.packet_receipt.proved = True - self.packet_receipt.concluded_at = time.time() - if self.packet_receipt.callbacks.delivery != None: - self.packet_receipt.callbacks.delivery(self.packet_receipt) - - if self.callbacks.progress != None: - try: - self.callbacks.progress(self) - except Exception as e: - RNS.log("Error while executing response progress callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - - if self.callbacks.response != None: - try: - self.callbacks.response(self) - except Exception as e: - RNS.log("Error while executing response received callback from "+str(self)+". The contained exception was: "+str(e), RNS.LOG_ERROR) - -def get_request_id(self): - """ - :returns: The request ID as *bytes*. - """ - return self.request_id - -def get_status(self): - """ - :returns: The current status of the request, one of ``RNS.RequestReceipt.FAILED``, ``RNS.RequestReceipt.SENT``, ``RNS.RequestReceipt.DELIVERED``, ``RNS.RequestReceipt.READY``. - """ - return self.status - -def get_progress(self): - """ - :returns: The progress of a response being received as a *float* between 0.0 and 1.0. - """ - return self.progress - -def get_response(self): - """ - :returns: The response as *bytes* if it is ready, otherwise *None*. - """ - if self.status == RequestReceipt.READY: - return self.response - else: - return None - -def get_response_time(self): - """ - :returns: The response time of the request in seconds. - """ - if self.status == RequestReceipt.READY: - return self.response_concluded_at - self.started_at - else: - return None - + break; + } */ + case Type::Packet::KEEPALIVE: + { + if (!_object->_initiator && packet.data() == "\xFF") { + //p keepalive_packet = RNS.Packet(self, bytes([0xFE]), context=RNS.Packet.KEEPALIVE) + Packet keepalive_packet(_object->_link_destination, Bytes("\xFE"), Type::Packet::DATA, Type::Packet::KEEPALIVE); + keepalive_packet.send(); + had_outbound(true); + } + break; + } + // TODO: find the most efficient way to allow multiple + // transfers at the same time, sending resource hash on + // each packet is a huge overhead. Probably some kind + // of hash -> sequence map + case Type::Packet::RESOURCE: + { + for (auto& resource : _object->_incoming_resources) { + //z resource.receive_part(packet); + } + break; + } +/*z + case Type::Packet::CHANNEL: + { + //z if (!_object->_channel) { + if (true) { + DEBUG(f"Channel data received without open channel") + } + else { + //z packet.prove(); + //z plaintext = decrypt(packet.data()); + //z if (plaintext) { + //z _object->_channel._receive(plaintext); + //z } + } + break; + } +*/ + } + } + else if (packet.packet_type() == Type::Packet::PROOF) { + if (packet.context() == Type::Packet::RESOURCE_PRF) { + Bytes resource_hash = packet.data().left(Type::Identity::HASHLENGTH/8); + for (const auto& resource : _object->_outgoing_resources) { + if (resource_hash == resource.hash()) { + //z resource.validate_proof(packet.data()); + } + } + } + } + } + } + + _object->_watchdog_lock = false; +} + +const Bytes Link::encrypt(const Bytes& plaintext) { + assert(_object); + try { + if (!_object->_fernet) { + try { + _object->_fernet.reset(new Fernet(_object->_derived_key)); + } + catch (std::exception& e) { + ERRORF("Could not instantiate Fernet while performin encryption on link %s. The contained exception was: %s", toString().c_str(), e.what()); + throw e; + } + } + return _object->_fernet->encrypt(plaintext); + } + catch (std::exception& e) { + ERRORF("Encryption on link %s failed. The contained exception was: %s", toString().c_str(), e.what()); + throw e; + } +} + +const Bytes Link::decrypt(const Bytes& ciphertext) { + assert(_object); + try { + if (!_object->_fernet) { + _object->_fernet.reset(new Fernet(_object->_derived_key)); + } + return _object->_fernet->decrypt(ciphertext); + } + catch (std::exception& e) { + ERRORF("Decryption failed on link %s. The contained exception was: %s", toString().c_str(), e.what()); + return {Bytes::NONE}; + } +} + +const Bytes Link::sign(const Bytes& message) { + assert(_object); + return _object->_sig_prv->sign(message); +} + +bool Link::validate(const Bytes& signature, const Bytes& message) { + assert(_object); + try { + _object->_peer_sig_pub->verify(signature, message); + return true; + } + catch (std::exception& e) { + return false; + } +} + +void Link::set_link_established_callback(Callbacks::established callback) { + assert(_object); + _object->_callbacks._established = callback; +} + +void Link::set_link_closed_callback(Callbacks::closed callback) { + assert(_object); + _object->_callbacks._closed = callback; +} + +void Link::set_packet_callback(Callbacks::packet callback) { + assert(_object); + _object->_callbacks._packet = callback; +} + +void Link::set_remote_identified_callback(Callbacks::remote_identified callback) { + assert(_object); + _object->_callbacks._remote_identified = callback; +} + +void Link::set_resource_callback(Callbacks::resource callback) { + assert(_object); + _object->_callbacks._resource = callback; +} + +void Link::set_resource_started_callback(Callbacks::resource_started callback) { + assert(_object); + _object->_callbacks._resource_started = callback; +} + +void Link::set_resource_concluded_callback(Callbacks::resource_concluded callback) { + assert(_object); + _object->_callbacks._resource_concluded = callback; +} + + +void Link::resource_concluded(const Resource& resource) { + assert(_object); + if (_object->_incoming_resources.count(resource) > 0) { + _object->_incoming_resources.erase(resource); + } + if (_object->_outgoing_resources.count(resource) > 0) { + _object->_outgoing_resources.erase(resource); + } +} + +/* +Sets the resource strategy for the link. + +:param resource_strategy: One of ``RNS.ACCEPT_NONE``, ``RNS.ACCEPT_ALL`` or ``RNS.ACCEPT_APP``. If ``RNS.ACCEPT_APP`` is set, the `resource_callback` will be called to determine whether the resource should be accepted or not. +:raises: *TypeError* if the resource strategy is unsupported. +*/ +void Link::set_resource_strategy(resource_strategy strategy) { + assert(_object); + if ((strategy & resource_strategies) > 0) { + throw std::runtime_error("Unsupported resource strategy"); + } + else { + _object->_resource_strategy = strategy; + } +} + +void Link::register_outgoing_resource(const Resource& resource) { + assert(_object); + _object->_outgoing_resources.insert(resource); +} + +void Link::register_incoming_resource(const Resource& resource) { + assert(_object); + _object->_incoming_resources.insert(resource); +} + +bool Link::has_incoming_resource(const Resource& resource) { + assert(_object); + for (const auto& incoming_resource : _object->_incoming_resources) { + if (incoming_resource.hash() == resource.hash()) { + return true; + } + } + return false; +} + +void Link::cancel_outgoing_resource(const Resource& resource) { + assert(_object); + if (_object->_outgoing_resources.count(resource) > 0) { + _object->_outgoing_resources.erase(resource); + } + else { + ERROR("Attempt to cancel a non-existing outgoing resource"); + } +} + +void Link::cancel_incoming_resource(const Resource& resource) { + assert(_object); + if (_object->_incoming_resources.count(resource)) { + _object->_incoming_resources.erase(resource); + } + else { + ERROR("Attempt to cancel a non-existing incoming resource"); + } +} + +bool Link::ready_for_new_resource() { + assert(_object); + return (_object->_outgoing_resources.size() > 0); +} + +std::string Link::toString() const { + if (!_object) { + return ""; + } + return "{Link:" + _object->_link_id.toHex() + "}"; +} + +// getters + +const Destination& Link::destination() const { + assert(_object); + return _object->_destination; +} + +const Bytes& Link::link_id() const { + assert(_object); + return _object->_link_id; +} + +const Bytes& Link::hash() const { + assert(_object); + return _object->_hash; +} + +Type::Link::status Link::status() const { + assert(_object); + return _object->_status; +} + +double Link::establishment_timeout() const { + assert(_object); + return _object->_establishment_timeout; +} + +uint16_t Link::establishment_cost() const { + assert(_object); + return _object->_establishment_cost; +} + +double Link::request_time() const { + assert(_object); + return _object->_request_time; +} + +double Link::last_inbound() const { + assert(_object); + return _object->_last_inbound; +} + +std::set& Link::pending_requests() const { + assert(_object); + return _object->_pending_requests; +} + +// setters + +void Link::destination(const Destination& destination) { + assert(_object); + _object->_destination = destination; +} + +void Link::attached_interface(const Interface& interface) { + assert(_object); + _object->_attached_interface = interface; +} + +void Link::establishment_timeout(double timeout) { + assert(_object); + _object->_establishment_timeout = timeout; +} + +void Link::establishment_cost(uint16_t cost) { + assert(_object); + _object->_establishment_cost = cost; +} + +void Link::request_time(double time) { + assert(_object); + _object->_request_time = time; +} + +void Link::last_inbound(double time) { + assert(_object); + _object->_last_inbound = time; +} + + +//RequestReceipt::RequestReceipt(const Link& link, const PacketReceipt& packet_receipt /*= {Type::NONE}*/, const Resource& resource /*= {Type::NONE}*/, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int request_size /*= 0*/) : +RequestReceipt::RequestReceipt(const Link& link, const PacketReceipt& packet_receipt, const Resource& resource, RequestReceipt::Callbacks::response response_callback /*= nullptr*/, RequestReceipt::Callbacks::failed failed_callback /*= nullptr*/, RequestReceipt::Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int request_size /*= 0*/) : + _object(new RequestReceiptData()) +{ + assert(_object); + _object->_packet_receipt = packet_receipt; + _object->_resource = resource; + if (_object->_packet_receipt) { + _object->_hash = packet_receipt.truncated_hash(); + //z _object->_packet_receipt.set_timeout_callback(request_timed_out); + _object->_started_at = OS::time(); + } + else if (_object->_resource) { + _object->_hash = resource.request_id(); + //const_cast(resource).set_concluded_callback(request_resource_concluded); + const_cast(resource).set_concluded_callback(std::bind(&RequestReceipt::request_resource_concluded, this, std::placeholders::_1)); + } + _object->_link = link; + _object->_request_id = _object->_hash; + _object->_request_size = request_size; + _object->_sent_at = OS::time(); + if (timeout != 0.0) { + _object->_timeout = timeout; + } + else { + throw new std::invalid_argument("No timeout specified for request receipt"); + } + + _object->_callbacks._response = response_callback; + _object->_callbacks._failed = failed_callback; + _object->_callbacks._progress = progress_callback; + + _object->_link.pending_requests().insert(*this); +} + +void RequestReceipt::request_resource_concluded(const Resource& resource) { + assert(_object); + if (resource.status() == Type::Resource::COMPLETE) { + DEBUGF("Request %s successfully sent as resource.", _object->_request_id.toHex().c_str()); + if (_object->_started_at == 0.0) { + _object->_started_at = OS::time(); + } + _object->_status = Type::RequestReceipt::DELIVERED; + _object->_resource_response_timeout = OS::time() + _object->_timeout; + //p response_timeout_thread = threading.Thread(target=_object->___response_timeout_job) + //p response_timeout_thread.daemon = True + //p response_timeout_thread.start() + } + else { + DEBUGF("Sending request %s as resource failed with status: %d", _object->_request_id.toHex().c_str(), resource.status()); + _object->_status = Type::RequestReceipt::FAILED; + _object->_concluded_at = OS::time(); + _object->_link.pending_requests().erase(*this); + if (_object->_callbacks._failed != nullptr) { + try { + _object->_callbacks._failed(*this); + } + catch (std::exception& e) { + ERRORF("Error while executing request failed callback from %s. The contained exception was: %s", toString().c_str(), e.what()); + } + } + } +} + + +void RequestReceipt::__response_timeout_job() { + assert(_object); + while (_object->_status == Type::RequestReceipt::DELIVERED) { + double now = OS::time(); + if (now > _object->___resource_response_timeout) { + request_timed_out({Type::NONE}); + } + + OS::sleep(0.1); + } +} + + +void RequestReceipt::request_timed_out(const PacketReceipt& packet_receipt) { + assert(_object); + _object->_status = Type::RequestReceipt::FAILED; + _object->_concluded_at = OS::time(); + _object->_link.pending_requests().erase(*this); + + if (_object->_callbacks._failed != nullptr) { + try { + _object->_callbacks._failed(*this); + } + catch (std::exception& e) { + ERRORF("Error while executing request timed out callback from %s. The contained exception was: %s", toString().c_str(), e.what()); + } + } +} + + +void RequestReceipt::response_resource_progress(const Resource& resource) { + assert(_object); + if (resource) { + if (_object->_status != Type::RequestReceipt::FAILED) { + _object->_status = Type::RequestReceipt::RECEIVING; + if (_object->_packet_receipt) { + if (_object->_packet_receipt.status() != Type::PacketReceipt::DELIVERED) { + _object->_packet_receipt.status(Type::PacketReceipt::DELIVERED); + _object->_packet_receipt.proved(true); + _object->_packet_receipt.concluded_at(OS::time()); + if (_object->_packet_receipt.callbacks()._delivery != nullptr) { + _object->_packet_receipt.callbacks()._delivery(_object->_packet_receipt); + } + } + } + + _object->_progress = resource.get_progress(); + + if (_object->_callbacks._progress != nullptr) { + try { + _object->_callbacks._progress(*this); + } + catch (std::exception& e) { + ERRORF("Error while executing response progress callback from %s. The contained exception was: %s", toString().c_str(), e.what()); + } + } + } + else { + const_cast(resource).cancel(); + } + } +} + +void RequestReceipt::response_received(const Bytes& response) { + assert(_object); + if (_object->_status != Type::RequestReceipt::FAILED) { + _object->_progress = 1.0; + _object->_response = response; + _object->_status = Type::RequestReceipt::READY; + _object->_response_concluded_at = OS::time(); + + if (_object->_packet_receipt) { + _object->_packet_receipt.status(Type::PacketReceipt::DELIVERED); + _object->_packet_receipt.proved(true); + _object->_packet_receipt.concluded_at(OS::time()); + if (_object->_packet_receipt.callbacks()._delivery != nullptr) { + _object->_packet_receipt.callbacks()._delivery(_object->_packet_receipt); + } + } + if (_object->_callbacks._progress != nullptr) { + try { + _object->_callbacks._progress(*this); + } + catch (std::exception& e) { + ERRORF("Error while executing response progress callback from %s. The contained exception was: %s", toString().c_str(), e.what()); + } + } + if (_object->_callbacks._response != nullptr) { + try { + _object->_callbacks._response(*this); + } + catch (std::exception& e) { + ERRORF("Error while executing response received callback from %s. The contained exception was: %s", toString().c_str(), e.what()); + } + } + } +} + +// :returns: The request ID as *bytes*. +const Bytes& RequestReceipt::get_request_id() const { + assert(_object); + return _object->_request_id; +} + +// :returns: The current status of the request, one of ``RNS.RequestReceipt.FAILED``, ``RNS.RequestReceipt.SENT``, ``RNS.RequestReceipt.DELIVERED``, ``RNS.RequestReceipt.READY``. +Type::RequestReceipt::status RequestReceipt::get_status() const { + assert(_object); + return _object->_status; +} + +// :returns: The progress of a response being received as a *float* between 0.0 and 1.0. +float RequestReceipt::get_progress() const { + assert(_object); + return _object->_progress; +} + +// :returns: The response as *bytes* if it is ready, otherwise *None*. +const Bytes RequestReceipt::get_response() const { + assert(_object); + if (_object->_status == Type::RequestReceipt::READY) { + return _object->_response; + } + else { + return Bytes::NONE; + } +} + +// :returns: The response time of the request in seconds. +double RequestReceipt::get_response_time() const { + assert(_object); + if (_object->_status == Type::RequestReceipt::READY) { + return _object->_response_concluded_at - _object->_started_at; + } + else { + return 0.0; + } +} + +std::string RequestReceipt::toString() const { + if (!_object) { + return ""; + } + return "{RequestReceipt:" + _object->_hash.toHex() + "}"; +} + +// getters + +const Bytes& RequestReceipt::hash() const { + assert(_object); + return _object->_hash; +} + +const Bytes& RequestReceipt::request_id() const { + assert(_object); + return _object->_request_id; +} + +const size_t RequestReceipt::response_transfer_size() const { + assert(_object); + return _object->_response_transfer_size; +} + +// setters + +void RequestReceipt::response_size(size_t size) { + assert(_object); + _object->_response_size = size; +} + +void RequestReceipt::response_transfer_size(size_t size) { + assert(_object); + _object->_response_transfer_size = size; +} diff --git a/src/Link.h b/src/Link.h index 24e0e12..11fc4a7 100644 --- a/src/Link.h +++ b/src/Link.h @@ -1,8 +1,6 @@ #pragma once -#include "Packet.h" #include "Destination.h" -#include "Bytes.h" #include "Type.h" #include @@ -10,29 +8,106 @@ namespace RNS { + class ResourceRequest; + class ResourceResponse; + class RequestReceipt; + class Link; + + class LinkData; + class RequestReceiptData; + class Resource; class Packet; + class Destination; + class ResourceAdvertisement; + class PacketReceipt; - - class RequestReceiptCallbacks { - private: - //z self.response = None - //z self.failed = None - //z self.progress = None + class ResourceRequest { + public: + double _requested_at = 0.0; + Bytes _path_hash; + Bytes _request_data; }; - class Link { + class ResourceResponse { + Bytes request_id; + Bytes response_data; + }; /* - This class is used to establish and manage links to other peers. When a - link instance is created, Reticulum will attempt to establish verified - and encrypted connectivity with the specified destination. - - :param destination: A :ref:`RNS.Destination` instance which to establish a link to. - :param established_callback: An optional function or method with the signature *callback(link)* to be called when the link has been established. - :param closed_callback: An optional function or method with the signature *callback(link)* to be called when the link is closed. + An instance of this class is returned by the ``request`` method of ``RNS.Link`` + instances. It should never be instantiated manually. It provides methods to + check status, response time and response data when the request concludes. */ + class RequestReceipt { - static uint8_t resource_strategies; + public: + class Callbacks { + public: + using response = void(*)(const RequestReceipt& packet_receipt); + using failed = void(*)(const RequestReceipt& packet_receipt); + using progress = void(*)(const RequestReceipt& packet_receipt); + public: + response _response = nullptr; + failed _failed = nullptr; + progress _progress = nullptr; + friend class RequestReceipt; + }; + + public: + RequestReceipt(Type::NoneConstructor none) {} + RequestReceipt(const RequestReceipt& request_receipt) : _object(request_receipt._object) {} + //RequestReceipt(const Link& link, const PacketReceipt& packet_receipt = {Type::NONE}, const Resource& resource = {Type::NONE}, RequestReceipt::Callbacks::response response_callback = nullptr, RequestReceipt::Callbacks::failed failed_callback = nullptr, RequestReceipt::Callbacks::progress progress_callback = nullptr, double timeout = 0.0, int request_size = 0); + RequestReceipt(const Link& link, const PacketReceipt& packet_receipt, const Resource& resource, RequestReceipt::Callbacks::response response_callback = nullptr, RequestReceipt::Callbacks::failed failed_callback = nullptr, RequestReceipt::Callbacks::progress progress_callback = nullptr, double timeout = 0.0, int request_size = 0); + + inline RequestReceipt& operator = (const RequestReceipt& packet_receipt) { + _object = packet_receipt._object; + return *this; + } + inline operator bool() const { + return _object.get() != nullptr; + } + inline bool operator < (const RequestReceipt& packet_receipt) const { + return _object.get() < packet_receipt._object.get(); + } + + public: + void request_resource_concluded(const Resource& resource); + void __response_timeout_job(); + void request_timed_out(const PacketReceipt& packet_receipt); + void response_resource_progress(const Resource& resource); + void response_received(const Bytes& response); + const Bytes& get_request_id() const; + Type::RequestReceipt::status get_status() const; + float get_progress() const; + const Bytes get_response() const; + double get_response_time() const; + + std::string toString() const; + + // getters + const Bytes& hash() const; + const Bytes& request_id() const; + const size_t response_transfer_size() const; + + // setters + void response_size(size_t size); + void response_transfer_size(size_t size); + + private: + std::shared_ptr _object; + + }; + +/* + This class is used to establish and manage links to other peers. When a + link instance is created, Reticulum will attempt to establish verified + and encrypted connectivity with the specified destination. + + :param destination: A :ref:`RNS.Destination` instance which to establish a link to. + :param established_callback: An optional function or method with the signature *callback(link)* to be called when the link has been established. + :param closed_callback: An optional function or method with the signature *callback(link)* to be called when the link is closed. +*/ + class Link { public: class Callbacks { @@ -41,21 +116,23 @@ namespace RNS { using closed = void(*)(const Link& link); using packet = void(*)(const Bytes& plaintext, const Packet& packet); using remote_identified = void(*)(const Link& link, const Identity& remote_identity); - //using resource = void(*)(const ResourceAdvertisement& resource_advertisement); - //using resource_started = void(*)(const Resource& resource); - //using resource_concluded = void(*)(const Resource& resource); + using resource = void(*)(const ResourceAdvertisement& resource_advertisement); + using resource_started = void(*)(const Resource& resource); + using resource_concluded = void(*)(const Resource& resource); public: established _established = nullptr; closed _closed = nullptr; packet _packet = nullptr; remote_identified _remote_identified = nullptr; - //resource _resource = nullptr; - //resource_started _resource_started = nullptr; - //resource_concluded _resource_concluded = nullptr; - + resource _resource = nullptr; + resource_started _resource_started = nullptr; + resource_concluded _resource_concluded = nullptr; friend class Link; }; + public: + static uint8_t resource_strategies; + public: Link(Type::NoneConstructor none) { MEM("Link NONE object created"); @@ -64,97 +141,100 @@ namespace RNS { MEM("Link object copy created"); } Link(const Destination& destination = {Type::NONE}, Callbacks::established established_callback = nullptr, Callbacks::closed closed_callback = nullptr, const Destination& owner = {Type::NONE}, const Bytes& peer_pub_bytes = {Bytes::NONE}, const Bytes& peer_sig_pub_bytes = {Bytes::NONE}); + //Link(const Destination& destination = {Type::NONE}, Callbacks::established established_callback = nullptr, Callbacks::closed closed_callback = nullptr, const Destination& owner = {Type::NONE}, const Bytes& peer_pub_bytes = {Bytes::NONE}, const Bytes& peer_sig_pub_bytes = {Bytes::NONE}); virtual ~Link(){ MEM("Link object destroyed"); } - inline Link& operator = (const Link& link) { + Link& operator = (const Link& link) { _object = link._object; return *this; } - inline operator bool() const { + operator bool() const { return _object.get() != nullptr; } - inline bool operator < (const Link& link) const { + bool operator < (const Link& link) const { return _object.get() < link._object.get(); } public: + static Link validate_request( const Destination& owner, const Bytes& data, const Packet& packet); + void load_peer(const Bytes& peer_pub_bytes, const Bytes& peer_sig_pub_bytes); void set_link_id(const Packet& packet); - void receive(const Packet& packet); - + void handshake(); void prove(); void prove_packet(const Packet& packet); + void validate_proof(const Packet& packet); + void identify(const Identity& identity); + const RequestReceipt request(const Bytes& path, const Bytes& data = {Bytes::NONE}, RequestReceipt::Callbacks::response response_callback = nullptr, RequestReceipt::Callbacks::failed failed_callback = nullptr, RequestReceipt::Callbacks::progress progress_callback = nullptr, double timeout = 0.0); + void rtt_packet(const Packet& packet); + float get_establishment_rate(); + const Bytes& get_salt(); + const Bytes get_context(); + double no_inbound_for(); + double no_outbound_for(); + double no_data_for(); + double inactive_for(); + const Identity& get_remote_identity(); + void had_outbound(bool is_keepalive = false); + void teardown(); + void teardown_packet(const Packet& packet); + void link_closed(); + void start_watchdog(); + void __watchdog_job(); + void send_keepalive(); + void handle_request(const Bytes& request_id, const ResourceRequest& unpacked_request); + void handle_response(const Bytes& request_id, const Bytes& response_data, size_t response_size, size_t response_transfer_size); + void request_resource_concluded(const Resource& resource); + void response_resource_concluded(const Resource& resource); + //z const Channel& get_channel(); + void receive(const Packet& packet); + const Bytes encrypt(const Bytes& plaintext); + const Bytes decrypt(const Bytes& ciphertext); + const Bytes sign(const Bytes& message); + bool validate(const Bytes& signature, const Bytes& message); + void set_link_established_callback(Callbacks::established callback); + void set_link_closed_callback(Callbacks::closed callback); + void set_packet_callback(Callbacks::packet callback); + void set_remote_identified_callback(Callbacks::remote_identified callback); + void set_resource_callback(Callbacks::resource callback); + void set_resource_started_callback(Callbacks::resource_started callback); + void set_resource_concluded_callback(Callbacks::resource_concluded callback); + void resource_concluded(const Resource& resource); + void set_resource_strategy(Type::Link::resource_strategy strategy); + void register_outgoing_resource(const Resource& resource); + void register_incoming_resource(const Resource& resource); + bool has_incoming_resource(const Resource& resource); + void cancel_outgoing_resource(const Resource& resource); + void cancel_incoming_resource(const Resource& resource); + bool ready_for_new_resource(); - // getters/setters - inline const Destination& destination() const { assert(_object); return _object->_destination; } - inline const Bytes& link_id() const { assert(_object); return _object->_link_id; } - inline const Bytes& hash() const { assert(_object); return _object->_hash; } - inline Type::Link::status status() const { assert(_object); return _object->_status; } + //void __str__(); + std::string toString() const; - inline std::string toString() const { if (!_object) return ""; return "{Link: unknown}"; } + // getters + const Destination& destination() const; + const Interface& attached_interface() const; + const Bytes& link_id() const; + const Bytes& hash() const; + Type::Link::status status() const; + double establishment_timeout() const; + uint16_t establishment_cost() const; + double request_time() const; + double last_inbound() const; + std::set& pending_requests() const; - private: - class Object { - public: - Object(const Destination& destination) : _destination(destination) {} - virtual ~Object() {} - private: - Destination _destination = {Type::NONE}; - Bytes _link_id; - Bytes _hash; - Type::Link::status _status = Type::Link::PENDING; + // setters + void destination(const Destination& destination); + void attached_interface(const Interface& interface); + void establishment_timeout(double timeout); + void establishment_cost(uint16_t cost); + void request_time(double time); + void last_inbound(double time); - //z _rtt = None - //z _establishment_cost = 0 - Callbacks _callbacks; - Type::Link::resource_strategy _resource_strategy = Type::Link::ACCEPT_NONE; - //z _outgoing_resources = [] - //z _incoming_resources = [] - //z _pending_requests = [] - double _last_inbound = 0.0; - double _last_outbound = 0.0; - double _last_proof = 0.0; - double _last_data = 0.0; - uint16_t _tx = 0; - uint16_t _rx = 0; - uint16_t _txbytes = 0; - uint16_t _rxbytes = 0; - float _rssi = 0.0; - float _snr = 0.0; - float _q = 0.0; - uint16_t _traffic_timeout_factor = Type::Link::TRAFFIC_TIMEOUT_FACTOR; - uint16_t _keepalive_timeout_factor = Type::Link::KEEPALIVE_TIMEOUT_FACTOR; - uint16_t _keepalive = Type::Link::KEEPALIVE; - uint16_t _stale_time = Type::Link::STALE_TIME; - bool _watchdog_lock = false; - double _activated_at = 0.0; - Type::Destination::types _type = Type::Destination::LINK; - const Destination _destination = {Type::NONE}; - Destination _owner = {Type::NONE}; - bool _initiator = false; - uint8_t _expected_hops = 0; - const Interface _attached_interface = {Type::NONE}; - const Identity ___remote_identity = {Type::NONE}; - bool ___track_phy_stats = false; - //z const Channel __channel = {Type::NONE}; - - Cryptography::X25519PrivateKey::Ptr _prv; - Bytes _prv_bytes; - - Cryptography::Ed25519PrivateKey::Ptr _sig_prv; - Bytes _sig_prv_bytes; - - Cryptography::X25519PublicKey::Ptr _pub; - Bytes _pub_bytes; - - Cryptography::Ed25519PublicKey::Ptr _sig_pub; - Bytes _sig_pub_bytes; - - friend class Link; - }; - std::shared_ptr _object; + protected: + std::shared_ptr _object; }; -} \ No newline at end of file +} diff --git a/src/LinkData.h b/src/LinkData.h new file mode 100644 index 0000000..b8360d1 --- /dev/null +++ b/src/LinkData.h @@ -0,0 +1,125 @@ +#pragma once + +//#include "LinkCallbacks.h" +#include "Link.h" + +#include "Resource.h" +#include "Channel.h" +#include "Interface.h" +#include "Packet.h" +#include "Destination.h" +#include "Bytes.h" +#include "Type.h" +#include "Cryptography/Fernet.h" + +#include + +namespace RNS { + + class LinkData { + public: + LinkData(const Destination& destination) : _destination(destination) {} + virtual ~LinkData() {} + private: + Destination _destination; + + // CBA LINK + Destination _link_destination = {Type::NONE}; + + Bytes _link_id; + Bytes _hash; + Type::Link::status _status = Type::Link::PENDING; + + double _rtt = 0.0; + uint16_t _establishment_cost = 0; + Link::Callbacks _callbacks; + Type::Link::resource_strategy _resource_strategy = Type::Link::ACCEPT_NONE; + double _last_inbound = 0.0; + double _last_outbound = 0.0; + double _last_proof = 0.0; + double _last_data = 0.0; + uint16_t _tx = 0; + uint16_t _rx = 0; + uint16_t _txbytes = 0; + uint16_t _rxbytes = 0; + float _rssi = 0.0; + float _snr = 0.0; + float _q = 0.0; + uint16_t _traffic_timeout_factor = Type::Link::TRAFFIC_TIMEOUT_FACTOR; + uint16_t _keepalive_timeout_factor = Type::Link::KEEPALIVE_TIMEOUT_FACTOR; + uint16_t _keepalive = Type::Link::KEEPALIVE; + uint16_t _stale_time = Type::Link::STALE_TIME; + bool _watchdog_lock = false; + double _activated_at = 0.0; + Type::Destination::types _type = Type::Destination::LINK; + Destination _owner = {Type::NONE}; + bool _initiator = false; + uint8_t _expected_hops = 0; + Interface _attached_interface = {Type::NONE}; + Identity __remote_identity = {Type::NONE}; + Channel _channel = {Type::NONE}; + double _establishment_timeout = 0.0; + Bytes _request_data; + Packet _packet = {Type::NONE}; + double _request_time = 0.0; + float _establishment_rate = 0.0; + Type::Link::teardown_reason _teardown_reason = Type::Link::TEARDOWN_NONE; + + Cryptography::Fernet::Ptr _fernet; + + Cryptography::X25519PrivateKey::Ptr _prv; + Bytes _prv_bytes; + + Cryptography::Ed25519PrivateKey::Ptr _sig_prv; + Bytes _sig_prv_bytes; + + Cryptography::X25519PublicKey::Ptr _pub; + Bytes _pub_bytes; + + Cryptography::Ed25519PublicKey::Ptr _sig_pub; + Bytes _sig_pub_bytes; + + Cryptography::X25519PublicKey::Ptr _peer_pub; + Bytes _peer_pub_bytes; + + Cryptography::Ed25519PublicKey::Ptr _peer_sig_pub; + Bytes _peer_sig_pub_bytes; + + Bytes _shared_key; + Bytes _derived_key; + + std::set _incoming_resources; + std::set _outgoing_resources; + std::set _pending_requests; + + friend class Link; + }; + + class RequestReceiptData { + public: + RequestReceiptData() {} + virtual ~RequestReceiptData() {} + private: + Bytes _hash; + PacketReceipt _packet_receipt = {Type::NONE}; + Resource _resource = {Type::NONE}; + Link _link; + double _started_at = 0.0; + Bytes _request_id; + int _request_size = 0; + Bytes _response; + size_t _response_transfer_size = 0; + size_t _response_size = 0; + Type::RequestReceipt::status _status = Type::RequestReceipt::SENT; + double _sent_at = 0.0; + int _progress = 0; + double _concluded_at = 0.0; + double _response_concluded_at = 0.0; + double _timeout = 0.0; + double _resource_response_timeout = 0.0; + double ___resource_response_timeout = 0.0; + RequestReceipt::Callbacks _callbacks; + friend class RequestReceipt; + }; + +} diff --git a/src/Log.h b/src/Log.h index 2423d7c..415001d 100644 --- a/src/Log.h +++ b/src/Log.h @@ -27,10 +27,13 @@ #define DEBUGF(msg, ...) (RNS::debugf(msg, __VA_ARGS__)) #define TRACE(msg) (RNS::trace(msg)) #define TRACEF(msg, ...) (RNS::tracef(msg, __VA_ARGS__)) - //#define MEM(msg) (RNS::mem(msg)) - #define MEM(ignore) ((void)0) - //#define MEMF(msg, ...) (RNS::memf(msg, __VA_ARGS__)) - #define MEMF(...) ((void)0) + #if defined(MEM_LOG) + #define MEM(msg) (RNS::mem(msg)) + #define MEMF(msg, ...) (RNS::memf(msg, __VA_ARGS__)) + #else + #define MEM(ignore) ((void)0) + #define MEMF(...) ((void)0) + #endif #else #define DEBUG(ignore) ((void)0) #define DEBUGF(...) ((void)0) diff --git a/src/Packet.cpp b/src/Packet.cpp index 25e6a0e..dfa5fe1 100644 --- a/src/Packet.cpp +++ b/src/Packet.cpp @@ -17,7 +17,9 @@ ProofDestination::ProofDestination(const Packet& packet) : Destination({Type::NO { } -Packet::Packet(const Destination& destination, const Interface& attached_interface, const Bytes& data, types packet_type /*= DATA*/, context_types context /*= CONTEXT_NONE*/, Type::Transport::types transport_type /*= Type::Transport::BROADCAST*/, header_types header_type /*= HEADER_1*/, const Bytes& transport_id /*= {Bytes::NONE}*/, bool create_receipt /*= true*/) : _object(new Object(destination, attached_interface)) { +Packet::Packet(const Destination& destination, const Interface& attached_interface, const Bytes& data, types packet_type /*= DATA*/, context_types context /*= CONTEXT_NONE*/, Type::Transport::types transport_type /*= Type::Transport::BROADCAST*/, header_types header_type /*= HEADER_1*/, const Bytes& transport_id /*= {Bytes::NONE}*/, bool create_receipt /*= true*/) : + _object(new Object(destination, attached_interface)) +{ if (_object->_destination) { TRACE("Creating packet with destination..."); @@ -50,6 +52,12 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa MEM("Packet object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); } +Packet::Packet(const Destination& destination, const Link& link, const Bytes& data, Type::Packet::types packet_type /*= Type::Packet::DATA*/, Type::Packet::context_types context /*= Type::Packet::CONTEXT_NONE*/) : + _object(new Object(destination, link)) +{ + MEM("Packet link object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); +} + uint8_t Packet::get_packed_flags() { assert(_object); @@ -278,7 +286,9 @@ void Packet::pack() { // Resource proofs are not encrypted _object->_raw << _object->_data; } + // CBA LINK else if (_object->_packet_type == PROOF && _object->_destination.type() == Type::Destination::LINK) { + //else if (_object->_packet_type == PROOF && _object->_destination_link) { // Packet proofs over links are not encrypted _object->_raw << _object->_data; } @@ -299,6 +309,9 @@ void Packet::pack() { else { // In all other cases, we encrypt the packet // with the destination's encryption method + // CBA LINK + // CBA TODO Determine if we need to use link (_destination_link) to encrypt here + // (if not then likely there is no need for the added _destination_link) _object->_raw << _object->_destination.encrypt(_object->_data); _object->_encrypted = true; } @@ -389,25 +402,24 @@ Sends the packet. :returns: A :ref:`RNS.PacketReceipt` instance if *create_receipt* was set to *True* when the packet was instantiated, if not returns *None*. If the packet could not be sent *False* is returned. */ -bool Packet::send() { +PacketReceipt Packet::send() { assert(_object); TRACE("Packet::send: sending packet..."); if (_object->_sent) { throw std::logic_error("Packet was already sent"); } -// TODO -/* - if (_destination->type == RNS::Destination::LINK) { - if (_destination->status == Type::Link::CLOSED) { + // CBA LINK + if (_object->_destination.type() == Type::Destination::LINK) { + //if (_object->_destination_link) { + if (_object->_destination.status() == Type::Link::CLOSED) { throw std::runtime_error("Attempt to transmit over a closed link"); } else { - _destination->last_outbound = time(); - _destination->tx += 1; - _destination->txbytes += _data_len; + _object->_destination.last_outbound(OS::time()); + _object->_destination.increment_tx(); + _object->_destination.increment_txbytes(_object->_data.size()); } } -*/ if (!_object->_packed) { pack(); @@ -415,15 +427,15 @@ bool Packet::send() { if (Transport::outbound(*this)) { TRACE("Packet::send: successfully sent packet!!!"); - //z return self.receipt - // MOCK - return true; + //p return self.receipt + return _object->_receipt; } else { ERROR("No interfaces could process the outbound packet"); _object->_sent = false; - //z _receipt = None; - return false; + _object->_receipt = {Type::NONE}; + //p return False + return {Type::NONE}; } } @@ -634,7 +646,9 @@ std::string Packet::dumpString() const { if (_object->_context == RESOURCE_PRF) { encrypted = false; } + // CBA LINK if (_object->_destination && _object->_destination.type() == Type::Destination::LINK) { + //if (_object->_destination && _object->_destination_link) { encrypted = false; } break; @@ -746,6 +760,7 @@ std::string Packet::dumpString() const { } #endif + PacketReceipt::PacketReceipt(const Packet& packet) : _object(new Object()) { if (!packet.destination()) { @@ -755,8 +770,10 @@ PacketReceipt::PacketReceipt(const Packet& packet) : _object(new Object()) { _object->_truncated_hash = packet.getTruncatedHash(); _object->_destination = packet.destination(); + // CBA LINK if (packet.destination().type() == Type::Destination::LINK) { - // CBA BUG? Destination does not have rtt or traffic_timeout_factor memebers + //if (packet.destination().destination_link()) { + // CBA BUG? Destination does not have rtt or traffic_timeout_factor members //z _object->_timeout = packet.destination().rtt() * packet.destination().traffic_timeout_factor(); _object->_timeout = TIMEOUT_PER_HOP * Transport::hops_to(_object->_destination.hash()); } diff --git a/src/Packet.h b/src/Packet.h index 8de48b4..9ce8436 100644 --- a/src/Packet.h +++ b/src/Packet.h @@ -1,8 +1,8 @@ #pragma once -#include "Destination.h" #include "Link.h" #include "Interface.h" +#include "Destination.h" #include "Bytes.h" #include "Log.h" #include "Type.h" @@ -99,9 +99,18 @@ namespace RNS { _object->_callbacks._timeout = callback; } - // getters/setters + // getters inline const Bytes& hash() const { assert(_object); return _object->_hash; } inline Type::PacketReceipt::Status status() const { assert(_object); return _object->_status; } + inline bool proved() const { assert(_object); return _object->_proved; } + inline double concluded_at() const { assert(_object); return _object->_concluded_at; } + inline const Bytes& truncated_hash() const { assert(_object); return _object->_truncated_hash; } + inline const Callbacks& callbacks() const { assert(_object); return _object->_callbacks; } + + // setters + inline void status(Type::PacketReceipt::Status status) { assert(_object); _object->_status = status; } + inline void proved(bool proved) { assert(_object); _object->_proved = proved; } + inline void concluded_at(double concluded_at) { assert(_object); _object->_concluded_at = concluded_at; } private: class Object { @@ -162,6 +171,13 @@ namespace RNS { const Bytes& transport_id = {Bytes::NONE}, bool create_receipt = true ) : Packet(destination, {Type::NONE}, data, packet_type, context, transport_type, header_type, transport_id, create_receipt) {} + Packet( + const Destination& destination, + const Link& link, + const Bytes& data, + Type::Packet::types packet_type = Type::Packet::DATA, + Type::Packet::context_types context = Type::Packet::CONTEXT_NONE + ); virtual ~Packet() { MEM("Packet object destroyed, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); } @@ -191,7 +207,7 @@ namespace RNS { void unpack_flags(uint8_t flags); void pack(); bool unpack(); - bool send(); + PacketReceipt send(); bool resend(); void prove(const Destination& destination = {Type::NONE}); ProofDestination generate_proof_destination() const; @@ -202,39 +218,46 @@ namespace RNS { const Bytes getTruncatedHash() const; const Bytes get_hashable_part() const; - // getters/setters + inline std::string toString() const { if (!_object) return ""; return "{Packet:" + _object->_packet_hash.toHex() + "}"; } + + // getters inline const Destination& destination() const { assert(_object); return _object->_destination; } - inline void destination(const Destination& destination) { assert(_object); _object->_destination = destination; } inline const Link& link() const { assert(_object); return _object->_link; } - inline void link(const Link& link) { assert(_object); _object->_link = link; } inline const Interface& attached_interface() const { assert(_object); return _object->_attached_interface; } inline const Interface& receiving_interface() const { assert(_object); return _object->_receiving_interface; } - inline void receiving_interface(const Interface& receiving_interface) { assert(_object); _object->_receiving_interface = receiving_interface; } inline Type::Packet::header_types header_type() const { assert(_object); return _object->_header_type; } inline Type::Transport::types transport_type() const { assert(_object); return _object->_transport_type; } inline Type::Destination::types destination_type() const { assert(_object); return _object->_destination_type; } inline Type::Packet::types packet_type() const { assert(_object); return _object->_packet_type; } inline Type::Packet::context_types context() const { assert(_object); return _object->_context; } inline bool sent() const { assert(_object); return _object->_sent; } - inline void sent(bool sent) { assert(_object); _object->_sent = sent; } inline double sent_at() const { assert(_object); return _object->_sent_at; } - inline void sent_at(double sent_at) { assert(_object); _object->_sent_at = sent_at; } inline bool create_receipt() const { assert(_object); return _object->_create_receipt; } inline const PacketReceipt& receipt() const { assert(_object); return _object->_receipt; } - inline void receipt(const PacketReceipt& receipt) { assert(_object); _object->_receipt = receipt; } inline uint8_t flags() const { assert(_object); return _object->_flags; } inline uint8_t hops() const { assert(_object); return _object->_hops; } - inline void hops(uint8_t hops) { assert(_object); _object->_hops = hops; } inline bool cached() const { assert(_object); return _object->_cached; } - inline void cached(bool cached) { assert(_object); _object->_cached = cached; } inline const Bytes& packet_hash() const { assert(_object); return _object->_packet_hash; } inline const Bytes& destination_hash() const { assert(_object); return _object->_destination_hash; } inline const Bytes& transport_id() const { assert(_object); return _object->_transport_id; } - inline void transport_id(const Bytes& transport_id) { assert(_object); _object->_transport_id = transport_id; } inline const Bytes& raw() const { assert(_object); return _object->_raw; } inline const Bytes& data() const { assert(_object); return _object->_data; } + //inline const Link& destination_link() const { assert(_object); return _object->_destination_link; } + //CBA Following method is only used by Resource to access decrypted resource advertisement form Link. Consider a better way. + inline const Bytes& plaintext() { assert(_object); return _object->_plaintext; } - inline std::string toString() const { if (!_object) return ""; return "{Packet:" + _object->_packet_hash.toHex() + "}"; } + // setters + inline void destination(const Destination& destination) { assert(_object); _object->_destination = destination; } + inline void link(const Link& link) { assert(_object); _object->_link = link; } + inline void receiving_interface(const Interface& receiving_interface) { assert(_object); _object->_receiving_interface = receiving_interface; } + inline void sent(bool sent) { assert(_object); _object->_sent = sent; } + inline void sent_at(double sent_at) { assert(_object); _object->_sent_at = sent_at; } + inline void receipt(const PacketReceipt& receipt) { assert(_object); _object->_receipt = receipt; } + inline void hops(uint8_t hops) { assert(_object); _object->_hops = hops; } + inline void cached(bool cached) { assert(_object); _object->_cached = cached; } + inline void transport_id(const Bytes& transport_id) { assert(_object); _object->_transport_id = transport_id; } + //CBA Following method is only used by Link to provide Resource access to decrypted resource advertisement. Consider a better way. + inline void plaintext(const Bytes& plaintext) { assert(_object); _object->_plaintext = plaintext; } #ifndef NDEBUG std::string debugString() const; @@ -245,9 +268,14 @@ namespace RNS { class Object { public: Object(const Destination& destination, const Interface& attached_interface) : _destination(destination), _attached_interface(attached_interface) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); } - virtual ~Object() { MEM("Identity::Data object destroyed, this: " + std::to_string((uintptr_t)this)); } + Object(const Destination& destination, const Link& destination_link) : _destination(destination), _destination_link(destination_link) { MEM("Packet::Data object created, this: " + std::to_string((uintptr_t)this)); } + virtual ~Object() { MEM("Packet::Data object destroyed, this: " + std::to_string((uintptr_t)this)); } private: Destination _destination = {Type::NONE}; + + // CBA LINK + Link _destination_link = {Type::NONE}; + Link _link = {Type::NONE}; Interface _attached_interface = {Type::NONE}; @@ -284,6 +312,8 @@ namespace RNS { Bytes _raw; // header + ( plaintext | ciphertext-token ) Bytes _data; // plaintext | ciphertext + Bytes _plaintext; // used exclusively to relay decrypted resource advertisement form Link to Resource + friend class Packet; }; std::shared_ptr _object; diff --git a/src/Resource.cpp b/src/Resource.cpp new file mode 100644 index 0000000..cb4a653 --- /dev/null +++ b/src/Resource.cpp @@ -0,0 +1,122 @@ +#include "Resource.h" + +#include "ResourceData.h" +#include "Reticulum.h" +#include "Transport.h" +#include "Packet.h" +#include "Log.h" + +#include + +using namespace RNS; +using namespace RNS::Type::Resource; +using namespace RNS::Utilities; + +//Resource::Resource(const Link& link /*= {Type::NONE}*/) : +// _object(new ResourceData(link)) +//{ +// assert(_object); +// MEM("Resource object created"); +//} + +Resource::Resource(const Bytes& data, const Link& link, const Bytes& request_id, bool is_response, double timeout) : + _object(new ResourceData(link)) +{ + assert(_object); + MEM("Resource object created"); +} + +Resource::Resource(const Bytes& data, const Link& link, bool advertise /*= true*/, bool auto_compress /*= true*/, Callbacks::concluded callback /*= nullptr*/, Callbacks::progress progress_callback /*= nullptr*/, double timeout /*= 0.0*/, int segment_index /*= 1*/, const Bytes& original_hash /*= {Type::NONE}*/, const Bytes& request_id /*= {Type::NONE}*/, bool is_response /*= false*/) : + _object(new ResourceData(link)) +{ + assert(_object); + MEM("Resource object created"); +} + + +void Resource::validate_proof(const Bytes& proof_data) { +} + +void Resource::cancel() { +} + +/* +:returns: The current progress of the resource transfer as a *float* between 0.0 and 1.0. +*/ +float Resource::get_progress() const { +/* + assert(_object); + if (_object->_initiator) { + _object->_processed_parts = (_object->_segment_index-1)*math.ceil(Type::Resource::MAX_EFFICIENT_SIZE/Type::Resource::SDU); + _object->_processed_parts += _object->sent_parts; + _object->_progress_total_parts = float(_object->grand_total_parts); + } + else { + _object->_processed_parts = (_object->_segment_index-1)*math.ceil(Type::Resource::MAX_EFFICIENT_SIZE/Type::Resource::SDU); + _object->_processed_parts += _object->_received_count; + if (_object->split) { + _object->progress_total_parts = float(math.ceil(_object->total_size/Type::Resource::SDU)); + } + else { + _object->progress_total_parts = float(_object->total_parts); + } + } + + return (float)_object->processed_parts / (float)_object->progress_total_parts; +*/ + return 0.0; +} + +void Resource::set_concluded_callback(Callbacks::concluded callback) { + assert(_object); + _object->_callbacks._concluded = callback; +} + +void Resource::set_progress_callback(Callbacks::progress callback) { + assert(_object); + _object->_callbacks._progress = callback; +} + + +std::string Resource::toString() const { + if (!_object) { + return ""; + } + //return "<"+RNS.hexrep(self.hash,delimit=False)+"/"+RNS.hexrep(self.link.link_id,delimit=False)+">" + //return "{Resource:" + _object->_hash.toHex() + "}"; + return "{Resource: unknown}"; +} + +// getters +const Bytes& Resource::hash() const { + assert(_object); + return _object->_hash; +} + +const Bytes& Resource::request_id() const { + assert(_object); + return _object->_request_id; +} + +const Bytes& Resource::data() const { + assert(_object); + return _object->_data; +} + +const Type::Resource::status Resource::status() const { + assert(_object); + return _object->_status; +} + +const size_t Resource::size() const { + assert(_object); + return _object->_size; +} + +const size_t Resource::total_size() const { + assert(_object); + return _object->_total_size; +} + +// setters + diff --git a/src/Resource.h b/src/Resource.h new file mode 100644 index 0000000..e66597c --- /dev/null +++ b/src/Resource.h @@ -0,0 +1,109 @@ +#pragma once + +#include "Destination.h" +#include "Type.h" + +#include +#include + +namespace RNS { + + class ResourceData; + class Packet; + class Destination; + class Link; + class Resource; + + class Resource { + + public: + class Callbacks { + public: + //using concluded = void(*)(const Resource& resource); + typedef std::function concluded; + using progress = void(*)(const Resource& resource); + public: + concluded _concluded = nullptr; + progress _progress = nullptr; + friend class Resource; + }; + + public: + Resource(Type::NoneConstructor none) { + MEM("Resource NONE object created"); + } + Resource(const Resource& resource) : _object(resource._object) { + MEM("Resource object copy created"); + } + //Resource(const Link& link = {Type::NONE}); + Resource(const Bytes& data, const Link& link, const Bytes& request_id, bool is_response, double timeout); + Resource(const Bytes& data, const Link& link, bool advertise = true, bool auto_compress = true, Callbacks::concluded callback = nullptr, Callbacks::progress progress_callback = nullptr, double timeout = 0.0, int segment_index = 1, const Bytes& original_hash = {Type::NONE}, const Bytes& request_id = {Type::NONE}, bool is_response = false); + virtual ~Resource(){ + MEM("Resource object destroyed"); + } + + Resource& operator = (const Resource& resource) { + _object = resource._object; + return *this; + } + operator bool() const { + return _object.get() != nullptr; + } + bool operator < (const Resource& resource) const { + return _object.get() < resource._object.get(); + //return _object->_hash < resource._object->_hash; + } + + public: + //p static def accept(advertisement_packet, callback=None, progress_callback = None, request_id = None): + + public: +//p def hashmap_update_packet(self, plaintext): +//p def hashmap_update(self, segment, hashmap): +//p def get_map_hash(self, data): +//p def advertise(self): +//p def __advertise_job(self): +//p def watchdog_job(self): +//p def __watchdog_job(self): +//p def assemble(self): +//p def prove(self): + void validate_proof(const Bytes& proof_data); +//p def receive_part(self, packet): +//p def request_next(self): +//p def request(self, request_data): + void cancel(); +//p def set_callback(self, callback): +//p def progress_callback(self, callback): + float get_progress() const; +//p def get_transfer_size(self): +//p def get_data_size(self): +//p def get_parts(self): +//p def get_segments(self): +//p def get_hash(self): +//p def is_compressed(self): + void set_concluded_callback(Callbacks::concluded callback); + void set_progress_callback(Callbacks::progress callback); + + std::string toString() const; + + // getters + const Bytes& hash() const; + const Bytes& request_id() const; + const Bytes& data() const; + const Type::Resource::status status() const; + const size_t size() const; + const size_t total_size() const; + + // setters + + protected: + std::shared_ptr _object; + + }; + + + class ResourceAdvertisement { + + }; + +} diff --git a/src/ResourceData.h b/src/ResourceData.h new file mode 100644 index 0000000..86cd18f --- /dev/null +++ b/src/ResourceData.h @@ -0,0 +1,31 @@ +#pragma once + +#include "Resource.h" + +#include "Interface.h" +#include "Packet.h" +#include "Destination.h" +#include "Bytes.h" +#include "Type.h" +#include "Cryptography/Fernet.h" + +namespace RNS { + + class ResourceData { + public: + ResourceData(const Link& link) : _link(link) {} + virtual ~ResourceData() {} + private: + Link _link; + Bytes _hash; + Bytes _request_id; + Bytes _data; + Type::Resource::status _status = Type::Resource::NONE; + size_t _size = 0; + size_t _total_size = 0; + Resource::Callbacks _callbacks; + + friend class Resource; + }; + +} diff --git a/src/Reticulum.cpp b/src/Reticulum.cpp index 713429a..0b10c07 100644 --- a/src/Reticulum.cpp +++ b/src/Reticulum.cpp @@ -63,11 +63,6 @@ void Reticulum::sigterm_handler(signal, frame): RNS.exit() */ -// Return the currently running Reticulum instance -/*static*/ const Reticulum& Reticulum::get_instance() { - return _instance; -} - //def __init__(self,configdir=None, loglevel=None, logdest=None, verbosity=None): Reticulum::Reticulum() : _object(new Object()) { MEM("Reticulum default object creating..., this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); @@ -379,11 +374,11 @@ void Reticulum::__create_default_config() { void Reticulum::rpc_loop() { } -void Reticulum::get_interface_stats() { +void Reticulum::get_interface_stats() const { } */ -const std::map& Reticulum::get_path_table() { +const std::map& Reticulum::get_path_table() const { /* path_table = [] for dst_hash in Transport::destination_table: @@ -402,7 +397,7 @@ const std::map& Reticulum::get_path_table() return Transport::get_destination_table(); } -const std::map& Reticulum::get_rate_table() { +const std::map& Reticulum::get_rate_table() const { /* rate_table = [] for dst_hash in Transport::announce_rate_table: @@ -440,38 +435,38 @@ void Reticulum::drop_announce_queues() { Transport::drop_announce_queues(); } -std::string Reticulum::get_next_hop_if_name(const Bytes& destination) { +const std::string Reticulum::get_next_hop_if_name(const Bytes& destination) const { return Transport::next_hop_interface(destination).name(); } -double Reticulum::get_first_hop_timeout(const Bytes& destination) { +double Reticulum::get_first_hop_timeout(const Bytes& destination) const { return Transport::first_hop_timeout(destination); } -Bytes Reticulum::get_next_hop(const Bytes& destination) { +const Bytes Reticulum::get_next_hop(const Bytes& destination) const { return Transport::next_hop(destination); } -size_t Reticulum::get_link_count() { +size_t Reticulum::get_link_count() const { return Transport::get_link_table().size(); } /*p -void Reticulum::get_packet_rssi(const Bytes& packet_hash) { +void Reticulum::get_packet_rssi(const Bytes& packet_hash) const { for entry in Transport::local_client_rssi_cache: if entry[0] == packet_hash: return entry[1] return None -void Reticulum::get_packet_snr(const Bytes& packet_hash) { +void Reticulum::get_packet_snr(const Bytes& packet_hash) const { for entry in Transport::local_client_snr_cache: if entry[0] == packet_hash: return entry[1] return None -void Reticulum::get_packet_q(const Bytes& packet_hash) { +void Reticulum::get_packet_q(const Bytes& packet_hash) const { for entry in Transport::local_client_q_cache: if entry[0] == packet_hash: return entry[1] diff --git a/src/Reticulum.h b/src/Reticulum.h index 7375580..678b160 100644 --- a/src/Reticulum.h +++ b/src/Reticulum.h @@ -1,5 +1,6 @@ #pragma once +#include "Transport.h" #include "Log.h" #include "Type.h" #include "Utilities/OS.h" @@ -40,7 +41,8 @@ namespace RNS { static bool panic_on_interface_error; public: - static const Reticulum& get_instance(); + // Return the currently running Reticulum instance + inline static const Reticulum& get_instance() { return _instance; } public: Reticulum(Type::NoneConstructor none) { @@ -76,16 +78,19 @@ namespace RNS { void clear_caches(); //void __create_default_config(); //void rpc_loop(); - //void get_interface_stats(); - const std::map& get_path_table(); - const std::map& get_rate_table(); + //void get_interface_stats() const; + const std::map& get_path_table() const; + const std::map& get_rate_table() const; bool drop_path(const Bytes& destination); uint16_t drop_all_via(const Bytes& transport_hash); void drop_announce_queues(); - std::string get_next_hop_if_name(const Bytes& destination); - double get_first_hop_timeout(const Bytes& destination); - Bytes get_next_hop(const Bytes& destination); - size_t get_link_count(); + const std::string get_next_hop_if_name(const Bytes& destination) const; + double get_first_hop_timeout(const Bytes& destination) const; + const Bytes get_next_hop(const Bytes& destination) const; + size_t get_link_count() const; + //void get_packet_rssi(const Bytes& packet_hash) const; + //void get_packet_snr(const Bytes& packet_hash) const; + //void get_packet_q(const Bytes& packet_hash) const; /* Returns whether proofs sent are explicit or implicit. diff --git a/src/Transport.cpp b/src/Transport.cpp index ae15413..c4ad904 100644 --- a/src/Transport.cpp +++ b/src/Transport.cpp @@ -158,12 +158,12 @@ using namespace RNS::Utilities; if (!owner.is_connected_to_shared_instance()) { if (os.path.isfile(packet_hashlist_path)) { try { - file = open(packet_hashlist_path, "rb"); - packet_hashlist = umsgpack.unpackb(file.read()); - file.close(); + //p file = open(packet_hashlist_path, "rb") + //p Transport.packet_hashlist = umsgpack.unpackb(file.read()) + //p file.close() } catch (std::exception& e) { - ERROR("Could not load packet hashlist from storage, the contained exception was: %s", e.what()); + ERRORF("Could not load packet hashlist from storage, the contained exception was: %s", e.what()); } } } @@ -1239,7 +1239,7 @@ using namespace RNS::Utilities; _jobs_locked = true; - Packet packet({Type::NONE}, raw); + Packet packet(RNS::Destination(RNS::Type::NONE), raw); if (!packet.unpack()) { WARNING("Transport::inbound: Packet unpack failed!"); return; @@ -3657,7 +3657,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: DEBUG("Transport::read_tunnel_table"); #if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS) // TODO -/* +/*p tunnel_table_path = RNS.Reticulum.storagepath+"/tunnels" if os.path.isfile(tunnel_table_path) and not Transport.owner.is_connected_to_shared_instance: serialised_tunnels = [] @@ -3987,7 +3987,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: ++count; } if (count > 0) { - extreme("Released " + std::to_string(count) + " reverse table entries"); + TRACEF("Released %u reverse table entries", count); } return count; } @@ -3999,7 +3999,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: ++count; } if (count > 0) { - extreme("Released " + std::to_string(count) + " links"); + TRACEF("Released %u links", count); } return count; } @@ -4012,7 +4012,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: ++count; } if (count > 0) { - extreme("Removed " + std::to_string(count) + " paths"); + TRACEF("Released %u paths", count); } return count; } @@ -4024,7 +4024,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: ++count; } if (count > 0) { - extreme("Removed " + std::to_string(count) + " waiting path requests"); + TRACEF("Released %u waiting path requests", count); } return count; } @@ -4036,7 +4036,7 @@ TRACE("Transport::write_path_table: buffer size " + std::to_string(Persistence:: ++count; } if (count > 0) { - extreme("Removed " + std::to_string(count) + " tunnels"); + TRACEF("Released %u tunnels", count); } return count; } diff --git a/src/Type.h b/src/Type.h index 324e073..7dd4ddb 100644 --- a/src/Type.h +++ b/src/Type.h @@ -194,6 +194,7 @@ namespace RNS { namespace Type { }; enum teardown_reason { + TEARDOWN_NONE = 0x00, TIMEOUT = 0x01, INITIATOR_CLOSED = 0x02, DESTINATION_CLOSED = 0x03, @@ -207,6 +208,18 @@ namespace RNS { namespace Type { } + namespace RequestReceipt { + + enum status { + FAILED = 0x00, + SENT = 0x01, + DELIVERED = 0x02, + RECEIVING = 0x03, + READY = 0x04, + }; + + } + namespace Interface { // Interface mode definitions @@ -359,4 +372,104 @@ namespace RNS { namespace Type { static const uint16_t LOCAL_CLIENT_CACHE_MAXSIZE = 512; } + namespace Resource { + + // The initial window size at beginning of transfer + static const uint8_t WINDOW = 4; + + // Absolute minimum window size during transfer + static const uint8_t WINDOW_MIN = 1; + + // The maximum window size for transfers on slow links + static const uint8_t WINDOW_MAX_SLOW = 10; + + // The maximum window size for transfers on fast links + static const uint8_t WINDOW_MAX_FAST = 75; + + // For calculating maps and guard segments, this + // must be set to the global maximum window. + static const uint8_t WINDOW_MAX = WINDOW_MAX_FAST; + + // If the fast rate is sustained for this many request + // rounds, the fast link window size will be allowed. + static const uint8_t FAST_RATE_THRESHOLD = WINDOW_MAX_SLOW - WINDOW - 2; + + // If the RTT rate is higher than this value, + // the max window size for fast links will be used. + // The default is 50 Kbps (the value is stored in + // bytes per second, hence the "/ 8"). + static const uint16_t RATE_FAST = (50*1000) / 8; + + // The minimum allowed flexibility of the window size. + // The difference between window_max and window_min + // will never be smaller than this value. + static const uint8_t WINDOW_FLEXIBILITY = 4; + + // Number of bytes in a map hash + static const uint8_t MAPHASH_LEN = 4; + static const uint16_t SDU = Packet::MDU; + static const uint8_t RANDOM_HASH_SIZE = 4; + + // This is an indication of what the + // maximum size a resource should be, if + // it is to be handled within reasonable + // time constraint, even on small systems. + # + // A small system in this regard is + // defined as a Raspberry Pi, which should + // be able to compress, encrypt and hash-map + // the resource in about 10 seconds. + # + // This constant will be used when determining + // how to sequence the sending of large resources. + # + // Capped at 16777215 (0xFFFFFF) per segment to + // fit in 3 bytes in resource advertisements. + static const uint32_t MAX_EFFICIENT_SIZE = 16 * 1024 * 1024 - 1; + static const uint8_t RESPONSE_MAX_GRACE_TIME = 10; + + // The maximum size to auto-compress with + // bz2 before sending. + static const uint32_t AUTO_COMPRESS_MAX_SIZE = MAX_EFFICIENT_SIZE; + + static const uint8_t PART_TIMEOUT_FACTOR = 4; + static const uint8_t PART_TIMEOUT_FACTOR_AFTER_RTT = 2; + static const uint8_t MAX_RETRIES = 8; + static const uint8_t MAX_ADV_RETRIES = 4; + static const uint8_t SENDER_GRACE_TIME = 10; + static const float RETRY_GRACE_TIME = 0.25; + static const float PER_RETRY_DELAY = 0.5; + + static const uint8_t WATCHDOG_MAX_SLEEP = 1; + + static const uint8_t HASHMAP_IS_NOT_EXHAUSTED = 0x00; + static const uint8_t HASHMAP_IS_EXHAUSTED = 0xFF; + + // Status constants + enum status { + NONE = 0x00, + QUEUED = 0x01, + ADVERTISED = 0x02, + TRANSFERRING = 0x03, + AWAITING_PROOF = 0x04, + ASSEMBLING = 0x05, + COMPLETE = 0x06, + FAILED = 0x07, + CORRUPT = 0x08 + }; + + namespace ResourceAdvertisement { + static const uint8_t OVERHEAD = 134; + static const uint16_t HASHMAP_MAX_LEN = floor((Link::MDU-OVERHEAD)/Resource::MAPHASH_LEN); + //static const uint16_t HASHMAP_MAX_LEN = ((Link::MDU-OVERHEAD)/Resource::MAPHASH_LEN); + static const uint16_t COLLISION_GUARD_SIZE = 2*Resource::WINDOW_MAX+HASHMAP_MAX_LEN; + + //assert HASHMAP_MAX_LEN > 0, "The configured MTU is too small to include any map hashes in resource advertisments" + } + + } + + namespace Channel { + } + } } diff --git a/src/Utilities/OS.h b/src/Utilities/OS.h index 59c1042..8bf5010 100644 --- a/src/Utilities/OS.h +++ b/src/Utilities/OS.h @@ -79,10 +79,12 @@ namespace RNS { namespace Utilities { _filesystem = filesystem; } +/* inline static void register_filesystem(FileSystemImpl* filesystemimpl) { TRACE("Registering filesystem..."); _filesystem = filesystemimpl; } +*/ inline static void deregister_filesystem() { TRACE("Deregistering filesystem..."); diff --git a/src/Utilities/Persistence.h b/src/Utilities/Persistence.h index 615ca70..8aa5ac9 100644 --- a/src/Utilities/Persistence.h +++ b/src/Utilities/Persistence.h @@ -18,14 +18,18 @@ namespace ArduinoJson { template struct Converter> { static void toJson(const std::vector& src, JsonVariant dst) { + TRACE("<<< Serializing vector"); JsonArray array = dst.to(); for (T item : src) array.add(item); + TRACE("<<< Finished serializing vector"); } static std::vector fromJson(JsonVariantConst src) { + TRACE("<<< Deserializing vector"); std::vector dst; for (T item : src.as()) dst.push_back(item); + TRACE("<<< Finished deserializing vector"); return dst; } static bool checkJson(JsonVariantConst src) { @@ -114,6 +118,28 @@ namespace ArduinoJson { } }; +/* + // ArduinoJSON serialization support for RNS::Bytes + template <> + struct Converter { + static bool toJson(const RNS::Bytes& src, JsonVariant dst) { + //TRACE("<<< Serializing Bytes"); + //TRACE("<<< Finished serializing Bytes"); + return true; + } + static RNS::Bytes fromJson(JsonVariantConst src) { + Bytes bytes; + //TRACE(">>> Deserializing Bytes"); + //TRACE(">>> Finished deserializing Bytes"); + return bytes; + } + static bool checkJson(JsonVariantConst src) { + return + src.is(); + } + }; +*/ + /* // ArduinoJSON serialization support for RNS::Interface template <> @@ -190,10 +216,8 @@ namespace ArduinoJson { static RNS::Packet fromJson(JsonVariantConst src) { //TRACE(">>> Deserializing Packet"); RNS::Bytes raw = src["raw"]; - RNS::Packet packet( - {RNS::Type::NONE}, - raw - ); + //RNS::Bytes raw = src["raw"].as(); + RNS::Packet packet(RNS::Destination(RNS::Type::NONE), raw); //packet.set_hash(src["hash"]); packet.sent_at(src["sent_at"]); RNS::Bytes destination_hash = src["destination_hash"]; diff --git a/src/Utilities/Print.h b/src/Utilities/Print.h index ee3b1b7..987a6b1 100644 --- a/src/Utilities/Print.h +++ b/src/Utilities/Print.h @@ -26,10 +26,14 @@ #include #include -#define DEC 10 -#define HEX 16 -#define OCT 8 -#define BIN 2 +//#define DEC 10 +//#define HEX 16 +//#define OCT 8 +//#define BIN 2 +static constexpr uint8_t DEC {10}; +static constexpr uint8_t HEX {16}; +static constexpr uint8_t OCT {8}; +static constexpr uint8_t BIN {2}; class Print { diff --git a/test/crc/Test.cpp b/test/crc/Test.cpp new file mode 100644 index 0000000..77e987c --- /dev/null +++ b/test/crc/Test.cpp @@ -0,0 +1,100 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +// Imported from Crypto.cpp +extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); + +void setUp(void) +{ + // set stuff up here +} + +void tearDown(void) +{ + // clean stuff up here +} + +void testCrc() { + char data[32]; + uint8_t crc; + strcpy(data, "foo"); + crc = crypto_crc8(0, data, sizeof(data)); + TEST_ASSERT_EQUAL_UINT8(174, crc); + strcpy(data, "bar"); + crc = crypto_crc8(0, data, sizeof(data)); + TEST_ASSERT_EQUAL_UINT8(63, crc); + strcpy(data, "foo"); + crc = crypto_crc8(0, data, sizeof(data)); + TEST_ASSERT_EQUAL_UINT8(174, crc); +} + +#ifndef ARDUINO +unsigned long millis() { + timeval time; + ::gettimeofday(&time, NULL); + return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); + return 0; +} +#endif + +#ifdef ARDUINO +void testsleep(float seconds) { delay((uint32_t)(seconds * 1000)); } +#else +void testsleep(float seconds) { timespec time; time.tv_sec = (time_t)(seconds); time.tv_nsec = (seconds - (float)time.tv_sec) * 1000000000; ::nanosleep(&time, nullptr); } +#endif + +uint64_t timeOffset = 0; + +uint64_t ltime() { + // handle roll-over of 32-bit millis (approx. 49 days) + static uint32_t low32, high32; + uint32_t new_low32 = millis(); + if (new_low32 < low32) high32++; + low32 = new_low32; + return ((uint64_t)high32 << 32 | low32) + timeOffset; +} + +void testTime() { + //uint64_t start = RNS::Utilities::OS::ltime(); + //RNS::Utilities::OS::sleep(0.1); + //TEST_ASSERT_TRUE((RNS::Utilities::OS::ltime() - start) > 100); + uint64_t start = ltime(); + testsleep(0.1); + uint64_t end = ltime(); + TEST_ASSERT_TRUE((end - start) > 50); + TEST_ASSERT_TRUE((end - start) < 200); +} + +void testConvert() { + //uint64_t time = ltime(); + //printf("time: %lld\n", time); + + uint64_t num = 1234567890; + TEST_ASSERT_EQUAL_UINT64(1234567890, num); + + char str[16]; + snprintf(str, 16, "%lld", num); + TEST_ASSERT_EQUAL_STRING("1234567890", str); + + char* buf = (char*)# + + //uint64_t newnum = (uint64_t)(*buf); + uint64_t newnum = *(uint64_t*)buf; + TEST_ASSERT_EQUAL_UINT64(1234567890, newnum); +} + +int main(void) +{ + UNITY_BEGIN(); + //RUN_TEST(testCrc); + //RUN_TEST(testTime); + RUN_TEST(testConvert); + return UNITY_END(); +} diff --git a/test/crypto/Test.cpp b/test/crypto/Test.cpp new file mode 100644 index 0000000..77e987c --- /dev/null +++ b/test/crypto/Test.cpp @@ -0,0 +1,100 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +// Imported from Crypto.cpp +extern uint8_t crypto_crc8(uint8_t tag, const void *data, unsigned size); + +void setUp(void) +{ + // set stuff up here +} + +void tearDown(void) +{ + // clean stuff up here +} + +void testCrc() { + char data[32]; + uint8_t crc; + strcpy(data, "foo"); + crc = crypto_crc8(0, data, sizeof(data)); + TEST_ASSERT_EQUAL_UINT8(174, crc); + strcpy(data, "bar"); + crc = crypto_crc8(0, data, sizeof(data)); + TEST_ASSERT_EQUAL_UINT8(63, crc); + strcpy(data, "foo"); + crc = crypto_crc8(0, data, sizeof(data)); + TEST_ASSERT_EQUAL_UINT8(174, crc); +} + +#ifndef ARDUINO +unsigned long millis() { + timeval time; + ::gettimeofday(&time, NULL); + return (uint64_t)(time.tv_sec * 1000) + (uint64_t)(time.tv_usec / 1000); + return 0; +} +#endif + +#ifdef ARDUINO +void testsleep(float seconds) { delay((uint32_t)(seconds * 1000)); } +#else +void testsleep(float seconds) { timespec time; time.tv_sec = (time_t)(seconds); time.tv_nsec = (seconds - (float)time.tv_sec) * 1000000000; ::nanosleep(&time, nullptr); } +#endif + +uint64_t timeOffset = 0; + +uint64_t ltime() { + // handle roll-over of 32-bit millis (approx. 49 days) + static uint32_t low32, high32; + uint32_t new_low32 = millis(); + if (new_low32 < low32) high32++; + low32 = new_low32; + return ((uint64_t)high32 << 32 | low32) + timeOffset; +} + +void testTime() { + //uint64_t start = RNS::Utilities::OS::ltime(); + //RNS::Utilities::OS::sleep(0.1); + //TEST_ASSERT_TRUE((RNS::Utilities::OS::ltime() - start) > 100); + uint64_t start = ltime(); + testsleep(0.1); + uint64_t end = ltime(); + TEST_ASSERT_TRUE((end - start) > 50); + TEST_ASSERT_TRUE((end - start) < 200); +} + +void testConvert() { + //uint64_t time = ltime(); + //printf("time: %lld\n", time); + + uint64_t num = 1234567890; + TEST_ASSERT_EQUAL_UINT64(1234567890, num); + + char str[16]; + snprintf(str, 16, "%lld", num); + TEST_ASSERT_EQUAL_STRING("1234567890", str); + + char* buf = (char*)# + + //uint64_t newnum = (uint64_t)(*buf); + uint64_t newnum = *(uint64_t*)buf; + TEST_ASSERT_EQUAL_UINT64(1234567890, newnum); +} + +int main(void) +{ + UNITY_BEGIN(); + //RUN_TEST(testCrc); + //RUN_TEST(testTime); + RUN_TEST(testConvert); + return UNITY_END(); +}