Initial commit

This commit is contained in:
Scott Powell 2025-01-13 14:07:48 +11:00
commit 6c7efdd0f6
59 changed files with 8604 additions and 0 deletions

View file

@ -0,0 +1,149 @@
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
#include <SPIFFS.h>
#define RADIOLIB_STATIC_ONLY 1
#include <RadioLib.h>
#include <helpers/RadioLibWrappers.h>
#include <helpers/ArduinoHelpers.h>
#include <helpers/StaticPoolPacketManager.h>
#include <helpers/SimpleSeenTable.h>
/* ------------------------------ Config -------------------------------- */
#ifdef HELTEC_LORA_V3
#include <helpers/HeltecV3Board.h>
static HeltecV3Board board;
#else
#error "need to provide a 'board' object"
#endif
/* ------------------------------ Code -------------------------------- */
class MyMesh : public mesh::Mesh {
SimpleSeenTable* _table;
uint32_t last_advert_timestamp = 0;
mesh::Identity server_id;
uint8_t server_secret[PUB_KEY_SIZE];
int server_path_len = -1;
uint8_t server_path[MAX_PATH_SIZE];
bool got_adv = false;
protected:
int searchPeersByHash(const uint8_t* hash) override {
if (got_adv && server_id.isHashMatch(hash)) {
return 1;
}
return 0; // not found
}
void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override {
if (memcmp(app_data, "PING", 4) == 0) {
Serial.println("Received advertisement from a PING server");
// check for replay attacks
if (timestamp > last_advert_timestamp) {
last_advert_timestamp = timestamp;
server_id = id;
self_id.calcSharedSecret(server_secret, id); // calc ECDH shared secret
got_adv = true;
}
}
}
void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, uint8_t* data, size_t len) override {
if (type == PAYLOAD_TYPE_RESPONSE) {
if (_table->hasSeenPacket(packet)) return;
Serial.println("Received PING Reply!");
if (packet->isRouteFlood()) {
// let server know path TO here, so they can use sendDirect() for future ping responses
mesh::Packet* path = createPathReturn(server_id, server_secret, packet->path, packet->path_len, 0, NULL, 0);
if (path) sendFlood(path);
}
}
}
void onPeerPathRecv(mesh::Packet* packet, int sender_idx, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
if (_table->hasSeenPacket(packet)) return;
// must be from server_id
Serial.printf("PATH to server, path_len=%d\n", (uint32_t) path_len);
memcpy(server_path, path, server_path_len = path_len); // store a copy of path, for sendDirect()
if (packet->isRouteFlood()) {
// send a reciprocal return path to sender, but send DIRECTLY!
mesh::Packet* rpath = createPathReturn(server_id, server_secret, packet->path, packet->path_len, 0, NULL, 0);
if (rpath) sendDirect(rpath, path, path_len);
}
if (extra_type == PAYLOAD_TYPE_RESPONSE) {
Serial.println("Received PING Reply!");
}
}
public:
MyMesh(mesh::Radio& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleSeenTable& table)
: mesh::Mesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16)), _table(&table)
{
}
void sendPingPacket() {
if (!got_adv) return; // have not received Advert yet
uint32_t now = getRTCClock()->getCurrentTime(); // important, need timestamp in packet, so that packet_hash will be unique
mesh::Packet* ping = createDatagram(PAYLOAD_TYPE_ANON_REQ, server_id, server_secret, (uint8_t *) &now, sizeof(now));
if (ping) {
if (server_path_len < 0) {
sendFlood(ping);
} else {
sendDirect(ping, server_path, server_path_len);
}
}
}
};
SPIClass spi;
StdRNG fast_rng;
SimpleSeenTable table;
SX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
MyMesh the_mesh(*new RadioLibWrapper(radio, board), fast_rng, *new VolatileRTCClock(), table);
unsigned long nextPing;
void halt() {
while (1) ;
}
void setup() {
Serial.begin(115200);
board.begin();
spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
if (status != RADIOLIB_ERR_NONE) {
Serial.print("ERROR: radio init failed: ");
Serial.println(status);
halt();
}
fast_rng.begin(radio.random(0x7FFFFFFF));
the_mesh.begin();
RadioNoiseListener true_rng(radio);
the_mesh.self_id = mesh::LocalIdentity(&true_rng); // create new random identity
nextPing = 0;
}
void loop() {
if (the_mesh.millisHasNowPassed(nextPing)) {
the_mesh.sendPingPacket();
nextPing = the_mesh.futureMillis(10000); // attempt ping every 10 seconds
}
the_mesh.loop();
}

View file

@ -0,0 +1,174 @@
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
#include <SPIFFS.h>
#define RADIOLIB_STATIC_ONLY 1
#include <RadioLib.h>
#include <helpers/RadioLibWrappers.h>
#include <helpers/ArduinoHelpers.h>
#include <helpers/StaticPoolPacketManager.h>
/* ------------------------------ Config -------------------------------- */
#ifdef HELTEC_LORA_V3
#include <helpers/HeltecV3Board.h>
static HeltecV3Board board;
#else
#error "need to provide a 'board' object"
#endif
/* ------------------------------ Code -------------------------------- */
struct ClientInfo {
mesh::Identity id;
uint32_t last_timestamp;
uint8_t secret[PUB_KEY_SIZE];
int out_path_len;
uint8_t out_path[MAX_PATH_SIZE];
};
#define MAX_CLIENTS 4
class MyMesh : public mesh::Mesh {
int num_clients;
ClientInfo known_clients[MAX_CLIENTS];
ClientInfo* putClient(const mesh::Identity& id) {
for (int i = 0; i < num_clients; i++) {
if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
}
if (num_clients < MAX_CLIENTS) {
auto newClient = &known_clients[num_clients++];
newClient->id = id;
newClient->out_path_len = -1; // initially out_path is unknown
newClient->last_timestamp = 0;
self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
return newClient;
}
return NULL; // table is full
}
protected:
void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
if (type == PAYLOAD_TYPE_ANON_REQ) { // received a PING!
uint32_t timestamp;
memcpy(&timestamp, data, 4);
auto client = putClient(sender); // add to known clients (if not already known)
if (client == NULL || timestamp <= client->last_timestamp) {
return; // FATAL: client table is full -OR- replay attack -OR- have seen this packet before
}
client->last_timestamp = timestamp;
uint32_t now = getRTCClock()->getCurrentTime(); // response packets always prefixed with timestamp
if (packet->isRouteFlood()) {
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the Ping response
mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
PAYLOAD_TYPE_RESPONSE, (uint8_t *) &now, sizeof(now));
if (path) sendFlood(path);
} else {
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, (uint8_t *) &now, sizeof(now));
if (reply) {
if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
sendDirect(reply, client->out_path, client->out_path_len);
} else {
sendFlood(reply);
}
}
}
}
}
int matching_peer_indexes[MAX_CLIENTS];
int searchPeersByHash(const uint8_t* hash) override {
int n = 0;
for (int i = 0; i < num_clients; i++) {
if (known_clients[i].id.isHashMatch(hash)) {
matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
}
}
return n;
}
// not needed for this example, but for sake of 'completeness' of Mesh impl
void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
if (peer_idx >= 0 && peer_idx < MAX_CLIENTS) {
// lookup pre-calculated shared_secret
int i = matching_peer_indexes[peer_idx];
memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
} else {
MESH_DEBUG_PRINTLN("Invalid peer_idx: %d", peer_idx);
}
}
void onPeerPathRecv(mesh::Packet* packet, int sender_idx, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
if (sender_idx >= 0 && sender_idx < MAX_CLIENTS) {
Serial.printf("PATH to client, path_len=%d\n", (uint32_t) path_len);
// TODO: prevent replay attacks
int i = matching_peer_indexes[sender_idx];
if (i >= 0 && i < num_clients) {
auto client = &known_clients[i]; // get from our known_clients table (sender SHOULD already be known in this context)
memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
}
} else {
MESH_DEBUG_PRINTLN("Invalid sender_idx: %d", sender_idx);
}
// NOTE: no reciprocal path send!!
}
public:
MyMesh(mesh::Radio& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc)
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(16))
{
num_clients = 0;
}
};
SPIClass spi;
StdRNG fast_rng;
SX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
MyMesh the_mesh(*new RadioLibWrapper(radio, board), *new ArduinoMillis(), fast_rng, *new VolatileRTCClock());
unsigned long nextAnnounce;
void halt() {
while (1) ;
}
void setup() {
Serial.begin(115200);
board.begin();
spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
if (status != RADIOLIB_ERR_NONE) {
Serial.print("ERROR: radio init failed: ");
Serial.println(status);
halt();
}
fast_rng.begin(radio.random(0x7FFFFFFF));
the_mesh.begin();
RadioNoiseListener true_rng(radio);
the_mesh.self_id = mesh::LocalIdentity(&true_rng); // create new random identity
nextAnnounce = 0;
}
void loop() {
if (the_mesh.millisHasNowPassed(nextAnnounce)) {
mesh::Packet* pkt = the_mesh.createAdvert(the_mesh.self_id, (const uint8_t *)"PING", 4);
if (pkt) the_mesh.sendFlood(pkt);
nextAnnounce = the_mesh.futureMillis(30000); // announce every 30 seconds (test only, don't do in production!)
}
the_mesh.loop();
// TODO: periodically check for OLD entries in known_clients[], and evict
}

View file

