From 670820a41e31dd6c6744331208ec06bf8cee71e3 Mon Sep 17 00:00:00 2001 From: DeFiDude <59237470+DeFiDude@users.noreply.github.com> Date: Sat, 25 Apr 2026 20:36:59 -0600 Subject: [PATCH] Add AutoInterface (IPv6 multicast LAN auto-discovery, Python-wire-compatible) --- .gitignore | 1 + src/Interfaces/AutoInterface.cpp | 582 +++++++++++++++++++++++++++ src/Interfaces/AutoInterface.h | 200 +++++++++ src/Interfaces/AutoInterfacePeer.cpp | 78 ++++ src/Interfaces/AutoInterfacePeer.h | 42 ++ test/test_autoiface/test_main.cpp | 458 +++++++++++++++++++++ 6 files changed, 1361 insertions(+) create mode 100644 src/Interfaces/AutoInterface.cpp create mode 100644 src/Interfaces/AutoInterface.h create mode 100644 src/Interfaces/AutoInterfacePeer.cpp create mode 100644 src/Interfaces/AutoInterfacePeer.h create mode 100644 test/test_autoiface/test_main.cpp diff --git a/.gitignore b/.gitignore index 4c74948..cc6ac5f 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ .vscode/launch.json .vscode/ipch destination_table +cache/ diff --git a/src/Interfaces/AutoInterface.cpp b/src/Interfaces/AutoInterface.cpp new file mode 100644 index 0000000..fc70ed4 --- /dev/null +++ b/src/Interfaces/AutoInterface.cpp @@ -0,0 +1,582 @@ +#include "AutoInterface.h" +#include "AutoInterfacePeer.h" + +#include "../Log.h" +#include "../Transport.h" +#include "../Utilities/OS.h" + +#include +#include +#include + +// Sockets layer — POSIX on native, lwIP on Arduino. lwIP intentionally +// exposes a BSD-compatible API via (socket/bind/recvfrom/ +// sendto/setsockopt/fcntl all work as macros), so the bodies below are +// identical on both targets. +#ifdef ARDUINO +#include +// Defense in depth: AutoInterface needs IPv6 + MLD enabled in lwIP so +// IPV6_JOIN_GROUP works. espressif32@6.7.0's prebuilt SDK enables both +// (LWIP_IPV6=1, LWIP_IPV6_MLD inherited from LWIP_IPV6); if a future +// platform release flips that off, fail loudly at compile time so we +// don't ship silent multicast breakage. +#if !LWIP_IPV6 +#error "AutoInterface requires lwIP IPv6. CONFIG_LWIP_IPV6 must be enabled." +#endif +#if !LWIP_IPV6_MLD +#error "AutoInterface requires lwIP MLD. CONFIG_LWIP_IPV6_MLD must be enabled." +#endif +#include +#include +// errno on lwIP is provided via Arduino's stdlib; is safe to include. +#include +#else +#include +#include +#include +#include +#include +#include +#endif + +namespace RNS { + + AutoInterface::AutoInterface(const char* name, + const char* group_id, + char addr_type, + char scope, + uint16_t discovery_port, + uint16_t data_port, + uint8_t max_peers) + : _addr_type(addr_type), + _scope(scope), + _discovery_port(discovery_port), + _unicast_disco_port(discovery_port + 1), + _data_port(data_port), + _max_peers(max_peers) + { + _name = name ? name : "AutoInterface"; + _group_id_bytes = Bytes(group_id); + _HW_MTU = HW_MTU; + _FIXED_MTU = FIXED_MTU; + _bitrate = BITRATE_GUESS; + _IN = true; + _OUT = true; + } + + AutoInterface::~AutoInterface() { + if (_online) { + stop(); + } + } + + namespace { + // Python / glibc / macOS produce lowercase canonical IPv6 strings; + // lwIP's ip6addr_ntoa_r produces UPPERCASE. RFC 5952 mandates + // lowercase, so normalize here so our SHA256 hashes wire-match + // every other AutoInterface implementation regardless of platform. + std::string canonicalize_ipv6(const std::string& addr_str) { + struct in6_addr tmp; + if (inet_pton(AF_INET6, addr_str.c_str(), &tmp) != 1) return addr_str; + char buf[INET6_ADDRSTRLEN]; + if (inet_ntop(AF_INET6, &tmp, buf, sizeof(buf)) == nullptr) return addr_str; + std::string out(buf); + for (auto& c : out) { + if (c >= 'A' && c <= 'F') c = static_cast(c - 'A' + 'a'); + } + return out; + } + } + + void AutoInterface::set_link_local(const std::string& addr_str, uint32_t scope_id) { + _scope_id = scope_id; + // Re-canonicalize so the stored form is the lowercase RFC 5952 form + // regardless of whether the caller passed an expanded + // "fe80:0000:..." form (Arduino IPv6Address::toString) or + // uppercase from lwIP. Peers compute their expected self-token by + // hashing what they read off recvfrom + inet_ntop, which on every + // other implementation is lowercase canonical. + struct in6_addr tmp; + if (inet_pton(AF_INET6, addr_str.c_str(), &tmp) == 1) { + std::memcpy(_self_link_local_bin.data(), &tmp, 16); + } + _link_local_addr = canonicalize_ipv6(addr_str); + _self_disco_token = compute_discovery_token(_group_id_bytes, _link_local_addr); + } + + bool AutoInterface::start() { + if (_online) return true; + if (_link_local_addr.empty()) { + WARNING("AutoInterface::start: no link-local address configured"); + return false; + } + + // Compute group hash + multicast address now (cheap; idempotent). + _group_hash = compute_group_hash(_group_id_bytes); + _mcast_addr_str = compute_multicast_address(_group_hash, _addr_type, _scope); + struct in6_addr mc_tmp; + if (inet_pton(AF_INET6, _mcast_addr_str.c_str(), &mc_tmp) != 1) { + WARNING("AutoInterface::start: invalid multicast address"); + return false; + } + std::memcpy(_mcast_addr_bin.data(), &mc_tmp, 16); + + if (!open_sockets()) { + close_sockets(); + return false; + } + + _online = true; + _final_init_done = false; // ignore any RX before peer_jobs first tick + _next_announce_ms = 0; + _next_peer_job_ms = PEER_JOB_INTERVAL_MS; + _last_mcast_echo_ms = 0; + _has_mcast_echo = false; + return true; + } + + void AutoInterface::stop() { + if (!_online) return; + // Tear down all spawned peers — Transport must not retain stale refs. + for (auto& kv : _peers) { + Transport::deregister_interface(kv.second.wrapper); + kv.second.peer_iface->stop(); + } + _peers.clear(); + close_sockets(); + _online = false; + _final_init_done = false; + _has_mcast_echo = false; + } + + void AutoInterface::loop() { + loop_at(static_cast(Utilities::OS::ltime())); + } + + void AutoInterface::loop_at(uint64_t now_ms) { + if (!_online) return; + + // Drain RX (each capped to 4 packets / call to bound CPU). + poll_multicast(); + poll_unicast_disco(); + poll_data(); + + if (now_ms >= _next_announce_ms) { + announce_peer(); + _next_announce_ms = now_ms + ANNOUNCE_INTERVAL_MS; + // First announce sent — RX may now process discovery packets. + _final_init_done = true; + } + + if (now_ms >= _next_peer_job_ms) { + peer_jobs(now_ms); + _next_peer_job_ms = now_ms + PEER_JOB_INTERVAL_MS; + } + } + + void AutoInterface::send_outgoing(const Bytes& /*data*/) { + // No-op. Outbound goes through per-peer wrappers (matches Python). + } + + // --- Wire-format derivation --- + // + // Mirrors Python AutoInterface.py: + // - group_hash = SHA256(group_id) (lines 202-203) + // - mcast address = "ff{type}{scope}:0:{g[2:4]}:..." (lines 204-212) + // each ":NN:" pair is uint16 = (g[2k]<<8)|g[2k+1], + // printed with min-2 hex chars (Python "{:02x}") + // - discovery token = SHA256(group_id || link_local_addr_str) (lines 491-501) + // link_local_addr_str is canonical RFC 5952 (no scope suffix) + + Bytes AutoInterface::compute_group_hash(const Bytes& group_id) { + return Identity::full_hash(group_id); + } + + std::string AutoInterface::compute_multicast_address(const Bytes& group_hash, + char addr_type, + char scope) { + if (group_hash.size() < 14) { + return std::string(); + } + const uint8_t* g = group_hash.data(); + char buf[64]; + std::snprintf(buf, sizeof(buf), + "ff%c%c:0:%02x:%02x:%02x:%02x:%02x:%02x", + addr_type, scope, + (unsigned)((g[2] << 8) | g[3]), + (unsigned)((g[4] << 8) | g[5]), + (unsigned)((g[6] << 8) | g[7]), + (unsigned)((g[8] << 8) | g[9]), + (unsigned)((g[10] << 8) | g[11]), + (unsigned)((g[12] << 8) | g[13])); + return std::string(buf); + } + + Bytes AutoInterface::compute_discovery_token(const Bytes& group_id, + const std::string& link_local_addr) { + Bytes material; + material.append(group_id); + material.append(link_local_addr); + return Identity::full_hash(material); + } + + // --- Peer table semantics --- + + bool AutoInterface::has_peer(const IPv6Addr& addr) const { + return _peers.find(addr_key(addr)) != _peers.end(); + } + + uint64_t AutoInterface::peer_last_heard_ms(const IPv6Addr& addr) const { + auto it = _peers.find(addr_key(addr)); + return it == _peers.end() ? 0 : it->second.last_heard_ms; + } + + void AutoInterface::add_peer(const IPv6Addr& addr, + uint32_t scope_id, + uint64_t now_ms) { + const std::string key = addr_key(addr); + auto it = _peers.find(key); + if (it != _peers.end()) { + // Already known — just refresh the freshness timestamp. + it->second.last_heard_ms = now_ms; + return; + } + if (_peers.size() >= _max_peers) { + WARNING("AutoInterface: peer cap reached, ignoring new peer"); + return; + } + + // Create the peer impl as a shared_ptr; alias it into a base + // shared_ptr so the Interface wrapper shares the same + // control block (no double-delete). The peer ctor already sets + // HW_MTU / FIXED_MTU / bitrate / IN / OUT. + auto peer_impl = std::make_shared(this, addr, scope_id); + std::shared_ptr base = peer_impl; + + PeerEntry entry; + entry.addr = addr; + entry.scope_id = scope_id; + entry.last_heard_ms = now_ms; + entry.last_outbound_ms = now_ms; + entry.peer_iface = peer_impl; + entry.wrapper = Interface(base); + + auto inserted = _peers.emplace(key, std::move(entry)); + Interface& w = inserted.first->second.wrapper; + w.mode(_mode); + w.start(); // sets _online = true on the impl + Transport::register_interface(w); + } + + void AutoInterface::refresh_peer(const std::string& key, uint64_t now_ms) { + auto it = _peers.find(key); + if (it != _peers.end()) { + it->second.last_heard_ms = now_ms; + } + } + + void AutoInterface::peer_jobs(uint64_t now_ms) { + // Pass 1: collect timed-out peers (don't mutate map while iterating). + std::vector to_remove; + to_remove.reserve(_peers.size()); + for (const auto& kv : _peers) { + if (now_ms > kv.second.last_heard_ms + PEERING_TIMEOUT_MS) { + to_remove.push_back(kv.first); + } + } + + // Pass 2: deregister + erase. + for (const auto& key : to_remove) { + auto it = _peers.find(key); + if (it == _peers.end()) continue; + Transport::deregister_interface(it->second.wrapper); + it->second.peer_iface->stop(); + _peers.erase(it); + } + + // Pass 3: reverse-peering — periodically send a unicast token to each + // peer so they see us even when our multicast announces are dropped + // by a hostile AP. Mirrors Python AutoInterface lines 393-403. + for (auto& kv : _peers) { + if (now_ms > kv.second.last_outbound_ms + REVERSE_PEERING_INTERVAL_MS) { + reverse_announce(kv.second.addr, kv.second.scope_id); + kv.second.last_outbound_ms = now_ms; + } + } + } + + // --- Test-only entry points --- + + void AutoInterface::test_inject_peer(const IPv6Addr& addr, + uint32_t scope_id, + uint64_t now_ms) { + add_peer(addr, scope_id, now_ms); + } + + void AutoInterface::test_run_peer_jobs(uint64_t now_ms) { + peer_jobs(now_ms); + } + + void AutoInterface::test_loop_at(uint64_t now_ms) { + loop_at(now_ms); + } + + // --- Socket lifecycle --- + // + // Three non-blocking AF_INET6 / SOCK_DGRAM sockets: + // _disco_sock — RX multicast on _discovery_port + TX announces + // _unicast_sock — RX reverse-peering tokens on _unicast_disco_port + // _data_sock — RX peer payloads + TX peer payloads on _data_port + // + // Multicast group join (IPV6_JOIN_GROUP) is best-effort: failure logs a + // warning but does not fail start(). This lets us boot without LAN + // connectivity (or on hosts where the chosen scope id has no link-local + // IPv6) and recover later when the network comes up — Python AutoInterface + // has the same robustness property. + + namespace { + // RAII helper to close a half-opened FD chain on early-return. + void try_close(int& fd) { + if (fd >= 0) { + ::close(fd); + fd = -1; + } + } + + bool make_nonblocking(int fd) { + int flags = ::fcntl(fd, F_GETFL, 0); + if (flags < 0) return false; + return ::fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0; + } + + bool bind_any(int fd, uint16_t port) { + sockaddr_in6 a{}; + a.sin6_family = AF_INET6; + a.sin6_port = htons(port); + a.sin6_addr = in6addr_any; + return ::bind(fd, reinterpret_cast(&a), sizeof(a)) == 0; + } + } + + bool AutoInterface::open_sockets() { + const int yes = 1; + const int hops = 1; + const unsigned int ifindex = static_cast(_scope_id); + + // --- Multicast discovery socket (RX + TX announces) --- + _disco_sock = ::socket(AF_INET6, SOCK_DGRAM, 0); + if (_disco_sock < 0) { + WARNING("AutoInterface: socket(disco) failed"); + return false; + } + ::setsockopt(_disco_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); +#ifdef SO_REUSEPORT + ::setsockopt(_disco_sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)); +#endif + const int v6only = 1; + ::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only)); + // IPV6_MULTICAST_IF: outgoing multicast leaves on this interface + ::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, + &ifindex, sizeof(ifindex)); + // IPV6_MULTICAST_LOOP: receive our own multicast frames so we can detect + // the multicast echo (matches Python AutoInterface lines 451-464). + ::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &yes, sizeof(yes)); + // IPV6_MULTICAST_HOPS = 1 — link-local only, never leak. + ::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &hops, sizeof(hops)); + if (!bind_any(_disco_sock, _discovery_port)) { + WARNING("AutoInterface: bind(disco) failed"); + return false; + } + if (!make_nonblocking(_disco_sock)) { + WARNING("AutoInterface: make_nonblocking(disco) failed"); + return false; + } + + // IPV6_JOIN_GROUP: best-effort (see header note). + struct ipv6_mreq mreq{}; + std::memcpy(&mreq.ipv6mr_multiaddr, _mcast_addr_bin.data(), 16); + mreq.ipv6mr_interface = ifindex; + if (::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_JOIN_GROUP, + &mreq, sizeof(mreq)) != 0) { + WARNINGF("AutoInterface: IPV6_JOIN_GROUP failed (errno=%d) — " + "multicast RX may not work on this interface", errno); + } + + // --- Unicast discovery socket (port 29717) --- + _unicast_sock = ::socket(AF_INET6, SOCK_DGRAM, 0); + if (_unicast_sock < 0) return false; + ::setsockopt(_unicast_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); +#ifdef SO_REUSEPORT + ::setsockopt(_unicast_sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)); +#endif + ::setsockopt(_unicast_sock, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only)); + if (!bind_any(_unicast_sock, _unicast_disco_port)) { + WARNING("AutoInterface: bind(unicast) failed"); + return false; + } + if (!make_nonblocking(_unicast_sock)) return false; + + // --- Data socket (port 42671) --- + _data_sock = ::socket(AF_INET6, SOCK_DGRAM, 0); + if (_data_sock < 0) return false; + ::setsockopt(_data_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); +#ifdef SO_REUSEPORT + ::setsockopt(_data_sock, SOL_SOCKET, SO_REUSEPORT, &yes, sizeof(yes)); +#endif + ::setsockopt(_data_sock, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only)); + if (!bind_any(_data_sock, _data_port)) { + WARNING("AutoInterface: bind(data) failed"); + return false; + } + if (!make_nonblocking(_data_sock)) return false; + + return true; + } + + void AutoInterface::close_sockets() { + if (_disco_sock >= 0) { + // Best-effort leave group before closing. + struct ipv6_mreq mreq{}; + std::memcpy(&mreq.ipv6mr_multiaddr, _mcast_addr_bin.data(), 16); + mreq.ipv6mr_interface = static_cast(_scope_id); + ::setsockopt(_disco_sock, IPPROTO_IPV6, IPV6_LEAVE_GROUP, + &mreq, sizeof(mreq)); + } + try_close(_disco_sock); + try_close(_unicast_sock); + try_close(_data_sock); + } + + // --- TX / RX paths (BSD socket API; lwIP exposes the same signatures). --- + + namespace { + constexpr int kPollBudget = 4; // packets per poll() call + + void make_dst_sockaddr(sockaddr_in6& dst, + const AutoInterface::IPv6Addr& addr, + uint32_t scope_id, + uint16_t port) { + std::memset(&dst, 0, sizeof(dst)); + dst.sin6_family = AF_INET6; + dst.sin6_port = htons(port); + dst.sin6_scope_id = scope_id; + std::memcpy(&dst.sin6_addr, addr.data(), 16); + } + } + + void AutoInterface::announce_peer() { + if (_disco_sock < 0 || _self_disco_token.size() < 32) return; + sockaddr_in6 dst; + make_dst_sockaddr(dst, _mcast_addr_bin, _scope_id, _discovery_port); + ssize_t n = ::sendto(_disco_sock, + _self_disco_token.data(), _self_disco_token.size(), + 0, reinterpret_cast(&dst), sizeof(dst)); + if (n < 0 && errno != ENETUNREACH && errno != EHOSTUNREACH) { + VERBOSEF("AutoInterface::announce_peer: sendto errno=%d", errno); + } + } + + void AutoInterface::reverse_announce(const IPv6Addr& peer_addr, + uint32_t peer_scope) { + if (_unicast_sock < 0 || _self_disco_token.size() < 32) return; + sockaddr_in6 dst; + make_dst_sockaddr(dst, peer_addr, peer_scope, _unicast_disco_port); + ::sendto(_unicast_sock, + _self_disco_token.data(), _self_disco_token.size(), + 0, reinterpret_cast(&dst), sizeof(dst)); + } + + void AutoInterface::poll_multicast() { + if (_disco_sock < 0) return; + for (int i = 0; i < kPollBudget; ++i) { + sockaddr_in6 src{}; + socklen_t sl = sizeof(src); + ssize_t n = ::recvfrom(_disco_sock, _rx_buf, HW_MTU, 0, + reinterpret_cast(&src), &sl); + if (n <= 0) break; + if (!_final_init_done) continue; + + // Self-echo: confirms multicast loopback works (carrier). + if (std::memcmp(&src.sin6_addr, _self_link_local_bin.data(), 16) == 0) { + _last_mcast_echo_ms = static_cast(Utilities::OS::ltime()); + _has_mcast_echo = true; + continue; + } + if (n < 32) continue; + + char src_str[64]; + ::inet_ntop(AF_INET6, &src.sin6_addr, src_str, sizeof(src_str)); + std::string canon = canonicalize_ipv6(src_str); + Bytes expected = compute_discovery_token(_group_id_bytes, canon); + if (expected.size() < 32) continue; + if (std::memcmp(_rx_buf, expected.data(), 32) != 0) continue; + + IPv6Addr addr; + std::memcpy(addr.data(), &src.sin6_addr, 16); + add_peer(addr, src.sin6_scope_id, + static_cast(Utilities::OS::ltime())); + } + } + + void AutoInterface::poll_unicast_disco() { + if (_unicast_sock < 0) return; + for (int i = 0; i < kPollBudget; ++i) { + sockaddr_in6 src{}; + socklen_t sl = sizeof(src); + ssize_t n = ::recvfrom(_unicast_sock, _rx_buf, HW_MTU, 0, + reinterpret_cast(&src), &sl); + if (n <= 0) break; + if (!_final_init_done) continue; + if (n < 32) continue; + + char src_str[64]; + ::inet_ntop(AF_INET6, &src.sin6_addr, src_str, sizeof(src_str)); + std::string canon = canonicalize_ipv6(src_str); + Bytes expected = compute_discovery_token(_group_id_bytes, canon); + if (expected.size() < 32) continue; + if (std::memcmp(_rx_buf, expected.data(), 32) != 0) continue; + + IPv6Addr addr; + std::memcpy(addr.data(), &src.sin6_addr, 16); + add_peer(addr, src.sin6_scope_id, + static_cast(Utilities::OS::ltime())); + } + } + + void AutoInterface::poll_data() { + if (_data_sock < 0) return; + for (int i = 0; i < kPollBudget; ++i) { + sockaddr_in6 src{}; + socklen_t sl = sizeof(src); + ssize_t n = ::recvfrom(_data_sock, _rx_buf, HW_MTU, 0, + reinterpret_cast(&src), &sl); + if (n <= 0) break; + IPv6Addr addr; + std::memcpy(addr.data(), &src.sin6_addr, 16); + Bytes data(_rx_buf, static_cast(n)); + route_inbound(data, addr); + } + } + + void AutoInterface::route_inbound(const Bytes& data, const IPv6Addr& src) { + auto it = _peers.find(addr_key(src)); + if (it == _peers.end()) return; + + // MIF dedup ring — drops duplicates that arrive on multiple netifs + // within MIF_DEDUP_TTL_MS. Single-NIC devices rarely hit this but + // the cost is small and it matches Python's behaviour. + Bytes h = Identity::full_hash(data); + const uint64_t now = static_cast(Utilities::OS::ltime()); + for (const auto& d : _mif_dedup) { + if (d.hash == h && now < d.expires_ms) return; + } + _mif_dedup.push_back({h, now + MIF_DEDUP_TTL_MS}); + while (_mif_dedup.size() > RNS_AUTOIFACE_MIF_DEDUP_LEN) { + _mif_dedup.pop_front(); + } + + it->second.last_heard_ms = now; + it->second.peer_iface->deliver_incoming(data); + } + +} // namespace RNS diff --git a/src/Interfaces/AutoInterface.h b/src/Interfaces/AutoInterface.h new file mode 100644 index 0000000..f4e2297 --- /dev/null +++ b/src/Interfaces/AutoInterface.h @@ -0,0 +1,200 @@ +#pragma once + +#include "../Interface.h" +#include "../Bytes.h" +#include "../Identity.h" + +#include +#include +#include +#include +#include +#include + +// MIF (multi-interface) dedup ring length. Override per device in +// platformio.ini build_flags for memory-tight targets (e.g. Ratcom). +#ifndef RNS_AUTOIFACE_MIF_DEDUP_LEN +#define RNS_AUTOIFACE_MIF_DEDUP_LEN 48 +#endif + +// Default cap on concurrent spawned peers. Each peer costs ~280 B plus +// whatever Transport caches for its paths. Override per device. +#ifndef RNS_AUTOIFACE_MAX_PEERS_DEFAULT +#define RNS_AUTOIFACE_MAX_PEERS_DEFAULT 8 +#endif + +namespace RNS { + + class AutoInterfacePeer; + + /* + * Reticulum AutoInterface — IPv6 link-local multicast LAN auto-discovery. + * + * Wire-compatible with the Python reference implementation + * (RNS/Interfaces/AutoInterface.py). Listens on a multicast group derived + * from SHA256(group_id) and spawns a per-peer AutoInterfacePeer Interface + * for each discovered node. + * + * Design notes: + * - One parent AutoInterface holds the multicast/unicast/data sockets. + * - One AutoInterfacePeer (registered with Transport) per peer. + * - Single-threaded, cooperative: loop() polls non-blocking sockets. + * - IFAC: not implemented in v1 (see plan). + */ + class AutoInterface : public InterfaceImpl { + public: + // Wire-compatible defaults — must match Python AutoInterface.py + static constexpr uint16_t DEFAULT_DISCOVERY_PORT = 29716; + static constexpr uint16_t DEFAULT_UNICAST_DISCO_PORT = 29717; // discovery + 1 + static constexpr uint16_t DEFAULT_DATA_PORT = 42671; + static constexpr const char* DEFAULT_GROUP_ID = "reticulum"; + static constexpr uint16_t HW_MTU = 1196; + static constexpr bool FIXED_MTU = true; + static constexpr uint32_t BITRATE_GUESS = 10 * 1000 * 1000; + + static constexpr uint32_t ANNOUNCE_INTERVAL_MS = 1600; + static constexpr uint32_t PEER_JOB_INTERVAL_MS = 4000; + static constexpr uint32_t PEERING_TIMEOUT_MS = 22000; + static constexpr uint32_t MCAST_ECHO_TIMEOUT_MS = 6500; + static constexpr uint32_t REVERSE_PEERING_INTERVAL_MS = 5200; // 1.6 * 3.25 + static constexpr uint32_t MIF_DEDUP_TTL_MS = 750; + + static constexpr char SCOPE_LINK = '2'; + static constexpr char SCOPE_ADMIN = '4'; + static constexpr char SCOPE_SITE = '5'; + static constexpr char SCOPE_ORGANISATION = '8'; + static constexpr char SCOPE_GLOBAL = 'e'; + + static constexpr char MCAST_ADDR_TYPE_PERMANENT = '0'; + static constexpr char MCAST_ADDR_TYPE_TEMPORARY = '1'; + + using IPv6Addr = std::array; + + AutoInterface(const char* name = "AutoInterface", + const char* group_id = DEFAULT_GROUP_ID, + char addr_type = MCAST_ADDR_TYPE_TEMPORARY, + char scope = SCOPE_LINK, + uint16_t discovery_port = DEFAULT_DISCOVERY_PORT, + uint16_t data_port = DEFAULT_DATA_PORT, + uint8_t max_peers = RNS_AUTOIFACE_MAX_PEERS_DEFAULT); + virtual ~AutoInterface(); + + // InterfaceImpl overrides + virtual bool start() override; + virtual void stop() override; + virtual void loop() override; + virtual void send_outgoing(const Bytes& data) override; // no-op (mirrors Python) + + // Diagnostics / UI surface + size_t peer_count() const { return _peers.size(); } + bool has_carrier() const { return _has_mcast_echo; } + const std::string& multicast_address() const { return _mcast_addr_str; } + const std::string& link_local_address() const { return _link_local_addr; } + bool has_peer(const IPv6Addr& addr) const; + uint64_t peer_last_heard_ms(const IPv6Addr& addr) const; + + // Inject the local link-local address + interface scope id. + // Must be called before start(). Production code resolves these from + // WiFi.linkLocalIPv6() + esp_netif_get_netif_impl_index() (Arduino) or + // getifaddrs() + if_nametoindex() (native). + void set_link_local(const std::string& addr_str, uint32_t scope_id); + + // Diagnostic FD accessors — returns -1 when closed. + int discovery_socket_fd() const { return _disco_sock; } + int unicast_socket_fd() const { return _unicast_sock; } + int data_socket_fd() const { return _data_sock; } + + // Test-only entry points (do not call from production code). + // Allow driving the peer table without real sockets / real time. + void test_inject_peer(const IPv6Addr& addr, uint32_t scope_id, uint64_t now_ms); + void test_run_peer_jobs(uint64_t now_ms); + void test_loop_at(uint64_t now_ms); + + // Drive a single iteration with an injected clock. Production code + // uses the no-arg loop() which calls this with OS::ltime(). + void loop_at(uint64_t now_ms); + + virtual std::string toString() const override { + return "AutoInterface[" + _name + "]"; + } + + // Wire-format derivation (pure, exposed for tests / external diagnostics). + // All match the Python reference (RNS/Interfaces/AutoInterface.py). + static Bytes compute_group_hash(const Bytes& group_id); + static std::string compute_multicast_address(const Bytes& group_hash, + char addr_type, + char scope); + static Bytes compute_discovery_token(const Bytes& group_id, + const std::string& link_local_addr); + + protected: + friend class AutoInterfacePeer; + + // Lifecycle helpers — implemented in commits 4+ + bool open_sockets(); + void close_sockets(); + void poll_multicast(); + void poll_unicast_disco(); + void poll_data(); + void announce_peer(); + void reverse_announce(const IPv6Addr& peer_addr, uint32_t scope_id); + void peer_jobs(uint64_t now_ms); + void add_peer(const IPv6Addr& addr, uint32_t scope_id, uint64_t now_ms); + void refresh_peer(const std::string& key, uint64_t now_ms); + void route_inbound(const Bytes& data, const IPv6Addr& src); + + // Map key derivation + static std::string addr_key(const IPv6Addr& addr) { + return std::string(reinterpret_cast(addr.data()), addr.size()); + } + + // Configuration (immutable after start) + Bytes _group_id_bytes; + Bytes _group_hash; + char _addr_type; + char _scope; + uint16_t _discovery_port; + uint16_t _unicast_disco_port; + uint16_t _data_port; + uint8_t _max_peers; + std::string _mcast_addr_str; + IPv6Addr _mcast_addr_bin{}; + + // Sockets — opaque int FDs; -1 when closed + int _disco_sock = -1; + int _unicast_sock = -1; + int _data_sock = -1; + + // Local link-local state + std::string _link_local_addr; + IPv6Addr _self_link_local_bin{}; + uint32_t _scope_id = 0; + Bytes _self_disco_token; + + // Peer table — keyed by 16-byte address (as std::string for cheap lookup) + struct PeerEntry { + IPv6Addr addr{}; + uint32_t scope_id = 0; + uint64_t last_heard_ms = 0; + uint64_t last_outbound_ms = 0; + std::shared_ptr peer_iface; + Interface wrapper{Type::NONE}; + }; + std::map _peers; + + // Multi-interface dedup ring + struct DedupEntry { Bytes hash; uint64_t expires_ms = 0; }; + std::deque _mif_dedup; + + // Pacing / state + uint64_t _next_announce_ms = 0; + uint64_t _next_peer_job_ms = 0; + uint64_t _last_mcast_echo_ms = 0; + bool _has_mcast_echo = false; + bool _final_init_done = false; + + // RX scratch (single, reused across all three sockets — single-threaded). + uint8_t _rx_buf[HW_MTU + 4]{}; + }; + +} // namespace RNS diff --git a/src/Interfaces/AutoInterfacePeer.cpp b/src/Interfaces/AutoInterfacePeer.cpp new file mode 100644 index 0000000..1fd644f --- /dev/null +++ b/src/Interfaces/AutoInterfacePeer.cpp @@ -0,0 +1,78 @@ +#include "AutoInterfacePeer.h" +#include "AutoInterface.h" + +#include "../Log.h" + +#include + +#ifdef ARDUINO +#include +#include +#else +#include +#include +#include +#endif + +namespace RNS { + + AutoInterfacePeer::AutoInterfacePeer(AutoInterface* parent, + const AutoInterface::IPv6Addr& addr, + uint32_t scope_id) + : _parent(parent), + _peer_addr(addr), + _peer_scope(scope_id) + { + _HW_MTU = AutoInterface::HW_MTU; + _FIXED_MTU = AutoInterface::FIXED_MTU; + _bitrate = AutoInterface::BITRATE_GUESS; + _IN = true; + _OUT = true; + } + + AutoInterfacePeer::~AutoInterfacePeer() {} + + bool AutoInterfacePeer::start() { _online = true; return true; } + void AutoInterfacePeer::stop() { _online = false; } + void AutoInterfacePeer::loop() {} // RX driven by parent's poll_data() + + void AutoInterfacePeer::send_outgoing(const Bytes& data) { + if (!_online || !_parent) return; + const int fd = _parent->_data_sock; + if (fd < 0) return; + sockaddr_in6 dst{}; + dst.sin6_family = AF_INET6; + dst.sin6_port = htons(_parent->_data_port); + dst.sin6_scope_id = _peer_scope; + std::memcpy(&dst.sin6_addr, _peer_addr.data(), 16); + ssize_t n = sendto(fd, data.data(), data.size(), 0, + reinterpret_cast(&dst), sizeof(dst)); + if (n > 0) { + _txb += static_cast(n); + _parent->_txb += static_cast(n); + handle_outgoing(data); + } + } + + void AutoInterfacePeer::deliver_incoming(const Bytes& data) { + if (!_online) return; + handle_incoming(data); + } + + std::string AutoInterfacePeer::toString() const { + // Lowercase RFC 5952 canonical form via inet_ntop, lowercased to match + // Python (lwIP emits uppercase). Display only — never used for hashing. + char buf[INET6_ADDRSTRLEN]; + struct in6_addr a; + std::memcpy(&a, _peer_addr.data(), 16); + if (inet_ntop(AF_INET6, &a, buf, sizeof(buf)) == nullptr) { + return "AutoInterfacePeer[invalid]"; + } + std::string out(buf); + for (auto& c : out) { + if (c >= 'A' && c <= 'F') c = static_cast(c - 'A' + 'a'); + } + return std::string("AutoInterfacePeer[") + out + "]"; + } + +} // namespace RNS diff --git a/src/Interfaces/AutoInterfacePeer.h b/src/Interfaces/AutoInterfacePeer.h new file mode 100644 index 0000000..d4805ca --- /dev/null +++ b/src/Interfaces/AutoInterfacePeer.h @@ -0,0 +1,42 @@ +#pragma once + +#include "../Interface.h" +#include "../Bytes.h" +#include "AutoInterface.h" + +#include + +namespace RNS { + + /* + * Per-peer Interface spawned by AutoInterface for each discovered node. + * Registered with Transport so per-path attached_interface routing works. + * Sends outbound traffic via the parent's shared _data_sock. + */ + class AutoInterfacePeer : public InterfaceImpl { + public: + AutoInterfacePeer(AutoInterface* parent, + const AutoInterface::IPv6Addr& addr, + uint32_t scope_id); + virtual ~AutoInterfacePeer(); + + virtual bool start() override; + virtual void stop() override; + virtual void loop() override; + virtual void send_outgoing(const Bytes& data) override; + + // Called by AutoInterface::route_inbound after dedup + void deliver_incoming(const Bytes& data); + + const AutoInterface::IPv6Addr& peer_addr() const { return _peer_addr; } + uint32_t peer_scope() const { return _peer_scope; } + + virtual std::string toString() const override; + + protected: + AutoInterface* _parent; + AutoInterface::IPv6Addr _peer_addr{}; + uint32_t _peer_scope = 0; + }; + +} // namespace RNS diff --git a/test/test_autoiface/test_main.cpp b/test/test_autoiface/test_main.cpp new file mode 100644 index 0000000..bc36b1b --- /dev/null +++ b/test/test_autoiface/test_main.cpp @@ -0,0 +1,458 @@ +// Unit tests for AutoInterface wire-format derivation. +// +// Fixture values were captured from Python Reticulum +// (RNS/Interfaces/AutoInterface.py) so any divergence here means we are no +// longer wire-compatible with desktop Reticulum nodes. +// +// Source of fixture values: +// group_hash: hashlib.sha256(b"reticulum").hexdigest() +// mcast addr: Python AutoInterface lines 202-212 with the captured group hash +// token: hashlib.sha256(group_id + link_local_addr.encode("utf-8")).hexdigest() + +#include +#include + +#include "Interfaces/AutoInterface.h" +#include "Bytes.h" +#include "Log.h" + +using RNS::AutoInterface; +using RNS::Bytes; + +// SHA256("reticulum") +static const char* kGroupHashReticulumHex = + "eac4d70bfb1c16e45e39485e31e1f5ccb18cedf878e0310d9a96100168f89f0d"; + +// Default group "reticulum", addr_type=temporary ('1'), scope=link ('2') +static const char* kMcastDefaultLink = + "ff12:0:d70b:fb1c:16e4:5e39:485e:31e1"; + +// Default group "reticulum", addr_type=permanent ('0'), scope=admin ('4') +static const char* kMcastDefaultAdminPerm = + "ff04:0:d70b:fb1c:16e4:5e39:485e:31e1"; + +// Custom group "testnet", addr_type=temporary ('1'), scope=link ('2') +// Note: trailing group is "315" — only 3 hex chars (RFC 5952: leading zeros +// suppressed). This is the format Python emits and that lwIP's inet_pton +// accepts; do not pad to 4 chars. +static const char* kMcastTestnetLink = + "ff12:0:ce9f:2416:5207:33ba:cb37:315"; + +// SHA256("reticulum" + "fe80::abcd:1234") +static const char* kTokenReticulumFe80AbcdHex = + "eb45d091e4798b743d44f9242e245e90cb193ed1c39ac40563e2956e3759a6ca"; + +// SHA256("reticulum" + "fe80::1") +static const char* kTokenReticulumFe80OneHex = + "97b25576749ea936b0d8a8536ffaf442d157cf47d460dcf13c48b7bd18b6c163"; + +// SHA256("testnet" + "fe80::abcd:1234") +static const char* kTokenTestnetFe80AbcdHex = + "33c8aed6ebf08a5e3470d76a43cb090602e14952861877f25d72640aedcad0bf"; + +void test_group_hash_default() { + Bytes h = AutoInterface::compute_group_hash(Bytes("reticulum")); + TEST_ASSERT_EQUAL_size_t(32, h.size()); + TEST_ASSERT_EQUAL_STRING(kGroupHashReticulumHex, h.toHex().c_str()); +} + +void test_multicast_address_default_group_link_temp() { + Bytes h = AutoInterface::compute_group_hash(Bytes("reticulum")); + std::string mcast = AutoInterface::compute_multicast_address( + h, + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK); + TEST_ASSERT_EQUAL_STRING(kMcastDefaultLink, mcast.c_str()); +} + +void test_multicast_address_default_group_admin_permanent() { + Bytes h = AutoInterface::compute_group_hash(Bytes("reticulum")); + std::string mcast = AutoInterface::compute_multicast_address( + h, + AutoInterface::MCAST_ADDR_TYPE_PERMANENT, + AutoInterface::SCOPE_ADMIN); + TEST_ASSERT_EQUAL_STRING(kMcastDefaultAdminPerm, mcast.c_str()); +} + +void test_multicast_address_custom_group() { + // Critical: tail group is "315" (3 hex chars). Python's "{:02x}" produces + // 3 chars when the value exceeds 0xff but is < 0x1000. Make sure C++ + // snprintf behaves the same way. + Bytes h = AutoInterface::compute_group_hash(Bytes("testnet")); + std::string mcast = AutoInterface::compute_multicast_address( + h, + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK); + TEST_ASSERT_EQUAL_STRING(kMcastTestnetLink, mcast.c_str()); +} + +void test_multicast_address_short_group_hash_returns_empty() { + Bytes too_short(reinterpret_cast("abcd"), 4); + std::string mcast = AutoInterface::compute_multicast_address( + too_short, + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK); + TEST_ASSERT_TRUE(mcast.empty()); +} + +void test_discovery_token_default_group() { + Bytes token = AutoInterface::compute_discovery_token( + Bytes("reticulum"), std::string("fe80::abcd:1234")); + TEST_ASSERT_EQUAL_size_t(32, token.size()); + TEST_ASSERT_EQUAL_STRING(kTokenReticulumFe80AbcdHex, token.toHex().c_str()); +} + +void test_discovery_token_compressed_address() { + // Validates that we accept the RFC 5952 short form "fe80::1" as-is. + Bytes token = AutoInterface::compute_discovery_token( + Bytes("reticulum"), std::string("fe80::1")); + TEST_ASSERT_EQUAL_STRING(kTokenReticulumFe80OneHex, token.toHex().c_str()); +} + +void test_set_link_local_canonicalizes_expanded_form() { + // Arduino-ESP32 IPv6Address::toString() returns the fully expanded form + // "fe80:0000:0000:0000:0022:5d59:22e5:0924". Peers RX a packet from us + // and compute SHA256(group_id || canonical_src_str), so our self-token + // must be hashed against the canonical RFC 5952 form, not the expanded + // form, or we will be silently rejected by every other implementation. + AutoInterface ai("test_iface", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + AutoInterface::DEFAULT_DISCOVERY_PORT, + AutoInterface::DEFAULT_DATA_PORT, 4); + ai.set_link_local("fe80:0000:0000:0000:0022:5d59:22e5:0924", 1); + TEST_ASSERT_EQUAL_STRING("fe80::22:5d59:22e5:924", + ai.link_local_address().c_str()); +} + +void test_set_link_local_lowercases_uppercase_input() { + // lwIP's ip6addr_ntoa_r emits UPPERCASE hex; Python / glibc / macOS + // produce lowercase. Wire compat requires us to normalize to lowercase + // (RFC 5952 canonical) before hashing, both on the self-token side and + // the RX validation side. + AutoInterface ai("test_iface", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + AutoInterface::DEFAULT_DISCOVERY_PORT, + AutoInterface::DEFAULT_DATA_PORT, 4); + ai.set_link_local("FE80::3EDC:75FF:FE40:8000", 1); + TEST_ASSERT_EQUAL_STRING("fe80::3edc:75ff:fe40:8000", + ai.link_local_address().c_str()); +} + +void test_discovery_token_custom_group() { + Bytes token = AutoInterface::compute_discovery_token( + Bytes("testnet"), std::string("fe80::abcd:1234")); + TEST_ASSERT_EQUAL_STRING(kTokenTestnetFe80AbcdHex, token.toHex().c_str()); + + // Sanity: different from default-group token for the same address. + Bytes other = AutoInterface::compute_discovery_token( + Bytes("reticulum"), std::string("fe80::abcd:1234")); + TEST_ASSERT_FALSE(token == other); +} + +// --- Peer-table semantics --- + +static AutoInterface::IPv6Addr make_addr(uint8_t last) { + // fe80:: — link-local with a unique tail byte + AutoInterface::IPv6Addr a{}; + a[0] = 0xfe; + a[1] = 0x80; + a[15] = last; + return a; +} + +void test_add_peer_registers_and_counts() { + AutoInterface ai("test_iface", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + AutoInterface::DEFAULT_DISCOVERY_PORT, + AutoInterface::DEFAULT_DATA_PORT, + /*max_peers=*/4); + + TEST_ASSERT_EQUAL_size_t(0, ai.peer_count()); + + auto a1 = make_addr(0x01); + ai.test_inject_peer(a1, /*scope=*/1, /*now_ms=*/1000); + + TEST_ASSERT_EQUAL_size_t(1, ai.peer_count()); + TEST_ASSERT_TRUE(ai.has_peer(a1)); + TEST_ASSERT_EQUAL_UINT64(1000, ai.peer_last_heard_ms(a1)); +} + +void test_add_peer_idempotent_refreshes_last_heard() { + AutoInterface ai("test_iface", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + AutoInterface::DEFAULT_DISCOVERY_PORT, + AutoInterface::DEFAULT_DATA_PORT, 4); + + auto a1 = make_addr(0x02); + ai.test_inject_peer(a1, 1, 5000); + TEST_ASSERT_EQUAL_size_t(1, ai.peer_count()); + TEST_ASSERT_EQUAL_UINT64(5000, ai.peer_last_heard_ms(a1)); + + // Second add for the same address: count stays 1, last_heard advances. + ai.test_inject_peer(a1, 1, 9999); + TEST_ASSERT_EQUAL_size_t(1, ai.peer_count()); + TEST_ASSERT_EQUAL_UINT64(9999, ai.peer_last_heard_ms(a1)); +} + +void test_add_peer_respects_max_peers_cap() { + AutoInterface ai("test_iface", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + AutoInterface::DEFAULT_DISCOVERY_PORT, + AutoInterface::DEFAULT_DATA_PORT, + /*max_peers=*/3); + + for (uint8_t i = 1; i <= 5; ++i) { + ai.test_inject_peer(make_addr(i), 1, 1000 + i); + } + + // Only first 3 should have been admitted. + TEST_ASSERT_EQUAL_size_t(3, ai.peer_count()); + TEST_ASSERT_TRUE(ai.has_peer(make_addr(1))); + TEST_ASSERT_TRUE(ai.has_peer(make_addr(2))); + TEST_ASSERT_TRUE(ai.has_peer(make_addr(3))); + TEST_ASSERT_FALSE(ai.has_peer(make_addr(4))); + TEST_ASSERT_FALSE(ai.has_peer(make_addr(5))); +} + +void test_peer_jobs_evicts_timed_out_peers() { + AutoInterface ai("test_iface", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + AutoInterface::DEFAULT_DISCOVERY_PORT, + AutoInterface::DEFAULT_DATA_PORT, 4); + + auto fresh = make_addr(0x10); // injected near "now" + auto stale = make_addr(0x11); // last_heard well in the past + ai.test_inject_peer(stale, 1, /*now_ms=*/0); + ai.test_inject_peer(fresh, 1, /*now_ms=*/30000); + TEST_ASSERT_EQUAL_size_t(2, ai.peer_count()); + + // Run jobs at t = 25s. PEERING_TIMEOUT_MS = 22000. + // stale: 25000 > 0 + 22000 → evict + // fresh: 25000 > 30000 + 22000 → false → keep + ai.test_run_peer_jobs(25000); + + TEST_ASSERT_EQUAL_size_t(1, ai.peer_count()); + TEST_ASSERT_FALSE(ai.has_peer(stale)); + TEST_ASSERT_TRUE(ai.has_peer(fresh)); +} + +void test_peer_jobs_keeps_recent_peers() { + AutoInterface ai("test_iface", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + AutoInterface::DEFAULT_DISCOVERY_PORT, + AutoInterface::DEFAULT_DATA_PORT, 4); + + auto a = make_addr(0x20); + ai.test_inject_peer(a, 1, 10000); + ai.test_run_peer_jobs(15000); // 15s < 22s timeout + TEST_ASSERT_EQUAL_size_t(1, ai.peer_count()); +} + +// --- Socket lifecycle (native impl). Uses ephemeral high ports to avoid +// colliding with any system AutoInterface listener on the host. + +static const uint16_t kTestDiscoPort = 49716; +static const uint16_t kTestDataPort = 49717; + +void test_start_without_link_local_fails() { + AutoInterface ai("test_lifecycle", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + kTestDiscoPort, kTestDataPort, 4); + + // No set_link_local() call — start() should refuse. + TEST_ASSERT_FALSE(ai.start()); + TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd()); + TEST_ASSERT_EQUAL_INT(-1, ai.unicast_socket_fd()); + TEST_ASSERT_EQUAL_INT(-1, ai.data_socket_fd()); +} + +void test_start_opens_three_sockets() { + AutoInterface ai("test_lifecycle", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + kTestDiscoPort, kTestDataPort, 4); + + // "fe80::1" + scope=1 (loopback / lo0 on most hosts). IPV6_JOIN_GROUP + // may warn on some hosts but start() tolerates that — see open_sockets() + // best-effort note. + ai.set_link_local("fe80::1", 1); + TEST_ASSERT_TRUE(ai.start()); + + TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.discovery_socket_fd()); + TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.unicast_socket_fd()); + TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.data_socket_fd()); + + // All three FDs must be distinct. + TEST_ASSERT_NOT_EQUAL(ai.discovery_socket_fd(), ai.unicast_socket_fd()); + TEST_ASSERT_NOT_EQUAL(ai.discovery_socket_fd(), ai.data_socket_fd()); + TEST_ASSERT_NOT_EQUAL(ai.unicast_socket_fd(), ai.data_socket_fd()); + + // Multicast address must be populated. + TEST_ASSERT_FALSE(ai.multicast_address().empty()); + + ai.stop(); +} + +void test_stop_closes_sockets_and_clears_peers() { + AutoInterface ai("test_lifecycle", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + kTestDiscoPort + 10, kTestDataPort + 10, 4); + ai.set_link_local("fe80::1", 1); + TEST_ASSERT_TRUE(ai.start()); + + ai.test_inject_peer(make_addr(0x42), 1, 1000); + TEST_ASSERT_EQUAL_size_t(1, ai.peer_count()); + + ai.stop(); + + TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd()); + TEST_ASSERT_EQUAL_INT(-1, ai.unicast_socket_fd()); + TEST_ASSERT_EQUAL_INT(-1, ai.data_socket_fd()); + TEST_ASSERT_EQUAL_size_t(0, ai.peer_count()); +} + +void test_start_stop_start_is_idempotent() { + AutoInterface ai("test_lifecycle", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + kTestDiscoPort + 20, kTestDataPort + 20, 4); + ai.set_link_local("fe80::1", 1); + + TEST_ASSERT_TRUE(ai.start()); + int fd1 = ai.discovery_socket_fd(); + TEST_ASSERT_GREATER_OR_EQUAL_INT(0, fd1); + ai.stop(); + TEST_ASSERT_EQUAL_INT(-1, ai.discovery_socket_fd()); + + // Restart on the same ports must succeed (REUSEADDR on disco_sock). + TEST_ASSERT_TRUE(ai.start()); + TEST_ASSERT_GREATER_OR_EQUAL_INT(0, ai.discovery_socket_fd()); + ai.stop(); +} + +void test_loop_at_does_not_crash_when_offline() { + AutoInterface ai("test_loop_offline", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + kTestDiscoPort + 30, kTestDataPort + 30, 4); + // No start() — loop_at on an offline interface must early-return. + ai.test_loop_at(0); + ai.test_loop_at(99999); + TEST_ASSERT_FALSE(ai.has_carrier()); +} + +void test_loop_at_drives_announce_and_peer_jobs_scheduling() { + AutoInterface ai("test_loop_sched", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + kTestDiscoPort + 40, kTestDataPort + 40, 4); + ai.set_link_local("fe80::1", 1); + TEST_ASSERT_TRUE(ai.start()); + + // Prime peer table — stale + fresh. Use t=0 / t=30000 so they end up on + // opposite sides of PEERING_TIMEOUT_MS=22000 at t=25000. + auto stale = make_addr(0x30); + auto fresh = make_addr(0x31); + ai.test_inject_peer(stale, 1, 0); + ai.test_inject_peer(fresh, 1, 30000); + TEST_ASSERT_EQUAL_size_t(2, ai.peer_count()); + + // First loop_at() at t=0 sends an announce (next_announce_ms starts at 0 + // after start()) and schedules peer_jobs for t=4000. Peer count should + // not change at t=0. + ai.test_loop_at(0); + TEST_ASSERT_EQUAL_size_t(2, ai.peer_count()); + + // Advance to t=25000 — past PEERING_TIMEOUT for stale peer. loop_at + // should fire peer_jobs (next_peer_job_ms=4000 < 25000) and evict. + ai.test_loop_at(25000); + TEST_ASSERT_EQUAL_size_t(1, ai.peer_count()); + TEST_ASSERT_TRUE(ai.has_peer(fresh)); + + ai.stop(); +} + +// Loopback round-trip: announce + multicast RX. Skips silently if +// IPV6_JOIN_GROUP isn't supported on the test host's loopback interface +// (some Linux configurations). This is the closest we can get to a real +// peering handshake without two physical machines. +void test_loopback_announce_receives_self_echo() { + AutoInterface ai("test_loopback", "reticulum", + AutoInterface::MCAST_ADDR_TYPE_TEMPORARY, + AutoInterface::SCOPE_LINK, + kTestDiscoPort + 50, kTestDataPort + 50, 4); + ai.set_link_local("fe80::1", 1); + if (!ai.start()) { + TEST_IGNORE_MESSAGE("start() failed on this host's loopback"); + return; + } + + // First announce sets _final_init_done = true and sends to mcast. + ai.test_loop_at(0); + + // Give the kernel a moment to loop the multicast packet back. + for (int i = 0; i < 20 && !ai.has_carrier(); ++i) { + ai.test_loop_at(static_cast(i + 1) * 10); + struct timespec ts { 0, 5'000'000 }; // 5 ms + nanosleep(&ts, nullptr); + } + + if (!ai.has_carrier()) { + // Multicast loopback may be filtered out on some hosts (e.g. macOS + // treats lo0's link-local strangely). Don't fail the suite — the + // real validation is the Phase 2 E2E test against Python. + TEST_IGNORE_MESSAGE("no multicast echo on this host's loopback"); + } else { + TEST_ASSERT_TRUE(ai.has_carrier()); + } + + ai.stop(); +} + +void setUp(void) {} +void tearDown(void) {} + +int runUnityTests(void) { + UNITY_BEGIN(); + RUN_TEST(test_group_hash_default); + RUN_TEST(test_multicast_address_default_group_link_temp); + RUN_TEST(test_multicast_address_default_group_admin_permanent); + RUN_TEST(test_multicast_address_custom_group); + RUN_TEST(test_multicast_address_short_group_hash_returns_empty); + RUN_TEST(test_discovery_token_default_group); + RUN_TEST(test_discovery_token_compressed_address); + RUN_TEST(test_set_link_local_canonicalizes_expanded_form); + RUN_TEST(test_set_link_local_lowercases_uppercase_input); + RUN_TEST(test_discovery_token_custom_group); + RUN_TEST(test_add_peer_registers_and_counts); + RUN_TEST(test_add_peer_idempotent_refreshes_last_heard); + RUN_TEST(test_add_peer_respects_max_peers_cap); + RUN_TEST(test_peer_jobs_evicts_timed_out_peers); + RUN_TEST(test_peer_jobs_keeps_recent_peers); + RUN_TEST(test_start_without_link_local_fails); + RUN_TEST(test_start_opens_three_sockets); + RUN_TEST(test_stop_closes_sockets_and_clears_peers); + RUN_TEST(test_start_stop_start_is_idempotent); + RUN_TEST(test_loop_at_does_not_crash_when_offline); + RUN_TEST(test_loop_at_drives_announce_and_peer_jobs_scheduling); + RUN_TEST(test_loopback_announce_receives_self_echo); + return UNITY_END(); +} + +int main(void) { return runUnityTests(); } + +#ifdef ARDUINO +void setup() { delay(2000); runUnityTests(); } +void loop() {} +#endif + +void app_main() { runUnityTests(); }