From 2c4c64131ba7c7fdcd353e912fe5a62cd67706b8 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Thu, 8 Oct 2026 04:34:20 -0400 Subject: [PATCH] fix(#836): correct anon-regions request format + reply correlation D1 found Discover Regions got no reply from the owner's repeater. Root cause (firmware BaseChatMesh.sendAnonReq): the firmware prepends its own 4-byte tag, but buildAnonRegionsRequestFrame also prepended a timestamp, shifting the request-type byte so the repeater dispatched it as a login, never regions. And discoverRegions correlated on a client-invented tag, not the firmware tag the 0x8C echoes. Fix: request payload is [0x01][reply_path_len] (no timestamp); discoverRegions learns the tag from the RESP_CODE_SENT ack via the frame stream and matches the 0x8C by it. Removed the dead tag map + 0x8C switch case. Tests corrected to the real contract (they had encoded the wrong one). Co-Authored-By: Claude Opus 4.8 --- lib/connector/meshcore_connector.dart | 71 +++++++++-------------- lib/connector/meshcore_protocol.dart | 28 ++++----- test/connector/region_connector_test.dart | 39 +++++++------ test/connector/region_protocol_test.dart | 24 ++++---- 4 files changed, 78 insertions(+), 84 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index d4d914bc..b0ac79b5 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -5811,20 +5811,7 @@ class MeshCoreConnector extends ChangeNotifier { // Frames and parsers live in meshcore_protocol.dart; this is the connector // wiring, modeled on the 0xC6 pkt-hash request/reply correlation above. - /// Pending regions-discovery requests, keyed by the tag the firmware echoes - /// (the anon request's timestamp, returned as RESP_CODE_SENT.tag and again in - /// the 0x8C reply). Mirrors [_pendingPktHashCompleters]. - final Map> _pendingRegionsCompleters = {}; Completer? _defaultFloodScopeCompleter; - int _regionsTagSeq = 0; - - /// Unique 32-bit tag for a regions request. The firmware treats the anon - /// request's timestamp purely as an echo tag, so a monotonic value avoids - /// collisions between back-to-back discoveries. - int _nextRegionsTag() { - final base = DateTime.now().millisecondsSinceEpoch & 0xFFFFFF; - return (base << 8) | (_regionsTagSeq++ & 0xFF); - } /// True iff the connected firmware supports region flood-scoping + discovery. bool get supportsRegionScope => firmwareSupportsRegionScope(_firmwareVerCode); @@ -5839,47 +5826,46 @@ class MeshCoreConnector extends ChangeNotifier { } /// Discover the flood regions a reachable repeater advertises. Sends an anon - /// regions request to [repeaterPubKey] (32 bytes) and awaits the 0x8C reply, - /// correlated by the echoed tag. Returns null on timeout. Throws [StateError] - /// when the firmware does not support region scoping (fail-closed; callers - /// gate the UI on [supportsRegionScope]). + /// regions request to [repeaterPubKey] (32 bytes). + /// + /// Correlation: the firmware generates the anon-request tag and returns it in + /// the `RESP_CODE_SENT` ack; the repeater echoes that same tag in its `0x8C` + /// reply. So we learn the tag from the ack that follows our send, then match + /// the `0x8C` by it (the client cannot pick the tag, #836). Returns null on + /// timeout. Throws [StateError] when the firmware does not support region + /// scoping (fail-closed; callers gate the UI on [supportsRegionScope]). Future discoverRegions({ required Uint8List repeaterPubKey, Duration timeout = const Duration(seconds: 10), }) async { _guardRegionScope(); - final tag = _nextRegionsTag(); final completer = Completer(); - _pendingRegionsCompleters[tag] = completer; - final timer = Timer(timeout, () { - if (!completer.isCompleted) completer.complete(null); + int? tag; // firmware tag, learned from the RESP_CODE_SENT after we send + void finish(RegionsReply? reply) { + if (!completer.isCompleted) completer.complete(reply); + } + + final sub = receivedFrames.listen((frame) { + if (frame.isEmpty) return; + if (tag == null && frame[0] == respCodeSent && frame.length >= 6) { + tag = readUint32LE(frame, 2); + return; + } + if (tag != null && frame[0] == pushCodeBinaryResponse) { + final reply = parseRegionsReply(frame); + if (reply != null && reply.tag == tag) finish(reply); + } }); + final timer = Timer(timeout, () => finish(null)); try { - await sendFrame( - buildAnonRegionsRequestFrame(repeaterPubKey, timestamp: tag), - ); + await sendFrame(buildAnonRegionsRequestFrame(repeaterPubKey)); return await completer.future; } catch (e) { - appLogger.warn( - 'regions discovery failed for tag $tag: $e', - tag: 'Region', - ); + appLogger.warn('regions discovery failed: $e', tag: 'Region'); return null; } finally { timer.cancel(); - _pendingRegionsCompleters.remove(tag); - } - } - - /// Routes a 0x8C binary response to a waiting regions request, matched by tag. - /// 0x8C is a generic envelope, so a frame whose tag matches no pending regions - /// request is left alone (a timeout, or another handler, owns it). - void _handleRegionsReply(Uint8List frame) { - final parsed = parseRegionsReply(frame); - if (parsed == null) return; - final completer = _pendingRegionsCompleters[parsed.tag]; - if (completer != null && !completer.isCompleted) { - completer.complete(parsed); + await sub.cancel(); } } @@ -6318,9 +6304,6 @@ class MeshCoreConnector extends ChangeNotifier { case cmdOffbandPktHash: _handleOffbandPktHashFrame(frame); break; - case pushCodeBinaryResponse: - _handleRegionsReply(frame); - break; case respCodeDefaultFloodScope: _handleDefaultFloodScopeReply(frame); break; diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index 3cb9a655..b4f2df86 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -705,22 +705,24 @@ const int defaultScopeNameField = 31; bool firmwareSupportsRegionScope(int? firmwareVerCode) => (firmwareVerCode ?? 0) >= 13; -/// Regions-discovery ANON request to [repeaterPubKey] (32 bytes). Wire: -/// `[57][pubkey32][timestamp:4 LE][0x01][reply_path_len=0]`. The firmware echoes -/// [timestamp] as the `RESP_CODE_SENT` tag, so the caller correlates the `0x8C` -/// reply by that tag. A zero reply-path means zero-hop direct, which the repeater -/// requires (`isRouteDirect`) to answer a regions request. -Uint8List buildAnonRegionsRequestFrame( - Uint8List repeaterPubKey, { - int? timestamp, -}) { - final ts = timestamp ?? DateTime.now().millisecondsSinceEpoch ~/ 1000; +/// Regions-discovery ANON request to [repeaterPubKey] (32 bytes). Wire after +/// the pubkey: `[ANON_REQ_TYPE_REGIONS 0x01][reply_path_len]`. +/// +/// The firmware's `sendAnonReq` (BaseChatMesh) prepends its OWN 4-byte tag to +/// this payload before transmit, and returns that tag in `RESP_CODE_SENT`; the +/// repeater echoes it in the `0x8C` reply. So the client must NOT add a +/// timestamp/tag here: doing so shifts the request-type byte and the repeater +/// reads it as a login request, never regions (D1 bug, #836). Correlate the +/// reply by the `RESP_CODE_SENT` tag, not a client value. +/// +/// `reply_path_len = 0` asks the repeater to reply zero-hop, which fits a +/// directly reachable repeater; a multi-hop return path is not yet supported. +Uint8List buildAnonRegionsRequestFrame(Uint8List repeaterPubKey) { final writer = BufferWriter(); writer.writeByte(cmdSendAnonReq); writer.writeBytes(repeaterPubKey); - writer.writeUInt32LE(ts); writer.writeByte(anonReqTypeRegions); - writer.writeByte(0); // reply_path_len = 0 (zero-hop direct) + writer.writeByte(0); // reply_path_len = 0 (zero-hop reply) return writer.toBytes(); } @@ -793,7 +795,7 @@ DefaultFloodScope? parseDefaultFloodScopeReply(Uint8List frame) { /// A regions-discovery reply parsed from a `PUSH_CODE_BINARY_RESPONSE` (0x8C) /// envelope: `[0x8C][0][tag:4][clock:4][CSV names]`. [tag] matches the -/// `RESP_CODE_SENT` tag from [buildAnonRegionsRequestFrame]; names are +/// firmware-chosen tag returned in `RESP_CODE_SENT` for the request; names are /// `#`-stripped and comma-separated, with `*` marking a wildcard. class RegionsReply { const RegionsReply({ diff --git a/test/connector/region_connector_test.dart b/test/connector/region_connector_test.dart index c72c953e..26349fdb 100644 --- a/test/connector/region_connector_test.dart +++ b/test/connector/region_connector_test.dart @@ -25,14 +25,19 @@ Uint8List _padName(String name, int len) { return b; } -// Build the 0x8C reply a repeater would elicit for a given outgoing request, -// echoing the request's tag (bytes 33..37 of the CMD_SEND_ANON_REQ frame). -Uint8List _regionsReplyFor( - Uint8List req, { - required int clock, - required String csv, -}) { - final tag = ByteData.sublistView(req, 33, 37).getUint32(0, Endian.little); +// The firmware's send ack: [RESP_CODE_SENT][flood][tag:4 LE][est:4]. The tag is +// the firmware-chosen anon-req tag the repeater echoes in its 0x8C reply. +Uint8List _respSent(int tag) { + final b = BytesBuilder() + ..addByte(respCodeSent) + ..addByte(0) + ..add(_u32le(tag)) + ..add(_u32le(0)); + return b.toBytes(); +} + +// The repeater's 0x8C regions reply: [0x8C][0][tag:4][clock:4][CSV]. +Uint8List _regionsReply(int tag, {required int clock, required String csv}) { final b = BytesBuilder() ..addByte(pushCodeBinaryResponse) ..addByte(0) @@ -63,14 +68,16 @@ void main() { Uint8List? sent; connector.sendFrameOverrideForTest = (data) { sent = data; + // Firmware ack carries the tag; the repeater's 0x8C echoes it. + connector.handleFrameForTest(_respSent(0xAABBCCDD)); connector.handleFrameForTest( - _regionsReplyFor(data, clock: 0x01020304, csv: 'oki,test,*'), + _regionsReply(0xAABBCCDD, clock: 0x01020304, csv: 'oki,test,*'), ); }; final reply = await connector.discoverRegions(repeaterPubKey: pub); expect(sent, isNotNull); expect(sent![0], cmdSendAnonReq); - expect(sent![37], anonReqTypeRegions); + expect(sent![33], anonReqTypeRegions); // type right after the pubkey expect(reply, isNotNull); expect(reply!.regionNames, ['oki', 'test', '*']); expect(reply.clock, 0x01020304); @@ -90,13 +97,11 @@ void main() { 'a 0x8C with a non-matching tag never satisfies the request', () async { connector.sendFrameOverrideForTest = (_) { - final b = BytesBuilder() - ..addByte(pushCodeBinaryResponse) - ..addByte(0) - ..add(_u32le(0xFFFFFFFF)) - ..add(_u32le(1)) - ..add(Uint8List.fromList([...'zzz'.codeUnits, 0])); - connector.handleFrameForTest(b.toBytes()); + // Ack says tag A, but the 0x8C carries a different tag -> no match. + connector.handleFrameForTest(_respSent(0x11111111)); + connector.handleFrameForTest( + _regionsReply(0x22222222, clock: 1, csv: 'zzz'), + ); }; final reply = await connector.discoverRegions( repeaterPubKey: pub, diff --git a/test/connector/region_protocol_test.dart b/test/connector/region_protocol_test.dart index bf0fc7d1..3177bbeb 100644 --- a/test/connector/region_protocol_test.dart +++ b/test/connector/region_protocol_test.dart @@ -14,16 +14,20 @@ Uint8List _key16(int seed) => void main() { group('buildAnonRegionsRequestFrame', () { - test('[57][pubkey32][ts4 LE][0x01][reply_path_len=0]', () { - final pub = Uint8List.fromList(List.generate(32, (i) => i + 1)); - final frame = buildAnonRegionsRequestFrame(pub, timestamp: 0x11223344); - expect(frame.length, 1 + 32 + 4 + 1 + 1); - expect(frame[0], cmdSendAnonReq); - expect(frame.sublist(1, 33), pub); - expect(frame.sublist(33, 37), [0x44, 0x33, 0x22, 0x11]); // LE timestamp - expect(frame[37], anonReqTypeRegions); - expect(frame[38], 0); // zero reply-path = zero-hop direct - }); + test( + '[57][pubkey32][0x01][reply_path_len=0] (firmware prepends the tag)', + () { + final pub = Uint8List.fromList(List.generate(32, (i) => i + 1)); + final frame = buildAnonRegionsRequestFrame(pub); + // No client timestamp: BaseChatMesh.sendAnonReq prepends the 4-byte tag, + // so the type byte must sit immediately after the 32-byte pubkey (#836). + expect(frame.length, 1 + 32 + 1 + 1); + expect(frame[0], cmdSendAnonReq); + expect(frame.sublist(1, 33), pub); + expect(frame[33], anonReqTypeRegions); + expect(frame[34], 0); // reply_path_len = 0 (zero-hop reply) + }, + ); }); group('flood-scope key frames', () {