Add Meshtext Companion channel chat and automatic radio2 setup
This commit is contained in:
1 parent
1f1a499482
commit
05907f49e0
52 files changed
+7700
-128
No files matched your search
+4
-1
@@ -4,6 +4,7 @@
|
||||
#include <cassert>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -12,6 +13,7 @@
|
||||
#define MAX_HASH_SIZE 8
|
||||
#define MAX_TEXT_LEN 150
|
||||
#define MAX_FRAME_SIZE 172
|
||||
#define MAX_GROUP_CHANNELS 40
|
||||
#define EXPECTED_ACK_TABLE_SIZE 8
|
||||
#define TXT_TYPE_PLAIN 0
|
||||
#define TXT_TYPE_CLI_COMMAND 1
|
||||
@@ -169,7 +171,7 @@ public:
|
||||
bool hasTerminalOutput() const { return false; }
|
||||
Terminal& terminalOutput() { return terminal; }
|
||||
void rememberOneKeyAck(ContactInfo&) {}
|
||||
uint8_t findChannelIdx(const mesh::GroupChannel&) { return 0; }
|
||||
int findChannelIdxForPacket(const mesh::GroupChannel&, const mesh::Packet*) { return 0; }
|
||||
bool getChannel(int, ChannelDetails&) { return false; }
|
||||
uint16_t emergencyClientRepeatKey(mesh::Packet*) { return 0; }
|
||||
bool hasEmergencyClientRepeat(uint16_t) { return false; }
|
||||
@@ -223,6 +225,7 @@ public:
|
||||
void onCLICommandRecv(const ContactInfo&, mesh::Packet*, uint32_t, const char*, char*);
|
||||
bool onSignedMessageRecv(const ContactInfo&, mesh::Packet*, uint32_t, const uint8_t*, const char*);
|
||||
void onChannelMessageRecv(const mesh::GroupChannel&, mesh::Packet*, uint32_t, const char*);
|
||||
bool queueChannelText(uint8_t, const uint8_t[32], float, uint8_t, uint32_t, const char*, bool);
|
||||
bool handleDirectCommand(const char*, char*, size_t);
|
||||
bool handleCommand(const char*, uint32_t, char*);
|
||||
mesh::Packet* composeMsgPacket(const ContactInfo&, uint32_t, uint8_t, const char*, uint32_t&);
|
||||
|
||||
Vendored
+831
@@ -0,0 +1,831 @@
|
||||
// Template compiled by test_companion_meshtext.py. Markers insert actual
|
||||
// production method bodies; all boundary substitutes are visible below.
|
||||
@FIXTURE@
|
||||
#include <SHA256.h>
|
||||
#include <helpers/CompanionMeshtextChannel.h>
|
||||
#include <helpers/CompanionFrameLimits.h>
|
||||
#include <helpers/UTF8Helpers.h>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
using std::isfinite;
|
||||
@CONSTANTS@
|
||||
#define MAX_GROUP_CHANNELS 8
|
||||
#define COMPANION_FEATURE_NOTIFICATIONS 1
|
||||
#define COMPANION_FEATURE_TEXT_TERMINAL 0
|
||||
#define TXT_TYPE_PLAIN 0
|
||||
|
||||
void mesh::Utils::sha256(uint8_t* out, size_t size, const uint8_t* data, int length) {
|
||||
assert(length >= 0 && size <= 32);
|
||||
SHA256 hash; hash.update(data, length); hash.finalize(out, size);
|
||||
}
|
||||
|
||||
struct Preferences {
|
||||
static inline std::vector<uint8_t> blob;
|
||||
static inline bool fail_begin=false, fail_write=false, fail_read=false;
|
||||
static inline unsigned writes=0;
|
||||
bool begin(const char* name, bool read_only) { assert(!strcmp(name,"mesh-mt") && !read_only); return !fail_begin; }
|
||||
size_t getBytesLength(const char* key) { assert(!strcmp(key,"settings")); return blob.size(); }
|
||||
size_t getBytes(const char*, void* out, size_t size) {
|
||||
if(fail_read) return 0;
|
||||
size=std::min(size,blob.size()); memcpy(out,blob.data(),size); return size;
|
||||
}
|
||||
size_t putBytes(const char*, const void* in, size_t size) {
|
||||
++writes; if(fail_write) return 0; const auto* data=static_cast<const uint8_t*>(in);
|
||||
blob.assign(data,data+size); return size;
|
||||
}
|
||||
void end() {}
|
||||
bool remove(const char* key) { assert(!strcmp(key,"settings")); if(fail_write) return false; blob.clear(); return true; }
|
||||
static void reset() { blob.clear(); fail_begin=fail_write=fail_read=false; writes=0; }
|
||||
};
|
||||
static uint32_t test_random_seed=0x12345678;
|
||||
static uint32_t esp_random() { return test_random_seed; }
|
||||
|
||||
namespace mesh { struct GroupChannel {
|
||||
uint8_t hash[1]={},secret[32]={},tx_radio=RADIO_TX_AUTO;
|
||||
}; }
|
||||
struct ChannelDetails { mesh::GroupChannel channel; char name[32]={}; };
|
||||
struct BaseChatMesh {
|
||||
ChannelDetails stored[MAX_GROUP_CHANNELS];
|
||||
bool getChannel(int index, ChannelDetails& out) {
|
||||
if(index<0 || index>=MAX_GROUP_CHANNELS) return false;
|
||||
out=stored[index]; return true;
|
||||
}
|
||||
bool setChannel(int index, const ChannelDetails& in) {
|
||||
if(index<0 || index>=MAX_GROUP_CHANNELS) return false;
|
||||
stored[index]=in;
|
||||
mesh::Utils::sha256(stored[index].channel.hash,1,in.channel.secret,
|
||||
mesh::Utils::isZeroes(in.channel.secret+16,16)?16:32); return true;
|
||||
}
|
||||
};
|
||||
struct MtRadio : Radio {
|
||||
bool supported=true;
|
||||
bool supportsMeshtext() const override { return supported; }
|
||||
};
|
||||
struct Serial {
|
||||
bool connected=false;
|
||||
std::vector<std::vector<uint8_t>> frames;
|
||||
bool isConnected() { return connected; }
|
||||
void writeFrame(const uint8_t* bytes,int size) { assert(size>=0); frames.emplace_back(bytes,bytes+size); }
|
||||
};
|
||||
struct UI { void setMessageNotificationOverride(bool,bool=false) {} };
|
||||
struct Notifications {
|
||||
uint8_t key[32]={}; unsigned calls=0;
|
||||
bool message(const void*,const uint8_t* secret,bool,uint32_t) { ++calls; memcpy(key,secret,32); return false; }
|
||||
bool overridesScreen() const { return false; }
|
||||
};
|
||||
struct StrHelper {
|
||||
static void strncpy(char* out,const char* in,size_t size) { ::strncpy(out,in,size-1); out[size-1]=0; }
|
||||
};
|
||||
class MyMesh : public BaseChatMesh {
|
||||
public:
|
||||
MemoryFS fs; Clock clock; MtRadio radio; mesh::Radio* _radio=&radio;
|
||||
mesh::RadioProfileCLI _radio_profiles;
|
||||
struct {float freq=909.5; char node_name[32]="Test";} _prefs;
|
||||
mesh::LocalIdentity self_id;
|
||||
mesh::mt::Region _mt_region=mesh::mt::Region::Unset;
|
||||
uint32_t _mt_slot=0,_mt_node=0,_mt_packet_id=0,_mt_sent=0,_mt_failed=0,_mt_received=0;
|
||||
uint32_t _mt_default_node=0,_mt_node_override=0;
|
||||
uint8_t _mt_hop_limit=7;
|
||||
char _mt_short_name[17]={};
|
||||
mesh::mt::SeenPackets _mt_seen;
|
||||
bool _mt_settings_valid=true,_mt_active=false,_mt_profile_dirty=true,_mt_last_radio_ready=false;
|
||||
uint32_t _mt_primary_generation=0,_mt_secondary_generation=0,_mt_intent_generation=0;
|
||||
float _mt_primary_frequency=0; const char* _mt_status="no Meshtext channels";
|
||||
bool _radio_available=true,foreign_pending=false,admit_foreign=true,save_result=true,ok=false;
|
||||
uint32_t foreign_generation=0; uint8_t foreign_profile=255;
|
||||
unsigned foreign_admissions=0,meshcore_sends=0;
|
||||
std::vector<std::vector<uint8_t>> foreign,offline;
|
||||
size_t offline_capacity=4;
|
||||
Serial serial; Serial* _serial=&serial; UI ui; UI* _ui=&ui; Notifications _notifications;
|
||||
uint8_t out_frame[MAX_FRAME_SIZE]={}; uint8_t app_target_ver=3;
|
||||
int error=-1;
|
||||
MyMesh() { g_mock_millis=0; self_id.pub_key[0]=42; _radio_profiles.begin(&fs,&radio,&clock); }
|
||||
bool isAliasRadio2Defined() const;
|
||||
bool resolveChannelAlias(ChannelDetails&) const;
|
||||
bool getChannel(int,ChannelDetails&);
|
||||
bool setChannel(int,const ChannelDetails&);
|
||||
bool getChannelForSave(uint8_t index,ChannelDetails& value) { return BaseChatMesh::getChannel(index,value); }
|
||||
mesh::mt::Region meshtextRegion() const;
|
||||
void refreshMeshtextIdentity();
|
||||
void beginMeshtext();
|
||||
bool saveMeshtextSettings(mesh::mt::Region,uint32_t,uint8_t hops=UINT8_MAX,
|
||||
const char* short_name=nullptr,uint32_t node_override=UINT32_MAX);
|
||||
bool eraseMeshtextSettings();
|
||||
bool isMeshtextChannel(const ChannelDetails&) const;
|
||||
bool validateMeshtextChannelChange(int,const ChannelDetails&);
|
||||
void refreshMeshtextProfile();
|
||||
bool sendMeshtextText(const ChannelDetails&,const char*,size_t);
|
||||
bool sendMeshtextNodeInfo(const ChannelDetails&);
|
||||
bool onForeignRadioFrame(const uint8_t*,size_t,uint8_t,uint32_t,float,float);
|
||||
void onForeignRadioSendComplete(bool);
|
||||
bool handleMeshtextCommand(const char*,char*,size_t);
|
||||
bool queueChannelText(uint8_t,const uint8_t[32],float,uint8_t,uint32_t,const char*,bool);
|
||||
bool hasForeignRadioFrame() const { return foreign_pending; }
|
||||
bool queueForeignRadioFrame(const uint8_t* bytes,size_t size,uint8_t profile,uint32_t generation) {
|
||||
if(!admit_foreign || foreign_pending) return false;
|
||||
++foreign_admissions; foreign.emplace_back(bytes,bytes+size); foreign_profile=profile;
|
||||
foreign_generation=generation; foreign_pending=true; return true;
|
||||
}
|
||||
mesh::RTCClock* getRTCClock() { return &clock; }
|
||||
bool addToOfflineQueue(const uint8_t* bytes,int size) {
|
||||
assert(size>=0 && size<=MAX_FRAME_SIZE); if(offline.size()>=offline_capacity) return false;
|
||||
offline.emplace_back(bytes,bytes+size); return true;
|
||||
}
|
||||
bool saveChannels() { return save_result; }
|
||||
void writeErrFrame(uint8_t value) { error=value; }
|
||||
void writeOKFrame() { ok=true; }
|
||||
bool sendGroupMessage(uint32_t,mesh::GroupChannel&,const char*,const char*,int) { ++meshcore_sends; return true; }
|
||||
void command(uint8_t* cmd_frame,int len);
|
||||
void commit(int index,const ChannelDetails& value) {
|
||||
assert(setChannel(index,value)); _mt_profile_dirty=true; refreshMeshtextProfile();
|
||||
}
|
||||
const char* cli(const char* command,bool expected=true) {
|
||||
static char reply[256]; assert(_radio_profiles.handle(command,reply,sizeof(reply)));
|
||||
if(strncmp(command,"get ",4) && strncmp(command,"del ",4)) {
|
||||
if((!strncmp(reply,"OK",2))!=expected) { fprintf(stderr,"%s -> %s\n",command,reply); assert(false); }
|
||||
}
|
||||
return reply;
|
||||
}
|
||||
void advance(uint32_t ms) { g_mock_millis+=ms; clock.epoch+=ms/1000; _radio_profiles.loop(); refreshMeshtextProfile(); }
|
||||
};
|
||||
@METHODS@
|
||||
void MyMesh::command(uint8_t* cmd_frame,int len) {
|
||||
error=-1; ok=false; serial.frames.clear();
|
||||
@COMMANDS@
|
||||
}
|
||||
static ChannelDetails channel(const char* name,int private_bytes=0) {
|
||||
ChannelDetails value; assert(strlen(name)<sizeof(value.name)); strcpy(value.name,name);
|
||||
if(private_bytes) { for(int i=0;i<private_bytes;++i)value.channel.secret[i]=i+1; }
|
||||
else mesh::Utils::sha256(value.channel.secret,16,reinterpret_cast<const uint8_t*>(name),strlen(name));
|
||||
return value;
|
||||
}
|
||||
static void active(MyMesh& node) {
|
||||
node.beginMeshtext(); node.commit(0,channel("#mt-longfast"));
|
||||
assert(node._mt_active && node.radio.p.secondary.params.protocol==mesh::RadioProfileProtocol::Meshtext);
|
||||
}
|
||||
static void assertUntouched(const MyMesh& node) { assert(node.foreign.empty() && !node.meshcore_sends); }
|
||||
static void keys() {
|
||||
Preferences::reset(); MyMesh node; active(node);
|
||||
auto raw=channel("#mt-longfast"); ChannelDetails stored;
|
||||
assert(node.getChannelForSave(0,stored) && !memcmp(raw.channel.secret,stored.channel.secret,32));
|
||||
mesh::mt::Channel wire; assert(describe(stored,wire));
|
||||
assert(!strcmp(wire.name,"LongFast") && wire.named_preset && wire.key_length==16);
|
||||
assert(!memcmp(wire.key,mesh::mt::DefaultPsk,16));
|
||||
ChannelDetails policy; assert(node.getChannel(0,policy));
|
||||
assert(policy.channel.tx_radio==mesh::RADIO_TX_OFF);
|
||||
assert(memcmp(policy.channel.secret,raw.channel.secret,16));
|
||||
for(const char* name:{"#mt-LoNgFaSt","#mt-shortturbo","#mt-longmoderate"}) {
|
||||
auto c=channel(name); const auto before=c;
|
||||
assert(describe(c,wire) && !memcmp(wire.key,mesh::mt::DefaultPsk,16));
|
||||
assert(!memcmp(c.channel.secret,before.channel.secret,32));
|
||||
}
|
||||
for(int size:{16,32}) {
|
||||
auto c=channel("#mt-longfast",size); const auto before=c;
|
||||
assert(describe(c,wire) && wire.key_length==size && !memcmp(wire.key,c.channel.secret,32));
|
||||
assert(!memcmp(c.channel.secret,before.channel.secret,32));
|
||||
node.foreign_pending=false; assert(node.sendMeshtextText(c,"private",7));
|
||||
mesh::mt::DecodedText decoded;
|
||||
assert(mesh::mt::decodeText(node.foreign.back().data(),node.foreign.back().size(),wire.name,wire.key,size,1,decoded));
|
||||
assert(!strcmp(decoded.text,"private"));
|
||||
}
|
||||
auto custom=channel("#mt-emergency"); assert(describe(custom,wire));
|
||||
auto ordinary=channel("#emergency"); assert(!memcmp(wire.key,ordinary.channel.secret,16));
|
||||
assert(!wire.named_preset && !strcmp(wire.name,"emergency"));
|
||||
auto invalid=channel("#mt-abcdefghijkl"); assert(!describe(invalid,wire));
|
||||
puts("PASS keys");
|
||||
}
|
||||
static void automatic() {
|
||||
Preferences::reset(); MyMesh node; assert(!node.radio.p.enabled()); active(node);
|
||||
assert(node.radio.p.secondary.mode==mesh::RadioProfileMode::RxTx);
|
||||
assert(node.radio.p.secondary.params.bw==250 && node.radio.p.secondary.params.sf==11);
|
||||
assert(node._radio_profiles.autoSecondaryActive() && node.fs.files.empty() && Preferences::writes==0);
|
||||
const auto generation=node.radio.p.generation[1]; node.refreshMeshtextProfile();
|
||||
assert(node.radio.p.generation[1]==generation); assertUntouched(node);
|
||||
MyMesh reboot; reboot.stored[0]=node.stored[0]; reboot.fs=node.fs;
|
||||
reboot._radio_profiles.begin(&reboot.fs,&reboot.radio,&reboot.clock); reboot.beginMeshtext();
|
||||
assert(reboot._mt_active && reboot._radio_profiles.autoSecondaryActive()); assertUntouched(reboot);
|
||||
node.commit(0,{}); assert(!node._mt_active && !node.radio.p.enabled()); assertUntouched(node);
|
||||
puts("PASS auto");
|
||||
}
|
||||
static void conflicts() {
|
||||
Preferences::reset(); MyMesh node; active(node);
|
||||
assert(!node.validateMeshtextChannelChange(1,channel("#mt-longturbo")));
|
||||
assert(!node.validateMeshtextChannelChange(1,channel("#r2-emergency")));
|
||||
node.commit(1,channel("#mt-longturbo")); assert(!node._mt_active && !node.radio.p.enabled());
|
||||
node.commit(1,{}); assert(node._mt_active);
|
||||
assert(node.validateMeshtextChannelChange(1,channel("#mt-emergency",32)));
|
||||
node.commit(1,channel("#mt-emergency",32)); node.commit(0,{});
|
||||
assert(!node._mt_active && !node.radio.p.enabled());
|
||||
assert(node.isMeshtextChannel(node.stored[1]));
|
||||
assert(!node.sendMeshtextText(node.stored[1],"x",1));
|
||||
node.commit(1,{}); node._prefs.freq=915; node.commit(0,channel("#mt-longfast"));
|
||||
assert(!node._mt_active && strstr(node._mt_status,"ambiguous"));
|
||||
assert(!node.validateMeshtextChannelChange(0,channel("#mt-longfast")));
|
||||
assert(node.saveMeshtextSettings(mesh::mt::Region::US,0) && node._mt_active);
|
||||
assert(node.saveMeshtextSettings(mesh::mt::Region::EU868,0) && node._mt_active);
|
||||
assert(!node.validateMeshtextChannelChange(0,channel("#mt-shortturbo")));
|
||||
node.commit(0,channel("#mt-shortturbo")); assert(!node._mt_active);
|
||||
node.commit(0,channel("#mt-longfast")); assert(node._mt_active);
|
||||
assert(node.saveMeshtextSettings(mesh::mt::Region::EU868,2)); assert(!node._mt_active);
|
||||
assert(node.saveMeshtextSettings(mesh::mt::Region::EU868,1)); assert(node._mt_active);
|
||||
assert(std::fabs(node.radio.p.secondary.params.freq-869.525f)<0.0001f);
|
||||
node._radio_available=false; node.refreshMeshtextProfile(); assert(!node._mt_active);
|
||||
node._radio_available=true; node.refreshMeshtextProfile(); assert(node._mt_active);
|
||||
node.commit(0,channel("ordinary")); assert(!node._mt_active && !node.radio.p.enabled());
|
||||
assertUntouched(node); puts("PASS conflicts");
|
||||
}
|
||||
static void manual() {
|
||||
Preferences::reset(); MyMesh node; node.beginMeshtext();
|
||||
node.cli("set radio2 906.875,250,11,5,rxtx,80"); node.advance(2000);
|
||||
const auto saved_files=node.fs.files; const auto saved=node._radio_profiles.savedSecondaryConfig();
|
||||
node.commit(0,channel("#mt-longfast")); assert(node._mt_active);
|
||||
assert(node.radio.p.secondary.params.freq==906.875f && node.radio.p.secondary.params.preamble==16);
|
||||
assert(node._radio_profiles.savedSecondaryConfig().params==saved.params && node.fs.files==saved_files);
|
||||
node.cli("set tempradio2 909.5,62.5,7,5,rx,1,80"); node.advance(2000);
|
||||
assert(!node._mt_active && node.radio.p.secondary_temporary);
|
||||
assert(node.radio.p.secondary.params.protocol==mesh::RadioProfileProtocol::MeshCore);
|
||||
node.advance(60000); assert(node._mt_active && !node.radio.p.secondary_temporary);
|
||||
node.commit(0,{}); assert(!node._mt_active);
|
||||
assert(node.radio.p.secondary.params==saved.params && node.fs.files==saved_files);
|
||||
node.cli("set radio2 off"); node.advance(2000); const auto off_files=node.fs.files;
|
||||
node.commit(0,channel("#mt-longfast")); assert(!node._mt_active && !node.radio.p.enabled());
|
||||
node.commit(0,{}); assert(!node.radio.p.enabled() && node.fs.files==off_files);
|
||||
node.cli("set radio2 auto"); node.advance(2000); node.commit(0,channel("#mt-longfast"));
|
||||
assert(node._mt_active && node._radio_profiles.autoSecondaryActive());
|
||||
// An external/temporary owner is not ours to disable when a channel vanishes.
|
||||
auto external=node.radio.p.secondary; external.params.freq=910.25; external.params.bw=125;
|
||||
external.params.sf=8; external.params.cr=5; external.params.preamble=80;
|
||||
external.params.protocol=mesh::RadioProfileProtocol::MeshCore;
|
||||
node.radio.p.setSecondary(external,false); node.refreshMeshtextProfile();
|
||||
assert(!node._mt_active && node.radio.p.secondary.params==external.params);
|
||||
node.commit(0,{}); assert(node.radio.p.secondary.params==external.params);
|
||||
assertUntouched(node);
|
||||
puts("PASS manual");
|
||||
}
|
||||
static void settings() {
|
||||
Preferences::reset(); MyMesh node; active(node); assert(node._mt_node && node._mt_packet_id);
|
||||
assert(node.saveMeshtextSettings(mesh::mt::Region::ANZ,1));
|
||||
assert(Preferences::blob.size()==40 && Preferences::writes==1);
|
||||
const auto committed=Preferences::blob; Preferences::fail_write=true;
|
||||
assert(!node.saveMeshtextSettings(mesh::mt::Region::US,2));
|
||||
assert(node._mt_region==mesh::mt::Region::ANZ && node._mt_slot==1 && Preferences::blob==committed);
|
||||
assert(!node._mt_settings_valid && !node._mt_active && !node.radio.p.enabled());
|
||||
Preferences::fail_write=false; node.foreign_pending=true;
|
||||
const auto writes=Preferences::writes; assert(!node.saveMeshtextSettings(mesh::mt::Region::US,0));
|
||||
assert(Preferences::writes==writes); node.foreign_pending=false;
|
||||
assert(!node.saveMeshtextSettings(mesh::mt::Region::US,1025));
|
||||
assert(node.saveMeshtextSettings(mesh::mt::Region::ANZ,1) && node._mt_active);
|
||||
MyMesh reboot; reboot.stored[0]=node.stored[0]; reboot.beginMeshtext();
|
||||
assert(reboot._mt_region==mesh::mt::Region::ANZ && reboot._mt_slot==1 && reboot._mt_active);
|
||||
Preferences::blob[5]=1; MyMesh corrupt; corrupt.stored[0]=node.stored[0]; corrupt.beginMeshtext();
|
||||
assert(!corrupt._mt_settings_valid && !corrupt._mt_active && !corrupt.radio.p.enabled());
|
||||
char reply[160]; assert(corrupt.handleMeshtextCommand("set mt.region us",reply,sizeof(reply)));
|
||||
assert(!strncmp(reply,"OK",2) && corrupt._mt_active && corrupt._mt_settings_valid);
|
||||
assert(corrupt.handleMeshtextCommand("set mt.slot 1junk",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(corrupt.handleMeshtextCommand("get mt.status",reply,sizeof(reply)) && strstr(reply,"RX time-shared"));
|
||||
assert(!corrupt.handleMeshtextCommand("get unknown",reply,sizeof(reply)));
|
||||
// The atomic blob may have committed despite failed readback: suspend RAM,
|
||||
// then reconstruct the committed choice only after a successful new read.
|
||||
Preferences::fail_read=true;
|
||||
assert(!corrupt.saveMeshtextSettings(mesh::mt::Region::ANZ,2));
|
||||
assert(!corrupt._mt_settings_valid && !corrupt._mt_active && !corrupt.radio.p.enabled());
|
||||
Preferences::fail_read=false; MyMesh readback;
|
||||
readback.stored[0]=corrupt.stored[0]; readback.beginMeshtext();
|
||||
assert(readback._mt_active && readback._mt_region==mesh::mt::Region::ANZ && readback._mt_slot==2);
|
||||
Preferences::fail_write=true; assert(!readback.eraseMeshtextSettings());
|
||||
assert(!readback._mt_active && !readback._mt_settings_valid && !readback.radio.p.enabled());
|
||||
Preferences::fail_write=false; assert(readback.eraseMeshtextSettings() && Preferences::blob.empty());
|
||||
assert(readback._mt_region==mesh::mt::Region::Unset && readback._mt_slot==0);
|
||||
assert(readback._mt_hop_limit==7);
|
||||
readback.refreshMeshtextProfile(); assert(!readback._mt_active);
|
||||
Preferences::fail_begin=true; assert(!corrupt.eraseMeshtextSettings());
|
||||
assert(!corrupt._mt_active && !corrupt._mt_settings_valid && !corrupt.radio.p.enabled());
|
||||
Preferences::fail_begin=false;
|
||||
assertUntouched(node); assertUntouched(reboot); assertUntouched(corrupt); puts("PASS settings");
|
||||
}
|
||||
static const uint8_t rx_frame[]=@RX_FRAME@,rx_retry[]=@RX_RETRY@,rx_dm[]=@RX_DM@,
|
||||
rx_ack[]=@RX_ACK@,rx_other[]=@RX_OTHER@;
|
||||
static bool receiveFrame(MyMesh& node,const uint8_t* bytes,size_t size,float snr=3) {
|
||||
return node.onForeignRadioFrame(bytes,size,1,node.radio.p.generation[1],snr,-90);
|
||||
}
|
||||
static bool validUtf8(const uint8_t* text,size_t size) {
|
||||
uint8_t frame[255]; return mesh::mt::encodeText(1,1,3,"LongFast",mesh::mt::DefaultPsk,16,
|
||||
reinterpret_cast<const char*>(text),size,frame)!=0;
|
||||
}
|
||||
static void receive() {
|
||||
Preferences::reset(); MyMesh node; active(node);
|
||||
assert(!node.onForeignRadioFrame(rx_frame,sizeof(rx_frame),0,node.radio.p.generation[1],3,-90));
|
||||
assert(!node.onForeignRadioFrame(rx_frame,sizeof(rx_frame),1,node.radio.p.generation[1]-1,3,-90));
|
||||
assert(!receiveFrame(node,rx_dm,sizeof(rx_dm))); assert(!receiveFrame(node,rx_other,sizeof(rx_other)));
|
||||
assert(node.offline.empty());
|
||||
assert(receiveFrame(node,rx_frame,sizeof(rx_frame),100));
|
||||
assert(node.offline.size()==1 && node._mt_received==1 && node._notifications.calls==1);
|
||||
auto envelope=node.offline.back(); assert(envelope[0]==RESP_CODE_CHANNEL_MSG_RECV_V3);
|
||||
assert(envelope[1]==127 && envelope[2]==0 && envelope[3]==0 && envelope[4]==0);
|
||||
assert(envelope[5]==0 && envelope[6]==TXT_TYPE_PLAIN && envelope.size()<=MAX_FRAME_SIZE);
|
||||
uint32_t timestamp=0; memcpy(×tamp,envelope.data()+7,sizeof(timestamp));
|
||||
assert(timestamp==node.clock.epoch);
|
||||
assert(validUtf8(envelope.data()+11,envelope.size()-11));
|
||||
assert(!memcmp(envelope.data()+11,"!11223344: ",11));
|
||||
assert(envelope.size()==175); // 153 ASCII bytes remain; no partial euro scalar.
|
||||
ChannelDetails policy; assert(node.getChannel(0,policy));
|
||||
assert(!memcmp(node._notifications.key,policy.channel.secret,32));
|
||||
assert(memcmp(node._notifications.key,mesh::mt::DefaultPsk,16));
|
||||
assert(receiveFrame(node,rx_frame,sizeof(rx_frame)) && node.offline.size()==1);
|
||||
node.offline_capacity=1; assert(receiveFrame(node,rx_retry,sizeof(rx_retry)));
|
||||
assert(node._mt_received==1 && !node._mt_seen.seen(0x11223344,102));
|
||||
node.offline_capacity=4; node.app_target_ver=1; node.serial.connected=true;
|
||||
assert(receiveFrame(node,rx_retry,sizeof(rx_retry)) && node._mt_received==2);
|
||||
assert(node.offline.back()[0]==RESP_CODE_CHANNEL_MSG_RECV && node.offline.back()[1]==0);
|
||||
assert(node.serial.frames.size()==1 && node.serial.frames[0][0]==PUSH_CODE_MSG_WAITING);
|
||||
assert(receiveFrame(node,rx_ack,sizeof(rx_ack)) && node._mt_received==3);
|
||||
assertUntouched(node); // request-ACK produces no radio response, no relay
|
||||
node.offline_capacity=6;
|
||||
uint8_t ordinary_key[32]={1};
|
||||
node.app_target_ver=3;
|
||||
assert(node.queueChannelText(0,ordinary_key,-100,255,123,"negative",false));
|
||||
assert(node.offline.back()[1]==128 && node.offline.back()[5]==255);
|
||||
assert(node.queueChannelText(0,ordinary_key,std::numeric_limits<float>::quiet_NaN(),0,124,"nan",false));
|
||||
assert(node.offline.back()[1]==0);
|
||||
uint8_t empty_secret[32]={}; assert(!node.queueChannelText(MAX_GROUP_CHANNELS,empty_secret,0,0,0,"x",false));
|
||||
assert(!node.queueChannelText(0,empty_secret,0,0,0,nullptr,false));
|
||||
puts("PASS receive");
|
||||
}
|
||||
static void transmit() {
|
||||
Preferences::reset(); MyMesh node; active(node); assertUntouched(node);
|
||||
uint8_t request[32]={CMD_SEND_CHANNEL_TXT_MSG,TXT_TYPE_PLAIN,0};
|
||||
memcpy(request+7,"hello",5); node.command(request,12);
|
||||
assert(node.ok && node.error==-1 && node.foreign.size()==1 && !node.meshcore_sends);
|
||||
assert(node.foreign_profile==1 && node.foreign_generation==node.radio.p.generation[1]);
|
||||
mesh::mt::DecodedText decoded; auto& frame=node.foreign.back();
|
||||
assert(mesh::mt::decodeText(frame.data(),frame.size(),"LongFast",mesh::mt::DefaultPsk,16,1,decoded));
|
||||
assert(!strcmp(decoded.text,"hello"));
|
||||
assert(decoded.hop_limit==7 && decoded.hop_start==7 && decoded.hops==0);
|
||||
assert(frame[12]==0xe7); // limit/start 7, no want-ACK or MQTT flag.
|
||||
assert(!mesh::mt::decodeText(frame.data(),frame.size(),"LongFast",mesh::mt::DefaultPsk,16,node._mt_node,decoded));
|
||||
node.command(request,12); assert(!node.ok && node.error==ERR_CODE_BAD_STATE && node.foreign.size()==1);
|
||||
node.foreign_pending=false; node.onForeignRadioSendComplete(true); node.onForeignRadioSendComplete(false);
|
||||
assert(node._mt_sent==1 && node._mt_failed==1);
|
||||
char oversized[229]; memset(oversized,'x',sizeof(oversized));
|
||||
assert(!node.sendMeshtextText(node.stored[0],oversized,sizeof(oversized)));
|
||||
assert(!node.sendMeshtextText(node.stored[0],"x\0y",3));
|
||||
node._mt_packet_id=UINT32_MAX; assert(node.sendMeshtextText(node.stored[0],"last",4));
|
||||
node.foreign_pending=false; assert(node._mt_packet_id==0 && !node.sendMeshtextText(node.stored[0],"x",1));
|
||||
assert(node.offline.empty() && node._notifications.calls==0); puts("PASS transmit");
|
||||
}
|
||||
static void applySet(MyMesh& node,int index,const ChannelDetails& value,int key_size=16) {
|
||||
uint8_t frame[66]={CMD_SET_CHANNEL,static_cast<uint8_t>(index)};
|
||||
memcpy(frame+2,value.name,32); memcpy(frame+34,value.channel.secret,key_size); node.command(frame,34+key_size);
|
||||
}
|
||||
static void commands() {
|
||||
Preferences::reset(); MyMesh node; active(node); ChannelDetails raw;
|
||||
auto original=node.stored[0]; original.channel.tx_radio=mesh::RADIO_TX_BOTH; node.commit(0,original);
|
||||
uint8_t get[]={CMD_GET_CHANNEL,0}; node.command(get,sizeof(get));
|
||||
assert(node.serial.frames.size()==1 && node.serial.frames[0].size()==50);
|
||||
assert(!memcmp(node.serial.frames[0].data()+34,original.channel.secret,16));
|
||||
applySet(node,0,original); assert(node.ok && node.getChannelForSave(0,raw));
|
||||
assert(raw.channel.tx_radio==mesh::RADIO_TX_BOTH && !memcmp(raw.channel.secret,original.channel.secret,32));
|
||||
auto custom=channel("#mt-longfast",16); node.save_result=false; applySet(node,0,custom);
|
||||
assert(node.error==ERR_CODE_FILE_IO_ERROR && !node.ok && node.getChannelForSave(0,raw));
|
||||
assert(!memcmp(raw.channel.secret,original.channel.secret,32)); node.save_result=true;
|
||||
applySet(node,0,custom); assert(node.ok && node.getChannelForSave(0,raw));
|
||||
assert(!memcmp(raw.channel.secret,custom.channel.secret,32) && raw.channel.tx_radio==mesh::RADIO_TX_AUTO);
|
||||
applySet(node,1,channel("#mt-longturbo")); assert(node.error==ERR_CODE_BAD_STATE && !node.ok);
|
||||
applySet(node,1,channel("#mt-mt-room")); assert(node.error==ERR_CODE_ILLEGAL_ARG && !node.ok);
|
||||
auto aes256=channel("#mt-longfast",32); applySet(node,0,aes256,32);
|
||||
assert(node.ok && node.getChannelForSave(0,raw) && !memcmp(raw.channel.secret,aes256.channel.secret,32));
|
||||
// Original two-byte GET is still a 16-byte response; opt-in GET exposes 32.
|
||||
node.command(get,sizeof(get)); assert(node.serial.frames[0].size()==50);
|
||||
uint8_t extended_get[]={CMD_GET_CHANNEL,0,32}; node.command(extended_get,sizeof(extended_get));
|
||||
assert(node.serial.frames[0].size()==66 && !memcmp(node.serial.frames[0].data()+34,aes256.channel.secret,32));
|
||||
auto rename=aes256; strcpy(rename.name,"#mt-LoNgFaSt"); applySet(node,0,rename);
|
||||
assert(node.ok && node.getChannelForSave(0,raw) && !memcmp(raw.channel.secret,aes256.channel.secret,32));
|
||||
node.save_result=false; auto changed=channel("#mt-longfast",32); changed.channel.secret[20]^=0x80;
|
||||
applySet(node,0,changed,32);
|
||||
assert(node.error==ERR_CODE_FILE_IO_ERROR && !node.ok && node.getChannelForSave(0,raw));
|
||||
assert(!memcmp(raw.channel.secret,aes256.channel.secret,32)); node.save_result=true;
|
||||
auto downgrade=channel("#mt-longfast",16); applySet(node,0,downgrade,32);
|
||||
assert(node.ok && node.getChannelForSave(0,raw) && mesh::Utils::isZeroes(raw.channel.secret+16,16));
|
||||
auto mc=channel("private",32); applySet(node,1,mc,32);
|
||||
assert(node.error==ERR_CODE_UNSUPPORTED_CMD && !node.ok);
|
||||
node.commit(1,channel("ordinary")); uint8_t get_mc[]={CMD_GET_CHANNEL,1,32}; node.command(get_mc,sizeof(get_mc));
|
||||
assert(node.serial.frames[0].size()==50); node.commit(1,{});
|
||||
applySet(node,0,{}); assert(node.ok && !node._mt_active && !node.radio.p.enabled());
|
||||
assertUntouched(node); puts("PASS commands");
|
||||
}
|
||||
static void privateCLI() {
|
||||
Preferences::reset(); MyMesh node; node.beginMeshtext(); char reply[256];
|
||||
const char* key128="0102030405060708090a0b0c0d0e0f10";
|
||||
const char* key256="0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20";
|
||||
char command[160]; snprintf(command,sizeof(command),"set mt.channel 0 mt-longfast %s",key256);
|
||||
assert(node.handleMeshtextCommand(command,reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node._mt_active && node._radio_profiles.autoSecondaryActive());
|
||||
auto expected=channel("mt-longfast",32); assert(!memcmp(node.stored[0].channel.secret,expected.channel.secret,32));
|
||||
assert(!strstr(reply,key256) && !strstr(reply,key128));
|
||||
assert(node.handleMeshtextCommand("get mt.channel 0",reply,sizeof(reply)));
|
||||
assert(strstr(reply,"AES-256") && strstr(reply,"key not displayed") && !strstr(reply,key256));
|
||||
const auto previous=node.stored[0]; node.save_result=false;
|
||||
snprintf(command,sizeof(command),"set mt.channel 0 mt-longfast %s",key128);
|
||||
assert(node.handleMeshtextCommand(command,reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(!memcmp(node.stored[0].channel.secret,previous.channel.secret,32));
|
||||
assert(node.handleMeshtextCommand("delete mt.channel 0",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(!memcmp(node.stored[0].channel.secret,previous.channel.secret,32)); node.save_result=true;
|
||||
for(const char* invalid:{"set mt.channel -1 mt-longfast AQ==", "set mt.channel 8 mt-longfast AQ==",
|
||||
"set mt.channel 999999999999999999999 mt-longfast AQ==", "set mt.channel 1 ordinary AQ==",
|
||||
"set mt.channel 1 #mt-mt-room AQ==", "set mt.channel 1 mt-longfast BADKEY",
|
||||
"set mt.channel 1 mt-longfast 0102030405060708090a0b0c0d0e0f1Z",
|
||||
"set mt.channel 1 mt-longfast 00000000000000000000000000000000",
|
||||
"set mt.channel 1 mt-longfast AQ== extra", "set mt.channel 1 mt-longfast",
|
||||
"delete mt.channel 0 extra", "get mt.channel 0 extra"}) {
|
||||
assert(node.handleMeshtextCommand(invalid,reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(!node.stored[1].name[0] && !memcmp(node.stored[0].channel.secret,previous.channel.secret,32));
|
||||
}
|
||||
assert(node.handleMeshtextCommand("set mt.channel 1 mt-team AQ==",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node._mt_active && !memcmp(node.stored[1].channel.secret,mesh::mt::DefaultPsk,16));
|
||||
assert(node.handleMeshtextCommand("delete mt.channel 0",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(!node._mt_active && !node.radio.p.enabled());
|
||||
assert(node.handleMeshtextCommand("set mt.preset longfast",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(!node._mt_active); node.advance(2000);
|
||||
assert(node._mt_active && node._radio_profiles.manualSecondaryConfigured());
|
||||
const auto saved_files=node.fs.files;
|
||||
assert(node.handleMeshtextCommand("delete mt.channel 1",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(!node._mt_active && node.radio.p.enabled() && node.fs.files==saved_files);
|
||||
assert(node.radio.p.secondary.params.protocol==mesh::RadioProfileProtocol::MeshCore);
|
||||
assert(node.handleMeshtextCommand("set mt.channel 1 mt-team AQ==",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node._mt_active);
|
||||
assert(node.handleMeshtextCommand("get mt.channel 1",reply,sizeof(reply)) && strstr(reply,"AES-128"));
|
||||
assert(node.handleMeshtextCommand("set mt.preset notapreset",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
for(const char* line:{"set mt.channel 0 mt-team ABCD", " SET\tMT.CHANNEL\t0\tmt-team\tABCD"}) {
|
||||
const auto* key=mesh::cli::terminalPasswordInput(line); assert(key && !strcmp(key,"ABCD"));
|
||||
assert(mesh::cli::shouldMaskTerminalInput(line));
|
||||
}
|
||||
for(const char* line:{"set mt.channel 0 mt-team", "set mt.channel 0", "get mt.channel 0"}) {
|
||||
assert(!mesh::cli::shouldMaskTerminalInput(line));
|
||||
}
|
||||
assertUntouched(node); puts("PASS cli");
|
||||
}
|
||||
static void hops() {
|
||||
Preferences::reset(); MyMesh node; active(node); char reply[256];
|
||||
assert(node._mt_hop_limit==7 && Preferences::writes==0);
|
||||
assert(node.handleMeshtextCommand("get mt.hops",reply,sizeof(reply)) && !strcmp(reply,"> 7"));
|
||||
for(uint8_t limit:{0,3,7}) {
|
||||
char command[32]; snprintf(command,sizeof(command),"set mt.hops %u",limit);
|
||||
assert(node.handleMeshtextCommand(command,reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node._mt_hop_limit==limit && node._mt_region==mesh::mt::Region::Unset && node._mt_slot==0);
|
||||
assert(Preferences::blob.size()==40 && !memcmp(Preferences::blob.data(),"MT03",4));
|
||||
assert(Preferences::blob[5]==limit && Preferences::blob[6]==0 && Preferences::blob[7]==0);
|
||||
MyMesh reboot; reboot.stored[0]=node.stored[0]; reboot.beginMeshtext();
|
||||
assert(reboot._mt_hop_limit==limit && reboot._mt_active && reboot._mt_region==node._mt_region && reboot._mt_slot==node._mt_slot);
|
||||
assert(node.sendMeshtextText(node.stored[0],"hop",3));
|
||||
const auto& frame=node.foreign.back(); mesh::mt::DecodedText decoded;
|
||||
assert(mesh::mt::decodeText(frame.data(),frame.size(),"LongFast",mesh::mt::DefaultPsk,16,1,decoded));
|
||||
assert(decoded.hop_limit==limit && decoded.hop_start==limit && decoded.hops==0);
|
||||
assert(frame[12]==uint8_t(limit|(limit<<5))); node.foreign_pending=false;
|
||||
assertUntouched(reboot);
|
||||
}
|
||||
const auto writes=Preferences::writes; const auto committed=Preferences::blob;
|
||||
for(const char* invalid:{"set mt.hops 8","set mt.hops -1","set mt.hops 3junk",
|
||||
"set mt.hops 4294967296","set mt.hops 18446744073709551615","set mt.hops 3 extra"}) {
|
||||
assert(node.handleMeshtextCommand(invalid,reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(node._mt_hop_limit==7 && Preferences::writes==writes && Preferences::blob==committed);
|
||||
}
|
||||
assert(!node.saveMeshtextSettings(mesh::mt::Region::US,1,8));
|
||||
assert(node.handleMeshtextCommand("set mt.hops 3",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node.handleMeshtextCommand("set mt.region us",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node.handleMeshtextCommand("set mt.slot 2",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node._mt_hop_limit==3 && node._mt_region==mesh::mt::Region::US && node._mt_slot==2);
|
||||
assert(node.saveMeshtextSettings(mesh::mt::Region::ANZ,4)); // Two arguments preserve the hop setting.
|
||||
assert(node._mt_hop_limit==3 && node._mt_slot==4 && node._mt_region==mesh::mt::Region::ANZ);
|
||||
assert(node.handleMeshtextCommand("set mt.hops 0",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node._mt_slot==4 && node._mt_region==mesh::mt::Region::ANZ && node._mt_hop_limit==0);
|
||||
const auto before_pending=Preferences::blob; const auto pending_writes=Preferences::writes;
|
||||
node.foreign_pending=true;
|
||||
assert(node.handleMeshtextCommand("set mt.hops 7",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(node._mt_hop_limit==0 && node._mt_slot==4 && node._mt_region==mesh::mt::Region::ANZ);
|
||||
assert(Preferences::blob==before_pending && Preferences::writes==pending_writes); node.foreign_pending=false;
|
||||
Preferences::fail_write=true;
|
||||
assert(!node.saveMeshtextSettings(mesh::mt::Region::US,1,7));
|
||||
assert(node._mt_hop_limit==0 && node._mt_slot==4 && node._mt_region==mesh::mt::Region::ANZ);
|
||||
assert(Preferences::blob==before_pending && !node._mt_active && !node._mt_settings_valid);
|
||||
Preferences::fail_write=false;
|
||||
assert(node.saveMeshtextSettings(mesh::mt::Region::ANZ,4) && node._mt_hop_limit==0);
|
||||
assert(node.eraseMeshtextSettings() && node._mt_hop_limit==7);
|
||||
// Python hashlib supplies this legacy MT01 image independently. Loading it
|
||||
// defaults hops to seven without silently rewriting persistent settings.
|
||||
const uint8_t legacy[]=@LEGACY_SETTINGS@;
|
||||
Preferences::reset(); Preferences::blob.assign(legacy,legacy+sizeof(legacy));
|
||||
const auto legacy_blob=Preferences::blob; MyMesh migrated;
|
||||
migrated.stored[0]=channel("#mt-longfast"); migrated.beginMeshtext();
|
||||
assert(migrated._mt_settings_valid && migrated._mt_active && migrated._mt_hop_limit==7);
|
||||
assert(migrated._mt_region==mesh::mt::Region::US && migrated._mt_slot==2);
|
||||
assert(Preferences::writes==0 && Preferences::blob==legacy_blob);
|
||||
assert(migrated.handleMeshtextCommand("set mt.hops 3",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(Preferences::writes==1 && !memcmp(Preferences::blob.data(),"MT03",4) && Preferences::blob[5]==3);
|
||||
assert(migrated._mt_region==mesh::mt::Region::US && migrated._mt_slot==2);
|
||||
MyMesh migrated_reboot; migrated_reboot.stored[0]=migrated.stored[0]; migrated_reboot.beginMeshtext();
|
||||
assert(migrated_reboot._mt_active && migrated_reboot._mt_hop_limit==3);
|
||||
assert(migrated_reboot._mt_region==mesh::mt::Region::US && migrated_reboot._mt_slot==2);
|
||||
// Even a checksummed legacy reserved-byte change or MT02 out-of-range hop
|
||||
// value remains malformed, rather than becoming an undocumented option.
|
||||
Preferences::blob=legacy_blob; Preferences::blob[5]=1;
|
||||
mesh::Utils::sha256(Preferences::blob.data()+12,4,Preferences::blob.data(),12);
|
||||
MyMesh bad_legacy; bad_legacy.stored[0]=migrated.stored[0]; bad_legacy.beginMeshtext();
|
||||
assert(!bad_legacy._mt_settings_valid && !bad_legacy._mt_active);
|
||||
Preferences::blob=legacy_blob; memcpy(Preferences::blob.data(),"MT02",4); Preferences::blob[5]=8;
|
||||
mesh::Utils::sha256(Preferences::blob.data()+12,4,Preferences::blob.data(),12);
|
||||
MyMesh bad_hops; bad_hops.stored[0]=migrated.stored[0]; bad_hops.beginMeshtext();
|
||||
assert(!bad_hops._mt_settings_valid && !bad_hops._mt_active);
|
||||
assertUntouched(migrated); assertUntouched(migrated_reboot); puts("PASS hops");
|
||||
}
|
||||
static mesh::mt::DecodedText decodeOwnText(MyMesh& node,const char* text,size_t length) {
|
||||
node.foreign_pending=false;
|
||||
const uint32_t expected_packet=node._mt_packet_id;
|
||||
assert(node.sendMeshtextText(node.stored[0],text,length));
|
||||
const auto& raw=node.foreign.back(); mesh::mt::DecodedText decoded;
|
||||
assert(mesh::mt::decodeText(raw.data(),raw.size(),"LongFast",mesh::mt::DefaultPsk,16,1,decoded));
|
||||
assert(decoded.from==node._mt_node && decoded.id==expected_packet && node._mt_packet_id==expected_packet+1);
|
||||
node.foreign_pending=false; return decoded;
|
||||
}
|
||||
static void shortname() {
|
||||
Preferences::reset(); MyMesh node; active(node); char reply[256];
|
||||
uint8_t meshcore_identity[32]; memcpy(meshcore_identity,node.self_id.pub_key,32);
|
||||
const uint32_t default_node=@LOCAL_NODE@;
|
||||
assert(node._mt_node==default_node && node._mt_default_node==default_node && !node._mt_node_override);
|
||||
const uint32_t original_packet=node._mt_packet_id;
|
||||
assert(node.handleMeshtextCommand("set mt.shortname MIKE",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(!strcmp(node._mt_short_name,"MIKE") && node._mt_node==default_node && node._mt_packet_id==original_packet);
|
||||
assert(!memcmp(meshcore_identity,node.self_id.pub_key,32));
|
||||
assert(Preferences::blob.size()==40 && !memcmp(Preferences::blob.data(),"MT03",4));
|
||||
assert(!memcmp(Preferences::blob.data()+12,"MIKE\0",5));
|
||||
for(unsigned i=17;i<36;++i) assert(Preferences::blob[i]==0);
|
||||
assert(node.handleMeshtextCommand("get mt.shortname",reply,sizeof(reply)) && strstr(reply,"MIKE"));
|
||||
char node_id[12]; snprintf(node_id,sizeof(node_id),"!%08lx",(unsigned long)default_node);
|
||||
assert(node.handleMeshtextCommand("get mt.node",reply,sizeof(reply)) && strstr(reply,node_id));
|
||||
assert(node.handleMeshtextCommand("get mt.status",reply,sizeof(reply)) && strstr(reply,node_id));
|
||||
auto decoded=decodeOwnText(node,"identity",8);
|
||||
assert(!strcmp(decoded.text,"identity") && !strstr(decoded.text,"MIKE") && !strstr(decoded.text,node_id));
|
||||
strcpy(node._prefs.node_name,"Different MeshCore name");
|
||||
decoded=decodeOwnText(node,"unchanged",9);
|
||||
assert(decoded.from==default_node && !strcmp(decoded.text,"unchanged"));
|
||||
assert(node.handleMeshtextCommand("set mt.hops 3",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node.handleMeshtextCommand("set mt.region us",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node.handleMeshtextCommand("set mt.slot 2",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(!strcmp(node._mt_short_name,"MIKE") && node._mt_node==default_node && !node._mt_node_override);
|
||||
assert(node._mt_region==mesh::mt::Region::US && node._mt_slot==2 && node._mt_hop_limit==3);
|
||||
const char* four_emoji="\xf0\x9f\x98\x80\xf0\x9f\x98\x80\xf0\x9f\x98\x80\xf0\x9f\x98\x80";
|
||||
assert(node.saveMeshtextSettings(node._mt_region,node._mt_slot,UINT8_MAX,four_emoji));
|
||||
assert(strlen(node._mt_short_name)==16 && !strcmp(node._mt_short_name,four_emoji));
|
||||
assert(node._mt_hop_limit==3 && node._mt_node==default_node && !memcmp(meshcore_identity,node.self_id.pub_key,32));
|
||||
std::string body(229,'x');
|
||||
decoded=decodeOwnText(node,body.data(),228); assert(decoded.text_len==228);
|
||||
const auto admissions=node.foreign_admissions;
|
||||
assert(!node.sendMeshtextText(node.stored[0],body.data(),229) && node.foreign_admissions==admissions);
|
||||
auto persisted=Preferences::blob; const auto packet=node._mt_packet_id;
|
||||
for(const char* invalid:{"set mt.shortname ABCDE","set mt.shortname ",
|
||||
"set mt.shortname A:B","set mt.shortname A\nB","set mt.shortname \xc0\xaf",
|
||||
"set mt.shortname \xed\xa0\x80","set mt.shortname \xf4\x90\x80\x80",
|
||||
"set mt.shortname \xf0\x9f\x98", "set mt.shortname \xe2\x80\xae"}) {
|
||||
assert(node.handleMeshtextCommand(invalid,reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(Preferences::blob==persisted && !strcmp(node._mt_short_name,four_emoji));
|
||||
assert(node._mt_node==default_node && node._mt_packet_id==packet);
|
||||
}
|
||||
const auto writes=Preferences::writes; node.foreign_pending=true;
|
||||
assert(node.handleMeshtextCommand("set mt.shortname BOB",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(Preferences::writes==writes && Preferences::blob==persisted && !strcmp(node._mt_short_name,four_emoji));
|
||||
node.foreign_pending=false; Preferences::fail_write=true;
|
||||
assert(!node.saveMeshtextSettings(mesh::mt::Region::ANZ,4,7,"BOB"));
|
||||
assert(!strcmp(node._mt_short_name,four_emoji) && Preferences::blob==persisted);
|
||||
assert(node._mt_region==mesh::mt::Region::US && node._mt_slot==2 && node._mt_hop_limit==3);
|
||||
assert(!node._mt_active && !node._mt_settings_valid && node._mt_node==default_node && node._mt_packet_id==packet);
|
||||
Preferences::fail_write=false;
|
||||
assert(node.saveMeshtextSettings(node._mt_region,node._mt_slot));
|
||||
assert(!strcmp(node._mt_short_name,four_emoji));
|
||||
test_random_seed=0x87654321; MyMesh reboot; reboot.stored[0]=node.stored[0]; reboot.beginMeshtext();
|
||||
assert(reboot._mt_node==default_node && reboot._mt_default_node==default_node && !reboot._mt_node_override);
|
||||
assert(reboot._mt_packet_id==test_random_seed && !strcmp(reboot._mt_short_name,four_emoji));
|
||||
assert(reboot._mt_region==mesh::mt::Region::US && reboot._mt_slot==2 && reboot._mt_hop_limit==3);
|
||||
assertUntouched(reboot);
|
||||
assert(node.handleMeshtextCommand("set mt.shortname default",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(!node._mt_short_name[0] && node._mt_node==default_node && node._mt_packet_id==packet);
|
||||
memset(node._prefs.node_name,'A',31); node._prefs.node_name[31]=0;
|
||||
decoded=decodeOwnText(node,body.data(),228);
|
||||
assert(decoded.text_len==228 && !node.sendMeshtextText(node.stored[0],body.data(),229));
|
||||
node._prefs.node_name[0]=0;
|
||||
decoded=decodeOwnText(node,body.data(),228); assert(decoded.text_len==228 && !strstr(decoded.text,node_id));
|
||||
assert(!node.sendMeshtextText(node.stored[0],body.data(),229));
|
||||
// Validate both independently supplied 16-byte predecessors without writes.
|
||||
const uint8_t mt01[]=@LEGACY_SETTINGS@,mt02[]=@LEGACY_HOPS_SETTINGS@;
|
||||
for(unsigned version=0;version<2;++version) {
|
||||
Preferences::reset(); const auto* old=version?mt02:mt01; Preferences::blob.assign(old,old+16);
|
||||
const auto before=Preferences::blob; MyMesh legacy; legacy.stored[0]=channel("#mt-longfast"); legacy.beginMeshtext();
|
||||
assert(legacy._mt_active && legacy._mt_settings_valid && !legacy._mt_short_name[0] && !legacy._mt_node_override);
|
||||
assert(legacy._mt_node==default_node && legacy._mt_hop_limit==(version?3:7));
|
||||
assert(Preferences::writes==0 && Preferences::blob==before);
|
||||
assert(legacy.handleMeshtextCommand("set mt.shortname TEST",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(Preferences::writes==1 && Preferences::blob.size()==40 && !memcmp(Preferences::blob.data(),"MT03",4));
|
||||
assert(legacy._mt_region==mesh::mt::Region::US && legacy._mt_slot==2 && legacy._mt_hop_limit==(version?3:7));
|
||||
assertUntouched(legacy);
|
||||
}
|
||||
const auto valid_image=Preferences::blob;
|
||||
for(unsigned fault=0;fault<7;++fault) {
|
||||
Preferences::blob=valid_image;
|
||||
switch(fault) {
|
||||
case 0: memset(Preferences::blob.data()+12,'X',17); break; // no NUL
|
||||
case 1: Preferences::blob[14]=0; Preferences::blob[15]='X'; break; // non-canonical tail
|
||||
case 2: Preferences::blob[29]=1; break; // reserved padding
|
||||
case 3: memset(Preferences::blob.data()+12,0,17); Preferences::blob[12]=0xc0; Preferences::blob[13]=0xaf; break;
|
||||
case 4: memset(Preferences::blob.data()+12,0,17); memcpy(Preferences::blob.data()+12,"ABCDE",5); break;
|
||||
case 5: Preferences::blob[32]=3; break; // reserved override
|
||||
case 6: memset(Preferences::blob.data()+32,0xff,4); break;
|
||||
}
|
||||
mesh::Utils::sha256(Preferences::blob.data()+36,4,Preferences::blob.data(),36);
|
||||
MyMesh invalid; invalid.stored[0]=channel("#mt-longfast"); invalid.beginMeshtext();
|
||||
assert(!invalid._mt_settings_valid && !invalid._mt_active && !invalid.radio.p.enabled()); assertUntouched(invalid);
|
||||
}
|
||||
assert(!memcmp(meshcore_identity,node.self_id.pub_key,32)); puts("PASS shortname");
|
||||
}
|
||||
static void nodeOverride() {
|
||||
Preferences::reset(); MyMesh node; active(node); char reply[256];
|
||||
uint8_t identity[32]; memcpy(identity,node.self_id.pub_key,32);
|
||||
const uint32_t derived=@LOCAL_NODE@,packet=node._mt_packet_id;
|
||||
assert(node._mt_node==derived && node._mt_default_node==derived && !node._mt_node_override);
|
||||
for(const char* value:{"!12345678","ABCDEF01","00000004","fffffffe"}) {
|
||||
char command[64]; snprintf(command,sizeof(command),"set mt.node %s",value);
|
||||
const char* digits=value[0]=='!'?value+1:value; const uint32_t chosen=std::strtoul(digits,nullptr,16);
|
||||
const uint32_t next_packet=node._mt_packet_id;
|
||||
assert(node.handleMeshtextCommand(command,reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node._mt_node==chosen && node._mt_node_override==chosen && node._mt_default_node==derived);
|
||||
assert(node._mt_packet_id==next_packet && !memcmp(identity,node.self_id.pub_key,32));
|
||||
const uint32_t image_id=uint32_t(Preferences::blob[32])|(uint32_t(Preferences::blob[33])<<8)
|
||||
|(uint32_t(Preferences::blob[34])<<16)|(uint32_t(Preferences::blob[35])<<24);
|
||||
assert(image_id==chosen);
|
||||
char label[12]; snprintf(label,sizeof(label),"!%08lx",(unsigned long)chosen);
|
||||
assert(node.handleMeshtextCommand("get mt.node",reply,sizeof(reply)) && strstr(reply,label));
|
||||
auto decoded=decodeOwnText(node,"chosen",6); assert(decoded.from==chosen && !strcmp(decoded.text,"chosen"));
|
||||
MyMesh reboot; reboot.stored[0]=node.stored[0]; reboot.beginMeshtext();
|
||||
assert(reboot._mt_node==chosen && reboot._mt_node_override==chosen && reboot._mt_default_node==derived);
|
||||
assertUntouched(reboot);
|
||||
}
|
||||
assert(node._mt_packet_id==packet+4);
|
||||
assert(node.handleMeshtextCommand("set mt.shortname ID",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node.handleMeshtextCommand("set mt.region anz",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node.handleMeshtextCommand("set mt.slot 2",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node.handleMeshtextCommand("set mt.hops 3",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node._mt_node==0xfffffffe && node._mt_node_override==0xfffffffe && !strcmp(node._mt_short_name,"ID"));
|
||||
const auto blob=Preferences::blob; const auto next_packet=node._mt_packet_id,writes=Preferences::writes;
|
||||
for(const char* invalid:{"set mt.node 00000000","set mt.node !00000001","set mt.node 00000002",
|
||||
"set mt.node 00000003","set mt.node FFFFFFFF","set mt.node !ffffffff",
|
||||
"set mt.node 1234567","set mt.node 123456789","set mt.node 0x12345678",
|
||||
"set mt.node !1234567g","set mt.node !!12345678","set mt.node 12345678 extra"}) {
|
||||
assert(node.handleMeshtextCommand(invalid,reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(node._mt_node==0xfffffffe && node._mt_node_override==0xfffffffe && Preferences::blob==blob);
|
||||
assert(node._mt_packet_id==next_packet && Preferences::writes==writes);
|
||||
}
|
||||
node.foreign_pending=true;
|
||||
assert(node.handleMeshtextCommand("set mt.node !12345678",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(node._mt_node==0xfffffffe && Preferences::blob==blob && Preferences::writes==writes); node.foreign_pending=false;
|
||||
Preferences::fail_write=true;
|
||||
assert(!node.saveMeshtextSettings(mesh::mt::Region::US,1,7,"BOB",0x12345678));
|
||||
assert(node._mt_node==0xfffffffe && node._mt_node_override==0xfffffffe && !strcmp(node._mt_short_name,"ID"));
|
||||
assert(node._mt_region==mesh::mt::Region::ANZ && node._mt_slot==2 && node._mt_hop_limit==3);
|
||||
assert(node._mt_packet_id==next_packet && Preferences::blob==blob && !node._mt_active && !node._mt_settings_valid);
|
||||
Preferences::fail_write=false; assert(node.saveMeshtextSettings(node._mt_region,node._mt_slot));
|
||||
assert(node._mt_node==0xfffffffe && node._mt_node_override==0xfffffffe && node._mt_packet_id==next_packet);
|
||||
assert(node.handleMeshtextCommand("set mt.node default",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node._mt_node==derived && !node._mt_node_override && node._mt_packet_id==next_packet);
|
||||
assert(!strcmp(node._mt_short_name,"ID") && node._mt_region==mesh::mt::Region::ANZ && node._mt_slot==2 && node._mt_hop_limit==3);
|
||||
auto decoded=decodeOwnText(node,"default",7); assert(decoded.from==derived);
|
||||
// If NVS commits but readback fails, RAM keeps its prior identity while the
|
||||
// backend suspends. A fresh boot may then adopt the committed override.
|
||||
Preferences::fail_read=true; const uint32_t before_uncertain=node._mt_packet_id;
|
||||
assert(!node.saveMeshtextSettings(node._mt_region,node._mt_slot,UINT8_MAX,nullptr,0x12345678));
|
||||
assert(node._mt_node==derived && !node._mt_node_override && node._mt_packet_id==before_uncertain);
|
||||
assert(!node._mt_active && !node._mt_settings_valid); Preferences::fail_read=false;
|
||||
MyMesh reboot; reboot.stored[0]=node.stored[0]; reboot.beginMeshtext();
|
||||
assert(reboot._mt_node==0x12345678 && reboot._mt_node_override==0x12345678 && reboot._mt_default_node==derived);
|
||||
assert(!strcmp(reboot._mt_short_name,"ID") && reboot._mt_hop_limit==3);
|
||||
assert(!memcmp(identity,node.self_id.pub_key,32) && !memcmp(identity,reboot.self_id.pub_key,32));
|
||||
assertUntouched(reboot);
|
||||
// Exercise the actual identity-refresh lifecycle after the durable-import
|
||||
// boundary, independently hashing the imported public keys in Python.
|
||||
Preferences::reset(); MyMesh imported; active(imported);
|
||||
const auto original_sequence=imported._mt_packet_id;
|
||||
assert(imported._mt_seen.remember(0x11223344,101));
|
||||
const auto no_settings=Preferences::blob; const auto original_writes=Preferences::writes;
|
||||
imported.self_id.pub_key[0]=43; imported.refreshMeshtextIdentity();
|
||||
assert(imported._mt_default_node==@IMPORTED_NODE_43@ && imported._mt_node==@IMPORTED_NODE_43@);
|
||||
assert(!imported._mt_node_override && imported._mt_packet_id==original_sequence);
|
||||
assert(!imported._mt_seen.seen(0x11223344,101));
|
||||
assert(Preferences::blob==no_settings && Preferences::writes==original_writes);
|
||||
decoded=decodeOwnText(imported,"imported",8); assert(decoded.from==@IMPORTED_NODE_43@);
|
||||
assert(imported.handleMeshtextCommand("set mt.node !12345678",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
const auto overridden_sequence=imported._mt_packet_id; const auto overridden_settings=Preferences::blob;
|
||||
const auto overridden_writes=Preferences::writes;
|
||||
assert(imported._mt_seen.remember(0x11223344,102));
|
||||
imported.self_id.pub_key[0]=44; imported.refreshMeshtextIdentity();
|
||||
assert(imported._mt_default_node==@IMPORTED_NODE_44@ && imported._mt_node==0x12345678);
|
||||
assert(imported._mt_node_override==0x12345678 && imported._mt_packet_id==overridden_sequence);
|
||||
assert(!imported._mt_seen.seen(0x11223344,102));
|
||||
assert(Preferences::blob==overridden_settings && Preferences::writes==overridden_writes);
|
||||
decoded=decodeOwnText(imported,"override",8); assert(decoded.from==0x12345678);
|
||||
const auto reset_sequence=imported._mt_packet_id;
|
||||
assert(imported.handleMeshtextCommand("set mt.node default",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(imported._mt_node==@IMPORTED_NODE_44@ && imported._mt_default_node==@IMPORTED_NODE_44@);
|
||||
assert(!imported._mt_node_override && imported._mt_packet_id==reset_sequence);
|
||||
decoded=decodeOwnText(imported,"reset",5); assert(decoded.from==@IMPORTED_NODE_44@);
|
||||
assert(imported._mt_packet_id==original_sequence+3 && imported.self_id.pub_key[0]==44);
|
||||
puts("PASS node");
|
||||
}
|
||||
static void nodeinfo() {
|
||||
test_random_seed=0x12345678;
|
||||
Preferences::reset(); MyMesh node; active(node); char reply[256];
|
||||
assertUntouched(node);
|
||||
assert(node.handleMeshtextCommand("get mt.shortname",reply,sizeof(reply)));
|
||||
char fallback[5]; snprintf(fallback,sizeof(fallback),"%04lx",(unsigned long)(node._mt_node&0xffff));
|
||||
assert(strstr(reply,fallback) && strstr(reply,"manual NodeInfo only"));
|
||||
const uint8_t expected_default[]=@NODEINFO_DEFAULT@,expected_named[]=@NODEINFO_NAMED@,
|
||||
expected_utf8[]=@NODEINFO_UTF8@,expected_private[]=@NODEINFO_PRIVATE@;
|
||||
const auto original_settings=Preferences::blob; const auto original_writes=Preferences::writes;
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && strstr(reply,"queued"));
|
||||
assert(node.foreign.back()==std::vector<uint8_t>(expected_default,expected_default+sizeof(expected_default)));
|
||||
assert(node.foreign_profile==1 && node.foreign_generation==node.radio.p.generation[1]);
|
||||
assert(Preferences::blob==original_settings && Preferences::writes==original_writes);
|
||||
const auto pending_id=node._mt_packet_id; const auto pending_count=node.foreign.size();
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(node._mt_packet_id==pending_id && node.foreign.size()==pending_count);
|
||||
assert(!node.sendMeshtextText(node.stored[0],"busy",4));
|
||||
assert(!node.saveMeshtextSettings(mesh::mt::Region::US,0));
|
||||
node.foreign_pending=false;
|
||||
assert(node.handleMeshtextCommand("set mt.node !12345678",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
assert(node.handleMeshtextCommand("set mt.shortname MIKE",reply,sizeof(reply)) && !strncmp(reply,"OK",2));
|
||||
strcpy(node._prefs.node_name,"Mike Carper");
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && strstr(reply,"queued"));
|
||||
assert(node.foreign.back()==std::vector<uint8_t>(expected_named,expected_named+sizeof(expected_named)));
|
||||
node.foreign_pending=false;
|
||||
auto text=decodeOwnText(node,"hello",5);
|
||||
assert(text.id==0x1234567a && !strcmp(text.text,"hello"));
|
||||
const char* emojis="\xf0\x9f\x98\x80\xf0\x9f\x98\x80\xf0\x9f\x98\x80\xf0\x9f\x98\x80";
|
||||
assert(node.saveMeshtextSettings(node._mt_region,node._mt_slot,UINT8_MAX,emojis));
|
||||
memset(node._prefs.node_name,'A',22); strcpy(node._prefs.node_name+22,"\xe2\x82\xac" "rest");
|
||||
assert(node.handleMeshtextCommand("get mt.shortname",reply,sizeof(reply)) && strstr(reply,"effective=\xf0\x9f\x98\x80 ("));
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && strstr(reply,"queued"));
|
||||
assert(node.foreign.back()==std::vector<uint8_t>(expected_utf8,expected_utf8+sizeof(expected_utf8)));
|
||||
assert(strlen(node._prefs.node_name)==29 && strlen(node._mt_short_name)==16); // no mutation
|
||||
node.foreign_pending=false; node.commit(1,channel("mt-Team",32));
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 1",reply,sizeof(reply)) && strstr(reply,"queued"));
|
||||
assert(node.foreign.back()==std::vector<uint8_t>(expected_private,expected_private+sizeof(expected_private)));
|
||||
node.foreign_pending=false;
|
||||
const auto count=node.foreign.size(); const uint32_t packet=node._mt_packet_id;
|
||||
node.commit(2,channel("ordinary"));
|
||||
for(const char* bad:{"send mt.nodeinfo","send mt.nodeinfo ","send mt.nodeinfo -1",
|
||||
"send mt.nodeinfo 8","send mt.nodeinfo 4294967296","send mt.nodeinfo 999999999999999",
|
||||
"send mt.nodeinfo 0 extra","send mt.nodeinfo 2","send mt.nodeinfo 3"}) {
|
||||
assert(node.handleMeshtextCommand(bad,reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(node.foreign.size()==count && node._mt_packet_id==packet);
|
||||
}
|
||||
node.advance(3600000);
|
||||
assert(node.foreign.size()==count && node._mt_packet_id==packet); // no hourly/periodic advert
|
||||
node._radio_available=false; node.refreshMeshtextProfile();
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
node._radio_available=true; node.refreshMeshtextProfile();
|
||||
strcpy(node._prefs.node_name,"\xc0\xaf");
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(node.foreign.size()==count && node._mt_packet_id==packet);
|
||||
strcpy(node._prefs.node_name,"Test");
|
||||
node.admit_foreign=false;
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(node.foreign.size()==count && node._mt_packet_id==packet+1); // failed nonce never reused
|
||||
node.admit_foreign=true;
|
||||
node.cli("set radio2 906.875,250,11,5,rx,16"); node.advance(2000);
|
||||
assert(node._mt_active && !node.radio.p.canTransmit(1));
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
assert(node.foreign.size()==count && node._mt_packet_id==packet+1);
|
||||
node.cli("set radio2 off"); node.advance(2000);
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
node.cli("set radio2 auto"); node.advance(2000);
|
||||
node._mt_packet_id=UINT32_MAX;
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && strstr(reply,"queued"));
|
||||
node.foreign_pending=false;
|
||||
assert(node._mt_packet_id==0 && !node.sendMeshtextText(node.stored[0],"done",4));
|
||||
assert(node.handleMeshtextCommand("send mt.nodeinfo 0",reply,sizeof(reply)) && !strncmp(reply,"Error",5));
|
||||
MyMesh reboot; reboot.stored[0]=node.stored[0]; reboot.beginMeshtext();
|
||||
assertUntouched(reboot); assert(!node.meshcore_sends);
|
||||
puts("PASS nodeinfo");
|
||||
}
|
||||
int main(int argc,char** argv) {
|
||||
assert(argc==2);
|
||||
if(!strcmp(argv[1],"keys"))keys();
|
||||
else if(!strcmp(argv[1],"auto"))automatic();
|
||||
else if(!strcmp(argv[1],"conflicts"))conflicts();
|
||||
else if(!strcmp(argv[1],"manual"))manual();
|
||||
else if(!strcmp(argv[1],"settings"))settings();
|
||||
else if(!strcmp(argv[1],"receive"))receive();
|
||||
else if(!strcmp(argv[1],"transmit"))transmit();
|
||||
else if(!strcmp(argv[1],"commands"))commands();
|
||||
else if(!strcmp(argv[1],"cli"))privateCLI();
|
||||
else if(!strcmp(argv[1],"hops"))hops();
|
||||
else if(!strcmp(argv[1],"shortname"))shortname();
|
||||
else if(!strcmp(argv[1],"node"))nodeOverride();
|
||||
else if(!strcmp(argv[1],"nodeinfo"))nodeinfo();
|
||||
else assert(!"unknown test case");
|
||||
}
|
||||
@@ -393,6 +393,11 @@ TEST(CLICommandUtils, MasksTerminalPasswordInput) {
|
||||
const char* wifi = "set wifi.pwd secret phrase";
|
||||
EXPECT_STREQ("secret phrase", mesh::cli::terminalPasswordInput(wifi));
|
||||
EXPECT_EQ(nullptr, mesh::cli::terminalPasswordInput("set wifi.pwd "));
|
||||
EXPECT_FALSE(mesh::cli::shouldMaskTerminalInput("set mt.channel 1 mt-longfast "));
|
||||
EXPECT_FALSE(mesh::cli::shouldMaskTerminalInput("get mt.channel 1"));
|
||||
EXPECT_TRUE(mesh::cli::shouldMaskTerminalInput("set mt.channel 1 mt-longfast a"));
|
||||
EXPECT_STREQ("secret", mesh::cli::terminalPasswordInput("SET MT.CHANNEL 1 mt-Team secret"));
|
||||
EXPECT_STREQ("AQ==", mesh::cli::terminalPasswordInput("set mt.channel 1 mt-longfast AQ=="));
|
||||
}
|
||||
|
||||
TEST(CLICommandUtils, BackspaceErasesAsciiAndUtf8Characters) {
|
||||
|
||||
@@ -0,0 +1,656 @@
|
||||
"""Execute Companion channel aliases with independent SHA-256 test vectors."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from cpp_source import body
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HASH_NAMES = (
|
||||
"#emergency", "#r2-emergency", "#mt-emergency",
|
||||
"#custom", "#r2-custom", "#mt-custom",
|
||||
)
|
||||
|
||||
HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
#include <helpers/CompanionChannelAlias.h>
|
||||
|
||||
struct DigestVector { const char* text; uint8_t digest[32]; };
|
||||
static const DigestVector vectors[] = { @VECTORS@ };
|
||||
struct KeyDigestVector { uint8_t key[32]; size_t length; uint8_t digest[32]; };
|
||||
static const KeyDigestVector key_vectors[] = { @KEY_VECTORS@ };
|
||||
static void sha256(uint8_t* out, size_t out_length, const uint8_t* in, int in_length) {
|
||||
assert(out && in && in_length >= 0 && out_length <= 32);
|
||||
for (const auto& vector : vectors) {
|
||||
if (strlen(vector.text) == static_cast<size_t>(in_length)
|
||||
&& !memcmp(vector.text, in, in_length)) {
|
||||
memcpy(out, vector.digest, out_length);
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (const auto& vector : key_vectors) {
|
||||
if (vector.length == static_cast<size_t>(in_length) && !memcmp(vector.key, in, in_length)) {
|
||||
memcpy(out, vector.digest, out_length);
|
||||
return;
|
||||
}
|
||||
}
|
||||
assert(!"unexpected input to independent SHA-256 oracle");
|
||||
}
|
||||
static void hashtagKey(const char* name, uint8_t out[32]) {
|
||||
memset(out, 0, 32);
|
||||
sha256(out, 16, reinterpret_cast<const uint8_t*>(name), strlen(name));
|
||||
}
|
||||
static void assertAlias(const char* name, CompanionChannelKind kind,
|
||||
bool hashtag, const char* tail) {
|
||||
const auto parsed = parseCompanionChannelAlias(name);
|
||||
assert(parsed.kind == kind);
|
||||
assert(parsed.hashtag == hashtag);
|
||||
assert(parsed.tail && !strcmp(parsed.tail, tail));
|
||||
}
|
||||
static void grammar() {
|
||||
assertAlias("", CompanionChannelKind::MeshCore, false, "");
|
||||
assert(parseCompanionChannelAlias(nullptr).kind == CompanionChannelKind::Invalid);
|
||||
assertAlias("Public", CompanionChannelKind::MeshCore, false, "Public");
|
||||
assertAlias("#emergency", CompanionChannelKind::MeshCore, true, "emergency");
|
||||
assertAlias("r2-Public", CompanionChannelKind::Radio2, false, "Public");
|
||||
assertAlias("#r2-emergency", CompanionChannelKind::Radio2, true, "emergency");
|
||||
assertAlias("mt-LongFast", CompanionChannelKind::Meshtext, false, "LongFast");
|
||||
assertAlias("#mt-emergency", CompanionChannelKind::Meshtext, true, "emergency");
|
||||
// Routing markers must be complete, leading and case-sensitive.
|
||||
assertAlias("r2", CompanionChannelKind::MeshCore, false, "r2");
|
||||
assertAlias("mt", CompanionChannelKind::MeshCore, false, "mt");
|
||||
assertAlias("R2-Public", CompanionChannelKind::MeshCore, false, "R2-Public");
|
||||
assertAlias("#MT-emergency", CompanionChannelKind::MeshCore, true, "MT-emergency");
|
||||
assertAlias("room-r2-Public", CompanionChannelKind::MeshCore, false, "room-r2-Public");
|
||||
for (const auto* name : {"r2-", "#r2-", "mt-", "#mt-",
|
||||
"r2-#room", "mt-#room", "#r2-#room", "#mt-#room",
|
||||
"r2-r2-room", "r2-mt-room", "mt-r2-room", "mt-mt-room",
|
||||
"#r2-r2-room", "#r2-mt-room", "#mt-r2-room", "#mt-mt-room"}) {
|
||||
assert(parseCompanionChannelAlias(name).kind == CompanionChannelKind::Invalid);
|
||||
}
|
||||
puts("PASS grammar");
|
||||
}
|
||||
static void canonical() {
|
||||
struct Case { const char* display; const char* canonical; };
|
||||
const Case cases[] = {{"Public", "Public"}, {"#emergency", "#emergency"},
|
||||
{"r2-Public", "Public"}, {"#r2-emergency", "#emergency"},
|
||||
{"mt-LongFast", "LongFast"}, {"#mt-emergency", "#emergency"}};
|
||||
for (const auto& item : cases) {
|
||||
char output[40];
|
||||
assert(companionChannelCanonicalName(item.display, output, sizeof(output)));
|
||||
assert(!strcmp(output, item.canonical));
|
||||
// The exact terminating-NUL boundary must be accepted, never truncated.
|
||||
assert(companionChannelCanonicalName(item.display, output, strlen(item.canonical) + 1));
|
||||
assert(!strcmp(output, item.canonical));
|
||||
assert(!companionChannelCanonicalName(item.display, output, strlen(item.canonical)));
|
||||
}
|
||||
char output[40];
|
||||
assert(!companionChannelCanonicalName("#mt-", output, sizeof(output)));
|
||||
assert(!companionChannelCanonicalName("#r2-mt-room", output, sizeof(output)));
|
||||
assert(!companionChannelCanonicalName("#r2-emergency", nullptr, 40));
|
||||
assert(!companionChannelCanonicalName(nullptr, output, sizeof(output)));
|
||||
assert(!companionChannelCanonicalName("#r2-emergency", output, 0));
|
||||
puts("PASS canonical");
|
||||
}
|
||||
static void keys() {
|
||||
uint8_t canonical[32], alias[32], key[32], before[32];
|
||||
hashtagKey("#emergency", canonical);
|
||||
// Fixed published emergency vector also checks the Python-generated oracle.
|
||||
const uint8_t emergency[16] = {0xe1,0xad,0x57,0x8d,0x25,0x10,0x8e,0x34,
|
||||
0x48,0x08,0xf3,0x0d,0xfd,0xaa,0xf9,0x26};
|
||||
assert(!memcmp(canonical, emergency, sizeof(emergency)));
|
||||
for (const auto* name : {"#r2-emergency", "#mt-emergency"}) {
|
||||
hashtagKey(name, alias);
|
||||
memcpy(key, alias, 32);
|
||||
resolveCompanionChannelKey(name, key, sha256);
|
||||
assert(!memcmp(key, canonical, 32));
|
||||
// A second resolution of a wire copy must not derive a new key.
|
||||
resolveCompanionChannelKey(name, key, sha256);
|
||||
assert(!memcmp(key, canonical, 32));
|
||||
assert(memcmp(alias, canonical, 16));
|
||||
}
|
||||
hashtagKey("#custom", canonical);
|
||||
for (const auto* name : {"#r2-custom", "#mt-custom"}) {
|
||||
hashtagKey(name, key);
|
||||
resolveCompanionChannelKey(name, key, sha256);
|
||||
assert(!memcmp(key, canonical, 32));
|
||||
}
|
||||
// Unprefixed hashtag keys and non-hashtag channel keys retain exact bytes.
|
||||
hashtagKey("#emergency", key); memcpy(before, key, 32);
|
||||
resolveCompanionChannelKey("#emergency", key, sha256);
|
||||
assert(!memcmp(key, before, 32));
|
||||
for (const auto* name : {"Public", "r2-Public", "mt-LongFast",
|
||||
"#r2-emergency", "#mt-emergency", "#r2-mt-room"}) {
|
||||
for (size_t i = 0; i < 16; ++i) key[i] = static_cast<uint8_t>(i + 1);
|
||||
memset(key + 16, 0, 16); memcpy(before, key, 32);
|
||||
resolveCompanionChannelKey(name, key, sha256);
|
||||
assert(!memcmp(key, before, 32));
|
||||
// A 256-bit custom PSK whose first half happens to equal the alias hash
|
||||
// must remain a 256-bit key, rather than being replaced by a public key.
|
||||
hashtagKey("#r2-emergency", key);
|
||||
for (size_t i = 16; i < 32; ++i) key[i] = static_cast<uint8_t>(i + 1);
|
||||
memcpy(before, key, 32);
|
||||
resolveCompanionChannelKey(name, key, sha256);
|
||||
assert(!memcmp(key, before, 32));
|
||||
}
|
||||
puts("PASS keys");
|
||||
}
|
||||
static void receive() {
|
||||
for (const auto* name : {"Public", "#emergency"}) {
|
||||
assert(companionChannelReceivePriority(name, 0) == 0);
|
||||
assert(companionChannelReceivePriority(name, 1) == 1);
|
||||
assert(companionChannelReceivePriority(name, 0, false) == 0);
|
||||
assert(companionChannelReceivePriority(name, 1, false) == 1);
|
||||
}
|
||||
for (const auto* name : {"r2-Public", "#r2-emergency"}) {
|
||||
assert(companionChannelReceivePriority(name, 0) == -1);
|
||||
assert(companionChannelReceivePriority(name, 1) == 0);
|
||||
assert(companionChannelReceivePriority(name, 0, false) == 0);
|
||||
assert(companionChannelReceivePriority(name, 1, false) == 1);
|
||||
}
|
||||
for (const auto* name : {"mt-LongFast", "#mt-emergency"}) {
|
||||
assert(companionChannelReceivePriority(name, 0) == -1);
|
||||
assert(companionChannelReceivePriority(name, 1) == -1);
|
||||
// Without a configured radio2, either prefix behaves as ordinary MeshCore.
|
||||
assert(companionChannelReceivePriority(name, 0, false) == 0);
|
||||
assert(companionChannelReceivePriority(name, 1, false) == 1);
|
||||
}
|
||||
for (const auto* name : {"#mt-", "#r2-mt-emergency"}) {
|
||||
for (uint8_t origin : {0, 1}) {
|
||||
assert(companionChannelReceivePriority(name, origin, true) == -1);
|
||||
assert(companionChannelReceivePriority(name, origin, false) == -1);
|
||||
}
|
||||
}
|
||||
puts("PASS receive");
|
||||
}
|
||||
int main(int argc, char** argv) {
|
||||
assert(argc == 2);
|
||||
if (!strcmp(argv[1], "grammar")) grammar();
|
||||
else if (!strcmp(argv[1], "canonical")) canonical();
|
||||
else if (!strcmp(argv[1], "keys")) keys();
|
||||
else if (!strcmp(argv[1], "receive")) receive();
|
||||
else assert(!"unknown test case");
|
||||
}
|
||||
'''
|
||||
|
||||
RUNTIME_HARNESS = r'''
|
||||
#include <RadioProfiles.h>
|
||||
#define MAX_GROUP_CHANNELS 5
|
||||
#define MAX_PACKET_PAYLOAD 255
|
||||
namespace mesh {
|
||||
struct GroupChannel { uint8_t secret[32] = {}, hash[1] = {}, tx_radio = RADIO_TX_AUTO; };
|
||||
struct Packet { uint8_t radio_origin = 0, tx_radio = RADIO_TX_AUTO;
|
||||
uint8_t payload[MAX_PACKET_PAYLOAD] = {}; int payload_len = 0; };
|
||||
struct Utils {
|
||||
static void sha256(uint8_t* out, size_t length, const uint8_t* in, int in_length) {
|
||||
::sha256(out, length, in, in_length);
|
||||
}
|
||||
static bool isZeroes(const uint8_t* bytes, size_t length) {
|
||||
for (size_t i = 0; i < length; ++i) if (bytes[i]) return false;
|
||||
return true;
|
||||
}
|
||||
// The native test exercises the caller's authenticated-key gating, while
|
||||
// substituting only the cipher primitive with an explicit key-match oracle.
|
||||
static int MACThenDecrypt(const uint8_t* key, uint8_t*, const uint8_t* data, int length) {
|
||||
return length == 16 && !memcmp(key, data, 16) ? 1 : 0;
|
||||
}
|
||||
};
|
||||
}
|
||||
struct ChannelDetails { mesh::GroupChannel channel; char name[32] = {}; };
|
||||
struct Radio { mesh::RadioProfiles config; bool present = true;
|
||||
mesh::RadioProfiles* profiles() { return present ? &config : nullptr; } };
|
||||
class BaseChatMesh {
|
||||
public:
|
||||
ChannelDetails stored[MAX_GROUP_CHANNELS]; unsigned delivered = 0;
|
||||
bool getChannel(int index, ChannelDetails& channel) {
|
||||
if (index < 0 || index >= MAX_GROUP_CHANNELS) return false;
|
||||
channel = stored[index]; return true;
|
||||
}
|
||||
bool setChannel(int index, const ChannelDetails& channel) {
|
||||
if (index < 0 || index >= MAX_GROUP_CHANNELS) return false;
|
||||
stored[index] = channel;
|
||||
mesh::Utils::sha256(stored[index].channel.hash, sizeof(stored[index].channel.hash),
|
||||
channel.channel.secret,
|
||||
mesh::Utils::isZeroes(channel.channel.secret + 16, 16) ? 16 : 32);
|
||||
return true;
|
||||
}
|
||||
void onGroupDataRecv(mesh::Packet*, uint8_t, const mesh::GroupChannel&, uint8_t*, size_t) {
|
||||
++delivered;
|
||||
}
|
||||
};
|
||||
class MyMesh : public BaseChatMesh {
|
||||
public:
|
||||
Radio radio; Radio* _radio = &radio;
|
||||
bool isAliasRadio2Defined() const;
|
||||
bool resolveChannelAlias(ChannelDetails&) const;
|
||||
bool getChannel(int, ChannelDetails&);
|
||||
bool setChannel(int, const ChannelDetails&);
|
||||
int searchChannelsForPacket(const mesh::Packet*, const uint8_t*, mesh::GroupChannel[], int);
|
||||
int findChannelIdxForPacket(const mesh::GroupChannel&, const mesh::Packet*);
|
||||
bool allowGroupPacketOnRadio(mesh::Packet*);
|
||||
void onGroupDataRecv(mesh::Packet*, uint8_t, const mesh::GroupChannel&, uint8_t*, size_t);
|
||||
@SAVE_GETTER@
|
||||
};
|
||||
@METHODS@
|
||||
static ChannelDetails channel(const char* name) {
|
||||
ChannelDetails value;
|
||||
strcpy(value.name, name);
|
||||
hashtagKey(name, value.channel.secret);
|
||||
return value;
|
||||
}
|
||||
int main() {
|
||||
MyMesh node;
|
||||
node.radio.config.secondary.mode = mesh::RadioProfileMode::RxTx;
|
||||
auto ordinary = channel("#emergency");
|
||||
auto secondary = channel("#r2-emergency");
|
||||
auto mt = channel("#mt-emergency");
|
||||
ordinary.channel.tx_radio = mesh::RADIO_TX_BOTH;
|
||||
secondary.channel.tx_radio = mesh::RADIO_TX_PRIMARY;
|
||||
mt.channel.tx_radio = mesh::RADIO_TX_BOTH;
|
||||
assert(node.setChannel(0, ordinary));
|
||||
assert(node.setChannel(1, secondary));
|
||||
assert(node.setChannel(2, mt));
|
||||
ChannelDetails wire, raw;
|
||||
assert(node.getChannel(1, wire));
|
||||
assert(wire.channel.tx_radio == mesh::RADIO_TX_SECONDARY);
|
||||
assert(!memcmp(wire.channel.secret, ordinary.channel.secret, 32));
|
||||
uint8_t expected_hash;
|
||||
sha256(&expected_hash, 1, ordinary.channel.secret, 16);
|
||||
assert(wire.channel.hash[0] == expected_hash);
|
||||
assert(node.getChannelForSave(1, raw));
|
||||
assert(!strcmp(raw.name, secondary.name));
|
||||
assert(!memcmp(raw.channel.secret, secondary.channel.secret, 32));
|
||||
assert(raw.channel.tx_radio == mesh::RADIO_TX_PRIMARY);
|
||||
// Applying the raw GET/persistence representation again must be idempotent.
|
||||
assert(node.setChannel(1, raw) && node.getChannel(1, wire));
|
||||
assert(!memcmp(wire.channel.secret, ordinary.channel.secret, 32));
|
||||
assert(node.getChannel(2, wire));
|
||||
assert(wire.channel.tx_radio == mesh::RADIO_TX_OFF);
|
||||
assert(!memcmp(wire.channel.secret, ordinary.channel.secret, 32));
|
||||
assert(node.getChannelForSave(2, raw));
|
||||
assert(!memcmp(raw.channel.secret, mt.channel.secret, 32));
|
||||
assert(raw.channel.tx_radio == mesh::RADIO_TX_BOTH);
|
||||
// Both Rx and RxTx define the secondary profile. The real RadioProfiles
|
||||
// transmit permission remains distinct from the channel's routing policy.
|
||||
for (auto mode : {mesh::RadioProfileMode::Rx, mesh::RadioProfileMode::RxTx}) {
|
||||
node.radio.config.secondary.mode = mode;
|
||||
assert(node.isAliasRadio2Defined());
|
||||
assert(node.getChannel(0, wire) && wire.channel.tx_radio == mesh::RADIO_TX_BOTH);
|
||||
assert(node.getChannel(1, wire) && wire.channel.tx_radio == mesh::RADIO_TX_SECONDARY);
|
||||
assert(node.getChannel(2, wire) && wire.channel.tx_radio == mesh::RADIO_TX_OFF);
|
||||
assert(node.radio.config.canTransmit(1) == (mode == mesh::RadioProfileMode::RxTx));
|
||||
}
|
||||
|
||||
mesh::Packet packet;
|
||||
packet.payload[0] = wire.channel.hash[0]; packet.payload_len = 17;
|
||||
memcpy(packet.payload + 1, ordinary.channel.secret, 16);
|
||||
mesh::GroupChannel matches[4];
|
||||
assert(node.allowGroupPacketOnRadio(&packet));
|
||||
assert(packet.tx_radio == mesh::RADIO_TX_AUTO); // the ordinary primary slot wins
|
||||
assert(node.searchChannelsForPacket(&packet, packet.payload, matches, 4) == 1);
|
||||
assert(node.findChannelIdxForPacket(matches[0], &packet) == 0);
|
||||
packet.radio_origin = 1;
|
||||
assert(node.allowGroupPacketOnRadio(&packet));
|
||||
assert(packet.tx_radio == mesh::RADIO_TX_SECONDARY); // bound before local delivery
|
||||
assert(node.searchChannelsForPacket(&packet, packet.payload, matches, 4) == 1);
|
||||
assert(node.findChannelIdxForPacket(matches[0], &packet) == 1);
|
||||
uint8_t data = 0;
|
||||
node.onGroupDataRecv(&packet, 0, matches[0], &data, 1);
|
||||
assert(node.delivered == 1 && packet.tx_radio == mesh::RADIO_TX_SECONDARY);
|
||||
|
||||
ChannelDetails empty;
|
||||
assert(node.setChannel(0, empty));
|
||||
packet.tx_radio = mesh::RADIO_TX_AUTO;
|
||||
assert(node.allowGroupPacketOnRadio(&packet));
|
||||
assert(packet.tx_radio == mesh::RADIO_TX_SECONDARY); // alias-only secondary admission
|
||||
packet.radio_origin = 0;
|
||||
packet.tx_radio = mesh::RADIO_TX_AUTO;
|
||||
assert(!node.allowGroupPacketOnRadio(&packet)); // authenticated alias on wrong radio
|
||||
assert(packet.tx_radio == mesh::RADIO_TX_AUTO);
|
||||
packet.payload[1] ^= 1;
|
||||
assert(node.allowGroupPacketOnRadio(&packet)); // hash match alone is insufficient
|
||||
packet.payload[1] ^= 1;
|
||||
assert(node.setChannel(1, empty));
|
||||
for (uint8_t origin : {0, 1}) {
|
||||
packet.radio_origin = origin;
|
||||
assert(node.searchChannelsForPacket(&packet, packet.payload, matches, 4) == 0);
|
||||
assert(node.findChannelIdxForPacket(wire.channel, &packet) == -1);
|
||||
assert(!node.allowGroupPacketOnRadio(&packet)); // configured MT cannot enter MeshCore
|
||||
uint8_t blocked_data = 0;
|
||||
const auto before_delivery = node.delivered;
|
||||
node.onGroupDataRecv(&packet, 0, wire.channel, &blocked_data, 1);
|
||||
assert(node.delivered == before_delivery);
|
||||
}
|
||||
// Both disabled secondary profile and an absent profile ignore routing markers.
|
||||
for (bool absent : {false, true}) {
|
||||
node.radio.config.secondary.mode = mesh::RadioProfileMode::Off; node.radio.present = !absent;
|
||||
assert(!node.isAliasRadio2Defined());
|
||||
assert(node.getChannel(2, wire) && wire.channel.tx_radio == mesh::RADIO_TX_BOTH);
|
||||
assert(!memcmp(wire.channel.secret, ordinary.channel.secret, 32));
|
||||
for (uint8_t origin : {0, 1}) {
|
||||
packet.radio_origin = origin;
|
||||
assert(node.allowGroupPacketOnRadio(&packet));
|
||||
assert(node.searchChannelsForPacket(&packet, packet.payload, matches, 4) == 1);
|
||||
assert(node.findChannelIdxForPacket(matches[0], &packet) == 2);
|
||||
}
|
||||
assert(node.setChannel(1, secondary) && node.getChannel(1, wire));
|
||||
assert(wire.channel.tx_radio == mesh::RADIO_TX_PRIMARY);
|
||||
assert(!memcmp(wire.channel.secret, ordinary.channel.secret, 32));
|
||||
assert(node.setChannel(1, empty));
|
||||
}
|
||||
// Custom private keys survive both wire resolution and storage access.
|
||||
ChannelDetails custom = secondary;
|
||||
for (size_t i = 0; i < 16; ++i) custom.channel.secret[i] = static_cast<uint8_t>(i + 1);
|
||||
assert(node.setChannel(3, custom) && node.getChannel(3, wire));
|
||||
assert(!memcmp(wire.channel.secret, custom.channel.secret, 32));
|
||||
assert(node.getChannelForSave(3, raw));
|
||||
assert(!memcmp(raw.channel.secret, custom.channel.secret, 32));
|
||||
custom = secondary;
|
||||
for (size_t i = 16; i < 32; ++i) custom.channel.secret[i] = static_cast<uint8_t>(i + 1);
|
||||
assert(node.setChannel(3, custom) && node.getChannel(3, wire));
|
||||
assert(!memcmp(wire.channel.secret, custom.channel.secret, 32));
|
||||
assert(node.getChannelForSave(3, raw));
|
||||
assert(!memcmp(raw.channel.secret, custom.channel.secret, 32));
|
||||
strcpy(custom.name, "#r2-mt-room");
|
||||
assert(!node.setChannel(3, custom));
|
||||
assert(!node.getChannel(-1, wire) && !node.setChannel(MAX_GROUP_CHANNELS, custom));
|
||||
puts("PASS runtime raw/wire keys, receive aliases and radio2 fallback");
|
||||
}
|
||||
'''
|
||||
|
||||
COMMAND_STUBS = r'''
|
||||
struct StrHelper {
|
||||
static void strncpy(char* out, const char* in, size_t length) {
|
||||
assert(length > 0);
|
||||
::strncpy(out, in, length - 1); out[length - 1] = 0;
|
||||
}
|
||||
};
|
||||
struct Serial {
|
||||
uint8_t frame[128] = {}; int length = 0;
|
||||
void writeFrame(const uint8_t* data, int size) {
|
||||
assert(size >= 0 && size <= static_cast<int>(sizeof(frame)));
|
||||
memcpy(frame, data, size); length = size;
|
||||
}
|
||||
};
|
||||
'''
|
||||
|
||||
COMMAND_MEMBERS = r'''
|
||||
Serial serial; Serial* _serial = &serial;
|
||||
bool save_result = true, ok = false; int error = -1; unsigned save_calls = 0;
|
||||
bool saveChannels() { ++save_calls; return save_result; }
|
||||
void writeErrFrame(uint8_t code) { error = code; }
|
||||
void writeOKFrame() { ok = true; }
|
||||
void command(uint8_t*, int);
|
||||
'''
|
||||
|
||||
COMMAND_HARNESS = r'''
|
||||
void MyMesh::command(uint8_t* cmd_frame, int len) {
|
||||
uint8_t out_frame[128] = {};
|
||||
error = -1; ok = false; serial.length = 0;
|
||||
@COMMAND_BRANCHES@
|
||||
}
|
||||
static void applySet(MyMesh& node, uint8_t index, const ChannelDetails& value, int key_bytes = 16) {
|
||||
uint8_t frame[66] = {CMD_SET_CHANNEL, index};
|
||||
memcpy(frame + 2, value.name, 32);
|
||||
memcpy(frame + 34, value.channel.secret, key_bytes);
|
||||
node.command(frame, 34 + key_bytes);
|
||||
}
|
||||
static void expectRaw(MyMesh& node, uint8_t index, const ChannelDetails& expected) {
|
||||
ChannelDetails raw;
|
||||
assert(node.getChannelForSave(index, raw));
|
||||
assert(!strcmp(raw.name, expected.name));
|
||||
assert(!memcmp(raw.channel.secret, expected.channel.secret, 32));
|
||||
assert(raw.channel.tx_radio == expected.channel.tx_radio);
|
||||
}
|
||||
static void expectGet(MyMesh& node, uint8_t index, const ChannelDetails& expected) {
|
||||
uint8_t command[2] = {CMD_GET_CHANNEL, index};
|
||||
node.command(command, sizeof(command));
|
||||
assert(node.error == -1 && !node.ok && node.serial.length == 50);
|
||||
assert(node.serial.frame[0] == RESP_CODE_CHANNEL_INFO && node.serial.frame[1] == index);
|
||||
assert(!strcmp(reinterpret_cast<const char*>(node.serial.frame + 2), expected.name));
|
||||
assert(!memcmp(node.serial.frame + 34, expected.channel.secret, 16));
|
||||
}
|
||||
int main() {
|
||||
MyMesh node;
|
||||
node.radio.config.secondary.mode = mesh::RadioProfileMode::RxTx;
|
||||
auto original = channel("#r2-emergency");
|
||||
original.channel.tx_radio = mesh::RADIO_TX_BOTH;
|
||||
assert(node.setChannel(0, original));
|
||||
expectGet(node, 0, original);
|
||||
ChannelDetails wire;
|
||||
assert(node.getChannel(0, wire));
|
||||
assert(memcmp(node.serial.frame + 34, wire.channel.secret, 16)); // GET is not the wire key
|
||||
|
||||
// Switching the display alias without changing the canonical key preserves
|
||||
// the user's raw manual policy, not the alias's effective secondary policy.
|
||||
auto ordinary = channel("#emergency");
|
||||
applySet(node, 0, ordinary);
|
||||
assert(node.ok && node.error == -1 && node.save_calls == 1);
|
||||
ordinary.channel.tx_radio = mesh::RADIO_TX_BOTH;
|
||||
expectRaw(node, 0, ordinary);
|
||||
applySet(node, 0, original);
|
||||
assert(node.ok && node.error == -1 && node.save_calls == 2);
|
||||
expectRaw(node, 0, original);
|
||||
expectGet(node, 0, original);
|
||||
|
||||
// Failed persistence restores the exact app representation. In particular,
|
||||
// it must not replace the stored prefixed hashtag key with its wire key.
|
||||
node.save_result = false;
|
||||
const auto replacement = channel("#r2-custom");
|
||||
applySet(node, 0, replacement);
|
||||
assert(!node.ok && node.error == ERR_CODE_FILE_IO_ERROR && node.save_calls == 3);
|
||||
expectRaw(node, 0, original);
|
||||
expectGet(node, 0, original);
|
||||
node.save_result = true;
|
||||
|
||||
// A genuinely different private PSK resets manual routing to AUTO.
|
||||
auto private_channel = original;
|
||||
for (size_t i = 0; i < 16; ++i) private_channel.channel.secret[i] = static_cast<uint8_t>(i + 1);
|
||||
private_channel.channel.tx_radio = mesh::RADIO_TX_AUTO;
|
||||
applySet(node, 0, private_channel);
|
||||
assert(node.ok && node.error == -1 && node.save_calls == 4);
|
||||
expectRaw(node, 0, private_channel);
|
||||
assert(node.getChannel(0, wire));
|
||||
assert(!memcmp(wire.channel.secret, private_channel.channel.secret, 32));
|
||||
// Reapplying an unchanged private key retains an explicitly saved policy.
|
||||
private_channel.channel.tx_radio = mesh::RADIO_TX_PRIMARY;
|
||||
assert(node.setChannel(0, private_channel));
|
||||
applySet(node, 0, private_channel);
|
||||
assert(node.ok && node.error == -1 && node.save_calls == 5);
|
||||
expectRaw(node, 0, private_channel);
|
||||
|
||||
auto invalid = private_channel;
|
||||
strcpy(invalid.name, "#r2-mt-emergency");
|
||||
applySet(node, 0, invalid);
|
||||
assert(!node.ok && node.error == ERR_CODE_ILLEGAL_ARG && node.save_calls == 5);
|
||||
expectRaw(node, 0, private_channel);
|
||||
const auto mt = channel("#mt-emergency");
|
||||
applySet(node, 0, mt);
|
||||
assert(!node.ok && node.error == ERR_CODE_UNSUPPORTED_CMD && node.save_calls == 5);
|
||||
expectRaw(node, 0, private_channel);
|
||||
|
||||
// Disabled or absent radio2 permits the MT display marker only as an
|
||||
// ordinary MeshCore channel; it does not activate Meshtext transport.
|
||||
node.radio.config.secondary.mode = mesh::RadioProfileMode::Off;
|
||||
applySet(node, 0, mt);
|
||||
assert(node.ok && node.error == -1 && node.save_calls == 6);
|
||||
expectRaw(node, 0, mt);
|
||||
expectGet(node, 0, mt);
|
||||
assert(node.getChannel(0, wire));
|
||||
assert(wire.channel.tx_radio == mesh::RADIO_TX_AUTO);
|
||||
assert(!memcmp(wire.channel.secret, ordinary.channel.secret, 32));
|
||||
node.radio.present = false;
|
||||
applySet(node, 0, mt);
|
||||
assert(node.ok && node.error == -1 && node.save_calls == 7);
|
||||
expectRaw(node, 0, mt);
|
||||
|
||||
// Binary framing remains 128-bit only; larger keys are not silently cut.
|
||||
applySet(node, 0, mt, 32);
|
||||
assert(!node.ok && node.error == ERR_CODE_UNSUPPORTED_CMD && node.save_calls == 7);
|
||||
expectRaw(node, 0, mt);
|
||||
applySet(node, MAX_GROUP_CHANNELS, mt);
|
||||
assert(!node.ok && node.error == ERR_CODE_NOT_FOUND && node.save_calls == 7);
|
||||
uint8_t bad_get[] = {CMD_GET_CHANNEL, MAX_GROUP_CHANNELS};
|
||||
node.command(bad_get, sizeof(bad_get));
|
||||
assert(node.error == ERR_CODE_NOT_FOUND && node.serial.length == 0);
|
||||
puts("PASS command raw GET, canonical-key SET, rollback and unsupported transport");
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def oracle_vectors():
|
||||
vectors = ",\n".join(
|
||||
"{" + json.dumps(name) + ",{" + ",".join(map(str, hashlib.sha256(name.encode()).digest())) + "}}"
|
||||
for name in HASH_NAMES
|
||||
)
|
||||
keys = [hashlib.sha256(name.encode()).digest()[:16] for name in HASH_NAMES]
|
||||
keys += [bytes(16), bytes(range(1, 17)),
|
||||
hashlib.sha256(b"#r2-emergency").digest()[:16] + bytes(range(17, 33))]
|
||||
key_vectors = ",\n".join(
|
||||
"{{" + ",".join(map(str, key)) + "}," + str(len(key)) + ",{" +
|
||||
",".join(map(str, hashlib.sha256(key).digest())) + "}}" for key in keys
|
||||
)
|
||||
return vectors, key_vectors
|
||||
|
||||
|
||||
class CompanionChannelAliasTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
raise unittest.SkipTest("a host C++ compiler is required")
|
||||
cls.temporary = tempfile.TemporaryDirectory(prefix="meshcore-channel-alias-")
|
||||
cls.addClassCleanup(cls.temporary.cleanup)
|
||||
work = Path(cls.temporary.name)
|
||||
cls.binary = work / ("alias.exe" if sys.platform == "win32" else "alias")
|
||||
vectors, key_vectors = oracle_vectors()
|
||||
source = work / "alias.cpp"
|
||||
source.write_text(HARNESS.replace("@VECTORS@", vectors).replace("@KEY_VECTORS@", key_vectors), encoding="utf-8")
|
||||
sanitizers = (["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
|
||||
"-fno-pie", "-no-pie"] if sys.platform.startswith("linux") else [])
|
||||
built = subprocess.run(
|
||||
[compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror", *sanitizers,
|
||||
"-I" + str(ROOT / "src"), str(source), "-o", str(cls.binary)],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
if built.returncode:
|
||||
raise AssertionError(built.stdout + built.stderr)
|
||||
|
||||
def run_case(self, case):
|
||||
checked = subprocess.run([str(self.binary), case], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
|
||||
self.assertIn("PASS " + case, checked.stdout)
|
||||
|
||||
def test_prefix_grammar(self):
|
||||
self.run_case("grammar")
|
||||
|
||||
def test_canonical_names_and_output_bounds(self):
|
||||
self.run_case("canonical")
|
||||
|
||||
def test_independent_sha256_vectors_and_custom_keys(self):
|
||||
self.run_case("keys")
|
||||
|
||||
def test_receive_priority_and_unconfigured_radio2_fallback(self):
|
||||
self.run_case("receive")
|
||||
|
||||
def test_core_admission_precedes_group_seen_and_direct_forward(self):
|
||||
core = (ROOT / "src/Mesh.cpp").read_text(encoding="utf-8")
|
||||
received = body(core, "DispatcherAction Mesh::onRecvPacket(Packet* pkt)")
|
||||
gate = re.search(
|
||||
r"if\s*\(\(pkt->getPayloadType\(\)\s*==\s*PAYLOAD_TYPE_GRP_TXT\s*"
|
||||
r"\|\|\s*pkt->getPayloadType\(\)\s*==\s*PAYLOAD_TYPE_GRP_DATA\)\s*"
|
||||
r"&&\s*!allowGroupPacketOnRadio\(pkt\)\)\s*return ACTION_RELEASE;", received,
|
||||
)
|
||||
self.assertIsNotNone(gate, "both encrypted group types must pass admission")
|
||||
# TRACE has an unrelated earlier direct block; check the general
|
||||
# direct-path branch, whose relaying runs before local group delivery.
|
||||
direct = received.index("if (pkt->isRouteDirect() && pkt->getPathHashCount() > 0)")
|
||||
group = received.index("case PAYLOAD_TYPE_GRP_DATA:")
|
||||
group_seen = received.index("_tables->markSeen(pkt);", group)
|
||||
candidates = received.index("searchChannelsForPacket(pkt, &channel_hash, channels, 4)", group)
|
||||
delivery = received.index("onGroupDataRecv(pkt,", candidates)
|
||||
self.assertLess(gate.end(), direct)
|
||||
self.assertLess(gate.end(), group_seen)
|
||||
self.assertLess(group_seen, candidates)
|
||||
self.assertLess(candidates, delivery)
|
||||
header = (ROOT / "src/Mesh.h").read_text(encoding="utf-8")
|
||||
self.assertRegex(header, r"virtual bool allowGroupPacketOnRadio\(Packet\* packet\)\s*\{ return true; \}")
|
||||
|
||||
def test_production_channel_access_and_receive_resolution(self):
|
||||
companion = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text(encoding="utf-8")
|
||||
header = (ROOT / "examples/companion_radio/MyMesh.h").read_text(encoding="utf-8")
|
||||
signatures = (
|
||||
"bool MyMesh::isAliasRadio2Defined(", "bool MyMesh::resolveChannelAlias(",
|
||||
"bool MyMesh::getChannel(", "bool MyMesh::setChannel(",
|
||||
"int MyMesh::searchChannelsForPacket(", "int MyMesh::findChannelIdxForPacket(",
|
||||
"bool MyMesh::allowGroupPacketOnRadio(", "void MyMesh::onGroupDataRecv(",
|
||||
)
|
||||
methods = "\n".join(body(companion, signature) for signature in signatures)
|
||||
save_getter = body(header, "bool getChannelForSave(uint8_t").replace("override", "")
|
||||
shared = HARNESS[:HARNESS.index("static void assertAlias(")]
|
||||
vectors, key_vectors = oracle_vectors()
|
||||
source_text = (shared + RUNTIME_HARNESS).replace("@VECTORS@", vectors).replace(
|
||||
"@KEY_VECTORS@", key_vectors).replace("@METHODS@", methods).replace("@SAVE_GETTER@", save_getter)
|
||||
self.run_native_program(source_text, "runtime")
|
||||
|
||||
def test_production_binary_get_set_raw_keys_and_rollback(self):
|
||||
companion = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text(encoding="utf-8")
|
||||
header = (ROOT / "examples/companion_radio/MyMesh.h").read_text(encoding="utf-8")
|
||||
signatures = ("bool MyMesh::isAliasRadio2Defined(", "bool MyMesh::resolveChannelAlias(",
|
||||
"bool MyMesh::getChannel(", "bool MyMesh::setChannel(")
|
||||
methods = "\n".join(body(companion, signature) for signature in signatures)
|
||||
save_getter = body(header, "bool getChannelForSave(uint8_t").replace("override", "")
|
||||
command_signatures = (
|
||||
"if (cmd_frame[0] == CMD_GET_CHANNEL && len >= 2)",
|
||||
"if (cmd_frame[0] == CMD_SET_CHANNEL && len >= 2 + 32 + 32)",
|
||||
"if (cmd_frame[0] == CMD_SET_CHANNEL && len >= 2 + 32 + 16)",
|
||||
)
|
||||
branches = " else ".join(body(companion, signature) for signature in command_signatures)
|
||||
macros = ("CMD_GET_CHANNEL", "CMD_SET_CHANNEL", "RESP_CODE_CHANNEL_INFO",
|
||||
"ERR_CODE_UNSUPPORTED_CMD", "ERR_CODE_NOT_FOUND", "ERR_CODE_FILE_IO_ERROR",
|
||||
"ERR_CODE_ILLEGAL_ARG")
|
||||
constants = "\n".join(re.search(r"^#define\s+" + name + r"\s+[^\r\n]+", companion,
|
||||
flags=re.MULTILINE).group(0) for name in macros)
|
||||
shared = HARNESS[:HARNESS.index("static void assertAlias(")]
|
||||
fixture = RUNTIME_HARNESS[:RUNTIME_HARNESS.index("\nint main()")]
|
||||
fixture = fixture.replace("class MyMesh :", COMMAND_STUBS + "\nclass MyMesh :")
|
||||
fixture = fixture.replace("@SAVE_GETTER@", save_getter + "\n" + COMMAND_MEMBERS)
|
||||
vectors, key_vectors = oracle_vectors()
|
||||
source_text = (shared + constants + "\n" + fixture + COMMAND_HARNESS).replace(
|
||||
"@VECTORS@", vectors).replace("@KEY_VECTORS@", key_vectors).replace(
|
||||
"@METHODS@", methods).replace("@COMMAND_BRANCHES@", branches)
|
||||
self.run_native_program(source_text, "command")
|
||||
|
||||
def run_native_program(self, source_text, expected):
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
with tempfile.TemporaryDirectory(prefix="meshcore-channel-runtime-") as directory:
|
||||
work = Path(directory)
|
||||
source = work / "runtime.cpp"
|
||||
source.write_text(source_text, encoding="utf-8")
|
||||
binary = work / ("runtime.exe" if sys.platform == "win32" else "runtime")
|
||||
sanitizers = (["-fsanitize=address,undefined", "-fno-sanitize-recover=all",
|
||||
"-fno-pie", "-no-pie"] if sys.platform.startswith("linux") else [])
|
||||
built = subprocess.run(
|
||||
[compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror", *sanitizers,
|
||||
"-I" + str(ROOT / "src"), str(source), "-o", str(binary)],
|
||||
capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
checked = subprocess.run([str(binary)], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(checked.returncode, 0, checked.stdout + checked.stderr)
|
||||
self.assertIn("PASS " + expected, checked.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -31,7 +31,8 @@ class CompanionLostReplyTests(unittest.TestCase):
|
||||
methods += "\n".join(extract_braced(source, signature) for signature in (
|
||||
"void MyMesh::onMessageRecv(",
|
||||
"void MyMesh::onCLICommandRecv(", "bool MyMesh::onSignedMessageRecv(",
|
||||
"void MyMesh::onChannelMessageRecv(", "void MyMesh::clearExpectedAck(",
|
||||
"void MyMesh::onChannelMessageRecv(", "bool MyMesh::queueChannelText(",
|
||||
"void MyMesh::clearExpectedAck(",
|
||||
"void MyMesh::expireExpectedAcks(", "bool MyMesh::processAck(",
|
||||
))
|
||||
methods += "\n" + "\n".join(extract_braced(base, signature).replace(
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Run actual Companion Meshtext methods with real CLI/AES/SHA and bounded adapters.
|
||||
|
||||
No PlatformIO or hardware is used. Only filesystem/NVS, the serial/UI boundary,
|
||||
and the foreign-frame queue are substituted. Protocol/profile decisions remain
|
||||
the production code, extracted without rewriting their bodies.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from cpp_source import body
|
||||
from test_meshtext_chat import array, data_text, reference_frame, varint
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class CompanionMeshtextTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
try:
|
||||
import cryptography # noqa: F401
|
||||
except ImportError:
|
||||
raise unittest.SkipTest("Python cryptography is required for independent receive frames")
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
raise unittest.SkipTest("a host C++ compiler is required")
|
||||
required = ["AESCommon.cpp", "AES128.cpp", "AES256.cpp", "BlockCipher.cpp",
|
||||
"Crypto.cpp", "SHA256.cpp", "Hash.cpp"]
|
||||
override = os.environ.get("MESHCORE_CRYPTO_DIR")
|
||||
candidates = [Path(override)] if override else sorted((ROOT / ".pio/libdeps").glob("*/Crypto"))
|
||||
crypto = next((path for path in candidates if all((path / name).is_file() for name in required)), None)
|
||||
if not crypto:
|
||||
raise unittest.SkipTest("an existing rweather/Crypto checkout is required (MESHCORE_CRYPTO_DIR)")
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix="meshcore-companion-mt-")
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
work = Path(cls.temp.name)
|
||||
# Identity.h uses a quoted Utils include. Shadow both to keep the real
|
||||
# SHA implementation rather than the general native tests' zero hash.
|
||||
utils = (ROOT / "test/mocks/Utils.h").read_text(encoding="utf-8")
|
||||
fake_sha = body(utils, "static void sha256(")
|
||||
utils = utils.replace(fake_sha, "static void sha256(uint8_t*, size_t, const uint8_t*, int);")
|
||||
utils = utils.replace("#define CIPHER_MAC_SIZE 16", "#ifndef CIPHER_MAC_SIZE\n#define CIPHER_MAC_SIZE 16\n#endif")
|
||||
utils = utils.replace("class Utils {", "class Utils {\npublic:\n static bool isHexChar(char);\n static bool fromHex(uint8_t*, int, const char*);\n static bool isZeroes(const uint8_t* p, size_t n) {\n for (size_t i=0;i<n;++i) { if(p[i]) return false; }\n return true;\n }")
|
||||
(work / "Utils.h").write_text(utils, encoding="utf-8")
|
||||
identity = (ROOT / "test/mocks/Identity.h").read_text(encoding="utf-8")
|
||||
(work / "Identity.h").write_text(identity.replace('"Utils.h"', '<Utils.h>'), encoding="utf-8")
|
||||
|
||||
source = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text(encoding="utf-8")
|
||||
mt = (ROOT / "examples/companion_radio/MeshtextCompanion.cpp").read_text(encoding="utf-8")
|
||||
mt = mt[mt.index("namespace {"):].rsplit("#endif", 1)[0]
|
||||
signatures = ("bool MyMesh::isAliasRadio2Defined(", "bool MyMesh::resolveChannelAlias(",
|
||||
"bool MyMesh::getChannel(", "bool MyMesh::setChannel(", "bool MyMesh::queueChannelText(")
|
||||
methods = "\n".join(body(source, signature) for signature in signatures)
|
||||
utils_source = (ROOT / "src/Utils.cpp").read_text(encoding="utf-8")
|
||||
# CLI keys use the production strict hexadecimal parser as well.
|
||||
methods = ("namespace mesh {\n" + "\n".join(body(utils_source, signature) for signature in
|
||||
("static uint8_t hexVal(", "bool Utils::isHexChar(", "bool Utils::fromHex("))
|
||||
+ "\n}\n" + methods)
|
||||
branches = " else ".join(body(source, signature) for signature in (
|
||||
"if (cmd_frame[0] == CMD_GET_CHANNEL && len >= 2)",
|
||||
"if (cmd_frame[0] == CMD_SET_CHANNEL && len >= 2 + 32 + 32)",
|
||||
"if (cmd_frame[0] == CMD_SET_CHANNEL && len >= 2 + 32 + 16)",
|
||||
"if (cmd_frame[0] == CMD_SEND_CHANNEL_TXT_MSG)",
|
||||
))
|
||||
constants = []
|
||||
for name in ("CMD_GET_CHANNEL", "CMD_SET_CHANNEL", "CMD_SEND_CHANNEL_TXT_MSG",
|
||||
"RESP_CODE_CHANNEL_INFO", "RESP_CODE_CHANNEL_MSG_RECV", "RESP_CODE_CHANNEL_MSG_RECV_V3",
|
||||
"PUSH_CODE_MSG_WAITING", "ERR_CODE_UNSUPPORTED_CMD", "ERR_CODE_NOT_FOUND",
|
||||
"ERR_CODE_FILE_IO_ERROR", "ERR_CODE_ILLEGAL_ARG", "ERR_CODE_BAD_STATE"):
|
||||
constants.append(re.search(r"^#define\s+" + name + r"\s+[^\r\n]+", source, re.MULTILINE).group(0))
|
||||
fixture = (ROOT / "test/fixtures/radio_profiles/cli_test.cpp").read_text(encoding="utf-8")
|
||||
fixture = fixture[:fixture.index("static void permanentScheduleOrder()")]
|
||||
text = (ROOT / "test/fixtures/companion_meshtext.cpp").read_text(encoding="utf-8")
|
||||
payload = ("A" * 153 + "\u20ac" + "B" * 69).encode() # 225 bytes, truncation splits a scalar
|
||||
vectors = {
|
||||
"@RX_FRAME@": reference_frame(data_text(payload), packet_id=101),
|
||||
"@RX_RETRY@": reference_frame(data_text(b"retry"), packet_id=102),
|
||||
"@RX_DM@": reference_frame(data_text(b"dm"), to=0x99887766, packet_id=103),
|
||||
"@RX_ACK@": reference_frame(data_text(b"want ack") + b"\x18\x01", flags=0x6B, packet_id=104),
|
||||
"@RX_OTHER@": reference_frame(b"\x08\x02\x12\x01x", packet_id=105),
|
||||
}
|
||||
# Independent standard User/NodeInfo wire expectations; never encode
|
||||
# an expected NodeInfo through the production codec under test.
|
||||
def nodeinfo_frame(sender, packet_id, long_name, short_name, name="LongFast", key=None):
|
||||
def field(number, value):
|
||||
return varint((number << 3) | 2) + varint(len(value)) + value
|
||||
user = field(1, ("!%08x" % sender).encode())
|
||||
if long_name:
|
||||
user += field(2, long_name)
|
||||
user += field(3, short_name) + b"\x38\x01\x48\x01" # CLIENT_MUTE; no DMs
|
||||
data = b"\x08\x04" + field(2, user) # NODEINFO_APP, no want_response
|
||||
args = {} if key is None else {"key": key}
|
||||
return reference_frame(data, name, sender=sender, packet_id=packet_id, flags=0xE7, **args)
|
||||
default_node = int.from_bytes(hashlib.sha256(bytes([42]) + bytes(31)).digest()[:4], "little")
|
||||
vectors.update({
|
||||
"@NODEINFO_DEFAULT@": nodeinfo_frame(default_node, 0x12345678, b"Test",
|
||||
("%04x" % (default_node & 0xFFFF)).encode()),
|
||||
"@NODEINFO_NAMED@": nodeinfo_frame(0x12345678, 0x12345679, b"Mike Carper", b"MIKE"),
|
||||
"@NODEINFO_UTF8@": nodeinfo_frame(0x12345678, 0x1234567B, b"A" * 22, "\U0001f600".encode()),
|
||||
"@NODEINFO_PRIVATE@": nodeinfo_frame(0x12345678, 0x1234567C, b"A" * 22,
|
||||
"\U0001f600".encode(), "Team", bytes(range(1, 33))),
|
||||
})
|
||||
text = text.replace("@FIXTURE@", fixture).replace("@CONSTANTS@", "\n".join(constants))
|
||||
text = text.replace("@METHODS@", methods + "\n" + mt).replace("@COMMANDS@", branches)
|
||||
for marker, frame in vectors.items():
|
||||
text = text.replace(marker, array(frame))
|
||||
legacy = bytearray(16)
|
||||
legacy[:4] = b"MT01"
|
||||
legacy[4] = 1 # Region::US; old reserved bytes 5..7 must remain zero.
|
||||
legacy[8:12] = (2).to_bytes(4, "little")
|
||||
legacy[12:] = hashlib.sha256(legacy[:12]).digest()[:4]
|
||||
text = text.replace("@LEGACY_SETTINGS@", array(legacy))
|
||||
legacy_hops = bytearray(legacy)
|
||||
legacy_hops[:4] = b"MT02"
|
||||
legacy_hops[5] = 3
|
||||
legacy_hops[12:] = hashlib.sha256(legacy_hops[:12]).digest()[:4]
|
||||
text = text.replace("@LEGACY_HOPS_SETTINGS@", array(legacy_hops))
|
||||
public_key = bytes([42]) + bytes(31)
|
||||
text = text.replace("@LOCAL_NODE@", str(int.from_bytes(hashlib.sha256(public_key).digest()[:4], "little")))
|
||||
for first in (43, 44):
|
||||
public_key = bytes([first]) + bytes(31)
|
||||
text = text.replace("@IMPORTED_NODE_%d@" % first,
|
||||
str(int.from_bytes(hashlib.sha256(public_key).digest()[:4], "little")))
|
||||
cpp = work / "companion.cpp"
|
||||
cpp.write_text(text, encoding="utf-8")
|
||||
cls.binary = work / ("companion.exe" if sys.platform == "win32" else "companion")
|
||||
sanitizers = (["-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie"]
|
||||
if sys.platform.startswith("linux") else [])
|
||||
result = subprocess.run(
|
||||
[compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
|
||||
"-Wno-unused-variable", "-Wno-reorder", "-Wno-sign-compare",
|
||||
"-DMESH_ENABLE_MESHTEXT_CHAT=1", "-DMESH_ENABLE_FLEET_CONTROL=1",
|
||||
*sanitizers, "-I" + str(work), "-I" + str(crypto),
|
||||
"-I" + str(ROOT / "test/fixtures/radio_profiles/mocks"), "-I" + str(ROOT / "test/mocks"),
|
||||
"-I" + str(ROOT / "src"), str(cpp), str(ROOT / "src/helpers/RadioProfileCLI.cpp"),
|
||||
str(ROOT / "src/helpers/MeshtextChat.cpp"), *[str(crypto / name) for name in required],
|
||||
"-o", str(cls.binary)], capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
if result.returncode:
|
||||
raise AssertionError(result.stdout + result.stderr)
|
||||
|
||||
def run_case(self, name):
|
||||
result = subprocess.run([str(self.binary), name], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("PASS " + name, result.stdout)
|
||||
|
||||
def test_public_alias_and_private_aes_keys_preserve_raw_app_state(self):
|
||||
self.run_case("keys")
|
||||
|
||||
def test_automatic_profile_is_runtime_only_and_no_automatic_transmit(self):
|
||||
self.run_case("auto")
|
||||
|
||||
def test_conflicts_region_slots_and_custom_channel_dependency(self):
|
||||
self.run_case("conflicts")
|
||||
|
||||
def test_saved_manual_overlay_temporary_priority_and_off_veto(self):
|
||||
self.run_case("manual")
|
||||
|
||||
def test_atomic_settings_corruption_write_failures_and_reboot(self):
|
||||
self.run_case("settings")
|
||||
|
||||
def test_actual_offline_queue_v1_v3_utf8_dedup_and_no_reply_relay(self):
|
||||
self.run_case("receive")
|
||||
|
||||
def test_explicit_app_text_transmit_only_and_bounds(self):
|
||||
self.run_case("transmit")
|
||||
|
||||
def test_binary_get_set_raw_psk_and_save_failure_rollback(self):
|
||||
self.run_case("commands")
|
||||
|
||||
def test_private_cli_provisioning_metadata_masking_and_transactional_delete(self):
|
||||
self.run_case("cli")
|
||||
|
||||
def test_default_seven_hops_cli_override_atomic_persistence_and_legacy_migration(self):
|
||||
self.run_case("hops")
|
||||
|
||||
def test_shortname_unicode_identity_text_budget_atomic_settings_and_mt03_validation(self):
|
||||
self.run_case("shortname")
|
||||
|
||||
def test_node_id_override_wire_sender_persistence_default_reset_and_failures(self):
|
||||
self.run_case("node")
|
||||
source = (ROOT / "examples/companion_radio/MyMesh.cpp").read_text(encoding="utf-8")
|
||||
imported = body(source, "if (cmd_frame[0] == CMD_IMPORT_PRIVATE_KEY && len >= 65)")
|
||||
guard = re.search(r"else\s+if\s*\(hasForeignRadioFrame\(\)\)\s*\{[^}]*"
|
||||
r"writeErrFrame\(ERR_CODE_BAD_STATE\)", imported)
|
||||
self.assertIsNotNone(guard, "pending Meshtext TX must block the identity import")
|
||||
self.assertLess(guard.end(), imported.index("flushContactsBeforeReboot()"))
|
||||
self.assertLess(guard.end(), imported.index("identity.readFrom("))
|
||||
self.assertLess(guard.end(), imported.index("_store->saveMainIdentity(identity)"))
|
||||
committed = body(imported, "if (_store->saveMainIdentity(identity))")
|
||||
self.assertLess(committed.index("self_id = identity;"), committed.index("refreshMeshtextIdentity();"))
|
||||
self.assertLess(committed.index("refreshMeshtextIdentity();"), committed.index("writeOKFrame();"))
|
||||
self.assertEqual(imported.count("refreshMeshtextIdentity();"), 1,
|
||||
"the refresh belongs only to the successfully saved identity branch")
|
||||
|
||||
def test_manual_nodeinfo_standard_fields_shared_sequence_guards_and_no_automatic_adverts(self):
|
||||
self.run_case("nodeinfo")
|
||||
source = (ROOT / "examples/companion_radio/MeshtextCompanion.cpp").read_text(encoding="utf-8")
|
||||
self.assertEqual(source.count("sendMeshtextNodeInfo("), 2,
|
||||
"NodeInfo has exactly one caller: the explicit CLI")
|
||||
chat = body(source, "bool MyMesh::sendMeshtextText(")
|
||||
self.assertNotIn("_mt_short_name", chat)
|
||||
self.assertNotIn("node_name", chat)
|
||||
self.assertNotIn("encodeNodeInfo", chat)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from pathlib import Path
|
||||
import re
|
||||
from cpp_source import body
|
||||
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
@@ -82,10 +83,17 @@ assert re.search(
|
||||
assert terminal.index("handleLocalControlCommand(") < terminal.index(
|
||||
'strncmp(command, "set ", 4) == 0'
|
||||
)
|
||||
assert 'terminalOutput().print(" board\\r\\n")' in terminal
|
||||
assert 'terminalOutput().print(" version\\r\\n")' in terminal
|
||||
assert 'terminalOutput().print(" get pwrmgt.bootreason\\r\\n")' in terminal
|
||||
assert 'terminalOutput().print(" set pin <0-999999>\\r\\n")' in terminal
|
||||
# Help is emitted in bounded chunks with concatenated C++ literals. Check the
|
||||
# actual help branch rather than requiring one print() call per command.
|
||||
help_branch = body(terminal, 'if (strcmp(command, "help") == 0)')
|
||||
for help_line in (' board\\r\\n', ' version\\r\\n',
|
||||
' get pwrmgt.bootreason\\r\\n', ' set pin <0-999999>\\r\\n',
|
||||
' set mt.hops <0..7> (saved; default 7)\\r\\n',
|
||||
' get mt.node / get mt.shortname\\r\\n',
|
||||
' set mt.node <!8hex|default> (saved; use a unique ID)\\r\\n',
|
||||
' set mt.shortname <1..4 UTF-8 characters|default> (saved; NodeInfo uses 4 bytes)\\r\\n',
|
||||
' send mt.nodeinfo <channel slot> (one manual advert; no automatic adverts)\\r\\n'):
|
||||
assert help_line in help_branch
|
||||
assert re.search(
|
||||
r"#if COMPANION_FEATURE_MEMORY_DIAGNOSTICS\s+"
|
||||
r'terminalOutput\(\)\.print\(" memory\\r\\n"\);\s+#endif',
|
||||
|
||||
@@ -17,6 +17,7 @@ HARNESS = r'''
|
||||
#include <RadioProfiles.h>
|
||||
#include <helpers/CLICommandUtils.h>
|
||||
#include <helpers/CompanionTxRoutingCLI.h>
|
||||
#include <helpers/CompanionChannelAlias.h>
|
||||
#include <helpers/IdentityStore.h>
|
||||
#include "ContactFileTransaction.h"
|
||||
#if defined(STM32_PLATFORM)
|
||||
@@ -65,14 +66,26 @@ public:
|
||||
bool canMutateContacts() const { return writable && !store.hasIncompleteContactLoad(); }
|
||||
int getTotalContactSlots() const { return contacts.size(); }
|
||||
ContactInfo* getContactPtrByIdx(int i) { return &contacts.at(i); }
|
||||
bool getChannel(int i, ChannelDetails& c) { if (i<0 || i>=MAX_GROUP_CHANNELS) return false; c=channels[i]; return true; }
|
||||
bool getChannel(int i, ChannelDetails& c) {
|
||||
if (i<0 || i>=MAX_GROUP_CHANNELS) return false;
|
||||
c=channels[i];
|
||||
if (radio.config.enabled()) {
|
||||
auto kind=parseCompanionChannelAlias(c.name).kind;
|
||||
if (kind==CompanionChannelKind::Radio2) c.channel.tx_radio=mesh::RADIO_TX_SECONDARY;
|
||||
else if (kind==CompanionChannelKind::Meshtext) c.channel.tx_radio=mesh::RADIO_TX_OFF;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
bool setChannel(int i, const ChannelDetails& c) { if (i<0 || i>=MAX_GROUP_CHANNELS) return false; channels[i]=c; return true; }
|
||||
bool saveChannels() { ++writes; return writes_ok && store.saveChannels(this); }
|
||||
bool scheduleContactWrite(const ContactInfo&) { ++writes; return writes_ok; }
|
||||
bool flushContactsBeforeReboot() { return writes_ok; }
|
||||
bool onChannelLoaded(uint8_t i,const ChannelDetails& c) override { return setChannel(i,c); }
|
||||
bool getChannelForSave(uint8_t i,ChannelDetails& c) override { return getChannel(i,c); }
|
||||
bool getChannelForSave(uint8_t i,ChannelDetails& c) override {
|
||||
if (i>=MAX_GROUP_CHANNELS) return false; c=channels[i]; return true;
|
||||
}
|
||||
bool handleTxRoutingCommand(const char*,char*,size_t);
|
||||
bool isAliasRadio2Defined() const { return radio.config.enabled(); }
|
||||
};
|
||||
@METHODS@
|
||||
|
||||
@@ -232,6 +245,24 @@ int main() {
|
||||
for (auto& byte : node.store.fs.files["/channels2"]) byte=0;
|
||||
node.store.loadChannels(&node);
|
||||
for (auto& c : node.channels) assert(c.channel.tx_radio==mesh::RADIO_TX_AUTO);
|
||||
// Prefix-bound routes cannot be silently overridden. With no radio2, the
|
||||
// ordinary raw/manual policy can still be changed without rewriting the PSK.
|
||||
MyMesh aliased;
|
||||
strcpy(aliased.channels[1].name,"#r2-emergency");
|
||||
aliased.channels[1].channel.secret[0]=42;
|
||||
aliased.radio.config.secondary.mode=mesh::RadioProfileMode::RxTx;
|
||||
auto alias_cmd=[&](const char* text) { assert(aliased.handleTxRoutingCommand(text,reply,sizeof(reply))); };
|
||||
alias_cmd("get tx.channel 1"); assert(strstr(reply,"active=radio2"));
|
||||
alias_cmd("set tx.channel 1 radio"); assert(strstr(reply,"prefix controls routing"));
|
||||
assert(aliased.writes==0 && aliased.channels[1].channel.tx_radio==mesh::RADIO_TX_AUTO);
|
||||
alias_cmd("set tx.channel 1 radio2"); assert(!strncmp(reply,"OK",2) && aliased.writes==0);
|
||||
aliased.radio.config.secondary.mode=mesh::RadioProfileMode::Off;
|
||||
alias_cmd("set tx.channel 1 radio"); assert(!strncmp(reply,"OK",2));
|
||||
assert(aliased.channels[1].channel.tx_radio==mesh::RADIO_TX_PRIMARY);
|
||||
assert(aliased.channels[1].channel.secret[0]==42);
|
||||
assert(aliased.store.fs.files["/channels2"][68+36]==42);
|
||||
aliased.radio.config.secondary.mode=mesh::RadioProfileMode::Rx;
|
||||
alias_cmd("get tx.channel 1"); assert(strstr(reply,"active=off") && strstr(reply,"unavailable"));
|
||||
}
|
||||
'''
|
||||
|
||||
@@ -266,9 +297,9 @@ class CompanionTxRoutingTest(unittest.TestCase):
|
||||
|
||||
def test_phone_protocol_updates_preserve_same_channel_policy(self):
|
||||
source = (ROOT / 'examples/companion_radio/MyMesh.cpp').read_text()
|
||||
command = source[source.index('const bool have_previous = getChannel(channel_idx, previous);'):]
|
||||
command = source[source.index('const bool have_previous = getChannelForSave(channel_idx, previous);'):]
|
||||
command = command[:command.index('} else if (cmd_frame[0] == CMD_SIGN_START')]
|
||||
self.assertIn('!memcmp(channel.channel.secret, previous.channel.secret, sizeof(channel.channel.secret))', command)
|
||||
self.assertIn('!memcmp(wire_channel.channel.secret, previous_wire_channel.channel.secret, sizeof(channel.channel.secret))', command)
|
||||
self.assertIn('channel.channel.tx_radio = previous.channel.tx_radio;', command)
|
||||
self.assertIn('setChannel(channel_idx, previous);', command)
|
||||
self.assertIn('handleTxRoutingCommand(command, reply, reply_size)',
|
||||
|
||||
@@ -37,10 +37,26 @@ public:
|
||||
};
|
||||
class Tables : public mesh::MeshTables {
|
||||
public:
|
||||
bool wasSeen(const mesh::Packet*) override { return false; }
|
||||
void markSeen(const mesh::Packet*) override {}
|
||||
// Existing admission tests do not deduplicate. Opt in for receive-order
|
||||
// regressions with a real payload/type hash, deliberately excluding profile.
|
||||
bool deduplicate = false, have_seen = false;
|
||||
unsigned seen_queries = 0, seen_marks = 0;
|
||||
uint8_t seen_hash[MAX_HASH_SIZE] = {};
|
||||
bool wasSeen(const mesh::Packet* packet) override {
|
||||
if (!deduplicate) return false;
|
||||
++seen_queries;
|
||||
uint8_t hash[MAX_HASH_SIZE];
|
||||
packet->calculatePacketHash(hash);
|
||||
return have_seen && !memcmp(hash, seen_hash, sizeof(hash));
|
||||
}
|
||||
void markSeen(const mesh::Packet* packet) override {
|
||||
if (!deduplicate) return;
|
||||
++seen_marks;
|
||||
packet->calculatePacketHash(seen_hash);
|
||||
have_seen = true;
|
||||
}
|
||||
void markSent(const mesh::Packet*) override {}
|
||||
void clear(const mesh::Packet*) override {}
|
||||
void clear(const mesh::Packet*) override { have_seen = false; }
|
||||
};
|
||||
class Chat : public BaseChatMesh {
|
||||
public:
|
||||
@@ -57,6 +73,12 @@ public:
|
||||
bool writable = true;
|
||||
uint8_t max_hops = 1;
|
||||
unsigned discovered = 0, stored = 0, full = 0;
|
||||
bool forward_packets = false, reject_primary_groups = false;
|
||||
bool bind_secondary_groups = false, packet_group_search = false;
|
||||
uint32_t direct_forward_delay = 0;
|
||||
unsigned group_admissions = 0, group_searches = 0, received_groups = 0;
|
||||
uint8_t last_search_origin = 0xFF;
|
||||
mesh::GroupChannel primary_group, secondary_group, received_group;
|
||||
Chat(Radio& radio, Clock& clock, RNG& rng, RTC& rtc,
|
||||
StaticPoolPacketManager& pool, Tables& tables)
|
||||
: BaseChatMesh(radio, clock, rng, rtc, pool, tables) {}
|
||||
@@ -64,7 +86,40 @@ public:
|
||||
bool shouldAutoAddContactType(uint8_t) const override { return auto_add; }
|
||||
uint8_t getAutoAddMaxHops() const override { return max_hops; }
|
||||
bool canMutateContacts() const override { return writable; }
|
||||
bool allowPacketForward(const mesh::Packet*) override { return false; }
|
||||
bool allowPacketForward(const mesh::Packet*) override { return forward_packets; }
|
||||
uint32_t getDirectRetransmitDelay(const mesh::Packet*) override { return direct_forward_delay; }
|
||||
bool allowGroupPacketOnRadio(mesh::Packet* packet) override {
|
||||
++group_admissions;
|
||||
// Stub only the application's policy, not the core admission/order path.
|
||||
if (reject_primary_groups && packet->radio_origin == 0) return false;
|
||||
if (bind_secondary_groups && packet->radio_origin == 1) {
|
||||
packet->tx_radio = mesh::RADIO_TX_SECONDARY;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
int searchChannelsForPacket(const mesh::Packet* packet, const uint8_t* hash,
|
||||
mesh::GroupChannel channels[], int max_matches) override {
|
||||
if (!packet_group_search) {
|
||||
return BaseChatMesh::searchChannelsForPacket(packet, hash, channels, max_matches);
|
||||
}
|
||||
++group_searches;
|
||||
last_search_origin = packet->radio_origin;
|
||||
const auto& channel = packet->radio_origin == 1 ? secondary_group : primary_group;
|
||||
if (max_matches < 1 || channel.hash[0] != hash[0]) return 0;
|
||||
channels[0] = channel;
|
||||
return 1;
|
||||
}
|
||||
void onGroupDataRecv(mesh::Packet* packet, uint8_t type,
|
||||
const mesh::GroupChannel& channel, uint8_t* data, size_t len) override {
|
||||
if (!packet_group_search) {
|
||||
BaseChatMesh::onGroupDataRecv(packet, type, channel, data, len);
|
||||
return;
|
||||
}
|
||||
++received_groups;
|
||||
received_group = channel;
|
||||
// Native AES is a no-op mock. Production Utils/HMAC and the core channel
|
||||
// search/decrypt path run, but these tests make no plaintext/AES assertion.
|
||||
}
|
||||
void onContactsFull() override { ++full; }
|
||||
bool putBlobByKey(const uint8_t*, int, const uint8_t*, int) override {
|
||||
++stored;
|
||||
@@ -123,6 +178,43 @@ protected:
|
||||
uint8_t raw[MAX_TRANS_UNIT];
|
||||
return chat.importContact(raw, packet.writeTo(raw));
|
||||
}
|
||||
void configureGroupSearch() {
|
||||
chat.packet_group_search = true;
|
||||
memset(chat.primary_group.secret, 0, sizeof(chat.primary_group.secret));
|
||||
memset(chat.secondary_group.secret, 0, sizeof(chat.secondary_group.secret));
|
||||
memset(chat.primary_group.secret, 1, 16);
|
||||
memset(chat.secondary_group.secret, 2, 16);
|
||||
// Simulate the supported one-byte channel-hash collision. Authentication
|
||||
// must distinguish these keys, not the packet's channel hash alone.
|
||||
chat.primary_group.hash[0] = chat.secondary_group.hash[0] = 17;
|
||||
}
|
||||
mesh::Packet groupPacket(const mesh::GroupChannel& channel, uint8_t route = ROUTE_TYPE_FLOOD) {
|
||||
mesh::Packet packet;
|
||||
packet.header = route | (PAYLOAD_TYPE_GRP_TXT << PH_TYPE_SHIFT);
|
||||
packet.setPathHashSizeAndCount(1, 0);
|
||||
memset(packet.payload, 0, sizeof(packet.payload));
|
||||
uint8_t data[CIPHER_BLOCK_SIZE] = {};
|
||||
const uint32_t timestamp = 10;
|
||||
memcpy(data, ×tamp, sizeof(timestamp));
|
||||
memcpy(data + 5, "hello", 5);
|
||||
packet.payload[0] = channel.hash[0];
|
||||
packet.payload_len = 1 + mesh::Utils::encryptThenMAC(
|
||||
channel.secret, packet.payload + 1, data, sizeof(data));
|
||||
return packet;
|
||||
}
|
||||
bool queueReceived(mesh::Packet packet, uint8_t origin) {
|
||||
auto* received = chat.obtainNewPacket();
|
||||
if (received == nullptr) return false;
|
||||
packet.radio_profile = packet.radio_origin = origin;
|
||||
packet.radio_generation = packet.radio_origin_generation = radio.config.generation[origin];
|
||||
packet.radio_local = packet.radio_bound = false;
|
||||
packet.radio_reply = packet.radio_reply_force = false;
|
||||
packet.tx_radio = mesh::RADIO_TX_AUTO;
|
||||
*received = packet;
|
||||
pool.queueInbound(received, 0);
|
||||
chat.loop();
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(ContactImport, ExplicitImportBypassesDiscoveryFiltersOnlyForThatPacket) {
|
||||
@@ -306,6 +398,108 @@ TEST_F(ContactImport, ContactRoutingAlsoControlsAcknowledgementsAndReturnedPaths
|
||||
EXPECT_EQ(1, pool.getOutboundByIdx(0)->radio_profile);
|
||||
EXPECT_EQ(1, pool.getOutboundByIdx(1)->radio_profile);
|
||||
}
|
||||
|
||||
TEST_F(ContactImport, GroupAdmissionRejectsWrongProfileBeforeGlobalDeduplication) {
|
||||
radio.dual = true;
|
||||
radio.config.secondary.mode = mesh::RadioProfileMode::RxTx;
|
||||
radio.config.cross = mesh::RadioCrossMode::Off;
|
||||
tables.deduplicate = true;
|
||||
chat.reject_primary_groups = true;
|
||||
configureGroupSearch();
|
||||
const auto packet = groupPacket(chat.secondary_group);
|
||||
|
||||
ASSERT_TRUE(queueReceived(packet, 0));
|
||||
EXPECT_EQ(chat.group_admissions, 1u);
|
||||
EXPECT_EQ(chat.group_searches, 0u);
|
||||
EXPECT_EQ(chat.received_groups, 0u);
|
||||
EXPECT_EQ(tables.seen_queries, 0u);
|
||||
EXPECT_EQ(tables.seen_marks, 0u);
|
||||
EXPECT_FALSE(tables.wasSeen(&packet));
|
||||
EXPECT_EQ(pool.getFreeCount(), 8);
|
||||
|
||||
// Exactly the same wire payload must remain eligible on its allowed radio.
|
||||
ASSERT_TRUE(queueReceived(packet, 1));
|
||||
EXPECT_EQ(chat.group_admissions, 2u);
|
||||
EXPECT_EQ(chat.group_searches, 1u);
|
||||
EXPECT_EQ(chat.last_search_origin, 1);
|
||||
EXPECT_EQ(chat.received_groups, 1u);
|
||||
EXPECT_EQ(tables.seen_marks, 1u);
|
||||
EXPECT_TRUE(tables.wasSeen(&packet));
|
||||
EXPECT_EQ(pool.getFreeCount(), 8);
|
||||
|
||||
ASSERT_TRUE(queueReceived(packet, 1));
|
||||
EXPECT_EQ(chat.group_admissions, 3u);
|
||||
EXPECT_EQ(chat.group_searches, 1u);
|
||||
EXPECT_EQ(chat.received_groups, 1u);
|
||||
EXPECT_EQ(tables.seen_marks, 1u);
|
||||
}
|
||||
|
||||
TEST_F(ContactImport, PacketAwareGroupSearchUsesCapturedOriginAndAuthenticatedKey) {
|
||||
radio.dual = true;
|
||||
radio.config.secondary.mode = mesh::RadioProfileMode::RxTx;
|
||||
configureGroupSearch();
|
||||
const auto secondary_packet = groupPacket(chat.secondary_group);
|
||||
uint8_t plaintext[MAX_PACKET_PAYLOAD];
|
||||
ASSERT_GT(mesh::Utils::MACThenDecrypt(chat.secondary_group.secret, plaintext,
|
||||
secondary_packet.payload + 1, secondary_packet.payload_len - 1), 0);
|
||||
ASSERT_EQ(mesh::Utils::MACThenDecrypt(chat.primary_group.secret, plaintext,
|
||||
secondary_packet.payload + 1, secondary_packet.payload_len - 1), 0);
|
||||
|
||||
// The transceiver reports primary while a delayed secondary packet is
|
||||
// processed. The packet-aware hook must receive the captured RX origin.
|
||||
ASSERT_EQ(radio.receiveProfile(), 0);
|
||||
ASSERT_TRUE(queueReceived(secondary_packet, 1));
|
||||
EXPECT_EQ(chat.last_search_origin, 1);
|
||||
EXPECT_EQ(chat.received_groups, 1u);
|
||||
EXPECT_EQ(memcmp(chat.received_group.secret, chat.secondary_group.secret, PUB_KEY_SIZE), 0);
|
||||
ASSERT_TRUE(queueReceived(secondary_packet, 0));
|
||||
EXPECT_EQ(chat.last_search_origin, 0);
|
||||
EXPECT_EQ(chat.received_groups, 1u); // same hash, wrong authenticated key
|
||||
ASSERT_TRUE(queueReceived(groupPacket(chat.primary_group), 0));
|
||||
EXPECT_EQ(chat.received_groups, 2u);
|
||||
EXPECT_EQ(memcmp(chat.received_group.secret, chat.primary_group.secret, PUB_KEY_SIZE), 0);
|
||||
EXPECT_EQ(chat.group_searches, 3u);
|
||||
EXPECT_EQ(pool.getFreeCount(), 8);
|
||||
}
|
||||
|
||||
TEST_F(ContactImport, GroupAdmissionBindsDirectRelayBeforeCrossProfileFanout) {
|
||||
radio.dual = true;
|
||||
radio.config.secondary.mode = mesh::RadioProfileMode::RxTx;
|
||||
radio.config.cross = mesh::RadioCrossMode::On;
|
||||
tables.deduplicate = true;
|
||||
chat.forward_packets = chat.reject_primary_groups = chat.bind_secondary_groups = true;
|
||||
chat.direct_forward_delay = 100;
|
||||
configureGroupSearch();
|
||||
auto packet = groupPacket(chat.secondary_group, ROUTE_TYPE_DIRECT);
|
||||
chat.self_id.pub_key[0] = 0x42;
|
||||
packet.setPathHashSizeAndCount(1, 2);
|
||||
packet.path[0] = chat.self_id.pub_key[0];
|
||||
packet.path[1] = 0x93;
|
||||
|
||||
ASSERT_TRUE(queueReceived(packet, 0));
|
||||
EXPECT_EQ(tables.seen_queries, 0u);
|
||||
EXPECT_EQ(tables.seen_marks, 0u);
|
||||
EXPECT_EQ(pool.getOutboundTotal(), 0);
|
||||
EXPECT_EQ(pool.getFreeCount(), 8);
|
||||
|
||||
ASSERT_TRUE(queueReceived(packet, 1));
|
||||
EXPECT_EQ(chat.group_admissions, 2u);
|
||||
EXPECT_EQ(chat.group_searches, 0u); // direct relay returns before local search
|
||||
EXPECT_EQ(chat.received_groups, 0u);
|
||||
EXPECT_EQ(tables.seen_marks, 1u);
|
||||
ASSERT_EQ(pool.getOutboundTotal(), 1); // cross=on must not add a primary copy
|
||||
const auto* relayed = pool.getOutboundByIdx(0);
|
||||
ASSERT_NE(relayed, nullptr);
|
||||
EXPECT_EQ(relayed->radio_profile, 1);
|
||||
EXPECT_EQ(relayed->radio_origin, 1);
|
||||
EXPECT_EQ(relayed->tx_radio, mesh::RADIO_TX_SECONDARY);
|
||||
EXPECT_TRUE(relayed->radio_bound);
|
||||
EXPECT_FALSE(relayed->radio_reply);
|
||||
EXPECT_FALSE(relayed->radio_reply_force);
|
||||
EXPECT_EQ(relayed->getPathHashCount(), 1);
|
||||
EXPECT_EQ(relayed->path[0], 0x93);
|
||||
EXPECT_EQ(pool.getFreeCount(), 7);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
"""Host-only checks of the preset sweep; never opens a hardware port."""
|
||||
import contextlib
|
||||
import io
|
||||
import pathlib
|
||||
import random
|
||||
import struct
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1] / "tools" / "hil"))
|
||||
import meshtext_auto_radio2 as hil
|
||||
|
||||
|
||||
class SweepPlanTests(unittest.TestCase):
|
||||
def test_meshtext_help_exposes_stock_peer_port_without_opening_hardware(self):
|
||||
output = io.StringIO()
|
||||
with patch.object(sys, "argv", ["meshtext_auto_radio2.py", "--help"]), \
|
||||
patch.object(hil, "Companion") as companion, \
|
||||
patch.object(hil, "StockPeer") as stock, \
|
||||
contextlib.redirect_stdout(output), self.assertRaises(SystemExit) as exit_result:
|
||||
hil.main()
|
||||
self.assertEqual(exit_result.exception.code, 0)
|
||||
self.assertIn("Meshtext Companion / stock-peer", output.getvalue())
|
||||
self.assertIn("--stock-port", output.getvalue())
|
||||
self.assertNotIn("meshtastic", output.getvalue().lower())
|
||||
companion.assert_not_called()
|
||||
stock.assert_not_called()
|
||||
|
||||
def test_us_centers_and_native_stable_presets(self):
|
||||
expected = {
|
||||
"LongFast": 906.875, "ShortTurbo": 926.75,
|
||||
"ShortFast": 918.875, "ShortSlow": 920.625,
|
||||
"MediumFast": 913.125, "MediumSlow": 914.875,
|
||||
"LongTurbo": 908.75, "LongMod": 902.6875,
|
||||
"LongSlow": 905.3125, "MediumTurbo": 925.25,
|
||||
}
|
||||
self.assertEqual(sum(p.stock_enum is not None for p in hil.PRESETS), 9)
|
||||
for preset in hil.PRESETS:
|
||||
self.assertEqual(preset.frequency, expected[preset.name])
|
||||
self.assertEqual(preset.describe()["preamble"], 16)
|
||||
|
||||
def test_alias_selection_and_rejections(self):
|
||||
self.assertEqual(hil.choose_presets("long_moderate")[0].name, "LongMod")
|
||||
for value in ("", "longfast,longfast", "not-a-preset"):
|
||||
with self.assertRaises(hil.TestFailure):
|
||||
hil.choose_presets(value)
|
||||
|
||||
def test_auto_profile_readback(self):
|
||||
profile = hil.parse_profile("> 906.875,250.000,11,5,rxtx,16; auto-owned")
|
||||
self.assertEqual(profile, (906.875, 250, 11, 5, "rxtx", 16))
|
||||
with self.assertRaises(hil.TestFailure):
|
||||
hil.parse_profile("> off")
|
||||
|
||||
def test_queue_envelopes(self):
|
||||
body = bytes((1, 0, 0)) + struct.pack("<I", 123456) + b"!12345678: test"
|
||||
for packet in (b"\x08" + body, b"\x11\x00\x00\x00" + body):
|
||||
value = hil.decode_channel_frame(packet)
|
||||
self.assertEqual(value["channel"], 1)
|
||||
self.assertEqual(value["timestamp"], 123456)
|
||||
self.assertEqual(value["text"], b"!12345678: test")
|
||||
self.assertIsNone(hil.decode_channel_frame(b"\x0a"))
|
||||
with self.assertRaises(hil.TestFailure):
|
||||
hil.decode_channel_frame(b"\x08")
|
||||
|
||||
def test_temporary_profile_status_dialects(self):
|
||||
for value in ("> off", "off", "TempRadio inactive"):
|
||||
self.assertTrue(hil.temporary_off(value))
|
||||
for value in ("> 1 min left", "TempRadio active", "TempRadio inactive; scheduled"):
|
||||
self.assertFalse(hil.temporary_off(value))
|
||||
|
||||
|
||||
class SweepPolicyTests(unittest.TestCase):
|
||||
def test_traffic_counts_preserve_the_configured_threshold(self):
|
||||
case = {"v4_to_v3": [{"received": True}] * 3,
|
||||
"v3_to_v4": [{"received": True}, {"received": False}, {"received": True}]}
|
||||
self.assertEqual(hil.assess_traffic(case, 3), [
|
||||
{"direction": "v3_to_v4", "received": 2, "attempted": 3, "required": 3}])
|
||||
self.assertEqual(case["traffic_counts"]["v4_to_v3"], {"received": 3, "attempted": 3})
|
||||
self.assertFalse(hil.assess_traffic(case, 2))
|
||||
|
||||
def test_seeded_gap_jitter_is_reproducible_and_zero_is_unchanged(self):
|
||||
gaps = []
|
||||
with patch.object(hil.time, "sleep") as sleep:
|
||||
for _ in range(2):
|
||||
rng = random.Random(0x12345678)
|
||||
packets = [{} for _ in range(4)]
|
||||
for packet in packets:
|
||||
hil.pause_after_packet(packet, 1, 0.5, rng)
|
||||
gaps.append([packet["gap_after_seconds"] for packet in packets])
|
||||
self.assertEqual(gaps[0], gaps[1])
|
||||
self.assertTrue(all(1 <= gap <= 1.5 for gap in gaps[0]))
|
||||
rng = Mock()
|
||||
packet = {}
|
||||
hil.pause_after_packet(packet, 1, 0, rng)
|
||||
rng.uniform.assert_not_called()
|
||||
sleep.assert_called_with(1)
|
||||
self.assertEqual(packet["gap_after_seconds"], 1)
|
||||
|
||||
def run_fake(self, *, continue_on_loss=False, lose_first=True, reboot=False,
|
||||
reboot_loss=False, auto_clear=False):
|
||||
presets = [hil.PRESETS[1], hil.PRESETS[0]]
|
||||
state = SimpleNamespace(alias="", rebooted=False, configured=[], commands=[])
|
||||
|
||||
class FakeCompanion:
|
||||
max_channels = 2
|
||||
|
||||
def __init__(self, port):
|
||||
self.port = SimpleNamespace(write=self.write, flush=lambda: None)
|
||||
|
||||
def write(self, frame):
|
||||
state.rebooted = True
|
||||
return len(frame)
|
||||
|
||||
def start(self):
|
||||
return {"primary": {"public_key_prefix": "unchanged"}}
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def channel_name(self, slot):
|
||||
return "normal"
|
||||
|
||||
def cli(self, command):
|
||||
state.commands.append(command)
|
||||
if command.startswith("set mt.channel "):
|
||||
state.alias = command.split()[3]
|
||||
elif command.startswith("delete mt.channel "):
|
||||
state.alias = ""
|
||||
if command in ("get tempradio", "get tempradio2"):
|
||||
return "> off"
|
||||
if command == "get radio":
|
||||
return "unchanged-primary"
|
||||
if command == "get mt.status":
|
||||
return "> Meshtext; active; TX=0 RX=0 fail=0" if state.alias else "> Meshtext; no Meshtext channels; TX=0 RX=0 fail=0"
|
||||
if command == "get radio2":
|
||||
return "auto-owned" if state.alias else "> off (automatic allowed)"
|
||||
return "> diagnostic"
|
||||
|
||||
def mt_node(self):
|
||||
return 0x12345678
|
||||
|
||||
def wait_auto(self, preset):
|
||||
return {"radio2": "auto-owned", "status": "active"}
|
||||
|
||||
def send_text(self, slot, token):
|
||||
pass
|
||||
|
||||
def wait_text(self, slot, from_node, token, timeout):
|
||||
lost = ((lose_first and state.alias == presets[0].alias and not state.rebooted)
|
||||
or (reboot_loss and state.rebooted))
|
||||
return {"received": not lost}
|
||||
|
||||
class FakeStock:
|
||||
node = 0x87654321
|
||||
|
||||
def __init__(self, port):
|
||||
pass
|
||||
|
||||
def configure(self, preset, key, tx, hops):
|
||||
state.configured.append(preset.name)
|
||||
return {"readback": {"use_preset": True, "channel_num": 0, "bandwidth": preset.bandwidth,
|
||||
"spread_factor": preset.sf, "coding_rate": preset.cr,
|
||||
"tx_power": tx, "hop_limit": hops}}
|
||||
|
||||
def packets_since(self, timestamp, sender):
|
||||
return []
|
||||
|
||||
def wait_packet(self, sender, predicate, since, timeout):
|
||||
return {"id": 1}
|
||||
|
||||
def send_text(self, token, hops):
|
||||
return SimpleNamespace(id=1)
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
args = SimpleNamespace(key_bits=128, region="auto", tx_power=-9, hops=7,
|
||||
minimum_received=3, messages_per_direction=3,
|
||||
continue_on_loss=continue_on_loss, gap_seconds=1, gap_jitter_seconds=0.5,
|
||||
companion_port="fake-v4", stock_port="fake-v3", channel_slot=1,
|
||||
quiet_seconds=1, timeout=15, nodeinfo=False, reboot=reboot,
|
||||
auto_clear=auto_clear, output=pathlib.Path("unused-mocked-report.json"))
|
||||
with patch.object(hil, "Companion", FakeCompanion), patch.object(hil, "StockPeer", FakeStock), \
|
||||
patch.object(hil.time, "sleep"), patch.object(hil, "write_report") as writer, \
|
||||
patch.object(hil.importlib.metadata, "version", return_value="mock"), \
|
||||
patch.object(hil.secrets, "token_hex", return_value="12345678"), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
report = hil.run(args, presets)
|
||||
writer.assert_called_once_with(args.output, report)
|
||||
return report, state
|
||||
|
||||
def test_default_loss_policy_is_failfast_with_diagnostics(self):
|
||||
report, state = self.run_fake()
|
||||
self.assertEqual(state.configured, ["ShortTurbo"])
|
||||
self.assertEqual(report["result"], "FAIL")
|
||||
self.assertEqual(report["failed_cases"], ["ShortTurbo"])
|
||||
case = report["cases"][0]
|
||||
self.assertEqual(case["traffic_counts"]["v3_to_v4"]["received"], 0)
|
||||
for name in ("status_after_traffic", "radio2_after_traffic",
|
||||
"radio2_status_after_traffic", "radio2_scan_after_traffic"):
|
||||
self.assertIn(name, case)
|
||||
|
||||
def test_continue_on_loss_collects_both_cases_but_still_fails(self):
|
||||
report, state = self.run_fake(continue_on_loss=True)
|
||||
self.assertEqual(state.configured, ["ShortTurbo", "LongFast"])
|
||||
self.assertEqual([case["result"] for case in report["cases"]], ["FAIL", "PASS"])
|
||||
self.assertEqual(report["result"], "FAIL")
|
||||
self.assertIn("ShortTurbo", report["failure"]["message"])
|
||||
self.assertEqual(report["gap_jitter_seed"], 0x12345678)
|
||||
for case in report["cases"]:
|
||||
for direction in ("v4_to_v3", "v3_to_v4"):
|
||||
self.assertTrue(all(1 <= packet["gap_after_seconds"] <= 1.5 for packet in case[direction]))
|
||||
|
||||
def test_continued_loss_does_not_skip_reboot_and_reboot_loss_is_strict(self):
|
||||
report, state = self.run_fake(continue_on_loss=True, reboot=True, reboot_loss=True)
|
||||
self.assertTrue(state.rebooted)
|
||||
self.assertEqual(report["reboot_persistence"]["result"], "FAIL")
|
||||
self.assertEqual(report["result"], "FAIL")
|
||||
self.assertIn("after reboot in v3_to_v4", report["failure"]["message"])
|
||||
|
||||
def test_successful_reboot_and_auto_clear_leave_final_profile_readded(self):
|
||||
report, state = self.run_fake(continue_on_loss=True, lose_first=False, reboot=True, auto_clear=True)
|
||||
self.assertEqual(report["result"], "PASS")
|
||||
self.assertEqual(report["reboot_persistence"]["result"], "PASS")
|
||||
self.assertEqual(report["auto_clear"]["result"], "PASS")
|
||||
self.assertIn("no Meshtext channels", report["auto_clear"]["removed"]["mt_status"])
|
||||
self.assertEqual(state.alias, "mt-longfast")
|
||||
self.assertEqual(report["failed_cases"], [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,175 @@
|
||||
"""Host-only stock SDK/boot-readback contracts; no SDK installation or serial IO."""
|
||||
|
||||
import copy
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from types import ModuleType, SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools" / "hil"))
|
||||
import meshtext_auto_radio2 as hil
|
||||
|
||||
|
||||
class MeshInterfaceError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class PresetEnum:
|
||||
values = {p.stock_enum: index for index, p in enumerate(hil.PRESETS) if p.stock_enum}
|
||||
|
||||
@classmethod
|
||||
def keys(cls):
|
||||
return cls.values.keys()
|
||||
|
||||
@classmethod
|
||||
def Value(cls, name):
|
||||
return cls.values[name]
|
||||
|
||||
|
||||
def fake_sdk():
|
||||
package = ModuleType("meshtastic")
|
||||
package.__path__ = []
|
||||
protobuf = ModuleType("meshtastic.protobuf")
|
||||
protobuf.__path__ = []
|
||||
channel = ModuleType("meshtastic.protobuf.channel_pb2")
|
||||
channel.Channel = SimpleNamespace(PRIMARY=1)
|
||||
config = ModuleType("meshtastic.protobuf.config_pb2")
|
||||
config.Config = SimpleNamespace(DeviceConfig=SimpleNamespace(CLIENT_MUTE=1),
|
||||
LoRaConfig=SimpleNamespace(US=1, ModemPreset=PresetEnum))
|
||||
interface = ModuleType("meshtastic.mesh_interface")
|
||||
interface.MeshInterface = SimpleNamespace(MeshInterfaceError=MeshInterfaceError)
|
||||
util = ModuleType("meshtastic.util")
|
||||
util.to_node_num = int
|
||||
package.protobuf, package.mesh_interface = protobuf, interface
|
||||
protobuf.channel_pb2, protobuf.config_pb2 = channel, config
|
||||
return {module.__name__: module for module in (package, protobuf, channel, config, interface, util)}
|
||||
|
||||
|
||||
class Node:
|
||||
def __init__(self):
|
||||
self.localConfig = SimpleNamespace(device=SimpleNamespace(role=0),
|
||||
lora=SimpleNamespace(modem_preset=0))
|
||||
self.channels = [SimpleNamespace(role=0, settings=SimpleNamespace(
|
||||
name="before", psk=b"old", uplink_enabled=True, downlink_enabled=True))]
|
||||
self.calls = []
|
||||
self.written_lora = None
|
||||
self.nodeNum = 0x12345678
|
||||
|
||||
def ensureSessionKey(self):
|
||||
self.calls.append("session")
|
||||
|
||||
def beginSettingsTransaction(self):
|
||||
self.calls.append("begin")
|
||||
|
||||
def writeChannel(self, index):
|
||||
self.calls.append(("channel", index))
|
||||
|
||||
def writeConfig(self, name):
|
||||
self.calls.append(("config", name))
|
||||
if name == "lora":
|
||||
self.written_lora = copy.deepcopy(self.localConfig.lora)
|
||||
|
||||
def commitSettingsTransaction(self):
|
||||
self.calls.append("commit")
|
||||
|
||||
|
||||
class StockConfigurationTests(unittest.TestCase):
|
||||
def configure(self, preset, *, normalized=False, handshake_misses=0, session_misses=0,
|
||||
readback_cr=None):
|
||||
node = Node()
|
||||
session_reads = []
|
||||
|
||||
def session_node(node_num):
|
||||
self.assertEqual(node_num, node.nodeNum)
|
||||
session_reads.append(True)
|
||||
return {} if len(session_reads) <= session_misses else {"adminSessionPassKey": b"mock-key"}
|
||||
|
||||
iface = SimpleNamespace(localNode=node, myInfo=SimpleNamespace(my_node_num=0x12345678),
|
||||
metadata=SimpleNamespace(firmware_version="mock-stable"), close=lambda: None,
|
||||
_getOrCreateByNum=session_node)
|
||||
stock = hil.StockPeer.__new__(hil.StockPeer)
|
||||
stock.iface = iface
|
||||
attempts = []
|
||||
|
||||
def connect():
|
||||
attempts.append(True)
|
||||
if len(attempts) <= handshake_misses:
|
||||
raise MeshInterfaceError("transient simulated boot handshake")
|
||||
# The official stock boot helper derives BW/SF from the preset.
|
||||
if normalized and preset.stock_enum:
|
||||
node.localConfig.lora.bandwidth = preset.bandwidth
|
||||
node.localConfig.lora.spread_factor = preset.sf
|
||||
if readback_cr is not None:
|
||||
node.localConfig.lora.coding_rate = readback_cr
|
||||
stock.iface = iface
|
||||
|
||||
stock.connect = connect
|
||||
with patch.dict(sys.modules, fake_sdk()), patch.object(hil.time, "sleep"), \
|
||||
patch.object(hil.time, "monotonic", side_effect=range(1, 250)):
|
||||
result = stock.configure(preset, bytes(range(16)), -9, 7)
|
||||
return node, result, attempts
|
||||
|
||||
def test_nine_native_presets_clear_bw_sf_and_keep_native_cr_with_hash_slot(self):
|
||||
for preset in hil.PRESETS:
|
||||
if not preset.stock_enum:
|
||||
continue
|
||||
with self.subTest(preset=preset.name):
|
||||
node, result, _ = self.configure(preset)
|
||||
lora = node.written_lora
|
||||
self.assertTrue(lora.use_preset)
|
||||
self.assertEqual(lora.modem_preset, PresetEnum.Value(preset.stock_enum))
|
||||
# Stock clamps a zero CR to 5 instead of selecting preset CR.
|
||||
self.assertEqual((lora.bandwidth, lora.spread_factor, lora.coding_rate), (0, 0, preset.cr))
|
||||
self.assertEqual((lora.channel_num, lora.override_frequency, lora.frequency_offset), (0, 0, 0))
|
||||
self.assertEqual((lora.region, lora.tx_power, lora.hop_limit), (1, -9, 7))
|
||||
self.assertTrue(lora.tx_enabled and lora.ignore_mqtt)
|
||||
self.assertFalse(lora.config_ok_to_mqtt)
|
||||
self.assertEqual(node.calls, ["session", "begin", ("config", "device"),
|
||||
("config", "lora"), ("channel", 0), "commit"])
|
||||
self.assertEqual(node.channels[0].settings.name, preset.name)
|
||||
self.assertEqual(node.channels[0].settings.psk, bytes(range(16)))
|
||||
self.assertFalse(node.channels[0].settings.uplink_enabled)
|
||||
self.assertFalse(node.channels[0].settings.downlink_enabled)
|
||||
self.assertEqual(result["node"], "!12345678")
|
||||
|
||||
def test_native_stock_boot_normalization_is_not_a_readback_failure(self):
|
||||
for preset in hil.PRESETS:
|
||||
if preset.stock_enum:
|
||||
with self.subTest(preset=preset.name):
|
||||
node, _, _ = self.configure(preset, normalized=True)
|
||||
self.assertEqual(node.written_lora.bandwidth, 0)
|
||||
self.assertEqual(node.written_lora.spread_factor, 0)
|
||||
self.assertEqual(node.localConfig.lora.bandwidth, preset.bandwidth)
|
||||
|
||||
def test_custom_mediumturbo_tuple_and_explicit_calculated_slot(self):
|
||||
preset = next(p for p in hil.PRESETS if p.name == "MediumTurbo")
|
||||
node, _, _ = self.configure(preset)
|
||||
lora = node.written_lora
|
||||
self.assertFalse(lora.use_preset)
|
||||
self.assertEqual((lora.bandwidth, lora.spread_factor, lora.coding_rate), (500, 9, 5))
|
||||
self.assertEqual(lora.channel_num, 47)
|
||||
self.assertEqual(node.channels[0].settings.name, "MediumTurbo")
|
||||
|
||||
def test_transient_meshinterface_handshake_error_retries(self):
|
||||
_, _, attempts = self.configure(hil.PRESETS[0], handshake_misses=1)
|
||||
self.assertEqual(len(attempts), 2)
|
||||
|
||||
def test_async_admin_session_is_ready_before_writes(self):
|
||||
node, _, _ = self.configure(hil.PRESETS[0], session_misses=3)
|
||||
self.assertEqual(node.calls[0:2], ["session", "begin"])
|
||||
|
||||
def test_missing_admin_session_aborts_without_writing(self):
|
||||
with self.assertRaisesRegex(hil.TestFailure, "admin session setup timed out"):
|
||||
self.configure(hil.PRESETS[0], session_misses=100)
|
||||
|
||||
def test_zero_or_wrong_cr_is_not_accepted_as_native_readback(self):
|
||||
for preset_name, observed_cr in (("LongFast", 0), ("LongSlow", 5)):
|
||||
preset = next(p for p in hil.PRESETS if p.name == preset_name)
|
||||
with self.subTest(preset=preset_name, cr=observed_cr):
|
||||
with self.assertRaisesRegex(hil.TestFailure, "configuration readback did not match"):
|
||||
self.configure(preset, readback_cr=observed_cr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,491 @@
|
||||
"""Execute the bounded MT codec with real Crypto AES and an independent oracle.
|
||||
|
||||
No PlatformIO, hardware or downloaded sources are used. Set MESHCORE_CRYPTO_DIR
|
||||
to an existing rweather/Crypto checkout, or use the cached PlatformIO dependency.
|
||||
The Python cryptography package independently generates encrypted wire vectors.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_KEY = bytes.fromhex("d4f1bb3a20290759f0bcffabcf4e6901")
|
||||
FROM, PACKET_ID = 0x11223344, 0x89ABCDEF
|
||||
|
||||
|
||||
def varint(value):
|
||||
encoded = bytearray()
|
||||
while value >= 128:
|
||||
encoded.append((value & 127) | 128)
|
||||
value >>= 7
|
||||
encoded.append(value)
|
||||
return bytes(encoded)
|
||||
|
||||
|
||||
def data_text(text):
|
||||
return b"\x08\x01\x12" + varint(len(text)) + text
|
||||
|
||||
|
||||
def data_nodeinfo(long_name, short_name, sender):
|
||||
# Independent handwritten schema oracle: User fields 1/2/3/7/9 only.
|
||||
user_id = ("!%08x" % sender).encode("ascii")
|
||||
user = b"\x0a" + varint(len(user_id)) + user_id
|
||||
if long_name:
|
||||
user += b"\x12" + varint(len(long_name)) + long_name
|
||||
user += b"\x1a" + varint(len(short_name)) + short_name
|
||||
user += b"\x38\x01\x48\x01" # CLIENT_MUTE=1, is_unmessagable=true.
|
||||
return b"\x08\x04\x12" + varint(len(user)) + user
|
||||
|
||||
|
||||
def reference_frame(data, name="LongFast", key=DEFAULT_KEY, *, to=0xFFFFFFFF,
|
||||
sender=FROM, packet_id=PACKET_ID, flags=0x63):
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
channel_hash = 0
|
||||
for byte in name.encode() + key:
|
||||
channel_hash ^= byte
|
||||
header = struct.pack("<III4B", to, sender, packet_id, flags, channel_hash, 0, 0)
|
||||
encryptor = Cipher(algorithms.AES(key), modes.CTR(struct.pack("<QQ", packet_id, sender))).encryptor()
|
||||
return header + encryptor.update(data) + encryptor.finalize()
|
||||
|
||||
|
||||
def array(value):
|
||||
return "{" + ",".join(map(str, value)) + "}"
|
||||
|
||||
|
||||
def literal(value):
|
||||
return '"' + "".join("\\x%02x" % byte for byte in value) + '"'
|
||||
|
||||
|
||||
HARNESS = r'''
|
||||
#include <helpers/MeshtextChat.h>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <initializer_list>
|
||||
using namespace mesh::mt;
|
||||
struct Golden {
|
||||
uint8_t key[32]; size_t key_len; const char* name; const char* text; size_t text_len;
|
||||
uint8_t frame[255]; size_t frame_len;
|
||||
};
|
||||
static const Golden golden[] = { @GOLDEN@ };
|
||||
// Stock 2.7.26 Router::perhapsEncode marks Data.bitfield present even when
|
||||
// config_ok_to_mqtt and want_response are both false: field 9 is 0x48,0x00.
|
||||
static const Golden stock_zero_bitfield[] = { @STOCK_ZERO_BITFIELD@ };
|
||||
struct NodeInfoGolden {
|
||||
uint8_t key[32]; size_t key_len; const char* name;
|
||||
const char* long_name; size_t long_name_len; const char* short_name; size_t short_name_len;
|
||||
uint32_t from, id; uint8_t hops; uint8_t frame[255]; size_t frame_len;
|
||||
};
|
||||
static const NodeInfoGolden node_info_golden[] = { @NODEINFO_GOLDEN@ };
|
||||
struct Malformed { const char* label; uint8_t frame[255]; size_t length; };
|
||||
static const Malformed malformed[] = { @MALFORMED@ };
|
||||
struct Modem {
|
||||
Region region; Preset preset; bool valid; float frequency, bandwidth; uint8_t sf, cr;
|
||||
};
|
||||
static const Modem modems[] = { @MODEMS@ };
|
||||
static void presets() {
|
||||
Preset preset = Preset::LongFast;
|
||||
for (const auto* name : {"ShortTurbo", "ShortFast", "ShortSlow", "MediumTurbo", "MediumFast",
|
||||
"MediumSlow", "LongTurbo", "LongFast", "LongMod", "LongSlow"}) {
|
||||
assert(parsePreset(name, preset)); assert(!strcmp(presetName(preset), name));
|
||||
}
|
||||
assert(parsePreset("LongModerate", preset) && preset == Preset::LongModerate);
|
||||
assert(parsePreset("longfast", preset) && preset == Preset::LongFast);
|
||||
assert(parsePreset("shortturbo", preset) && preset == Preset::ShortTurbo);
|
||||
assert(parsePreset("LoNgTuRbO", preset) && preset == Preset::LongTurbo);
|
||||
assert(parsePreset("LONGMODERATE", preset) && preset == Preset::LongModerate);
|
||||
for (const auto* invalid : {"", "Long-Fast", "LongUltra", "mt-LongFast", "LongFast "}) {
|
||||
preset = Preset::LongFast;
|
||||
assert(!parsePreset(invalid, preset) && preset == Preset::LongFast);
|
||||
}
|
||||
assert(!parsePreset(nullptr, preset));
|
||||
assert(presetName(static_cast<Preset>(255)) == nullptr);
|
||||
for (const auto& test : modems) {
|
||||
mesh::RadioProfileParams params;
|
||||
params.freq = 123; const auto original = params;
|
||||
assert(modemConfig(test.region, test.preset, params) == test.valid);
|
||||
if (!test.valid) { assert(params == original); continue; }
|
||||
assert(std::fabs(params.freq - test.frequency) < 0.0001f);
|
||||
assert(params.bw == test.bandwidth && params.sf == test.sf && params.cr == test.cr);
|
||||
assert(params.preamble == 16 && params.protocol == mesh::RadioProfileProtocol::Meshtext);
|
||||
assert(modemConfig(test.region, test.preset, params, 1));
|
||||
const float start = test.region == Region::US ? 902 : test.region == Region::EU868 ? 869.4f
|
||||
: test.region == Region::EU433 ? 433 : 915;
|
||||
const uint32_t width = test.region == Region::US ? 26000 : test.region == Region::EU868 ? 250
|
||||
: test.region == Region::EU433 ? 1000 : 13000;
|
||||
const uint32_t slots = width / static_cast<uint32_t>(test.bandwidth);
|
||||
assert(std::fabs(params.freq - (start + test.bandwidth / 2000)) < 0.0001f);
|
||||
assert(modemConfig(test.region, test.preset, params, slots));
|
||||
const auto last = params;
|
||||
assert(!modemConfig(test.region, test.preset, params, slots + 1) && params == last);
|
||||
assert(!modemConfig(test.region, test.preset, params, 0xffffffffU) && params == last);
|
||||
}
|
||||
mesh::RadioProfileParams params;
|
||||
assert(!modemConfig(Region::Unset, Preset::LongFast, params));
|
||||
assert(!modemConfig(static_cast<Region>(255), Preset::LongFast, params));
|
||||
assert(!modemConfig(Region::US, static_cast<Preset>(255), params));
|
||||
puts("PASS presets");
|
||||
}
|
||||
static void frames() {
|
||||
for (const auto& test : golden) {
|
||||
uint8_t frame[MaxFrameSize + 2]; memset(frame, 0xa5, sizeof(frame));
|
||||
const size_t length = encodeText(0x11223344, 0x89abcdef, 3, test.name, test.key, test.key_len,
|
||||
test.text, test.text_len, frame);
|
||||
assert(length == test.frame_len && !memcmp(frame, test.frame, length));
|
||||
assert(frame[MaxFrameSize] == 0xa5 && frame[MaxFrameSize + 1] == 0xa5);
|
||||
DecodedText decoded;
|
||||
assert(decodeText(test.frame, test.frame_len, test.name, test.key, test.key_len, 0x99887766, decoded));
|
||||
assert(decoded.from == 0x11223344 && decoded.id == 0x89abcdef);
|
||||
assert(decoded.hop_limit == 3 && decoded.hop_start == 3 && decoded.hops == 0);
|
||||
assert(decoded.text_len == test.text_len && !memcmp(decoded.text, test.text, test.text_len));
|
||||
assert(decoded.text[decoded.text_len] == 0);
|
||||
memcpy(frame, test.frame, test.frame_len); frame[12] = (7 << 5) | 2;
|
||||
assert(decodeText(frame, length, test.name, test.key, test.key_len, 0x99887766, decoded));
|
||||
assert(decoded.hops == 5 && decoded.hop_start == 7 && decoded.hop_limit == 2);
|
||||
frame[12] = 3; // older hop-start-less packets remain readable
|
||||
assert(decodeText(frame, length, test.name, test.key, test.key_len, 0x99887766, decoded));
|
||||
assert(decoded.hops == 0);
|
||||
assert(!decodeText(frame, length, test.name, test.key, test.key_len, 0x11223344, decoded));
|
||||
frame[13] ^= 1;
|
||||
assert(!decodeText(frame, length, test.name, test.key, test.key_len, 0x99887766, decoded));
|
||||
}
|
||||
assert(!memcmp(DefaultPsk, golden[0].key, 16));
|
||||
puts("PASS frames");
|
||||
}
|
||||
static void malformed_frames() {
|
||||
for (const auto& test : malformed) {
|
||||
DecodedText decoded;
|
||||
decoded.id = 123; strcpy(decoded.text, "unchanged"); decoded.text_len = 9;
|
||||
if (decodeText(test.frame, test.length, "LongFast", DefaultPsk, 16, 0x99887766, decoded)) {
|
||||
fprintf(stderr, "accepted malformed vector: %s\n", test.label); assert(false);
|
||||
}
|
||||
assert(decoded.id == 123 && decoded.text_len == 9 && !strcmp(decoded.text, "unchanged"));
|
||||
}
|
||||
puts("PASS malformed");
|
||||
}
|
||||
static void node_info_frames() {
|
||||
static_assert(MaxLongNameSize == 24, "stock long-name limit");
|
||||
static_assert(MaxShortNameSize == 4, "stock short-name max_size:5 includes NUL");
|
||||
for (const auto& test : node_info_golden) {
|
||||
uint8_t frame[MaxFrameSize + 2]; memset(frame, 0xa5, sizeof(frame));
|
||||
const size_t length = encodeNodeInfo(test.from, test.id, test.hops, test.name, test.key, test.key_len,
|
||||
test.long_name, test.long_name_len,
|
||||
test.short_name, test.short_name_len, frame);
|
||||
// Full independent encrypted-frame equality also proves exact standard User
|
||||
// fields, matching nonce/header, and absence of Data.want_response/keys/MAC.
|
||||
assert(length == test.frame_len && !memcmp(frame, test.frame, length));
|
||||
assert(frame[length] == 0xa5 && frame[MaxFrameSize] == 0xa5 && frame[MaxFrameSize + 1] == 0xa5);
|
||||
assert((frame[12] & 0x18) == 0); // Neither want_ack nor via_mqtt.
|
||||
assert((frame[12] & 7) == test.hops && (frame[12] >> 5) == test.hops);
|
||||
assert(frame[14] == 0 && frame[15] == 0);
|
||||
DecodedText decoded; decoded.id = 123; strcpy(decoded.text, "unchanged");
|
||||
assert(!decodeText(frame, length, test.name, test.key, test.key_len, 0x99887766, decoded));
|
||||
assert(decoded.id == 123 && !strcmp(decoded.text, "unchanged")); // NodeInfo RX still ignored.
|
||||
}
|
||||
puts("PASS nodeinfo");
|
||||
}
|
||||
static void node_info_bounds() {
|
||||
uint8_t frame[MaxFrameSize]; memset(frame, 0xa5, sizeof(frame));
|
||||
const auto invalid = [&](uint32_t from, uint32_t id, uint8_t hops, const char* name,
|
||||
const uint8_t* key, size_t key_len, const char* long_name, size_t long_len,
|
||||
const char* short_name, size_t short_len) {
|
||||
assert(!encodeNodeInfo(from, id, hops, name, key, key_len, long_name, long_len, short_name, short_len, frame));
|
||||
for (uint8_t byte : frame) assert(byte == 0xa5); // Rejection writes no partial packet.
|
||||
};
|
||||
char long_name[MaxLongNameSize + 1]; memset(long_name, 'L', sizeof(long_name));
|
||||
char short_name[MaxShortNameSize + 1]; memset(short_name, 'S', sizeof(short_name));
|
||||
for (uint32_t from : {0U, 1U, 2U, 3U, 0xffffffffU})
|
||||
invalid(from, 1, 7, "LongFast", DefaultPsk, 16, "long", 4, "shrt", 4);
|
||||
invalid(4, 0, 7, "LongFast", DefaultPsk, 16, "long", 4, "shrt", 4);
|
||||
invalid(4, 1, 8, "LongFast", DefaultPsk, 16, "long", 4, "shrt", 4);
|
||||
for (const auto* name : {static_cast<const char*>(nullptr), "", "123456789012"})
|
||||
invalid(4, 1, 7, name, DefaultPsk, 16, "long", 4, "shrt", 4);
|
||||
for (size_t key_len : {size_t(0), size_t(1), size_t(15), size_t(17), size_t(31), size_t(33)})
|
||||
invalid(4, 1, 7, "LongFast", DefaultPsk, key_len, "long", 4, "shrt", 4);
|
||||
invalid(4, 1, 7, "LongFast", nullptr, 16, "long", 4, "shrt", 4);
|
||||
invalid(4, 1, 7, "LongFast", DefaultPsk, 16, nullptr, 0, "shrt", 4);
|
||||
invalid(4, 1, 7, "LongFast", DefaultPsk, 16, "long", 4, nullptr, 4);
|
||||
invalid(4, 1, 7, "LongFast", DefaultPsk, 16, "long", 4, "", 0);
|
||||
for (size_t size : {MaxLongNameSize + 1, size_t(-1)})
|
||||
invalid(4, 1, 7, "LongFast", DefaultPsk, 16, long_name, size, "shrt", 4);
|
||||
for (size_t size : {MaxShortNameSize + 1, size_t(-1)})
|
||||
invalid(4, 1, 7, "LongFast", DefaultPsk, 16, "long", 4, short_name, size);
|
||||
const char* bad_names[] = {"\0", "\xc0\xaf", "\xe0\x80\x80", "\xed\xa0\x80",
|
||||
"\xf0\x80\x80\x80", "\xf4\x90\x80\x80", "\x80", "\xc2", "\xe2\x82"};
|
||||
const size_t bad_lengths[] = {1, 2, 3, 3, 4, 4, 1, 1, 2};
|
||||
for (size_t i = 0; i < sizeof(bad_lengths) / sizeof(bad_lengths[0]); ++i) {
|
||||
invalid(4, 1, 7, "LongFast", DefaultPsk, 16, bad_names[i], bad_lengths[i], "shrt", 4);
|
||||
invalid(4, 1, 7, "LongFast", DefaultPsk, 16, "long", 4, bad_names[i], bad_lengths[i]);
|
||||
}
|
||||
const char embedded_nul[] = {'a', 0, 'b'};
|
||||
invalid(4, 1, 7, "LongFast", DefaultPsk, 16, embedded_nul, 3, "shrt", 4);
|
||||
invalid(4, 1, 7, "LongFast", DefaultPsk, 16, "long", 4, embedded_nul, 3);
|
||||
assert(!encodeNodeInfo(4, 1, 7, "LongFast", DefaultPsk, 16, "long", 4, "shrt", 4, nullptr));
|
||||
// Exact-length byte arrays need no trailing NUL; the codec never scans them.
|
||||
assert(encodeNodeInfo(4, 1, 7, "LongFast", DefaultPsk, 16,
|
||||
long_name, MaxLongNameSize, short_name, MaxShortNameSize, frame));
|
||||
assert(encodeNodeInfo(4, 1, 0, "LongFast", DefaultPsk, 16, "", 0, "a", 1, frame));
|
||||
// A single non-ASCII scalar can occupy the complete four-byte stock field.
|
||||
assert(encodeNodeInfo(4, 1, 3, "LongFast", DefaultPsk, 16, "\xc3\xa9", 2, "\xf0\x9f\x9a\x80", 4, frame));
|
||||
puts("PASS nodeinfo_bounds");
|
||||
}
|
||||
static void argument_bounds() {
|
||||
uint8_t frame[MaxFrameSize] = {};
|
||||
char text[MaxTextSize + 2]; memset(text, 'x', sizeof(text));
|
||||
assert(encodeText(1, 1, 7, "LongFast", DefaultPsk, 16, text, MaxTextSize, frame));
|
||||
for (size_t length : {size_t(0), MaxTextSize + 1, size_t(0xffffffffU)})
|
||||
assert(!encodeText(1, 1, 3, "LongFast", DefaultPsk, 16, text, length, frame));
|
||||
assert(!encodeText(0, 1, 3, "LongFast", DefaultPsk, 16, text, 1, frame));
|
||||
assert(!encodeText(0xffffffffU, 1, 3, "LongFast", DefaultPsk, 16, text, 1, frame));
|
||||
assert(!encodeText(1, 0, 3, "LongFast", DefaultPsk, 16, text, 1, frame));
|
||||
assert(!encodeText(1, 1, 8, "LongFast", DefaultPsk, 16, text, 1, frame));
|
||||
assert(encodeText(1, 1, 3, "12345678901", DefaultPsk, 16, text, 1, frame));
|
||||
for (const auto* name : {static_cast<const char*>(nullptr), "", "123456789012", "01234567890123456789012345678901xx"})
|
||||
assert(!encodeText(1, 1, 3, name, DefaultPsk, 16, text, 1, frame));
|
||||
for (size_t key_length : {size_t(0), size_t(1), size_t(15), size_t(17), size_t(31), size_t(33)})
|
||||
assert(!encodeText(1, 1, 3, "LongFast", DefaultPsk, key_length, text, 1, frame));
|
||||
assert(!encodeText(1, 1, 3, "LongFast", nullptr, 16, text, 1, frame));
|
||||
assert(!encodeText(1, 1, 3, "LongFast", DefaultPsk, 16, nullptr, 1, frame));
|
||||
assert(!encodeText(1, 1, 3, "LongFast", DefaultPsk, 16, text, 1, nullptr));
|
||||
const char* invalid_utf8[] = {"\0", "\xc0\xaf", "\xe0\x80\x80", "\xed\xa0\x80",
|
||||
"\xf0\x80\x80\x80", "\xf4\x90\x80\x80", "\x80", "\xc2", "\xe2\x82"};
|
||||
const size_t lengths[] = {1, 2, 3, 3, 4, 4, 1, 1, 2};
|
||||
for (size_t i = 0; i < sizeof(lengths) / sizeof(lengths[0]); ++i)
|
||||
assert(!encodeText(1, 1, 3, "LongFast", DefaultPsk, 16, invalid_utf8[i], lengths[i], frame));
|
||||
const char nul_text[] = {'a', 0, 'b'};
|
||||
assert(!encodeText(1, 1, 3, "LongFast", DefaultPsk, 16, nul_text, 3, frame));
|
||||
DecodedText decoded;
|
||||
assert(!decodeText(nullptr, 50, "LongFast", DefaultPsk, 16, 0, decoded));
|
||||
assert(!decodeText(frame, 0, "LongFast", DefaultPsk, 16, 0, decoded));
|
||||
assert(!decodeText(frame, 256, "LongFast", DefaultPsk, 16, 0, decoded));
|
||||
assert(!decodeText(frame, 50, "LongFast", nullptr, 16, 0, decoded));
|
||||
assert(!decodeText(frame, 50, nullptr, DefaultPsk, 16, 0, decoded));
|
||||
puts("PASS bounds");
|
||||
}
|
||||
static void extensions() {
|
||||
const uint8_t frame[] = @EXTENSION_FRAME@;
|
||||
DecodedText decoded;
|
||||
assert(decodeText(frame, sizeof(frame), "LongFast", DefaultPsk, 16, 0x99887766, decoded));
|
||||
assert(decoded.text_len == 1 && !strcmp(decoded.text, "x"));
|
||||
// Header ACK/request flags do not make this passive decoder transmit.
|
||||
const uint8_t requests[] = @REQUEST_FRAME@;
|
||||
assert(decodeText(requests, sizeof(requests), "LongFast", DefaultPsk, 16, 0x99887766, decoded));
|
||||
puts("PASS extensions");
|
||||
}
|
||||
static void stock_zero_bitfield_frames() {
|
||||
for (const auto& test : stock_zero_bitfield) {
|
||||
DecodedText decoded;
|
||||
assert(decodeText(test.frame, test.frame_len, test.name, test.key, test.key_len,
|
||||
0x99887766, decoded));
|
||||
assert(decoded.from == 0x11223344 && decoded.id == 0x89abcdef);
|
||||
assert(decoded.hop_limit == 7 && decoded.hop_start == 7 && decoded.hops == 0);
|
||||
assert((test.frame[12] & 0x18) == 0); // Stock SDK requested neither ACK nor MQTT.
|
||||
assert(decoded.text_len == test.text_len && !memcmp(decoded.text, test.text, test.text_len));
|
||||
assert(decoded.text[decoded.text_len] == 0);
|
||||
}
|
||||
puts("PASS stock_zero_bitfield");
|
||||
}
|
||||
static void dedup() {
|
||||
SeenPackets seen;
|
||||
assert(!seen.seen(1, 1));
|
||||
assert(seen.remember(1, 1)); assert(seen.seen(1, 1)); assert(!seen.remember(1, 1));
|
||||
assert(seen.remember(2, 1)); // same ID from another sender is distinct
|
||||
assert(!seen.remember(0, 1) && !seen.remember(1, 0) && !seen.remember(0xffffffffU, 1));
|
||||
seen.clear(); assert(!seen.seen(1, 1));
|
||||
for (uint32_t i = 1; i <= SeenPackets::Capacity; ++i) assert(seen.remember(1, i));
|
||||
assert(seen.seen(1, 1)); assert(seen.remember(1, 33)); assert(!seen.seen(1, 1));
|
||||
// Invalid data never poisons dedup; the subsequent valid frame is accepted.
|
||||
seen.clear(); DecodedText decoded;
|
||||
for (const auto& test : malformed)
|
||||
if (decodeText(test.frame, test.length, "LongFast", DefaultPsk, 16, 0x99887766, decoded))
|
||||
seen.remember(decoded.from, decoded.id);
|
||||
assert(!seen.seen(0x11223344, 0x89abcdef));
|
||||
assert(decodeText(golden[0].frame, golden[0].frame_len, "LongFast", DefaultPsk, 16, 0x99887766, decoded));
|
||||
assert(seen.remember(decoded.from, decoded.id));
|
||||
assert(!seen.remember(decoded.from, decoded.id));
|
||||
// Successful own TX uses the same pair cache to suppress over-air echoes.
|
||||
seen.clear(); assert(seen.remember(0x11223344, 0x89abcdef));
|
||||
assert(seen.seen(0x11223344, 0x89abcdef));
|
||||
puts("PASS dedup");
|
||||
}
|
||||
int main(int argc, char** argv) {
|
||||
assert(argc == 2);
|
||||
if (!strcmp(argv[1], "presets")) presets();
|
||||
else if (!strcmp(argv[1], "frames")) frames();
|
||||
else if (!strcmp(argv[1], "malformed")) malformed_frames();
|
||||
else if (!strcmp(argv[1], "nodeinfo")) node_info_frames();
|
||||
else if (!strcmp(argv[1], "nodeinfo_bounds")) node_info_bounds();
|
||||
else if (!strcmp(argv[1], "bounds")) argument_bounds();
|
||||
else if (!strcmp(argv[1], "extensions")) extensions();
|
||||
else if (!strcmp(argv[1], "stock_zero_bitfield")) stock_zero_bitfield_frames();
|
||||
else if (!strcmp(argv[1], "dedup")) dedup();
|
||||
else assert(false);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def vectors():
|
||||
inputs = [(DEFAULT_KEY, "LongFast", b"hello"),
|
||||
(bytes(range(32)), "LongTurbo", "caf\u00e9 \U0001f6f0\ufe0f".encode()),
|
||||
(bytes(range(16)), "LongMod", bytes(range(33, 127))),
|
||||
(DEFAULT_KEY, "LongFast", b"a" * 127),
|
||||
(DEFAULT_KEY, "LongFast", b"b" * 128),
|
||||
(bytes(range(32)), "LongTurbo", b"c" * 228),
|
||||
(DEFAULT_KEY, "LongFast", "\u0080\u07ff\u0800\ud7ff\ue000\uffff\U00010000\U0010ffff".encode())]
|
||||
golden = []
|
||||
for key, name, text in inputs:
|
||||
frame = reference_frame(data_text(text), name, key)
|
||||
golden.append("{" + array(key) + "," + str(len(key)) + ',"' + name + '",'
|
||||
+ literal(text) + "," + str(len(text)) + "," + array(frame) + "," + str(len(frame)) + "}")
|
||||
stock_zero_bitfield = []
|
||||
for key, name in [(bytes(range(16)), "ShortTurbo"), (bytes(range(32)), "LongFast")]:
|
||||
text = "stock field9 zero caf\u00e9".encode()
|
||||
# Independently encrypted exact stock Data shape, not our encodeText:
|
||||
# TEXT_MESSAGE_APP + UTF-8 payload + OPTIONAL uint32 bitfield=0.
|
||||
data = data_text(text) + b"\x48\x00"
|
||||
frame = reference_frame(data, name, key, flags=0xE7)
|
||||
stock_zero_bitfield.append("{" + array(key) + "," + str(len(key)) + ',"' + name + '",'
|
||||
+ literal(text) + "," + str(len(text)) + ","
|
||||
+ array(frame) + "," + str(len(frame)) + "}")
|
||||
node_inputs = [(DEFAULT_KEY, "LongFast", b"MeshCore", b"CORE", FROM, 7),
|
||||
(bytes(range(32)), "LongTurbo", ("\u00e9" * 12).encode(), "\U0001f680".encode(), 0xABCDEF12, 0),
|
||||
(bytes(range(16)), "LongMod", b"L" * 24, "\u00e9\u00e9".encode(), 4, 3),
|
||||
(bytes(range(32)), "private", b"", b"a", 0xFFFFFFFE, 1)]
|
||||
node_inputs += [(DEFAULT_KEY, "LongFast", "\u6d4b\u8bd5".encode(), "\u6d4bA".encode(), FROM, hops)
|
||||
for hops in (2, 4, 5, 6)]
|
||||
node_info = []
|
||||
for offset, (key, name, long_name, short_name, sender, hops) in enumerate(node_inputs):
|
||||
packet_id = PACKET_ID + offset
|
||||
frame = reference_frame(data_nodeinfo(long_name, short_name, sender), name, key,
|
||||
sender=sender, packet_id=packet_id, flags=hops | (hops << 5))
|
||||
node_info.append("{" + array(key) + "," + str(len(key)) + ',"' + name + '",'
|
||||
+ literal(long_name) + "," + str(len(long_name)) + ","
|
||||
+ literal(short_name) + "," + str(len(short_name)) + ","
|
||||
+ str(sender) + "U," + str(packet_id) + "U," + str(hops) + ","
|
||||
+ array(frame) + "," + str(len(frame)) + "}")
|
||||
bad_data = {
|
||||
"empty Data": b"", "missing port": b"\x12\x01x", "missing text": b"\x08\x01",
|
||||
"empty text": b"\x08\x01\x12\x00", "other app": b"\x08\x02\x12\x01x",
|
||||
"wrong port wire": b"\x0a\x01\x01\x12\x01x", "wrong payload wire": b"\x08\x01\x10\x01",
|
||||
"truncated length": b"\x08\x01\x12\x80", "oversized length": b"\x08\x01\x12\xff\x01x",
|
||||
"field zero": b"\x00" + data_text(b"x"), "unknown group wire": data_text(b"x") + b"\x53",
|
||||
"overflow varint": b"\xff" * 9 + b"\x02", "noncanonical tag": b"\x88\x00\x01\x12\x01x",
|
||||
"duplicate port": data_text(b"x") + b"\x08\x01", "duplicate text": data_text(b"x") + b"\x12\x01y",
|
||||
"UTF8 surrogate": data_text(b"\xed\xa0\x80"), "embedded NUL": data_text(b"x\x00y"),
|
||||
"proxied DM dest": data_text(b"x") + b"\x25" + struct.pack("<I", 0x99887766),
|
||||
"invalid boolean": data_text(b"x") + b"\x18\x02", "bad source wire": data_text(b"x") + b"\x28\x01",
|
||||
"truncated fixed32": data_text(b"x") + b"\x25\x00\x00",
|
||||
"truncated unknown fixed64": data_text(b"x") + b"\x51\x00",
|
||||
"long text": data_text(b"x" * 229),
|
||||
}
|
||||
rejected = [(label, reference_frame(data)) for label, data in bad_data.items()]
|
||||
rejected += [("DM", reference_frame(data_text(b"x"), to=0x99887766)),
|
||||
("zero sender", reference_frame(data_text(b"x"), sender=0)),
|
||||
("reserved sender", reference_frame(data_text(b"x"), sender=0xFFFFFFFF)),
|
||||
("zero packet ID", reference_frame(data_text(b"x"), packet_id=0)),
|
||||
("short header", reference_frame(data_text(b"x"))[:15]),
|
||||
("overlong frame", bytes(250))]
|
||||
malformed = ["{\"" + label + "\"," + array(frame) + "," + str(len(frame)) + "}" for label, frame in rejected]
|
||||
extension = reference_frame(data_text(b"x") + b"\x50\x81\x01\x59" + bytes(8)
|
||||
+ b"\x62\x03abc\x6d" + bytes(4))
|
||||
request = reference_frame(data_text(b"x") + b"\x18\x01", flags=0x6B)
|
||||
presets = [("ShortTurbo", 500000, 7, 5), ("ShortFast", 250000, 7, 5),
|
||||
("ShortSlow", 250000, 8, 5), ("MediumTurbo", 500000, 9, 5),
|
||||
("MediumFast", 250000, 9, 5), ("MediumSlow", 250000, 10, 5),
|
||||
("LongTurbo", 500000, 11, 8), ("LongFast", 250000, 11, 5),
|
||||
("LongModerate", 125000, 11, 8), ("LongSlow", 125000, 12, 8)]
|
||||
modems = []
|
||||
for region, start, end in [("US", 902000000, 928000000), ("EU868", 869400000, 869650000),
|
||||
("EU433", 433000000, 434000000), ("ANZ", 915000000, 928000000)]:
|
||||
for preset, bandwidth, sf, cr in presets:
|
||||
name = "LongMod" if preset == "LongModerate" else preset
|
||||
name_hash = 5381
|
||||
for byte in name.encode():
|
||||
name_hash = (name_hash * 33 + byte) & 0xFFFFFFFF
|
||||
slots = (end - start) // bandwidth
|
||||
frequency = (start + bandwidth // 2 + (name_hash % slots) * bandwidth) / 1e6 if slots else 0.0
|
||||
modems.append("{Region::" + region + ",Preset::" + preset + "," + str(bool(slots)).lower()
|
||||
+ "," + str(frequency) + "f," + str(bandwidth / 1000) + "f," + str(sf) + "," + str(cr) + "}")
|
||||
return (HARNESS.replace("@GOLDEN@", ",\n".join(golden)).replace("@MALFORMED@", ",\n".join(malformed))
|
||||
.replace("@STOCK_ZERO_BITFIELD@", ",\n".join(stock_zero_bitfield))
|
||||
.replace("@NODEINFO_GOLDEN@", ",\n".join(node_info))
|
||||
.replace("@MODEMS@", ",\n".join(modems)).replace("@EXTENSION_FRAME@", array(extension))
|
||||
.replace("@REQUEST_FRAME@", array(request)))
|
||||
|
||||
|
||||
class MeshtextChatTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
try:
|
||||
import cryptography # noqa: F401
|
||||
except ImportError:
|
||||
raise unittest.SkipTest("Python cryptography is required for the independent AES oracle")
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if not compiler:
|
||||
raise unittest.SkipTest("a host C++ compiler is required")
|
||||
required = ["AESCommon.cpp", "AES128.cpp", "AES256.cpp", "BlockCipher.cpp", "Crypto.cpp"]
|
||||
override = os.environ.get("MESHCORE_CRYPTO_DIR")
|
||||
candidates = [Path(override)] if override else sorted((ROOT / ".pio/libdeps").glob("*/Crypto"))
|
||||
crypto = next((path for path in candidates if all((path / item).is_file() for item in required)), None)
|
||||
if not crypto:
|
||||
raise unittest.SkipTest("an existing rweather/Crypto dependency is required (MESHCORE_CRYPTO_DIR)")
|
||||
cls.temp = tempfile.TemporaryDirectory(prefix="meshcore-mt-codec-")
|
||||
cls.addClassCleanup(cls.temp.cleanup)
|
||||
work = Path(cls.temp.name)
|
||||
source = work / "chat.cpp"
|
||||
source.write_text(vectors(), encoding="utf-8")
|
||||
cls.binary = work / ("chat.exe" if sys.platform == "win32" else "chat")
|
||||
sanitizers = (["-fsanitize=address,undefined", "-fno-sanitize-recover=all", "-fno-pie", "-no-pie"]
|
||||
if sys.platform.startswith("linux") else [])
|
||||
result = subprocess.run(
|
||||
[compiler, "-std=c++11", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
|
||||
"-DMESH_ENABLE_MESHTEXT_CHAT=1",
|
||||
*sanitizers, "-I" + str(ROOT / "src"), "-I" + str(crypto), str(source),
|
||||
str(ROOT / "src/helpers/MeshtextChat.cpp"), *[str(crypto / item) for item in required],
|
||||
"-o", str(cls.binary)], capture_output=True, text=True, timeout=60,
|
||||
)
|
||||
if result.returncode:
|
||||
raise AssertionError(result.stdout + result.stderr)
|
||||
|
||||
def run_case(self, name):
|
||||
result = subprocess.run([str(self.binary), name], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("PASS " + name, result.stdout)
|
||||
|
||||
def test_modem_presets_regions_and_strict_slots(self):
|
||||
self.run_case("presets")
|
||||
|
||||
def test_actual_aes128_aes256_against_independent_golden_frames(self):
|
||||
self.run_case("frames")
|
||||
|
||||
def test_malformed_protobuf_utf8_and_broadcast_only(self):
|
||||
self.run_case("malformed")
|
||||
|
||||
def test_explicit_standard_nodeinfo_aes128_aes256_all_hops_and_no_receive(self):
|
||||
self.run_case("nodeinfo")
|
||||
|
||||
def test_nodeinfo_stock_name_utf8_and_argument_bounds(self):
|
||||
self.run_case("nodeinfo_bounds")
|
||||
|
||||
def test_argument_and_text_bounds(self):
|
||||
self.run_case("bounds")
|
||||
|
||||
def test_safe_unknown_fields_and_no_request_response_action(self):
|
||||
self.run_case("extensions")
|
||||
|
||||
def test_stock_present_zero_bitfield_broadcast_hops7_aes128_and_aes256(self):
|
||||
self.run_case("stock_zero_bitfield")
|
||||
|
||||
def test_dedup_only_valid_packets_and_own_tx(self):
|
||||
self.run_case("dedup")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,203 @@
|
||||
"""Qualify linked chat code and ship its MIT notice without touching firmware."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import package_meshtext_license as license
|
||||
import firmware_memory_manifest as memory
|
||||
import firmware_build_recipe as recipe
|
||||
import package_cascade_release as release
|
||||
|
||||
SYMBOLS = ("_ZN4mesh2mt10encodeTextEj", "_ZN4mesh2mt10decodeTextEj",
|
||||
"_ZN6MyMesh16sendMeshtextTextEj", "_ZN6MyMesh19onForeignRadioFrameEj",
|
||||
"_ZN4mesh10Dispatcher22queueForeignRadioFrameEj")
|
||||
|
||||
|
||||
def elf32(path, symbols=SYMBOLS, flags=6, undefined=(), zero=()):
|
||||
names, table = bytearray(b"\0"), bytearray(16)
|
||||
data = b"CODE" * max(1, len(symbols))
|
||||
for i, name in enumerate(symbols):
|
||||
offset = len(names)
|
||||
names += name.encode() + b"\0"
|
||||
table += struct.pack("<IIIBBH", offset, 0x40000000 + i * 4,
|
||||
0 if name in zero else 4, 0x12, 0, 0 if name in undefined else 1)
|
||||
payload = 52 + 4 * 40
|
||||
strings = payload + len(data)
|
||||
symtab = strings + len(names)
|
||||
header = b"\x7fELF\x01\x01\x01" + bytes(9)
|
||||
header += struct.pack("<HH5I6H", 2, 40, 1, 0, 0, 52, 0, 52, 0, 0, 40, 4, 0)
|
||||
sections = bytes(40)
|
||||
sections += struct.pack("<10I", 0, 1, flags, 0x40000000, payload, len(data), 0, 0, 4, 0)
|
||||
sections += struct.pack("<10I", 0, 3, 0, 0, strings, len(names), 0, 0, 1, 0)
|
||||
sections += struct.pack("<10I", 0, 2, 0, 0, symtab, len(table), 2, 1, 4, 16)
|
||||
path.write_bytes(header + sections + data + names + table)
|
||||
|
||||
|
||||
class MeshtextLicenseTest(unittest.TestCase):
|
||||
def qualify(self, build, stem):
|
||||
output = stem.parent / (stem.name + ".capabilities.json")
|
||||
result = subprocess.run([sys.executable, str(ROOT / "scripts/check_firmware_capabilities.py"),
|
||||
"--image", str(build / "firmware.elf"), "--output", str(output),
|
||||
"--target", "test_companion_radio_usb", "--platform", "ESP32_PLATFORM",
|
||||
"--build-profile", "standard"], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
return json.loads(output.read_text())
|
||||
|
||||
@unittest.skipUnless(sys.platform.startswith("linux"), "requires a Linux ELF compiler")
|
||||
def test_compiler_produced_symbols_qualify_chat_and_notice(self):
|
||||
compiler = shutil.which("g++")
|
||||
if compiler is None:
|
||||
self.skipTest("g++ is not installed")
|
||||
# Do not build symbol spellings from SYMBOLS: the compiler must independently
|
||||
# produce the Itanium name lengths that the production matcher recognizes.
|
||||
source = """
|
||||
namespace mesh {
|
||||
namespace mt {
|
||||
unsigned encodeText(unsigned value) { return value + 1; }
|
||||
unsigned decodeText(unsigned value) { return value + 2; }
|
||||
}
|
||||
class Dispatcher {
|
||||
public: unsigned queueForeignRadioFrame(unsigned);
|
||||
};
|
||||
unsigned Dispatcher::queueForeignRadioFrame(unsigned value) { return value + 3; }
|
||||
}
|
||||
class MyMesh {
|
||||
public:
|
||||
unsigned sendMeshtextText(unsigned);
|
||||
unsigned onForeignRadioFrame(unsigned);
|
||||
};
|
||||
unsigned MyMesh::sendMeshtextText(unsigned value) { return value + 4; }
|
||||
unsigned MyMesh::onForeignRadioFrame(unsigned value) { return value + 5; }
|
||||
extern "C" void _start() {}
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
input_path = root / "linked.cpp"
|
||||
input_path.write_text(source)
|
||||
result = subprocess.run([compiler, "-m32", "-O0", "-fno-pie", "-no-pie",
|
||||
"-fno-exceptions", "-fno-rtti", "-fno-stack-protector", "-nostdlib",
|
||||
"-Wl,-e,_start", "-Wl,--build-id=none", str(input_path),
|
||||
"-o", str(root / "firmware.elf")], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
codec, chat = license.meshtext_evidence(root / "firmware.elf")
|
||||
self.assertEqual(len(codec), 2)
|
||||
self.assertEqual(len(chat), 5)
|
||||
manifest = self.qualify(root, root / "compiled")
|
||||
self.assertIn(license.CAPABILITY, manifest["capabilities"])
|
||||
self.assertEqual(manifest["verification"][0]["source"], "linked ELF symbols")
|
||||
self.assertEqual(license.collect_build_notice(root, root / "compiled").read_bytes(),
|
||||
license.notice_bytes())
|
||||
|
||||
def test_only_allocated_defined_executable_symbols_qualify(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "firmware.elf"
|
||||
elf32(path)
|
||||
codec, chat = license.meshtext_evidence(path)
|
||||
self.assertEqual(len(codec), 2)
|
||||
self.assertEqual(len(chat), 5)
|
||||
for flags in (0, 2, 4):
|
||||
elf32(path, flags=flags)
|
||||
self.assertEqual(license.meshtext_evidence(path), ([], []))
|
||||
for missing in SYMBOLS:
|
||||
elf32(path, undefined=(missing,))
|
||||
self.assertFalse(license.meshtext_evidence(path)[1])
|
||||
elf32(path, zero=(missing,))
|
||||
self.assertFalse(license.meshtext_evidence(path)[1])
|
||||
path.write_bytes(b"debug strings " + b"\0".join(s.encode() for s in SYMBOLS))
|
||||
self.assertEqual(license.meshtext_evidence(path), ([], []))
|
||||
|
||||
def test_partial_codec_still_requires_license_but_never_advertises_chat(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
elf32(root / "firmware.elf", symbols=SYMBOLS[:1])
|
||||
manifest = self.qualify(root, root / "partial")
|
||||
self.assertNotIn(license.CAPABILITY, manifest["capabilities"])
|
||||
self.assertEqual(manifest["third_party_notices"][0]["license"], "MIT")
|
||||
self.assertEqual(license.collect_build_notice(root, root / "partial").read_bytes(), license.notice_bytes())
|
||||
|
||||
def test_unaffected_builds_reject_stale_output_notice(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
elf32(root / "firmware.elf", symbols=("unrelated_defined_function",))
|
||||
manifest = self.qualify(root, root / "plain")
|
||||
self.assertNotIn("third_party_notices", manifest)
|
||||
self.assertIsNone(license.collect_build_notice(root, root / "plain"))
|
||||
notice = license.sidecar(root / "plain")
|
||||
notice.write_bytes(license.notice_bytes())
|
||||
with self.assertRaisesRegex(ValueError, "stale"):
|
||||
license.collect_build_notice(root, root / "plain")
|
||||
self.assertEqual(notice.read_bytes(), license.notice_bytes())
|
||||
|
||||
def test_notice_is_hashed_staged_and_recipe_bound_without_binary_changes(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
build, output = root / "build", root / "out"
|
||||
build.mkdir(); output.mkdir()
|
||||
elf32(build / "firmware.elf")
|
||||
label = "v1.17.1.9-halo-keymind-cascade-dev"
|
||||
version = label + "-deadbeef"
|
||||
stem = output / ("test_companion_radio_usb-" + version)
|
||||
manifest = self.qualify(build, stem)
|
||||
self.assertIn(license.CAPABILITY, manifest["capabilities"])
|
||||
self.assertEqual(manifest["verification"][0]["source"], "linked ELF symbols")
|
||||
app, merged = b"qualified-application", b"qualified-merged"
|
||||
(output / (stem.name + ".bin")).write_bytes(app)
|
||||
(output / (stem.name + "-merged.bin")).write_bytes(merged)
|
||||
notice = license.collect_build_notice(build, stem)
|
||||
self.assertEqual(notice.read_bytes(), license.notice_bytes())
|
||||
self.assertEqual(license.collect_build_notice(build, stem), notice)
|
||||
report = dict(schema_version=1, passed=True, available_internal_bytes=80000,
|
||||
required_heap_bytes=50000, largest_internal_region_bytes=80000,
|
||||
required_contiguous_bytes=5120,
|
||||
elf_sha256=hashlib.sha256((build / "firmware.elf").read_bytes()).hexdigest(), target="build_env")
|
||||
(build / "firmware.memory.json").write_text(json.dumps(report))
|
||||
memory.package_report(build, stem)
|
||||
proof = memory.validate_package(stem)
|
||||
self.assertEqual(proof["files"][notice.name], hashlib.sha256(notice.read_bytes()).hexdigest())
|
||||
records = release.collect_artifacts(output, version)
|
||||
self.assertEqual(sum(path == notice for path in records[0]["files"]), 1)
|
||||
self.assertTrue(recipe.package_occupied(stem))
|
||||
commit = "deadbeef" + "0" * 32
|
||||
status = root / "status"
|
||||
status.write_text("state=completed\nexit_code=0\n"
|
||||
f"working_directory={root}\noutput_directory=out\nsource_commit={commit}\n"
|
||||
f"firmware_version={label}\nfirmware_profile=cascade\n"
|
||||
"radio_frequency=909.5\nradio_bandwidth=500\nradio_sf=5\nradio_cr=5\n")
|
||||
result = subprocess.run([sys.executable, str(ROOT / "scripts/package_cascade_release.py"),
|
||||
"--input", str(output), "--output", str(root / "stage"), "--build-status", str(status),
|
||||
"--version", "1.17.1.9", "--commit", commit], capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
staged = root / "stage/companion"
|
||||
self.assertEqual((staged / notice.name).read_bytes(), license.notice_bytes())
|
||||
self.assertIn(notice.name, (staged / "TARGET-MANIFEST.json").read_text())
|
||||
self.assertIn(notice.name, (staged / "SHA256SUMS.txt").read_text())
|
||||
self.assertEqual((output / (stem.name + ".bin")).read_bytes(), app)
|
||||
self.assertEqual((output / (stem.name + "-merged.bin")).read_bytes(), merged)
|
||||
notice.write_bytes(b"tampered")
|
||||
with self.assertRaisesRegex(ValueError, "mismatched"):
|
||||
memory.validate_package(stem)
|
||||
notice.unlink()
|
||||
with self.assertRaisesRegex(ValueError, "missing"):
|
||||
memory.validate_package(stem)
|
||||
|
||||
def test_license_only_package_blocks_resume_and_missing_metadata_is_rejected(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
root = Path(folder)
|
||||
stem = root / "occupied"
|
||||
license.sidecar(stem).write_bytes(license.notice_bytes())
|
||||
self.assertTrue(recipe.package_occupied(stem))
|
||||
(root / "occupied.capabilities.json").write_text(json.dumps({"capabilities": [license.CAPABILITY]}))
|
||||
with self.assertRaisesRegex(ValueError, "lacks"):
|
||||
license.validate_artifact_notice(stem)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,354 @@
|
||||
"""Run the actual Dispatcher foreign-frame ownership and isolation contract."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from test_radio_receive_contract import method
|
||||
from test_radio_profile_scan import HARNESS as SCAN_HARNESS
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HARNESS = r'''
|
||||
#include <Dispatcher.h>
|
||||
#include <helpers/StaticPoolPacketManager.h>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
using namespace mesh;
|
||||
class Clock : public MillisecondClock {
|
||||
public: unsigned long now=1000; unsigned long getMillis() override { return now; }
|
||||
};
|
||||
class TestRadio : public Radio {
|
||||
public:
|
||||
RadioProfiles p;
|
||||
uint8_t active=0;
|
||||
bool supported=true, receiving=false, complete=false, sending=false, start_ok=true, carrier=false;
|
||||
bool incoming=false;
|
||||
unsigned sends=0, finishes=0, recovery=0, processed=0;
|
||||
RadioParamApplyResult prepare=RadioParamApplyResult::APPLIED;
|
||||
std::vector<uint8_t> sent;
|
||||
TestRadio() {
|
||||
p.primary.freq=909.5f; p.primary.bw=500; p.primary.sf=5; p.primary.cr=5;
|
||||
p.secondary.params=p.primary; p.secondary.params.protocol=RadioProfileProtocol::Meshtext;
|
||||
p.secondary.params.preamble=16; p.secondary.mode=RadioProfileMode::RxTx;
|
||||
}
|
||||
RadioProfiles* profiles() override { return &p; }
|
||||
const RadioProfiles* profiles() const override { return &p; }
|
||||
bool supportsMeshtext() const override { return supported; }
|
||||
uint8_t receiveProfile() const override { return active; }
|
||||
int recvRaw(uint8_t* bytes,int) override {
|
||||
if (!incoming) return 0;
|
||||
incoming=false; bytes[0]=0x11;bytes[1]=0;bytes[2]=0x23;return 3;
|
||||
}
|
||||
void onReceiveProcessed() override { ++processed; }
|
||||
uint32_t getEstAirtimeFor(int) override { return 100; }
|
||||
uint32_t getProfileAirtime(uint8_t,int,uint8_t=0) override { return 100; }
|
||||
float packetScore(float,int) override { return 1; }
|
||||
RadioParamApplyResult prepareTransmitProfile(uint8_t n) override {
|
||||
if (prepare==RadioParamApplyResult::APPLIED) active=n;
|
||||
return prepare;
|
||||
}
|
||||
bool startSendRaw(const uint8_t* bytes,int len) override {
|
||||
++sends;sent.assign(bytes,bytes+len);sending=start_ok;complete=false;return start_ok;
|
||||
}
|
||||
bool isSendComplete() override { return complete; }
|
||||
void onSendFinished() override { ++finishes;sending=false; }
|
||||
bool isInRecvMode() const override { return !sending; }
|
||||
bool isReceiving() override { return receiving; }
|
||||
bool isCarrierWaveActive() const override { return carrier; }
|
||||
bool recoverRadio(bool) override { ++recovery;return true; }
|
||||
};
|
||||
class TestDispatcher : public Dispatcher {
|
||||
public:
|
||||
unsigned foreign_rx=0, mc_rx=0, raw_logs=0, mc_sent=0;
|
||||
bool allow_foreign=true;
|
||||
unsigned long duty_window=3600000;
|
||||
std::vector<bool> done;
|
||||
TestDispatcher(TestRadio& r, Clock& c, StaticPoolPacketManager& m):Dispatcher(r,c,m) {}
|
||||
using Dispatcher::queueForeignRadioFrame;
|
||||
using Dispatcher::hasForeignRadioFrame;
|
||||
using Dispatcher::setRadioAvailable;
|
||||
using Dispatcher::getTransmitProfileMask;
|
||||
using Dispatcher::getNextQueueWakeDelay;
|
||||
DispatcherAction onRecvPacket(Packet*) override { ++mc_rx;return ACTION_RELEASE; }
|
||||
void logRxRaw(float,float,const uint8_t*,int) override { ++raw_logs; }
|
||||
bool onForeignRadioFrame(const uint8_t* bytes,size_t length,uint8_t profile,uint32_t generation,float,float) override {
|
||||
assert(length==3 && bytes[0]==0x11 && profile==1 && generation);++foreign_rx;return false;
|
||||
}
|
||||
void onForeignRadioSendComplete(bool ok) override { done.push_back(ok); }
|
||||
bool allowForeignRadioTransmit() const override { return allow_foreign; }
|
||||
unsigned long getDutyCycleWindowMs() const override { return duty_window; }
|
||||
void onSendComplete(Packet*) override { ++mc_sent; }
|
||||
bool queue(const uint8_t* b,size_t n=3) { return queueForeignRadioFrame(b,n,1,_radio->profiles()->generation[1]); }
|
||||
};
|
||||
struct Fixture {
|
||||
Clock clock;TestRadio radio;StaticPoolPacketManager manager{8};TestDispatcher d{radio,clock,manager};
|
||||
Fixture() { d.begin(); }
|
||||
void tick(unsigned delta=1) { clock.now+=delta;d.loop(); }
|
||||
};
|
||||
static const uint8_t bytes[]={0x11,0,0x23};
|
||||
static Packet* newPacket(TestDispatcher& d,uint8_t policy=RADIO_TX_BOTH) {
|
||||
auto* p=d.obtainNewPacket();assert(p);p->header=ROUTE_TYPE_FLOOD | (PAYLOAD_TYPE_GRP_TXT<<2);
|
||||
p->tx_radio=policy;p->payload[0]=0x12;p->payload_len=1;return p;
|
||||
}
|
||||
int main() {
|
||||
{ Fixture f;assert(f.d.queue(bytes));assert(f.d.hasOutbound());assert(!f.d.queue(bytes));
|
||||
uint32_t delay=99;assert(f.d.getNextQueueWakeDelay(delay) && delay==0);
|
||||
f.tick();assert(f.radio.sends==1 && f.radio.active==1 && f.radio.sent==std::vector<uint8_t>(bytes,bytes+3));
|
||||
f.tick(20);assert(f.radio.sends==1 && f.d.done.empty());
|
||||
f.radio.complete=true;f.tick();assert(f.d.done.size()==1 && f.d.done[0]);
|
||||
assert(!f.d.hasOutbound() && f.radio.finishes==1 && f.radio.p.tx_packets[1]==1);
|
||||
assert(f.d.getNumSentFlood()==0 && f.d.getNumSentDirect()==0 && f.d.getTotalAirTime()==21);
|
||||
}
|
||||
{ Fixture f;f.radio.active=1;f.radio.incoming=true;f.tick();
|
||||
assert(f.d.foreign_rx==1 && !f.d.mc_rx && !f.d.raw_logs && f.d.getLastMeshCoreRecvMillis()==0);
|
||||
assert(f.radio.processed==1 && f.d.getNumRecvFlood()==0 && f.radio.p.rx_packets[1]==1);
|
||||
f.radio.p.secondary.mode=RadioProfileMode::Off;f.radio.incoming=true;f.tick();
|
||||
assert(f.d.foreign_rx==1 && !f.d.raw_logs && !f.d.mc_rx);
|
||||
}
|
||||
{ Fixture f;assert(f.d.queue(bytes));++f.radio.p.generation[1];f.tick();
|
||||
assert(f.radio.sends==0 && f.d.done.size()==1 && !f.d.done[0] && !f.d.hasOutbound());
|
||||
}
|
||||
{ Fixture f;f.radio.start_ok=false;assert(f.d.queue(bytes));f.tick();f.tick(2000);
|
||||
assert(f.radio.sends==1 && f.d.done.size()==1 && !f.d.done[0] && !f.d.hasOutbound());
|
||||
}
|
||||
{ Fixture f;assert(f.d.queue(bytes));f.tick();f.tick(1151);
|
||||
assert(f.radio.sends==1 && f.radio.finishes==1 && f.radio.recovery==1);
|
||||
assert(f.d.done.size()==1 && !f.d.done[0] && !f.d.hasOutbound());f.tick(10000);assert(f.radio.sends==1);
|
||||
}
|
||||
{ Fixture f;assert(f.d.queue(bytes));f.tick();f.d.setRadioAvailable(false);f.tick(10000);
|
||||
assert(f.radio.sends==1 && f.radio.finishes==1 && f.d.done.size()==1 && !f.d.done[0]);
|
||||
assert(!f.d.queue(bytes) && !f.d.hasOutbound());
|
||||
}
|
||||
{ Fixture f;assert(f.d.queue(bytes));f.tick();++f.radio.p.generation[1];f.radio.complete=true;f.tick();
|
||||
assert(f.d.done.size()==1 && !f.d.done[0] && f.radio.finishes==1);
|
||||
}
|
||||
{ Fixture f;f.radio.prepare=RadioParamApplyResult::FAILED;assert(f.d.queue(bytes));f.tick();
|
||||
assert(f.radio.sends==0 && f.d.done.size()==1 && !f.d.done[0]);
|
||||
}
|
||||
{ Fixture f;assert(f.d.queue(bytes));f.d.allow_foreign=false;f.tick();
|
||||
assert(f.radio.sends==0 && f.d.done.size()==1 && !f.d.done[0] && !f.d.queue(bytes));
|
||||
}
|
||||
{ Fixture f;assert(f.d.queue(bytes));f.tick();f.d.begin();
|
||||
assert(f.radio.finishes==1 && f.d.done.size()==1 && !f.d.done[0] && !f.d.hasOutbound());
|
||||
}
|
||||
{ Fixture f;f.radio.prepare=RadioParamApplyResult::BUSY;assert(f.d.queue(bytes));f.tick();f.tick(8151);
|
||||
assert(f.radio.sends==0 && f.d.done.size()==1 && !f.d.done[0] && f.radio.recovery==1);
|
||||
}
|
||||
{ Fixture f;f.radio.receiving=true;assert(f.d.queue(bytes));f.tick();f.tick(201);
|
||||
assert(f.radio.sends==0 && f.d.hasOutbound());f.radio.receiving=false;f.tick(201);assert(f.radio.sends==1);
|
||||
}
|
||||
{ Fixture f;auto* p=newPacket(f.d);f.radio.p.cross=RadioCrossMode::On;
|
||||
assert(!f.radio.p.canCross() && f.d.getTransmitProfileMask(p)==1);
|
||||
assert(f.d.sendPacket(p,0));assert(f.manager.getOutboundTotal()==1);f.tick();
|
||||
assert(f.radio.sends==1 && f.radio.active==0);f.radio.complete=true;f.tick();assert(f.d.mc_sent==1);
|
||||
auto* denied=newPacket(f.d,RADIO_TX_SECONDARY);assert(!f.d.sendPacket(denied,0));
|
||||
assert(f.manager.getOutboundTotal()==0 && f.radio.sends==1);
|
||||
}
|
||||
{ Fixture f;auto* p=newPacket(f.d,RADIO_TX_PRIMARY);assert(f.d.sendPacket(p,0));f.tick();
|
||||
assert(f.d.queue(bytes));f.tick();assert(f.radio.sends==1);f.radio.complete=true;f.tick();
|
||||
f.tick();assert(f.radio.sends==2 && f.radio.active==1);f.radio.complete=true;f.tick();
|
||||
assert(f.d.done.size()==1 && f.d.done[0] && f.d.mc_sent==1);
|
||||
}
|
||||
{ Fixture f;f.d.duty_window=200;f.d.begin();assert(f.d.queue(bytes));f.tick();
|
||||
f.clock.now+=100;f.radio.complete=true;f.d.loop();assert(f.d.getRemainingTxBudget()==0);
|
||||
assert(f.d.queue(bytes));f.tick(100);assert(f.radio.sends==1);
|
||||
f.tick(101);assert(f.radio.sends==2);
|
||||
}
|
||||
{ Fixture f;assert(f.d.queue(bytes));f.tick();f.radio.complete=true;f.tick();
|
||||
assert(f.d.queue(bytes));auto* p=newPacket(f.d,RADIO_TX_PRIMARY);assert(f.d.sendPacket(p,0));f.tick();
|
||||
assert(f.radio.sends==2 && f.radio.active==0);f.radio.complete=true;f.tick();f.tick();
|
||||
assert(f.radio.sends==3 && f.radio.active==1);
|
||||
}
|
||||
{ Fixture f;f.radio.supported=false;assert(!f.d.queue(bytes));f.radio.supported=true;
|
||||
assert(!f.d.queueForeignRadioFrame(bytes,3,0,f.radio.p.generation[0]));
|
||||
assert(!f.d.queueForeignRadioFrame(bytes,3,1,f.radio.p.generation[1]+1));
|
||||
assert(!f.d.queue(nullptr));assert(!f.d.queue(bytes,0));uint8_t full[256]={};assert(!f.d.queue(full,256));
|
||||
f.radio.carrier=true;assert(!f.d.queue(bytes));f.radio.carrier=false;
|
||||
f.radio.p.secondary.mode=RadioProfileMode::Rx;assert(!f.d.queue(bytes));
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class MeshtextTransportTest(unittest.TestCase):
|
||||
def compile_and_run(self, text, extra_flags=()):
|
||||
compiler = shutil.which('g++') or shutil.which('clang++')
|
||||
self.assertIsNotNone(compiler)
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
cpp, exe = Path(folder)/'test.cpp', Path(folder)/'test.exe'
|
||||
(Path(folder)/'Arduino.h').write_text('#pragma once\n#include <cstdint>\n#include <cmath>\n')
|
||||
cpp.write_text(text)
|
||||
result = subprocess.run([compiler, '-std=c++17', '-Wall', '-Wextra',
|
||||
*extra_flags, '-I', folder, '-I', str(ROOT/'src'), str(cpp), '-o', str(exe)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr[-12000:])
|
||||
run = subprocess.run([str(exe)], capture_output=True, text=True)
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
|
||||
def test_actual_dispatcher(self):
|
||||
compiler = shutil.which('g++') or shutil.which('clang++')
|
||||
self.assertIsNotNone(compiler)
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
cpp, exe = Path(folder)/'test.cpp', Path(folder)/'test.exe'
|
||||
cpp.write_text(HARNESS)
|
||||
flags = ['-std=c++17', '-Wall', '-Wextra', '-DMESH_ENABLE_MESHTEXT_CHAT=1']
|
||||
if os.name != 'nt':
|
||||
flags += ['-fsanitize=address,undefined', '-fno-omit-frame-pointer', '-fno-pie', '-no-pie']
|
||||
result = subprocess.run([compiler, *flags,
|
||||
'-I', str(ROOT/'test/mocks'), '-I', str(ROOT/'src'),
|
||||
str(ROOT/'src/Dispatcher.cpp'), str(ROOT/'src/Packet.cpp'),
|
||||
str(ROOT/'src/helpers/StaticPoolPacketManager.cpp'), str(cpp), '-o', str(exe)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr[-12000:])
|
||||
env = os.environ.copy()
|
||||
env['ASAN_OPTIONS'] = env.get('ASAN_OPTIONS', '') + ':detect_leaks=0'
|
||||
run = subprocess.run([str(exe)], capture_output=True, text=True, env=env)
|
||||
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
|
||||
|
||||
def test_protocol_retune_and_rollback(self):
|
||||
source = (ROOT/'src/helpers/radiolib/RadioLibWrappers.cpp').read_text()
|
||||
names = [('uint8_t', 'beginReconfigure'), ('void', 'endReconfigure'),
|
||||
('void', 'serviceProfileScan')] + [('mesh::RadioParamApplyResult', n) for n in
|
||||
('tuneProfile', 'prepareTransmitProfile', 'tryRestoreCodingRate', 'trySetParams', 'trySetPrimaryParams')]
|
||||
methods = '\n'.join(method(source, f'{kind} RadioLibWrapper::{name}(') for kind, name in names)
|
||||
methods += '\n' + method(source, 'mesh::RadioParamApplyResult RadioLibWrapper::prepareTransmitProfile(uint8_t profile, bool')
|
||||
wrapper = (ROOT/'src/helpers/radiolib/CustomSX1262Wrapper.h').read_text()
|
||||
methods += '\n' + method(wrapper, 'void setProfileStandbyWarm(').replace(
|
||||
'void setProfileStandbyWarm(bool enabled) override',
|
||||
'void RadioLibWrapper::setProfileStandbyWarm(bool enabled)')
|
||||
harness = SCAN_HARNESS.split('@METHODS@')[0]
|
||||
harness = harness.replace('uint16_t _physical_preamble=32;', '''
|
||||
uint16_t _physical_preamble=32;
|
||||
mesh::RadioProfileProtocol _physical_protocol=mesh::RadioProfileProtocol::MeshCore;
|
||||
mesh::RadioProfileProtocol applied_protocol=mesh::RadioProfileProtocol::MeshCore;
|
||||
unsigned protocol_writes=0;
|
||||
bool protocol_fail=false;
|
||||
bool applyProtocol(mesh::RadioProfileProtocol p) {
|
||||
++protocol_writes;
|
||||
if (protocol_fail && p==mesh::RadioProfileProtocol::Meshtext) return false;
|
||||
applied_protocol=p;return true;
|
||||
}''')
|
||||
cases = r'''
|
||||
int main() {
|
||||
using Protocol=mesh::RadioProfileProtocol;
|
||||
using Result=mesh::RadioParamApplyResult;
|
||||
{
|
||||
RadioLibWrapper w;
|
||||
mesh::RadioProfileConfig cfg;cfg.params=w._profiles.primary;
|
||||
cfg.params.protocol=Protocol::Meshtext;cfg.mode=mesh::RadioProfileMode::RxTx;
|
||||
w._profiles.setSecondary(cfg,false);
|
||||
assert(w._profiles.preamble(1,128)==16 && w._profiles.automaticPreambleFits());
|
||||
assert(w.tuneProfile(1)==Result::APPLIED);
|
||||
assert(w._physical_protocol==Protocol::Meshtext && w.applied_protocol==Protocol::Meshtext);
|
||||
assert(w.protocol_writes==1 && w._physical_preamble==16);
|
||||
assert(w.tuneProfile(0)==Result::APPLIED);
|
||||
assert(w._physical_protocol==Protocol::MeshCore && w.applied_protocol==Protocol::MeshCore);
|
||||
assert(w.protocol_writes==2);
|
||||
const auto generation=w._profiles.generation[1];
|
||||
cfg.params.protocol=Protocol::MeshCore;w._profiles.setSecondary(cfg,false);
|
||||
assert(w._profiles.generation[1]==generation+1);
|
||||
}
|
||||
{
|
||||
RadioLibWrapper w;mesh::RadioProfileConfig cfg;cfg.params=w._profiles.primary;
|
||||
cfg.params.protocol=Protocol::Meshtext;cfg.mode=mesh::RadioProfileMode::RxTx;
|
||||
w._profiles.setSecondary(cfg,false);w.protocol_fail=true;
|
||||
assert(w.tuneProfile(1)==Result::FAILED);
|
||||
assert(w._physical_protocol==Protocol::MeshCore && w.applied_protocol==Protocol::MeshCore);
|
||||
assert(w._active_profile==0 && w._profile_generation==1);
|
||||
assert(w.protocol_writes==2);
|
||||
}
|
||||
{
|
||||
RadioLibWrapper w;mesh::RadioProfileConfig cfg;cfg.params=w._profiles.primary;
|
||||
cfg.params.protocol=Protocol::Meshtext;cfg.mode=mesh::RadioProfileMode::RxTx;
|
||||
w._profiles.setSecondary(cfg,false);w.failRxStarts=1;
|
||||
assert(w.tuneProfile(1)==Result::FAILED);
|
||||
assert(w._physical_protocol==Protocol::MeshCore && w.applied_protocol==Protocol::MeshCore);
|
||||
assert(w._active_profile==0 && w.isInRecvMode());
|
||||
}
|
||||
{
|
||||
mesh::RadioProfiles p;p.primary.freq=909.5;p.primary.bw=500;p.primary.sf=5;p.primary.cr=5;
|
||||
p.secondary.params=p.primary;p.secondary.params.protocol=Protocol::Meshtext;
|
||||
p.secondary.mode=mesh::RadioProfileMode::RxTx;
|
||||
for (auto cross: {mesh::RadioCrossMode::Off,mesh::RadioCrossMode::On,mesh::RadioCrossMode::Auto}) {
|
||||
p.cross=cross;assert(!p.canCross());assert(p.transmitMask(0)==1 && p.transmitMask(1)==2);
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_and_run(harness + methods + cases, ['-DMESH_ENABLE_MESHTEXT_CHAT=1'])
|
||||
|
||||
def test_sx1262_wire_settings_and_deep_recovery(self):
|
||||
wrapper = (ROOT/'src/helpers/radiolib/CustomSX1262Wrapper.h').read_text()
|
||||
wire = method(wrapper, 'bool applyProtocol(').replace(' override', '')
|
||||
chip_source = (ROOT/'src/helpers/radiolib/CustomSX1262.h').read_text()
|
||||
protocol = method(chip_source, 'int16_t setProfileProtocol(')
|
||||
source = (ROOT/'src/helpers/radiolib/RadioLibWrappers.cpp').read_text()
|
||||
restore = method(source, 'bool RadioLibWrapper::restoreAfterDeepInit()')
|
||||
harness = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <RadioProfiles.h>
|
||||
#include <helpers/radiolib/SX1262ProfileSwitchState.h>
|
||||
#define RADIOLIB_ERR_NONE 0
|
||||
#define RADIOLIB_SX126X_LORA_CRC_ON 1
|
||||
#define RADIOLIB_SX126X_LORA_HEADER_EXPLICIT 0
|
||||
#define RADIOLIB_SX126X_LORA_IQ_STANDARD 0
|
||||
#define STATE_IDLE 0
|
||||
struct SX1262 {
|
||||
uint8_t sync=0x12;bool crc=false,explicit_header=false,iq=true;
|
||||
size_t preambleLengthLoRa=32;
|
||||
uint8_t crcTypeLoRa=1,implicitLen=255,headerType=0,invertIQEnabled=0;
|
||||
unsigned step=0,fail_at=0;
|
||||
int status() { return ++step==fail_at ? -1 : 0; }
|
||||
int setSyncWord(uint8_t n) { sync=n;return status(); }
|
||||
int setCRC(uint8_t n) { crc=n==1;return status(); }
|
||||
int explicitHeader() { explicit_header=true;return status(); }
|
||||
int invertIQ(bool n) { iq=n;return status(); }
|
||||
int setPreambleLength(uint16_t) { return 0; }
|
||||
};
|
||||
struct CustomSX1262: SX1262 {
|
||||
SX1262ProfileSwitchState _profileSwitch{false};
|
||||
@PROTOCOL@
|
||||
};
|
||||
struct RadioLibWrapper {
|
||||
CustomSX1262 chip;CustomSX1262* _radio=&chip;
|
||||
bool _rx_ps_armed=true,_params_valid=true,_dbm_valid=false,_rx_boosted_gain_valid=false;
|
||||
int state=1;uint8_t _cur_sf=11,_cur_cr=5;float _cur_freq=906.875,_cur_bw=250;
|
||||
int8_t _cur_dbm=22;bool _cur_rx_boosted_gain=false;
|
||||
mesh::RadioProfileProtocol _physical_protocol=mesh::RadioProfileProtocol::Meshtext;
|
||||
bool radioDeepInit() { chip.sync=0x12;chip.step=0;return true; }
|
||||
bool registerInterruptAction() { return true; }
|
||||
bool applyParams(float,float,uint8_t,uint8_t) { return true; }
|
||||
uint16_t currentPreambleLength() { return 16; }
|
||||
int applyCachedTxPower(int8_t) { return 0; }
|
||||
bool applyRxBoostedGainMode(bool) { return true; }
|
||||
void recalibrateNoiseFloor() {}
|
||||
@WIRE@
|
||||
bool restoreAfterDeepInit();
|
||||
};
|
||||
@RESTORE@
|
||||
int main() {
|
||||
using Protocol=mesh::RadioProfileProtocol;
|
||||
for (Protocol p: {Protocol::MeshCore,Protocol::Meshtext}) {
|
||||
RadioLibWrapper w;assert(w.applyProtocol(p));
|
||||
assert(w.chip.sync==(p==Protocol::MeshCore ? 0x12 : 0x2b));
|
||||
assert(w.chip.crc && w.chip.explicit_header && !w.chip.iq);
|
||||
}
|
||||
for (unsigned fail=1;fail<=4;++fail) {
|
||||
RadioLibWrapper w;w.chip.fail_at=fail;assert(!w.applyProtocol(Protocol::Meshtext));
|
||||
}
|
||||
RadioLibWrapper w;assert(w.restoreAfterDeepInit());
|
||||
assert(w.chip.sync==0x2b && w.chip.crc && w.chip.explicit_header && !w.chip.iq);
|
||||
assert(!w._rx_ps_armed && w.state==STATE_IDLE);
|
||||
w._physical_protocol=Protocol::MeshCore;assert(w.restoreAfterDeepInit());assert(w.chip.sync==0x12);
|
||||
}
|
||||
'''
|
||||
self.compile_and_run('#include <initializer_list>\n' + harness.replace('@WIRE@',wire)
|
||||
.replace('@PROTOCOL@',protocol).replace('@RESTORE@',restore),
|
||||
['-DMESH_ENABLE_MESHTEXT_CHAT=1'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,375 @@
|
||||
"""Run the production profile CLI's RAM-only automatic ownership layer."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
HARNESS = r'''
|
||||
// Reuse only the existing memory FS/radio fixture; run dedicated scenarios.
|
||||
#define main existing_cli_main
|
||||
#include "test/fixtures/radio_profiles/cli_test.cpp"
|
||||
#undef main
|
||||
|
||||
static mesh::RadioProfileConfig candidate(float frequency = 910.5f) {
|
||||
mesh::RadioProfileConfig config;
|
||||
config.mode = mesh::RadioProfileMode::RxTx;
|
||||
config.params.freq = frequency; config.params.bw = 250;
|
||||
config.params.sf = 11; config.params.cr = 5; config.params.preamble = 16;
|
||||
config.params.protocol = mesh::RadioProfileProtocol::Meshtext;
|
||||
return config;
|
||||
}
|
||||
|
||||
static void rewriteCRC(std::vector<uint8_t>& image) {
|
||||
uint32_t crc = 0xffffffffU;
|
||||
for (size_t i = 0; i < image.size() - 4; ++i) {
|
||||
crc ^= image[i];
|
||||
for (unsigned bit = 0; bit < 8; ++bit) crc = (crc >> 1) ^ ((crc & 1) ? 0xedb88320U : 0);
|
||||
}
|
||||
memcpy(image.data() + image.size() - 4, &crc, 4);
|
||||
}
|
||||
|
||||
static void lifetime() {
|
||||
Fixture f;
|
||||
const auto config = candidate();
|
||||
assert(f.cli.canAutoSecondary());
|
||||
assert(f.cli.requestAutoSecondary(config));
|
||||
assert(f.cli.autoSecondaryActive());
|
||||
assert(f.radio.p.secondary.params == config.params);
|
||||
assert(strstr(f.cmd("get radio2"), "auto-owned"));
|
||||
const auto generation = f.radio.p.generation[1];
|
||||
for (unsigned i = 0; i < 8; ++i) {
|
||||
assert(f.cli.requestAutoSecondary(config)); f.advance(1, false);
|
||||
assert(f.radio.p.generation[1] == generation);
|
||||
}
|
||||
assert(!f.cli.requestAutoSecondary(candidate(911.5f))); // no last-request-wins conflict
|
||||
assert(f.radio.p.secondary.params == config.params);
|
||||
assert(f.fs.files.empty()); // RF adoption never writes flash
|
||||
f.cli.clearAutoSecondary();
|
||||
assert(!f.cli.autoSecondaryActive() && !f.radio.p.enabled());
|
||||
const auto cleared = f.radio.p.generation[1];
|
||||
f.cli.clearAutoSecondary(); f.advance(1, false);
|
||||
assert(f.radio.p.generation[1] == cleared && f.fs.files.empty());
|
||||
auto invalid = config; invalid.mode = mesh::RadioProfileMode::Off;
|
||||
assert(!f.cli.requestAutoSecondary(invalid));
|
||||
invalid = config; invalid.params.freq = 0;
|
||||
assert(!f.cli.requestAutoSecondary(invalid));
|
||||
}
|
||||
|
||||
static void savedIntent() {
|
||||
Fixture f(true);
|
||||
assert(f.cli.requestAutoSecondary(candidate()));
|
||||
f.cmd("set radio2.cross off");
|
||||
assert(f.cli.savePrimaryPreamble(120));
|
||||
f.cmd("set tx.reply radio2 force");
|
||||
assert(f.cli.autoSecondaryActive());
|
||||
const auto image = f.fs.files["/radio_profiles"];
|
||||
assert(image.size() == 24 && image[2] == 2 && image[3] == 0);
|
||||
Radio reboot; mesh::RadioProfileCLI restored;
|
||||
restored.begin(&f.fs, &reboot, &f.clock, true);
|
||||
assert(!reboot.p.enabled() && restored.canAutoSecondary());
|
||||
assert(!restored.manualSecondaryConfigured());
|
||||
|
||||
f.cmd("set radio2 off");
|
||||
assert(!f.cli.autoSecondaryActive() && !f.cli.canAutoSecondary());
|
||||
assert(f.fs.files["/radio_profiles"][3] == 0x80);
|
||||
f.advance(2000);
|
||||
assert(!f.radio.p.enabled());
|
||||
restored.begin(&f.fs, &reboot, &f.clock);
|
||||
assert(!restored.canAutoSecondary() && !restored.requestAutoSecondary(candidate()));
|
||||
|
||||
// Version 1 cannot distinguish explicit Off from unused Off. Preserve it.
|
||||
auto legacy = image; legacy[2] = 1; rewriteCRC(legacy);
|
||||
f.fs.files["/radio_profiles"] = legacy;
|
||||
restored.begin(&f.fs, &reboot, &f.clock);
|
||||
assert(!restored.canAutoSecondary());
|
||||
}
|
||||
|
||||
static void manualTakeover() {
|
||||
Fixture f;
|
||||
assert(f.cli.requestAutoSecondary(candidate()));
|
||||
const auto intent = f.cli.secondaryIntentGeneration();
|
||||
f.fs.fail_write = true;
|
||||
f.cmd("set radio2 910.5,250,11,5,rxtx,16", false);
|
||||
assert(f.cli.autoSecondaryActive() && f.cli.secondaryIntentGeneration() == intent);
|
||||
f.fs.fail_write = false;
|
||||
f.cmd("set radio2 910.5,250,11,5,rxtx,16");
|
||||
assert(!f.cli.autoSecondaryActive());
|
||||
assert(f.cli.secondaryIntentGeneration() == intent + 1);
|
||||
assert(f.cli.manualSecondaryConfigured() && !f.cli.canAutoSecondary());
|
||||
f.advance(2000);
|
||||
assert(f.radio.p.secondary.params.protocol == mesh::RadioProfileProtocol::MeshCore);
|
||||
const auto manual_generation = f.radio.p.generation[1];
|
||||
f.cli.clearAutoSecondary();
|
||||
assert(f.radio.p.generation[1] == manual_generation && f.radio.p.enabled());
|
||||
f.cmd("set radio2 910.5,250,11,5,rxtx,16");
|
||||
assert(f.cli.secondaryIntentGeneration() == intent + 2); // identical manual RF still owns intent
|
||||
f.advance(2000);
|
||||
assert(f.radio.p.generation[1] == manual_generation);
|
||||
Radio reboot; mesh::RadioProfileCLI restored;
|
||||
restored.begin(&f.fs, &reboot, &f.clock);
|
||||
assert(restored.manualSecondaryConfigured() && !restored.canAutoSecondary());
|
||||
}
|
||||
|
||||
static void overlay() {
|
||||
Fixture f;
|
||||
f.cmd("set radio2 910.5,500,8,5,rx,80"); f.advance(2000);
|
||||
const auto saved = f.fs.files["/radio_profiles"];
|
||||
const auto rf = f.radio.p.secondary.params;
|
||||
assert(f.cli.useSecondaryProtocol(mesh::RadioProfileProtocol::Meshtext));
|
||||
assert(f.radio.p.secondary.params.freq == rf.freq && f.radio.p.secondary.params.bw == rf.bw);
|
||||
assert(f.radio.p.secondary.params.sf == rf.sf && f.radio.p.secondary.params.cr == rf.cr);
|
||||
assert(f.radio.p.secondary.mode == mesh::RadioProfileMode::Rx);
|
||||
assert(f.radio.p.secondary.params.preamble == 16);
|
||||
assert(f.radio.p.secondary.params.protocol == mesh::RadioProfileProtocol::Meshtext);
|
||||
assert(f.cli.savedSecondaryConfig().params == rf);
|
||||
assert(f.fs.files["/radio_profiles"] == saved);
|
||||
const auto generation = f.radio.p.generation[1];
|
||||
for (unsigned i = 0; i < 4; ++i) {
|
||||
assert(f.cli.useSecondaryProtocol(mesh::RadioProfileProtocol::Meshtext)); f.advance(1, false);
|
||||
assert(f.radio.p.generation[1] == generation);
|
||||
}
|
||||
f.cli.clearSecondaryProtocol();
|
||||
assert(f.radio.p.secondary.params == rf && f.fs.files["/radio_profiles"] == saved);
|
||||
assert(!f.cli.useSecondaryProtocol(static_cast<mesh::RadioProfileProtocol>(9)));
|
||||
assert(f.cli.useSecondaryProtocol(mesh::RadioProfileProtocol::Meshtext));
|
||||
f.cmd("set radio2 912.5,500,8,5,rxtx,80"); f.advance(2000);
|
||||
f.cli.clearSecondaryProtocol();
|
||||
assert(f.radio.p.secondary.params.freq == 912.5f);
|
||||
assert(f.radio.p.secondary.params.protocol == mesh::RadioProfileProtocol::MeshCore);
|
||||
assert(f.radio.p.secondary.params.preamble == 80);
|
||||
}
|
||||
|
||||
static void leasesAndSchedules() {
|
||||
Fixture f;
|
||||
assert(f.cli.requestAutoSecondary(candidate()));
|
||||
f.cmd("set tempradio2 911.5,500,8,5,rxtx,1,80");
|
||||
assert(!f.cli.canAutoSecondary() && !f.cli.autoSecondaryActive());
|
||||
assert(!f.cli.requestAutoSecondary(candidate()));
|
||||
f.advance(2000);
|
||||
assert(f.radio.p.secondary_temporary && f.radio.p.secondary.params.freq == 911.5f);
|
||||
const auto lease_generation = f.radio.p.generation[1];
|
||||
f.cli.clearAutoSecondary(); f.cli.clearSecondaryProtocol();
|
||||
assert(f.radio.p.generation[1] == lease_generation);
|
||||
f.advance(60000);
|
||||
assert(!f.radio.p.enabled() && f.cli.canAutoSecondary());
|
||||
assert(f.cli.requestAutoSecondary(candidate()));
|
||||
f.cmd("set radioat2 912.5,500,8,5,rxtx,+1,80");
|
||||
assert(!f.cli.canAutoSecondary() && !f.cli.autoSecondaryActive());
|
||||
assert(!f.cli.requestAutoSecondary(candidate()));
|
||||
f.cmd("del radioat2 all");
|
||||
assert(f.cli.canAutoSecondary());
|
||||
f.cmd("set tempradioat2 912.5,500,8,5,rxtx,+1,+2,80");
|
||||
assert(!f.cli.canAutoSecondary());
|
||||
f.cmd("del tempradioat2 all");
|
||||
assert(f.cli.canAutoSecondary());
|
||||
}
|
||||
|
||||
static void primaryTemporary() {
|
||||
Fixture f;
|
||||
assert(f.cli.requestAutoSecondary(candidate()));
|
||||
f.radio.p.primary_temporary = true; f.advance(1, false);
|
||||
assert(!f.radio.p.enabled() && !f.cli.autoSecondaryActive());
|
||||
assert(!f.cli.canAutoSecondary() && !f.cli.requestAutoSecondary(candidate()));
|
||||
const auto generation = f.radio.p.generation[1];
|
||||
for (unsigned i = 0; i < 4; ++i) f.advance(1, false);
|
||||
assert(f.radio.p.generation[1] == generation);
|
||||
f.radio.p.primary_temporary = false; f.advance(1, false);
|
||||
assert(f.cli.autoSecondaryActive());
|
||||
}
|
||||
|
||||
static void automaticPermission() {
|
||||
Fixture f;
|
||||
f.cmd("set radio2 off"); f.advance(2000);
|
||||
assert(strstr(f.cmd("get radio2"), "manual"));
|
||||
const auto off_image = f.fs.files["/radio_profiles"];
|
||||
f.fs.fail_write = true; f.cmd("set radio2 auto", false);
|
||||
assert(!f.cli.canAutoSecondary() && f.fs.files["/radio_profiles"] == off_image);
|
||||
f.fs.fail_write = false; f.cmd("set radio2 auto");
|
||||
assert(f.fs.files["/radio_profiles"][2] == 2 && f.fs.files["/radio_profiles"][3] == 0);
|
||||
assert(!f.cli.canAutoSecondary()); // two-second publication barrier
|
||||
f.advance(2000);
|
||||
assert(f.cli.canAutoSecondary() && strstr(f.cmd("get radio2"), "automatic allowed"));
|
||||
Radio reboot; mesh::RadioProfileCLI restored;
|
||||
restored.begin(&f.fs, &reboot, &f.clock);
|
||||
assert(restored.canAutoSecondary());
|
||||
f.cmd("set tempradio2 911.5,500,8,5,rxtx,1,80");
|
||||
f.cmd("set radio2 auto", false);
|
||||
f.advance(2000); f.cmd("set radio2 auto", false);
|
||||
assert(f.radio.p.secondary_temporary);
|
||||
f.advance(60000);
|
||||
f.cmd("set radioat2 912.5,500,8,5,rxtx,+1,80");
|
||||
f.cmd("set radio2 auto", false);
|
||||
assert(strstr(f.cmd("get radioat2 all"), "1@"));
|
||||
f.cmd("del radioat2 all");
|
||||
f.cmd("set radio2 auto"); f.advance(2000);
|
||||
assert(f.cli.canAutoSecondary());
|
||||
}
|
||||
|
||||
static void unmanagedTakeover() {
|
||||
Fixture f;
|
||||
assert(f.cli.requestAutoSecondary(candidate()));
|
||||
auto external = candidate(912.5f);
|
||||
external.params.protocol = mesh::RadioProfileProtocol::MeshCore;
|
||||
external.params.preamble = 80;
|
||||
f.radio.p.setSecondary(external, false);
|
||||
f.cli.clearAutoSecondary();
|
||||
assert(!f.cli.canAutoSecondary() && !f.cli.autoSecondaryActive());
|
||||
const auto generation = f.radio.p.generation[1];
|
||||
for (unsigned i = 0; i < 4; ++i) f.advance(1, false);
|
||||
assert(f.radio.p.secondary.params == external.params && f.radio.p.generation[1] == generation);
|
||||
f.cmd("set radio2 913.5,500,8,5,rxtx,80"); f.advance(2000);
|
||||
assert(f.cli.manualSecondaryConfigured() && f.radio.p.secondary.params.freq == 913.5f);
|
||||
assert(f.cli.useSecondaryProtocol(mesh::RadioProfileProtocol::Meshtext));
|
||||
external.params.freq = 914.5f;
|
||||
f.radio.p.setSecondary(external, false);
|
||||
f.cli.clearSecondaryProtocol(); f.advance(1, false);
|
||||
assert(f.radio.p.secondary.params == external.params);
|
||||
assert(!f.cli.useSecondaryProtocol(mesh::RadioProfileProtocol::Meshtext));
|
||||
}
|
||||
|
||||
static void remoteBarrier() {
|
||||
for (bool delivered : {false, true}) {
|
||||
Fixture f(true);
|
||||
assert(f.cli.requestAutoSecondary(candidate()));
|
||||
const auto generation = f.radio.p.generation[1];
|
||||
f.cli.beginReplyCommand(); f.cmd("set radio2 912.5,500,8,5,rxtx,80"); f.cli.endReplyCommand();
|
||||
assert(f.cli.hasReplyMutation() && !f.cli.canAutoSecondary());
|
||||
f.advance(10000);
|
||||
assert(f.radio.p.generation[1] == generation);
|
||||
assert(f.cli.finishReplyMutation(delivered)); f.advance(1);
|
||||
if (delivered) {
|
||||
assert(f.cli.manualSecondaryConfigured() && !f.cli.autoSecondaryActive());
|
||||
assert(f.radio.p.secondary.params.freq == 912.5f);
|
||||
} else {
|
||||
assert(f.cli.autoSecondaryActive() && f.radio.p.generation[1] == generation);
|
||||
assert(f.fs.files.count("/radio_profiles") == 0);
|
||||
}
|
||||
}
|
||||
Fixture f(true);
|
||||
assert(f.cli.requestAutoSecondary(candidate()));
|
||||
const auto generation = f.radio.p.generation[1];
|
||||
f.cli.beginReplyCommand(); f.cmd("set radio2 off"); f.cli.endReplyCommand();
|
||||
f.cli.clearAutoSecondary(); // alias removed while the old generation owns a reply
|
||||
f.advance(10000);
|
||||
assert(f.radio.p.generation[1] == generation);
|
||||
assert(f.cli.finishReplyMutation(true)); f.advance(1);
|
||||
assert(!f.radio.p.enabled() && !f.cli.canAutoSecondary());
|
||||
}
|
||||
|
||||
static void storageGuards() {
|
||||
Fixture f;
|
||||
f.fs.files["/radio_profiles"] = {0};
|
||||
Radio reboot; mesh::RadioProfileCLI restored;
|
||||
restored.begin(&f.fs, &reboot, &f.clock);
|
||||
assert(!restored.canAutoSecondary() && !restored.requestAutoSecondary(candidate()));
|
||||
assert(!restored.useSecondaryProtocol(mesh::RadioProfileProtocol::Meshtext));
|
||||
assert(f.fs.files["/radio_profiles"] == std::vector<uint8_t>{0});
|
||||
restored.begin(nullptr, &reboot, &f.clock);
|
||||
assert(!restored.canAutoSecondary());
|
||||
Fixture valid;
|
||||
valid.cmd("set radio2.cross off");
|
||||
const auto before = valid.fs.files["/radio_profiles"];
|
||||
valid.fs.fail_read_open = true;
|
||||
restored.begin(&valid.fs, &reboot, &valid.clock);
|
||||
assert(!restored.canAutoSecondary() && valid.fs.files["/radio_profiles"] == before);
|
||||
|
||||
Fixture backup;
|
||||
backup.cmd("set radio2 910.5,500,8,5,rxtx,80");
|
||||
const auto committed = backup.fs.files["/radio_profiles"];
|
||||
assert(backup.fs.rename("/radio_profiles", "/radio_profiles.bak"));
|
||||
backup.fs.files["/radio_profiles"] = {0}; backup.fs.fail_remove = true;
|
||||
restored.begin(&backup.fs, &reboot, &backup.clock);
|
||||
assert(restored.manualSecondaryConfigured() && reboot.p.enabled());
|
||||
assert(!restored.canAutoSecondary());
|
||||
assert(!restored.useSecondaryProtocol(mesh::RadioProfileProtocol::Meshtext));
|
||||
assert(backup.fs.files["/radio_profiles.bak"] == committed);
|
||||
|
||||
Fixture malformed;
|
||||
malformed.cmd("set radio2 910.5,500,8,5,rxtx,80");
|
||||
auto image = malformed.fs.files["/radio_profiles"];
|
||||
image[3] &= 0x7F; rewriteCRC(image); // enabled v2 profile cannot lack manual intent
|
||||
malformed.fs.files["/radio_profiles"] = image;
|
||||
Radio rejected;
|
||||
restored.begin(&malformed.fs, &rejected, &malformed.clock);
|
||||
assert(!rejected.p.enabled() && !restored.canAutoSecondary());
|
||||
}
|
||||
|
||||
static void featureOff() {
|
||||
Fixture f;
|
||||
assert(!f.cli.canAutoSecondary() && !f.cli.requestAutoSecondary(candidate()));
|
||||
assert(!f.cli.autoSecondaryActive());
|
||||
assert(!f.cli.useSecondaryProtocol(mesh::RadioProfileProtocol::Meshtext));
|
||||
f.cli.clearAutoSecondary(); f.cli.clearSecondaryProtocol();
|
||||
assert(!f.radio.p.enabled() && f.fs.files.empty());
|
||||
f.cmd("set radio2 910.5,500,8,5,rxtx,80"); f.advance(2000);
|
||||
assert(f.radio.p.enabled() && f.fs.files["/radio_profiles"][2] == 1);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
assert(argc == 2);
|
||||
if (!strcmp(argv[1], "lifetime")) lifetime();
|
||||
else if (!strcmp(argv[1], "saved_intent")) savedIntent();
|
||||
else if (!strcmp(argv[1], "manual_takeover")) manualTakeover();
|
||||
else if (!strcmp(argv[1], "overlay")) overlay();
|
||||
else if (!strcmp(argv[1], "leases")) leasesAndSchedules();
|
||||
else if (!strcmp(argv[1], "primary_temporary")) primaryTemporary();
|
||||
else if (!strcmp(argv[1], "automatic_permission")) automaticPermission();
|
||||
else if (!strcmp(argv[1], "unmanaged_takeover")) unmanagedTakeover();
|
||||
else if (!strcmp(argv[1], "remote_barrier")) remoteBarrier();
|
||||
else if (!strcmp(argv[1], "storage")) storageGuards();
|
||||
else if (!strcmp(argv[1], "feature_off")) featureOff();
|
||||
else return 2;
|
||||
puts("PASS auto secondary ownership");
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class RadioProfileAutoTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++")
|
||||
if compiler is None:
|
||||
raise unittest.SkipTest("a host C++17 compiler is required")
|
||||
cls.work = tempfile.TemporaryDirectory(prefix="radio-profile-auto-")
|
||||
cls.addClassCleanup(cls.work.cleanup)
|
||||
directory = Path(cls.work.name)
|
||||
source = directory / "auto.cpp"
|
||||
source.write_text(HARNESS, encoding="utf-8")
|
||||
cls.binaries = {}
|
||||
for enabled, fleet in ((0, 0), (1, 0), (1, 1)):
|
||||
binary = directory / f"auto-{enabled}-{fleet}.exe"
|
||||
result = subprocess.run([
|
||||
compiler, "-std=c++17", "-Wall", "-Wextra",
|
||||
f"-DMESH_ENABLE_MESHTEXT_CHAT={enabled}", f"-DMESH_ENABLE_FLEET_CONTROL={fleet}",
|
||||
"-I", str(ROOT), "-I", str(ROOT / "test/fixtures/radio_profiles/mocks"),
|
||||
"-I", str(ROOT / "test/mocks"), "-I", str(ROOT / "src"),
|
||||
str(ROOT / "src/helpers/RadioProfileCLI.cpp"), str(source), "-o", str(binary),
|
||||
], capture_output=True, text=True, timeout=60)
|
||||
if result.returncode:
|
||||
raise AssertionError(result.stdout + result.stderr)
|
||||
cls.binaries[enabled, fleet] = binary
|
||||
|
||||
def test_feature_off_keeps_existing_role_behavior(self):
|
||||
self.run_case("feature_off", enabled=0, fleet=0)
|
||||
|
||||
def test_ownership_intent_and_precedence(self):
|
||||
for fleet in (0, 1):
|
||||
for case in ("lifetime", "saved_intent", "manual_takeover", "overlay", "leases",
|
||||
"primary_temporary", "automatic_permission", "unmanaged_takeover",
|
||||
"remote_barrier", "storage"):
|
||||
with self.subTest(fleet=fleet, case=case):
|
||||
self.run_case(case, fleet=fleet)
|
||||
|
||||
def run_case(self, case, enabled=1, fleet=0):
|
||||
result = subprocess.run([str(self.binaries[enabled, fleet]), case],
|
||||
capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn("PASS auto secondary", result.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -136,7 +136,7 @@ int main(int argc, char** argv) {
|
||||
else if (which == "wrong_size") { state.bytes.pop_back(); expected = Result::Invalid; }
|
||||
else if (which == "corrupt_crc") { state.bytes[7] ^= 1; expected = Result::Invalid; }
|
||||
else if (which == "future_version") {
|
||||
state.bytes[2] = 2;
|
||||
state.bytes[2] = 3;
|
||||
const uint32_t crc = mesh::checksum(state.bytes.data(), state.bytes.size() - 4);
|
||||
memcpy(state.bytes.data() + state.bytes.size() - 4, &crc, 4);
|
||||
expected = Result::Invalid;
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
"""Host-only exercise of the actual SX1262 owned protocol/packet staging path."""
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
|
||||
import test_sx1262_batched_modulation as compiler
|
||||
from test_radio_receive_contract import method
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class ProtocolBatchingTests(unittest.TestCase):
|
||||
compile_run = compiler.BatchedModulationTests.compile_run
|
||||
|
||||
def test_owned_protocol_commit_errors_and_full_setup_fallback(self):
|
||||
source = (ROOT / "src/helpers/radiolib/CustomSX1262.h").read_text()
|
||||
state = (ROOT / "src/helpers/radiolib/SX1262ProfileSwitchState.h").read_text()
|
||||
methods = "\n".join(method(source, signature).replace(" override", "") for signature in (
|
||||
"int16_t setCRC(", "int16_t explicitHeader()", "int16_t invertIQ(",
|
||||
"int16_t setProfileProtocol(", "int16_t startReceive()"))
|
||||
harness = r'''
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
@STATE@
|
||||
#define MC_SX1262_FAST_PACKET_CACHE 1
|
||||
#define RADIOLIB_ERR_NONE 0
|
||||
#define RADIOLIB_SX126X_RX_TIMEOUT_INF 0xffffff
|
||||
#define RADIOLIB_SX126X_PACKET_TYPE_LORA 1
|
||||
#define RADIOLIB_SX126X_LORA_CRC_ON 1
|
||||
#define RADIOLIB_SX126X_LORA_HEADER_EXPLICIT 0
|
||||
#define RADIOLIB_SX126X_LORA_IQ_STANDARD 0
|
||||
#define RADIOLIB_RADIO_MODE_NONE 0
|
||||
#define RADIOLIB_IRQ_RX_DEFAULT_FLAGS 1
|
||||
#define RADIOLIB_IRQ_RX_DEFAULT_MASK 2
|
||||
#define RADIOLIB_IRQ_PREAMBLE_DETECTED 3
|
||||
struct Module {
|
||||
enum {MODE_RX=1}; std::string* trace;
|
||||
void setRfSwitchState(int n) { assert(n==MODE_RX);*trace+='W'; }
|
||||
};
|
||||
struct SX1262 {
|
||||
std::string trace; char fail=0; bool standbyXOSC=true;
|
||||
size_t preambleLengthLoRa=32;
|
||||
uint8_t crcTypeLoRa=1, implicitLen=255, headerType=0, invertIQEnabled=0;
|
||||
uint8_t physicalSync=0x12, physicalCrc=1, physicalLen=255, physicalHeader=0, physicalIq=0;
|
||||
bool iqWorkaroundNormal=true;
|
||||
unsigned packetWrites=0, workaroundWrites=0, syncWrites=0;
|
||||
uint32_t rxTimeout=0; int stagedMode=3;
|
||||
Module module{&trace};Module* getMod() { return &module; }
|
||||
int16_t call(char c) { trace+=c;return fail==c ? -100:0; }
|
||||
int16_t setSyncWord(uint8_t sync) {
|
||||
++syncWrites;physicalSync=sync;return call('Y');
|
||||
}
|
||||
// Model the pinned RadioLib setPacketParams() IQ-register workaround as
|
||||
// part of the packet commit, including an error before the command itself.
|
||||
int16_t setPacketParams(size_t p,uint8_t crc,uint8_t len,uint8_t header,uint8_t iq) {
|
||||
assert(p==preambleLengthLoRa);
|
||||
++workaroundWrites;
|
||||
if(call('I')) return -100;
|
||||
iqWorkaroundNormal=iq==0;
|
||||
++packetWrites;
|
||||
if(call('P')) return -100;
|
||||
physicalCrc=crc;physicalLen=len;physicalHeader=header;physicalIq=iq;return 0;
|
||||
}
|
||||
int16_t setCRC(uint8_t crc,uint16_t,uint16_t,bool) {
|
||||
if(call('C')) return -100;crcTypeLoRa=crc;
|
||||
return setPacketParams(preambleLengthLoRa,crcTypeLoRa,implicitLen,headerType,invertIQEnabled);
|
||||
}
|
||||
int16_t explicitHeader() {
|
||||
if(call('E')) return -100;
|
||||
const int rc=setPacketParams(preambleLengthLoRa,crcTypeLoRa,255,0,invertIQEnabled);
|
||||
if(!rc) {implicitLen=255;headerType=0;}return rc;
|
||||
}
|
||||
int16_t invertIQ(bool enabled) {
|
||||
if(call('i')) return -100;invertIQEnabled=enabled;
|
||||
return setPacketParams(preambleLengthLoRa,crcTypeLoRa,implicitLen,headerType,invertIQEnabled);
|
||||
}
|
||||
int16_t clearIrqStatus() { return call('c'); }
|
||||
int16_t setRx(uint32_t timeout) { assert(timeout==0xffffff);return call('R'); }
|
||||
int16_t startReceive(uint32_t,uint32_t,uint32_t,size_t) {
|
||||
const int rc=setPacketParams(preambleLengthLoRa,crcTypeLoRa,implicitLen,headerType,invertIQEnabled);
|
||||
return rc ? rc:call('F');
|
||||
}
|
||||
uint8_t getPacketType() { call('Q');return 1; }
|
||||
};
|
||||
struct Radio: SX1262 {
|
||||
SX1262ProfileSwitchState _profileSwitch{true};
|
||||
bool _coldStandby=false;uint32_t _profileFastResumes=0;
|
||||
@METHODS@
|
||||
};
|
||||
void owned(Radio& r) {
|
||||
r._profileSwitch.rxResult(0,true);
|
||||
r._profileSwitch.packetResult(0,r.preambleLengthLoRa,r.crcTypeLoRa,r.implicitLen,r.headerType,r.invertIQEnabled);
|
||||
r._profileSwitch.begin(true,true);r._profileSwitch.standbyResult(0);
|
||||
assert(r._profileSwitch.canResumeFast());r.trace.clear();
|
||||
}
|
||||
void restored(Radio& r) {
|
||||
r._profileSwitch.end(false);r.fail=0;r.trace.clear();
|
||||
assert(r.setProfileProtocol(0x12)==0);
|
||||
assert(r.trace=="YCIPEIPiIP");
|
||||
assert(r.physicalSync==0x12 && r.physicalCrc==1 && r.physicalLen==255
|
||||
&& r.physicalHeader==0 && r.physicalIq==0 && r.iqWorkaroundNormal);
|
||||
assert(r.startReceive()==0 && r._profileSwitch.rxValid);
|
||||
}
|
||||
int main() {
|
||||
// Staging itself is sync-only; resume performs exactly one full packet
|
||||
// write and one IQ workaround. An acknowledged old tuple cannot skip it.
|
||||
for(uint8_t sync:{uint8_t(0x12),uint8_t(0x2b)}) {
|
||||
Radio r;owned(r);assert(r.setProfileProtocol(sync)==0 && r.trace=="Y");
|
||||
assert(!r._profileSwitch.packetValid && r._profileSwitch.rxValid);
|
||||
assert(r.packetWrites==0 && r.workaroundWrites==0);
|
||||
assert(r.startReceive()==0 && r.trace=="YcIPWR");
|
||||
assert(r.packetWrites==1 && r.workaroundWrites==1 && r.syncWrites==1);
|
||||
assert(r._profileSwitch.packetValid && r._profileSwitch.rxValid);
|
||||
assert(r.physicalSync==sync && r.iqWorkaroundNormal && r.physicalLen==255);
|
||||
}
|
||||
// A nonstandard prior tuple is repaired, not merely assumed compatible.
|
||||
{ Radio r;r.crcTypeLoRa=r.physicalCrc=0;r.implicitLen=r.physicalLen=16;
|
||||
r.headerType=r.physicalHeader=1;r.invertIQEnabled=r.physicalIq=1;r.iqWorkaroundNormal=false;
|
||||
owned(r);assert(r.setProfileProtocol(0x2b)==0);
|
||||
assert(r.physicalCrc==0 && r.physicalHeader==1 && r.physicalIq==1);
|
||||
assert(r.startReceive()==0 && r.packetWrites==1 && r.workaroundWrites==1);
|
||||
assert(r.physicalCrc==1 && r.physicalHeader==0 && r.physicalIq==0 && r.iqWorkaroundNormal);
|
||||
}
|
||||
// Setup, partial/busy hops, disabled optimization, and a revoked RX context
|
||||
// must execute all normal setters. No staging before acknowledged standby.
|
||||
for(int gate=0;gate<5;++gate) {
|
||||
Radio r;
|
||||
if(gate==1) {r._profileSwitch.rxResult(0,true);r._profileSwitch.begin(true,true);}
|
||||
if(gate==2) {owned(r);r._profileSwitch.enabled=false;r._profileSwitch.invalidate();}
|
||||
if(gate==3) {owned(r);r._profileSwitch.invalidate();}
|
||||
if(gate==4) {r._profileSwitch.rxResult(0,true);r._profileSwitch.begin(false,true);r._profileSwitch.standbyResult(0);}
|
||||
r.trace.clear();assert(r.setProfileProtocol(0x2b)==0 && r.trace=="YCIPEIPiIP");
|
||||
assert(r.packetWrites==3 && r.workaroundWrites==3 && !r._profileSwitch.packetValid);
|
||||
}
|
||||
// Sync, IRQ-clear, IQ-workaround, packet, and RX failures all revoke reuse;
|
||||
// wrapper rollback can then restore old wire settings through full setup.
|
||||
for(char failure:std::string("YcIPR")) {
|
||||
Radio r;owned(r);r.fail=failure;
|
||||
if(failure=='Y') assert(r.setProfileProtocol(0x2b)==-100);
|
||||
else {assert(r.setProfileProtocol(0x2b)==0);assert(r.startReceive()==-100);}
|
||||
assert(r._profileSwitch.failed() && !r._profileSwitch.rxValid && !r._profileSwitch.packetValid);
|
||||
restored(r);
|
||||
}
|
||||
// Fallback setup errors propagate; no later setter hides an earlier error.
|
||||
for(char failure:std::string("CEi")) {
|
||||
Radio r;r.fail=failure;assert(r.setProfileProtocol(0x2b)==-100);
|
||||
assert(r.trace.back()==failure && !r._profileSwitch.rxValid);restored(r);
|
||||
}
|
||||
}
|
||||
'''
|
||||
self.compile_run(harness.replace("@STATE@", state).replace("@METHODS@", methods))
|
||||
|
||||
def test_wrapper_uses_batched_protocol_and_pinned_iq_workaround(self):
|
||||
wrapper = (ROOT / "src/helpers/radiolib/CustomSX1262Wrapper.h").read_text()
|
||||
apply = method(wrapper, "bool applyProtocol(")
|
||||
self.assertIn("setProfileProtocol(sync)", apply)
|
||||
self.assertNotIn("setCRC(", apply)
|
||||
radio = (ROOT / "src/helpers/radiolib/CustomSX1262.h").read_text()
|
||||
resume = method(radio, "int16_t startReceive()")
|
||||
self.assertIn("rc = setPacketParams(", resume)
|
||||
self.assertLess(resume.index("rc = setPacketParams("), resume.index("rc = setRx("))
|
||||
# The installed/pinned implementation delegates its required IQ-register
|
||||
# repair to setPacketParams. Keep this assumption explicit and tested.
|
||||
commands = ROOT / ".pio/libdeps/heltec_v4_2_v4_3_companion_radio_full_femon/RadioLib/src/modules/SX126x/SX126x_commands.cpp"
|
||||
if commands.exists():
|
||||
packet = method(commands.read_text(), "int16_t SX126x::setPacketParams(")
|
||||
self.assertIn("fixInvertedIQ(invertIQ)", packet)
|
||||
self.assertLess(packet.index("fixInvertedIQ("), packet.index("SPIwriteStream("))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user