@ -0,0 +1,338 @@
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
#include <SPIFFS.h>
#define RADIOLIB_STATIC_ONLY 1
#include <RadioLib.h>
#include <helpers/CustomSX1262Wrapper.h>
#include <helpers/ArduinoHelpers.h>
#include <helpers/StaticPoolPacketManager.h>
#include <helpers/SimpleMeshTables.h>
#include <helpers/IdentityStore.h>
/* ------------------------------ Config -------------------------------- */
#define ANNOUNCE_DATA "repeater:v1"
#define ADMIN_PASSWORD "h^(kl@#)"
#if defined(HELTEC_LORA_V3)
#include <helpers/HeltecV3Board.h>
static HeltecV3Board board;
#else
#error "need to provide a 'board' object"
#endif
/* ------------------------------ Code -------------------------------- */
#define CMD_GET_STATS 0x01
#define CMD_SET_CLOCK 0x02
#define CMD_SEND_ANNOUNCE 0x03
#define CMD_SET_CONFIG 0x04
struct RepeaterStats {
uint16_t batt_milli_volts;
uint16_t curr_tx_queue_len;
uint16_t curr_free_queue_len;
int16_t last_rssi;
uint32_t n_packets_recv;
uint32_t n_packets_sent;
uint32_t total_air_time_secs;
uint32_t total_up_time_secs;
};
struct ClientInfo {
mesh::Identity id;
uint32_t last_timestamp;
uint8_t secret[PUB_KEY_SIZE];
int out_path_len;
uint8_t out_path[MAX_PATH_SIZE];
};
#define MAX_CLIENTS 4
class MyMesh : public mesh::Mesh {
RadioLibWrapper* my_radio;
mesh::MeshTables* _tables;
float airtime_factor;
uint8_t reply_data[MAX_PACKET_PAYLOAD];
int num_clients;
ClientInfo known_clients[MAX_CLIENTS];
ClientInfo* putClient(const mesh::Identity& id) {
for (int i = 0; i < num_clients; i++) {
if (id.matches(known_clients[i].id)) return &known_clients[i]; // already known
}
if (num_clients < MAX_CLIENTS) {
auto newClient = &known_clients[num_clients++];
newClient->id = id;
newClient->out_path_len = -1; // initially out_path is unknown
newClient->last_timestamp = 0;
self_id.calcSharedSecret(newClient->secret, id); // calc ECDH shared secret
return newClient;
}
return NULL; // table is full
}
int handleRequest(ClientInfo* sender, uint8_t* payload, size_t payload_len) {
uint32_t now = getRTCClock()->getCurrentTime();
memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
switch (payload[0]) {
case CMD_GET_STATS: {
uint32_t max_age_secs;
if (payload_len >= 5) {
memcpy(&max_age_secs, &payload[1], 4); // first param in request pkt
} else {
max_age_secs = 12*60*60; // default, 12 hours
}
RepeaterStats stats;
stats.batt_milli_volts = board.getBattMilliVolts();
stats.curr_tx_queue_len = _mgr->getOutboundCount();
stats.curr_free_queue_len = _mgr->getFreeCount();
stats.last_rssi = (int16_t) my_radio->getLastRSSI();
stats.n_packets_recv = my_radio->getPacketsRecv();
stats.n_packets_sent = my_radio->getPacketsSent();
stats.total_air_time_secs = getTotalAirTime() / 1000;
stats.total_up_time_secs = _ms->getMillis() / 1000;
memcpy(&reply_data[4], &stats, sizeof(stats));
return 4 + sizeof(stats); // reply_len
}
case CMD_SET_CLOCK: {
if (payload_len >= 5) {
uint32_t curr_epoch_secs;
memcpy(&curr_epoch_secs, &payload[1], 4); // first param is current UNIX time
if (curr_epoch_secs > now) { // time can only go forward!!
getRTCClock()->setCurrentTime(curr_epoch_secs);
memcpy(&reply_data[4], "OK", 2);
} else {
memcpy(&reply_data[4], "ER", 2);
}
return 4 + 2; // reply_len
}
return 0; // invalid request
}
case CMD_SEND_ANNOUNCE: {
// broadcast another self Advertisement
auto adv = createAdvert(self_id, (const uint8_t *)ANNOUNCE_DATA, strlen(ANNOUNCE_DATA));
if (adv) sendFlood(adv, 1500); // send after slight delay
memcpy(&reply_data[4], "OK", 2);
return 4 + 2; // reply_len
}
case CMD_SET_CONFIG: {
if (payload_len >= 4 && payload_len < 32 && memcmp(&payload[1], "AF", 2) == 0) {
payload[payload_len] = 0; // make it a C string
airtime_factor = atof((char *) &payload[3]);
memcpy(&reply_data[4], "OK", 2);
return 4 + 2; // reply_len
}
return 0; // unknown config var
}
}
// unknown command
return 0; // reply_len
}
protected:
float getAirtimeBudgetFactor() const override {
return airtime_factor;
}
bool allowPacketForward(mesh::Packet* packet) override {
uint8_t hash[MAX_HASH_SIZE];
packet->calculatePacketHash(hash);
if (_tables->hasForwarded(hash)) return false; // has already been forwarded
_tables->setHasForwarded(hash); // mark packet as forwarded
return true; // Yes, allow packet to be forwarded
}
void onAnonDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Identity& sender, uint8_t* data, size_t len) override {
if (type == PAYLOAD_TYPE_ANON_REQ) { // received an initial request by a possible admin client (unknown at this stage)
uint32_t timestamp;
memcpy(&timestamp, data, 4);
if (memcmp(&data[4], ADMIN_PASSWORD, 8) == 0) { // check for valid password
auto client = putClient(sender); // add to known clients (if not already known)
if (client == NULL || timestamp <= client->last_timestamp) {
return; // FATAL: client table is full -OR- replay attack -OR- have seen this packet before
}
client->last_timestamp = timestamp;
uint32_t now = getRTCClock()->getCurrentTime();
memcpy(reply_data, &now, 4); // response packets always prefixed with timestamp
memcpy(&reply_data[4], "OK", 2);
if (packet->isRouteFlood()) {
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
mesh::Packet* path = createPathReturn(sender, client->secret, packet->path, packet->path_len,
PAYLOAD_TYPE_RESPONSE, reply_data, 4 + 2);
if (path) sendFlood(path);
} else {
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, sender, client->secret, reply_data, 4 + 2);
if (reply) {
if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
sendDirect(reply, client->out_path, client->out_path_len);
} else {
sendFlood(reply);
}
}
}
}
}
}
int matching_peer_indexes[MAX_CLIENTS];
int searchPeersByHash(const uint8_t* hash) override {
int n = 0;
for (int i = 0; i < num_clients; i++) {
if (known_clients[i].id.isHashMatch(hash)) {
matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
}
}
return n;
}
void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
int i = matching_peer_indexes[peer_idx];
if (i >= 0 && i < num_clients) {
// lookup pre-calculated shared_secret
memcpy(dest_secret, known_clients[i].secret, PUB_KEY_SIZE);
} else {
MESH_DEBUG_PRINTLN("getPeerSharedSecret: Invalid peer idx: %d", i);
}
}
void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, uint8_t* data, size_t len) override {
if (type == PAYLOAD_TYPE_REQ) { // request (from a Known admin client!)
int i = matching_peer_indexes[sender_idx];
if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
auto client = &known_clients[i];
uint32_t timestamp;
memcpy(&timestamp, data, 4);
if (timestamp > client->last_timestamp) { // prevent replay attacks AND receiving via multiple paths
int reply_len = handleRequest(client, &data[4], len - 4);
if (reply_len == 0) return; // invalid command
client->last_timestamp = timestamp;
if (packet->isRouteFlood()) {
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the response
mesh::Packet* path = createPathReturn(client->id, client->secret, packet->path, packet->path_len,
PAYLOAD_TYPE_RESPONSE, reply_data, reply_len);
if (path) sendFlood(path);
} else {
mesh::Packet* reply = createDatagram(PAYLOAD_TYPE_RESPONSE, client->id, client->secret, reply_data, reply_len);
if (reply) {
if (client->out_path_len >= 0) { // we have an out_path, so send DIRECT
sendDirect(reply, client->out_path, client->out_path_len);
} else {
sendFlood(reply);
}
}
}
}
} else {
MESH_DEBUG_PRINTLN("onPeerDataRecv: invalid peer idx: %d", i);
}
}
}
void onPeerPathRecv(mesh::Packet* packet, int sender_idx, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
// TODO: prevent replay attacks
int i = matching_peer_indexes[sender_idx];
if (i >= 0 && i < num_clients) { // get from our known_clients table (sender SHOULD already be known in this context)
Serial.printf("PATH to client, path_len=%d\n", (uint32_t) path_len);
auto client = &known_clients[i];
memcpy(client->out_path, path, client->out_path_len = path_len); // store a copy of path, for sendDirect()
} else {
MESH_DEBUG_PRINTLN("onPeerPathRecv: invalid peer idx: %d", i);
}
// NOTE: no reciprocal path send!!
}
public:
MyMesh(RadioLibWrapper& radio, mesh::MillisecondClock& ms, mesh::RNG& rng, mesh::RTCClock& rtc, mesh::MeshTables& tables)
: mesh::Mesh(radio, ms, rng, rtc, *new StaticPoolPacketManager(32)), _tables(&tables)
{
my_radio = &radio;
airtime_factor = 5.0; // 1/6th
num_clients = 0;
}
void sendSelfAdvertisement() {
mesh::Packet* pkt = createAdvert(self_id, (const uint8_t *)ANNOUNCE_DATA, strlen(ANNOUNCE_DATA));
if (pkt) {
sendFlood(pkt);
} else {
MESH_DEBUG_PRINTLN("ERROR: unable to create advertisement packet!");
}
}
};
#if defined(P_LORA_SCLK)
SPIClass spi;
CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
#else
CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
#endif
StdRNG fast_rng;
SimpleMeshTables tables;
MyMesh the_mesh(*new CustomSX1262Wrapper(radio, board), *new ArduinoMillis(), fast_rng, *new VolatileRTCClock(), tables);
void halt() {
while (1) ;
}
void setup() {
Serial.begin(115200);
delay(5000);
board.begin();
#if defined(P_LORA_SCLK)
spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
#else
int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
#endif
if (status != RADIOLIB_ERR_NONE) {
Serial.print("ERROR: radio init failed: ");
Serial.println(status);
halt();
}
SPIFFS.begin(true);
IdentityStore store(SPIFFS, "/identity");
if (!store.load("_main", the_mesh.self_id)) {
the_mesh.self_id = mesh::LocalIdentity(the_mesh.getRNG()); // create new random identity
store.save("_main", the_mesh.self_id);
}
Serial.print("Repeater ID: ");
mesh::Utils::printHex(Serial, the_mesh.self_id.pub_key, PUB_KEY_SIZE); Serial.println();
the_mesh.begin();
// send out initial Advertisement to the mesh
the_mesh.sendSelfAdvertisement();
}
void loop() {
the_mesh.loop();
// TODO: periodically check for OLD/inactive entries in known_clients[], and evict
}

View file

@ -0,0 +1,334 @@
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
#include <SPIFFS.h>
#define RADIOLIB_STATIC_ONLY 1
#include <RadioLib.h>
#include <helpers/RadioLibWrappers.h>
#include <helpers/ArduinoHelpers.h>
#include <helpers/StaticPoolPacketManager.h>
#include <helpers/SimpleSeenTable.h>
/* ---------------------------------- CONFIGURATION ------------------------------------- */
//#define RUN_AS_ALICE true
#if RUN_AS_ALICE
const char* alice_private = "B8830658388B2DDF22C3A508F4386975970CDE1E2A2A495C8F3B5727957A97629255A1392F8BA4C26A023A0DAB78BFC64D261C8E51507496DD39AFE3707E7B42";
#else
const char *bob_private = "30BAA23CCB825D8020A59C936D0AB7773B07356020360FC77192813640BAD375E43BBF9A9A7537E4B9614610F1F2EF874AAB390BA9B0C2F01006B01FDDFEFF0C";
#endif
const char *alice_public = "106A5136EC0DD797650AD204C065CF9B66095F6ED772B0822187785D65E11B1F";
const char *bob_public = "020BCEDAC07D709BD8507EC316EB5A7FF2F0939AF5057353DCE7E4436A1B9681";
#ifdef HELTEC_LORA_V3
#include <helpers/HeltecV3Board.h>
static HeltecV3Board board;
#else
#error "need to provide a 'board' object"
#endif
#define FLOOD_SEND_TIMEOUT_MILLIS 4000
#define DIRECT_SEND_TIMEOUT_MILLIS 2000
/* -------------------------------------------------------------------------------------- */
static unsigned long txt_send_timeout;
#define MAX_CONTACTS 1
#define MAX_SEARCH_RESULTS 1
#define MAX_TEXT_LEN (10*CIPHER_BLOCK_SIZE) // must be LESS than (MAX_PACKET_PAYLOAD - 4 - CIPHER_MAC_SIZE - 1)
struct ContactInfo {
mesh::Identity id;
const char* name;
int out_path_len;
uint8_t out_path[MAX_PATH_SIZE];
uint32_t last_advert_timestamp;
uint8_t shared_secret[PUB_KEY_SIZE];
};
class MyMesh : public mesh::Mesh {
public:
SimpleSeenTable* _table;
mesh::LocalIdentity self_id;
ContactInfo contacts[MAX_CONTACTS];
int num_contacts;
void addContact(const char* name, const mesh::Identity& id) {
if (num_contacts < MAX_CONTACTS) {
contacts[num_contacts].id = id;
contacts[num_contacts].name = name;
contacts[num_contacts].last_advert_timestamp = 0;
contacts[num_contacts].out_path_len = -1;
// only need to calculate the shared_secret once, for better performance
self_id.calcSharedSecret(contacts[num_contacts].shared_secret, id);
num_contacts++;
}
}
protected:
int matching_peer_indexes[MAX_SEARCH_RESULTS];
int searchPeersByHash(const uint8_t* hash) override {
int n = 0;
for (int i = 0; i < num_contacts && n < MAX_SEARCH_RESULTS; i++) {
if (contacts[i].id.isHashMatch(hash)) {
matching_peer_indexes[n++] = i; // store the INDEXES of matching contacts (for subsequent 'peer' methods)
}
}
return n;
}
void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override {
Serial.print("Valid Advertisement -> ");
mesh::Utils::printHex(Serial, id.pub_key, PUB_KEY_SIZE);
Serial.println();
for (int i = 0; i < num_contacts; i++) {
ContactInfo& from = contacts[i];
// check for replay attacks
if (id.matches(from.id) && timestamp > from.last_advert_timestamp) { // is from one of our contacts
from.last_advert_timestamp = timestamp;
Serial.printf(" From contact: %s\n", from.name);
}
}
}
void getPeerSharedSecret(uint8_t* dest_secret, int peer_idx) override {
int i = matching_peer_indexes[peer_idx];
if (i >= 0 && i < num_contacts) {
// lookup pre-calculated shared_secret
memcpy(dest_secret, contacts[i].shared_secret, PUB_KEY_SIZE);
} else {
MESH_DEBUG_PRINTLN("getPeerSHharedSecret: Invalid peer idx: %d", i);
}
}
void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, uint8_t* data, size_t len) override {
if (type == PAYLOAD_TYPE_TXT_MSG) {
if (_table->hasSeenPacket(packet)) return;
int i = matching_peer_indexes[sender_idx];
if (i < 0 && i >= num_contacts) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: Invalid sender idx: %d", i);
return;
}
ContactInfo& from = contacts[i];
uint32_t timestamp;
memcpy(&timestamp, data, 4); // timestamp (by sender's RTC clock - which could be wrong)
// len can be > original length, but 'text' will be padded with zeroes
data[len] = 0; // need to make a C string again, with null terminator
Serial.print("MSG -> from ");
Serial.print(from.name);
Serial.print(": ");
Serial.println((const char *) &data[4]);
uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to sender that we got it
mesh::Utils::sha256((uint8_t *) &ack_hash, 4, data, len, from.id.pub_key, PUB_KEY_SIZE);
if (packet->isRouteFlood()) {
// let this sender know path TO here, so they can use sendDirect(), and ALSO encode the ACK
mesh::Packet* path = createPathReturn(from.id, from.shared_secret, packet->path, packet->path_len,
PAYLOAD_TYPE_ACK, (uint8_t *) &ack_hash, 4);
if (path) sendFlood(path);
} else {
mesh::Packet* ack = createAck(ack_hash);
if (ack) {
if (from.out_path_len < 0) {
sendFlood(ack);
} else {
sendDirect(ack, from.out_path, from.out_path_len);
}
}
}
}
}
void onPeerPathRecv(mesh::Packet* packet, int sender_idx, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
if (_table->hasSeenPacket(packet)) return;
int i = matching_peer_indexes[sender_idx];
if (i < 0 && i >= num_contacts) {
MESH_DEBUG_PRINTLN("onPeerPathRecv: Invalid sender idx: %d", i);
return;
}
ContactInfo& from = contacts[i];
Serial.printf("PATH to: %s, path_len=%d\n", from.name, (uint32_t) path_len);
memcpy(from.out_path, path, from.out_path_len = path_len); // store a copy of path, for sendDirect()
if (packet->isRouteFlood()) {
// send a reciprocal return path to sender, but send DIRECTLY!
mesh::Packet* rpath = createPathReturn(from.id, from.shared_secret, packet->path, packet->path_len, 0, NULL, 0);
if (rpath) sendDirect(rpath, path, path_len);
}
if (extra_type == PAYLOAD_TYPE_ACK && extra_len >= 4) {
// also got an encoded ACK!
processAck(extra);
}
}
void onAckRecv(mesh::Packet* packet, uint32_t ack_crc) override {
processAck((uint8_t *)&ack_crc);
}
void processAck(const uint8_t *data) {
if (memcmp(data, &expected_ack_crc, 4) == 0) { // got an ACK from recipient
Serial.println("Got ACK!");
// NOTE: the same ACK can be received multiple times!
expected_ack_crc = 0; // reset our expected hash, now that we have received ACK
txt_send_timeout = 0;
}
}
public:
uint32_t expected_ack_crc;
MyMesh(mesh::Radio& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleSeenTable& table)
: mesh::Mesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16)), _table(&table)
{
num_contacts = 0;
}
mesh::Packet* composeMsgPacket(ContactInfo& recipient, const char *text) {
int text_len = strlen(text);
if (text_len > MAX_TEXT_LEN) return NULL;
uint8_t temp[4+MAX_TEXT_LEN+1];
uint32_t timestamp = getRTCClock()->getCurrentTime();
memcpy(temp, &timestamp, 4); // mostly an extra blob to help make packet_hash unique
memcpy(&temp[4], text, text_len);
// calc expected ACK reply
mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, (const uint8_t *) temp, 4 + text_len, self_id.pub_key, PUB_KEY_SIZE);
return createDatagram(PAYLOAD_TYPE_TXT_MSG, recipient.id, recipient.shared_secret, temp, 4 + text_len);
}
void sendSelfAnnounce() {
mesh::Packet* announce = createAdvert(self_id);
if (announce) {
sendFlood(announce);
Serial.println(" (advert sent).");
} else {
Serial.println(" ERROR: unable to create packet.");
}
}
};
SPIClass spi;
StdRNG fast_rng;
SimpleSeenTable table;
SX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
MyMesh the_mesh(*new RadioLibWrapper(radio, board), fast_rng, *new VolatileRTCClock(), table);
void halt() {
while (1) ;
}
static char command[MAX_TEXT_LEN+1];
void setup() {
Serial.begin(115200);
board.begin();
spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
if (status != RADIOLIB_ERR_NONE) {
Serial.print("ERROR: radio init failed: ");
Serial.println(status);
halt();
}
fast_rng.begin(radio.random(0x7FFFFFFF));
#if RUN_AS_ALICE
Serial.println(" --- user: Alice ---");
the_mesh.self_id = mesh::LocalIdentity(alice_private, alice_public);
the_mesh.addContact("Bob", mesh::Identity(bob_public));
#else
Serial.println(" --- user: Bob ---");
the_mesh.self_id = mesh::LocalIdentity(bob_private, bob_public);
the_mesh.addContact("Alice", mesh::Identity(alice_public));
#endif
Serial.println("Help:");
Serial.println(" enter 'ann' to announce presence to mesh");
Serial.println(" enter 'send {message text}' to send a message");
the_mesh.begin();
command[0] = 0;
txt_send_timeout = 0;
// send out initial Announce to the mesh
the_mesh.sendSelfAnnounce();
}
void loop() {
int len = strlen(command);
while (Serial.available() && len < sizeof(command)-1) {
char c = Serial.read();
if (c != '\n') {
command[len++] = c;
command[len] = 0;
}
Serial.print(c);
}
if (len == sizeof(command)-1) { // command buffer full
command[sizeof(command)-1] = '\r';
}
if (len > 0 && command[len - 1] == '\r') { // received complete line
command[len - 1] = 0; // replace newline with C string null terminator
if (memcmp(command, "send ", 5) == 0) {
// TODO: some way to select recipient??
ContactInfo& recipient = the_mesh.contacts[0]; // just send to first contact for now
const char *text = &command[5];
mesh::Packet* pkt = the_mesh.composeMsgPacket(recipient, text);
if (pkt) {
if (recipient.out_path_len < 0) {
the_mesh.sendFlood(pkt);
txt_send_timeout = the_mesh.futureMillis(FLOOD_SEND_TIMEOUT_MILLIS);
} else {
the_mesh.sendDirect(pkt, recipient.out_path, recipient.out_path_len);
txt_send_timeout = the_mesh.futureMillis(DIRECT_SEND_TIMEOUT_MILLIS);
}
Serial.println(" (message sent)");
} else {
Serial.println(" ERROR: unable to create packet.");
}
} else if (strcmp(command, "ann") == 0) {
the_mesh.sendSelfAnnounce();
} else if (strcmp(command, "key") == 0) {
mesh::LocalIdentity new_id(the_mesh.getRNG());
new_id.printTo(Serial);
} else {
Serial.print(" ERROR: unknown command: "); Serial.println(command);
}
command[0] = 0; // reset command buffer
}
if (txt_send_timeout && the_mesh.millisHasNowPassed(txt_send_timeout)) {
// failed to get an ACK
ContactInfo& recipient = the_mesh.contacts[0]; // just the one contact for now
Serial.println(" ERROR: timed out, no ACK.");
// path to our contact is now possibly broken, fallback to Flood mode
recipient.out_path_len = -1;
txt_send_timeout = 0;
}
the_mesh.loop();
}

