Skip to content

Commit 1872e5b

Browse files
NomDeTomclaudecaveman99
authored
TMM extend to ephemeral 3rd tier store (#11050)
* Harden TMM NodeInfo direct-response: staleness, key hygiene, throttle The NodeInfo direct-response path answered queries on behalf of other nodes from an unauthenticated, never-expiring cache while suppressing the genuine request (STOP). That let a long-gone or forged identity be served as a fresh-looking, authoritative reply indefinitely. Three fixes: - Staleness gate: refuse to spoof a reply for a node not actually heard within ~6h (PSRAM cache via lastObservedMs; NodeDB fallback via sinceLastSeen, which tolerates last_heard==0 when the clock is unset). A stale entry now falls through so the real request propagates instead of being answered for a dead node. - Key hygiene: mirror NodeDB::updateUser() PKI checks when caching overheard NodeInfo - reject a packet advertising our own public key, and pin keys (drop a NodeInfo whose key mismatches an already-known key from NodeDB or from our own cache). Prevents cache poisoning / key substitution via the spoofed-reply path. - Response throttle: at most one spoofed reply per target node per 30s. Direct responses bypass the per-sender rate limiter (they STOP the request first) and the reply target is attacker-controlled, so this bounds airtime exhaustion and reflected floods. Recorded in a new NodeInfoPayloadEntry.lastResponseMs (PSRAM; self-expiring timestamp compare, no sweep needed). Tests: native NodeDB-fallback staleness (stale drops, fresh serves) plus PSRAM-guarded staleness, throttle, and key-mismatch cases. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Add TODO(T1-T9) markers for code-review findings on NodeInfo hardening Comment-only. Tags each site flagged in the review of the direct-response throttle/staleness/key-hygiene change so the follow-ups are visible in-context: T1 throttle black-holes distinct requestors; T2 per-target key doesn't bound aggregate TX; T3 non-PSRAM fallback unthrottled; T4 millis-wrap defeats the staleness gate; T5 redundant second O(n) scan for the throttle stamp; T6 duplicated 32-byte key compares; T7 sinceLastSeen() called twice; T8 two 6h constants can desync; T9 clockMs()==0 collides with the 0 sentinel. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Address code-review cleanups T6, T7, T8 in NodeInfo direct-response T8: derive kNodeInfoMaxServeAgeSecs from kNodeInfoMaxServeAgeMs so the PSRAM and NodeDB-fallback staleness windows cannot desync. T6: collapse the three duplicated 32-byte key compares in cacheNodeInfoPacket (owner-impersonation + NodeDB pin + cache TOFU pin) into one pubKeysEqual() helper, so the compare lives in one place. T7: compute sinceLastSeen(node) once on the fallback staleness path so the tested age and the logged age cannot diverge (it calls getTime() each time). Remaining review items still marked in-code: T1/T2/T3 (throttle design), T4/T9 (millis-wrap + 0-sentinel), T5 (redundant throttle-stamp scan). Native test_traffic_management suite: 48/48 passing. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Throttle the NodeDB fallback direct-response path (T3) The per-target NodeInfo response throttle lived only in the PSRAM NodeInfoPayloadEntry, so non-PSRAM boards - which answer from the NodeDB fallback path - emitted spoofed direct replies with no rate limit at all, leaving the airtime/reflection surface the throttle exists to close. Add a single module-global fallback stamp (nodeInfoFallbackLastResponseMs, 4 bytes, guarded by cacheLock) that throttles the fallback path to one spoofed reply per window across all targets. Coarser than the PSRAM per-target throttle, but the fallback path has no per-node slot to stamp, and a global cap still bounds spoofed transmissions - which is the point. Add a native test exercising the fallback throttle window. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Make NodeInfo staleness/throttle wrap- and sentinel-safe (T4, T9) T9: the millis-based fields that use 0 as a "never" sentinel (lastObservedMs, lastResponseMs, nodeInfoFallbackLastResponseMs) could be stamped with a literal 0 during the one-millisecond clockMs()==0 instant at each ~49.7-day wrap, momentarily colliding with the sentinel and disabling the staleness/throttle gate for that entry. Route all such stamps through a new nowStampMs() that maps 0 -> 1; the 1 ms skew is irrelevant to every window these fields feed. T4: the staleness gate's modular age compare is only unambiguous while true age < 2^32 ms (~49.7 days); an entry that lingered unrefreshed that long could wrap to a small age and read as fresh, defeating the gate. Add a NodeInfo eviction pass to the maintenance sweep that drops entries past the serve window, so an entry is removed long before its age can approach the wrap boundary. This also frees slots holding stale identities. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Stamp PSRAM throttle entry by captured index, not a rescan (T5) The post-send throttle stamp did a second full O(n) scan of the PSRAM NodeInfo array under a fresh lock, even though findNodeInfoEntry() had already located the slot at the top of shouldRespondToNodeInfo(). Capture the slot index during that initial lookup and address the entry directly on the stamp path. Because the cache lock is released between the two accesses, the slot could have been evicted or reused, so re-validate node == p->to under the lock before stamping. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Document accepted per-target throttle tradeoffs (T1, T2) Convert the T1/T2 TODO markers into a NOTE: the per-target PSRAM throttle keying and its lack of an aggregate bound are deliberate design choices, not pending work. A distinct requestor being throttled for one window is harmless on a redundant mesh, and keeping the PSRAM path per-target preserves throughput for legitimate multi-target responders (the fallback path already bounds aggregate via its global stamp). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Track signed-provenance of cached NodeInfo public keys Add keySignerProven to NodeInfoPayloadEntry, set when an observed NODEINFO frame's XEdDSA signature was verified (mp.xeddsa_signed). This distinguishes a trust-on-first-use key from one proven to belong to a signer. The flag is monotonic - once proven it stays proven, and the existing key-pin checks forbid the underlying key from changing - so a later unsigned frame cannot downgrade it. A signature can only be verified against a key we already held, so a first-contact key is always TOFU until a later signed frame upgrades it. Groundwork for using the TMM cache as a last-resort public-key source, where this flag serves as a trust tier. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Draw public keys from the TMM NodeInfo cache as a last resort Add TrafficManagementModule::copyPublicKey() and consult it from NodeDB::copyPublicKey() after the hot (NodeInfoLite) and warm (WarmNodeStore) tiers miss. This extends the pool of peers the node can encrypt to: a key the NodeInfo direct-response cache overheard for a node that has since aged out of both NodeDB tiers can still be used. The getter reports whether the key is signer-proven or trust-on-first-use. NodeDB serves TOFU keys here too - the same first-contact trust NodeDB already applies in updateUser() - so the pool actually expands to new long-tail nodes rather than only re-confirming known keys. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Retain keyed NodeInfo entries as a pubkey pool; trust-tier eviction Now that NodeDB::copyPublicKey() draws keys from the NodeInfo cache, the flat 6 h serve-window eviction would discard useful keys the moment a node stops being servable. Split retention: an entry carrying a 32-byte public key is kept for kNodeInfoKeyRetentionMs (7 d), while a keyless entry still expires at the serve window. Both windows stay well under the ~49.7-day millis wrap, preserving the T4 wrap-safety guarantee. Make LRU victim selection trust-tiered to match: a keyless slot is sacrificed before any keyed one, and a trust-on-first-use key before a signer-proven key; within a tier the oldest loses. Mirrors WarmNodeStore's keyed-first admission so the most valuable keys are the stickiest under memory pressure. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Test signed-provenance flag and copyPublicKey key-pool source PSRAM-gated tests (run on the ESP32 build, alongside the existing NodeInfo PSRAM tests): - copyPublicKey serves a TOFU key learned from an unsigned NodeInfo and reports signerProven=false - a later signature-verified NodeInfo upgrades provenance to signer-proven while the pinned key bytes stay unchanged - copyPublicKey reports a miss for an uncached node Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Inherit signer provenance from NodeDB when caching a re-found node When the TrafficManagement NodeInfo cache re-caches a node, mark its key signer-proven if NodeDB already knows the node as a verified signer for that same key - even if this particular (unicast/unsigned) frame carried no signature. Previously the flag only upgraded on a frame we verified ourselves, so a node we had already proven elsewhere looked TOFU here. Add NodeDB::isVerifiedSignerForKey(), which checks both tiers - the hot store's signed bitfield and the warm tier's cached signer bit - and requires the key to match so a rotated/mismatched key never inherits a stale verdict. Add WarmNodeStore::isVerifiedSigner() to expose the warm signer bit (the rebase onto develop added the bit itself; this surfaces it for lookups). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Lock NodeInfoPayloadEntry packing with a size assert keySignerProven cost zero bytes: sourceChannel, the two bools, and decodedBitfield are four 1-byte fields that fill a single 4-byte tail word (struct alignment is 4), so the flag consumed former padding rather than growing the 2000-entry PSRAM array. Add a static_assert pinning the entry to sizeof(meshtastic_User) + 20 so a future 5th trailing byte - which would open a fresh word (~8 KB PSRAM across the array) - fails the build instead of silently costing memory, prompting new flags to be packed into existing bytes. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Pack NodeInfo cache booleans into 1-bit fields Fold hasDecodedBitfield and keySignerProven into adjacent uint8_t:1 bitfields so they share a single byte, reserving 6 spare bits for future flags without growing the 2000-entry PSRAM array. sizeof is unchanged (still one packed tail word, sizeof(meshtastic_User) + 20); access is by name exactly as before, so no call sites change. Reorders decodedBitfield ahead of the flags so the two 1-bit members stay adjacent and the compiler packs them together. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Gate NodeInfo replay on signer-proven provenance (compile-time, default on) Add TMM_NODEINFO_REPLAY_REQUIRE_SIGNED (default 1): the direct-response path now only spoofs a reply for a node whose key is signer-proven, in addition to the staleness gate - so replay is based on flagging AND staleness. Replay is a courtesy feature, and vouching for an unverified (trust-on-first-use) identity to other nodes is the risk this closes, so signed-only is the safer default. Define the macro to 0 at build time to also serve fresh TOFU-only nodes. Both paths are gated: the PSRAM path checks the cached keySignerProven flag, the NodeDB fallback checks nodeInfoLiteHasXeddsaSigned(node). The effective gate (TMM_NODEINFO_REPLAY_SIGNED_GATE) is bypassed when PKI is excluded from the build, since nothing can be signed there and the courtesy feature would otherwise be disabled outright. Tests: existing reply-expecting tests establish signer-proven state (a new markKeySignerProvenForTest hook for the PSRAM cache, the NodeDB signed bit for the fallback path); add fallback and PSRAM tests asserting an unsigned/TOFU node is withheld under the default gate. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Rehydrate re-admitted node names from the TMM NodeInfo cache The warm tier keeps an evicted node's key but not its name (the 40-byte record has no room), so a re-admitted long-tail node is nameless until its next NodeInfo broadcast. The TrafficManagement NodeInfo cache is much larger (2000 PSRAM entries) and commonly still holds the full User, so use it as a name reservoir the warm tier structurally cannot be. On re-admission (getOrCreateMeshNode), after the warm-tier restore, copy the cached identity from the TMM cache via a new copyUser() getter - but only when its cached key matches the key just restored from warm, so a name never attaches to a different identity than the one we encrypt to (key-matched trust). Guarded by HAS_TRAFFIC_MANAGEMENT and a null check; a no-op without the PSRAM cache or when no key is present. CopyUserToNodeInfoLite sets only user-related bits, so the warm-restored signer bit is preserved. Limitations (by design): PSRAM-only, and the TMM cache is RAM-only, so this helps within an uptime session, not across reboot. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Drop non-portable NodeInfoPayloadEntry size assert (fixes pico build) The static_assert pinned sizeof(NodeInfoPayloadEntry) to sizeof(meshtastic_User) + 20, but nanopb packs the generated User struct differently per platform: on pico its size is not a multiple of 4, so alignment padding before the uint32 timestamps makes the overhead 22, not 20, and the assert failed the build (native happened to be +20 and passed, hiding it). The bitfield packing it was guarding still stands; replace the fixed-count assert with a comment, since no portable byte count exists. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01G7QggdwMM1CJkguuCmMfZs * Run the NodeInfo cache paths in native tests (TMM_HAS_NODEINFO_CACHE) The NodeInfo direct-response cache and everything layered on it - key pinning, signer provenance, staleness, throttle - was compiled only for ARCH_ESP32 + BOARD_HAS_PSRAM, so its entire test set was skipped by the native CI suite and ran nowhere but real hardware. Fold the scattered platform guards into one TMM_HAS_NODEINFO_CACHE macro that also enables the cache (plain heap, delete[] path already existed) for ARCH_PORTDUINO unit-test builds. Production portduino and embedded test builds are unchanged. Tests that exercise the NodeDB fallback path drop the cache explicitly via a new dropNodeInfoCacheForTest() hook, so both response paths are covered in one binary. Native suite: 60/60 (was 50 with the 10 cache tests compiled out). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT (cherry picked from commit b2dafbb) * Pin NodeInfo cache keys against the warm tier, not just the hot store cacheNodeInfoPacket() mirrored NodeDB::updateUser()'s key pin but checked only getMeshNode() - the hot store. updateUser's own pin effectively covers the warm tier too (getOrCreateMeshNode rehydrates the warm key before the check), so the mirror had a gap: for a node evicted to the warm tier whose cache slot was also gone, an attacker's NodeInfo with a bogus key passed the pin, and the cache's TOFU pin then locked the genuine node's frames out until the poisoned entry aged away. Split the authoritative lookup out of NodeDB::copyPublicKey() as copyPublicKeyAuthoritative() (hot store, then warm tier - never the opportunistic TMM tier, which would compare the cache against itself) and pin against that. Test: warm-tier-only key rejects a mismatching NodeInfo and accepts the matching one. Native suite: 61/61. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT (cherry picked from commit 28e8808) * Convert NodeInfo cache clocks to uint8 tick counters Replace the entry's uint32 millis stamps (lastObservedMs, lastResponseMs) with three uint8 free-running tick clocks - the same modular scheme the UnifiedCache counters already use: obsTick 3 min/tick (12.8 h period) - replay staleness gate respTick 5 s/tick (21.3 min) - per-target response throttle retTick 1 h/tick (10.67 d) - retention TTL + LRU age Validity is an explicit flag bit (hasObserved / hasResponded), not a 0 sentinel, and the maintenance sweep saturates a stamp (clears its flag) once its window passes, so no stamp can age toward its ~256-tick aliasing horizon. That retires the wrap/sentinel special cases (T4, T9) - nowStampMs() survives only for the fallback path's module-global millis stamp. obsTick is separated from retention by design: only a genuinely heard NODEINFO frame stamps it, so later membership-based retention refresh can never make a silent node look servable. Also drops lastObservedRxTime, which was only echoed in a debug log. Entry shrinks 136 -> 128 B; the 2000-entry array 272 kB -> 256 kB, 8 kB below the original develop footprint while keeping the throttle and retention features. Tick granularity costs at most one tick per window (+-5 s on 30 s, +-3 min on 6 h, +-1 h on 7 d). Native suite: 61/61. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT (cherry picked from commit e48ed9c) * Keep the NodeInfo cache a superset of NodeDB (seed + keep-alive) The cache learned identities only from overheard NODEINFO frames, so its membership was opportunistic: a NodeDB-tier node whose frame was never heard this boot had no entry (no key pin to protect it, no name to rehydrate), and the retention TTL evicted entries for nodes that still lived in the hot store or warm tier. Add an anti-entropy pass to the maintenance sweep (reconcileNodeInfoMembershipLocked): every hot-store / warm-tier node gets an entry - full identity from the hot store (hasFullUser), key-only from the warm tier - with signer provenance inherited key-matched, and NodeDB's key adopted wholesale on conflict. Member entries (isMember) are re-stamped each sweep, so they never age toward the retention TTL; when a node leaves both tiers the keep-alive stops and its entry ages out from its final member re-stamp. Membership also outranks key trust in LRU victim selection, and the reconcile pass skips seeding rather than churn one member out for another when hot+warm exceeds the cache. Two properties are load-bearing: - seeding/keep-alive never touch obsTick/hasObserved, so a seeded or retained entry is never served as a spoofed reply - only genuinely heard frames make a node servable; - copyUser() now requires hasFullUser, so a key-only warm seed can never stamp HAS_USER onto a nameless node via name-rehydration. Native suite: 64/64. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT (cherry picked from commit 4f1b30d) * Write-through NodeDB identity commits into the NodeInfo cache updateUser() is the single chokepoint through which every remote identity/key write enters NodeDB (key-verification keys stay in CryptoEngine's pending buffer until a NodeInfo carries them here), so one hook at its tail lets the NodeInfo cache reflect a commit immediately instead of waiting up to a minute for the reconcile sweep - which stays in place as the anti-entropy backstop. onNodeIdentityCommitted() upserts the full User: NodeDB's key is authoritative (a conflicting cached key is stale residue - replaced, provenance dropped), a keyless commit keeps an already-cached TOFU key, and signer provenance transfers only for the committed key. The observation stamp is never touched: knowledge is not observation, so a hook write can never make a never-heard node servable - covered by the new test alongside immediate copyUser/copyPublicKey visibility. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT (cherry picked from commit e160b89) * Purge TrafficManagement caches on explicit node removal NodeDB::removeNodeByNum() already forgets the node everywhere NodeDB owns - hot store, satellite stores, warm tier - but the TrafficManagement caches kept the deleted identity: the NodeInfo entry went on feeding the key pool (NodeDB::copyPublicKey) and name rehydration, and the unified slot kept its role/next-hop/dedup state, resurrecting the node on next contact. Add purgeNode(): clears both the unified cache slot and the NodeInfo cache entry, called from removeNodeByNum() alongside the warm-tier removal. Removal means full removal; passive eviction never calls this, and the reconcile sweep will not re-seed a node absent from both NodeDB tiers. Test: an observed identity plus a next-hop hint both vanish after removeNodeByNum(). Left for CI to execute per request. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT (cherry picked from commit b5564c1) * Document the tmm-fix-2 / tmm-fix-superset reconciliation decisions Two parallel implementations of the same superset design are being combined on this branch. This decision matrix records every divergence and which side each reconciled feature takes, ahead of the code commits that apply them. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT * Reconcile retention: no timed eviction, obsTick LRU, hourly seeding Adopt tmm-fix-superset's retention model (reconciliation decisions #3, #4, #9 in .notes/tmm-super-superset-reconciliation.md): - Entries are never evicted on a timer. The 7-day retention TTL and its third tick clock (retTick) are gone; wrap-safety rests entirely on the sweep's presence-bit saturation, and a quiet entry keeps its value (pubkey pool, name rehydration). Slots are reclaimed only by trust/membership-tiered LRU on insert - age scored by obsTick, with never-observed entries counting oldest - or by an explicit purge. - Membership refresh (entry -> NodeDB contains checks) runs every sweep; the heavy seeding pass runs at boot and then hourly, with the write-through hooks carrying immediacy in between. - Tick constants and helpers move into the header beside the existing UnifiedCache tick idiom, with static_asserts tying the tick windows to the fallback path's seconds/ms forms. Kept from tmm-fix-2 (decision #4): the warm tier is still seeded (key-only records via WarmNodeStore::entryAt) so the invariant remains cache superset-of hot AND warm, and the spareMembers guard still stops seeding from churning one member out for another when hot+warm exceeds the cache. Entry shrinks to 128 B (2000 entries = 256 kB). The TTL-based retention test is superseded by a no-timed-eviction test: a quiet keyed entry survives 9 days of sweeps while the serve gate saturates as before. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT * Reconcile hooks: key-commit write-through, purgeAll, key-matched signer Adopt tmm-fix-superset's hook coverage (reconciliation decisions #5-#8): - onNodeKeyCommitted(): write-through for the two key-write sites that bypass NodeDB::updateUser - the Router's admin-key learn (TOFU-grade) and KeyVerificationModule's manual-verification commit (proven=true, the strongest provenance the cache can carry). Both were coverage gaps in the tmm-fix-2 write-through design. - updateUser's hook call now transfers signer status key-matched (isVerifiedSignerForKey) instead of the node's bare signed flag, and runs on acceptance rather than only on change. - purgeAll(): factoryReset() and resetNodes() clear both TMM tables - removal-is-full-removal applies to bulk resets too, without relying on the usual post-reset reboot. - purgeNode() reuses the existing finders instead of open-coded scans and logs the (user-initiated) purge. - peekNodeInfoFlagsForTest(): flag introspection so saturation and membership tests can assert sweep effects directly. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT * Merge the two branches' test suites for the reconciled design Port tmm-fix-superset's unique tests, adapted to run natively under TMM_HAS_NODEINFO_CACHE (reconciliation decision #11): - keyHook_upsertsAndGovernsProvenance: TOFU learn -> manual-verification upgrade -> NodeDB-senior rotation resets provenance. - tickSaturation_sweepClearsObserved: the sweep saturates hasObserved past the serve window, the entry persists (no TTL), and a full 256-tick clock wrap cannot alias a saturated stamp back to fresh. - sweepMembershipMarking: reconciliation seeds a hot identity as member+fullUser+unobserved; the next sweep clears membership once the node leaves NodeDB, while the entry itself persists. tmm-fix-2's tests (warm pin, hot/warm seeding, updateUser write-through, removal purge - now also asserting the entry is gone via the new peek hook - and the no-timed-eviction rewrite) were already on this branch. Suite now counts 70 test functions. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT * Adapt cherry-picked and seeding tests to the reconciled semantics Two tests needed updating for interactions the validation run surfaced: - The #11035 test (ignoresUnsignedSignerIdentity) was written for a world without the native NodeInfo cache: it needs the NodeDB fallback path (dropNodeInfoCacheForTest) and the signed replay gate satisfied for its target, like the other fallback tests on this branch. - The hot-seed test's "observed frame makes it servable" step now sends a signature-verified frame: its node is a known signer, and per #11035 an unsigned frame from a signer must not (and does not) drive cache writes - the gate working as designed. Full native suite: 70/70 under ASan. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KWHDDxY4U2XLYW2WJJ2oLT * trunk fml * Doc tidyup * TrafficManagement: key NodeInfo-cache maintenance to its own guard runOnce() nested the entire NodeInfo maintenance block (tick-stamp saturation, membership refresh, boot/hourly reconcile) inside #if TRAFFIC_MANAGEMENT_CACHE_SIZE > 0, so a variant overriding the unified cache to 0 on a PSRAM board would compile the NodeInfo cache without its maintenance: hasObserved would never saturate, obsTick would alias past its 12.8 h wrap, and the 6 h staleness gate - whose wrap-safety explicitly depends on the sweep - would serve spoofed replies for long-gone nodes. Extract maintainNodeInfoCacheLocked(), guarded by TMM_HAS_NODEINFO_CACHE alone, and give runOnce() the same independent-guard structure purgeAll() already has. Also close the runtime cousin of the same mismatch: the write-through hooks (onNodeIdentityCommitted / onNodeKeyCommitted) now no-op while moduleConfig.has_traffic_management is off. Previously they kept filling the cache from NodeDB commits while runOnce() returned INT32_MAX, accumulating entries that were never swept or reconciled. Purges and reads stay ungated: removal must always work, and reads just miss an empty cache. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * TrafficManagement: forward throttled NodeInfo requests instead of consuming them The direct-response throttle returned true, which made handleReceived() STOP the request: within the 30 s window a repeat request was neither answered nor forwarded toward the genuine target, and the call site still logged "respond" and bumped nodeinfo_cache_hits for a reply that was never sent. A requester whose first reply was lost on a noisy link got silence for the whole window. Return false instead: the request flows through normal relay handling, so the genuine node (or another cache-holder) can answer, while our own spoofed TX stays bounded. Repeats of the same packet id are already absorbed by the router's duplicate detection, and the stats counter now only counts replies actually sent. Also log purgeNode() only when a slot was actually cleared - it runs for every NodeDB removal, including nodes the caches never tracked. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * TrafficManagement: consolidate NodeInfo-cache #if sprawl into one region Fourteen scattered #if TMM_HAS_NODEINFO_CACHE guards (one per function, each with its own #else stub of (void) casts) collapse into a single guarded region holding every NodeInfo-cache-only function, terminated by one #else block of no-op stub definitions. Because the stubs now exist on every build, the call sites in runOnce(), purgeNode() and purgeAll() drop their guards too; inner guards remain only for orthogonal features (PKI, warm tier) and for real conditional work (constructor allocation, PSRAM paths in shouldRespondToNodeInfo). No behavior change. Compile-checked on both sides of the macro: the native app build (stubs) and the native unit-test build (region). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Router: resolve sender key only for PKI-decrypt candidates perhapsDecode() resolved the sender's public key unconditionally for every encrypted packet, before even checking whether the packet could be PKI-decrypted (channel 0, unicast to us). Since copyPublicKey() grew its TrafficManagement fallback tier, a full hot+warm miss - the common case for channel traffic from senders outside both NodeDB tiers - additionally walked the 2000-entry NodeInfo cache under its lock, per packet, for a key that was then discarded. Move the resolution inside the PKI-candidate branch; remotePublic and haveRemoteKey had no consumers outside it. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * TrafficManagement: refresh NodeInfo membership hourly, not per-sweep The 60 s sweep re-derived isMember with a per-entry NodeDB lookup: O(entries x members) - about 700k node-number comparisons per minute on a full PSRAM cache (2000 entries x 250 hot + 100 warm), with strided PSRAM reads, all while holding cacheLock against the packet path. Move the refresh into the hourly reconcile pass, which is already O(members x entries): after the seeding loops (so the upsert pass still sees last pass's bits for spareMembers protection), clear every isMember bit and re-mark from both NodeDB tiers - including keyless warm records, which seed nothing but are still members. Accepted tradeoff, now documented on the field: membership lags a passive NodeDB eviction by up to an hour (the entry just stays LRU-sticky slightly longer). Additions stay immediate via the write-through hooks, explicit removals via purgeNode(). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * NodeDB: centralize bare-key commits in commitRemoteKey() The two key-write sites that bypass updateUser() (admin-channel learn in Router::perhapsDecode, manual verification in KeyVerificationModule) each carried their own #if HAS_TRAFFIC_MANAGEMENT write-through boilerplate - the pattern this PR itself had to retrofit twice, and which any future direct key write would silently miss, leaving the TrafficManagement cache divergent until the next hourly reconcile. Add NodeDB::commitRemoteKey(n, key32, KeyCommitTrust): writes the key to the hot store and routes the TrafficManagement write-through in one place, with provenance explicit at the call site (AdminChannelProven maps to TOFU-grade, ManuallyVerified to proven). The bypass sites keep their reason for existing - bare-key commits with provenance that updateUser's User-payload/TOFU-pin path cannot express - but no longer know about TrafficManagement at all; both stale includes are dropped (Router's was already unused on develop). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: tick wrap-safety analysis, updated cadences, CodeRabbit doc fixes node_info_stores.md gains a "Tick clocks and wrap safety" section recording which mechanism keeps each modular tick clock honest: the unified-cache clocks pair the 60 s sweep with read-time window resets, the NodeInfo obs/resp clocks are sweep-only (hence the compile-time invariant that maintainNodeInfoCacheLocked() is guarded by TMM_HAS_NODEINFO_CACHE alone), and the warm tier is immune by design - absolute unix-seconds, no wrap until 2106. Also brought current with this series: membership refresh moved to the hourly reconcile, throttled direct-response requests forward instead of being consumed, the commitRemoteKey() bare-key funnel, and the module-disabled gate on the write-through hooks. CodeRabbit doc review (PR #11050): present the NodeInfo payload cache as the third *identity* tier with the unified cache beside the chain, and describe NodeInfoLite's flattened fields / satellite copy-out accessors instead of the removed nested members. Two stale docs/tmm_node_stores.md references in the header now point at the real file. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * TrafficManagement: adapt tests to forwarded throttles and hourly membership Throttle tests (PSRAM and NodeDB-fallback paths): a request inside the 30 s window now CONTINUEs into normal relay handling instead of being consumed - assert no spoofed TX, no NAK suppression, and (PSRAM path) that nodeinfo_cache_hits counts only replies actually sent. Membership test (renamed reconcileMembershipMarking): the per-minute sweep no longer refreshes isMember, so the test now pins down both halves of the new contract - the very next sweep after a passive NodeDB eviction still shows the stale member bit (the documented up-to-an-hour lag), and a reconcile interval's worth of sweeps clears it. Disabled-module test additionally proves the write-through hooks share the has_traffic_management gate: a key commit while disabled must not land in the NodeInfo cache. Not covered here: a build permutation with TRAFFIC_MANAGEMENT_CACHE_SIZE overridden to 0 (the configuration the maintenance-guard fix protects) would need its own PlatformIO env plus guards on every unified-cache test - left as a follow-up. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * expand test coverage * nitpicks and docs update * more comment fixes * nitpicks * test: make TMM fixture cleanup abort-safe in tearDown() Several tests reset per-test global state (trafficManagementModule pointing at a stack `module`, owner.public_key, the RTC fake clock) only after their assertions. A TEST_ASSERT_* failure longjmps out and skips that trailing cleanup, leaving the state to dangle into later cases - concretely, the next setUp()'s resetNodes() would call trafficManagementModule->purgeAll() on a destroyed object. Move the resets into tearDown(), which runs unconditionally between tests, and drop the now-redundant per-test cleanups. Addresses a CodeRabbit review comment on PR #11050. clod helped too * docs tidy * Throttle NodeInfo direct responses A direct response is addressed to the requesting packet's from field, which is unauthenticated, and is sent by every neighbour that holds the target in cache. One request therefore makes several nodes transmit at an address the requester chose, and nothing limited how often that could be repeated. Replies are now spaced per requester, which bounds how much any single node can be made to receive, plus a global floor on how much airtime the feature can consume. The check sits where a reply is about to be sent, so requests declined for other reasons do not consume the budget. * test: reconcile TMM direct-response tests with #11104 throttle Makes the suite green for now. #11104's per-requester + global-floor throttle (60 s) is layered over the branch's per-target throttle, so the three existing "served again" checks (psram, fallback, sweep) now use a fresh requester to avoid the per-requester window masking the mechanism each one actually exercises. Adds a dedicated test for the new per-requester + 1 s global-floor behaviour (the reflector-flood gap the per-target throttle leaves open, and the bound that survives on non-PSRAM builds). Deferred: the branch's now-redundant fallback global stamp (nodeInfoFallbackLastResponseMs) is left in place as a follow-up cleanup. Clod wants credit. * TMM: unify direct-response throttles into per-sender + per-target RAM tables Replace the two path-specific NodeInfo-spoof throttles (per-entry respTick on the PSRAM cache path, single global stamp on the fallback path) with three symmetric bounds that behave identically with and without PSRAM: - per requester (60 s): how much any one node can be made to receive; - per target (60 s): how often we vouch for the same identity; - global floor (1 s): total airtime, the backstop once an attacker cycles requester/target past the 8-slot tables. Both axes are fixed 8-slot LRU tables in internal RAM (not the PSRAM NodeInfo cache), compared by wrap-safe uint32 ms subtraction, so there is no tick clock and no sweep to maintain. directResponseAllowed() resolves both slots before stamping either, so a reply one axis throttles never consumes the other's budget, and records the send itself. Retires: nodeInfoFallbackLastResponseMs, kNodeInfoResponseThrottleMs, nowStampMs, the respTick byte + hasResponded bit on every cache entry, currentRespTick/kNodeInfoRespTickMs/kNodeInfoThrottleTicks, and the sweep's respTick clear. Renumbers peekNodeInfoFlagsForTest (drops the responded bit). Tests: the psram/fallback throttle tests now assert the per-target axis at 60 s, isolated via a different requester, proving it holds with and without PSRAM; perRequesterAndGlobalFloor isolates the other two axes; the obsolete respTick wrap-safety test is removed. 83/83 native cases pass. clod helped too * whats up, doc? * trimming the comments * test: bump native-suite-count to 38 after upstream rebase Upstream develop carries 38 test_* suite directories but its native-suite-count file still reads 37 (a suite was added without bumping the count). Rebasing onto develop inherits that stale file, so the runner flags AMBER. Correct the registered total to 38. clod helped too --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Thomas Göttgens <tgoettgens@gmail.com>
1 parent 0165e91 commit 1872e5b

12 files changed

Lines changed: 3266 additions & 669 deletions

docs/node_info_stores.md

Lines changed: 248 additions & 0 deletions
Large diffs are not rendered by default.

docs/traffic_management_module.md

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
# The Traffic Management Module (TMM)
2+
3+
TMM is an optional module that shapes **transit** traffic on busy meshes. Large networks get
4+
noisy fast - repeated position packets, bursty senders, and unknown/undecryptable frames all
5+
burn limited airtime and power - and TMM filters or answers that traffic before it is
6+
rebroadcast. On supported targets it **ships enabled** (`has_traffic_management` defaults to
7+
true) with position dedup running at its 11 h default; the other features each default off, so
8+
the module is on out of the box but opt-in per feature. It was introduced in
9+
[meshtastic/firmware#9358](https://github.com/meshtastic/firmware/pull/9358).
10+
11+
This document covers the module's behaviour, with a deep dive on the two TMM-specific
12+
NodeInfo features - **direct-serve** (answering NodeInfo requests on another node's behalf)
13+
and the **throttling** that bounds it. The identity/traffic-state stores those features read
14+
from are documented separately in [node_info_stores.md](node_info_stores.md); this file owns
15+
the direct-serve and throttle behaviour, that file owns the stores.
16+
17+
Sources of truth: `src/modules/TrafficManagementModule.{h,cpp}`, defaults in
18+
`src/mesh/Default.h`.
19+
20+
---
21+
22+
## How it runs
23+
24+
- **Enablement is three-gated.** Compile-time `HAS_TRAFFIC_MANAGEMENT` (with the
25+
`MESHTASTIC_EXCLUDE_TRAFFIC_MANAGEMENT` build exclusion), then the runtime
26+
`moduleConfig.has_traffic_management` presence flag. While the runtime gate is off, the
27+
packet path, the maintenance sweep, the NodeDB write-through hooks, and the cache accessors
28+
all no-op - content, maintenance, and reads are keyed to the same condition.
29+
- **It runs before `RoutingModule`** in `callModules()`. Returning `STOP` from
30+
`handleReceived()` fully consumes a packet, so it is never rebroadcast; `CONTINUE` lets it
31+
proceed through normal relay handling.
32+
- **State is cheap.** Per-node traffic-shaping counters live in a flat 10-byte
33+
`UnifiedCacheEntry` array (position fingerprint, rate/unknown counters, modular tick
34+
stamps, a next-hop hint, and a 4-bit role fallback) - see
35+
[node_info_stores.md §3](node_info_stores.md). Direct-serve additionally reads the PSRAM
36+
NodeInfo payload cache (or the NodeDB fallback when that cache is absent).
37+
38+
## What it does
39+
40+
| Feature | Default | In one line |
41+
| ------------------------ | -------------- | -------------------------------------------------------------- |
42+
| Position dedup | on, 11 h | Suppresses a stationary sender's repeated position broadcasts. |
43+
| Per-sender rate limit | off | Caps how many transit packets one sender may spend per window. |
44+
| Unknown-packet filter | off | Drops a sender's undecryptable traffic past a threshold. |
45+
| NodeInfo direct response | off | Answers a NodeInfo request on the target's behalf (see below). |
46+
| Position precision clamp | channel-driven | Truncates relayed position to the channel's precision. |
47+
48+
Config lives under `moduleConfig.traffic_management`; the per-feature sections below give the
49+
exact fields, defaults, and behaviour. NodeInfo direct response has its own deep-dive sections
50+
after these.
51+
52+
### Position dedup
53+
54+
`position_min_interval_secs` (default 11 h; `0` disables). Drops a duplicate position from the
55+
same sender inside the interval, where "duplicate" means the same fingerprint on the channel's
56+
`position_precision` grid (firmware default 19-bit, ~90 m cells). Role caps only ever _shorten_
57+
the interval: **tracker / TAK tracker → 1 h**, **lost-and-found → 15 min**.
58+
59+
### Per-sender rate limit
60+
61+
`rate_limit_window_secs` + `rate_limit_max_packets` (default off; either `0` disables). Drops a
62+
sender's transit packets once it exceeds the budget within the window.
63+
64+
### Unknown-packet filter
65+
66+
`unknown_packet_threshold` (default `0` = off). Drops undecryptable traffic from a sender once it
67+
passes the threshold within a ~5 min window.
68+
69+
### NodeInfo direct response
70+
71+
`nodeinfo_direct_response_max_hops` (default `0` = off). When set, a neighbour that already
72+
holds the target's identity answers a unicast NodeInfo request on its behalf, saving the full
73+
round trip. This is TMM's most security-sensitive feature; the serve gates and the throttle
74+
that bounds it are covered in the two dedicated sections below.
75+
76+
### Position precision clamp
77+
78+
Driven by the channel's `position_precision` ceiling (else the 19-bit firmware default).
79+
`alterReceived()` truncates relayed position coordinates to that precision.
80+
81+
### Shelved
82+
83+
Present in the config surface but currently no-ops in the module, deferred until the right
84+
heuristics are settled: hop exhaustion for position/telemetry (`exhaust_hop_position` /
85+
`exhaust_hop_telemetry`) and `router_preserve_hops`. `alterReceived()` leaves rebroadcast hop
86+
handling untouched.
87+
88+
---
89+
90+
## NodeInfo direct response (direct-serve)
91+
92+
Normally a unicast NodeInfo request travels all the way to the target and the reply travels
93+
all the way back. On a large mesh that is several hops of airtime per lookup. When
94+
`nodeinfo_direct_response_max_hops > 0`, a neighbour that already holds the target's identity
95+
answers **on the target's behalf** with a spoofed reply, cutting the round trip to one hop.
96+
97+
**Data source.** The reply payload comes from the TMM NodeInfo payload cache (PSRAM-backed;
98+
full cached `User` plus provenance metadata) or, on builds without that cache, from the
99+
NodeDB fallback. Both are described in [node_info_stores.md §4](node_info_stores.md); this
100+
feature is a _consumer_ of them.
101+
102+
**Decision pipeline** (`shouldRespondToNodeInfo()`), in order - any failure returns `false`
103+
and the request is left to propagate normally:
104+
105+
1. **Eligibility** (checked by the caller): `nodeinfo_direct_response_max_hops > 0`,
106+
`NODEINFO_APP` portnum, `want_response`, and the packet is unicast, not to us, not from us.
107+
2. **Hop clamp** (`isMinHopsFromRequestor()`): respond only when the requester is within the
108+
role-clamped hop ceiling - **routers up to 3 hops** (`kRouterDefaultMaxHops`, may be
109+
lowered by config), **clients direct-only, 0 hops** (`kClientDefaultMaxHops`).
110+
3. **Identity lookup**: NodeInfo cache hit (cache path) or NodeDB fallback (fallback path).
111+
4. **Staleness gate (6 h)**: never vouch for a node not genuinely _heard_ within the serve
112+
window. Only a real observed frame stamps the recency bit - seeding and write-through are
113+
knowledge, not observation, so a silent node can never look alive to this path.
114+
5. **Signer-provenance gate** (`TMM_NODEINFO_REPLAY_SIGNED_GATE`, default on): vouch only for
115+
an identity whose key is signer-proven (XEdDSA-verified, directly or inherited from
116+
NodeDB). A trust-on-first-use identity is left for the genuine node - or another
117+
cache-holder that _has_ proof - to answer. Bypassed when PKI is compiled out.
118+
6. **Throttle** (`directResponseAllowed()`): see the next section.
119+
120+
**The spoofed reply.** On success TMM emits a NodeInfo reply with `from` set to the _target_
121+
(so the requester sees a valid answer), `to` the requester, `hop_limit = 0` (one hop only),
122+
`request_id` the original packet id, and the OK_TO_MQTT bit set from local
123+
`config.lora.config_ok_to_mqtt` policy. The requester's own identity claim in the request is
124+
**not** written back to NodeDB - a unicast NodeInfo is unsigned, so treating it as an
125+
identity update would be unauthenticated. `nodeinfo_cache_hits` counts only replies actually
126+
sent.
127+
128+
---
129+
130+
## Throttling direct responses
131+
132+
A direct reply is addressed to the requesting packet's `from` and spoofs the requested
133+
target - and **both fields are unauthenticated header data**. Without a bound, an attacker
134+
crafts requests carrying a victim's address as `from`, and every neighbour holding the target
135+
transmits at the victim: a reflector-amplification primitive. The throttle is the security
136+
core of this feature, checked immediately before a reply would go out so requests declined for
137+
other reasons never consume the budget.
138+
139+
**Three bounds**, all keyed off `clockMs()` and evaluated under `cacheLock`:
140+
141+
| Bound | Window | Bounds |
142+
| ------------------------------------------------ | ------ | ------------------------------------------------ |
143+
| Per requester (`kDirectResponsePerRequesterMs`) | 60 s | how much any single node can be made to receive |
144+
| Per target (`kDirectResponsePerTargetMs`) | 60 s | how often we vouch for the same identity |
145+
| Global airtime floor (`kDirectResponseGlobalMs`) | 1 s | total spoofed TX, regardless of key distribution |
146+
147+
**Mechanism.** The two per-key bounds are fixed **8-slot LRU tables in internal RAM**
148+
(`directRequesterSeen`, `directTargetSeen`) - _not_ the PSRAM NodeInfo cache - so they behave
149+
identically with and without PSRAM, on the cache path and the NodeDB-fallback path alike.
150+
Timestamps are full `uint32` milliseconds compared by wrap-safe subtraction, so there is no
151+
tick clock and no maintenance sweep to keep them honest. `directResponseAllowed(requester,
152+
target, now)` resolves a slot in _both_ tables before stamping either - so a reply one axis
153+
throttles never consumes the other axis's budget - then records the send on all three bounds.
154+
The global floor is a single stamp, checked first as the cheap common case.
155+
156+
**When a table fills.** For an unseen key with no free slot, `directResponseSlot()` evicts the
157+
**least-recently-used** entry (smallest last-reply time) and admits the new key. The LRU
158+
victim is by construction the entry closest to expiring anyway, so eviction is the
159+
lowest-cost choice. An attacker who cycles more than 8 distinct requesters or targets - easy,
160+
since both are unauthenticated - evicts entries and defeats _per-key_ throttling for the
161+
cycled keys; that is expected, and why the **global 1 s floor is the hard backstop**. It is a
162+
single stamp, cannot fill, and caps total spoofed replies at ~1/s no matter what. Per-key
163+
throttling degrades gracefully to the floor under pressure.
164+
165+
**Throttled is not dropped.** A throttled request returns `false`, which lets
166+
`handleReceived()` `CONTINUE`: the request forwards toward the genuine target (which can
167+
answer itself) rather than being black-holed. A requester whose first reply was lost on a
168+
noisy link would otherwise get silence for the whole window; repeats of the same packet id
169+
are already absorbed by the router's duplicate detection.
170+
171+
**Evolution.** The original design split throttling by path: a per-entry `respTick` stamp in
172+
each NodeInfo cache slot (cache path, 30 s, swept for wrap-safety) plus a single module-global
173+
stamp for the NodeDB fallback (30 s, neither per-requester nor per-target). Those two routes
174+
were unified into the symmetric per-requester + per-target RAM tables above, aligned to a
175+
single 60 s window, so both axes hold with and without PSRAM and the cache entry no longer
176+
carries throttle state.
177+
178+
---
179+
180+
## Configuration
181+
182+
All tunables live under `moduleConfig.traffic_management`; the whole module is gated by the
183+
`has_traffic_management` presence flag, and each per-feature section above lists its own
184+
field(s) and default. Two related sets of knobs are **firmware constants, not config**: the
185+
role-based position caps `default_traffic_mgmt_tracker_position_min_interval_secs` (1 h) and
186+
`default_traffic_mgmt_lost_and_found_position_min_interval_secs` (15 min), and the direct-serve
187+
throttle windows (the `kDirectResponse*Ms` constants).
188+
189+
## See also
190+
191+
- [node_info_stores.md](node_info_stores.md) - the NodeDB hot store, warm tier, TMM NodeInfo
192+
payload cache, and unified cache that the direct-serve path reads from, plus their trust,
193+
provenance, and anti-entropy model.

src/mesh/NodeDB.cpp

Lines changed: 127 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@
3131
#if HAS_VARIABLE_HOPS
3232
#include "modules/HopScalingModule.h"
3333
#endif
34+
#if HAS_TRAFFIC_MANAGEMENT
35+
#include "modules/TrafficManagementModule.h"
36+
#endif
3437
#include "xmodem.h"
3538
#include <ErriezCRC32.h>
3639
#include <algorithm>
@@ -767,6 +770,12 @@ bool NodeDB::factoryReset(bool eraseBleBonds)
767770
warmStore.clear();
768771
warmStore.saveIfDirty();
769772
#endif
773+
#if HAS_TRAFFIC_MANAGEMENT
774+
// Factory reset forgets everything; TMM's RAM caches must not survive to resurrect
775+
// identities (the device usually reboots after this, but don't rely on it).
776+
if (trafficManagementModule)
777+
trafficManagementModule->purgeAll();
778+
#endif
770779

771780
// second, install default state (this will deal with the duplicate mac address issue)
772781
installDefaultNodeDatabase();
@@ -1597,6 +1606,11 @@ void NodeDB::resetNodes(bool keepFavorites)
15971606
#if WARM_NODE_COUNT > 0
15981607
warmStore.clear(); // warm entries are never favorites; a DB reset clears them too
15991608
#endif
1609+
#if HAS_TRAFFIC_MANAGEMENT
1610+
// A user-initiated DB reset forgets everything; TMM's caches must not resurrect it.
1611+
if (trafficManagementModule)
1612+
trafficManagementModule->purgeAll();
1613+
#endif
16001614

16011615
devicestate.has_rx_waypoint = false;
16021616
saveNodeDatabaseToDisk();
@@ -1629,6 +1643,12 @@ void NodeDB::removeNodeByNum(NodeNum nodeNum)
16291643
// Explicit user removal: don't let the warm tier resurrect the node
16301644
warmStore.remove(nodeNum);
16311645
#endif
1646+
#if HAS_TRAFFIC_MANAGEMENT
1647+
// Explicit removal is full removal: the TrafficManagement caches (unified slot +
1648+
// NodeInfo identity cache) must not keep serving or resurrect the node either.
1649+
if (trafficManagementModule)
1650+
trafficManagementModule->purgeNode(nodeNum);
1651+
#endif
16321652

16331653
LOG_DEBUG("NodeDB::removeNodeByNum purged %d entries. Save changes", removed);
16341654
saveNodeDatabaseToDisk();
@@ -3404,6 +3424,20 @@ bool NodeDB::updateUser(uint32_t nodeId, meshtastic_User &p, uint8_t channelInde
34043424
}
34053425
}
34063426

3427+
#if HAS_TRAFFIC_MANAGEMENT
3428+
// Write-through: every accepted remote-identity commit lands here (NodeInfoModule,
3429+
// MeshService, and TMM's requester learning all funnel through updateUser; the two
3430+
// key-write sites that bypass it call onNodeKeyCommitted instead), so TMM's NodeInfo
3431+
// cache reflects the commit immediately rather than at the next reconcile pass. Runs on
3432+
// acceptance, not on `changed`: an identical update still proves the identity is
3433+
// current. `p` is the post-hygiene payload; signerKnown transfers only key-matched
3434+
// verified-signer status (isVerifiedSignerForKey semantics), never a bare node flag.
3435+
if (nodeId != getNodeNum() && trafficManagementModule) {
3436+
const bool signerKnown = p.public_key.size == 32 && isVerifiedSignerForKey(nodeId, p.public_key.bytes);
3437+
trafficManagementModule->onNodeIdentityCommitted(nodeId, p, signerKnown);
3438+
}
3439+
#endif
3440+
34073441
return changed;
34083442
}
34093443

@@ -3714,7 +3748,7 @@ uint32_t NodeDB::hotNodeLastHeard(NodeNum n) const
37143748
return 0;
37153749
}
37163750

3717-
bool NodeDB::copyPublicKey(NodeNum n, meshtastic_NodeInfoLite_public_key_t &out)
3751+
bool NodeDB::copyPublicKeyAuthoritative(NodeNum n, meshtastic_NodeInfoLite_public_key_t &out)
37183752
{
37193753
const meshtastic_NodeInfoLite *info = getMeshNode(n);
37203754
if (info && info->public_key.size == 32) {
@@ -3730,6 +3764,81 @@ bool NodeDB::copyPublicKey(NodeNum n, meshtastic_NodeInfoLite_public_key_t &out)
37303764
return false;
37313765
}
37323766

3767+
bool NodeDB::copyPublicKey(NodeNum n, meshtastic_NodeInfoLite_public_key_t &out)
3768+
{
3769+
if (copyPublicKeyAuthoritative(n, out))
3770+
return true;
3771+
#if HAS_TRAFFIC_MANAGEMENT
3772+
// Last resort: a key the TrafficManagement NodeInfo cache learned from an observed frame
3773+
// for a node no longer in either NodeDB tier. This extends the pool of peers we can
3774+
// encrypt to. Keys here may be trust-on-first-use (see copyPublicKey's signerProven), the
3775+
// same first-contact trust NodeDB itself applies via updateUser().
3776+
if (trafficManagementModule && trafficManagementModule->copyPublicKey(n, out.bytes)) {
3777+
out.size = 32;
3778+
return true;
3779+
}
3780+
#endif
3781+
return false;
3782+
}
3783+
3784+
bool NodeDB::isVerifiedSignerForKey(NodeNum n, const uint8_t *key32)
3785+
{
3786+
if (!key32)
3787+
return false;
3788+
// Hot store is authoritative when present; a node lives in the hot XOR warm tier, so if the
3789+
// hot store holds it the warm tier does not, and we decide entirely from the hot entry.
3790+
const meshtastic_NodeInfoLite *info = getMeshNode(n);
3791+
if (info)
3792+
return info->public_key.size == 32 && nodeInfoLiteHasXeddsaSigned(info) && memcmp(info->public_key.bytes, key32, 32) == 0;
3793+
#if WARM_NODE_COUNT > 0
3794+
uint8_t warmKey[32];
3795+
if (warmStore.copyKey(n, warmKey) && memcmp(warmKey, key32, 32) == 0)
3796+
return warmStore.isVerifiedSigner(n);
3797+
#endif
3798+
return false;
3799+
}
3800+
3801+
bool NodeDB::isKnownXeddsaSigner(NodeNum n)
3802+
{
3803+
// A node lives in the hot XOR warm tier, so the hot verdict is final when present.
3804+
const meshtastic_NodeInfoLite *info = getMeshNode(n);
3805+
if (info)
3806+
return nodeInfoLiteHasXeddsaSigned(info);
3807+
#if WARM_NODE_COUNT > 0
3808+
return warmStore.isVerifiedSigner(n);
3809+
#else
3810+
return false;
3811+
#endif
3812+
}
3813+
3814+
void NodeDB::commitRemoteKey(NodeNum n, const uint8_t key32[32], KeyCommitTrust trust)
3815+
{
3816+
if (!key32 || n == 0)
3817+
return;
3818+
// Local copy first: callers may pass the node's own key bytes back in (e.g. manual
3819+
// verification re-committing an already-stored key), and memcpy forbids overlap.
3820+
uint8_t key[32];
3821+
memcpy(key, key32, 32);
3822+
3823+
meshtastic_NodeInfoLite *info = getOrCreateMeshNode(n);
3824+
if (!info)
3825+
return;
3826+
// Unconditional overwrite - deliberately NOT updateUser()'s "don't replace a known key" pin.
3827+
// That pin protects against unauthenticated NodeInfo broadcasts; the only callers here are
3828+
// possession/authority-proven (ManuallyVerified = user confirmed the key; AdminChannelProven =
3829+
// decrypted via the admin key with p->from bound into the AEAD nonce), i.e. exactly the paths
3830+
// meant to establish or rotate a key. Keep new call sites to that same trust bar.
3831+
memcpy(info->public_key.bytes, key, 32);
3832+
info->public_key.size = 32;
3833+
3834+
#if HAS_TRAFFIC_MANAGEMENT
3835+
// Write-through, mirroring updateUser()'s identity hook: without it the TrafficManagement
3836+
// NodeInfo cache diverges until the next hourly reconcile.
3837+
if (trafficManagementModule)
3838+
trafficManagementModule->onNodeKeyCommitted(n, key, trust == KeyCommitTrust::ManuallyVerified);
3839+
#endif
3840+
}
3841+
37333842
meshtastic_Config_DeviceConfig_Role NodeDB::getNodeRole(NodeNum n)
37343843
{
37353844
const meshtastic_NodeInfoLite *info = getMeshNode(n);
@@ -3827,6 +3936,23 @@ meshtastic_NodeInfoLite *NodeDB::getOrCreateMeshNode(NodeNum n)
38273936
}
38283937
LOG_MIGRATION("Rehydrated node 0x%08x from warm tier (key=%d)", n, lite->public_key.size == 32);
38293938
}
3939+
#endif
3940+
#if HAS_TRAFFIC_MANAGEMENT
3941+
// Name rehydration: the warm tier keeps a node's key but not its name, so a re-admitted
3942+
// long-tail node is nameless until its next NodeInfo. The TrafficManagement NodeInfo
3943+
// cache is much larger and often still holds the full User. Restore it - but only when
3944+
// its cached key matches the key we just restored from warm, so a name never attaches to
3945+
// a different identity than the one we encrypt to. No-op without the TMM NodeInfo cache
3946+
// or when no key is present (key-matched by design). CopyUserToNodeInfoLite sets only the
3947+
// user-related bits, so the warm-restored signer bit survives.
3948+
if (lite->public_key.size == 32 && !nodeInfoLiteHasUser(lite) && trafficManagementModule) {
3949+
meshtastic_User tmmUser = meshtastic_User_init_zero;
3950+
if (trafficManagementModule->copyUser(n, tmmUser) && tmmUser.public_key.size == 32 &&
3951+
memcmp(tmmUser.public_key.bytes, lite->public_key.bytes, 32) == 0) {
3952+
TypeConversions::CopyUserToNodeInfoLite(lite, tmmUser);
3953+
LOG_INFO("Rehydrated node 0x%08x identity from TMM NodeInfo cache", n);
3954+
}
3955+
}
38303956
#endif
38313957
LOG_INFO("Adding node to database with %i nodes and %u bytes free!", numMeshNodes, memGet.getFreeHeap());
38323958
}

0 commit comments

Comments
 (0)