From 49ccbc2827240016f5700abec5621c71e1d6f3ef Mon Sep 17 00:00:00 2001 From: Chad Attermann Date: Tue, 3 Mar 2026 17:53:06 -0700 Subject: [PATCH] Major bug fixes and performance enhancements - Fixed bug in path table loading from flash storage wherein the raw (packed) announce packet associated with each path entry was not being unpacked prior to use. - Fixed bug in path table entry announce packet loading where critical changes to the announce packet (like hops increment) was being overwriteen each time packet was re-loaded from cache. - Optimized path table entries to lazy-load both announce packet and receive interface so that memory is consumed by these structures until if/when the path is actually used. - Updated several global timers and sizes to match new RNS 1.x values. - Bumped version to 0.2.9 --- library.json | 2 +- library.properties | 2 +- src/Destination.cpp | 6 +- src/Identity.cpp | 16 +- src/Interface.cpp | 33 ++- src/Interface.h | 4 +- src/Packet.cpp | 15 +- src/Packet.h | 2 + src/Reticulum.cpp | 59 +++-- src/Transport.cpp | 334 +++++++++++------------- src/Transport.h | 66 +++-- src/Type.h | 16 +- src/Utilities/Persistence.h | 54 ++-- test/test_persistence/test_main.cpp | 24 +- test/test_rns_persistence/test_main.cpp | 20 +- test/test_transport/test_main.cpp | 12 +- 16 files changed, 361 insertions(+), 304 deletions(-) diff --git a/library.json b/library.json index b568623..ffba21a 100644 --- a/library.json +++ b/library.json @@ -1,6 +1,6 @@ { "name": "microReticulum", - "version": "0.2.8", + "version": "0.2.9", "description": "Port of Reticulum Network Stack to C++ specifically but not exclusively targeting 32-bit and better MCUs", "keywords": "reticulum, rns, mesh, embedded, mcu, esp32, nrf52, native", "repository": diff --git a/library.properties b/library.properties index 6b8bf01..c0de963 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=microReticulum -version=0.2.8 +version=0.2.9 author=Chad Attermann maintainer=Chad Attermann sentence=Port of Reticulum Network Stack to C++ diff --git a/src/Destination.cpp b/src/Destination.cpp index 88c0e97..290f229 100644 --- a/src/Destination.cpp +++ b/src/Destination.cpp @@ -289,7 +289,7 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In _object->_path_responses.insert({tag, {OS::time(), announce_data}}); } catch (const std::bad_alloc&) { - ERRORF("announce: bad_alloc - out of memory, path response not stored for %s", _object->_hash.toHex().c_str()); + ERRORF("announce: bad_alloc - OUT OF MEMORY, path response not stored for %s", _object->_hash.toHex().c_str()); } catch (const std::exception& e) { ERRORF("announce: exception storing path response: %s", e.what()); @@ -317,7 +317,7 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In } } catch (const std::bad_alloc&) { - ERRORF("announce: bad_alloc - out of memory, announce not sent for %s", _object->_hash.toHex().c_str()); + ERRORF("announce: bad_alloc - OUT OF MEMORY, announce not sent for %s", _object->_hash.toHex().c_str()); return {Type::NONE}; } catch (const std::exception& e) { @@ -407,7 +407,7 @@ TRACE("***** Accepting link request"); _object->_links.insert(link); } catch (const std::bad_alloc&) { - ERROR("incoming_link_request: bad_alloc - out of memory, link not tracked"); + ERROR("incoming_link_request: bad_alloc - OUT OF MEMORY, link not tracked"); } catch (const std::exception& e) { ERRORF("incoming_link_request: exception tracking link: %s", e.what()); diff --git a/src/Identity.cpp b/src/Identity.cpp index 0915386..e27a5cd 100644 --- a/src/Identity.cpp +++ b/src/Identity.cpp @@ -205,7 +205,7 @@ Can be used to load previously created and saved identities into Reticulum. cull_known_destinations(); } catch (const std::bad_alloc&) { - ERRORF("remember: bad_alloc - out of memory, identity not stored for %s", destination_hash.toHex().c_str()); + ERRORF("remember: bad_alloc - OUT OF MEMORY, identity not stored for %s", destination_hash.toHex().c_str()); } catch (const std::exception& e) { ERRORF("remember: exception storing identity: %s", e.what()); @@ -319,19 +319,9 @@ Recall last heard app_data for a destination hash. file = open(RNS.Reticulum.storagepath+"/known_destinations","wb") umsgpack.dump(Identity.known_destinations, file) file.close() + DEBUGF("Saved known destinations to storage in %.3f seconds", OS::round(OS::time() - save_start, 3)); */ - std::string time_str; - double save_time = OS::time() - save_start; - if (save_time < 1) { - time_str = std::to_string((int)(save_time*1000)) + " ms"; - } - else { - time_str = std::to_string(OS::round(save_time, 1)) + " s"; - } - - DEBUGF("Saved known destinations to storage in %s", time_str.c_str()); - success = true; } catch (std::exception& e) { @@ -394,7 +384,7 @@ Recall last heard app_data for a destination hash. DEBUGF("Removed %d path(s) from known destinations", count); } catch (const std::bad_alloc& e) { - ERROR("cull_known_destinations: bad_alloc - out of memory building sort index, falling back to single erase"); + ERROR("cull_known_destinations: bad_alloc - OUT OF MEMORY building sort index, falling back to single erase"); // Fallback: std::min_element does no heap allocation — erase one oldest entry auto oldest = std::min_element( _known_destinations.begin(), _known_destinations.end(), diff --git a/src/Interface.cpp b/src/Interface.cpp index d299f89..d12303f 100644 --- a/src/Interface.cpp +++ b/src/Interface.cpp @@ -25,16 +25,41 @@ void InterfaceImpl::handle_incoming(const Bytes& data) { Transport::inbound(data, interface); } -void Interface::handle_incoming(const Bytes& data) { - //TRACEF("Interface.handle_incoming: data: %s", data.toHex().c_str()); - TRACE("Interface.handle_incoming"); +void Interface::send_outgoing(const Bytes& data) { assert(_impl); + //TRACEF("Interface.send_outgoing: data: %s", data.toHex().c_str()); + //TRACE("Interface.send_outgoing"); + // Catch exceptions from calls into Interface implementation + try { + _impl->send_outgoing(data); + } + catch (const std::bad_alloc&) { + ERROR("Interface::send_outgoing: bad_alloc - OUT OF MEMORY"); + } + catch (std::exception& e) { + ERRORF("Interface::send_outgoing: %s", e.what()); + } +} + +void Interface::handle_incoming(const Bytes& data) { + assert(_impl); + //TRACEF("Interface.handle_incoming: data: %s", data.toHex().c_str()); + //TRACE("Interface.handle_incoming"); /* _impl->_rxb += data.size(); // Pass data on to transport for handling Transport::inbound(data, *this); */ - _impl->handle_incoming(data); + // Catch exceptions from calls into Interface implementation + try { + _impl->handle_incoming(data); + } + catch (const std::bad_alloc&) { + ERROR("Interface::handle_incoming: bad_alloc - OUT OF MEMORY"); + } + catch (std::exception& e) { + ERRORF("Interface::handle_incoming: %s", e.what()); + } } void Interface::process_announce_queue() { diff --git a/src/Interface.h b/src/Interface.h index df5edbd..2983d58 100644 --- a/src/Interface.h +++ b/src/Interface.h @@ -161,9 +161,9 @@ namespace RNS { inline void add_announce(AnnounceEntry& entry) { assert(_impl); _impl->_announce_queue.push_back(entry); } protected: - inline void send_outgoing(const Bytes& data) { assert(_impl); _impl->send_outgoing(data); } + // Internal method to handle data going out on interface and pass on to impl + void send_outgoing(const Bytes& data); public: - //inline void handle_incoming(const Bytes& data) { assert(_impl); _impl->handle_incoming(data); } // Public method to handle data coming in on interface and pass on to impl void handle_incoming(const Bytes& data); diff --git a/src/Packet.cpp b/src/Packet.cpp index 707ec9b..6624077 100644 --- a/src/Packet.cpp +++ b/src/Packet.cpp @@ -23,7 +23,7 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa { if (_object->_destination) { - TRACE("Creating packet with destination..."); + //TRACE("Creating packet with destination..."); // CBA Should never see empty transport_type //if (transport_type == NONE) { // transport_type = Type::Transport::BROADCAST; @@ -47,7 +47,7 @@ Packet::Packet(const Destination& destination, const Interface& attached_interfa _object->_create_receipt = create_receipt; } else { - TRACE("Creating packet without destination..."); + //TRACE("Creating packet without destination..."); // CBA NOTE: This variant is for creating a new packet from a received raw buffer _object->_raw = data; _object->_packed = true; @@ -78,14 +78,14 @@ uint8_t Packet::get_packed_flags() { assert(_object); uint8_t packed_flags = 0; if (_object->_context == LRPROOF) { -TRACE("***** Packing with LINK type"); +//TRACE("***** Packing with LINK type"); packed_flags = (_object->_header_type << 6) | (_object->_context_flag << 5) | (_object->_transport_type << 4) | (Type::Destination::LINK << 2) | _object->_packet_type; } else { if (!_object->_destination) { throw std::logic_error("Packet destination is required"); } -TRACEF("***** Packing with %d type", _object->_destination.type()); +//TRACEF("***** Packing with %d type", _object->_destination.type()); packed_flags = (_object->_header_type << 6) | (_object->_context_flag << 5) | (_object->_transport_type << 4) | (_object->_destination.type() << 2) | _object->_packet_type; } return packed_flags; @@ -420,7 +420,7 @@ bool Packet::unpack() { update_hash(); } catch (const std::bad_alloc&) { - ERROR("Packet::unpack: bad_alloc - out of memory unpacking packet"); + ERROR("Packet::unpack: bad_alloc - OUT OF MEMORY unpacking packet"); return false; } catch (std::exception& e) { @@ -589,14 +589,15 @@ std::string Packet::debugString() const { if (_object->_packed) { //unpack(); } - std::string str = "ph=" + _object->_packet_hash.toHex(); - str += " ht=" + std::to_string(_object->_header_type); + std::string str; + str = "ht=" + std::to_string(_object->_header_type); str += " tt=" + std::to_string(_object->_transport_type); str += " dt=" + std::to_string(_object->_destination_type); str += " pt=" + std::to_string(_object->_packet_type); str += " hp=" + std::to_string(_object->_hops); str += " ti=" + _object->_transport_id.toHex(); str += " dh=" + _object->_destination_hash.toHex(); + str += " ph=" + _object->_packet_hash.toHex(); return str; } std::string Packet::dumpString() const { diff --git a/src/Packet.h b/src/Packet.h index b7ca023..8bb463d 100644 --- a/src/Packet.h +++ b/src/Packet.h @@ -250,6 +250,8 @@ namespace RNS { 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 bool packed() const { assert(_object); return _object->_packed; } + inline bool from_packed() const { assert(_object); return _object->_fromPacked; } // setters inline void destination(const Destination& destination) { assert(_object); _object->_destination = destination; } diff --git a/src/Reticulum.cpp b/src/Reticulum.cpp index 62b187d..7616797 100644 --- a/src/Reticulum.cpp +++ b/src/Reticulum.cpp @@ -205,31 +205,40 @@ void Reticulum::start() { void Reticulum::loop() { assert(_object); - if (!_object->_is_connected_to_shared_instance) { + // Catch exceptions from loop work + try { + if (!_object->_is_connected_to_shared_instance) { - // Perform Reticulum housekeeping - if (OS::time() > (_object->_jobs_last_run + JOB_INTERVAL)) { - jobs(); - _object->_jobs_last_run = OS::time(); + // Perform Reticulum housekeeping + if (OS::time() > (_object->_jobs_last_run + JOB_INTERVAL)) { + jobs(); + _object->_jobs_last_run = OS::time(); + } + + // Perform interface processing + for (auto& [hash, interface] : Transport::get_interfaces()) { + interface.loop(); + } + + // Perform Filesystem processing + FileSystem& filesystem = OS::get_filesystem(); + if (filesystem) { + filesystem.loop(); + } + + // Perform Transport processing + RNS::Transport::loop(); } - // Perform interface processing - for (auto& [hash, interface] : Transport::get_interfaces()) { - interface.loop(); - } - - // Perform Filesystem processing - FileSystem& filesystem = OS::get_filesystem(); - if (filesystem) { - filesystem.loop(); - } - - - // Perform Transport processing - RNS::Transport::loop(); - } - // Perform random number gnerator housekeeping - RNG.loop(); + // Perform random number gnerator housekeeping + RNG.loop(); + } + catch (const std::bad_alloc&) { + ERROR("Reticulum::loop: bad_alloc - OUT OF MEMORY"); + } + catch (std::exception& e) { + ERRORF("Reticulum::loop: %s", e.what()); + } } void Reticulum::jobs() { @@ -411,7 +420,7 @@ const std::map& Reticulum::get_path_table() return path_table */ - return Transport::get_destination_table(); + return Transport::get_path_table(); } const std::map& Reticulum::get_rate_table() const { @@ -438,8 +447,8 @@ bool Reticulum::drop_path(const Bytes& destination) { uint16_t Reticulum::drop_all_via(const Bytes& transport_hash) { uint16_t dropped_count = 0; - //for (auto& destination_hash : Transport::get_destination_table()) { - for (const auto& [destination_hash, destination_entry] : Transport::get_destination_table()) { + //for (auto& destination_hash : Transport::get_path_table()) { + for (const auto& [destination_hash, destination_entry] : Transport::get_path_table()) { if (destination_entry._received_from == transport_hash) { Transport::expire_path(destination_hash); ++dropped_count; diff --git a/src/Transport.cpp b/src/Transport.cpp index 7075ee2..b16a009 100644 --- a/src/Transport.cpp +++ b/src/Transport.cpp @@ -54,7 +54,7 @@ using namespace RNS::Utilities; /*static*/ std::list Transport::_receipts; /*static*/ std::map Transport::_announce_table; -/*static*/ std::map Transport::_destination_table; +/*static*/ std::map Transport::_path_table; /*static*/ std::map Transport::_reverse_table; /*static*/ std::map Transport::_link_table; /*static*/ std::map Transport::_held_announces; @@ -109,7 +109,7 @@ using namespace RNS::Utilities; /*static*/ uint16_t Transport::_path_table_maxpersist = RNS_PATH_TABLE_MAX; /*static*/ double Transport::_last_saved = 0.0; /*static*/ float Transport::_save_interval = 3600.0; -/*static*/ uint32_t Transport::_destination_table_crc = 0; +/*static*/ uint32_t Transport::_path_table_crc = 0; /*static*/ uint16_t Transport::_announce_table_maxsize = RNS_ANNOUNCE_TABLE_MAX; /*static*/ Reticulum Transport::_owner({Type::NONE}); @@ -138,12 +138,13 @@ using namespace RNS::Utilities; _tables_last_culled = OS::time(); _last_saved = OS::time(); - // ensure required directories exist + // Ensure required directories exist if (!OS::directory_exists(Reticulum::_cachepath)) { VERBOSE("No cache directory, creating..."); OS::create_directory(Reticulum::_cachepath); } + // Load transport identity if (!_identity) { char transport_identity_path[Type::Reticulum::FILEPATH_MAXSIZE]; snprintf(transport_identity_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/transport_identity", Reticulum::_storagepath); @@ -169,6 +170,7 @@ using namespace RNS::Utilities; // TODO /* + // Load packet hashlist packet_hashlist_path = Reticulum::storagepath + "/packet_hashlist"; if (!owner.is_connected_to_shared_instance()) { if (os.path.isfile(packet_hashlist_path)) { @@ -204,12 +206,13 @@ using namespace RNS::Utilities; _control_hashes.insert(tunnel_synthesize_destination.hash()); DEBUGF("Created transport-specific tunnel synthesize destination %s", tunnel_synthesize_destination.hash().toHex().c_str()); + // Start job loops _jobs_running = false; - // CBA Threading //p thread = threading.Thread(target=Transport.jobloop, daemon=True) //p thread.start() + // Load transport-related data if (Reticulum::transport_enabled()) { INFO("Transport mode is enabled"); @@ -219,6 +222,7 @@ using namespace RNS::Utilities; write_path_table(); clean_caches(); + // Read in tunnel table read_tunnel_table(); // Create transport-specific destination for probe requests @@ -235,6 +239,10 @@ using namespace RNS::Utilities; _start_time = OS::time(); } + // CBA TODO + // Sort interfaces according to bitrate + //p Transport.prioritize_interfaces() + // TODO /*p // Synthesize tunnels for any interfaces wanting it @@ -563,8 +571,8 @@ using namespace RNS::Utilities; // Cull the path table try { std::vector stale_paths; - stale_paths.reserve(_destination_table.size()); - for (const auto& [destination_hash, destination_entry] : _destination_table) { + stale_paths.reserve(_path_table.size()); + for (auto& [destination_hash, destination_entry] : _path_table) { const Interface& attached_interface = destination_entry.receiving_interface(); double destination_expiry; if (attached_interface && attached_interface.mode() == Type::Interface::MODE_ACCESS_POINT) { @@ -773,10 +781,10 @@ using namespace RNS::Utilities; // Check if we have a known path for the destination in the path table //if packet.packet_type != RNS.Packet.ANNOUNCE and packet.destination.type != RNS.Destination.PLAIN and packet.destination.type != RNS.Destination.GROUP and packet.destination_hash in Transport.destination_table: - if (packet.packet_type() != Type::Packet::ANNOUNCE && packet.destination().type() != Type::Destination::PLAIN && packet.destination().type() != Type::Destination::GROUP && _destination_table.find(packet.destination_hash()) != _destination_table.end()) { + if (packet.packet_type() != Type::Packet::ANNOUNCE && packet.destination().type() != Type::Destination::PLAIN && packet.destination().type() != Type::Destination::GROUP && _path_table.find(packet.destination_hash()) != _path_table.end()) { TRACE("Transport::outbound: Path to destination is known"); //outbound_interface = Transport.destination_table[packet.destination_hash][5] - DestinationEntry destination_entry = (*_destination_table.find(packet.destination_hash())).second; + DestinationEntry destination_entry = (*_path_table.find(packet.destination_hash())).second; Interface outbound_interface = destination_entry.receiving_interface(); // If there's more than one hop to the destination, and we know @@ -803,7 +811,7 @@ using namespace RNS::Utilities; //new_raw += packet.raw[2:] new_raw << packet.raw().mid(2); transmit(outbound_interface, new_raw); - //_destination_table[packet.destination_hash][0] = time.time() + //_path_table[packet.destination_hash][0] = time.time() destination_entry._timestamp = OS::time(); sent = true; } @@ -1389,8 +1397,8 @@ using namespace RNS::Utilities; bool for_local_client = false; bool for_local_client_link = false; if (packet.packet_type() != Type::Packet::ANNOUNCE) { - auto destination_iter = _destination_table.find(packet.destination_hash()); - if (destination_iter != _destination_table.end()) { + auto destination_iter = _path_table.find(packet.destination_hash()); + if (destination_iter != _path_table.end()) { DestinationEntry destination_entry = (*destination_iter).second; if (destination_entry._hops == 0) { // Destined for a local destination @@ -1500,8 +1508,8 @@ using namespace RNS::Utilities; TRACE("Transport::inbound: Packet is in transport..."); if (packet.transport_id() == _identity.hash()) { TRACE("Transport::inbound: We are designated next-hop"); - auto destination_iter = _destination_table.find(packet.destination_hash()); - if (destination_iter != _destination_table.end()) { + auto destination_iter = _path_table.find(packet.destination_hash()); + if (destination_iter != _path_table.end()) { TRACE("Transport::inbound: Found next-hop path to destination"); DestinationEntry destination_entry = (*destination_iter).second; Bytes next_hop = destination_entry._received_from; @@ -1783,8 +1791,8 @@ using namespace RNS::Utilities; //p random_blobs = [] std::set empty_random_blobs; std::set& random_blobs = empty_random_blobs; - auto iter = _destination_table.find(packet.destination_hash()); - if (iter != _destination_table.end()) { + auto iter = _path_table.find(packet.destination_hash()); + if (iter != _path_table.end()) { DestinationEntry destination_entry = (*iter).second; //p random_blobs = Transport.destination_table[packet.destination_hash][4] random_blobs = destination_entry._random_blobs; @@ -2095,7 +2103,7 @@ using namespace RNS::Utilities; try { // CBA First remove any existing path before inserting new one remove_path(packet.destination_hash()); - if (_destination_table.insert({packet.destination_hash(), destination_table_entry}).second) { + if (_path_table.insert({packet.destination_hash(), destination_table_entry}).second) { TRACEF("Added destination %s to path table!", packet.destination_hash().toHex().c_str()); ++_destinations_added; // CBA IMMEDIATE CULL @@ -2687,6 +2695,29 @@ Deregisters an announce handler. } } +/*static*/ bool Transport::is_interface_from_hash(const Bytes& interface_hash) { +#if defined(INTERFACES_SET) + for (const Interface& interface : _interfaces) { + if (interface.get_hash() == interface_hash) { + return true; + } + } +#elif defined(INTERFACES_LIST) + for (Interface& interface : _interfaces) { + if (interface.get_hash() == interface_hash) { + return true; + } + } +#elif defined(INTERFACES_MAP) + auto iter = _interfaces.find(interface_hash); + if (iter != _interfaces.end()) { + return true; + } +#endif + + return false; +} + /*static*/ Interface Transport::find_interface_from_hash(const Bytes& interface_hash) { #if defined(INTERFACES_SET) for (const Interface& interface : _interfaces) { @@ -2746,30 +2777,24 @@ Deregisters an announce handler. return false; } +/*static*/ bool Transport::is_cached_packet(const Bytes& packet_hash) { +#if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS) + try { + char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE]; + snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, packet_hash.toHex().c_str()); + return OS::file_exists(packet_cache_path); + } + catch (std::exception& e) { + ERRORF("Exception occurred while getting cached packet: %s", e.what()); + } +#endif + return false; +} + /*static*/ Packet Transport::get_cached_packet(const Bytes& packet_hash) { TRACEF("Loading packet %s from cache storage", packet_hash.toHex().c_str()); #if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS) try { -/*p - packet_hash = RNS.hexrep(packet_hash, delimit=False) - path = RNS.Reticulum.cachepath+"/"+packet_hash - - if os.path.isfile(path): - file = open(path, "rb") - cached_data = umsgpack.unpackb(file.read()) - file.close() - - packet = RNS.Packet(None, cached_data[0]) - interface_reference = cached_data[1] - - for interface in Transport.interfaces: - if str(interface) == interface_reference: - packet.receiving_interface = interface - - return packet - else: - return None -*/ char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE]; snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, packet_hash.toHex().c_str()); Packet packet({Type::NONE}); @@ -2779,8 +2804,7 @@ Deregisters an announce handler. return packet; } catch (std::exception& e) { - ERROR("Exception occurred while getting cached packet."); - ERRORF("The contained exception was: %s", e.what()); + ERRORF("Exception occurred while getting cached packet: %s", e.what()); } #endif return {Type::NONE}; @@ -2847,15 +2871,15 @@ Deregisters an announce handler. } /*static*/ bool Transport::remove_path(const Bytes& destination_hash) { - auto iter = _destination_table.find(destination_hash); - if (iter != _destination_table.end()) { + auto iter = _path_table.find(destination_hash); + if (iter != _path_table.end()) { // Remove cached packet file associated with this destination char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE]; - snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, iter->second._announce_packet.toHex().c_str()); + snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, iter->second.announce_packet_hash().toHex().c_str()); if (OS::file_exists(packet_cache_path)) { OS::remove_file(packet_cache_path); } - if (_destination_table.erase(destination_hash) < 1) { + if (_path_table.erase(destination_hash) < 1) { WARNINGF("Failed to remove destination %s from path table", destination_hash.toHex().c_str()); } return true; @@ -2868,7 +2892,7 @@ Deregisters an announce handler. :returns: *True* if a path to the destination is known, otherwise *False*. */ /*static*/ bool Transport::has_path(const Bytes& destination_hash) { - if (_destination_table.find(destination_hash) != _destination_table.end()) { + if (_path_table.find(destination_hash) != _path_table.end()) { return true; } else { @@ -2881,8 +2905,8 @@ Deregisters an announce handler. :returns: The number of hops to the specified destination, or ``RNS.Transport.PATHFINDER_M`` if the number of hops is unknown. */ /*static*/ uint8_t Transport::hops_to(const Bytes& destination_hash) { - auto iter = _destination_table.find(destination_hash); - if (iter != _destination_table.end()) { + auto iter = _path_table.find(destination_hash); + if (iter != _path_table.end()) { DestinationEntry destination_entry = (*iter).second; return destination_entry._hops; } @@ -2896,8 +2920,8 @@ Deregisters an announce handler. :returns: The destination hash as *bytes* for the next hop to the specified destination, or *None* if the next hop is unknown. */ /*static*/ Bytes Transport::next_hop(const Bytes& destination_hash) { - auto iter = _destination_table.find(destination_hash); - if (iter != _destination_table.end()) { + auto iter = _path_table.find(destination_hash); + if (iter != _path_table.end()) { DestinationEntry destination_entry = (*iter).second; return destination_entry._received_from; } @@ -2911,8 +2935,8 @@ Deregisters an announce handler. :returns: The interface for the next hop to the specified destination, or *None* if the interface is unknown. */ /*static*/ Interface Transport::next_hop_interface(const Bytes& destination_hash) { - auto iter = _destination_table.find(destination_hash); - if (iter != _destination_table.end()) { + auto iter = _path_table.find(destination_hash); + if (iter != _path_table.end()) { DestinationEntry destination_entry = (*iter).second; return destination_entry.receiving_interface(); } @@ -2982,8 +3006,8 @@ Deregisters an announce handler. } /*static*/ bool Transport::expire_path(const Bytes& destination_hash) { - auto iter = _destination_table.find(destination_hash); - if (iter != _destination_table.end()) { + auto iter = _path_table.find(destination_hash); + if (iter != _path_table.end()) { DestinationEntry destination_entry = (*iter).second; destination_entry._timestamp = 0; _tables_last_culled = 0; @@ -3183,8 +3207,8 @@ will announce it. bool destination_exists_on_local_client = false; if (_local_client_interfaces.size() > 0) { - auto iter = _destination_table.find(destination_hash); - if (iter != _destination_table.end()) { + auto iter = _path_table.find(destination_hash); + if (iter != _path_table.end()) { TRACEF("Transport::path_request_handler: entry found for destination %s", destination_hash.toHex().c_str()); DestinationEntry& destination_entry = (*iter).second; if (is_local_client_interface(destination_entry.receiving_interface())) { @@ -3198,7 +3222,7 @@ will announce it. } } - auto destination_iter = _destination_table.find(destination_hash); + auto destination_iter = _path_table.find(destination_hash); //local_destination = next((d for d in Transport.destinations if d.hash == destination_hash), None) #if defined(DESTINATIONS_SET) Destination local_destination({Type::NONE}); @@ -3219,10 +3243,13 @@ will announce it. DEBUGF("Answering path request for destination %s%s, destination is local to this system", destination_hash.toHex().c_str(), interface_str.c_str()); } //p elif (RNS.Reticulum.transport_enabled() or is_from_local_client) and (destination_hash in Transport.destination_table): - else if ((Reticulum::transport_enabled() || is_from_local_client) && destination_iter != _destination_table.end()) { + else if ((Reticulum::transport_enabled() || is_from_local_client) && destination_iter != _path_table.end()) { TRACEF("Transport::path_request_handler: entry found for destination %s", destination_hash.toHex().c_str()); DestinationEntry& destination_entry = (*destination_iter).second; const Packet& announce_packet = destination_entry.announce_packet(); +TRACEF("announce_packet destination_hash: %s", announce_packet.destination_hash().toHex().c_str()); +TRACEF("announce_packet hops: %u", announce_packet.hops()); +TRACEF("announce_packet str: %s", announce_packet.toString().c_str()); const Bytes& next_hop = destination_entry._received_from; const Interface& receiving_interface = destination_entry.receiving_interface(); @@ -3522,12 +3549,7 @@ will announce it. file.write(umsgpack.packb(Transport.packet_hashlist)) file.close() - save_time = time.time() - save_start - if save_time < 1: - time_str = str(round(save_time*1000,2))+"ms" - else: - time_str = str(round(save_time,2))+"s" - RNS.log("Saved packet hashlist in "+time_str, RNS.LOG_DEBUG) + DEBUGF("Saved packet hashlist in %.3f seconds", OS::round(time.time() - save_start)) except Exception as e: RNS.log("Could not save packet hashlist to storage, the contained exception was: "+str(e), RNS.LOG_ERROR) @@ -3545,51 +3567,15 @@ will announce it. char destination_table_path[Type::Reticulum::FILEPATH_MAXSIZE]; snprintf(destination_table_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/destination_table", Reticulum::_storagepath); if (!_owner.is_connected_to_shared_instance() && OS::file_exists(destination_table_path)) { -/*p - serialised_destinations = [] - try: - file = open(destination_table_path, "rb") - serialised_destinations = umsgpack.unpackb(file.read()) - file.close() - - for serialised_entry in serialised_destinations: - destination_hash = serialised_entry[0] - - if len(destination_hash) == RNS.Reticulum.TRUNCATED_HASHLENGTH//8: - timestamp = serialised_entry[1] - received_from = serialised_entry[2] - hops = serialised_entry[3] - expires = serialised_entry[4] - random_blobs = serialised_entry[5] - receiving_interface = Transport.find_interface_from_hash(serialised_entry[6]) - announce_packet = Transport.get_cached_packet(serialised_entry[7]) - - if announce_packet != None and receiving_interface != None: - announce_packet.unpack() - // We increase the hops, since reading a packet - // from cache is equivalent to receiving it again - // over an interface. It is cached with it's non- - // increased hop-count. - announce_packet.hops += 1 - Transport.destination_table[destination_hash] = [timestamp, received_from, hops, expires, random_blobs, receiving_interface, announce_packet] - RNS.log("Loaded path table entry for "+RNS.prettyhexrep(destination_hash)+" from storage", RNS.LOG_DEBUG) - else: - RNS.log("Could not reconstruct path table entry from storage for "+RNS.prettyhexrep(destination_hash), RNS.LOG_DEBUG) - if announce_packet == None: - RNS.log("The announce packet could not be loaded from cache", RNS.LOG_DEBUG) - if receiving_interface == None: - RNS.log("The interface is no longer available", RNS.LOG_DEBUG) -*/ - try { #if CUSTOM -TRACEF("Transport::start: buffer capacity %d bytes", Persistence::_buffer.capacity()); +TRACEF("Transport::read_path_table: buffer capacity %d bytes", Persistence::_buffer.capacity()); if (RNS::Utilities::OS::read_file(destination_table_path, Persistence::_buffer) > 0) { - TRACEF("Transport::start: read: %d bytes", Persistence::_buffer.size()); + TRACEF("Transport::read_path_table: read: %d bytes", Persistence::_buffer.size()); #ifndef NDEBUG // CBA DEBUG Dump path table -TRACEF("Transport::start: buffer addr: 0x%X", Persistence::_buffer.data()); -TRACEF("Transport::start: buffer size %d bytes", Persistence::_buffer.size()); +TRACEF("Transport::read_path_table: buffer addr: 0x%X", Persistence::_buffer.data()); +TRACEF("Transport::read_path_table: buffer size %d bytes", Persistence::_buffer.size()); //TRACE("SERIALIZED: destination_table"); //TRACE(Persistence::_buffer.toString().c_str()); #endif @@ -3598,53 +3584,57 @@ TRACEF("Transport::start: buffer size %d bytes", Persistence::_buffer.size()); #else DeserializationError error = deserializeJson(Persistence::_document, Persistence::_buffer.data()); #endif - TRACEF("Transport::start: doc size: %d bytes", Persistence::_buffer.size()); + TRACEF("Transport::read_path_table: doc size: %d bytes", Persistence::_buffer.size()); if (!error) { // Calculate crc for dirty-checking before write - _destination_table_crc = Crc::crc32(0, Persistence::_buffer.data(), Persistence::_buffer.size()); - _destination_table = Persistence::_document.as>(); + _path_table_crc = Crc::crc32(0, Persistence::_buffer.data(), Persistence::_buffer.size()); + _path_table = Persistence::_document.as>(); #else // CUSTOM - // Calculate crc for dirty-checking before write - if (Persistence::deserialize(_destination_table, destination_table_path, _destination_table_crc) > 0) { + // Calculate crc for dirty-checking before later write + if (Persistence::deserialize(_path_table, destination_table_path, _path_table_crc) > 0) { #endif // CUSTOM - TRACEF("Transport::start: successfully deserialized path table with %d entries", _destination_table.size()); + TRACEF("Transport::read_path_table: successfully deserialized path table with %d entries", _path_table.size()); std::vector invalid_paths; - for (auto& [destination_hash, destination_entry] : _destination_table) { + for (auto& [destination_hash, destination_entry] : _path_table) { #ifndef NDEBUG - TRACEF("Transport::start: entry: %s = %s", destination_hash.toHex().c_str(), destination_entry.debugString().c_str()); + TRACEF("Transport::read_path_table: hash: %s entry: {%s}", destination_hash.toHex().c_str(), destination_entry.debugString().c_str()); #endif - // CBA If announce packet load fails then remove destination entry (it's useless without announce packet) - if (!destination_entry.announce_packet()) { + // CBA Avoid accessing announce_packet() and receiving_interface() until actually needed in order to + // take advantage of lazy loading and avoid incurring memory hit to store if not actually needed. + + // CBA If announce packet is not cached then remove destination entry (it's useless without announce packet) + if (!is_cached_packet(destination_entry.announce_packet_hash())) { // remove destination - WARNINGF("Transport::start: removing invalid path to %s due to missing announce packet", destination_hash.toHex().c_str()); + WARNINGF("Transport::read_path_table: removing invalid path to %s due to missing announce packet", destination_hash.toHex().c_str()); invalid_paths.push_back(destination_hash); + continue; } - // CBA If receiving interface is not found then remove destination entry (it's useless without interface) - if (!destination_entry.receiving_interface()) { + // CBA If receiving interface is not present then remove destination entry (it's useless without receiving interface) + if (!is_interface_from_hash(destination_entry.receiving_interface_hash())) { // remove destination - WARNINGF("Transport::start: removing invalid path to %s due to missing receiving interface", destination_hash.toHex().c_str()); + WARNINGF("Transport::read_path_table: removing invalid path to %s due to missing receiving interface", destination_hash.toHex().c_str()); invalid_paths.push_back(destination_hash); + continue; } + DEBUGF("Loaded path table entry for %s from storage", destination_hash.toHex().c_str()); } for (const auto& destination_hash : invalid_paths) { - _destination_table.erase(destination_hash); + _path_table.erase(destination_hash); } + VERBOSEF("Loaded %zu path table entries from storage", _path_table.size()); return true; } else { - TRACE("Transport::start: failed to deserialize"); + TRACE("Transport::read_path_table: failed to deserialize"); } #if CUSTOM } else { - TRACE("Transport::start: destination table read failed"); + TRACE("Transport::read_path_table: destination table read failed"); } #else // CUSTOM #endif // CUSTOM - - VERBOSEF("Loaded %d valid path table entries from storage", _destination_table.size()); - } catch (std::exception& e) { ERRORF("Could not load destination table from storage, the contained exception was: %s", e.what()); @@ -3679,7 +3669,6 @@ TRACEF("Transport::start: buffer size %d bytes", Persistence::_buffer.size()); try { _saving_path_table = true; double save_start = OS::time(); - DEBUGF("Saving %d path table entries to storage...", _destination_table.size()); /*p serialised_destinations = [] @@ -3724,7 +3713,7 @@ TRACEF("Transport::start: buffer size %d bytes", Persistence::_buffer.size()); #if CUSTOM { - Persistence::_document.set(_destination_table); + Persistence::_document.set(_path_table); TRACEF("Transport::write_path_table: doc size %d bytes", Persistence::_document.memoryUsage()); //size_t size = 8192; @@ -3743,8 +3732,6 @@ TRACEF("Transport::write_path_table: buffer addr: %ld", (long)buffer); } } if (Persistence::_buffer.size() > 0) { - char destination_table_path[Type::Reticulum::FILEPATH_MAXSIZE]; - snprintf(destination_table_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/destination_table", Reticulum::_storagepath); #ifndef NDEBUG // CBA DEBUG Dump path table TRACEF("Transport::write_path_table: buffer addr: %ld", (long)Persistence::_buffer.data()); @@ -3754,55 +3741,57 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe #endif // Check crc to see if data has changed before writing uint32_t crc = Crc::crc32(0, Persistence::_buffer.data(), Persistence::_buffer.size()); - if (_destination_table_crc > 0 && crc == _destination_table_crc) { + if (_path_table_crc > 0 && crc == _path_table_crc) { TRACE("Transport::write_path_table: no change detected, skipping write"); } - else if (RNS::Utilities::OS::write_file(destination_table_path, Persistence::_buffer) == Persistence::_buffer.size()) { - TRACEF("Transport::write_path_table: wrote %d entries, %d bytes", _destination_table.size(), Persistence::_buffer.size()); - _destination_table_crc = crc; - success = true; + else { + TRACE("Transport::write_path_table: change detected, writing..."); + DEBUGF("Saving %d path table entries to storage...", _path_table.size()); + char destination_table_path[Type::Reticulum::FILEPATH_MAXSIZE]; + snprintf(destination_table_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/destination_table", Reticulum::_storagepath); + if (RNS::Utilities::OS::write_file(destination_table_path, Persistence::_buffer) == Persistence::_buffer.size()) { + TRACEF("Transport::write_path_table: wrote %d entries, %d bytes", _path_table.size(), Persistence::_buffer.size()); + _path_table_crc = crc; + success = true; #ifndef NDEBUG - // CBA DEBUG Dump path table - //TRACE("FILE: destination_table"); - //if (OS::read_file("/destination_table", Persistence::_buffer) > 0) { - // TRACE(Persistence::_buffer.toString().c_str()); - //} + // CBA DEBUG Dump path table + //TRACE("FILE: destination_table"); + //if (OS::read_file("/destination_table", Persistence::_buffer) > 0) { + // TRACE(Persistence::_buffer.toString().c_str()); + //} #endif - } - else { - TRACE("Transport::write_path_table: write failed"); + } + else { + ERROR("Transport::write_path_table: write failed"); + } } } else { - TRACE("Transport::write_path_table: failed to serialize"); + ERROR("Transport::write_path_table: failed to serialize"); } #else // CUSTOM - uint32_t crc = Persistence::crc(_destination_table); - if (_destination_table_crc > 0 && crc == _destination_table_crc) { + uint32_t crc = Persistence::crc(_path_table); + if (_path_table_crc > 0 && crc == _path_table_crc) { TRACE("Transport::write_path_table: no change detected, skipping write"); } else { TRACE("Transport::write_path_table: change detected, writing..."); + DEBUGF("Saving %d path table entries to storage...", _path_table.size()); char destination_table_path[Type::Reticulum::FILEPATH_MAXSIZE]; snprintf(destination_table_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/destination_table", Reticulum::_storagepath); - if (Persistence::serialize(_destination_table, destination_table_path, _destination_table_crc) > 0) { - TRACEF("Transport::write_path_table: wrote %d entries, %d bytes", _destination_table.size(), Persistence::_buffer.size()); + if (Persistence::serialize(_path_table, destination_table_path, _path_table_crc) > 0) { + TRACEF("Transport::write_path_table: wrote %d entries, %d bytes", _path_table.size(), Persistence::_buffer.size()); success = true; } + else { + ERROR("Transport::write_path_table: serialize failed"); + } } #endif // CUSTOM if (success) { - double save_time = OS::time() - save_start; - if (save_time < 1.0) { - //DEBUGF("Saved %zu path table entries in %.1f ms", _destination_table.size(), OS::round(save_time * 1000, 1)); - DEBUGF("Saved %zu path table entries in %.1f ms", _destination_table.size(), OS::round(save_time * 1000, 1)); - } - else { - //DEBUGF("Saved %zu path table entries in %.1f s", _destination_table.size(), OS::round(save_time, 1)); - DEBUGF("Saved %zu path table entries in %.1f s", _destination_table.size(), OS::round(save_time, 1)); - } + DEBUGF("Saved %zu path table entries in %.3f seconds", _path_table.size(), OS::round(OS::time() - save_start, 3)); } } catch (std::exception& e) { @@ -3939,14 +3928,9 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe file.write(umsgpack.packb(serialised_tunnels)) file.close() - save_time = time.time() - save_start - if save_time < 1: - time_str = str(round(save_time*1000,2))+" ms" - else: - time_str = str(round(save_time,2))+" s" - RNS.log("Saved "+str(len(serialised_tunnels))+" tunnel table entries in "+time_str, RNS.LOG_DEBUG) + DEBUGF("Saved %zu tunnel table entries in %.3f seconds", serialised_tunnels.size(), OS::round(OS::time() - save_start)) except Exception as e: - RNS.log("Could not save tunnel table to storage, the contained exception was: "+str(e), RNS.LOG_ERROR) + ERRORF("Could not save tunnel table to storage, the contained exception was: %s", e.what()) Transport.saving_tunnel_table = False */ @@ -3968,8 +3952,8 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe for (auto& file : files) { TRACEF("Transport::clean_caches: Checking for use of cached packet %s", file.c_str()); bool found = false; - for (auto& [destination_hash, destination_entry] : _destination_table) { - if (file.compare(destination_entry._announce_packet.toHex()) == 0) { + for (auto& [destination_hash, destination_entry] : _path_table) { + if (file.compare(destination_entry.announce_packet_hash().toHex()) == 0) { found = true; break; } @@ -4001,11 +3985,11 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe // memory // storage // _destinations - // _destination_table + // _path_table // _reverse_table // _announce_table // _held_announces - HEADF(LOG_VERBOSE, "mem: %u (%u%%) [%d] flash: %u (%u%%) [%d] paths: %u dsts: %u revr: %u annc: %u held: %u", memory, (int)((double)memory / (double)OS::heap_size() * 100.0), memory - _last_memory, flash, (int)((double)flash / (double)OS::storage_size() * 100.0), flash - _last_flash, _destination_table.size(), _destinations.size(), _reverse_table.size(), _announce_table.size(), _held_announces.size()); + HEADF(LOG_VERBOSE, "mem: %u (%u%%) [%d] flash: %u (%u%%) [%d] paths: %u dsts: %u revr: %u annc: %u held: %u", memory, (int)((double)memory / (double)OS::heap_size() * 100.0), memory - _last_memory, flash, (int)((double)flash / (double)OS::storage_size() * 100.0), flash - _last_flash, _path_table.size(), _destinations.size(), _reverse_table.size(), _announce_table.size(), _held_announces.size()); // _path_requests // _discovery_path_requests @@ -4066,14 +4050,14 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe /*static*/ void Transport::cull_path_table() { TRACE("Transport::cull_path_table()"); - if (_destination_table.size() > _path_table_maxsize) { + if (_path_table.size() > _path_table_maxsize) { try { // Build lightweight (timestamp, key) index to avoid copying full DestinationEntry // objects (which contain nested std::set) — prevents OOM on heap-constrained // devices when the table hits max capacity. std::vector> sorted_keys; - sorted_keys.reserve(_destination_table.size()); - for (const auto& [key, entry] : _destination_table) { + sorted_keys.reserve(_path_table.size()); + for (const auto& [key, entry] : _path_table) { sorted_keys.emplace_back(entry._timestamp, key); } // Sort ascending by timestamp so oldest entries are removed first @@ -4083,21 +4067,21 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe for (const auto& [timestamp, destination_hash] : sorted_keys) { TRACEF("Transport::cull_path_table: Removing destination %s from path table", destination_hash.toHex().c_str()); #if defined(RNS_USE_FS) && defined(RNS_PERSIST_PATHS) - auto it = _destination_table.find(destination_hash); - if (it != _destination_table.end()) { + auto it = _path_table.find(destination_hash); + if (it != _path_table.end()) { // Remove cached packet file associated with this destination char packet_cache_path[Type::Reticulum::FILEPATH_MAXSIZE]; - snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, it->second._announce_packet.toHex().c_str()); + snprintf(packet_cache_path, Type::Reticulum::FILEPATH_MAXSIZE, "%s/%s", Reticulum::_cachepath, it->second.announce_packet_hash().toHex().c_str()); if (OS::file_exists(packet_cache_path)) { OS::remove_file(packet_cache_path); } } #endif - if (_destination_table.erase(destination_hash) < 1) { + if (_path_table.erase(destination_hash) < 1) { WARNINGF("Failed to remove destination %s from path table", destination_hash.toHex().c_str()); } ++count; - if (_destination_table.size() <= _path_table_maxsize) { + if (_path_table.size() <= _path_table_maxsize) { break; } } @@ -4107,14 +4091,14 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe ERROR("cull_path_table: bad_alloc - out of memory building sort index, falling back to single erase"); // Fallback: std::min_element does no heap allocation — erase one oldest entry auto oldest = std::min_element( - _destination_table.begin(), _destination_table.end(), + _path_table.begin(), _path_table.end(), [](const std::pair& a, const std::pair& b) { return a.second._timestamp < b.second._timestamp; } ); - if (oldest != _destination_table.end()) { - _destination_table.erase(oldest); + if (oldest != _path_table.end()) { + _path_table.erase(oldest); } } catch (const std::exception& e) { @@ -4198,7 +4182,7 @@ TRACEF("Transport::write_path_table: buffer size %zu bytes", Persistence::_buffe /*static*/ uint16_t Transport::remove_paths(const std::vector& hashes) { uint16_t count = 0; for (const auto& destination_hash : hashes) { - //_destination_table.erase(destination_hash); + //_path_table.erase(destination_hash); remove_path(destination_hash); ++count; } diff --git a/src/Transport.h b/src/Transport.h index 352c17d..0348991 100644 --- a/src/Transport.h +++ b/src/Transport.h @@ -105,34 +105,68 @@ namespace RNS { class DestinationEntry { public: DestinationEntry() {} - DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set& random_blobs, const Bytes& receiving_interface, const Bytes& packet) : + DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set& random_blobs, const Interface& receiving_interface, const Packet& announce_packet) : _timestamp(timestamp), _received_from(received_from), _hops(announce_hops), _expires(expires), _random_blobs(random_blobs), _receiving_interface(receiving_interface), - _announce_packet(packet) + _announce_packet(announce_packet) + { + } + DestinationEntry(double timestamp, const Bytes& received_from, uint8_t announce_hops, double expires, const std::set& random_blobs, const Bytes& receiving_interface_hash, const Bytes& announce_packet_hash) : + _timestamp(timestamp), + _received_from(received_from), + _hops(announce_hops), + _expires(expires), + _random_blobs(random_blobs), + _receiving_interface_hash(receiving_interface_hash), + _announce_packet_hash(announce_packet_hash) { } public: - inline Interface receiving_interface() const { return find_interface_from_hash(_receiving_interface); } - inline Packet announce_packet() const { return get_cached_packet(_announce_packet); } + // Lazy load receiving_interface and announce_packet + inline Interface& receiving_interface() { + if (!_receiving_interface) _receiving_interface = find_interface_from_hash(_receiving_interface_hash); + return _receiving_interface; + } + inline Packet& announce_packet() { + if (!_announce_packet) _announce_packet = get_cached_packet(_announce_packet_hash); + if (_announce_packet) { + // Announce packet is cached in packed state + // so we need to unpack it before accessing. + _announce_packet.unpack(); + // We increase the hops, since reading a packet + // from cache is equivalent to receiving it again + // over an interface. It is cached with it's non- + // increased hop-count. + _announce_packet.hops(_announce_packet.hops() + 1); + } + return _announce_packet; + } + // Getters and setters for receiving_interface_hash and announce_packet_hash + inline Bytes receiving_interface_hash() const { if (_receiving_interface) return _receiving_interface.get_hash(); return _receiving_interface_hash; } + inline void receiving_interface_hash(const Bytes& hash) { if (hash != receiving_interface_hash()) _receiving_interface_hash = hash; _receiving_interface = {Type::NONE}; } + inline Bytes announce_packet_hash() const { if (_announce_packet) return _announce_packet.get_hash(); return _announce_packet_hash; } + inline void announce_packet_hash(const Bytes& hash) { if (hash != announce_packet_hash()) _announce_packet_hash = hash; _announce_packet = {Type::NONE}; } public: double _timestamp = 0; Bytes _received_from; uint8_t _hops = 0; double _expires = 0; std::set _random_blobs; - //Interface _receiving_interface = {Type::NONE}; - Bytes _receiving_interface; - //const Packet& _announce_packet; - //Packet _announce_packet = {Type::NONE}; - Bytes _announce_packet; inline bool operator < (const DestinationEntry& entry) const { // sort by ascending timestamp (oldest entries at the top) return _timestamp < entry._timestamp; } + private: + Interface _receiving_interface = {Type::NONE}; + Bytes _receiving_interface_hash; + //const Packet& _announce_packet; + Packet _announce_packet = {Type::NONE}; + Bytes _announce_packet_hash; + public: #ifndef NDEBUG inline std::string debugString() const { std::string dump; @@ -141,8 +175,8 @@ namespace RNS { " hops=" + std::to_string(_hops) + " expires=" + std::to_string(_expires) + //" random_blobs=" + _random_blobs + - " receiving_interface=" + _receiving_interface.toHex() + - " announce_packet=" + _announce_packet.toHex(); + " receiving_interface=" + receiving_interface_hash().toHex() + + " announce_packet=" + announce_packet_hash().toHex(); dump += " random_blobs=("; for (auto& blob : _random_blobs) { dump += blob.toHex() + ","; @@ -312,16 +346,18 @@ namespace RNS { static void handle_tunnel(const Bytes& tunnel_id, const Interface& interface); static void register_interface(Interface& interface); static void deregister_interface(const Interface& interface); - inline static const std::map get_interfaces() { return _interfaces; } + inline static const std::map& get_interfaces() { return _interfaces; } static void register_destination(Destination& destination); static void deregister_destination(const Destination& destination); static void register_link(Link& link); static void activate_link(Link& link); static void register_announce_handler(HAnnounceHandler handler); static void deregister_announce_handler(HAnnounceHandler handler); + static bool is_interface_from_hash(const Bytes& interface_hash); static Interface find_interface_from_hash(const Bytes& interface_hash); static bool should_cache_packet(const Packet& packet); static bool cache_packet(const Packet& packet, bool force_cache = false); + static bool is_cached_packet(const Bytes& packet_hash); static Packet get_cached_packet(const Bytes& packet_hash); static bool clear_cached_packet(const Bytes& packet_hash); static bool cache_request_packet(const Packet& packet); @@ -392,7 +428,7 @@ namespace RNS { // CBA TEST static inline void identity(Identity& identity) { _identity = identity; } - inline static const std::map& get_destination_table() { return _destination_table; } + inline static const std::map& get_path_table() { return _path_table; } inline static const std::map& get_announce_rate_table() { return _announce_rate_table; } inline static const std::map& get_link_table() { return _link_table; } @@ -425,7 +461,7 @@ namespace RNS { // 55.100 path table entries or approximately 22.300 link table entries. static std::map _announce_table; // A table for storing announces currently waiting to be retransmitted - static std::map _destination_table; // A lookup table containing the next hop to a given destination + static std::map _path_table; // A lookup table containing the next hop to a given destination static std::map _reverse_table; // A lookup table for storing packet hashes used to return proofs and replies static std::map _link_table; // A lookup table containing hops for links static std::map _held_announces; // A table containing temporarily held announce-table entries @@ -479,7 +515,7 @@ namespace RNS { static uint16_t _path_table_maxpersist; static double _last_saved; static float _save_interval; - static uint32_t _destination_table_crc; + static uint32_t _path_table_crc; static uint16_t _announce_table_maxsize; static Reticulum _owner; diff --git a/src/Type.h b/src/Type.h index ebb9d42..3438bca 100644 --- a/src/Type.h +++ b/src/Type.h @@ -104,7 +104,7 @@ namespace RNS { namespace Type { but it can be configured individually on a per-interface basis. */ - static const uint16_t MINIMUM_BITRATE = 500; + static const uint16_t MINIMUM_BITRATE = 5; // TODO: To reach the 300bps level without unreasonably impacting // performance on faster links, we need a mechanism for setting @@ -130,13 +130,13 @@ namespace RNS { namespace Type { //static const uint16_t JOB_INTERVAL = 60*5; static const uint16_t JOB_INTERVAL = 60; // CBA TEST - //static const uint16_t CLEAN_INTERVAL = 60*15; - static const uint16_t CLEAN_INTERVAL = 60; + static uint16_t CLEAN_INTERVAL = 60*15; + //static uint16_t CLEAN_INTERVAL = 60; // CBA MCU //static const uint16_t PERSIST_INTERVAL = 60*60*12; // CBA TEST - //static const uint16_t PERSIST_INTERVAL = 60*60; - static const uint16_t PERSIST_INTERVAL = 60; + static uint16_t PERSIST_INTERVAL = 60*60; + //static uint16_t PERSIST_INTERVAL = 60; static const uint16_t GRACIOUS_PERSIST_INTERVAL = 60*5; static const uint8_t DESTINATION_LENGTH = TRUNCATED_HASHLENGTH/8; // In bytes @@ -235,7 +235,7 @@ namespace RNS { namespace Type { static const float KEEPALIVE_MAX_RTT = 1.75; static const uint8_t KEEPALIVE_TIMEOUT_FACTOR = 4; // Grace period in seconds used in link timeout calculation. - static const uint8_t STALE_GRACE = 2; + static const uint8_t STALE_GRACE = 5; // Interval for sending keep-alive packets on established links in seconds. static const uint16_t KEEPALIVE = 360; /* @@ -442,12 +442,12 @@ namespace RNS { namespace Type { static const uint8_t LOCAL_REBROADCASTS_MAX = 2; // How many local rebroadcasts of an announce is allowed static const uint8_t PATH_REQUEST_TIMEOUT = 15; // Default timuout for client path requests in seconds - static constexpr const float PATH_REQUEST_GRACE = 0.35; // Grace time before a path announcement is made, allows directly reachable peers to respond first + static constexpr const float PATH_REQUEST_GRACE = 0.4; // Grace time before a path announcement is made, allows directly reachable peers to respond first static const uint8_t PATH_REQUEST_RW = 2; // Path request random window static const uint8_t PATH_REQUEST_MI = 5; // Minimum interval in seconds for automated path requests static constexpr const float LINK_TIMEOUT = Link::STALE_TIME * 1.25; - static const uint16_t REVERSE_TIMEOUT = 30*60; // Reverse table entries are removed after 30 minutes + static const uint16_t REVERSE_TIMEOUT = 8*60; // Reverse table entries are removed after 8 minutes // CBA MCU static const uint16_t MAX_RECEIPTS = RNS_RECEIPTS_MAX; // Maximum number of receipts to keep track of static const uint8_t MAX_RATE_TIMESTAMPS = RNS_RATE_TIMESTAMPS_MAX; // Maximum number of announce timestamps to keep per destination diff --git a/src/Utilities/Persistence.h b/src/Utilities/Persistence.h index bda8b10..d3033b8 100644 --- a/src/Utilities/Persistence.h +++ b/src/Utilities/Persistence.h @@ -209,7 +209,6 @@ namespace ArduinoJson { //dst["hash"] = src.get_hash(); dst["raw"] = src.raw(); dst["sent_at"] = src.sent_at(); - dst["destination_hash"] = src.get_hash(); //TRACE("<<< Finished serializing Packet"); return true; } @@ -220,8 +219,7 @@ namespace ArduinoJson { 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"]; - // set cached flag since pcket was read from cache + // set cached flag since packet was read from cache packet.cached(true); //TRACE(">>> Finished deserializing Packet"); return packet; @@ -230,8 +228,7 @@ namespace ArduinoJson { return //src["hash"].is() && src["raw"].is() && - src["sent_at"].is() && - src["destination_hash"].is(); + src["sent_at"].is(); } }; @@ -279,18 +276,21 @@ namespace ArduinoJson { dst["announce_hops"] = src._hops; dst["expires"] = src._expires; dst["random_blobs"] = src._random_blobs; + /* - //dst["interface_hash"] = src._receiving_interface; if (src._receiving_interface) { dst["interface_hash"] = src._receiving_interface.get_hash(); } else { dst["interface_hash"] = nullptr; } +*/ + dst["interface_hash"] = src.receiving_interface_hash(); + // CBA TODO Move packet serialization to *after* destination table serialization since packets are useless - // anyway if there's no space to left to write destination table. + // anyway if there's no space left to write destination table. // Whenever a reference to a packet is serialized we must ensure that packet itself also gets serialized separately - //dst["packet"] = src._announce_packet; +/* if (src._announce_packet) { dst["packet_hash"] = src._announce_packet.get_hash(); // Only cache packet if not already cached @@ -307,8 +307,8 @@ namespace ArduinoJson { dst["packet_hash"] = nullptr; } */ - dst["interface_hash"] = src._receiving_interface; - dst["packet_hash"] = src._announce_packet; + dst["packet_hash"] = src.announce_packet_hash(); + //TRACE("<<< Finished Serializing Transport::DestinationEntry"); return true; } @@ -320,22 +320,25 @@ namespace ArduinoJson { dst._hops = src["announce_hops"]; dst._expires = src["expires"]; dst._random_blobs = src["random_blobs"].as>(); + /* - //dst._receiving_interface = src["interface_hash"]; RNS::Bytes interface_hash = src["interface_hash"]; if (interface_hash) { // Query transport for matching interface dst._receiving_interface = RNS::Transport::find_interface_from_hash(interface_hash); } - //dst._announce_packet = src["packet"]; +*/ + dst.receiving_interface_hash(src["interface_hash"]); + +/* RNS::Bytes packet_hash = src["packet_hash"]; if (packet_hash) { - // Query transport for matching packet + // Query transport for matching cached packet dst._announce_packet = RNS::Transport::get_cached_packet(packet_hash); } */ - dst._receiving_interface = src["interface_hash"]; - dst._announce_packet = src["packet_hash"]; + dst.announce_packet_hash(src["packet_hash"]); + /* //RNS::Transport::DestinationEntry dst(src["timestamp"], src["received_from"], src["announce_hops"], src["expires"], src["random_blobs"], src["receiving_interface"], src["packet"]); RNS::Transport::DestinationEntry dst( @@ -376,14 +379,18 @@ namespace RNS { dst["announce_hops"] = src._hops; dst["expires"] = src._expires; dst["random_blobs"] = src._random_blobs; + /* - //dst["interface_hash"] = src._receiving_interface; if (src._receiving_interface) { dst["interface_hash"] = src._receiving_interface.get_hash(); } else { dst["interface_hash"] = nullptr; } +*/ + dst["interface_hash"] = src.receiving_interface_hash(); + +/* // CBA TODO Move packet serialization to *after* destination table serialization since packets are useless // anyway if there's no space to left to write destination table. // Whenever a reference to a packet is serialized we must ensure that packet itself also gets serialized separately @@ -404,8 +411,8 @@ namespace RNS { dst["packet_hash"] = nullptr; } */ - dst["interface_hash"] = src._receiving_interface; - dst["packet_hash"] = src._announce_packet; + dst["packet_hash"] = src.announce_packet_hash(); + //TRACE("<<< Finished Serializing Transport::DestinationEntry"); return true; } @@ -417,22 +424,25 @@ namespace RNS { dst._hops = src["announce_hops"]; dst._expires = src["expires"]; dst._random_blobs = src["random_blobs"].as>(); + /* - //dst._receiving_interface = src["interface_hash"]; RNS::Bytes interface_hash = src["interface_hash"]; if (interface_hash) { // Query transport for matching interface dst._receiving_interface = RNS::Transport::find_interface_from_hash(interface_hash); } - //dst._announce_packet = src["packet"]; +*/ + dst.receiving_interface_hash(src["interface_hash"]); + +/* RNS::Bytes packet_hash = src["packet_hash"]; if (packet_hash) { // Query transport for matching packet dst._announce_packet = RNS::Transport::get_cached_packet(packet_hash); } */ - dst._receiving_interface = src["interface_hash"]; - dst._announce_packet = src["packet_hash"]; + dst.announce_packet_hash(src["packet_hash"]); + /* //RNS::Transport::DestinationEntry dst(src["timestamp"], src["received_from"], src["announce_hops"], src["expires"], src["random_blobs"], src["receiving_interface"], src["packet"]); RNS::Transport::DestinationEntry dst( diff --git a/test/test_persistence/test_main.cpp b/test/test_persistence/test_main.cpp index d47d2fb..ac46e1f 100644 --- a/test/test_persistence/test_main.cpp +++ b/test/test_persistence/test_main.cpp @@ -517,11 +517,11 @@ void testDeserializeMap() { } #ifdef ARDUINO -const char test_destination_table_path[] = "/test_destination_table"; -const char test_empty_destination_table_path[] = "/test_empty_destination_table"; +const char test_path_table_path[] = "/test_path_table"; +const char test_empty_path_table_path[] = "/test_empty_path_table"; #else -const char test_destination_table_path[] = "test_destination_table"; -const char test_empty_destination_table_path[] = "test_empty_destination_table"; +const char test_path_table_path[] = "test_path_table"; +const char test_empty_path_table_path[] = "test_empty_path_table"; #endif void testSerializeDestinationTable() { @@ -588,7 +588,7 @@ void testSerializeDestinationTable() { TRACEF("testSerializeDestinationTable: serialized %zu bytes", length); if (length > 0) { TRACEF("testSerializeDestinationTable: json: %s", data.toString().c_str()); - if (RNS::Utilities::OS::write_file(test_destination_table_path, data) == data.size()) { + if (RNS::Utilities::OS::write_file(test_path_table_path, data) == data.size()) { TRACEF("testSerializeDestinationTable: wrote: %zu bytes", data.size()); } else { @@ -606,7 +606,7 @@ void testSerializeDestinationTable() { void testDeserializeDestinationTable() { RNS::Bytes data; - if (RNS::Utilities::OS::read_file(test_destination_table_path, data) > 0) { + if (RNS::Utilities::OS::read_file(test_path_table_path, data) > 0) { TRACEF("testDeserializeDestinationTable: read: %zu bytes", data.size()); TRACEF("testDeserializeDestinationTable: json: %s", data.toString().c_str()); JsonDocument doc; @@ -634,7 +634,7 @@ void testDeserializeDestinationTable() { TRACEF("testDeserializeDestinationTable: failed to deserialize: %s", error.c_str()); TEST_FAIL(); } - //assert(RNS::Utilities::OS::remove_file(test_destination_table_path)); + //assert(RNS::Utilities::OS::remove_file(test_path_table_path)); } else { TRACE("testDeserializeDestinationTable: read failed"); @@ -647,10 +647,10 @@ void testDeserializeEmptyDestinationTable() { // Write empty JSON destination table RNS::Bytes emptyData("{}"); - TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_destination_table_path, emptyData)); + TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_path_table_path, emptyData)); RNS::Bytes data; - if (RNS::Utilities::OS::read_file(test_empty_destination_table_path, data) > 0) { + if (RNS::Utilities::OS::read_file(test_empty_path_table_path, data) > 0) { TRACEF("testDeserializeEmptyDestinationTable: read: %zu bytes", data.size()); JsonDocument doc; @@ -677,7 +677,7 @@ void testDeserializeEmptyDestinationTable() { TRACE("testDeserializeEmptyDestinationTable: failed to deserialize"); TEST_FAIL(); } - //assert(RNS::Utilities::OS::remove_file(test_empty_destination_table_path)); + //assert(RNS::Utilities::OS::remove_file(test_empty_path_table_path)); } else { TRACE("testDeserializeEmptyDestinationTable: read failed"); @@ -1124,8 +1124,8 @@ int runUnityTests(void) { RNS::Utilities::OS::remove_file(test_map_path); RNS::Utilities::OS::remove_file(test_vector_path); RNS::Utilities::OS::remove_file(test_set_path); - RNS::Utilities::OS::remove_file(test_destination_table_path); - RNS::Utilities::OS::remove_file(test_empty_destination_table_path); + RNS::Utilities::OS::remove_file(test_path_table_path); + RNS::Utilities::OS::remove_file(test_empty_path_table_path); RNS::Utilities::OS::remove_file(test_array_path); RNS::Utilities::OS::remove_file(test_series_path); RNS::Utilities::OS::deregister_filesystem(); diff --git a/test/test_rns_persistence/test_main.cpp b/test/test_rns_persistence/test_main.cpp index e319e30..8734beb 100644 --- a/test/test_rns_persistence/test_main.cpp +++ b/test/test_rns_persistence/test_main.cpp @@ -36,11 +36,11 @@ private: }; #ifdef ARDUINO -const char test_destination_table_path[] = "/test_destination_table"; -const char test_empty_destination_table_path[] = "/test_empty_destination_table"; +const char test_path_table_path[] = "/test_path_table"; +const char test_empty_path_table_path[] = "/test_empty_path_table"; #else -const char test_destination_table_path[] = "test_destination_table"; -const char test_empty_destination_table_path[] = "test_empty_destination_table"; +const char test_path_table_path[] = "test_path_table"; +const char test_empty_path_table_path[] = "test_empty_path_table"; #endif void testSerializeDestinationTable() { @@ -95,7 +95,7 @@ void testSerializeDestinationTable() { } uint32_t stream_crc; - size_t wrote = RNS::Persistence::serialize(map, test_destination_table_path, stream_crc); + size_t wrote = RNS::Persistence::serialize(map, test_path_table_path, stream_crc); TRACEF("testSerializeDestinationTable: wrote: %d bytes", wrote); if (wrote == 0) { TRACE("testSerializeDestinationTable: write failed"); @@ -115,7 +115,7 @@ void testDeserializeDestinationTable() { std::map map; uint32_t stream_crc; - size_t read = RNS::Persistence::deserialize(map, test_destination_table_path, stream_crc); + size_t read = RNS::Persistence::deserialize(map, test_path_table_path, stream_crc); TRACEF("testDeserializeDestinationTable: deserialized %d bytes", read); if (read == 0) { TRACE("testDeserializeDestinationTable: failed to deserialize"); @@ -140,10 +140,10 @@ void testDeserializeEmptyDestinationTable() { // Write empty JSON destination table RNS::Bytes emptyData("{}"); - TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_destination_table_path, emptyData)); + TEST_ASSERT_EQUAL_size_t(2, RNS::Utilities::OS::write_file(test_empty_path_table_path, emptyData)); std::map destination_table; - RNS::Persistence::deserialize(destination_table, test_empty_destination_table_path); + RNS::Persistence::deserialize(destination_table, test_empty_path_table_path); TEST_ASSERT_EQUAL_size_t(0, destination_table.size()); } @@ -170,8 +170,8 @@ int runUnityTests(void) { RUN_TEST(testDeserializeEmptyDestinationTable); // Suite-level teardown - RNS::Utilities::OS::remove_file(test_destination_table_path); - RNS::Utilities::OS::remove_file(test_empty_destination_table_path); + RNS::Utilities::OS::remove_file(test_path_table_path); + RNS::Utilities::OS::remove_file(test_empty_path_table_path); RNS::Utilities::OS::deregister_filesystem(); return UNITY_END(); diff --git a/test/test_transport/test_main.cpp b/test/test_transport/test_main.cpp index deffe3c..c5524f5 100644 --- a/test/test_transport/test_main.cpp +++ b/test/test_transport/test_main.cpp @@ -30,7 +30,7 @@ public: InterfaceImpl::handle_incoming(data); } catch (const std::bad_alloc&) { - ERROR("handle_incoming: bad_alloc - out of memory"); + ERROR("handle_incoming: bad_alloc - OUT OF MEMORY"); } catch (const std::exception& e) { ERRORF("handle_incoming: exception: %s", e.what()); @@ -52,7 +52,7 @@ public: InterfaceImpl::handle_outgoing(data); } catch (const std::bad_alloc&) { - ERROR("handle_outgoing: bad_alloc - out of memory"); + ERROR("handle_outgoing: bad_alloc - OUT OF MEMORY"); } catch (const std::exception& e) { ERRORF("handle_outgoing: exception: %s", e.what()); @@ -130,7 +130,7 @@ void initRNS() { rns_initialized = true; } catch (const std::bad_alloc&) { - ERROR("initRNS: bad_alloc - out of memory"); + ERROR("initRNS: bad_alloc - OUT OF MEMORY"); } catch (const std::exception& e) { ERRORF("initRNS: exception: %s", e.what()); @@ -427,7 +427,7 @@ void test_incoming_announce_limit() { } } catch (const std::bad_alloc&) { - ERROR("test_incoming_announce_limit: bad_alloc - out of memory"); + ERROR("test_incoming_announce_limit: bad_alloc - OUT OF MEMORY"); break; } catch (const std::exception& e) { @@ -488,7 +488,7 @@ void test_incoming_announce_over_limit() { } } catch (const std::bad_alloc&) { - ERROR("test_incoming_announce_over_limit: bad_alloc - out of memory"); + ERROR("test_incoming_announce_over_limit: bad_alloc - OUT OF MEMORY"); break; } catch (const std::exception& e) { @@ -554,7 +554,7 @@ void test_incoming_announce_stress() { } } catch (const std::bad_alloc&) { - ERROR("test_incoming_announce_stress: bad_alloc - out of memory"); + ERROR("test_incoming_announce_stress: bad_alloc - OUT OF MEMORY"); break; } catch (const std::exception& e) {