Fix Python Reticulum interop: announce timestamps, link deadlock, packet routing

- Announce timestamps now use Unix epoch (time()) instead of OS::time()
  which returned uptime on Arduino. Python Transport compares announce
  emission timestamps for freshness — uptime-based values caused
  re-announces to be rejected by nodes with cached epoch timestamps.

- Remove blocking while(_jobs_running) waits in Transport::outbound()
  and Transport::inbound(). On single-threaded ESP32, these deadlock
  when outbound() is called from within jobs() (e.g. link proof retry).

- Fix missing _jobs_locked=false on early returns in Transport::inbound()
  which would permanently lock the transport after unpack failures,
  cache requests, or announce rate limiting.

- Link packets now inherit attached_interface from the Link object via
  the Packet(Link,...) constructor. This ensures TCP link traffic stays
  on TCP and LoRa link traffic stays on LoRa — critical for devices
  with multiple interfaces.

- Implement Link::attached_interface() const getter (was declared but
  missing implementation).

- Only apply collision-avoidance delay in Link::prove() for non-TCP
  interfaces where half-duplex radio collisions are a real concern.
This commit is contained in:
DeFiDude committed 2026-04-05 19:20:11 -06:00
1 parent e13b300b0c
commit 1cadb453eb
4 files changed
+98 -25

No files matched your search

+35 -9
View File
@@ -262,9 +262,24 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
else {
Bytes destination_hash = _object->_hash;
//p random_hash = Identity::get_random_hash()[0:5] + int(time.time()).to_bytes(5, "big")
// 5 random bytes + 5 big-endian timestamp bytes (matches Python reference)
// 5 random bytes + 5 big-endian epoch timestamp bytes (matches Python reference)
// CRITICAL: Must use Unix epoch (like Python's time.time()), NOT OS::time()
// which returns uptime on Arduino. Python Transport compares these timestamps
// for announce freshness — uptime-based values cause re-announces to be
// rejected by nodes that have cached a previous epoch-based timestamp.
Bytes random_part = Cryptography::random(5);
#ifdef ARDUINO
// On ESP32, time(nullptr) returns Unix epoch after NTP sync,
// or ~0 before sync. Either is better than millis()-based uptime.
uint64_t ts = (uint64_t)::time(nullptr);
if (ts < 1700000000) {
// NTP not yet synced — fall back to OS::time() (uptime seconds).
// Not ideal, but the announce will still work for first-time paths.
ts = (uint64_t)OS::time();
}
#else
uint64_t ts = (uint64_t)OS::time();
#endif
uint8_t time_bytes[5];
time_bytes[0] = (ts >> 32) & 0xFF;
time_bytes[1] = (ts >> 24) & 0xFF;
@@ -279,26 +294,27 @@ Packet Destination::announce(const Bytes& app_data, bool path_response, const In
}
Bytes signed_data;
//TRACEF("Destination::announce: hash: %s", _object->_hash.toHex().c_str());
//TRACEF("Destination::announce: public key: %s", _object->_identity.get_public_key().toHex().c_str());
//TRACEF("Destination::announce: name hash: %s", _object->_name_hash.toHex().c_str());
//TRACEF("Destination::announce: random hash: %s", random_hash.toHex().c_str());
//TRACEF("Destination::announce: app data: %s", new_app_data.toHex().c_str());
//TRACEF("Destination::announce: app data text:%s", new_app_data.toString().c_str());
TRACEF("[ANN-DIAG] dest_hash: %s", _object->_hash.toHex().c_str());
TRACEF("[ANN-DIAG] identity: %s", _object->_identity.hash().toHex().c_str());
TRACEF("[ANN-DIAG] pub_key(%d): %s", (int)_object->_identity.get_public_key().size(), _object->_identity.get_public_key().toHex().c_str());
TRACEF("[ANN-DIAG] name_hash: %s", _object->_name_hash.toHex().c_str());
TRACEF("[ANN-DIAG] random_hash: %s", random_hash.toHex().c_str());
TRACEF("[ANN-DIAG] app_data(%d):%s", (int)new_app_data.size(), new_app_data.toHex().c_str());
signed_data << _object->_hash << _object->_identity.get_public_key() << _object->_name_hash << random_hash;
if (new_app_data) {
signed_data << new_app_data;
}
//TRACEF("Destination::announce: signed data: %s", signed_data.toHex().c_str());
TRACEF("[ANN-DIAG] signed_data(%d): %s", (int)signed_data.size(), signed_data.toHex().c_str());
Bytes signature(_object->_identity.sign(signed_data));
//TRACEF("Destination::announce: signature: %s", signature.toHex().c_str());
TRACEF("[ANN-DIAG] signature: %s", signature.toHex().c_str());
announce_data << _object->_identity.get_public_key() << _object->_name_hash << random_hash << signature;
if (new_app_data) {
announce_data << new_app_data;
}
TRACEF("[ANN-DIAG] announce_data(%d): %s", (int)announce_data.size(), announce_data.toHex().c_str());
// CBA ACCUMULATES
try {
@@ -390,24 +406,34 @@ bool Destination::deregister_request_handler(const Bytes& path) {
void Destination::receive(const Packet& packet) {
assert(_object);
Serial.printf("[DEST-RX] receive: pkt_type=%d data=%d bytes dest=%s\n",
(int)packet.packet_type(), (int)packet.data().size(),
packet.destination_hash().toHex().substr(0, 12).c_str());
if (packet.packet_type() == Type::Packet::LINKREQUEST) {
Serial.println("[DEST-RX] → LINKREQUEST, entering incoming_link_request");
Bytes plaintext(packet.data());
incoming_link_request(plaintext, packet);
Serial.println("[DEST-RX] ← LINKREQUEST done");
}
else {
// CBA TODO Why isn't the Packet decrypting itself?
Serial.printf("[DEST-RX] → decrypting %d bytes...\n", (int)packet.data().size());
Bytes plaintext(decrypt(packet.data()));
if (plaintext) {
Serial.printf("[DEST-RX] decrypt OK, %d bytes plaintext\n", (int)plaintext.size());
if (packet.packet_type() == Type::Packet::DATA) {
if (_object->_callbacks._packet) {
try {
Serial.println("[DEST-RX] → calling packet callback");
_object->_callbacks._packet(plaintext, packet);
Serial.println("[DEST-RX] ← packet callback done");
}
catch (std::exception& e) {
DEBUGF("Error while executing receive callback from %s. The contained exception was: %s", toString().c_str(), e.what());
}
}
}
Serial.println("[DEST-RX] → proving packet");
}
else {
Serial.printf("[DEST] DECRYPT FAILED for %d byte packet to %s\n",
+33 -7
View File
@@ -176,8 +176,10 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
}
/*static*/ Link Link::validate_request( const Destination& owner, const Bytes& data, const Packet& packet) {
Serial.printf("[LINK-VR] validate_request: data=%d bytes\n", (int)data.size());
if (data.size() == ECPUBSIZE || data.size() == ECPUBSIZE + LINK_MTU_SIZE) {
try {
Serial.println("[LINK-VR] creating link object...");
Link link({Type::NONE}, nullptr, nullptr, owner, data.left(ECPUBSIZE/2), data.mid(ECPUBSIZE/2, ECPUBSIZE/2));
link.set_link_id(packet);
@@ -205,9 +207,13 @@ Link::Link(const Destination& destination /*= {Type::NONE}*/, Callbacks::establi
VERBOSEF("Validating link request %s", link.link_id().toHex().c_str());
TRACEF("Link MTU configured to %d", link.mtu());
TRACEF("Establishment timeout is %f for incoming link request %s", link.establishment_timeout(), link.link_id().toHex().c_str());
Serial.printf("[LINK-VR] → handshake (ECDH)... heap=%d\n", (int)ESP.getFreeHeap());
link.handshake();
Serial.println("[LINK-VR] ← handshake done");
link.attached_interface(packet.receiving_interface());
Serial.println("[LINK-VR] → prove (Ed25519 sign + send)...");
link.prove();
Serial.println("[LINK-VR] ← prove done");
link.request_time(OS::time());
Transport::register_link(link);
link.last_inbound(OS::time());
@@ -304,8 +310,12 @@ void Link::prove() {
_object->_last_proof_send = OS::time();
_object->_proof_retries = 0;
// Small random delay (50-200ms) to reduce collision with initiator's concurrent TX
delay(random(50, 200));
// Small random delay to reduce collision on half-duplex radio links.
// Only apply for non-TCP interfaces (LoRa, etc.) where TX collision is real.
if (_object->_attached_interface
&& _object->_attached_interface.toString().find("TCP") == std::string::npos) {
delay(random(50, 200));
}
Packet proof(*this, proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
proof.send();
@@ -332,9 +342,13 @@ void Link::retry_proof() {
Serial.printf("[LINK] Retrying proof for %s (attempt %d/%d, interval %.0fs)\n",
link_id().toHex().substr(0, 16).c_str(),
_object->_proof_retries, LinkData::MAX_PROOF_RETRIES, interval);
Serial.printf("[LINK-RETRY] creating packet... heap=%d\n", (int)ESP.getFreeHeap());
Packet proof(*this, _object->_cached_proof_data, Type::Packet::PROOF, Type::Packet::LRPROOF);
Serial.println("[LINK-RETRY] → proof.send()...");
proof.send();
Serial.println("[LINK-RETRY] ← proof.send() done");
had_outbound();
Serial.println("[LINK-RETRY] complete");
} else {
Serial.printf("[LINK] Proof retries exhausted for %s, tearing down\n",
link_id().toHex().substr(0, 16).c_str());
@@ -1080,27 +1094,31 @@ void Link::receive(const Packet& packet) {
}
if (packet.packet_type() == Type::Packet::DATA) {
VERBOSEF("[LINK-RX] context=0x%02X status=%d initiator=%d", (int)packet.context(), (int)_object->_status, _object->_initiator);
Serial.printf("[LINK-RX] DATA ctx=0x%02X data=%d bytes heap=%d\n",
(int)packet.context(), (int)packet.data().size(), (int)ESP.getFreeHeap());
bool should_query = false;
switch (packet.context()) {
case Type::Packet::CONTEXT_NONE:
{
Serial.println("[LINK-RX] → link decrypt...");
const Bytes plaintext = decrypt(packet.data());
if (plaintext) {
Serial.printf("[LINK-RX] decrypt OK, %d bytes\n", (int)plaintext.size());
if (_object->_callbacks._packet) {
//z thread = threading.Thread(target=_object->_callbacks.packet, args=(plaintext, packet))
//z thread.daemon = True
//z thread.start()
try {
Serial.println("[LINK-RX] → packet callback...");
_object->_callbacks._packet(plaintext, packet);
Serial.println("[LINK-RX] ← packet callback done");
}
catch (std::exception& e) {
ERRORF("Error while executing packet callback from %s. The contained exception was: %s", toString().c_str(), e.what());
}
}
if (_object->_destination.proof_strategy() == Type::Destination::PROVE_ALL) {
Serial.println("[LINK-RX] → prove_packet...");
const_cast<Packet&>(packet).prove();
Serial.println("[LINK-RX] ← prove_packet done");
should_query = true;
}
else if (_object->_destination.proof_strategy() == Type::Destination::PROVE_APP) {
@@ -1121,6 +1139,7 @@ void Link::receive(const Packet& packet) {
}
case Type::Packet::LINKIDENTIFY:
{
Serial.printf("[LINK-RX] LINKIDENTIFY %d bytes\n", (int)packet.data().size());
const Bytes plaintext = decrypt(packet.data());
if (plaintext) {
if (!(_object->_initiator) && plaintext.size() == Type::Identity::KEYSIZE/8 + Type::Identity::SIGLENGTH/8) {
@@ -1210,6 +1229,8 @@ void Link::receive(const Packet& packet) {
}
case Type::Packet::RESOURCE_ADV:
{
Serial.printf("[LINK-RX] RESOURCE_ADV %d bytes heap=%d\n",
(int)packet.data().size(), (int)ESP.getFreeHeap());
// Resource advertisement — decrypt and accept if strategy allows
const Bytes plaintext = decrypt(packet.data());
if (plaintext) {
@@ -1623,6 +1644,11 @@ void Link::destination(const Destination& destination) {
_object->_destination = destination;
}
const Interface& Link::attached_interface() const {
assert(_object);
return _object->_attached_interface;
}
void Link::attached_interface(const Interface& interface) {
assert(_object);
_object->_attached_interface = interface;
+11
View File
@@ -68,6 +68,11 @@ Packet::Packet(const Link& link, const Bytes& data, Type::Packet::types packet_t
TRACE("Creating packet with link...");
_object->_destination_link = link;
_object->_MTU = link.mtu();
// Route all link packets through the interface the link was established on.
// This ensures TCP links stay on TCP, LoRa links stay on LoRa, etc.
if (link.attached_interface()) {
_object->_attached_interface = link.attached_interface();
}
// CBA HACK: Need to re-build packed flags since Link was assigned
_object->_flags = get_packed_flags();
MEMF("Packet link object created, this: %p, data: %p", (void*)this, (void*)_object.get());
@@ -376,6 +381,12 @@ TRACEF("***** Destination Data: %s", _object->_ciphertext.toHex().c_str());
_object->_raw.data()[2], _object->_raw.data()[3]);
}
if (_object->_packet_type == ANNOUNCE) {
TRACEF("[ANN-DIAG] PACKED: flags=0x%02x hops=%d ctx=0x%02x raw(%d): %s",
_object->_flags, _object->_hops, _object->_context,
(int)_object->_raw.size(), _object->_raw.toHex().c_str());
}
if (_object->_raw.size() > _object->_MTU) {
throw std::length_error("Packet size of " + std::to_string(_object->_raw.size()) + " exceeds MTU of " + std::to_string(_object->_MTU) +" bytes");
}
+19 -9
View File
@@ -318,6 +318,7 @@ Transport::DestinationEntry empty_destination_entry;
// (responder sent proof but RTT never arrived — packet lost on air)
else if (link.status() == Type::Link::HANDSHAKE) {
const_cast<Link&>(link).retry_proof();
Serial.println("[TRANSPORT] retry_proof returned OK");
}
}
@@ -805,11 +806,10 @@ Transport::DestinationEntry empty_destination_entry;
TRACEF("Transport::outbound: destination=%s hops=%d", packet.destination_hash().toHex().c_str(), packet.hops());
while (_jobs_running) {
TRACE("Transport::outbound: sleeping...");
OS::sleep(0.0005);
}
// NOTE: The Python reference has `while jobs_running: sleep()` here,
// but on single-threaded ESP32 (Arduino), jobs/inbound/outbound all run
// on the same thread. Waiting for _jobs_running would deadlock when
// outbound() is called from within jobs() (e.g. link proof retry).
_jobs_locked = true;
bool sent = false;
@@ -1321,10 +1321,12 @@ Transport::DestinationEntry empty_destination_entry;
}
*/
while (_jobs_running) {
TRACE("Transport::inbound: sleeping...");
OS::sleep(0.0005);
}
Serial.printf("[TRANSPORT] inbound: %d bytes from %s, jobs_locked=%d jobs_running=%d\n",
(int)raw.size(), interface ? interface.toString().c_str() : "NULL",
(int)_jobs_locked, (int)_jobs_running);
// NOTE: _jobs_running wait removed — single-threaded ESP32 deadlocks
// when inbound() is called from within jobs() (e.g. loopback packets).
if (!_identity) {
WARNING("Transport::inbound: No identity!");
@@ -1334,10 +1336,15 @@ Transport::DestinationEntry empty_destination_entry;
_jobs_locked = true;
Packet packet(RNS::Destination(RNS::Type::NONE), raw);
Serial.printf("[TRANSPORT] unpacking %d bytes...\n", (int)raw.size());
if (!packet.unpack()) {
WARNING("Transport::inbound: Packet unpack failed!");
_jobs_locked = false; // FIX: was missing, would deadlock jobs
return;
}
Serial.printf("[TRANSPORT] unpacked: pt=%d dt=%d dest=%s\n",
(int)packet.packet_type(), (int)packet.destination_type(),
packet.destination_hash().toHex().substr(0, 12).c_str());
#ifndef NDEBUG
TRACEF("Transport::inbound: packet: %s", packet.debugString().c_str());
#endif
@@ -1520,6 +1527,7 @@ Transport::DestinationEntry empty_destination_entry;
if (packet.context() == Type::Packet::CACHE_REQUEST) {
if (cache_request_packet(packet)) {
TRACE("Transport::inbound: Cached packet");
_jobs_locked = false;
return;
}
}
@@ -1607,6 +1615,7 @@ Transport::DestinationEntry empty_destination_entry;
}
catch (const std::exception& e) {
WARNINGF("Dropping link request packet. The contained exception was: %s", e.what());
_jobs_locked = false;
return;
}
}
@@ -1743,6 +1752,7 @@ Transport::DestinationEntry empty_destination_entry;
bool is_known = (bool)Identity::recall(packet.destination_hash());
if (!is_known && ++_verify_count > 5) {
DEBUG("Transport::inbound: announce rate-limited (>5 new verifies/sec)");
_jobs_locked = false;
return;
}
}