From 03cfb1c03fcbc536527613d3934a57a6e7bede1f Mon Sep 17 00:00:00 2001 From: attermann Date: Wed, 20 Dec 2023 11:52:48 -0700 Subject: [PATCH] WIP: More porting and work on persistence Ported packet PROOFs. Implemented Transport probe destination. SPIFFs filesystem checks and formatting when necessary. --- platformio.ini | 18 ++- src/Destination.cpp | 87 ++++++------- src/Destination.h | 10 +- src/Identity.cpp | 19 ++- src/Identity.h | 2 +- src/Interfaces/LoRaInterface.cpp | 1 - src/Link.cpp | 29 +++++ src/Link.h | 3 + src/Log.cpp | 59 ++++++--- src/Log.h | 7 ++ src/Packet.cpp | 204 ++++++++++++++++++++++++++++--- src/Packet.h | 43 ++++--- src/Reticulum.h | 1 + src/Transport.cpp | 18 +-- src/Utilities/OS.cpp | 9 ++ 15 files changed, 392 insertions(+), 118 deletions(-) diff --git a/platformio.ini b/platformio.ini index 67e7a87..54b2b31 100644 --- a/platformio.ini +++ b/platformio.ini @@ -80,9 +80,25 @@ lib_deps = ArduinoJson@^6.21.3 rweather/Crypto@^0.4.0 sandeepmistry/LoRa@^0.8.0 - jgromes/RadioLib@^5.7.0 lovyan03/LovyanGFX@^1.1.8 +[env:ttgo-lora32-v21] +platform = espressif32 +board = ttgo-lora32-v21 +board_build.partitions = no_ota.csv +framework = arduino +monitor_speed = 115200 +build_flags = + -Wall + -Wextra + -Wno-missing-field-initializers + -Wno-format + -Isrc +lib_deps = + ArduinoJson@^6.21.3 + rweather/Crypto@^0.4.0 + sandeepmistry/LoRa@^0.8.0 + [env:ttgo-t-beam] platform = espressif32 board = ttgo-t-beam diff --git a/src/Destination.cpp b/src/Destination.cpp index 2a5d269..c8b944f 100644 --- a/src/Destination.cpp +++ b/src/Destination.cpp @@ -21,38 +21,38 @@ Destination::Destination(const Identity& identity, const directions direction, c if (strchr(app_name, '.') != nullptr) { throw std::invalid_argument("Dots can't be used in app names"); } - debug("Destination::Destination: app name: " + std::string(app_name)); + extreme("Destination::Destination: app name: " + std::string(app_name)); _object->_type = type; _object->_direction = direction; std::string fullaspects(aspects); if (!identity && direction == IN && _object->_type != PLAIN) { - debug("Destination::Destination: identity not provided, creating new one"); + extreme("Destination::Destination: identity not provided, creating new one"); _object->_identity = Identity(); // CBA TODO determine why identity.hexhash is added both here and by expand_name called below fullaspects += "." + _object->_identity.hexhash(); } - debug("Destination::Destination: full aspects: " + fullaspects); + extreme("Destination::Destination: full aspects: " + fullaspects); if (_object->_identity && _object->_type == PLAIN) { throw std::invalid_argument("Selected destination type PLAIN cannot hold an identity"); } _object->_name = expand_name(_object->_identity, app_name, fullaspects.c_str()); - debug("Destination::Destination: name: " + _object->_name); + extreme("Destination::Destination: name: " + _object->_name); // Generate the destination address hash - debug("Destination::Destination: creating hash..."); + extreme("Destination::Destination: creating hash..."); _object->_hash = hash(_object->_identity, app_name, fullaspects.c_str()); _object->_hexhash = _object->_hash.toHex(); - debug("Destination::Destination: hash: " + _object->_hash.toHex()); - debug("Destination::Destination: creating name hash..."); + extreme("Destination::Destination: hash: " + _object->_hash.toHex()); + extreme("Destination::Destination: creating name hash..."); //p self.name_hash = RNS.Identity.full_hash(self.expand_name(None, app_name, *aspects).encode("utf-8"))[:(RNS.Identity.NAME_HASH_LENGTH//8)] _object->_name_hash = name_hash(app_name, aspects); - debug("Destination::Destination: name hash: " + _object->_name_hash.toHex()); + extreme("Destination::Destination: name hash: " + _object->_name_hash.toHex()); - debug("Destination::Destination: calling register_destination"); + extreme("Destination::Destination: calling register_destination"); Transport::register_destination(*this); mem("Destination object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); @@ -71,13 +71,13 @@ Destination::Destination(const Identity& identity, const Type::Destination::dire _object->_hash = hash; _object->_hexhash = _object->_hash.toHex(); - debug("Destination::Destination: hash: " + _object->_hash.toHex()); - debug("Destination::Destination: creating name hash..."); + extreme("Destination::Destination: hash: " + _object->_hash.toHex()); + extreme("Destination::Destination: creating name hash..."); //p self.name_hash = RNS.Identity.full_hash(self.expand_name(None, app_name, *aspects).encode("utf-8"))[:(RNS.Identity.NAME_HASH_LENGTH//8)] _object->_name_hash = name_hash("unknown", "unknown"); - debug("Destination::Destination: name hash: " + _object->_name_hash.toHex()); + extreme("Destination::Destination: name hash: " + _object->_name_hash.toHex()); - debug("Destination::Destination: calling register_destination"); + extreme("Destination::Destination: calling register_destination"); Transport::register_destination(*this); mem("Destination object created, this: " + std::to_string((uintptr_t)this) + ", data: " + std::to_string((uintptr_t)_object.get())); @@ -90,7 +90,7 @@ Destination::Destination(const Identity& identity, const Type::Destination::dire // CBA Can't call deregister_destination here because it's possible (likely even) that Destination // is being destructed from that same collection which will result in a llop and memory errors. - //debug("Destination::~Destination: calling deregister_destination"); + //extreme("Destination::~Destination: calling deregister_destination"); //Transport::deregister_destination(*this); } } @@ -172,7 +172,7 @@ relevant interfaces. Application specific data can be added to the announce. //Packet Destination::announce(const Bytes& app_data /*= {}*/, bool path_response /*= false*/, const Interface& attached_interface /*= {Type::NONE}*/, const Bytes& tag /*= {}*/, bool send /*= true*/) { Packet Destination::announce(const Bytes& app_data, bool path_response, const Interface& attached_interface, const Bytes& tag /*= {}*/, bool send /*= true*/) { assert(_object); - debug("Destination::announce: announcing destination..."); + extreme("Destination::announce: announcing destination..."); if (_object->_type != SINGLE) { throw std::invalid_argument("Only SINGLE destination types can be announced"); @@ -201,29 +201,29 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In /* // CBA TEST - debug("Destination::announce: performing path test..."); - debug("Destination::announce: inserting path..."); + extreme("Destination::announce: performing path test..."); + extreme("Destination::announce: inserting path..."); _object->_path_responses.insert({Bytes("foo_tag"), {0, Bytes("this is foo tag")}}); - debug("Destination::announce: inserting path..."); + extreme("Destination::announce: inserting path..."); _object->_path_responses.insert({Bytes("test_tag"), {0, Bytes("this is test tag")}}); if (path_response) { - debug("Destination::announce: path_response is true"); + extreme("Destination::announce: path_response is true"); } if (!tag.empty()) { - debug("Destination::announce: tag is specified"); + extreme("Destination::announce: tag is specified"); std::string tagstr((const char*)tag.data(), tag.size()); debug(std::string("Destination::announce: tag: ") + tagstr); debug(std::string("Destination::announce: tag len: ") + std::to_string(tag.size())); - debug("Destination::announce: searching for tag..."); + extreme("Destination::announce: searching for tag..."); if (_object->_path_responses.find(tag) != _object->_path_responses.end()) { - debug("Destination::announce: found tag in _path_responses"); + extreme("Destination::announce: found tag in _path_responses"); debug(std::string("Destination::announce: data: ") +_object->_path_responses[tag].second.toString()); } else { - debug("Destination::announce: tag not found in _path_responses"); + extreme("Destination::announce: tag not found in _path_responses"); } } - debug("Destination::announce: path test finished"); + extreme("Destination::announce: path test finished"); */ if (path_response && !tag.empty() && _object->_path_responses.find(tag) != _object->_path_responses.end()) { @@ -250,20 +250,20 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In } Bytes signed_data; - debug("Destination::announce: hash: " + _object->_hash.toHex()); - debug("Destination::announce: public key: " + _object->_identity.get_public_key().toHex()); - debug("Destination::announce: name hash: " + _object->_name_hash.toHex()); - debug("Destination::announce: random hash: " + random_hash.toHex()); - debug("Destination::announce: app data: " + new_app_data.toHex()); - debug("Destination::announce: app data text:" + new_app_data.toString()); + extreme("Destination::announce: hash: " + _object->_hash.toHex()); + extreme("Destination::announce: public key: " + _object->_identity.get_public_key().toHex()); + extreme("Destination::announce: name hash: " + _object->_name_hash.toHex()); + extreme("Destination::announce: random hash: " + random_hash.toHex()); + extreme("Destination::announce: app data: " + new_app_data.toHex()); + extreme("Destination::announce: app data text:" + new_app_data.toString()); signed_data << _object->_hash << _object->_identity.get_public_key() << _object->_name_hash << random_hash; if (new_app_data) { signed_data << new_app_data; } - debug("Destination::announce: signed data: " + signed_data.toHex()); + extreme("Destination::announce: signed data: " + signed_data.toHex()); Bytes signature(_object->_identity.sign(signed_data)); - debug("Destination::announce: signature: " + signature.toHex()); + extreme("Destination::announce: signature: " + signature.toHex()); announce_data << _object->_identity.get_public_key() << _object->_name_hash << random_hash << signature; @@ -273,20 +273,20 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In _object->_path_responses.insert({tag, {OS::time(), announce_data}}); } - debug("Destination::announce: announce_data:" + announce_data.toHex()); + extreme("Destination::announce: announce_data:" + announce_data.toHex()); Type::Packet::context_types announce_context = Type::Packet::CONTEXT_NONE; if (path_response) { announce_context = Type::Packet::PATH_RESPONSE; } - debug("Destination::announce: creating announce packet..."); + extreme("Destination::announce: creating announce packet..."); //p announce_packet = RNS.Packet(self, announce_data, RNS.Packet.ANNOUNCE, context = announce_context, attached_interface = attached_interface) //Packet announce_packet(*this, announce_data, Type::Packet::ANNOUNCE, announce_context, Type::Transport::BROADCAST, Type::Packet::HEADER_1, nullptr, attached_interface); Packet announce_packet(*this, attached_interface, announce_data, Type::Packet::ANNOUNCE, announce_context, Type::Transport::BROADCAST, Type::Packet::HEADER_1); if (send) { - debug("Destination::announce: sending announce packet..."); + extreme("Destination::announce: sending announce packet..."); announce_packet.send(); return {Type::NONE}; } @@ -382,9 +382,9 @@ Encrypts information for ``RNS.Destination.SINGLE`` or ``RNS.Destination.GROUP`` :param plaintext: A *bytes-like* containing the plaintext to be encrypted. :raises: ``ValueError`` if destination does not hold a necessary key for encryption. */ -const Bytes Destination::encrypt(const Bytes& data) { +/*virtual*/ const Bytes Destination::encrypt(const Bytes& data) { assert(_object); - debug("Destination::encrypt: encrypting data..."); + extreme("Destination::encrypt: encrypting data..."); if (_object->_type == PLAIN) { return data; @@ -394,6 +394,7 @@ const Bytes Destination::encrypt(const Bytes& data) { return _object->_identity.encrypt(data); } +// TODO /* if (_object->_type == GROUP { if hasattr(self, "prv") and self.prv != None: @@ -406,8 +407,10 @@ const Bytes Destination::encrypt(const Bytes& data) { raise ValueError("No private key held by GROUP destination. Did you create or load one?") } */ - // MOCK - return {Bytes::NONE}; + + // CBA Reference implementation does not handle this default case + // CBA TODO Determine of returning plaintext is appropriate here (for now it's necessary for PROOF packets) + return data; } /* @@ -416,9 +419,9 @@ Decrypts information for ``RNS.Destination.SINGLE`` or ``RNS.Destination.GROUP`` :param ciphertext: *Bytes* containing the ciphertext to be decrypted. :raises: ``ValueError`` if destination does not hold a necessary key for decryption. */ -const Bytes Destination::decrypt(const Bytes& data) { +/*virtual*/ const Bytes Destination::decrypt(const Bytes& data) { assert(_object); - debug("Destination::decrypt: decrypting data..."); + extreme("Destination::decrypt: decrypting data..."); if (_object->_type == PLAIN) { return data; @@ -450,7 +453,7 @@ Signs information for ``RNS.Destination.SINGLE`` type destination. :param message: *Bytes* containing the message to be signed. :returns: A *bytes-like* containing the message signature, or *None* if the destination could not sign the message. */ -const Bytes Destination::sign(const Bytes& message) { +/*virtual*/ const Bytes Destination::sign(const Bytes& message) { assert(_object); if (_object->_type == SINGLE && _object->_identity) { return _object->_identity.sign(message); diff --git a/src/Destination.h b/src/Destination.h index dd1be6d..f0cf778 100644 --- a/src/Destination.h +++ b/src/Destination.h @@ -104,8 +104,8 @@ namespace RNS { :param accepts: If ``True`` or ``False``, this method sets whether the destination accepts incoming link requests. If not provided or ``None``, the method returns whether the destination currently accepts link requests. :returns: ``True`` or ``False`` depending on whether the destination accepts incoming link requests, if the *accepts* parameter is not provided or ``None``. */ - inline void set_accepts_links(bool accepts) { assert(_object); _object->_accept_link_requests = accepts; } - inline bool get_accepts_links() { assert(_object); return _object->_accept_link_requests; } + inline void accepts_links(bool accepts) { assert(_object); _object->_accept_link_requests = accepts; } + inline bool accepts_links() { assert(_object); return _object->_accept_link_requests; } /* Registers a function to be called when a link has been established to @@ -155,9 +155,9 @@ namespace RNS { void receive(const Packet& packet); void incoming_link_request(const Bytes& data, const Packet& packet); - const Bytes encrypt(const Bytes& data); - const Bytes decrypt(const Bytes& data); - const Bytes sign(const Bytes& message); + virtual const Bytes encrypt(const Bytes& data); + virtual const Bytes decrypt(const Bytes& data); + virtual const Bytes sign(const Bytes& message); // getters/setters inline Type::Destination::types type() const { assert(_object); return _object->_type; } diff --git a/src/Identity.cpp b/src/Identity.cpp index 721cfcf..3a85350 100644 --- a/src/Identity.cpp +++ b/src/Identity.cpp @@ -585,17 +585,24 @@ void Identity::prove(const Packet& packet, const Destination& destination /*= {T Bytes proof_data; if (RNS::Reticulum::should_use_implicit_proof()) { proof_data = signature; + extreme("Identity::prove: implicit proof data: " + proof_data.toHex()); } else { proof_data = packet.packet_hash() + signature; + extreme("Identity::prove: explicit proof data: " + proof_data.toHex()); } - //z if (!destination) { - //z destination = packet.generate_proof_destination(); - //z } - - Packet proof(destination, packet.receiving_interface(), proof_data, Type::Packet::PROOF); - proof.send(); + if (!destination) { + extreme("Identity::prove: proving packet with proof destination..."); + ProofDestination proof_destination = packet.generate_proof_destination(); + Packet proof(proof_destination, packet.receiving_interface(), proof_data, Type::Packet::PROOF); + proof.send(); + } + else { + extreme("Identity::prove: proving packet with specified destination..."); + Packet proof(destination, packet.receiving_interface(), proof_data, Type::Packet::PROOF); + proof.send(); + } } void Identity::prove(const Packet& packet) const { diff --git a/src/Identity.h b/src/Identity.h index 6f5bdcb..41d1798 100644 --- a/src/Identity.h +++ b/src/Identity.h @@ -150,7 +150,7 @@ namespace RNS { inline std::string hexhash() const { assert(_object); return _object->_hexhash; } inline const Bytes& app_data() const { assert(_object); return _object->_app_data; } inline void app_data(const Bytes& app_data) { assert(_object); _object->_app_data = app_data; } - //inline const Cryptography::X25519PrivateKey::Ptr prv() const { assert(_object); return _object->_prv; } + inline const Cryptography::X25519PrivateKey::Ptr prv() const { assert(_object); return _object->_prv; } inline const Cryptography::X25519PublicKey::Ptr pub() const { assert(_object); return _object->_pub; } inline std::string toString() const { if (!_object) return ""; return "{Identity:" + _object->_hash.toHex() + "}"; } diff --git a/src/Interfaces/LoRaInterface.cpp b/src/Interfaces/LoRaInterface.cpp index 11d3322..c46b49e 100644 --- a/src/Interfaces/LoRaInterface.cpp +++ b/src/Interfaces/LoRaInterface.cpp @@ -80,7 +80,6 @@ void LoRaInterface::loop() { #ifdef ARDUINO int available = LoRa.parsePacket(); if (available > 0) { -Serial.println(available); extreme("LoRaInterface: receiving bytes..."); // read header (for detecting split packets) diff --git a/src/Link.cpp b/src/Link.cpp index 6dd042a..39513da 100644 --- a/src/Link.cpp +++ b/src/Link.cpp @@ -21,3 +21,32 @@ void Link::set_link_id(const Packet& packet) { void Link::receive(const Packet& packet) { } + +void Link::prove() { +/* + 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() +*/ +} + +void Link::prove_packet(const Packet& 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() +*/ +} diff --git a/src/Link.h b/src/Link.h index 585d791..a9fc80e 100644 --- a/src/Link.h +++ b/src/Link.h @@ -46,6 +46,9 @@ namespace RNS { void set_link_id(const Packet& packet); void receive(const Packet& packet); + void prove(); + void prove_packet(const Packet& packet); + // getters/setters inline const Destination& destination() const { assert(_object); return _object->_destination; } inline const Bytes& link_id() const { assert(_object); return _object->_link_id; } diff --git a/src/Log.cpp b/src/Log.cpp index ac4562a..da2a458 100644 --- a/src/Log.cpp +++ b/src/Log.cpp @@ -1,37 +1,56 @@ #include "Log.h" +#include +#include #include using namespace RNS; -const char* getLevelName(LogLevel level) { +//LogLevel _level = LOG_VERBOSE; +LogLevel _level = LOG_EXTREME; +//LogLevel _level = LOG_MEM; +RNS::log_callback _on_log = nullptr; +char _datetime[32]; + +const char* RNS::getLevelName(LogLevel level) { switch (level) { case LOG_CRITICAL: - return "CRITICAL"; + return "!!!"; case LOG_ERROR: - return "ERROR"; + return "ERR"; case LOG_WARNING: - return "WARNING"; + return "WRN"; case LOG_NOTICE: - return "NOTICE"; + return "NOT"; case LOG_INFO: - return "INFO"; + return "INF"; case LOG_VERBOSE: - return "VERBOSE"; + return "VRB"; case LOG_DEBUG: - return "DEBUG"; + return "DBG"; case LOG_EXTREME: - return "EXTRA"; + return "---"; case LOG_MEM: - return "MEM"; + return "..."; default: return ""; } } -//LogLevel _level = LOG_VERBOSE; -LogLevel _level = LOG_EXTREME; -//LogLevel _level = LOG_MEM; +const char* RNS::getTimeString() { + struct timeval tv; + gettimeofday(&tv, nullptr); + int millis = lrint(tv.tv_usec/1000.0); + if (millis >= 1000) { + millis -= 1000; + tv.tv_sec++; + } + ; + struct tm* tm = localtime(&tv.tv_sec); + size_t len = strftime(_datetime, sizeof(_datetime), "%Y-%m-%d %H:%M:%S", tm); + sprintf(_datetime+len, ".%03d", millis); + return _datetime; +} void RNS::loglevel(LogLevel level) { _level = level; @@ -41,17 +60,27 @@ LogLevel RNS::loglevel() { return _level; } +void RNS::setLogCallback(log_callback on_log /*= nullptr*/) { + _on_log = on_log; +} + void RNS::doLog(const char* msg, LogLevel level) { if (level > _level) { return; } + if (_on_log != nullptr) { + _on_log(msg, level); + return; + } #ifdef ARDUINO + Serial.print(getTimeString()); + Serial.print(" ["); Serial.print(getLevelName(level)); - Serial.print(" "); + Serial.print("] "); Serial.println(msg); Serial.flush(); #else - printf("%s: %s\n", getLevelName(level), msg); + printf("%s [%s] %s\n", getTimeString(), getLevelName(level), msg); #endif } diff --git a/src/Log.h b/src/Log.h index 2daa818..3b5a61d 100644 --- a/src/Log.h +++ b/src/Log.h @@ -21,9 +21,16 @@ namespace RNS { LOG_MEM = 9 }; + using log_callback = void(*)(const char* msg, LogLevel level); + + const char* getLevelName(LogLevel level); + const char* getTimeString(); + void loglevel(LogLevel level); LogLevel loglevel(); + void setLogCallback(log_callback on_log = nullptr); + void doLog(const char* msg, LogLevel level); inline void log(const char* msg, LogLevel level = LOG_NOTICE) { doLog(msg, level); } diff --git a/src/Packet.cpp b/src/Packet.cpp index 7f13e06..dcfc6d3 100644 --- a/src/Packet.cpp +++ b/src/Packet.cpp @@ -3,6 +3,7 @@ #include "Transport.h" #include "Identity.h" #include "Log.h" +#include "Utilities/OS.h" #include #include @@ -10,6 +11,11 @@ using namespace RNS; using namespace RNS::Type::PacketReceipt; using namespace RNS::Type::Packet; +using namespace RNS::Utilities; + +ProofDestination::ProofDestination(const Packet& packet) : Destination({Type::NONE}, Type::Destination::OUT, Type::Destination::SINGLE, packet.get_hash().left(Type::Reticulum::TRUNCATED_HASHLENGTH/8)) +{ +} 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)) { @@ -232,7 +238,7 @@ but excluding any interface access codes. void Packet::pack() { assert(_object); - debug("Packet::pack: packing packet..."); + extreme("Packet::pack: packing packet..."); _object->_destination_hash = _object->_destination.hash(); @@ -243,14 +249,14 @@ void Packet::pack() { _object->_raw << _object->_hops; if (_object->_context == LRPROOF) { - debug("Packet::pack: destination link id: " + _object->_destination.link_id().toHex() ); + extreme("Packet::pack: destination link id: " + _object->_destination.link_id().toHex() ); _object->_raw << _object->_destination.link_id(); _object->_raw << (uint8_t)_object->_context; _object->_raw << _object->_data; } else { if (_object->_header_type == HEADER_1) { - debug("Packet::pack: destination hash: " + _object->_destination.hash().toHex() ); + extreme("Packet::pack: destination hash: " + _object->_destination.hash().toHex() ); _object->_raw << _object->_destination.hash(); _object->_raw << (uint8_t)_object->_context; @@ -295,8 +301,8 @@ void Packet::pack() { if (!_object->_transport_id) { throw std::invalid_argument("Packet with header type 2 must have a transport ID"); } - debug("Packet::pack: transport id: " + _object->_transport_id.toHex() ); - debug("Packet::pack: destination hash: " + _object->_destination.hash().toHex() ); + extreme("Packet::pack: transport id: " + _object->_transport_id.toHex() ); + extreme("Packet::pack: destination hash: " + _object->_destination.hash().toHex() ); _object->_raw << _object->_transport_id; _object->_raw << _object->_destination.hash(); _object->_raw << (uint8_t)_object->_context; @@ -318,7 +324,7 @@ void Packet::pack() { bool Packet::unpack() { assert(_object); - debug("Packet::unpack: unpacking packet..."); + extreme("Packet::unpack: unpacking packet..."); try { if (_object->_raw.size() < Type::Reticulum::HEADER_MINSIZE) { throw std::length_error("Packet size of " + std::to_string(_object->_raw.size()) + " does not meet minimum header size of " + std::to_string(Type::Reticulum::HEADER_MINSIZE) +" bytes"); @@ -376,10 +382,11 @@ Sends the packet. */ bool Packet::send() { assert(_object); - debug("Packet::send: sending packet..."); + extreme("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) { @@ -398,7 +405,7 @@ bool Packet::send() { } if (Transport::outbound(*this)) { - debug("Packet::send: successfully sent packet!!!"); + extreme("Packet::send: successfully sent packet!!!"); //z return self.receipt // MOCK return true; @@ -418,7 +425,7 @@ Re-sends the packet. */ bool Packet::resend() { assert(_object); - debug("Packet::resend: re-sending packet..."); + extreme("Packet::resend: re-sending packet..."); if (!_object->_sent) { throw std::logic_error("Packet was not sent yet"); } @@ -427,7 +434,7 @@ bool Packet::resend() { pack(); if (Transport::outbound(*this)) { - debug("Packet::resend: successfully sent packet!!!"); + extreme("Packet::resend: successfully sent packet!!!"); //z return self.receipt // MOCK return true; @@ -441,11 +448,11 @@ bool Packet::resend() { } void Packet::prove(const Destination& destination /*= {Type::NONE}*/) { -/* assert(_object); + extreme("Packet::prove: proving packet..."); if (_object->_fromPacked && _object->_destination) { if (_object->_destination.identity() && _object->_destination.identity().prv()) { - _object->_destination.identity().prove(*this, _object->_destination); + _object->_destination.identity().prove(*this, destination); } } else if (_object->_fromPacked && _object->_link) { @@ -454,7 +461,29 @@ void Packet::prove(const Destination& destination /*= {Type::NONE}*/) { else { error("Could not prove packet associated with neither a destination nor a link"); } -*/ +} + + +// Generates a special destination that allows Reticulum +// to direct the proof back to the proved packet's sender +ProofDestination Packet::generate_proof_destination() const { + return ProofDestination(*this); +} + +bool Packet::validate_proof_packet(const Packet& proof_packet) { + assert(_object); + if (!_object->_receipt) { + return false; + } + return _object->_receipt.validate_proof_packet(proof_packet); +} + +bool Packet::validate_proof(const Bytes& proof) { + assert(_object); + if (!_object->_receipt) { + return false; + } + return _object->_receipt.validate_proof(proof); } void Packet::update_hash() { @@ -489,12 +518,6 @@ const Bytes Packet::get_hashable_part() const { return hashable_part; } -// Generates a special destination that allows Reticulum -// to direct the proof back to the proved packet's sender -//ProofDestination& Packet::generate_proof_destination() { -// return ProofDestination(); -//} - #ifndef NDEBUG std::string Packet::debugString() const { @@ -572,6 +595,149 @@ PacketReceipt::PacketReceipt(const Packet& packet) : _object(new Object()) { } } +// Validate a proof packet +bool PacketReceipt::validate_proof_packet(const Packet& proof_packet) { + if (proof_packet.link()) { + return validate_link_proof(proof_packet.data(), proof_packet.link(), proof_packet); + } + else { + return validate_proof(proof_packet.data(), proof_packet); + } +} + +// Validate a raw proof for a link +//bool PacketReceipt::validate_link_proof(const Bytes& proof, const Link& link, const Packet& proof_packet /*= {Type::NONE}*/) { +bool PacketReceipt::validate_link_proof(const Bytes& proof, const Link& link) { + return validate_link_proof(proof, link, {Type::NONE}); +} +bool PacketReceipt::validate_link_proof(const Bytes& proof, const Link& link, const Packet& proof_packet) { + assert(_object); + extreme("PacketReceipt::validate_link_proof: validating link proof..."); + // TODO: Hardcoded as explicit proofs for now + if (true || proof.size() == EXPL_LENGTH) { + // This is an explicit proof + Bytes proof_hash = proof.left(Type::Identity::HASHLENGTH/8); + Bytes signature = proof.mid(Type::Identity::HASHLENGTH/8, Type::Identity::SIGLENGTH/8); + if (proof_hash == _object->_hash) { + //z if (link.validate(signature, _object->_hash)) { + if (false) { + _object->_status = DELIVERED; + _object->_proved = true; + _object->_concluded_at = OS::time(); + //z _object->_proof_packet = proof_packet; + //z link.last_proof(_object->_concluded_at); + + if (_object->_callbacks._delivery) { + try { + _object->_callbacks._delivery(*this); + } + catch (std::exception& e) { + error("An error occurred while evaluating external delivery callback for " + link.toString()); + error("The contained exception was: " + std::string(e.what())); + } + } + return true; + } + else { + return false; + } + } + else { + return false; + } + } + else if (proof.size() == IMPL_LENGTH) { + // TODO: Why is this disabled? + // signature = proof[:RNS.Identity.SIGLENGTH//8] + // proof_valid = self.link.validate(signature, self.hash) + // if proof_valid: + // self.status = PacketReceipt.DELIVERED + // self.proved = True + // self.concluded_at = time.time() + // if self.callbacks.delivery != None: + // self.callbacks.delivery(self) + // RNS.log("valid") + // return True + // else: + // RNS.log("invalid") + // return False + } + else { + return false; + } + return false; +} + +// Validate a raw proof +//bool PacketReceipt::validate_proof(const Bytes& proof, const Packet& proof_packet /*= {Type::NONE}*/) { +bool PacketReceipt::validate_proof(const Bytes& proof) { + return validate_proof(proof, {Type::NONE}); +} +bool PacketReceipt::validate_proof(const Bytes& proof, const Packet& proof_packet) { + assert(_object); + extreme("PacketReceipt::validate_proof: validating proof..."); + if (proof.size() == EXPL_LENGTH) { + // This is an explicit proof + Bytes proof_hash = proof.left(Type::Identity::HASHLENGTH/8); + Bytes signature = proof.mid(Type::Identity::HASHLENGTH/8, Type::Identity::SIGLENGTH/8); + if (proof_hash == _object->_hash) { + if (_object->_destination.identity().validate(signature, _object->_hash)) { + _object->_status = DELIVERED; + _object->_proved = true; + _object->_concluded_at = OS::time(); + //z _object->_proof_packet = proof_packet; + + if (_object->_callbacks._delivery) { + try { + _object->_callbacks._delivery(*this); + } + catch (std::exception& e) { + error("Error while executing proof validated callback. The contained exception was: " + std::string(e.what())); + } + } + return true; + } + else { + return false; + } + } + else { + return false; + } + } + else if (proof.size() == IMPL_LENGTH) { + // This is an implicit proof + if (!_object->_destination.identity()) { + return false; + } + + Bytes signature = proof.left(Type::Identity::SIGLENGTH/8); + if (_object->_destination.identity().validate(signature, _object->_hash)) { + _object->_status = DELIVERED; + _object->_proved = true; + _object->_concluded_at = OS::time(); + //z _object->_proof_packet = proof_packet; + + if (_object->_callbacks._delivery) { + try { + _object->_callbacks._delivery(*this); + } + catch (std::exception& e) { + error("Error while executing proof validated callback. The contained exception was: " + std::string(e.what())); + } + } + return true; + } + else { + return false; + } + } + else { + return false; + } + return false; +} + void PacketReceipt::check_timeout() { assert(_object); if (_object->_status == SENT && is_timed_out()) { diff --git a/src/Packet.h b/src/Packet.h index 5ed9c77..9ab1324 100644 --- a/src/Packet.h +++ b/src/Packet.h @@ -18,10 +18,15 @@ namespace RNS { class PacketReceipt; class Packet; - class ProofDestination { + class ProofDestination : public Destination { + public: + ProofDestination(const Packet& packet); + // CBA Can't use virtual methods because they are lost in object copies + //inline virtual const Bytes encrypt(const Bytes& data) { + // return data; + //} }; - /* The PacketReceipt class is used to receive notifications about :ref:`RNS.Packet` instances sent over the network. Instances @@ -59,22 +64,19 @@ namespace RNS { } public: - inline bool is_timed_out() { - assert(_object); - return ((_object->_sent_at + _object->_timeout) < Utilities::OS::time()); - } - + bool validate_proof_packet(const Packet& proof_packet); + //bool validate_link_proof(const Bytes& proof, const Link& link, const Packet& proof_packet = {Type::NONE}); + bool validate_link_proof(const Bytes& proof, const Link& link); + bool validate_link_proof(const Bytes& proof, const Link& link, const Packet& proof_packet); + //bool validate_proof(const Bytes& proof, const Packet& proof_packet = {Type::NONE}); + bool validate_proof(const Bytes& proof); + bool validate_proof(const Bytes& proof, const Packet& proof_packet); + inline double get_rtt() { assert(_object); return _object->_concluded_at - _object->_sent_at; } + inline bool is_timed_out() { assert(_object); return ((_object->_sent_at + _object->_timeout) < Utilities::OS::time()); } void check_timeout(); - /* - Sets a timeout in seconds - - :param timeout: The timeout in seconds. - */ - inline void set_timeout(int16_t timeout) { - assert(_object); - _object->_timeout = timeout; - } + // :param timeout: The timeout in seconds. + inline void set_timeout(int16_t timeout) { assert(_object); _object->_timeout = timeout; } /* Sets a function that gets called if a successfull delivery has been proven. @@ -115,7 +117,8 @@ namespace RNS { Destination _destination = {Type::NONE}; Callbacks _callbacks; double _concluded_at = 0; - //z Packet _proof_packet; + // CBA TODO This shoujld almost certainly not be a reference but we have an issue with circular dependency between Packet and PacketReceipt + //Packet _proof_packet = {Type::NONE}; int16_t _timeout = 0; friend class PacketReceipt; }; @@ -190,11 +193,13 @@ namespace RNS { bool send(); bool resend(); void prove(const Destination& destination = {Type::NONE}); + ProofDestination generate_proof_destination() const; + bool validate_proof_packet(const Packet& proof_packet); + bool validate_proof(const Bytes& proof); void update_hash(); const Bytes get_hash() const; const Bytes getTruncatedHash() const; const Bytes get_hashable_part() const; - //z ProofDestination& generate_proof_destination(); // getters/setters inline const Destination& destination() const { assert(_object); return _object->_destination; } @@ -260,7 +265,7 @@ namespace RNS { bool _fromPacked = false; bool _truncated = false; // whether data was truncated bool _encrypted = false; // whether data is encrytpted - PacketReceipt _receipt; + PacketReceipt _receipt = {Type::NONE}; uint16_t _mtu = Type::Reticulum::MTU; double _sent_at = 0; diff --git a/src/Reticulum.h b/src/Reticulum.h index 8be938e..eed18b7 100644 --- a/src/Reticulum.h +++ b/src/Reticulum.h @@ -81,6 +81,7 @@ namespace RNS { inline static void transport_enabled(bool transport_enabled) { __transport_enabled = transport_enabled; } inline static bool probe_destination_enabled() { return __allow_probes; } + inline static void probe_destination_enabled(bool allow_probes) { __allow_probes = allow_probes; } // getters/setters inline bool is_connected_to_shared_instance() const { assert(_object); return _object->_is_connected_to_shared_instance; } diff --git a/src/Transport.cpp b/src/Transport.cpp index 27c6a8c..7399f61 100644 --- a/src/Transport.cpp +++ b/src/Transport.cpp @@ -265,17 +265,17 @@ using namespace RNS::Utilities; except Exception as e: RNS.log("Could not load tunnel table from storage, the contained exception was: "+str(e), RNS.LOG_ERROR) - - if RNS.Reticulum.probe_destination_enabled(): - Transport.probe_destination = RNS.Destination(Transport.identity, RNS.Destination.IN, RNS.Destination.SINGLE, Transport.APP_NAME, "probe") - Transport.probe_destination.accepts_links(False) - Transport.probe_destination.set_proof_strategy(RNS.Destination.PROVE_ALL) - Transport.probe_destination.announce() - RNS.log("Transport Instance will respond to probe requests on "+str(Transport.probe_destination), RNS.LOG_NOTICE) - else: - Transport.probe_destination = None */ + // Create transport-specific destination for probe requests + if (Reticulum::probe_destination_enabled()) { + Destination probe_destination(_identity, Type::Destination::IN, Type::Destination::SINGLE, APP_NAME, "probe"); + probe_destination.accepts_links(false); + probe_destination.set_proof_strategy(Type::Destination::PROVE_ALL); + probe_destination.announce(); + notice("Transport Instance will respond to probe requests on " + probe_destination.toString()); + } + verbose("Transport instance " + _identity.toString() + " started"); _start_time = OS::time(); } diff --git a/src/Utilities/OS.cpp b/src/Utilities/OS.cpp index eb92646..e0052ac 100644 --- a/src/Utilities/OS.cpp +++ b/src/Utilities/OS.cpp @@ -37,6 +37,15 @@ void listDir(char * dir){ error("SPIFFS filesystem mount failed"); } else { + // ensure filesystem is writable and format if not + Bytes test; + if (!OS::write_file(test, "/test")) { + info("SPIFFS filesystem is being formatted, please wait..."); + SPIFFS.format(); + } + else { + OS::remove_file("test"); + } listDir("/"); debug("SPIFFS filesystem is ready"); }