View file

@ -0,0 +1,304 @@
#include <Arduino.h> // needed for PlatformIO
#include <Mesh.h>
#include <SPIFFS.h>
#define RADIOLIB_STATIC_ONLY 1
#include <RadioLib.h>
#include <helpers/CustomSX1262Wrapper.h>
#include <helpers/ArduinoHelpers.h>
#include <helpers/SimpleSeenTable.h>
#include <helpers/StaticPoolPacketManager.h>
/* ---------------------------------- CONFIGURATION ------------------------------------- */
#define ADMIN_PASSWORD "h^(kl@#)"
#ifdef HELTEC_LORA_V3
#include <helpers/HeltecV3Board.h>
static HeltecV3Board board;
#else
#error "need to provide a 'board' object"
#endif
/* -------------------------------------------------------------------------------------- */
#define MAX_TEXT_LEN (10*CIPHER_BLOCK_SIZE) // must be LESS than (MAX_PACKET_PAYLOAD - FROM_HASH_LEN - CIPHER_MAC_SIZE - 1)
#define CMD_GET_STATS 0x01
#define CMD_SET_CLOCK 0x02
#define CMD_SEND_ANNOUNCE 0x03
#define CMD_SET_CONFIG 0x04
struct RepeaterStats {
uint16_t batt_milli_volts;
uint16_t curr_tx_queue_len;
uint16_t curr_free_queue_len;
int16_t last_rssi;
uint32_t n_packets_recv;
uint32_t n_packets_sent;
uint32_t total_air_time_secs;
uint32_t total_up_time_secs;
};
class MyMesh : public mesh::Mesh {
SimpleSeenTable* _table;
uint32_t last_advert_timestamp = 0;
mesh::Identity server_id;
uint8_t server_secret[PUB_KEY_SIZE];
int server_path_len = -1;
uint8_t server_path[MAX_PATH_SIZE];
bool got_adv = false;
protected:
int searchPeersByHash(const uint8_t* hash) override {
if (got_adv && server_id.isHashMatch(hash)) {
return 1;
}
return 0; // not found
}
void onAdvertRecv(mesh::Packet* packet, const mesh::Identity& id, uint32_t timestamp, const uint8_t* app_data, size_t app_data_len) override {
if (memcmp(app_data, "repeater:", 9) == 0) {
Serial.println("Received advertisement from a repeater!");
// check for replay attacks
if (timestamp > last_advert_timestamp) {
last_advert_timestamp = timestamp;
server_id = id;
self_id.calcSharedSecret(server_secret, id); // calc ECDH shared secret
got_adv = true;
// 'login' to repeater. (mainly lets it know our public key)
uint32_t now = getRTCClock()->getCurrentTime(); // important, need timestamp in packet, so that packet_hash will be unique
uint8_t temp[4 + 8];
memcpy(temp, &now, 4);
memcpy(&temp[4], ADMIN_PASSWORD, 8);
mesh::Packet* login = createDatagram(PAYLOAD_TYPE_ANON_REQ, server_id, server_secret, temp, sizeof(temp));
if (login) sendFlood(login); // server_path won't be known yet
}
}
}
void handleResponse(const uint8_t* reply, size_t reply_len) {
if (reply_len >= 4 + sizeof(RepeaterStats)) { // got an GET_STATS reply from repeater
RepeaterStats stats;
memcpy(&stats, &reply[4], sizeof(stats));
Serial.println("Repeater Stats:");
Serial.printf(" battery: %d mV\n", (uint32_t) stats.batt_milli_volts);
Serial.printf(" tx queue: %d\n", (uint32_t) stats.curr_tx_queue_len);
Serial.printf(" free queue: %d\n", (uint32_t) stats.curr_free_queue_len);
Serial.printf(" last RSSI: %d\n", (int) stats.last_rssi);
Serial.printf(" num recv: %d\n", stats.n_packets_recv);
Serial.printf(" num sent: %d\n", stats.n_packets_sent);
Serial.printf(" air time (secs): %d\n", stats.total_air_time_secs);
Serial.printf(" up time (secs): %d\n", stats.total_up_time_secs);
} else if (reply_len > 4) { // got an SET_* reply from repeater
char tmp[MAX_PACKET_PAYLOAD];
memcpy(tmp, &reply[4], reply_len - 4);
tmp[reply_len - 4] = 0; // make a C string of reply
Serial.print("Reply: "); Serial.println(tmp);
}
}
void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, uint8_t* data, size_t len) override {
if (type == PAYLOAD_TYPE_RESPONSE) {
if (_table->hasSeenPacket(packet)) return;
handleResponse(data, len);
if (packet->isRouteFlood()) {
// let server know path TO here, so they can use sendDirect() for future ping responses
mesh::Packet* path = createPathReturn(server_id, server_secret, packet->path, packet->path_len, 0, NULL, 0);
if (path) sendFlood(path);
}
}
}
void onPeerPathRecv(mesh::Packet* packet, int sender_idx, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override {
if (_table->hasSeenPacket(packet)) return;
// must be from server_id
Serial.printf("PATH to repeater, path_len=%d\n", (uint32_t) path_len);
memcpy(server_path, path, server_path_len = path_len); // store a copy of path, for sendDirect()
if (packet->isRouteFlood()) {
// send a reciprocal return path to sender, but send DIRECTLY!
mesh::Packet* rpath = createPathReturn(server_id, server_secret, packet->path, packet->path_len, 0, NULL, 0);
if (rpath) sendDirect(rpath, path, path_len);
}
if (extra_type == PAYLOAD_TYPE_RESPONSE) {
handleResponse(extra, extra_len);
}
}
public:
MyMesh(mesh::Radio& radio, mesh::RNG& rng, mesh::RTCClock& rtc, SimpleSeenTable& table)
: mesh::Mesh(radio, *new ArduinoMillis(), rng, rtc, *new StaticPoolPacketManager(16)), _table(&table)
{
}
mesh::Packet* createStatsRequest(uint32_t max_age) {
uint8_t payload[9];
uint32_t now = getRTCClock()->getCurrentTime();
memcpy(payload, &now, 4);
payload[4] = CMD_GET_STATS;
memcpy(&payload[5], &max_age, 4);
return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
}
mesh::Packet* createSetClockRequest(uint32_t timestamp) {
uint8_t payload[9];
uint32_t now = getRTCClock()->getCurrentTime();
memcpy(payload, &now, 4);
payload[4] = CMD_SET_CLOCK;
memcpy(&payload[5], &now, 4); // repeated :-(
return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
}
mesh::Packet* createSetAirtimeFactorRequest(float airtime_factor) {
uint8_t payload[16];
uint32_t now = getRTCClock()->getCurrentTime();
memcpy(payload, &now, 4);
payload[4] = CMD_SET_CONFIG;
sprintf((char *) &payload[5], "AF%f", airtime_factor);
return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
}
mesh::Packet* createAnnounceRequest() {
uint8_t payload[5];
uint32_t now = getRTCClock()->getCurrentTime();
memcpy(payload, &now, 4);
payload[4] = CMD_SEND_ANNOUNCE;
return createDatagram(PAYLOAD_TYPE_REQ, server_id, server_secret, payload, sizeof(payload));
}
mesh::Packet* parseCommand(char* command) {
if (strcmp(command, "stats") == 0) {
return createStatsRequest(60*60); // max_age = one hour
} else if (memcmp(command, "setclock ", 9) == 0) {
uint32_t timestamp = atol(&command[9]);
return createSetClockRequest(timestamp);
} else if (memcmp(command, "set AF=", 7) == 0) {
float factor = atof(&command[7]);
return createSetAirtimeFactorRequest(factor);
} else if (strcmp(command, "ann") == 0) {
return createAnnounceRequest();
}
return NULL; // unknown command
}
void sendCommand(mesh::Packet* pkt) {
if (server_path_len < 0) {
sendFlood(pkt);
} else {
sendDirect(pkt, server_path, server_path_len);
}
}
};
StdRNG fast_rng;
SimpleSeenTable table;
#if defined(P_LORA_SCLK)
SPIClass spi;
CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY, spi);
#else
CustomSX1262 radio = new Module(P_LORA_NSS, P_LORA_DIO_1, P_LORA_RESET, P_LORA_BUSY);
#endif
MyMesh the_mesh(*new CustomSX1262Wrapper(radio, board), fast_rng, *new VolatileRTCClock(), table);
void halt() {
while (1) ;
}
static char command[MAX_TEXT_LEN+1];
#include <SHA256.h>
void setup() {
Serial.begin(115200);
delay(5000);
board.begin();
#if defined(P_LORA_SCLK)
spi.begin(P_LORA_SCLK, P_LORA_MISO, P_LORA_MOSI);
int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
#else
int status = radio.begin(915.0, 250, 9, 5, RADIOLIB_SX126X_SYNC_WORD_PRIVATE, 22);
#endif
if (status != RADIOLIB_ERR_NONE) {
Serial.print("ERROR: radio init failed: ");
Serial.println(status);
halt();
}
fast_rng.begin(radio.random(0x7FFFFFFF));
/* add this to tests
uint8_t mac_encrypted[CIPHER_MAC_SIZE+CIPHER_BLOCK_SIZE];
const char *orig_msg = "original";
int enc_len = mesh::Utils::encryptThenMAC(mesh.admin_secret, mac_encrypted, (const uint8_t *) orig_msg, strlen(orig_msg));
char decrypted[CIPHER_BLOCK_SIZE*2];
int len = mesh::Utils::MACThenDecrypt(mesh.admin_secret, (uint8_t *)decrypted, mac_encrypted, enc_len);
if (len > 0) {
decrypted[len] = 0;
Serial.print("decrypted text: "); Serial.println(decrypted);
} else {
Serial.println("MACs DONT match!");
}
*/
Serial.println("Help:");
Serial.println(" enter 'key' to generate new keypair");
Serial.println(" enter 'stats' to request repeater stats");
Serial.println(" enter 'setclock {unix-epoch-seconds}' to set repeater's clock");
Serial.println(" enter 'set AF={factor}' to set airtime budget factor");
Serial.println(" enter 'ann' to make repeater re-announce to mesh");
the_mesh.begin();
command[0] = 0;
}
void loop() {
int len = strlen(command);
while (Serial.available() && len < sizeof(command)-1) {
char c = Serial.read();
if (c != '\n') {
command[len++] = c;
command[len] = 0;
}
Serial.print(c);
}
if (len == sizeof(command)-1) { // command buffer full
command[sizeof(command)-1] = '\r';
}
if (len > 0 && command[len - 1] == '\r') { // received complete line
command[len - 1] = 0; // replace newline with C string null terminator
if (strcmp(command, "key") == 0) {
mesh::LocalIdentity new_id(the_mesh.getRNG());
new_id.printTo(Serial);
} else {
mesh::Packet* pkt = the_mesh.parseCommand(command);
if (pkt) {
the_mesh.sendCommand(pkt);
Serial.println(" (request sent)");
} else {
Serial.print(" ERROR: unknown command: "); Serial.println(command);
}
}
command[0] = 0; // reset command buffer
}
the_mesh.loop();
}