Merge pull request #1352 from OffbandMesh/fix/1270-nearby-width-dev

fix(#1270): cut the nearest-repeater hop at the packet's own width
pull/1359/head
Strycher 2 days ago committed by GitHub
commit 9c09e37a3f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -82,9 +82,10 @@ import 'caplog_reassembler.dart';
class DirectRepeater {
static const int maxAgeMinutes = 30; // Max age for direct repeater info
final int pubkeyFirstByte;
// Last-hop prefix at the device's configured path-hash width (1/2/3 bytes), so
// 2-/3-byte meshes display + match the full repeater prefix, not just 1 byte. (#151)
final Uint8List pubkeyPrefix;
// Last-hop prefix at the hop width the received packet itself used (1/2/3
// bytes), so 2-/3-byte meshes display + match the full repeater prefix, not
// just 1 byte (#151). The longest width heard for this repeater wins (#1270).
Uint8List pubkeyPrefix;
double snr;
DateTime lastUpdated;
@ -145,6 +146,11 @@ class DirectRepeater {
/// sub-threshold jitter refreshes the value silently and returns false. Fed
/// from every routed RX packet (not just adverts), so it tracks live traffic
/// rather than the ~12h advert cadence. (#150)
///
/// Packets name the same repeater at different widths (1, 2 or 3 bytes,
/// whatever each sender uses), so a prefix that starts another entry's
/// prefix, or is started by it, is that same repeater: it updates the entry
/// and the longer prefix is kept. (#1270)
static bool recordHop(
List<DirectRepeater> list,
Uint8List prefix,
@ -154,10 +160,12 @@ class DirectRepeater {
}) {
if (prefix.isEmpty) return false;
for (final r in list) {
if (_prefixEquals(r.pubkeyPrefix, prefix)) {
if (_sameRepeater(r.pubkeyPrefix, prefix)) {
final widened = prefix.length > r.pubkeyPrefix.length;
if (widened) r.pubkeyPrefix = Uint8List.fromList(prefix);
final moved = (r.snr - snr).abs() >= snrDelta;
r.update(snr);
return moved;
return moved || widened;
}
}
if (list.length >= cap) {
@ -178,9 +186,9 @@ class DirectRepeater {
return true;
}
static bool _prefixEquals(List<int> a, List<int> b) {
if (a.length != b.length) return false;
for (var i = 0; i < a.length; i++) {
static bool _sameRepeater(List<int> a, List<int> b) {
final n = a.length < b.length ? a.length : b.length;
for (var i = 0; i < n; i++) {
if (a[i] != b[i]) return false;
}
return true;
@ -12747,12 +12755,17 @@ class MeshCoreConnector extends ChangeNotifier {
final pathByteLen = _decodePathByteLen(pathLenRaw);
final pathBytes = packet.readBytes(pathByteLen);
final payload = packet.readBytes(packet.remaining);
// Each packet carries its own hop width; it need not match the width
// our radio sends. Splitting at the wrong one glues bytes of adjacent
// hops into IDs no repeater has. (#1270)
final hopWidth = pathHashSizeBytes(pathLenRaw);
// #186: feed the passive topology map from every routed packet's path,
// the same firehose that feeds nearest-repeater detection. Cheap: the
// path is already parsed here. Guarded so a topology-side fault can never
// stall the RX dispatch that also drives message handling.
if (pathBytes.isNotEmpty) {
// stall the RX dispatch that also drives message handling. Only packets
// at our own width: the graph builds traces, which route at that width.
if (pathBytes.isNotEmpty && hopWidth == _pathHashByteWidth) {
try {
final sp = _selfPublicKey;
if (sp != null) _topologyService?.setSelf(sp, _pathHashByteWidth);
@ -12776,6 +12789,7 @@ class MeshCoreConnector extends ChangeNotifier {
rawPacket,
payload,
pathBytes,
hopWidth,
routeType,
snr,
);
@ -12786,10 +12800,9 @@ class MeshCoreConnector extends ChangeNotifier {
// traffic, not just the ~12h advert cadence. SNR + path are already
// parsed above; recordHop is O(<=5) and notifies only on change.
if (pathBytes.isNotEmpty) {
final width = _pathHashByteWidth;
final prefix = Uint8List.fromList(
pathBytes.sublist(
pathBytes.length >= width ? pathBytes.length - width : 0,
pathBytes.length >= hopWidth ? pathBytes.length - hopWidth : 0,
),
);
if (DirectRepeater.recordHop(_directRepeaters, prefix, snr)) {
@ -12909,6 +12922,7 @@ class MeshCoreConnector extends ChangeNotifier {
Uint8List rawPacket,
Uint8List payload,
Uint8List path,
int hopWidth,
int routeType,
double snr,
) {
@ -12995,7 +13009,7 @@ class MeshCoreConnector extends ChangeNotifier {
} else {
_handleDiscovery(newContact, rawPacket);
}
_updateDirectRepeater(newContact, snr, path);
_updateDirectRepeater(newContact, snr, path, hopWidth);
return;
}
@ -13048,7 +13062,7 @@ class MeshCoreConnector extends ChangeNotifier {
_pathHistoryService!.handlePathUpdated(_contacts[existingIndex]);
}
_updateDirectRepeater(_contacts[existingIndex], snr, path);
_updateDirectRepeater(_contacts[existingIndex], snr, path, hopWidth);
appLogger.info(
'After merge: pathOverride=${_contacts[existingIndex].pathOverride}, devicePath=${_pathDiag(_contacts[existingIndex].path, _contacts[existingIndex].pathLength, _contacts[existingIndex].pathHashWidth)}',
@ -13057,16 +13071,22 @@ class MeshCoreConnector extends ChangeNotifier {
}
}
void _updateDirectRepeater(Contact contact, double snr, Uint8List path) {
void _updateDirectRepeater(
Contact contact,
double snr,
Uint8List path,
int hopWidth,
) {
// A chat/sensor advert with no path gives us no last-hop repeater to learn.
if ((contact.type == advTypeChat || contact.type == advTypeSensor) &&
path.isEmpty) {
return;
}
// The last hop's full configured-width prefix is the directly-heard
// repeater; fall back to the node's own prefix for a zero-hop advert. (#151)
final width = _pathHashByteWidth;
// The last hop, at the packet's own hop width, is the directly-heard
// repeater; fall back to the node's own prefix for a zero-hop advert.
// (#151, #1270)
final width = hopWidth;
final Uint8List prefix;
if (path.isNotEmpty) {
prefix = Uint8List.fromList(

@ -0,0 +1,223 @@
import 'dart:typed_data';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/services/mesh_topology_service.dart';
import 'package:meshcore_open/services/message_retry_service.dart';
import 'package:meshcore_open/services/path_history_service.dart';
import 'package:meshcore_open/services/storage_service.dart';
import 'package:meshcore_open/storage/drift/blob_store.dart';
import 'package:meshcore_open/storage/drift/offband_database.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
// #1270: every received packet says its own hop width in the high 2 bits of
// its path-length byte. Nearby Repeaters cut the last hop at the width OUR
// radio is set to send instead, so on a 3-byte radio one repeater (F2 83 9C...)
// heard through 1- and 2-byte packets showed up as several look-alike IDs
// (`11f283`, `d08af2`), each carrying bytes from the hop before it.
/// A path-length byte: hop count in the low 6 bits, width - 1 in the high 2.
int _pathLen(int hops, int width) => ((width - 1) << 6) | hops;
/// A PUSH_CODE_LOG_RX_DATA frame. routeType 0x01 keeps it off the
/// transport-code bytes.
Uint8List _rxFrame({
required int payloadType,
required int pathLenRaw,
required List<int> path,
required List<int> payload,
int snrQuarterDb = -12,
}) {
return (BytesBuilder()
..addByte(pushCodeLogRxData)
..addByte(snrQuarterDb & 0xFF)
..addByte(0) // rssi
..addByte((payloadType << 2) | 0x01)
..addByte(pathLenRaw)
..add(path)
..add(payload))
.toBytes();
}
Uint8List _u32(int v) =>
Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little);
List<int> _advertPayload(int keyByte, String name) =>
(BytesBuilder()
..add(List<int>.filled(32, keyByte))
..add(_u32(1790000000))
..add(List<int>.filled(64, 0))
..addByte(advTypeChat | 0x80)
..add(name.codeUnits)
..addByte(0))
.toBytes();
/// DEVICE_INFO long enough to carry the path-hash mode at byte 81.
Uint8List _deviceInfo({required int pathHashMode}) {
final frame = Uint8List(82);
frame[0] = respCodeDeviceInfo;
frame[1] = 14; // ver code
frame[2] = 100; // MAX_CONTACTS / 2
frame[3] = 8; // MAX_GROUP_CHANNELS
frame[81] = pathHashMode;
return frame;
}
void main() {
late OffbandDatabase db;
late MeshCoreConnector connector;
late MeshTopologyService topology;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
topology = MeshTopologyService();
connector = MeshCoreConnector();
connector.initialize(
retryService: MessageRetryService(),
pathHistoryService: PathHistoryService(StorageService()),
topologyService: topology,
);
connector.setSelfPublicKeyForTest(
Uint8List.fromList(List.filled(32, 0x0e)),
);
connector.sendFrameOverrideForTest = (_) {};
connector.setConnectedForTest();
connector.handleFrameForTest(_deviceInfo(pathHashMode: 2));
expect(connector.pathHashByteWidth, 3);
});
tearDown(() async {
BlobStore.clearTestOverride();
await db.close();
});
Set<String> prefixes() =>
connector.directRepeaters.map((r) => r.prefixHex).toSet();
test(
'a 2-byte packet names its own last hop, not a byte of the hop before',
() {
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeGRPTXT,
pathLenRaw: _pathLen(2, 2),
path: [0xa8, 0x11, 0xf2, 0x83],
payload: [1, 2, 3, 4],
),
);
expect(prefixes(), {'f283'});
},
);
test('a 1-byte packet names its own last hop, not the last three hops', () {
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeGRPTXT,
pathLenRaw: _pathLen(3, 1),
path: [0xd0, 0x8a, 0xf2],
payload: [1, 2, 3, 4],
),
);
expect(prefixes(), {'f2'});
});
test('one repeater heard at 1, 2 and 3 bytes is one entry', () {
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeGRPTXT,
pathLenRaw: _pathLen(2, 2),
path: [0xa8, 0x11, 0xf2, 0x83],
payload: [1, 2, 3, 4],
),
);
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeGRPTXT,
pathLenRaw: _pathLen(3, 1),
path: [0xd0, 0x8a, 0xf2],
payload: [1, 2, 3, 4],
),
);
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeGRPTXT,
pathLenRaw: _pathLen(1, 3),
path: [0xf2, 0x83, 0x9c],
payload: [1, 2, 3, 4],
),
);
expect(prefixes(), {'f2839c'});
});
test('an advert relayed through 2-byte hops names its own last hop', () {
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeADVERT,
pathLenRaw: _pathLen(2, 2),
path: [0xa8, 0x11, 0xf2, 0x83],
payload: _advertPayload(0x55, 'Echo'),
),
);
expect(prefixes(), {'f283'});
});
test('different repeaters stay separate entries', () {
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeGRPTXT,
pathLenRaw: _pathLen(1, 2),
path: [0xf2, 0x83],
payload: [1, 2, 3, 4],
),
);
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeGRPTXT,
pathLenRaw: _pathLen(1, 2),
path: [0xf2, 0x99],
payload: [1, 2, 3, 4],
),
);
expect(prefixes(), {'f283', 'f299'});
});
test('the topology map never learns hops split at the wrong width', () {
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeGRPTXT,
pathLenRaw: _pathLen(2, 2),
path: [0xa8, 0x11, 0xf2, 0x83],
payload: [1, 2, 3, 4],
),
);
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeGRPTXT,
pathLenRaw: _pathLen(3, 1),
path: [0xd0, 0x8a, 0xf2],
payload: [1, 2, 3, 4],
),
);
expect(topology.hasNode([0xa8, 0x11, 0xf2]), isFalse);
expect(topology.hasNode([0xd0, 0x8a, 0xf2]), isFalse);
connector.handleFrameForTest(
_rxFrame(
payloadType: payloadTypeGRPTXT,
pathLenRaw: _pathLen(2, 3),
path: [0x11, 0x22, 0x33, 0xf2, 0x83, 0x9c],
payload: [1, 2, 3, 4],
),
);
expect(topology.hasNode([0x11, 0x22, 0x33]), isTrue);
expect(topology.hasNode([0xf2, 0x83, 0x9c]), isTrue);
});
}
Loading…
Cancel
Save

Powered by TurnKey Linux.