From 2b8b6e61b748eaea3aee1d6ec39987148814347a Mon Sep 17 00:00:00 2001 From: Jason Huebert Date: Fri, 16 Oct 2026 14:35:26 -0500 Subject: [PATCH] feat: add mesh clock sync --- MESHCLOCK.md | 120 ++++++ examples/simple_repeater/BuildEpoch.h | 54 +++ examples/simple_repeater/MeshClockSync.cpp | 267 +++++++++++++ examples/simple_repeater/MeshClockSync.h | 114 ++++++ .../simple_repeater/MeshClockSyncConfig.h | 53 +++ examples/simple_repeater/MyMesh.cpp | 17 + examples/simple_repeater/MyMesh.h | 2 + platformio.ini | 30 +- test/test_mesh_clock/test_mesh_clock.cpp | 356 ++++++++++++++++++ 9 files changed, 1011 insertions(+), 2 deletions(-) create mode 100644 MESHCLOCK.md create mode 100644 examples/simple_repeater/BuildEpoch.h create mode 100644 examples/simple_repeater/MeshClockSync.cpp create mode 100644 examples/simple_repeater/MeshClockSync.h create mode 100644 examples/simple_repeater/MeshClockSyncConfig.h create mode 100644 test/test_mesh_clock/test_mesh_clock.cpp diff --git a/MESHCLOCK.md b/MESHCLOCK.md new file mode 100644 index 00000000..a9869b51 --- /dev/null +++ b/MESHCLOCK.md @@ -0,0 +1,120 @@ +# Mesh Clock Sync — User Guide + +Give a repeater a plausible UTC from the adverts it already hears, so features +that need a clock — most importantly fleet `!at` scheduling — work on a node with +no GPS, no NTP and no battery-backed RTC. + +**Off by default.** Enabling it changes nothing else; disabling it changes +nothing else either. + +--- + +## Why + +A repeater with no clock source starts its RTC at a fallback date. Anything that +compares times is then wrong, and the fleet feature refuses `!at` scripts because +it cannot trust the node's clock (`FLEET_AT_CLOCK_FLOOR`). If you already have +GPS, NTP, or set the clock with the `time` command, you do not need this. + +## Behaviour + +Every advert carries a signed Unix-epoch timestamp from its sender. When mesh +clock sync is **on**, each distinct source contributes **one vote** per batch. +When the batch fills, the repeater takes the **median** of the sources' predicted +"now" and counts how many sources agree with it: + +- **too few agree** — nothing happens; the batch is dropped and a new one starts. +- **the median is close to the node's own clock** (within 60 s) — nothing happens; + the node is already in sync. +- **enough sources agree and the clock differs** — the RTC is stepped **once** to + the median, and a new batch starts. + +The median is deliberately robust: a minority of sources with a wrong clock +cannot drag the result. Agreement (an inlier count) answers "is there a cluster?" +directly; a standard deviation would be inflated by any single extreme value. + +A sample's age does not matter. Because the node's clock advances at roughly real +rate even while wrong, every sample predicts the same "now", so a batch may be +collected over hours and its samples still cluster within seconds. + +## When not to use it + +- You have a real clock source (`time`, GPS, NTP). Mesh clock sync does not + detect or defer to one; leave it off. +- **Public adverts are not a root of trust.** N distinct fingerprints are N keys, + not N independent operators. The quorum filters broken clocks, nothing more. On + a mesh where anyone can inject keys, this is not a security boundary; treat the + result as "plausible", not "authoritative". +- A dense, long-lived mesh may hold stale signed adverts that happen to agree and + look like consensus. The build-date floor and the batch size bound the worst + case; do not enable this where a wrong clock has serious consequences. + +## CLI reference + +| Command | Effect | +|---|---| +| `clock mesh` | Status: `off`, or `on samples=/ last=` | +| `clock mesh on` | Enable | +| `clock mesh off` | Disable | + +The status `last=` field is one of: + +| Value | Meaning | +|---|---| +| `idle` | no batch has decided yet | +| `set(+N s)` / `set(-N s)` | clock stepped by the median | +| `in-sync(N s)` | median was close to the node clock; nothing changed | +| `no-consensus` | not enough sources agreed; batch dropped | + +`last=` is status only — it is **not** persisted, so a reboot reports `idle`. + +### Examples + +``` +> clock mesh +off + +> clock mesh on +OK - mesh clock sync on + +> clock mesh +on samples=12/33 last=idle + +# later, once a batch of 33 distinct sources has agreed +> clock mesh +on samples=0/33 last=set(+31536000s) +``` + +## Persistence + +Only the enabled flag persists, in **`/meshclock`** (4 bytes, CRC-checked). The +batch, the last result and its delta are RAM-only: a reboot always starts a fresh, +empty batch. A `clock mesh` command is written to flash about **3 seconds** later, +staged the same way as the other configs (scratch file, read back and checked, +previous config kept as a backup, then swapped in). + +## Defaults + +| Setting | Default | Meaning | +|---|---|---| +| `MESHCLOCK_SLOTS` | 33 | distinct sources held per batch (= the quorum size) | +| `MESHCLOCK_MIN_AGREE` | 22 | agreeing sources required to step the clock | +| `MESHCLOCK_TOLERANCE_SECS` | 60 | how close a source must be to the median to agree | +| `MESHCLOCK_MIN_DIFF_SECS` | 60 | below this difference the clock is left alone | + +Sparse meshes may take a long time to hear 33 distinct sources; the feature then +simply never acts, which is the safe failure mode. Sites can override +`MESHCLOCK_SLOTS` and `MESHCLOCK_MIN_AGREE` at build time to shrink the batch and +quorum. The estimator uses the batch's middle value, so an odd capacity is +recommended. + +## Limits + +- The design does not detect an external clock step mid-batch. If something walks + the clock while a batch is filling and enough stale samples are already held, + the batch can commit a clock that is off by the step. Not a concern if mesh + clock sync is the node's only clock source. +- A 4-byte source fingerprint can collide, dropping the second key's vote for one + batch. Rare; accepted to keep RAM tiny. +- Modular (32-bit) arithmetic keeps timestamps correct across 2038/2106; the only + limit is the same ±68-year ambiguity the RTC already has. diff --git a/examples/simple_repeater/BuildEpoch.h b/examples/simple_repeater/BuildEpoch.h new file mode 100644 index 00000000..9c17f681 --- /dev/null +++ b/examples/simple_repeater/BuildEpoch.h @@ -0,0 +1,54 @@ +// BuildEpoch.h — UTC build epoch from __DATE__/__TIME__. +// +// Bakes a firmware build time into the image with no build-system change, so +// it is trivially removable. The parse is `inline` rather than `constexpr` +// because the ESP32/nRF52 toolchains build as C++11, where a constexpr body +// must be a single return statement; the input is a string literal, so the +// optimizer folds it to a constant anyway. It uses the compiler's local time; +// callers treat it as a lower plausibility bound and absorb the up-to-~1 day +// local-vs-UTC difference with their own grace (see +// MESHCLOCK_BUILD_GRACE_SECS), never as an exact comparison. + +#ifndef _BUILD_EPOCH_H +#define _BUILD_EPOCH_H + +#include + +namespace meshclock { + +// Days since 1970-01-01 for a civil date (Howard Hinnant's algorithm). +inline int64_t daysFromCivil(int y, int m, int d) { + y -= m <= 2; + const int64_t era = (y >= 0 ? y : y - 399) / 400; + const unsigned yoe = (unsigned)(y - era * 400); + const unsigned doy = (unsigned)((153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1); + const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + return era * 146097 + (int64_t)doe - 719468; +} + +// __DATE__ month name ("Jan".."Dec") to 1..12. +inline int monthFromName(const char* s) { + return (s[0]=='J' && s[1]=='a') ? 1 : (s[0]=='F') ? 2 : + (s[0]=='M' && s[2]=='r') ? 3 : (s[0]=='A' && s[1]=='p') ? 4 : + (s[0]=='M') ? 5 : (s[0]=='J' && s[2]=='n') ? 6 : + (s[0]=='J') ? 7 : (s[0]=='A') ? 8 : (s[0]=='S') ? 9 : + (s[0]=='O') ? 10 : (s[0]=='N') ? 11 : 12; +} + +// __DATE__ = "Mmm DD YYYY" (day space-padded), __TIME__ = "HH:MM:SS". +inline uint32_t buildEpoch() { + const char* d = __DATE__; + const int mon = monthFromName(d); + const int day = (d[4] == ' ') ? (d[5] - '0') + : (d[4] - '0') * 10 + (d[5] - '0'); + const int year = (d[7]-'0')*1000 + (d[8]-'0')*100 + (d[9]-'0')*10 + (d[10]-'0'); + const char* t = __TIME__; + const int hh = (t[0]-'0')*10 + (t[1]-'0'); + const int mm = (t[3]-'0')*10 + (t[4]-'0'); + const int ss = (t[6]-'0')*10 + (t[7]-'0'); + return (uint32_t)(daysFromCivil(year, mon, day) * 86400 + hh*3600 + mm*60 + ss); +} + +} // namespace meshclock + +#endif // _BUILD_EPOCH_H diff --git a/examples/simple_repeater/MeshClockSync.cpp b/examples/simple_repeater/MeshClockSync.cpp new file mode 100644 index 00000000..76194751 --- /dev/null +++ b/examples/simple_repeater/MeshClockSync.cpp @@ -0,0 +1,267 @@ +// MeshClockSync.cpp — see MeshClockSync.h for the design overview and +// MESHCLOCK.md for the user manual. + +#include "MeshClockSync.h" +#include "BuildEpoch.h" +#include "CliUtil.h" + +#include + +// Fingerprint: 4 bytes sampled from the advert pubkey at fixed offsets clear of +// the vanity zones at both ends (the same idea AdvertRateLimiter uses). This is +// deliberately a private copy, not shared with AdvertRateLimiter: keeping clock +// sync self-contained is what makes it deletable if upstream adds its own clock +// feature. A 4-byte collision just drops the second key's vote for one batch +// (rare; accepted rather than widening the fingerprint and spending RAM). +static const uint8_t MESHCLOCK_KEY_OFFSETS[4] = { 8, 14, 20, 26 }; + +// The plausibility floor: an advert timestamped before the firmware existed is +// not trusted. buildEpoch() parses the compiler's local __DATE__/__TIME__, so a +// grace absorbs the local-vs-UTC difference; a malformed/absent __DATE__ would +// yield a tiny value, so fall back to a hardcoded date rather than admitting +// everything by accident. 2025-01-01 UTC matches the fleet feature's floor. +uint32_t MeshClockSync::buildFloor() { + uint32_t e = meshclock::buildEpoch(); + if (e < 1500000000UL) e = 1735689600UL; + return e > MESHCLOCK_BUILD_GRACE_SECS ? e - MESHCLOCK_BUILD_GRACE_SECS : e; +} + +// The state a fresh node starts in, and the baseline load() resets to before it +// reads the file: disabled, empty batch, no decision yet. One definition, so +// construction and reload cannot drift apart. +void MeshClockSync::resetToDefaults() { + memset(samples, 0, sizeof(samples)); + count = 0; + enabled = false; + last_result = IDLE; + last_delta = 0; +} + +MeshClockSync::MeshClockSync() { + reset(); +} + +void MeshClockSync::reset() { + resetToDefaults(); + save_flag.reset(); // a reset supersedes any edit still waiting to be written +} + +void MeshClockSync::begin(FILESYSTEM* fs) { + load(fs); +} + +void MeshClockSync::loop(FILESYSTEM* fs) { + if (save_flag.due()) save(fs); +} + +void MeshClockSync::setClockFn(void (*fn)(void* ctx, uint32_t epoch), void* ctx) { + set_fn = fn; + set_ctx = ctx; +} + +void MeshClockSync::setEnabled(bool on) { + if (enabled == on) return; // no-op: no dirty write + enabled = on; + clear(); // a stale batch must not survive an off->on toggle + markDirty(); +} + +// ---------------------------------------------------------------- collection + +bool MeshClockSync::hasSource(const uint8_t* fp) const { + // linear scan: count <= MESHCLOCK_SLOTS, so it is cheaper than any index and + // needs no extra state + for (int i = 0; i < count; i++) { + if (memcmp(samples[i].fp, fp, 4) == 0) return true; + } + return false; +} + +void MeshClockSync::onAdvert(uint32_t advert_ts, const uint8_t* pub_key, uint32_t local_now) { + if (!enabled) return; + + // signed comparison of a modular difference: correct across the 2038 wrap + if ((int32_t)(advert_ts - buildFloor()) < 0) return; + + uint8_t fp[4]; + for (int i = 0; i < 4; i++) fp[i] = pub_key[MESHCLOCK_KEY_OFFSETS[i]]; + if (hasSource(fp)) return; // one vote per source per batch + + memcpy(samples[count].fp, fp, sizeof(fp)); + samples[count].offset = advert_ts - local_now; // uint32 wrap + count++; + + if (count == MESHCLOCK_SLOTS) evaluate(local_now); +} + +// ---------------------------------------------------------------- decision + +void MeshClockSync::evaluate(uint32_t local_now) { + // Reconstruct each source's predicted current UTC: local_now + offset. Because + // the local clock advances at ~real rate even while wrong, local_now now minus + // local_now at receipt equals the real elapsed time, so every sample predicts + // the same "now" — samples taken hours apart still cluster. That is why no + // per-sample uptime and no collection window are needed. + uint32_t cand[MESHCLOCK_SLOTS]; + for (int i = 0; i < count; i++) cand[i] = local_now + samples[i].offset; + + // Median, not mean: robust to a minority of wrong clocks and needing no + // floating point. A mean would be dominated by the most frequent advertiser. + uint32_t sorted[MESHCLOCK_SLOTS]; + memcpy(sorted, cand, count * sizeof(uint32_t)); + for (int i = 1; i < count; i++) { // small insertion sort + uint32_t v = sorted[i]; + int j = i - 1; + while (j >= 0 && sorted[j] > v) { sorted[j + 1] = sorted[j]; j--; } + sorted[j + 1] = v; + } + const uint32_t median = sorted[count / 2]; // odd batch: the single middle value + + // defensive floor check on the result + if ((int32_t)(median - buildFloor()) < 0) { + last_result = NO_CONSENSUS; + clear(); + return; + } + + // Inlier count, not standard deviation: one extreme value inflates a standard + // deviation even when the rest agree; a count answers "is there a cluster?". + int inliers = 0; + for (int i = 0; i < count; i++) { + const uint32_t d = cand[i] > median ? cand[i] - median : median - cand[i]; + if (d <= MESHCLOCK_TOLERANCE_SECS) inliers++; + } + if (inliers < MESHCLOCK_MIN_AGREE) { + last_result = NO_CONSENSUS; + clear(); + return; + } + + // deadband vs the node's own clock + const uint32_t d = median > local_now ? median - local_now : local_now - median; + last_delta = (int32_t)(median - local_now); // exact within ±68 years + if (d < MESHCLOCK_MIN_DIFF_SECS) { + last_result = IN_SYNC; + clear(); + return; + } + + if (set_fn) set_fn(set_ctx, median); + last_result = SET_CLOCK; + clear(); +} + +// ---------------------------------------------------------------- persistence + +// Format-level validity of a record: version, an enabled flag of 0/1, and the +// CRC. Shared by the file validator, the staged-save writeback check and load(), +// so no route can admit a record another refuses. +static bool clockRecordValid(const MeshClockCfg& rec) { + if (rec.version != MESHCLOCK_CFG_VERSION) return false; + if (rec.enabled > 1) return false; + return rec.crc == crc16_ccitt((const uint8_t*)&rec, offsetof(MeshClockCfg, crc)); +} + +static bool clockWriteFile(File& f, void* ctx) { + const MeshClockSync& c = *(const MeshClockSync*)ctx; + MeshClockCfg rec; + rec.version = MESHCLOCK_CFG_VERSION; + rec.enabled = c.isEnabled() ? 1 : 0; + rec.crc = crc16_ccitt((const uint8_t*)&rec, offsetof(MeshClockCfg, crc)); + return f.write((const uint8_t*)&rec, sizeof(rec)) == sizeof(rec); +} + +static bool clockValidateFile(File& f, void* ctx) { + (void)ctx; + MeshClockCfg rec; + if (f.read((uint8_t*)&rec, sizeof(rec)) != sizeof(rec)) return false; + uint8_t extra; + if (f.read(&extra, 1) != 0) return false; // record must be exactly sizeof(rec) + return clockRecordValid(rec); +} + +void MeshClockSync::save(FILESYSTEM* fs) { + // Staged save: scratch file, read back, keep the previous good file as a + // backup, then promote — the same transaction every persisted config here uses. + bool ok = saveStaged(fs, MESHCLOCK_CFG_FILE, clockWriteFile, this, + clockValidateFile, NULL, clockValidateFile, NULL); + if (ok) save_flag.clear(); + else save_flag.retryLater(); +} + +void MeshClockSync::load(FILESYSTEM* fs) { + reset(); // the file decides everything below; nothing survives from before + + char path[64]; + PersistLoadSource src = chooseConfigToLoad(fs, MESHCLOCK_CFG_FILE, clockValidateFile, NULL, + path, sizeof(path)); + if (src == PERSIST_LOAD_NONE) return; // nothing usable: keep the defaults + File file = fsOpenRead(fs, path); + if (!file) return; + + MeshClockCfg rec; + const bool ok = file.read((uint8_t*)&rec, sizeof(rec)) == sizeof(rec); + file.close(); + if (!ok) return; + if (!clockRecordValid(rec)) return; // chooseConfigToLoad validated it; re-verify anyway + + enabled = (rec.enabled == 1); + + // Loaded from the backup, so put a good canonical file back at the next + // opportunity; the backup stays valid meanwhile. + if (src == PERSIST_LOAD_RECOVERED) markDirty(); +} + +// ---------------------------------------------------------------- CLI + +#define MESHCLOCK_USAGE "Err - clock mesh takes on|off" + +static void clockStatus(MeshClockSync& c, char* reply) { + if (!c.isEnabled()) { + strcpy(reply, "off"); + return; + } + char* out = reply; + int remain = CLI_REPLY_MAX; + radd(&out, &remain, "on samples=%d/%d last=", c.getSampleCount(), MESHCLOCK_SLOTS); + switch (c.getLastResult()) { + case MeshClockSync::SET_CLOCK: + radd(&out, &remain, "set(%+lds)", (long)c.getLastDeltaSecs()); + break; + case MeshClockSync::IN_SYNC: { + long d = (long)c.getLastDeltaSecs(); + if (d < 0) d = -d; + radd(&out, &remain, "in-sync(%lds)", d); + break; + } + case MeshClockSync::NO_CONSENSUS: + radd(&out, &remain, "no-consensus"); + break; + default: + radd(&out, &remain, "idle"); + break; + } +} + +void meshClockCLI(MeshClockSync& clock, const char* command, char* reply) { + // An oversized command is refused whole rather than acted on as a prefix. + char buf[MAX_PACKET_PAYLOAD + 1]; + if (!cliCopyCommand(buf, sizeof(buf), command)) { strcpy(reply, "Err - command too long"); return; } + char* p = buf; + char* cmd = nextToken(&p); + + if (cmd == NULL) { + if (!cliNoExtra(p, reply, MESHCLOCK_USAGE)) return; + clockStatus(clock, reply); + } else if (strcmp(cmd, "on") == 0) { + if (!cliNoExtra(p, reply, MESHCLOCK_USAGE)) return; + clock.setEnabled(true); + strcpy(reply, "OK - mesh clock sync on"); + } else if (strcmp(cmd, "off") == 0) { + if (!cliNoExtra(p, reply, MESHCLOCK_USAGE)) return; + clock.setEnabled(false); + strcpy(reply, "OK - mesh clock sync off"); + } else { + strcpy(reply, MESHCLOCK_USAGE); + } +} diff --git a/examples/simple_repeater/MeshClockSync.h b/examples/simple_repeater/MeshClockSync.h new file mode 100644 index 00000000..f2f6b197 --- /dev/null +++ b/examples/simple_repeater/MeshClockSync.h @@ -0,0 +1,114 @@ +// MeshClockSync.h — mesh clock sync for the simple_repeater firmware: estimate +// UTC from the signed adverts the repeater already hears, so features that need +// a plausible clock (notably the fleet feature's !at scheduling) work on a node +// with no GPS, no NTP and no battery-backed RTC. Personal fork feature; all +// fork-owned code lives in this file pair plus minimal hook lines in +// MyMesh.h/MyMesh.cpp (same footprint as the packet filter). No changes to +// MeshCore core sources. See MESHCLOCK.md for the user manual. +// +// Off by default. When enabled, each distinct source contributes one vote per +// batch (a 4-byte fingerprint of its advert key); when the batch fills, the +// batch's median predicted "now" is taken, and if enough sources agree it steps +// the RTC once and clears. The batch, the last result and its delta are +// RAM-only: a reboot starts an empty batch. Only the enabled flag persists, in +// /meshclock. The feature shares no state with AdvertRateLimiter or the filter, +// so it can be deleted cleanly if upstream ever adds its own clock feature. +// +// CLI: "clock mesh on|off" and a bare "clock mesh" status, handled by +// meshClockCLI() (see MeshClockSync.cpp). + +#ifndef _MESH_CLOCK_SYNC_H +#define _MESH_CLOCK_SYNC_H + +#include +#include +#include // FILESYSTEM typedef +#include "MeshClockSyncConfig.h" +#include "PersistUtil.h" + +// One source's vote: the fingerprint sampled from its advert key, and the +// modular difference between its signed advert timestamp and this node's clock +// at receipt. The offset is unsigned on purpose — modular arithmetic re-adds it +// with no sign handling, and only the ±2^31 (~68 year) ambiguity inherent to a +// 32-bit epoch remains, the same limit the RTC already has. +struct MeshClockSample { + uint8_t fp[4]; // fingerprint bytes sampled from the advert public key + uint32_t offset; // advert_timestamp - local_now_at_receipt (wraps) +}; +static_assert(sizeof(MeshClockSample) == 8, "clock sample must stay 8 bytes"); + +// Persisted /meshclock record: the enabled flag plus a CRC-16 over it. A torn +// write of exactly the right length is otherwise undetectable on a record this +// small, and the CRC rides v1 from day one (no older format to stay compatible +// with). +struct MeshClockCfg { + uint8_t version; // MESHCLOCK_CFG_VERSION + uint8_t enabled; // 0/1 + uint16_t crc; // crc16_ccitt over the version + enabled bytes +}; +static_assert(sizeof(MeshClockCfg) == 4, "clock config must stay 4 bytes"); + +class MeshClockSync { +public: + enum Result { IDLE = 0, SET_CLOCK, IN_SYNC, NO_CONSENSUS }; + + MeshClockSync(); + + // fs = where the enabled flag is persisted + void begin(FILESYSTEM* fs); // load persisted config + void loop(FILESYSTEM* fs); // lazy dirty-flag save + + // Injected device service, so the unit is host-testable without MyMesh: called + // with a chosen UTC epoch once a batch agrees. Wiring, not state. + void setClockFn(void (*fn)(void* ctx, uint32_t epoch), void* ctx); + + bool isEnabled() const { return enabled; } + void setEnabled(bool on); // persists; clears the batch on change + + // Feed one signature-verified advert (the core verifies the signature before + // MyMesh::onAdvertRecv). advert_ts is the signed timestamp, pub_key the + // PUB_KEY_SIZE origin key, local_now this node's RTC now. + void onAdvert(uint32_t advert_ts, const uint8_t* pub_key, uint32_t local_now); + + // Back to a freshly constructed sync (disabled, empty batch), for tests. + void reset(); + + // --- status for the CLI --- + int getSampleCount() const { return count; } + Result getLastResult() const { return last_result; } + int32_t getLastDeltaSecs() const { return last_delta; } // signed for display + + // Lower plausibility bound for an advert timestamp, derived from the build + // epoch. Exposed for a boundary test. + static uint32_t buildFloor(); + +private: + MeshClockSample samples[MESHCLOCK_SLOTS]; + int count; + bool enabled; + Result last_result; + int32_t last_delta; + LazySave save_flag; // needs save, written back by loop() + + // device service (see setClockFn); NULL = unset. Wiring, not state: it has an + // in-class initializer and reset() must never touch it. + void (*set_fn)(void*, uint32_t) = NULL; + void* set_ctx = NULL; + + // state of a fresh node, and the baseline load() resets to before it reads + void resetToDefaults(); + bool hasSource(const uint8_t* fp) const; + void clear() { count = 0; } + void evaluate(uint32_t local_now); + + // persistence + void load(FILESYSTEM* fs); + void save(FILESYSTEM* fs); + void markDirty() { save_flag.markDirty(); } +}; + +// CLI command handler: invoke with the command after "clock mesh" (prefix +// removed). Replies must fit the 160-byte CLI reply buffer. +void meshClockCLI(MeshClockSync& clock, const char* command, char* reply); + +#endif // _MESH_CLOCK_SYNC_H diff --git a/examples/simple_repeater/MeshClockSyncConfig.h b/examples/simple_repeater/MeshClockSyncConfig.h new file mode 100644 index 00000000..cbbd732a --- /dev/null +++ b/examples/simple_repeater/MeshClockSyncConfig.h @@ -0,0 +1,53 @@ +// MeshClockSyncConfig.h — build-time tunables for mesh clock sync +// (MeshClockSync.h/.cpp). All values have an #ifndef default; override via +// build_flags (e.g. in platformio.local.ini: -DMESHCLOCK_SLOTS=15) or by +// editing the defaults below. See MESHCLOCK.md for the user manual. + +#ifndef _MESH_CLOCK_SYNC_CONFIG_H +#define _MESH_CLOCK_SYNC_CONFIG_H + +// distinct sources held per batch. This is also the quorum size: the batch +// fills, decides once, then clears, so there is no separate time window or +// second threshold. 33 is odd, so the median is the single middle value; a site +// with a sparser mesh can shrink both this and the quorum below. +#ifndef MESHCLOCK_SLOTS + #define MESHCLOCK_SLOTS 33 +#endif + +// a candidate counts as agreeing with the median when it is within this many +// seconds of it +#ifndef MESHCLOCK_TOLERANCE_SECS + #define MESHCLOCK_TOLERANCE_SECS 60 +#endif + +// agreeing sources required before the clock is stepped: two thirds of the +// default batch. Sites overriding MESHCLOCK_SLOTS should override this to keep +// their desired quorum fraction. +#ifndef MESHCLOCK_MIN_AGREE + #define MESHCLOCK_MIN_AGREE 22 +#endif + +// deadband: a median closer than this to the node's own clock is "close +// enough", so the RTC is left alone and the batch reports in-sync +#ifndef MESHCLOCK_MIN_DIFF_SECS + #define MESHCLOCK_MIN_DIFF_SECS 60 +#endif + +// The build epoch is a plausibility floor only (rejects adverts timestamped +// before the firmware could have existed). It is parsed from the compiler's +// local __DATE__/__TIME__ with no build-system change, so this grace absorbs +// the up-to-~1 day local-vs-UTC difference and the date/time granularity. +#ifndef MESHCLOCK_BUILD_GRACE_SECS + #define MESHCLOCK_BUILD_GRACE_SECS 86400UL +#endif + +// persisted enabled flag (see MeshClockSync.cpp for the record) +#ifndef MESHCLOCK_CFG_FILE + #define MESHCLOCK_CFG_FILE "/meshclock" +#endif +#define MESHCLOCK_CFG_VERSION 1 + +static_assert(MESHCLOCK_MIN_AGREE >= 2 && MESHCLOCK_MIN_AGREE <= MESHCLOCK_SLOTS, + "MESHCLOCK_MIN_AGREE must be within the batch"); + +#endif // _MESH_CLOCK_SYNC_CONFIG_H diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 35845e76..624484ca 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -698,6 +698,9 @@ void MyMesh::onAdvertRecv(mesh::Packet *packet, const mesh::Identity &id, uint32 const uint8_t *app_data, size_t app_data_len) { mesh::Mesh::onAdvertRecv(packet, id, timestamp, app_data, app_data_len); // chain to super impl + // mesh clock sync: one vote per signature-verified advert source + meshClock.onAdvert(timestamp, id.pub_key, getRTCClock()->getCurrentTime()); + // if this a zero hop advert (and not via 'Share'), add it to neighbours if (packet->getPathHashCount() == 0 && !isShare(packet)) { AdvertDataParser parser(app_data, app_data_len); @@ -995,6 +998,10 @@ static uint32_t fleetClock(void* ctx) { return ((MyMesh*)ctx)->getRTCClock()->getCurrentTime(); } +static void meshClockSet(void* ctx, uint32_t epoch) { + ((MyMesh*)ctx)->getRTCClock()->setCurrentTime(epoch); +} + static uint32_t fleetJitter(void* ctx, uint32_t window) { return ((MyMesh*)ctx)->getRNG()->nextInt(0, window); } @@ -1041,6 +1048,8 @@ void MyMesh::begin(FILESYSTEM *fs) { fleet.setJitter(fleetJitter, this); fleet.setSender(fleetReplySend, this); fleet.begin(fs); + meshClock.setClockFn(meshClockSet, this); + meshClock.begin(fs); // TODO: key_store.begin(); region_map.load(_fs); @@ -1386,6 +1395,11 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply const char* sub = command + 5; while (*sub == ' ') sub++; fleetCLI(fleet, sub, reply); + } else if (memcmp(command, "clock mesh", 10) == 0 && (command[10] == 0 || command[10] == ' ')) { + // before the common CLI's bare "clock" prefix match, which would swallow it + const char* sub = command + 10; + while (*sub == ' ') sub++; + meshClockCLI(meshClock, sub, reply); } else{ _cli.handleCommand(sender_timestamp, command, reply); // common CLI commands } @@ -1450,6 +1464,9 @@ void MyMesh::loop() { // lazy dirty-flag save for the packet filter config filter.loop(_fs); + // lazy dirty-flag save for the mesh clock sync config + meshClock.loop(_fs); + // fleet config save + script drain (one per pass, after mesh::Mesh::loop() // and outside the receive bracket that produced it — never while the filter // is evaluating a packet; handleCommand(0, ...) gives a script line the same diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 668a4028..c764862a 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -39,6 +39,7 @@ #include "PacketFilter.h" #include "BatteryGate.h" #include "FleetManager.h" +#include "MeshClockSync.h" #ifdef WITH_BRIDGE extern AbstractBridge* bridge; @@ -102,6 +103,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { FilterRules filter; BatteryGate battGate; FleetManager fleet; + MeshClockSync meshClock; uint32_t pending_discover_tag; unsigned long pending_discover_until; bool region_load_active; diff --git a/platformio.ini b/platformio.ini index e475c5d5..684f67c4 100644 --- a/platformio.ini +++ b/platformio.ini @@ -175,6 +175,7 @@ test_ignore = test_packet_filter test_battery_gate test_fleet + test_mesh_clock build_src_filter = -<*> +<../src/Utils.cpp> @@ -274,10 +275,29 @@ build_src_filter = lib_deps = google/googletest @ 1.17.0 -; Sanitizer builds of the two native feature suites: same source selection, +; Native tests for mesh clock sync (fork-owned MeshClockSync*). Reuses the +; packet-filter env's NativeShim.h for the Arduino FILESYSTEM/File stand-ins +; and the mock millis()/g_mock_millis. +[env:native_mesh_clock] +platform = native +test_framework = googletest +build_flags = -std=c++17 + -I src + -I test/mocks + -I examples/simple_repeater + -include test/test_packet_filter/NativeShim.h +test_build_src = yes +test_filter = test_mesh_clock +build_src_filter = + -<*> + +<../examples/simple_repeater/MeshClockSync.cpp> +lib_deps = + google/googletest @ 1.17.0 + +; Sanitizer builds of the native feature suites: same source selection, ; include paths, force-included NativeShim and GTEST_HAS_POSIX_RE=0 as the ; ordinary envs, plus ASan + UBSan. Separate env names so the ordinary feature -; objects stay cached and a sanitizer run never replaces them. Both must report +; objects stay cached and a sanitizer run never replaces them. Each must report ; zero diagnostics — an assertion-only pass does not prove absence of UB ; (see the review's R16: a zero-length read, a null member call and an ; oversized fixture all passed assertions before being caught here). @@ -298,3 +318,9 @@ extends = env:native_fleet build_flags = ${env:native_fleet.build_flags} -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer + +[env:native_mesh_clock_san] +extends = env:native_mesh_clock +build_flags = + ${env:native_mesh_clock.build_flags} + -g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer diff --git a/test/test_mesh_clock/test_mesh_clock.cpp b/test/test_mesh_clock/test_mesh_clock.cpp new file mode 100644 index 00000000..4bc231c0 --- /dev/null +++ b/test/test_mesh_clock/test_mesh_clock.cpp @@ -0,0 +1,356 @@ +// Native tests for mesh clock sync (MeshClockSync): batch collection, the +// median/quorum decision, wrap safety, the enabled-flag persistence and the CLI. +// Reach the feature only through its public API exactly as MyMesh would. + +#include + +#include + +#include // g_mock_millis (NativeShim.h is force-included) +#include + +#include "MeshClockSync.h" +#include "BuildEpoch.h" +#include "CliUtil.h" + +// Two plausible-but-wrong clocks: the node's own is far behind, and the true +// time carried by adverts is well above any build floor. +static const uint32_t TRUE_NOW = 1800000000UL; // 2027-01-15 UTC +static const uint32_t WRONG_NOW = 1700000000UL; // 2023-11-14 UTC + +// ------------------------------------------------------------------ helpers + +// A distinct advert key per source id: the fingerprint samples pubkey bytes +// 8/14/20/26, so encoding the id there keeps sources distinct. +static void makeKey(uint8_t* key, int id) { + memset(key, 0, PUB_KEY_SIZE); + key[8] = (uint8_t)id; + key[14] = (uint8_t)(id + 1); + key[20] = (uint8_t)(id + 2); + key[26] = (uint8_t)(id + 3); +} + +static void feed(MeshClockSync& c, int id, uint32_t advert_ts, uint32_t local_now) { + uint8_t key[PUB_KEY_SIZE]; + makeKey(key, id); + c.onAdvert(advert_ts, key, local_now); +} + +// ------------------------------------------------------------------ fixture + +struct ClockTest : public ::testing::Test { + NativeFS fs; + MeshClockSync clock; + + uint32_t set_calls = 0; + uint32_t set_epoch = 0; + + static void onSet(void* ctx, uint32_t epoch) { + ClockTest* self = (ClockTest*)ctx; + self->set_calls++; + self->set_epoch = epoch; + } + + void SetUp() override { + g_mock_millis = 1000; + clock.setClockFn(onSet, this); + } + void TearDown() override { g_mock_millis = 0; } + + // flush a dirty save: edits mark the config dirty, loop() writes it once + // LAZY_SAVE_DELAY_MS has passed + void flushSave() { + g_mock_millis += LAZY_SAVE_DELAY_MS + 1; + clock.loop(&fs); + } +}; + +// ------------------------------------------------------------------ defaults + +TEST_F(ClockTest, DefaultsAreDisabledAndEmpty) { + EXPECT_FALSE(clock.isEnabled()); + EXPECT_EQ(clock.getSampleCount(), 0); + EXPECT_EQ(clock.getLastResult(), MeshClockSync::IDLE); + + clock.begin(&fs); // no config file: defaults survive + EXPECT_FALSE(clock.isEnabled()); + EXPECT_EQ(clock.getSampleCount(), 0); + EXPECT_EQ(clock.getLastResult(), MeshClockSync::IDLE); +} + +// ------------------------------------------------------------ build epoch + +TEST(ClockSyncBuildEpoch, ParsesAReasonableDate) { + const uint32_t e = meshclock::buildEpoch(); + EXPECT_GT(e, 1735689600UL); // after 2025-01-01 + EXPECT_LT(e, 4102444800UL); // before 2100-01-01 + EXPECT_LE(MeshClockSync::buildFloor(), e); +} + +// ------------------------------------------------------------ persistence + +TEST_F(ClockTest, EnableRoundTrips) { + clock.setEnabled(true); + EXPECT_TRUE(clock.isEnabled()); + flushSave(); + + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_TRUE(loaded.isEnabled()); + + loaded.setEnabled(false); + g_mock_millis += LAZY_SAVE_DELAY_MS + 1; + loaded.loop(&fs); + + MeshClockSync reloaded; + reloaded.begin(&fs); + EXPECT_FALSE(reloaded.isEnabled()); +} + +TEST_F(ClockTest, SameValueSetIsNoOp) { + clock.setEnabled(false); // already disabled: no dirty write + flushSave(); + EXPECT_FALSE(fs.exists(MESHCLOCK_CFG_FILE)); +} + +TEST_F(ClockTest, SaveOnlyWhenDirtyAndDue) { + clock.setEnabled(true); + clock.loop(&fs); // dirty but not due yet + EXPECT_FALSE(fs.exists(MESHCLOCK_CFG_FILE)); + flushSave(); + EXPECT_TRUE(fs.exists(MESHCLOCK_CFG_FILE)); +} + +TEST_F(ClockTest, CorruptedCrcRejected) { + clock.setEnabled(true); + flushSave(); + fs.files[MESHCLOCK_CFG_FILE][3] ^= 0x01; // CRC high byte + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_FALSE(loaded.isEnabled()); +} + +TEST_F(ClockTest, BadVersionRejected) { + clock.setEnabled(true); + flushSave(); + fs.files[MESHCLOCK_CFG_FILE][0] = 99; + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_FALSE(loaded.isEnabled()); +} + +TEST_F(ClockTest, BadEnabledFlagRejected) { + clock.setEnabled(true); + flushSave(); + // patch the flag and recompute the CRC, so the enabled-range check is what + // rejects the record rather than the checksum + std::vector& rec = fs.files[MESHCLOCK_CFG_FILE]; + rec[1] = 2; + uint16_t crc = crc16_ccitt(rec.data(), 2); + memcpy(&rec[2], &crc, 2); + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_FALSE(loaded.isEnabled()); +} + +TEST_F(ClockTest, TruncatedFileRejected) { + clock.setEnabled(true); + flushSave(); + fs.files[MESHCLOCK_CFG_FILE].resize(2); // short of the 4-byte record + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_FALSE(loaded.isEnabled()); +} + +TEST_F(ClockTest, OverlongFileRejected) { + clock.setEnabled(true); + flushSave(); + fs.files[MESHCLOCK_CFG_FILE].push_back(0); // record must be exactly 4 bytes + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_FALSE(loaded.isEnabled()); +} + +TEST_F(ClockTest, BackupRecoveredAndRepaired) { + clock.setEnabled(true); + flushSave(); // canonical: enabled + clock.setEnabled(false); + flushSave(); // canonical: disabled; backup: enabled + + fs.files[MESHCLOCK_CFG_FILE][0] = 99; // corrupt the canonical + MeshClockSync loaded; + loaded.begin(&fs); + EXPECT_TRUE(loaded.isEnabled()); // recovered from the backup + + std::vector before = fs.files[MESHCLOCK_CFG_FILE]; + loaded.loop(&fs); + EXPECT_EQ(fs.files[MESHCLOCK_CFG_FILE], before) << "repair save must wait out the lazy delay"; + g_mock_millis += LAZY_SAVE_DELAY_MS + 1; + loaded.loop(&fs); + ASSERT_NE(fs.files[MESHCLOCK_CFG_FILE], before); + + MeshClockSync reloaded; + reloaded.begin(&fs); + EXPECT_TRUE(reloaded.isEnabled()); +} + +// ------------------------------------------------------------ collection + +TEST_F(ClockTest, RejectsBeforeBuildFloor) { + clock.setEnabled(true); + const uint32_t floor = MeshClockSync::buildFloor(); + + feed(clock, 0, floor - 1, TRUE_NOW); // before the firmware existed + EXPECT_EQ(clock.getSampleCount(), 0); + + feed(clock, 1, 1715770351UL, TRUE_NOW); // 15 May 2024 fallback clock + EXPECT_EQ(clock.getSampleCount(), 0); +} + +TEST_F(ClockTest, TimestampAtFloorAccepted) { + clock.setEnabled(true); + const uint32_t floor = MeshClockSync::buildFloor(); + + feed(clock, 0, floor, TRUE_NOW); + EXPECT_EQ(clock.getSampleCount(), 1); // at the floor is not before it + feed(clock, 1, floor - 1, TRUE_NOW); + EXPECT_EQ(clock.getSampleCount(), 1); // rejected +} + +TEST_F(ClockTest, OneVotePerSource) { + clock.setEnabled(true); + uint8_t key[PUB_KEY_SIZE]; + makeKey(key, 5); + clock.onAdvert(TRUE_NOW, key, WRONG_NOW); + clock.onAdvert(TRUE_NOW + 10, key, WRONG_NOW); // same source: dropped + EXPECT_EQ(clock.getSampleCount(), 1); +} + +TEST_F(ClockTest, DisabledIgnoresAdverts) { + feed(clock, 0, TRUE_NOW, WRONG_NOW); + EXPECT_EQ(clock.getSampleCount(), 0); +} + +// ------------------------------------------------------------ decisions + +TEST_F(ClockTest, FullyAgreeingBatchSetsClock) { + clock.setEnabled(true); + for (int i = 0; i < MESHCLOCK_SLOTS - 1; i++) feed(clock, i, TRUE_NOW, WRONG_NOW); + EXPECT_EQ(clock.getSampleCount(), MESHCLOCK_SLOTS - 1); + EXPECT_EQ(set_calls, 0u); // decides only when the batch fills + + feed(clock, MESHCLOCK_SLOTS - 1, TRUE_NOW, WRONG_NOW); + EXPECT_EQ(set_calls, 1u); + EXPECT_EQ(set_epoch, TRUE_NOW); + EXPECT_EQ(clock.getLastResult(), MeshClockSync::SET_CLOCK); + EXPECT_EQ(clock.getSampleCount(), 0); // batch cleared after the decision +} + +TEST_F(ClockTest, MedianIgnoresMinorityOutliers) { + clock.setEnabled(true); + for (int i = 0; i < MESHCLOCK_SLOTS - 3; i++) feed(clock, i, TRUE_NOW, WRONG_NOW); + for (int i = MESHCLOCK_SLOTS - 3; i < MESHCLOCK_SLOTS; i++) { + feed(clock, i, TRUE_NOW + 10000000UL, WRONG_NOW); // wildly wrong minority + } + EXPECT_EQ(set_calls, 1u); + EXPECT_EQ(set_epoch, TRUE_NOW); // majority value, not dragged to the outliers +} + +TEST_F(ClockTest, QuorumNotMetClears) { + clock.setEnabled(true); + const int outliers = MESHCLOCK_SLOTS - (MESHCLOCK_MIN_AGREE - 1); + for (int i = 0; i < MESHCLOCK_MIN_AGREE - 1; i++) feed(clock, i, TRUE_NOW, WRONG_NOW); + for (int i = 0; i < outliers; i++) { + feed(clock, MESHCLOCK_MIN_AGREE - 1 + i, TRUE_NOW + 5000000UL, WRONG_NOW); + } + EXPECT_EQ(set_calls, 0u); + EXPECT_EQ(clock.getLastResult(), MeshClockSync::NO_CONSENSUS); + EXPECT_EQ(clock.getSampleCount(), 0); +} + +TEST_F(ClockTest, CloseEnoughIsInSync) { + clock.setEnabled(true); + const uint32_t local = TRUE_NOW; + for (int i = 0; i < MESHCLOCK_SLOTS; i++) feed(clock, i, local + 10, local); + EXPECT_EQ(set_calls, 0u); + EXPECT_EQ(clock.getLastResult(), MeshClockSync::IN_SYNC); + EXPECT_EQ(clock.getLastDeltaSecs(), 10); + EXPECT_EQ(clock.getSampleCount(), 0); +} + +TEST_F(ClockTest, NegativeOffsetReconstructsAcrossWrap) { + clock.setEnabled(true); + // within 2^31 of the build floor, so it survives the signed floor check, but + // local + offset still wraps around UINT32_MAX + const uint32_t target = 3800000000UL; // ~2090 UTC + const uint32_t local = target + 500; // local clock ahead, so offsets wrap + for (int i = 0; i < MESHCLOCK_SLOTS; i++) feed(clock, i, target, local); + EXPECT_EQ(set_calls, 1u); + EXPECT_EQ(set_epoch, target); + EXPECT_EQ(clock.getLastDeltaSecs(), -500); +} + +TEST_F(ClockTest, ClockStepMidBatchFailsConsensus) { + clock.setEnabled(true); + const uint32_t l1 = TRUE_NOW; + const uint32_t l2 = l1 + 1000; // external step, larger than the tolerance + + // MIN_AGREE-1 stale samples, then fresh ones: the stale cluster cannot reach + // quorum (see the documented mid-batch-step limitation) + for (int i = 0; i < MESHCLOCK_MIN_AGREE - 1; i++) feed(clock, i, TRUE_NOW, l1); + for (int i = MESHCLOCK_MIN_AGREE - 1; i < MESHCLOCK_SLOTS; i++) feed(clock, i, TRUE_NOW, l2); + + EXPECT_EQ(set_calls, 0u); + EXPECT_EQ(clock.getLastResult(), MeshClockSync::NO_CONSENSUS); + EXPECT_EQ(clock.getSampleCount(), 0); +} + +TEST_F(ClockTest, ResetClearsBatchAndFlag) { + clock.setEnabled(true); + feed(clock, 0, TRUE_NOW, WRONG_NOW); + EXPECT_EQ(clock.getSampleCount(), 1); + clock.reset(); + EXPECT_FALSE(clock.isEnabled()); + EXPECT_EQ(clock.getSampleCount(), 0); + EXPECT_EQ(clock.getLastResult(), MeshClockSync::IDLE); +} + +// ------------------------------------------------------------------ CLI + +TEST_F(ClockTest, CliSurface) { + char reply[CLI_REPLY_MAX]; + + meshClockCLI(clock, "", reply); + EXPECT_STREQ(reply, "off"); + + meshClockCLI(clock, "on", reply); + EXPECT_STREQ(reply, "OK - mesh clock sync on"); + EXPECT_TRUE(clock.isEnabled()); + + meshClockCLI(clock, "", reply); + EXPECT_STREQ(reply, "on samples=0/33 last=idle"); + + meshClockCLI(clock, "bogus", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off"); + + meshClockCLI(clock, "on extra", reply); + EXPECT_STREQ(reply, "Err - clock mesh takes on|off"); + EXPECT_TRUE(clock.isEnabled()); // a refused command changed nothing + + meshClockCLI(clock, "off", reply); + EXPECT_STREQ(reply, "OK - mesh clock sync off"); + EXPECT_FALSE(clock.isEnabled()); +} + +TEST_F(ClockTest, CliStatusShowsLastResult) { + clock.setEnabled(true); + for (int i = 0; i < MESHCLOCK_SLOTS; i++) feed(clock, i, TRUE_NOW, WRONG_NOW); + char reply[CLI_REPLY_MAX]; + meshClockCLI(clock, "", reply); + EXPECT_STREQ(reply, "on samples=0/33 last=set(+100000000s)"); +} + +int main(int argc, char **argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +}