diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index fd036cd6..54243b8a 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -3844,9 +3844,11 @@ class MeshCoreConnector extends ChangeNotifier { String? originalText, String? translatedLanguageCode, String? translationModelId, + String? region, ChannelMessage? replyTo, }) async { if (!isConnected || text.isEmpty) return; + final sendRegion = region ?? getEffectiveChannelRegion(channel.index); // Check if this is a reaction - if so, process it immediately instead of adding as a message final reactionInfo = ReactionHelper.parseReaction(text); @@ -3902,6 +3904,7 @@ class MeshCoreConnector extends ChangeNotifier { originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, + region: sendRegion, replyTo: replyTo, ); _addChannelMessage(channel.index, message); @@ -3922,7 +3925,7 @@ class MeshCoreConnector extends ChangeNotifier { ), channelSendQueueId: isResend ? null : message.messageId, ); - }, region: getEffectiveChannelRegion(channel.index)); + }, region: sendRegion); await transmit(); final settings = _appSettingsService?.settings; @@ -6220,6 +6223,7 @@ class MeshCoreConnector extends ChangeNotifier { pathHashWidth: packet.pathHashWidth, pathBytes: packet.pathBytes, channelIndex: channel.index, + region: _resolveTransportRegion(packet), packetHash: pktHash, ); @@ -6801,10 +6805,7 @@ class MeshCoreConnector extends ChangeNotifier { final hasTransport = routeType == _routeTransportFlood || routeType == _routeTransportDirect; - if (hasTransport) { - // Skip reserved bytes in transport header made up of two u16 fields - reader.skipBytes(4); - } + final transportCodes = hasTransport ? reader.readBytes(4) : null; final pathLenRaw = reader.readByte(); final pathByteLen = _decodePathByteLen(pathLenRaw); final pathBytes = reader.readBytes(pathByteLen); @@ -6816,6 +6817,7 @@ class MeshCoreConnector extends ChangeNotifier { payloadType: (header >> _phTypeShift) & _phTypeMask, payloadVer: (header >> _phVerShift) & _phVerMask, pathLenRaw: pathLenRaw, + transportCodes: transportCodes, pathBytes: pathBytes, payload: payload, ); @@ -6830,6 +6832,36 @@ class MeshCoreConnector extends ChangeNotifier { return digest[0]; } + String? _resolveTransportRegion(_RawPacket packet) { + if (packet.routeType != _routeTransportFlood || + packet.transportCodes == null) { + return null; + } + + // `foo` and `#foo` share a scope key, so dedupe without the prefix or a + // region listed both ways would always look ambiguous. + final candidates = { + for (final region in [ + ...RegionStore().loadRegions(), + ..._channelRegions.values, + _defaultRegion, + ]) + region.startsWith('#') ? region.substring(1) : region, + }.where((region) => region.trim().isNotEmpty).toList()..sort(); + String? match; + for (final region in candidates) { + final code = floodTransportCode( + scopeKey: floodScopeKeyForRegion(region), + payloadType: packet.payloadType, + payload: packet.payload, + ); + if (!_pathsEqual(code, packet.transportCodes!.sublist(0, 2))) continue; + if (match != null) return null; + match = region; + } + return match; + } + /// Firmware-compatible packet hash: SHA256(payloadType + payload) -> first 8 bytes as hex. String _computePacketHash(int payloadType, Uint8List payload) { final input = Uint8List(1 + payload.length); @@ -6979,6 +7011,7 @@ class MeshCoreConnector extends ChangeNotifier { pathBytes: message.pathBytes, pathVariants: message.pathVariants, channelIndex: message.channelIndex, + region: message.region, messageId: message.messageId, replyToMessageId: message.replyToMessageId ?? originalMessage!.messageId, @@ -7021,6 +7054,7 @@ class MeshCoreConnector extends ChangeNotifier { pathHashWidth: existing.pathHashWidth ?? processedMessage.pathHashWidth, pathBytes: mergedPathBytes, pathVariants: mergedPathVariants, + region: existing.region ?? processedMessage.region, packetHash: existing.packetHash ?? processedMessage.packetHash, // Mark as sent when first repeat is heard status: promotedFromPending @@ -7986,6 +8020,7 @@ class _RawPacket { final int payloadType; final int payloadVer; final int pathLenRaw; + final Uint8List? transportCodes; final Uint8List pathBytes; final Uint8List payload; @@ -7995,6 +8030,7 @@ class _RawPacket { required this.payloadType, required this.payloadVer, required this.pathLenRaw, + required this.transportCodes, required this.pathBytes, required this.payload, }); diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index c01eb8d1..f740969b 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -1081,9 +1081,29 @@ Uint8List buildSetFloodScopeFrame(String region) { return Uint8List.fromList([cmdSetFloodScope, 0]); } - final name = region.startsWith('#') ? region : '#$region'; - final hash = crypto.sha256.convert(utf8.encode(name)).bytes; - final scope = Uint8List.fromList(hash.sublist(0, 16)); + final scope = floodScopeKeyForRegion(region); return Uint8List.fromList([cmdSetFloodScope, 0, ...scope]); } + +Uint8List floodScopeKeyForRegion(String region) { + final name = region.startsWith('#') ? region : '#$region'; + final hash = crypto.sha256.convert(utf8.encode(name)).bytes; + return Uint8List.fromList(hash.sublist(0, 16)); +} + +Uint8List floodTransportCode({ + required Uint8List scopeKey, + required int payloadType, + required Uint8List payload, +}) { + final input = Uint8List(1 + payload.length) + ..[0] = payloadType + ..setRange(1, 1 + payload.length, payload); + final code = crypto.Hmac(crypto.sha256, scopeKey).convert(input).bytes; + if (code[0] == 0 && code[1] == 0) return Uint8List.fromList([1, 0]); + if (code[0] == 0xFF && code[1] == 0xFF) { + return Uint8List.fromList([0xFE, 0xFF]); + } + return Uint8List.fromList(code.sublist(0, 2)); +} diff --git a/lib/models/channel_message.dart b/lib/models/channel_message.dart index 3f1421cc..d3f64d1c 100644 --- a/lib/models/channel_message.dart +++ b/lib/models/channel_message.dart @@ -45,6 +45,7 @@ class ChannelMessage { final Uint8List pathBytes; final List pathVariants; final int? channelIndex; + final String? region; final String messageId; final String? packetHash; final String? replyToMessageId; @@ -71,6 +72,7 @@ class ChannelMessage { Uint8List? pathBytes, List? pathVariants, this.channelIndex, + this.region, String? messageId, this.packetHash, this.replyToMessageId, @@ -98,6 +100,7 @@ class ChannelMessage { int? pathHashWidth, Uint8List? pathBytes, List? pathVariants, + Object? region = _unset, String? packetHash, String? replyToMessageId, String? replyToSenderName, @@ -136,6 +139,7 @@ class ChannelMessage { pathBytes: pathBytes ?? this.pathBytes, pathVariants: pathVariants ?? this.pathVariants, channelIndex: channelIndex, + region: region == _unset ? this.region : region as String?, messageId: messageId, packetHash: packetHash ?? this.packetHash, replyToMessageId: replyToMessageId ?? this.replyToMessageId, @@ -242,6 +246,7 @@ class ChannelMessage { String? originalText, String? translatedLanguageCode, String? translationModelId, + String? region, ChannelMessage? replyTo, }) { return ChannelMessage( @@ -261,6 +266,7 @@ class ChannelMessage { pathBytes: Uint8List(0), pathVariants: const [], channelIndex: channelIndex, + region: region, ); } diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 2373b30f..e98cd98c 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -78,6 +78,7 @@ class _ChannelChatScreenState extends State { final ChatScrollController _scrollController = ChatScrollController(); final FocusNode _textFieldFocusNode = FocusNode(); ChannelMessage? _replyingToMessage; + bool _useReplyRegion = false; final CommunityStore _communityStore = CommunityStore(); final CommunityPskIndex _communityIndex = CommunityPskIndex(); final Map _messageKeys = {}; @@ -207,12 +208,14 @@ class _ChannelChatScreenState extends State { void _setReplyingTo(ChannelMessage message) { setState(() { _replyingToMessage = message; + _useReplyRegion = message.region?.isNotEmpty ?? false; }); } void _cancelReply() { setState(() { _replyingToMessage = null; + _useReplyRegion = false; }); } @@ -829,9 +832,41 @@ class _ChannelChatScreenState extends State { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ - RouteChip( - isDirect: (message.pathLength ?? -1) >= 0, - hops: displayHopCount, + Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + RouteChip( + isDirect: (message.pathLength ?? -1) >= 0, + hops: displayHopCount, + ), + if (message.region?.isNotEmpty ?? false) + Padding( + padding: const EdgeInsets.only(top: 2), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 2, + ), + decoration: BoxDecoration( + color: scheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular( + MeshRadii.xs, + ), + border: Border.all( + color: scheme.outlineVariant, + ), + ), + child: Text( + _displayRegion(message.region!), + style: MeshTheme.mono( + fontSize: 8.5 * textScale, + color: metaColor, + ), + ), + ), + ), + ], ), if (enableTracing) ...[ const SizedBox(width: 4), @@ -1841,6 +1876,7 @@ class _ChannelChatScreenState extends State { Widget _buildReplyBanner(double textScale) { final message = _replyingToMessage!; final scheme = Theme.of(context).colorScheme; + final replyRegion = message.region; return Container( width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), @@ -1878,6 +1914,40 @@ class _ChannelChatScreenState extends State { ], ), ), + if (replyRegion?.isNotEmpty ?? false) + InkWell( + borderRadius: BorderRadius.circular(MeshRadii.xs), + onTap: () => setState(() => _useReplyRegion = !_useReplyRegion), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3), + decoration: BoxDecoration( + color: _useReplyRegion + ? scheme.primaryContainer + : scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(MeshRadii.xs), + border: Border.all( + color: _useReplyRegion + ? scheme.primary + : scheme.outlineVariant, + ), + ), + child: Text( + context.l10n.channels_regionSetTo(replyRegion!), + style: + MeshTheme.mono( + fontSize: 10 * textScale, + color: _useReplyRegion + ? scheme.onPrimaryContainer + : scheme.onSurfaceVariant, + ).copyWith( + decoration: _useReplyRegion + ? null + : TextDecoration.lineThrough, + ), + ), + ), + ), + const SizedBox(width: 4), IconButton( icon: const Icon(Icons.close, size: 18), tooltip: context.l10n.chat_cancelReply, @@ -2196,6 +2266,7 @@ class _ChannelChatScreenState extends State { if (_replyingToMessage != null) { messageText = '@[${_replyingToMessage!.senderName}] $messageText'; } + final replyRegion = _useReplyRegion ? _replyingToMessage?.region : null; final maxBytes = maxChannelMessageBytes(connector.selfName); final outboundText = connector.prepareChannelOutboundText( @@ -2229,6 +2300,7 @@ class _ChannelChatScreenState extends State { originalText: originalText, translatedLanguageCode: translatedLanguageCode, translationModelId: translationModelId, + region: replyRegion, replyTo: replyTo, ); } @@ -2454,6 +2526,10 @@ class _ChannelChatScreenState extends State { return PathHelper.splitPathBytes(pathBytes, pathHashByteWidth).length; } + String _displayRegion(String region) { + return region.startsWith('#') ? region.substring(1) : region; + } + Future openRegionSelectDialog(Channel channel) async { // The AppBar subtitle reads the region from the connector inside a // Consumer, so setChannelRegion's notifyListeners refreshes it directly — diff --git a/lib/screens/channel_message_path_screen.dart b/lib/screens/channel_message_path_screen.dart index 3132bb46..44242745 100644 --- a/lib/screens/channel_message_path_screen.dart +++ b/lib/screens/channel_message_path_screen.dart @@ -211,6 +211,13 @@ class ChannelMessagePathScreen extends StatelessWidget { observedLabel, scheme: scheme, ), + if (message.region?.isNotEmpty ?? false) + _buildDetailRow( + context, + l10n.settings_regionName, + message.region!, + scheme: scheme, + ), ], ), ); diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart index 069588cb..dbb676ac 100644 --- a/lib/storage/channel_message_store.dart +++ b/lib/storage/channel_message_store.dart @@ -119,6 +119,7 @@ class ChannelMessageStore { 'isOutgoing': msg.isOutgoing, 'status': msg.status.index, 'channelIndex': msg.channelIndex, + 'region': msg.region, 'repeatCount': msg.repeatCount, 'pathLength': msg.pathLength, 'pathHashWidth': msg.pathHashWidth, @@ -203,6 +204,7 @@ class ChannelMessageStore { .toList() ?? const [], channelIndex: json['channelIndex'] as int?, + region: json['region'] as String?, messageId: json['messageId'] as String?, packetHash: json['packetHash'] as String?, replyToMessageId: json['replyToMessageId'] as String?, diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index fa834a4f..af67edd5 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'dart:typed_data'; +import 'package:crypto/crypto.dart' as crypto; import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; import 'package:meshcore_open/models/channel_message.dart'; @@ -148,6 +149,25 @@ void main() { }); }); + test('flood transport code uses the scope key HMAC', () { + final scopeKey = floodScopeKeyForRegion('Europe'); + final payload = Uint8List.fromList([0xA1, 0xB2, 0xC3]); + + expect( + floodTransportCode( + scopeKey: scopeKey, + payloadType: 0x05, + payload: payload, + ), + orderedEquals( + crypto.Hmac( + crypto.sha256, + scopeKey, + ).convert([0x05, ...payload]).bytes.sublist(0, 2), + ), + ); + }); + group('Contact.fromFrame — pathLen mapping', () { test('pathLen == 0 → pathLength == 0 (direct, NOT flood)', () { final frame = _buildContactFrame(pathLen: 0);