From b7129f1df1fd4caceb3af62ce3f62aeb74cc8c9a Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Thu, 3 Dec 2026 23:37:46 +0100 Subject: [PATCH] Repeater: the config checksum of the stats request covers regions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changelog-cs: Repeater: kontrolní součet konfigurace v požadavku na statistiky teď pokrývá i regiony Changelog-topic: stats-bundle Co-Authored-By: Claude Opus 5.5 --- docs/stats-bundle.md | 59 ++++++++++++-- examples/simple_repeater/MyMesh.cpp | 14 ++++ src/helpers/StatsBundle.h | 66 +++++++++++++++- test/test_stats_bundle/test_stats_bundle.cpp | 41 +++++++++- test/vectors/gen_stats_bundle_vectors.py | 41 +++++++++- test/vectors/stats_bundle_vectors.json | 82 +++++++++++++++++++- 6 files changed, 286 insertions(+), 17 deletions(-) diff --git a/docs/stats-bundle.md b/docs/stats-bundle.md index ca633d19f..7c9377932 100644 --- a/docs/stats-bundle.md +++ b/docs/stats-bundle.md @@ -152,7 +152,7 @@ prefs that Ansible manages. All integers big-endian. | # | bytes | field | encoding | |---|---|---|---| -| 1 | 1 | serialization version | `1` | +| 1 | 1 | serialization version | `2` (since regions; `1` had none) | | 2 | 4 | radio frequency | MHz x 1000 rounded: `round(869.432 * 1000)` = 869432 | | 3 | 4 | bandwidth | kHz x 1000 rounded (62.5 -> 62500) | | 4 | 1 | `sf` | | @@ -174,16 +174,65 @@ prefs that Ansible manages. All integers big-endian. | 20 | 1 | `rxps` level | | | 21 | 1 | `rxps` preamble | | | 22 | 1 | bridge | `bridge.enabled` 0 / 1 | +| 23 | 1 + n | home region | name, see "Regions" below (empty = none) | +| 24 | 1 | region count | `N`, number of regions (the root `*` is not counted) | +| 25.. | N x (1 + n, 1 + m, 1) | regions | `name`, `parent`, `flood`, sorted, see below | + +### Regions (rows 23-25) + +Appended after the bridge byte, so the CRC of a node and of the inventory can +be compared without any RF traffic. Everything is **length-prefixed UTF-8** +(1 length byte, then the bytes, like the node name): + +``` +home_name N { name parent flood } x N +``` + +* **Name** (`home`, `name`, `parent`): one leading `#` dropped (the CLI and + `meshcore_region` ignore it too), at most 31 bytes; the root `*`, an unset + value and "no parent" are all the **empty** string (length byte 0). +* **home_name**: the home region (`region home`); empty when there is none + (stored home id 0, which the CLI shows as `*`). +* **N**: one byte, the number of regions. +* **Region**: `name`, `parent` (the name of the parent; empty = child of the + root), `flood` (1 byte: 1 = flood allowed, 0 = denied, `region allowf` / + `region denyf`). +* **Order**: sorted by **bytes** of `name` (memcmp, a shorter prefix first), then + of `parent`. Insertion order, internal ids, and the order of `region` output + do not matter. A parent id that no region has (a corrupt map) is written as + the name `?`, which no real region can have, so it shows up as drift. + +Not in it: the root's own flood flag, the default flood scope +(`region default`; the module sets it only when `mc_default_scope` is given, +so the inventory does not always have a value), internal ids. The CRC reads the +**live** map, so a `region` change that was not yet saved (`region save`) is +already in it; after a reboot it is gone again. + +**From the inventory alone** (role `repeater-state`, module `meshcore_region`): + +| inventory | in the serialization | +|---|---| +| `mc_region_home` (default `"*"` when absent) | `home_name`; `"*"` -> empty | +| `mc_regions` list | one region per item; `N` = its length | +| item `name` | `name`, without `#` | +| item `parent` (default `"*"`) | `parent`; `"*"` -> empty | +| item `flood` (default `true`) | `flood` 1 / 0 | + +Example, `mc_regions: [{name: cz}, {name: cz-ulk, parent: cz}, {name: cz-sudety, +parent: cz}, {name: cs}]` with `mc_region_home: cz-ulk` gives (hex) +`06 637a2d756c6b | 04 | 02 6373 00 01 | 02 637a 00 01 | 09 637a2d7375646574 +79 02 637a 01 | 06 637a2d756c6b 02 637a 01` (spaces and bars only for reading); +the whole serialization has CRC `D5FD` (vector `cz_repeater`, and the same +map in another order, `cz_repeater_reordered`). `regions_canonical()` in the +Python reference is the whole recipe: lift it as it is. Reference: `prefs_canonical()` in `test/vectors/gen_stats_bundle_vectors.py`; -test vectors (canonical bytes and CRC for two nodes) in +test vectors (canonical bytes and CRC for three nodes, one with a denied-flood region) in `test/vectors/stats_bundle_vectors.json`. **Not in it:** the `filter flow` rules (they have `rules_auto` / `rules_static`), `filter` age and dry-run, FairnessLimiter caps, passwords, -guest and ACL entries, regions (the region map is persisted in its own file, not -in the prefs -- extending the CRC to it needs a canonical order of the map; open), -the adaptive battery thresholds (`pwr.*`, their own files) and GPS settings. +guest and ACL entries, the adaptive battery thresholds (`pwr.*`, their own files) and GPS settings. Adding a field means a new serialization version byte (and a new vector). ## Sizes diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 7941d200f..7526efe42 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -631,6 +631,20 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t sp.rxps_sleep_us = _prefs.rxps.sleep_us; sp.rxps_level = _prefs.rxps.level; sp.rxps_preamble = _prefs.rxps.preamble; #endif + // regions: the live map (a `region` change not yet saved counts too) + StatsRegion sr[MAX_REGION_ENTRIES]; + char sr_none[1] = {0}; + int nr = region_map.getCount(); + for (int i = 0; i < nr; i++) { + const RegionEntry* e = region_map.getByIdx(i); + const RegionEntry* par = e->parent == 0 ? NULL : region_map.findById(e->parent); + sr[i].name = e->name; + sr[i].parent = e->parent == 0 ? sr_none : (par ? par->name : "?"); + sr[i].flood = (e->flags & REGION_DENY_FLOOD) ? 0 : 1; + } + sp.regions = sr; sp.n_regions = (uint8_t)nr; + const RegionEntry* home = region_map.getHomeRegion(); + sp.home = home ? home->name : sr_none; in.prefs_crc = sbPrefsCrc(sp); } int n = sbEncode(in, payload_len >= 2 ? payload[1] : 0, &reply_data[4], SB_PAGE_MAX); diff --git a/src/helpers/StatsBundle.h b/src/helpers/StatsBundle.h index e69092629..a2d997f4c 100644 --- a/src/helpers/StatsBundle.h +++ b/src/helpers/StatsBundle.h @@ -305,6 +305,12 @@ inline bool sbDecode(const uint8_t* b, int len, StatsBundleOut* o) { // -- prefs CRC -------------------------------------------------------------- // CRC-16/CCITT-FALSE over the canonical serialization (docs/stats-bundle.md). +struct StatsRegion { + const char* name; + const char* parent; + uint8_t flood; // 1 = flood allowed, 0 = denied +}; + struct StatsPrefs { float freq_mhz, bw_khz; uint8_t sf, cr; @@ -315,15 +321,52 @@ struct StatsPrefs { uint8_t rxps_enabled, rxps_level, rxps_preamble; uint32_t rxps_rx_us, rxps_sleep_us; uint8_t bridge_enabled; + // regions (serialization v2): home region name ("*" / "" / NULL = none) and + // the whole map; parent "" = child of the root, "?" = parent id not found + const char* home; + const struct StatsRegion* regions; + uint8_t n_regions; }; inline uint32_t sbRound1000(float x) { double d = (double)x * 1000.0; return (uint32_t)(d + 0.5); } +// Region names in the canonical form: one leading '#' dropped, "*" (the root) +// and NULL = empty, at most 31 bytes. +struct SbName { const uint8_t* p; uint8_t n; }; +inline SbName sbCanonName(const char* s) { + SbName r = { (const uint8_t*)"", 0 }; + if (!s) return r; + if (*s == '#') s++; + if (s[0] == '*' && s[1] == 0) return r; + size_t n = 0; + while (n < 31 && s[n]) n++; + r.p = (const uint8_t*)s; r.n = (uint8_t)n; + return r; +} +inline uint16_t sbCrcName(uint16_t crc, const SbName& a) { + crc = flowCrc16(crc, &a.n, 1); + return a.n ? flowCrc16(crc, a.p, a.n) : crc; +} +// bytewise (name, then parent), as Python's sorted() on bytes +inline int sbRegionCmp(const StatsRegion& a, const StatsRegion& b) { + SbName x = sbCanonName(a.name), y = sbCanonName(b.name); + for (int k = 0; k < 2; k++) { + uint8_t m = x.n < y.n ? x.n : y.n; + int c = m ? memcmp(x.p, y.p, m) : 0; + if (c) return c; + if (x.n != y.n) return x.n < y.n ? -1 : 1; + x = sbCanonName(a.parent); y = sbCanonName(b.parent); + } + return 0; +} + +#define SB_REGIONS_MAX 255 + inline uint16_t sbPrefsCrc(const StatsPrefs& p) { uint8_t b[96]; int n = 0; uint32_t f = sbRound1000(p.freq_mhz), w = sbRound1000(p.bw_khz); - b[n++] = 1; // serialization version + b[n++] = 2; // serialization version for (int i = 3; i >= 0; i--) b[n++] = (uint8_t)(f >> (8 * i)); for (int i = 3; i >= 0; i--) b[n++] = (uint8_t)(w >> (8 * i)); b[n++] = p.sf; b[n++] = p.cr; b[n++] = (uint8_t)p.tx_dbm; @@ -340,5 +383,24 @@ inline uint16_t sbPrefsCrc(const StatsPrefs& p) { for (int i = 3; i >= 0; i--) b[n++] = (uint8_t)(p.rxps_sleep_us >> (8 * i)); b[n++] = p.rxps_level; b[n++] = p.rxps_preamble; b[n++] = p.bridge_enabled; - return flowCrc16(0xFFFF, b, (size_t)n); + uint16_t crc = flowCrc16(0xFFFF, b, (size_t)n); + // regions: home, count, then every region ordered by (name, parent) + crc = sbCrcName(crc, sbCanonName(p.home)); + uint8_t cnt = p.n_regions > SB_REGIONS_MAX ? SB_REGIONS_MAX : p.n_regions; + if (!p.regions) cnt = 0; + crc = flowCrc16(crc, &cnt, 1); + uint8_t idx[SB_REGIONS_MAX]; + for (uint8_t i = 0; i < cnt; i++) { // insertion sort of the indices + uint8_t j = i; + while (j > 0 && sbRegionCmp(p.regions[idx[j - 1]], p.regions[i]) > 0) { idx[j] = idx[j - 1]; j--; } + idx[j] = i; + } + for (uint8_t i = 0; i < cnt; i++) { + const StatsRegion& r = p.regions[idx[i]]; + crc = sbCrcName(crc, sbCanonName(r.name)); + crc = sbCrcName(crc, sbCanonName(r.parent)); + uint8_t fl = r.flood ? 1 : 0; + crc = flowCrc16(crc, &fl, 1); + } + return crc; } diff --git a/test/test_stats_bundle/test_stats_bundle.cpp b/test/test_stats_bundle/test_stats_bundle.cpp index 075791e3d..0eb91c212 100644 --- a/test/test_stats_bundle/test_stats_bundle.cpp +++ b/test/test_stats_bundle/test_stats_bundle.cpp @@ -231,23 +231,60 @@ TEST(StatsBundle, RuleChangeMovesSlots) { EXPECT_EQ('c', b.rule[1].kind); EXPECT_EQ(1, b.rule[1].slot); } +static const StatsRegion RG_CZ[] = {{"cz", "", 1}, {"cz-ulk", "cz", 1}, {"cz-sudety", "cz", 1}, {"cs", "*", 1}}; +// the same map, other insertion order and spelling ('#', parent "*") +static const StatsRegion RG_CZ_ALT[] = {{"cs", "*", 1}, {"cz-sudety", "#cz", 1}, {"cz-ulk", "cz", 1}, {"#cz", NULL, 1}}; + static StatsPrefs P1() { StatsPrefs p; memset(&p, 0, sizeof(p)); p.freq_mhz = 869.432f; p.bw_khz = 62.5f; p.sf = 8; p.cr = 8; p.tx_dbm = 22; p.name = "mast-three"; p.flood_max = 8; p.flood_max_advert = 3; p.path_hash_mode = 1; p.powersaving = 1; p.rx_boosted_gain = 1; + p.home = "cz-ulk"; p.regions = RG_CZ; p.n_regions = 4; return p; } +// Expected values: test/vectors/stats_bundle_vectors.json ("prefs") and the +// reference prefs_canonical() in gen_stats_bundle_vectors.py. TEST(StatsPrefsCrc, MatchesPythonReference) { - EXPECT_EQ(0x8A04, sbPrefsCrc(P1())); + EXPECT_EQ(0xD5FD, sbPrefsCrc(P1())); StatsPrefs q; memset(&q, 0, sizeof(q)); q.freq_mhz = 869.432f; q.bw_khz = 62.5f; q.sf = 8; q.cr = 8; q.tx_dbm = -9; q.name = "x1-\xc4\x8d" "e" "\xc5\xa1"; q.advert_interval = 120; q.flood_advert_interval = 12; q.flood_max = 64; q.flood_max_unscoped = 64; q.flood_max_advert = 64; q.path_hash_mode = 2; q.disable_fwd = 1; q.rxps_enabled = 1; q.rxps_rx_us = 7500; q.rxps_sleep_us = 30000; q.rxps_level = 2; q.rxps_preamble = 16; q.bridge_enabled = 1; - EXPECT_EQ(0xADE6, sbPrefsCrc(q)); + static const StatsRegion rq[] = {{"cz", "", 1}, {"cz-kvk", "cz", 0}}; + q.home = "*"; q.regions = rq; q.n_regions = 2; + EXPECT_EQ(0xDC8C, sbPrefsCrc(q)); +} + +TEST(StatsPrefsCrc, RegionsAreOrderIndependent) { + StatsPrefs p = P1(), q = P1(); + q.home = "#cz-ulk"; q.regions = RG_CZ_ALT; + EXPECT_EQ(sbPrefsCrc(p), sbPrefsCrc(q)); + EXPECT_EQ(0xD5FD, sbPrefsCrc(q)); +} + +TEST(StatsPrefsCrc, RegionsMatter) { + StatsPrefs p = P1(); + p.home = "*"; p.regions = NULL; p.n_regions = 0; + EXPECT_EQ(0x0B49, sbPrefsCrc(p)); // no map, no home + p.home = NULL; + EXPECT_EQ(0x0B49, sbPrefsCrc(p)); // NULL home = "*" = none + static const StatsRegion two[] = {{"cz-ulk", "cz", 1}, {"cz", "*", 1}}; + p.home = "cz-ulk"; p.regions = two; p.n_regions = 2; + EXPECT_EQ(0x7A3A, sbPrefsCrc(p)); + static const StatsRegion denied[] = {{"cz-ulk", "cz", 0}, {"cz", "*", 1}}; + p.regions = denied; + EXPECT_EQ(0x6A1B, sbPrefsCrc(p)); // flood allow/deny is covered + uint16_t base = sbPrefsCrc(P1()); + p = P1(); p.home = "cz"; EXPECT_NE(base, sbPrefsCrc(p)); + p = P1(); p.n_regions = 3; EXPECT_NE(base, sbPrefsCrc(p)); + static const StatsRegion moved[] = {{"cz", "", 1}, {"cz-ulk", "cz", 1}, {"cz-sudety", "cs", 1}, {"cs", "*", 1}}; + p = P1(); p.regions = moved; EXPECT_NE(base, sbPrefsCrc(p)); + static const StatsRegion orphan[] = {{"cz", "", 1}, {"cz-ulk", "cz", 1}, {"cz-sudety", "?", 1}, {"cs", "*", 1}}; + p = P1(); p.regions = orphan; EXPECT_NE(base, sbPrefsCrc(p)); } TEST(StatsPrefsCrc, EveryFieldMatters) { diff --git a/test/vectors/gen_stats_bundle_vectors.py b/test/vectors/gen_stats_bundle_vectors.py index 20401fa82..9bff94559 100644 --- a/test/vectors/gen_stats_bundle_vectors.py +++ b/test/vectors/gen_stats_bundle_vectors.py @@ -239,16 +239,38 @@ def round1000(x: float) -> int: return int(x * 1000.0 + 0.5) +def region_name(s) -> bytes: + """Canonical region name: one leading '#' dropped, "*" (the root) / None = empty, <= 31 B.""" + if not s: + return b"" + if s[0] == "#": + s = s[1:] + return b"" if s == "*" else s.encode()[:31] + + +def regions_canonical(home, regions) -> bytes: + """home name, count, then each region (name, parent, flood) sorted by (name, parent) bytes. + Inventory: mc_region_home (default "*") and mc_regions {name, parent (default "*"), flood (default true)}.""" + ent = sorted((region_name(r["name"]), region_name(r.get("parent")), 1 if r.get("flood", True) else 0) + for r in regions) + ln = lambda b: bytes([len(b)]) + b # noqa: E731 + out = ln(region_name(home)) + bytes([len(ent)]) + for n, par, fl in ent: + out += ln(n) + ln(par) + bytes([fl]) + return out + + def prefs_canonical(p) -> bytes: name = p["name"].encode()[:31] u32 = lambda v: v.to_bytes(4, "big") # noqa: E731 - return (bytes([1]) + u32(round1000(p["freq_mhz"])) + u32(round1000(p["bw_khz"])) + return (bytes([2]) + u32(round1000(p["freq_mhz"])) + u32(round1000(p["bw_khz"])) + bytes([p["sf"], p["cr"], p["tx_dbm"] & 0xFF, len(name)]) + name + bytes([p["advert_interval"], p["flood_advert_interval"], p["flood_max"], p["flood_max_unscoped"], p["flood_max_advert"], p["path_hash_mode"], p["disable_fwd"], p["powersaving"], p["rx_boosted_gain"], p["rxps_enabled"]]) + u32(p["rxps_rx_us"]) + u32(p["rxps_sleep_us"]) - + bytes([p["rxps_level"], p["rxps_preamble"], p["bridge_enabled"]])) + + bytes([p["rxps_level"], p["rxps_preamble"], p["bridge_enabled"]]) + + regions_canonical(p.get("home", "*"), p.get("regions", []))) PREFS_CASES = [ @@ -256,12 +278,23 @@ PREFS_CASES = [ advert_interval=0, flood_advert_interval=0, flood_max=8, flood_max_unscoped=0, flood_max_advert=3, path_hash_mode=1, disable_fwd=0, powersaving=1, rx_boosted_gain=1, rxps_enabled=0, rxps_rx_us=0, rxps_sleep_us=0, rxps_level=0, rxps_preamble=0, - bridge_enabled=0)), + bridge_enabled=0, home="cz-ulk", + regions=[dict(name="cz"), dict(name="cz-ulk", parent="cz"), + dict(name="cz-sudety", parent="cz"), dict(name="cs")])), + # same map as cz_repeater, other insertion order and spelling (#, parent "*"): same canonical bytes + ("cz_repeater_reordered", dict(freq_mhz=869.432, bw_khz=62.5, sf=8, cr=8, tx_dbm=22, name="mast-three", + advert_interval=0, flood_advert_interval=0, flood_max=8, flood_max_unscoped=0, + flood_max_advert=3, path_hash_mode=1, disable_fwd=0, powersaving=1, + rx_boosted_gain=1, rxps_enabled=0, rxps_rx_us=0, rxps_sleep_us=0, rxps_level=0, + rxps_preamble=0, bridge_enabled=0, home="#cz-ulk", + regions=[dict(name="cs", parent="*"), dict(name="cz-sudety", parent="cz"), + dict(name="cz-ulk", parent="#cz"), dict(name="#cz")])), ("rxps_node", dict(freq_mhz=869.432, bw_khz=62.5, sf=8, cr=8, tx_dbm=-9, name="x1-češ", advert_interval=120, flood_advert_interval=12, flood_max=64, flood_max_unscoped=64, flood_max_advert=64, path_hash_mode=2, disable_fwd=1, powersaving=0, rx_boosted_gain=0, rxps_enabled=1, rxps_rx_us=7500, rxps_sleep_us=30000, rxps_level=2, rxps_preamble=16, - bridge_enabled=1)), + bridge_enabled=1, home="*", + regions=[dict(name="cz"), dict(name="cz-kvk", parent="cz", flood=False)])), ] # ---- cases ----------------------------------------------------------------- diff --git a/test/vectors/stats_bundle_vectors.json b/test/vectors/stats_bundle_vectors.json index deaed8a44..dcaf29a7b 100644 --- a/test/vectors/stats_bundle_vectors.json +++ b/test/vectors/stats_bundle_vectors.json @@ -1334,8 +1334,8 @@ }, "prefs": [ { - "canonical": "01000d44380000f424080816077474682d6c746d000008000301000101000000000000000000000000", - "crc16": "8A04", + "canonical": "02000d44380000f424080816077474682d6c746d00000800030100010100000000000000000000000006637a2d756c6b04026373000102637a000109637a2d73756465747902637a0106637a2d756c6b02637a01", + "crc16": "D5FD", "name": "cz_repeater", "prefs": { "advert_interval": 0, @@ -1348,9 +1348,26 @@ "flood_max_advert": 3, "flood_max_unscoped": 0, "freq_mhz": 869.432, + "home": "cz-ulk", "name": "mast-three", "path_hash_mode": 1, "powersaving": 1, + "regions": [ + { + "name": "cz" + }, + { + "name": "cz-ulk", + "parent": "cz" + }, + { + "name": "cz-sudety", + "parent": "cz" + }, + { + "name": "cs" + } + ], "rx_boosted_gain": 1, "rxps_enabled": 0, "rxps_level": 0, @@ -1362,8 +1379,54 @@ } }, { - "canonical": "01000d44380000f4240808f70878312dc48d65c5a1780c404040020100000100001d4c00007530021001", - "crc16": "ADE6", + "canonical": "02000d44380000f424080816077474682d6c746d00000800030100010100000000000000000000000006637a2d756c6b04026373000102637a000109637a2d73756465747902637a0106637a2d756c6b02637a01", + "crc16": "D5FD", + "name": "cz_repeater_reordered", + "prefs": { + "advert_interval": 0, + "bridge_enabled": 0, + "bw_khz": 62.5, + "cr": 8, + "disable_fwd": 0, + "flood_advert_interval": 0, + "flood_max": 8, + "flood_max_advert": 3, + "flood_max_unscoped": 0, + "freq_mhz": 869.432, + "home": "#cz-ulk", + "name": "mast-three", + "path_hash_mode": 1, + "powersaving": 1, + "regions": [ + { + "name": "cs", + "parent": "*" + }, + { + "name": "cz-sudety", + "parent": "cz" + }, + { + "name": "cz-ulk", + "parent": "#cz" + }, + { + "name": "#cz" + } + ], + "rx_boosted_gain": 1, + "rxps_enabled": 0, + "rxps_level": 0, + "rxps_preamble": 0, + "rxps_rx_us": 0, + "rxps_sleep_us": 0, + "sf": 8, + "tx_dbm": 22 + } + }, + { + "canonical": "02000d44380000f4240808f70878312dc48d65c5a1780c404040020100000100001d4c00007530021001000202637a000106637a2d6b766b02637a00", + "crc16": "DC8C", "name": "rxps_node", "prefs": { "advert_interval": 120, @@ -1376,9 +1439,20 @@ "flood_max_advert": 64, "flood_max_unscoped": 64, "freq_mhz": 869.432, + "home": "*", "name": "x1-\u010de\u0161", "path_hash_mode": 2, "powersaving": 0, + "regions": [ + { + "name": "cz" + }, + { + "flood": false, + "name": "cz-kvk", + "parent": "cz" + } + ], "rx_boosted_gain": 0, "rxps_enabled": 1, "rxps_level": 2,