Merge branch 'dev' into ez_disable_discoveredContact_eviction_PR
This commit is contained in:
195 files changed
+26503
-6523
No files matched your search
@@ -6,7 +6,7 @@ import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
void main() {
|
||||
// Frame layout per the doc comment on buildUpdateContactPathFrame:
|
||||
// [cmd][pub_key x32][type][flags][path_len][path x64][name x32]
|
||||
// [timestamp x4][Lat? x4, Lon? x4][timestamp? x4]
|
||||
// [last_advert x4][Lat? x4, Lon? x4][lastmod? x4]
|
||||
//
|
||||
// Base (mandatory) bytes:
|
||||
// 1 cmd + 32 pubKey + 1 type + 1 flags + 1 pathLen + 64 path
|
||||
@@ -101,5 +101,77 @@ void main() {
|
||||
expect(latBytes.getInt32(0, Endian.little), (49.123456 * 1e6).round());
|
||||
expect(lonBytes.getInt32(0, Endian.little), (-123.123456 * 1e6).round());
|
||||
});
|
||||
|
||||
int lastAdvertField(Uint8List frame) => ByteData.sublistView(
|
||||
frame,
|
||||
baseFrameLength - 4,
|
||||
baseFrameLength,
|
||||
).getUint32(0, Endian.little);
|
||||
|
||||
test('writes the contact advert timestamp, not the phone clock', () {
|
||||
final advert = DateTime.utc(2025, 6, 1, 12);
|
||||
final frame = buildUpdateContactPathFrame(
|
||||
pubKey,
|
||||
path,
|
||||
path.length,
|
||||
lastAdvert: advert,
|
||||
lastModified: DateTime.utc(2026, 1, 2),
|
||||
);
|
||||
|
||||
expect(lastAdvertField(frame), advert.millisecondsSinceEpoch ~/ 1000);
|
||||
expect(
|
||||
ByteData.sublistView(
|
||||
frame,
|
||||
baseFrameLength + 8,
|
||||
).getUint32(0, Endian.little),
|
||||
DateTime.utc(2026, 1, 2).millisecondsSinceEpoch ~/ 1000,
|
||||
);
|
||||
});
|
||||
|
||||
test('writes 0 for last advert when unknown', () {
|
||||
final frame = buildUpdateContactPathFrame(pubKey, path, path.length);
|
||||
expect(lastAdvertField(frame), 0);
|
||||
});
|
||||
});
|
||||
|
||||
group('auto-add / repeat freq frames', () {
|
||||
test('SET_AUTOADD_CONFIG appends max hops only when given', () {
|
||||
final withoutHops = buildSetAutoAddConfigFrame(
|
||||
autoAddChat: true,
|
||||
autoAddRepeater: false,
|
||||
autoAddRoomServer: false,
|
||||
autoAddSensor: false,
|
||||
overwriteOldest: true,
|
||||
);
|
||||
expect(withoutHops, [
|
||||
cmdSetAutoAddConfig,
|
||||
autoAddChatFlag | autoAddOverwriteOldestFlag,
|
||||
]);
|
||||
|
||||
final withHops = buildSetAutoAddConfigFrame(
|
||||
autoAddChat: false,
|
||||
autoAddRepeater: false,
|
||||
autoAddRoomServer: false,
|
||||
autoAddSensor: false,
|
||||
overwriteOldest: false,
|
||||
maxHops: 3,
|
||||
);
|
||||
expect(withHops, [cmdSetAutoAddConfig, 0, 3]);
|
||||
});
|
||||
|
||||
test('parses RESP_ALLOWED_REPEAT_FREQ ranges', () {
|
||||
final data = ByteData(1 + 16);
|
||||
data.setUint8(0, respCodeAllowedRepeatFreq);
|
||||
data.setUint32(1, 433000, Endian.little);
|
||||
data.setUint32(5, 433000, Endian.little);
|
||||
data.setUint32(9, 869495, Endian.little);
|
||||
data.setUint32(13, 869600, Endian.little);
|
||||
final ranges = parseAllowedRepeatFreqFrame(data.buffer.asUint8List());
|
||||
expect(ranges, [
|
||||
(lowKHz: 433000, highKHz: 433000),
|
||||
(lowKHz: 869495, highKHz: 869600),
|
||||
]);
|
||||
expect(buildGetAllowedRepeatFreqFrame(), [cmdGetAllowedRepeatFreq]);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
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/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Uint8List _contactFrame(int code, Uint8List key, String name) {
|
||||
final data = ByteData(1 + 32 + 3 + 64 + 32 + 4 + 12);
|
||||
final bytes = data.buffer.asUint8List();
|
||||
bytes[0] = code;
|
||||
bytes.setRange(1, 33, key);
|
||||
bytes[33] = advTypeChat;
|
||||
bytes[35] = 0xFF; // path unknown
|
||||
bytes.setRange(100, 100 + name.length, name.codeUnits);
|
||||
data.setUint32(132, 1700000000, Endian.little);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
final key = Uint8List.fromList(List<int>.generate(32, (i) => i + 1));
|
||||
|
||||
test('NEW_ADVERT is discovered only, not a firmware contact', () {
|
||||
final connector = MeshCoreConnector();
|
||||
connector.handleFrameForTest(_contactFrame(pushCodeNewAdvert, key, 'Bob'));
|
||||
|
||||
expect(connector.contacts, isEmpty);
|
||||
expect(connector.discoveredContacts.map((c) => c.name), contains('Bob'));
|
||||
});
|
||||
|
||||
test('CONTACT_DELETED removes the firmware contact', () {
|
||||
final connector = MeshCoreConnector();
|
||||
connector.handleFrameForTest(_contactFrame(respCodeContact, key, 'Bob'));
|
||||
expect(connector.contacts.length, 1);
|
||||
|
||||
connector.handleFrameForTest([pushCodeContactDeleted, ...key]);
|
||||
expect(connector.contacts, isEmpty);
|
||||
});
|
||||
|
||||
test('CONTACTS_FULL raises the storage-full signal', () async {
|
||||
final connector = MeshCoreConnector();
|
||||
final events = connector.contactsFullEvents.first;
|
||||
connector.handleFrameForTest([pushCodeContactsFull]);
|
||||
|
||||
expect(connector.contactsStorageFull, isTrue);
|
||||
await events;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/connector/pending_command_replies.dart';
|
||||
|
||||
void main() {
|
||||
Uint8List frame(List<int> bytes) => Uint8List.fromList(bytes);
|
||||
final keyA = Uint8List.fromList(List<int>.generate(32, (i) => i + 1));
|
||||
final keyB = Uint8List.fromList(List<int>.generate(32, (i) => i + 100));
|
||||
|
||||
PendingCommandReplies newQueue() =>
|
||||
PendingCommandReplies(staleAfter: const Duration(seconds: 10));
|
||||
|
||||
test('ERR goes to the oldest pending command (firmware order)', () {
|
||||
final queue = newQueue();
|
||||
final time = queue.track(buildSetDeviceTimeFrame(1));
|
||||
queue.track(buildSetAdvertNameFrame('x'));
|
||||
|
||||
final failed = queue.takeErr(6);
|
||||
expect(failed, same(time));
|
||||
expect(queue.takeOk()?.commandCode, cmdSetAdvertName);
|
||||
expect(queue.length, 0);
|
||||
});
|
||||
|
||||
test('OK skips commands whose success is a specific RESP_CODE', () {
|
||||
final queue = newQueue();
|
||||
queue.track(buildSendTextMsgFrame(keyA, 'hi'));
|
||||
queue.track(buildRemoveContactFrame(keyA));
|
||||
|
||||
expect(queue.takeOk()?.commandCode, cmdRemoveContact);
|
||||
expect(queue.completeReply(frame([respCodeSent, 0, 0, 0, 0, 0])), isTrue);
|
||||
expect(queue.length, 0);
|
||||
});
|
||||
|
||||
test('specific replies clear their entry so a later ERR is not misread', () {
|
||||
final queue = newQueue();
|
||||
queue.track(buildGetChannelFrame(0));
|
||||
queue.track(buildSetChannelFrame(1, 'c', Uint8List(16)));
|
||||
|
||||
expect(queue.completeReply(frame([respCodeChannelInfo, 0])), isTrue);
|
||||
expect(queue.takeErr(2)?.commandCode, cmdSetChannel);
|
||||
});
|
||||
|
||||
test('CONTACT only completes GET_CONTACT_BY_KEY for the same key', () {
|
||||
final queue = newQueue();
|
||||
queue.track(buildGetContactByKeyFrame(keyA));
|
||||
|
||||
expect(queue.completeReply(frame([respCodeContact, ...keyB])), isFalse);
|
||||
expect(queue.completeReply(frame([respCodeContact, ...keyA])), isTrue);
|
||||
expect(queue.length, 0);
|
||||
});
|
||||
|
||||
test('untracked commands are not enrolled', () {
|
||||
final queue = newQueue();
|
||||
expect(queue.track(buildSyncNextMessageFrame()), isNull);
|
||||
expect(queue.track(buildRebootFrame()), isNull);
|
||||
expect(queue.takeErr(1), isNull);
|
||||
});
|
||||
|
||||
test('awaited command completes with error on ERR', () async {
|
||||
final queue = newQueue();
|
||||
final pending = queue.track(
|
||||
buildSetRadioParamsFrame(869525, 250000, 11, 5),
|
||||
waitForReply: true,
|
||||
);
|
||||
queue.takeErr(6);
|
||||
await expectLater(pending!.completer!.future, throwsException);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:latlong2/latlong.dart';
|
||||
import 'package:meshcore_open/helpers/guessed_location_estimator.dart';
|
||||
|
||||
const _phoenix = (33.45, -112.07);
|
||||
const _casaGrande = (32.88, -111.76);
|
||||
const _flagstaff = (35.20, -111.65);
|
||||
const _london = (51.50, -0.12);
|
||||
|
||||
Uint8List _key(List<int> bytes) =>
|
||||
Uint8List.fromList([...bytes, ...List.filled(32 - bytes.length, 0)]);
|
||||
|
||||
GuessInput _input({
|
||||
required List<GuessCandidate> candidates,
|
||||
required List<(Uint8List, double, double)> anchors,
|
||||
(double, double)? self,
|
||||
}) => (
|
||||
candidates: candidates,
|
||||
anchors: anchors,
|
||||
selfPosition: self,
|
||||
maxRangeKm: null,
|
||||
);
|
||||
|
||||
GuessCandidate _node(List<(List<int>, int)> paths) =>
|
||||
(publicKey: _key([0x99]), paths: paths);
|
||||
|
||||
double _km((double, double) a, double lat, double lon) => const Distance().as(
|
||||
LengthUnit.Kilometer,
|
||||
LatLng(a.$1, a.$2),
|
||||
LatLng(lat, lon),
|
||||
);
|
||||
|
||||
void main() {
|
||||
test('places a node next to the repeater its path ends on', () {
|
||||
final result = estimateGuessedLocations(
|
||||
_input(
|
||||
candidates: [
|
||||
_node([
|
||||
([0xA1, 0xB2], 1),
|
||||
]),
|
||||
],
|
||||
anchors: [
|
||||
(_key([0xA1]), _phoenix.$1, _phoenix.$2),
|
||||
(_key([0xB2]), _casaGrande.$1, _casaGrande.$2),
|
||||
],
|
||||
self: _phoenix,
|
||||
),
|
||||
);
|
||||
|
||||
expect(result, hasLength(1));
|
||||
final (index, lat, lon, highConfidence) = result.single;
|
||||
expect(index, 0);
|
||||
expect(_km(_casaGrande, lat, lon), lessThan(1));
|
||||
expect(highConfidence, isFalse);
|
||||
});
|
||||
|
||||
test('resolves a colliding hop prefix to the repeater in range', () {
|
||||
// Two repeaters share prefix 0xB2: one in Tucson, one in London.
|
||||
final result = estimateGuessedLocations(
|
||||
_input(
|
||||
candidates: [
|
||||
_node([
|
||||
([0xA1, 0xB2], 1),
|
||||
]),
|
||||
],
|
||||
anchors: [
|
||||
(_key([0xA1]), _phoenix.$1, _phoenix.$2),
|
||||
(_key([0xB2]), _london.$1, _london.$2),
|
||||
(_key([0xB2, 0x01]), _casaGrande.$1, _casaGrande.$2),
|
||||
],
|
||||
self: _phoenix,
|
||||
),
|
||||
);
|
||||
|
||||
final (_, lat, lon, _) = result.single;
|
||||
expect(_km(_casaGrande, lat, lon), lessThan(1));
|
||||
});
|
||||
|
||||
test('skips an ambiguous prefix when there is no reference point', () {
|
||||
final result = estimateGuessedLocations(
|
||||
_input(
|
||||
candidates: [
|
||||
_node([
|
||||
([0xB2], 1),
|
||||
]),
|
||||
],
|
||||
anchors: [
|
||||
(_key([0xB2]), _london.$1, _london.$2),
|
||||
(_key([0xB2, 0x01]), _casaGrande.$1, _casaGrande.$2),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
expect(result, isEmpty);
|
||||
});
|
||||
|
||||
test('weights repeaters by how many paths ended on them', () {
|
||||
final result = estimateGuessedLocations(
|
||||
_input(
|
||||
candidates: [
|
||||
_node([
|
||||
([0xB2], 1),
|
||||
([0xB2], 1),
|
||||
([0xB2], 1),
|
||||
([0xC3], 1),
|
||||
]),
|
||||
],
|
||||
anchors: [
|
||||
(_key([0xB2]), _phoenix.$1, _phoenix.$2),
|
||||
(_key([0xC3]), _casaGrande.$1, _casaGrande.$2),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
final (_, lat, lon, highConfidence) = result.single;
|
||||
expect(highConfidence, isTrue);
|
||||
// Three votes for Phoenix, one for Tucson: a quarter of the way.
|
||||
expect(
|
||||
lat,
|
||||
closeTo(_phoenix.$1 + (_casaGrande.$1 - _phoenix.$1) / 4, 0.01),
|
||||
);
|
||||
expect(
|
||||
lon,
|
||||
closeTo(_phoenix.$2 + (_casaGrande.$2 - _phoenix.$2) / 4, 0.01),
|
||||
);
|
||||
});
|
||||
|
||||
test('result does not depend on path order', () {
|
||||
List<(int, double, double, bool)> run(List<(List<int>, int)> paths) =>
|
||||
estimateGuessedLocations(
|
||||
_input(
|
||||
candidates: [_node(paths)],
|
||||
anchors: [
|
||||
(_key([0xB2]), _phoenix.$1, _phoenix.$2),
|
||||
(_key([0xC3]), _flagstaff.$1, _flagstaff.$2),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
expect(
|
||||
run([
|
||||
([0xB2], 1),
|
||||
([0xC3], 1),
|
||||
]),
|
||||
run([
|
||||
([0xC3], 1),
|
||||
([0xB2], 1),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
test('drops a repeater too far from the others to share one node', () {
|
||||
final result = estimateGuessedLocations(
|
||||
_input(
|
||||
candidates: [
|
||||
_node([
|
||||
([0xB2], 1),
|
||||
([0xC3], 1),
|
||||
([0xD4], 1),
|
||||
]),
|
||||
],
|
||||
anchors: [
|
||||
(_key([0xB2]), _phoenix.$1, _phoenix.$2),
|
||||
(_key([0xC3]), _casaGrande.$1, _casaGrande.$2),
|
||||
(_key([0xD4]), _london.$1, _london.$2),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
final (_, lat, lon, _) = result.single;
|
||||
expect(lat, closeTo((_phoenix.$1 + _casaGrande.$1) / 2, 0.01));
|
||||
expect(lon, closeTo((_phoenix.$2 + _casaGrande.$2) / 2, 0.01));
|
||||
});
|
||||
|
||||
test('handles 2-byte hop hashes', () {
|
||||
final result = estimateGuessedLocations(
|
||||
_input(
|
||||
candidates: [
|
||||
_node([
|
||||
([0xA1, 0x01, 0xB2, 0x02], 2),
|
||||
]),
|
||||
],
|
||||
anchors: [
|
||||
(_key([0xA1, 0x01]), _phoenix.$1, _phoenix.$2),
|
||||
(_key([0xB2, 0x02]), _casaGrande.$1, _casaGrande.$2),
|
||||
(_key([0xB2, 0x03]), _flagstaff.$1, _flagstaff.$2),
|
||||
],
|
||||
self: _phoenix,
|
||||
),
|
||||
);
|
||||
|
||||
final (_, lat, lon, _) = result.single;
|
||||
expect(_km(_casaGrande, lat, lon), lessThan(1));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/helpers/utf8_length_limiter.dart';
|
||||
|
||||
TextEditingValue _value(String text, [int? cursor]) => TextEditingValue(
|
||||
text: text,
|
||||
selection: TextSelection.collapsed(offset: cursor ?? text.length),
|
||||
);
|
||||
|
||||
void main() {
|
||||
const formatter = Utf8LengthLimitingTextInputFormatter(5);
|
||||
|
||||
test('accepts edits within the limit', () {
|
||||
final result = formatter.formatEditUpdate(_value('ab'), _value('abc'));
|
||||
expect(result.text, 'abc');
|
||||
});
|
||||
|
||||
test('clips only the inserted text and keeps the end of the draft', () {
|
||||
// Paste "XYZ" at the start of "abc" (limit 5 bytes).
|
||||
final result = formatter.formatEditUpdate(
|
||||
_value('abc', 0),
|
||||
_value('XYZabc', 3),
|
||||
);
|
||||
expect(result.text, 'XYabc');
|
||||
expect(result.selection.baseOffset, 2);
|
||||
});
|
||||
|
||||
test('rejects an insertion in the middle when full', () {
|
||||
final result = formatter.formatEditUpdate(
|
||||
_value('abcde', 2),
|
||||
_value('abXcde', 3),
|
||||
);
|
||||
expect(result.text, 'abcde');
|
||||
expect(result.selection.baseOffset, 2);
|
||||
});
|
||||
|
||||
test('does not split a multi-code-point grapheme', () {
|
||||
// Family emoji is 18 UTF-8 bytes, so it cannot fit in the 4 bytes left.
|
||||
final result = formatter.formatEditUpdate(
|
||||
_value('a'),
|
||||
_value('a\u{1F468}\u{1F469}\u{1F467}'),
|
||||
);
|
||||
expect(result.text, 'a');
|
||||
});
|
||||
|
||||
test('keeps whole emoji that fit', () {
|
||||
const limiter = Utf8LengthLimitingTextInputFormatter(9);
|
||||
final result = limiter.formatEditUpdate(
|
||||
_value('a'),
|
||||
_value('a\u{1F600}\u{1F601}'),
|
||||
);
|
||||
expect(result.text, 'a\u{1F600}\u{1F601}');
|
||||
final clipped = const Utf8LengthLimitingTextInputFormatter(
|
||||
8,
|
||||
).formatEditUpdate(_value('a'), _value('a\u{1F600}\u{1F601}'));
|
||||
expect(clipped.text, 'a\u{1F600}');
|
||||
});
|
||||
|
||||
test('replacing one emoji with another sharing a surrogate stays valid', () {
|
||||
const limiter = Utf8LengthLimitingTextInputFormatter(5);
|
||||
final result = limiter.formatEditUpdate(
|
||||
_value('a\u{1F600}'),
|
||||
_value('a\u{1F601}\u{1F602}'),
|
||||
);
|
||||
expect(result.text, 'a\u{1F601}');
|
||||
});
|
||||
|
||||
test('allows deletions even when the text is already over the limit', () {
|
||||
final result = formatter.formatEditUpdate(
|
||||
_value('abcdefg'),
|
||||
_value('abcdef'),
|
||||
);
|
||||
expect(result.text, 'abcdef');
|
||||
});
|
||||
}
|
||||
@@ -956,6 +956,55 @@ void main() {
|
||||
});
|
||||
});
|
||||
|
||||
group('oversized data body', () {
|
||||
test('a 159-byte data body is rejected and parity cannot overrun', () {
|
||||
final failed = <ImageReassemblyFailure>[];
|
||||
final r = ImageReassembler(onFailed: failed.add);
|
||||
// Header: sender 0x1234, img 5, idx 0 of 2; body one byte past the cap.
|
||||
final oversized = Uint8List.fromList(<int>[
|
||||
0x12,
|
||||
0x34,
|
||||
5,
|
||||
(0 << 4) | 2,
|
||||
...List<int>.filled(kImageChunkBodyBytes + 1, 0xAA),
|
||||
]);
|
||||
expect(oversized.length, kImageChunkBlobBytes);
|
||||
expect(r.addChunk(oversized).status, ImageChunkStatus.malformed);
|
||||
expect(r.pendingCount, 0);
|
||||
|
||||
// A parity chunk for the same stream must not throw.
|
||||
final parity = Uint8List.fromList(<int>[
|
||||
0x12,
|
||||
0x34,
|
||||
5,
|
||||
(2 << 4) | 2,
|
||||
...List<int>.filled(kImageChunkBodyBytes + 1, 0x55),
|
||||
]);
|
||||
expect(() => r.addChunk(parity), returnsNormally);
|
||||
});
|
||||
});
|
||||
|
||||
group('clear()', () {
|
||||
test('reports in-progress streams as failed (disconnected)', () {
|
||||
final failed = <ImageReassemblyFailure>[];
|
||||
final r = ImageReassembler(onFailed: failed.add);
|
||||
final set = buildImageChunks(
|
||||
payload: payloadOf(400, seed: 3),
|
||||
metadata: stdMeta,
|
||||
senderPrefix: senderA,
|
||||
imgId: 8,
|
||||
);
|
||||
r.addChunk(set.blobs[0]);
|
||||
expect(r.pendingCount, 1);
|
||||
r.clear();
|
||||
expect(r.pendingCount, 0);
|
||||
expect(failed, hasLength(1));
|
||||
expect(failed.single.reason, ImageReassemblyFailureReason.disconnected);
|
||||
expect(failed.single.isCorrupt, isFalse);
|
||||
expect(r.evictExpired(now: DateTime(2100)), isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('completed-image map is capped', () {
|
||||
/// A lone parity chunk of a `total == 1` image completes that image by
|
||||
/// itself — one packet, one remembered entry. That is the amplification the
|
||||
|
||||
+63
-11
@@ -5,6 +5,7 @@ import 'package:meshcore_open/services/image_chunk_transport.dart';
|
||||
import 'package:meshcore_open/widgets/image_send_codec_binding.dart';
|
||||
import 'package:meshcore_open/models/radio_settings.dart';
|
||||
import 'package:meshcore_open/utils/lora_airtime.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart' as protocol;
|
||||
|
||||
double _ms(Duration d) => d.inMicroseconds / 1000.0;
|
||||
|
||||
@@ -22,24 +23,24 @@ RadioSettings _radio({
|
||||
|
||||
void main() {
|
||||
group('loraTimeOnAir reference values (255-byte packet)', () {
|
||||
test('SF9, CR 4/8, BW 250 kHz -> 975 ms', () {
|
||||
test('SF9, CR 4/8, BW 250 kHz -> 992 ms', () {
|
||||
final toa = loraTimeOnAir(
|
||||
payloadBytes: 255,
|
||||
spreadingFactor: 9,
|
||||
bandwidthHz: 250000,
|
||||
codingRate: 8,
|
||||
);
|
||||
expect(_ms(toa), closeTo(975, 1));
|
||||
expect(_ms(toa), closeTo(991.744, 1));
|
||||
});
|
||||
|
||||
test('SF10, CR 4/5, BW 250 kHz -> 1148 ms', () {
|
||||
test('SF10, CR 4/5, BW 250 kHz -> 1181 ms', () {
|
||||
final toa = loraTimeOnAir(
|
||||
payloadBytes: 255,
|
||||
spreadingFactor: 10,
|
||||
bandwidthHz: 250000,
|
||||
codingRate: 5,
|
||||
);
|
||||
expect(_ms(toa), closeTo(1148, 1));
|
||||
expect(_ms(toa), closeTo(1180.672, 1));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -52,8 +53,8 @@ void main() {
|
||||
codingRate: 5,
|
||||
);
|
||||
// DE = 1 -> denominator 4*(12-2) = 40 -> 51 * 5 = 255 payload symbols
|
||||
// ToA = (12.25 + 263) * 32.768 ms
|
||||
expect(_ms(toa), closeTo(9019.392, 1));
|
||||
// ToA = (20.25 + 263) * 32.768 ms
|
||||
expect(_ms(toa), closeTo(9281.536, 1));
|
||||
});
|
||||
|
||||
test('SF12 / BW 500 kHz does NOT engage LDRO (Tsym = 8.192 ms)', () {
|
||||
@@ -64,8 +65,8 @@ void main() {
|
||||
codingRate: 5,
|
||||
);
|
||||
// DE = 0 -> denominator 48 -> 43 * 5 = 215 payload symbols
|
||||
// ToA = (12.25 + 223) * 8.192 ms
|
||||
expect(_ms(toa), closeTo(1927.9296, 1));
|
||||
// ToA = (20.25 + 223) * 8.192 ms
|
||||
expect(_ms(toa), closeTo(1992.704, 1));
|
||||
});
|
||||
|
||||
test('SF11 / BW 250 kHz does NOT engage LDRO (Tsym = 8.192 ms)', () {
|
||||
@@ -77,9 +78,60 @@ void main() {
|
||||
codingRate: 5,
|
||||
);
|
||||
// DE = 0 -> denominator 44 -> 47 * 5 = 235 payload symbols
|
||||
// ToA = (12.25 + 243) * 8.192 ms
|
||||
expect(_ms(withSf11), closeTo(2091.008, 1));
|
||||
// ToA = (20.25 + 243) * 8.192 ms
|
||||
expect(_ms(withSf11), closeTo(2156.544, 1));
|
||||
});
|
||||
|
||||
test('calculateLoRaAirtime derives LDRO off for SF11 / BW 250 kHz', () {
|
||||
// cr is in the 1..4 domain here; 16-symbol preamble at SF11.
|
||||
expect(
|
||||
protocol.calculateLoRaAirtime(
|
||||
payloadBytes: 255,
|
||||
spreadingFactor: 11,
|
||||
bandwidthHz: 250000,
|
||||
codingRate: 1,
|
||||
),
|
||||
2157,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('preamble matches firmware (32 symbols <= SF8, 16 above)', () {
|
||||
test('meshCorePreambleSymbols', () {
|
||||
expect(meshCorePreambleSymbols(7), 32);
|
||||
expect(meshCorePreambleSymbols(8), 32);
|
||||
expect(meshCorePreambleSymbols(9), 16);
|
||||
expect(meshCorePreambleSymbols(12), 16);
|
||||
});
|
||||
|
||||
for (final sf in [7, 8, 9, 12]) {
|
||||
test('SF$sf default preamble equals explicit firmware length', () {
|
||||
final preamble = sf <= 8 ? 32 : 16;
|
||||
Duration toa({int? preambleSymbols}) => loraTimeOnAir(
|
||||
payloadBytes: 100,
|
||||
spreadingFactor: sf,
|
||||
bandwidthHz: 125000,
|
||||
codingRate: 5,
|
||||
preambleSymbols: preambleSymbols,
|
||||
);
|
||||
expect(toa(), toa(preambleSymbols: preamble));
|
||||
expect(
|
||||
protocol.calculateLoRaAirtime(
|
||||
payloadBytes: 100,
|
||||
spreadingFactor: sf,
|
||||
bandwidthHz: 125000,
|
||||
codingRate: 1,
|
||||
),
|
||||
protocol.calculateLoRaAirtime(
|
||||
payloadBytes: 100,
|
||||
spreadingFactor: sf,
|
||||
bandwidthHz: 125000,
|
||||
codingRate: 1,
|
||||
preambleSymbols: preamble,
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
group('airtime monotonicity / sanity', () {
|
||||
@@ -136,7 +188,7 @@ void main() {
|
||||
codingRate: normalizeCodingRate(8),
|
||||
);
|
||||
expect(a, b);
|
||||
expect(_ms(a), closeTo(975, 1));
|
||||
expect(_ms(a), closeTo(991.744, 1));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
|
||||
void main() {
|
||||
test('outgoing reply keeps the selected target, not the latest post', () {
|
||||
final older = ChannelMessage.outgoing('first post', 'Alice', 0);
|
||||
ChannelMessage.outgoing('second post', 'Alice', 0);
|
||||
|
||||
final reply = ChannelMessage.outgoing(
|
||||
'@[Alice] answer',
|
||||
'Me',
|
||||
0,
|
||||
replyTo: older,
|
||||
);
|
||||
|
||||
expect(reply.replyToMessageId, older.messageId);
|
||||
expect(reply.replyToSenderName, 'Alice');
|
||||
expect(reply.replyToText, 'first post');
|
||||
expect(
|
||||
ChannelMessage.parseReplyMention(reply.text)?.actualMessage,
|
||||
'answer',
|
||||
);
|
||||
});
|
||||
|
||||
test('outgoing message without reply has no reply target', () {
|
||||
final message = ChannelMessage.outgoing('hello', 'Me', 0);
|
||||
expect(message.replyToMessageId, isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/helpers/path_helper.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/storage/contact_discovery_store.dart';
|
||||
import 'package:meshcore_open/storage/contact_store.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Uint8List _contactFrame(int pathLen, List<int> path) {
|
||||
final writer = BytesBuilder();
|
||||
writer.addByte(respCodeContact);
|
||||
writer.add(List.generate(32, (i) => i + 1));
|
||||
writer.addByte(advTypeRepeater);
|
||||
writer.addByte(0);
|
||||
writer.addByte(pathLen);
|
||||
writer.add(Uint8List(64)..setRange(0, path.length, path));
|
||||
writer.add(Uint8List(32)..setRange(0, 4, 'Node'.codeUnits));
|
||||
writer.add([0x01, 0x00, 0x00, 0x00]);
|
||||
writer.add(Uint8List(12));
|
||||
return writer.toBytes();
|
||||
}
|
||||
|
||||
Contact _contact({required int pathHashWidth}) => Contact(
|
||||
publicKey: Uint8List.fromList(List.generate(32, (i) => i + 1)),
|
||||
name: 'Node',
|
||||
type: advTypeRepeater,
|
||||
pathLength: 2,
|
||||
path: Uint8List.fromList([0xA1, 0xA2, 0xB1, 0xB2]),
|
||||
pathHashWidth: pathHashWidth,
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(1000),
|
||||
);
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
group('Contact.fromFrame keeps the path hash width', () {
|
||||
test('2-byte hops', () {
|
||||
final contact = Contact.fromFrame(
|
||||
_contactFrame((1 << 6) | 2, [0xA1, 0xA2, 0xB1, 0xB2]),
|
||||
)!;
|
||||
expect(contact.pathLength, 2);
|
||||
expect(contact.pathHashWidth, 2);
|
||||
expect(contact.path, [0xA1, 0xA2, 0xB1, 0xB2]);
|
||||
expect(PathHelper.splitPathBytes(contact.path, contact.pathHashWidth), [
|
||||
[0xA1, 0xA2],
|
||||
[0xB1, 0xB2],
|
||||
]);
|
||||
});
|
||||
|
||||
test('3-byte hops', () {
|
||||
final contact = Contact.fromFrame(
|
||||
_contactFrame((2 << 6) | 1, [0xA1, 0xA2, 0xA3]),
|
||||
)!;
|
||||
expect(contact.pathLength, 1);
|
||||
expect(contact.pathHashWidth, 3);
|
||||
expect(contact.path, [0xA1, 0xA2, 0xA3]);
|
||||
});
|
||||
|
||||
test('flood defaults to width 1', () {
|
||||
final contact = Contact.fromFrame(_contactFrame(0xFF, const []))!;
|
||||
expect(contact.pathLength, -1);
|
||||
expect(contact.pathHashWidth, 1);
|
||||
});
|
||||
|
||||
test('copyWith preserves width', () {
|
||||
final contact = _contact(pathHashWidth: 2).copyWith(name: 'Renamed');
|
||||
expect(contact.pathHashWidth, 2);
|
||||
});
|
||||
});
|
||||
|
||||
group('Contact.inferPathHashWidth', () {
|
||||
test('divides bytes by hops', () {
|
||||
expect(Contact.inferPathHashWidth(2, 4), 2);
|
||||
expect(Contact.inferPathHashWidth(1, 3), 3);
|
||||
});
|
||||
|
||||
test('falls back to 1', () {
|
||||
expect(Contact.inferPathHashWidth(0, 0), 1);
|
||||
expect(Contact.inferPathHashWidth(-1, 0), 1);
|
||||
expect(Contact.inferPathHashWidth(2, 3), 1);
|
||||
expect(Contact.inferPathHashWidth(1, 4), 1);
|
||||
});
|
||||
});
|
||||
|
||||
group('Contact stores persist the path hash width', () {
|
||||
test('ContactStore round-trip', () async {
|
||||
final store = ContactStore()..publicKeyHex = '1234567890';
|
||||
await store.saveContacts([_contact(pathHashWidth: 2)]);
|
||||
final loaded = await store.loadContacts();
|
||||
expect(loaded.single.pathHashWidth, 2);
|
||||
expect(loaded.single.path, [0xA1, 0xA2, 0xB1, 0xB2]);
|
||||
});
|
||||
|
||||
test('ContactDiscoveryStore round-trip', () async {
|
||||
final store = ContactDiscoveryStore()..setPublicKeyHex = 'AABBCCDDEEFF00';
|
||||
await store.saveContacts([_contact(pathHashWidth: 2)]);
|
||||
final loaded = await store.loadContacts();
|
||||
expect(loaded.single.pathHashWidth, 2);
|
||||
});
|
||||
|
||||
test('legacy data without width is inferred from hops', () async {
|
||||
final store = ContactStore()..publicKeyHex = '1234567890';
|
||||
final json = {
|
||||
'publicKey': base64Encode(List.generate(32, (i) => i + 1)),
|
||||
'name': 'Legacy',
|
||||
'type': advTypeRepeater,
|
||||
'pathLength': 2,
|
||||
'path': base64Encode([0xA1, 0xA2, 0xB1, 0xB2]),
|
||||
'lastSeen': 1000,
|
||||
};
|
||||
await PrefsManager.instance.setString(store.keyFor, jsonEncode([json]));
|
||||
final loaded = await store.loadContacts();
|
||||
expect(loaded.single.pathHashWidth, 2);
|
||||
});
|
||||
|
||||
test('legacy flood data without width falls back to 1', () async {
|
||||
final store = ContactStore()..publicKeyHex = '1234567890';
|
||||
final json = {
|
||||
'publicKey': base64Encode(List.generate(32, (i) => i + 1)),
|
||||
'name': 'Legacy',
|
||||
'type': advTypeRepeater,
|
||||
'pathLength': -1,
|
||||
'path': base64Encode(const <int>[]),
|
||||
'lastSeen': 1000,
|
||||
};
|
||||
await PrefsManager.instance.setString(store.keyFor, jsonEncode([json]));
|
||||
final loaded = await store.loadContacts();
|
||||
expect(loaded.single.pathHashWidth, 1);
|
||||
});
|
||||
|
||||
test('legacy mode-encoded pathLength yields its width', () async {
|
||||
final store = ContactStore()..publicKeyHex = '1234567890';
|
||||
final json = {
|
||||
'publicKey': base64Encode(List.generate(32, (i) => i + 1)),
|
||||
'name': 'Legacy',
|
||||
'type': advTypeRepeater,
|
||||
'pathLength': (2 << 6) | 1,
|
||||
'path': base64Encode([0xA1, 0xA2, 0xA3]),
|
||||
'lastSeen': 1000,
|
||||
};
|
||||
await PrefsManager.instance.setString(store.keyFor, jsonEncode([json]));
|
||||
final loaded = await store.loadContacts();
|
||||
expect(loaded.single.pathLength, 1);
|
||||
expect(loaded.single.pathHashWidth, 3);
|
||||
});
|
||||
});
|
||||
|
||||
group('ChannelMessage.fromFrame path_len 0xFF (direct)', () {
|
||||
Uint8List frame({required bool v3}) {
|
||||
final writer = BytesBuilder();
|
||||
if (v3) {
|
||||
writer.add([respCodeChannelMsgRecvV3, 0x10, 0x01, 0x00]);
|
||||
} else {
|
||||
writer.addByte(respCodeChannelMsgRecv);
|
||||
}
|
||||
writer.addByte(3); // channel index
|
||||
writer.addByte(0xFF);
|
||||
writer.addByte(txtTypePlain);
|
||||
writer.add([0x01, 0x00, 0x00, 0x00]);
|
||||
writer.add(utf8.encode('Alice: hi'));
|
||||
writer.addByte(0);
|
||||
return writer.toBytes();
|
||||
}
|
||||
|
||||
test('V3 does not read 63 x 4-byte hops', () {
|
||||
final message = ChannelMessage.fromFrame(frame(v3: true))!;
|
||||
expect(message.text, 'hi');
|
||||
expect(message.senderName, 'Alice');
|
||||
expect(message.pathLength, isNull);
|
||||
expect(message.pathBytes, isEmpty);
|
||||
expect(message.pathHashWidth, isNull);
|
||||
expect(message.channelIndex, 3);
|
||||
});
|
||||
|
||||
test('non-V3 reads path_len unsigned', () {
|
||||
final message = ChannelMessage.fromFrame(frame(v3: false))!;
|
||||
expect(message.text, 'hi');
|
||||
expect(message.pathLength, isNull);
|
||||
});
|
||||
});
|
||||
|
||||
test('PathHelper treats width 4 as invalid and clamps to 3', () {
|
||||
expect(PathHelper.splitPathBytes([1, 2, 3, 4], 4), [
|
||||
[1, 2, 3],
|
||||
[4],
|
||||
]);
|
||||
});
|
||||
|
||||
test('buildSetPathHashModeFrame rejects reserved mode 3', () {
|
||||
expect(buildSetPathHashModeFrame(3), [cmdSetPathHashMode, 0, 2]);
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
@@ -621,7 +641,8 @@ void main() {
|
||||
test(
|
||||
'ContactDiscoveryStore decodes and migrates legacy mode-encoded paths',
|
||||
() async {
|
||||
final store = ContactDiscoveryStore();
|
||||
final store = ContactDiscoveryStore()
|
||||
..setPublicKeyHex = 'AABBCCDDEEFF00112233';
|
||||
|
||||
final rawPath = Uint8List(64)
|
||||
..[0] = 0x11
|
||||
@@ -646,6 +667,8 @@ void main() {
|
||||
expect(contacts, hasLength(1));
|
||||
expect(contacts.first.pathLength, equals(1));
|
||||
expect(contacts.first.path, equals(Uint8List.fromList([0x11, 0x22])));
|
||||
expect(prefs.getString('discovered_contacts'), isNull);
|
||||
expect(prefs.getString(store.keyFor), isNotNull);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/remote_node_stats.dart';
|
||||
|
||||
Uint8List _frame(int statsSize, void Function(ByteData stats) fill) {
|
||||
final frame = Uint8List(RemoteNodeStats.payloadOffset + statsSize);
|
||||
fill(ByteData.sublistView(frame, RemoteNodeStats.payloadOffset));
|
||||
return frame;
|
||||
}
|
||||
|
||||
void _fillCommon(ByteData d) {
|
||||
d.setUint16(0, 4100, Endian.little);
|
||||
d.setInt16(4, -110, Endian.little);
|
||||
d.setUint32(16, 300, Endian.little);
|
||||
d.setUint32(20, 3600, Endian.little);
|
||||
d.setInt16(42, -22, Endian.little);
|
||||
d.setUint16(46, 9, Endian.little);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('decodes repeater stats with rx airtime and recv errors', () {
|
||||
final frame = _frame(56, (d) {
|
||||
_fillCommon(d);
|
||||
d.setUint32(48, 120, Endian.little);
|
||||
d.setUint32(52, 7, Endian.little);
|
||||
});
|
||||
final stats = RemoteNodeStats.tryParse(frame, isRoom: false)!;
|
||||
expect(stats.batteryMv, 4100);
|
||||
expect(stats.noiseFloor, -110);
|
||||
expect(stats.txAirSecs, 300);
|
||||
expect(stats.uptimeSecs, 3600);
|
||||
expect(stats.lastSnr, -5.5);
|
||||
expect(stats.floodDups, 9);
|
||||
expect(stats.rxAirSecs, 120);
|
||||
expect(stats.recvErrors, 7);
|
||||
expect(stats.posted, isNull);
|
||||
});
|
||||
|
||||
test('older repeater frame without recv errors', () {
|
||||
final frame = _frame(52, (d) {
|
||||
_fillCommon(d);
|
||||
d.setUint32(48, 120, Endian.little);
|
||||
});
|
||||
final stats = RemoteNodeStats.tryParse(frame, isRoom: false)!;
|
||||
expect(stats.rxAirSecs, 120);
|
||||
expect(stats.recvErrors, isNull);
|
||||
});
|
||||
|
||||
test('decodes room server posted / pushed counters', () {
|
||||
final frame = _frame(52, (d) {
|
||||
_fillCommon(d);
|
||||
d.setUint16(48, 42, Endian.little);
|
||||
d.setUint16(50, 17, Endian.little);
|
||||
});
|
||||
final stats = RemoteNodeStats.tryParse(frame, isRoom: true)!;
|
||||
expect(stats.posted, 42);
|
||||
expect(stats.postPushes, 17);
|
||||
expect(stats.rxAirSecs, isNull);
|
||||
expect(stats.recvErrors, isNull);
|
||||
});
|
||||
|
||||
test('rejects frames shorter than the common layout', () {
|
||||
expect(RemoteNodeStats.tryParse(Uint8List(50), isRoom: false), isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/review_mode/review_radio.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/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({
|
||||
'stale_key_${ReviewRadio.storagePrefix}': 'stale',
|
||||
'unrelated_key': 'keep',
|
||||
});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
test('disconnect during connectReview cancels quietly', () async {
|
||||
final connector = MeshCoreConnector();
|
||||
addTearDown(connector.dispose);
|
||||
final retryService = MessageRetryService();
|
||||
addTearDown(retryService.dispose);
|
||||
connector.initialize(
|
||||
retryService: retryService,
|
||||
pathHistoryService: PathHistoryService(StorageService()),
|
||||
);
|
||||
ReviewRadio? created;
|
||||
connector.reviewRadioFactoryForTest = () => created = ReviewRadio(
|
||||
scheduledMessageInterval: const Duration(milliseconds: 50),
|
||||
);
|
||||
|
||||
final connecting = connector.connectReview();
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
await connector.disconnect(manual: true);
|
||||
await connecting;
|
||||
|
||||
expect(connector.isConnected, isFalse);
|
||||
expect(connector.isReviewMode, isFalse);
|
||||
expect(
|
||||
PrefsManager.instance.getKeys().where(
|
||||
(k) => k.contains(ReviewRadio.storagePrefix),
|
||||
),
|
||||
isEmpty,
|
||||
);
|
||||
// Whether or not the radio was created, nothing keeps it running.
|
||||
created?.sendTestMessage();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
expect(connector.isConnected, isFalse);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/models/message.dart';
|
||||
import 'package:meshcore_open/review_mode/review_radio.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/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
Future<void> _waitFor(bool Function() condition, {int seconds = 8}) async {
|
||||
final end = DateTime.now().add(Duration(seconds: seconds));
|
||||
while (!condition()) {
|
||||
if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 25));
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({
|
||||
'stale_key_${ReviewRadio.storagePrefix}': 'stale',
|
||||
'unrelated_key': 'keep',
|
||||
// A legacy unscoped key that the contact store migrates into whichever
|
||||
// radio scope loads first. Review mode must not keep it.
|
||||
'contacts': '[]',
|
||||
});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
test('connectReview syncs, auto-replies, and disconnect cleans up', () async {
|
||||
final connector = MeshCoreConnector();
|
||||
addTearDown(connector.dispose);
|
||||
final retryService = MessageRetryService();
|
||||
addTearDown(retryService.dispose);
|
||||
connector.initialize(
|
||||
retryService: retryService,
|
||||
pathHistoryService: PathHistoryService(StorageService()),
|
||||
);
|
||||
connector.reviewRadioFactoryForTest = () => ReviewRadio(
|
||||
scheduledMessageInterval: const Duration(hours: 1),
|
||||
ackDelay: const Duration(milliseconds: 100),
|
||||
replyDelay: const Duration(milliseconds: 200),
|
||||
);
|
||||
|
||||
await connector.connectReview();
|
||||
|
||||
expect(connector.isConnected, isTrue);
|
||||
expect(connector.isReviewMode, isTrue);
|
||||
expect(connector.activeTransport, MeshCoreTransportType.review);
|
||||
// Stale data from a previous session is wiped on connect.
|
||||
expect(
|
||||
PrefsManager.instance.containsKey(
|
||||
'stale_key_${ReviewRadio.storagePrefix}',
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
expect(PrefsManager.instance.getString('unrelated_key'), 'keep');
|
||||
|
||||
await _waitFor(
|
||||
() => connector.contacts.length >= 6 && connector.channels.length >= 3,
|
||||
);
|
||||
expect(connector.channels.map((c) => c.name), contains('Hiking Group'));
|
||||
|
||||
final contact = connector.contacts.firstWhere((c) => c.name == 'Maya');
|
||||
await _waitFor(() => connector.getMessages(contact).isNotEmpty);
|
||||
final seeded = connector.getMessages(contact).length;
|
||||
|
||||
await connector.sendMessage(contact, 'hello from test');
|
||||
await _waitFor(
|
||||
() => connector
|
||||
.getMessages(contact)
|
||||
.any(
|
||||
(m) =>
|
||||
m.isOutgoing &&
|
||||
m.text == 'hello from test' &&
|
||||
m.status == MessageStatus.delivered,
|
||||
),
|
||||
);
|
||||
await _waitFor(() => connector.getMessages(contact).length >= seeded + 2);
|
||||
expect(connector.getMessages(contact).last.isOutgoing, isFalse);
|
||||
|
||||
await connector.disconnect(manual: true);
|
||||
|
||||
expect(connector.isReviewMode, isFalse);
|
||||
expect(connector.isConnected, isFalse);
|
||||
expect(connector.activeTransport, isNot(MeshCoreTransportType.review));
|
||||
final leftover = PrefsManager.instance.getKeys().where(
|
||||
(k) => k.contains(ReviewRadio.storagePrefix),
|
||||
);
|
||||
expect(leftover, isEmpty);
|
||||
expect(PrefsManager.instance.getString('unrelated_key'), 'keep');
|
||||
expect(PrefsManager.instance.getString('contacts'), '[]');
|
||||
|
||||
// Frames after teardown must not resurrect anything.
|
||||
connector.sendReviewTestMessage();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 300));
|
||||
expect(connector.isReviewMode, isFalse);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/review_mode/review_mode_storage.dart';
|
||||
import 'package:meshcore_open/review_mode/review_radio.dart';
|
||||
import 'package:meshcore_open/services/app_settings_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/contact_store.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
// Separate file: NotificationService is a singleton whose reply stream can
|
||||
// only be listened to by one connector per isolate.
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() async {
|
||||
SharedPreferences.setMockInitialValues({'unrelated_key': 'keep'});
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
});
|
||||
|
||||
test('channel mutes made in review mode are undone on exit', () async {
|
||||
final settings = AppSettingsService();
|
||||
await settings.loadSettings();
|
||||
await settings.muteChannel('Hiking Group');
|
||||
final connector = MeshCoreConnector();
|
||||
addTearDown(connector.dispose);
|
||||
final retryService = MessageRetryService();
|
||||
addTearDown(retryService.dispose);
|
||||
connector.initialize(
|
||||
retryService: retryService,
|
||||
pathHistoryService: PathHistoryService(StorageService()),
|
||||
appSettingsService: settings,
|
||||
);
|
||||
connector.reviewRadioFactoryForTest = () =>
|
||||
ReviewRadio(scheduledMessageInterval: const Duration(hours: 1));
|
||||
|
||||
await connector.connectReview();
|
||||
// Mutes are keyed by channel name, so these would leak into real radios.
|
||||
await settings.muteChannel('Public');
|
||||
await settings.unmuteChannel('Hiking Group');
|
||||
// Other app preferences are the user's to change, even while reviewing.
|
||||
await PrefsManager.instance.setString('unrelated_key', 'changed');
|
||||
|
||||
await connector.disconnect(manual: true);
|
||||
|
||||
expect(settings.isChannelMuted('Public'), isFalse);
|
||||
expect(settings.isChannelMuted('Hiking Group'), isTrue);
|
||||
expect(PrefsManager.instance.getString('unrelated_key'), 'changed');
|
||||
|
||||
// A fresh launch has nothing left to undo.
|
||||
final relaunched = AppSettingsService();
|
||||
await relaunched.loadSettings();
|
||||
await endReviewModeSession(relaunched);
|
||||
expect(relaunched.isChannelMuted('Public'), isFalse);
|
||||
expect(relaunched.isChannelMuted('Hiking Group'), isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'a session interrupted by the app being killed is undone at startup',
|
||||
() async {
|
||||
final settings = AppSettingsService();
|
||||
await settings.loadSettings();
|
||||
await settings.muteChannel('Hiking Group');
|
||||
|
||||
await beginReviewModeSession(settings);
|
||||
await settings.muteChannel('Public');
|
||||
await settings.unmuteChannel('Hiking Group');
|
||||
await PrefsManager.instance.setString(
|
||||
'contacts${ReviewRadio.storagePrefix}',
|
||||
'[]',
|
||||
);
|
||||
// The app is killed here: no disconnect, no cleanup.
|
||||
|
||||
final relaunched = AppSettingsService();
|
||||
await relaunched.loadSettings();
|
||||
expect(relaunched.isChannelMuted('Public'), isTrue);
|
||||
await endReviewModeSession(relaunched);
|
||||
|
||||
expect(relaunched.isChannelMuted('Public'), isFalse);
|
||||
expect(relaunched.isChannelMuted('Hiking Group'), isTrue);
|
||||
expect(
|
||||
PrefsManager.instance.getKeys().where(
|
||||
(k) => k.contains(ReviewRadio.storagePrefix),
|
||||
),
|
||||
isEmpty,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('the review scope never adopts legacy unscoped data', () async {
|
||||
await PrefsManager.instance.setString('contacts', '[]');
|
||||
await beginReviewModeSession(null);
|
||||
|
||||
final store = ContactStore()
|
||||
..setPublicKeyHex = ReviewRadio.selfPublicKeyHex;
|
||||
await store.loadContacts();
|
||||
expect(PrefsManager.instance.getString('contacts'), '[]');
|
||||
|
||||
final realRadio = ContactStore()..setPublicKeyHex = 'ab' * 32;
|
||||
await realRadio.loadContacts();
|
||||
expect(PrefsManager.instance.containsKey('contacts'), isFalse);
|
||||
expect(PrefsManager.instance.getString(realRadio.keyFor), '[]');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/models/channel.dart';
|
||||
import 'package:meshcore_open/models/channel_message.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/review_mode/review_radio.dart';
|
||||
import 'package:meshcore_open/review_mode/review_script.dart';
|
||||
import 'package:meshcore_open/services/message_retry_service.dart';
|
||||
|
||||
const _tick = Duration(milliseconds: 60);
|
||||
|
||||
class _Harness {
|
||||
final ReviewRadio radio;
|
||||
final List<Uint8List> frames = [];
|
||||
late final StreamSubscription<Uint8List> _sub;
|
||||
|
||||
_Harness(this.radio) {
|
||||
_sub = radio.frames.listen(frames.add);
|
||||
}
|
||||
|
||||
Future<void> settle([Duration d = _tick]) => Future<void>.delayed(d);
|
||||
|
||||
Future<List<Uint8List>> request(Uint8List frame) async {
|
||||
frames.clear();
|
||||
radio.handle(frame);
|
||||
await settle();
|
||||
return List<Uint8List>.of(frames);
|
||||
}
|
||||
|
||||
Future<void> close() async {
|
||||
await _sub.cancel();
|
||||
radio.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
ReviewRadio _fastRadio() => ReviewRadio(
|
||||
scheduledMessageInterval: const Duration(milliseconds: 40),
|
||||
ackDelay: const Duration(milliseconds: 100),
|
||||
replyDelay: const Duration(milliseconds: 200),
|
||||
);
|
||||
|
||||
void main() {
|
||||
test('public key constants are consistent', () {
|
||||
expect(ReviewRadio.selfPublicKeyHex.length, 64);
|
||||
expect(ReviewRadio.selfPublicKeyHex.startsWith('ee5e'), isTrue);
|
||||
expect(
|
||||
ReviewRadio.selfPublicKeyHex,
|
||||
ReviewRadio.selfPublicKeyHex.toLowerCase(),
|
||||
);
|
||||
expect(
|
||||
ReviewRadio.storagePrefix,
|
||||
ReviewRadio.selfPublicKeyHex.substring(0, 10),
|
||||
);
|
||||
});
|
||||
|
||||
test('responses are never synchronous', () async {
|
||||
final h = _Harness(ReviewRadio());
|
||||
h.radio.handle(buildAppStartFrame());
|
||||
expect(h.frames, isEmpty);
|
||||
await h.settle();
|
||||
expect(h.frames, hasLength(1));
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('handshake replies with SELF_INFO and DEVICE_INFO', () async {
|
||||
final h = _Harness(ReviewRadio());
|
||||
|
||||
final self = (await h.request(buildAppStartFrame())).single;
|
||||
expect(self[0], respCodeSelfInfo);
|
||||
final reader = BufferReader(self)..skipBytes(4);
|
||||
expect(
|
||||
pubKeyToHex(reader.readBytes(pubKeySize)),
|
||||
ReviewRadio.selfPublicKeyHex,
|
||||
);
|
||||
expect(reader.readInt32LE(), ReviewScript.selfLatitudeE6);
|
||||
expect(reader.readInt32LE(), ReviewScript.selfLongitudeE6);
|
||||
reader.skipBytes(4);
|
||||
expect(reader.readUInt32LE(), 910525000);
|
||||
expect(reader.readUInt32LE(), 62500);
|
||||
expect(reader.readByte(), 7);
|
||||
expect(reader.readByte(), 5);
|
||||
expect(reader.readCString(), 'Review Radio');
|
||||
|
||||
final info = (await h.request(buildDeviceQueryFrame())).single;
|
||||
expect(info[0], respCodeDeviceInfo);
|
||||
expect(info.length, 82);
|
||||
expect(info[1], ReviewScript.firmwareVerCode);
|
||||
expect(info[2] * 2, ReviewScript.maxContacts);
|
||||
expect(info[3], ReviewScript.maxChannels);
|
||||
expect(
|
||||
String.fromCharCodes(info.sublist(20, 40)),
|
||||
startsWith('MeshCore Open Review'),
|
||||
);
|
||||
expect(String.fromCharCodes(info.sublist(60, 66)), 'review');
|
||||
expect(info[81], 0);
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('contact list parses with the app Contact parser', () async {
|
||||
final h = _Harness(ReviewRadio());
|
||||
final out = await h.request(buildGetContactsFrame());
|
||||
|
||||
expect(out.first[0], respCodeContactsStart);
|
||||
expect(readUint32LE(out.first, 1), ReviewScript.contacts.length);
|
||||
expect(out.last[0], respCodeEndOfContacts);
|
||||
final contacts = out.sublist(1, out.length - 1);
|
||||
expect(contacts, hasLength(6));
|
||||
for (final f in contacts) {
|
||||
expect(f.length, contactFrameSize);
|
||||
}
|
||||
final parsed = contacts.map((f) => Contact.fromFrame(f)!).toList();
|
||||
expect(parsed.map((c) => c.name), ReviewScript.contacts.map((c) => c.name));
|
||||
expect(parsed.where((c) => c.type == advTypeChat), hasLength(4));
|
||||
expect(parsed.where((c) => c.type == advTypeRepeater), hasLength(1));
|
||||
expect(parsed.where((c) => c.type == advTypeRoom), hasLength(1));
|
||||
expect(parsed[1].pathLength, 2);
|
||||
expect(parsed[0].latitude, closeTo(45.5231, 1e-6));
|
||||
expect(parsed.map((c) => c.publicKeyHex).toSet(), hasLength(6));
|
||||
|
||||
// Incremental sync with a current 'since' returns nothing new.
|
||||
final since = readUint32LE(out.last, 1);
|
||||
final incremental = await h.request(buildGetContactsFrame(since: since));
|
||||
expect(incremental, hasLength(2));
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('get contact by key returns the contact or ERR', () async {
|
||||
final h = _Harness(ReviewRadio());
|
||||
final key = hexToPubKey(ReviewScript.contacts[2].publicKeyHex);
|
||||
final found = (await h.request(buildGetContactByKeyFrame(key))).single;
|
||||
expect(Contact.fromFrame(found)!.name, 'Sam');
|
||||
|
||||
final missing = (await h.request(
|
||||
buildGetContactByKeyFrame(Uint8List(pubKeySize)..fillRange(0, 32, 9)),
|
||||
)).single;
|
||||
expect(missing[0], respCodeErr);
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('channel info for configured and empty slots', () async {
|
||||
final h = _Harness(ReviewRadio());
|
||||
final pub = Channel.fromFrame(
|
||||
(await h.request(buildGetChannelFrame(0))).single,
|
||||
)!;
|
||||
expect(pub.name, 'Public');
|
||||
expect(pub.isPublicChannel, isTrue);
|
||||
final hiking = Channel.fromFrame(
|
||||
(await h.request(buildGetChannelFrame(1))).single,
|
||||
)!;
|
||||
expect(hiking.name, 'Hiking Group');
|
||||
expect(hiking.isPublicChannel, isFalse);
|
||||
final local = Channel.fromFrame(
|
||||
(await h.request(buildGetChannelFrame(2))).single,
|
||||
)!;
|
||||
expect(local.name, 'Local Net');
|
||||
final empty = Channel.fromFrame(
|
||||
(await h.request(buildGetChannelFrame(5))).single,
|
||||
)!;
|
||||
expect(empty.isEmpty, isTrue);
|
||||
|
||||
await h.request(
|
||||
buildSetChannelFrame(
|
||||
4,
|
||||
'New One',
|
||||
Uint8List.fromList(List.filled(16, 7)),
|
||||
),
|
||||
);
|
||||
final added = Channel.fromFrame(
|
||||
(await h.request(buildGetChannelFrame(4))).single,
|
||||
)!;
|
||||
expect(added.name, 'New One');
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('seed history drains through SYNC_NEXT_MESSAGE', () async {
|
||||
final h = _Harness(ReviewRadio());
|
||||
final direct = <ParsedContactText>[];
|
||||
final channel = <ChannelMessage>[];
|
||||
for (var i = 0; i < 20; i++) {
|
||||
final f = (await h.request(buildSyncNextMessageFrame())).single;
|
||||
if (f[0] == respCodeNoMoreMessages) break;
|
||||
if (f[0] == respCodeContactMsgRecvV3) {
|
||||
direct.add(parseContactMessageText(f)!);
|
||||
} else {
|
||||
expect(f[0], respCodeChannelMsgRecvV3);
|
||||
channel.add(ChannelMessage.fromFrame(f)!);
|
||||
}
|
||||
}
|
||||
expect(direct, hasLength(3));
|
||||
expect(channel, hasLength(4));
|
||||
expect(direct.first.text, contains('ridge'));
|
||||
expect(
|
||||
direct.first.senderPrefix,
|
||||
hexToPubKey(ReviewScript.contacts[0].publicKeyHex).sublist(0, 6),
|
||||
);
|
||||
expect(channel.map((m) => m.channelIndex).toSet(), {0, 1, 2});
|
||||
expect(
|
||||
channel.any(
|
||||
(m) => m.senderName == 'Jordan' && m.text.contains('trailhead'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
|
||||
final again = (await h.request(buildSyncNextMessageFrame())).single;
|
||||
expect(again[0], respCodeNoMoreMessages);
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('direct send yields SENT, SEND_CONFIRMED and a queued reply', () async {
|
||||
final h = _Harness(_fastRadio());
|
||||
final contact = ReviewScript.contacts[0];
|
||||
final key = hexToPubKey(contact.publicKeyHex);
|
||||
final ts = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
|
||||
final sent = await h.request(
|
||||
buildSendTextMsgFrame(key, 'Hello Maya', timestampSeconds: ts),
|
||||
);
|
||||
expect(sent.single[0], respCodeSent);
|
||||
final reader = BufferReader(sent.single)..skipBytes(2);
|
||||
final ackHash = reader.readUInt32LE();
|
||||
expect(reader.readUInt32LE(), greaterThan(0));
|
||||
expect(
|
||||
ackHash,
|
||||
MessageRetryService.computeExpectedAckHash(
|
||||
ts,
|
||||
0,
|
||||
'Hello Maya',
|
||||
hexToPubKey(ReviewRadio.selfPublicKeyHex),
|
||||
),
|
||||
);
|
||||
|
||||
h.frames.clear();
|
||||
await h.settle(const Duration(milliseconds: 150));
|
||||
expect(h.frames.first[0], pushCodeSendConfirmed);
|
||||
final confirmed = BufferReader(h.frames.first)..skipBytes(1);
|
||||
expect(confirmed.readUInt32LE(), ackHash);
|
||||
|
||||
await h.settle(const Duration(milliseconds: 300));
|
||||
expect(h.frames.last[0], pushCodeMsgWaiting);
|
||||
|
||||
// Drain the seed history; the reply is the last queued message.
|
||||
Uint8List? last;
|
||||
for (var i = 0; i < 20; i++) {
|
||||
final f = (await h.request(buildSyncNextMessageFrame())).single;
|
||||
if (f[0] == respCodeNoMoreMessages) break;
|
||||
last = f;
|
||||
}
|
||||
final reply = parseContactMessageText(last!)!;
|
||||
expect(reply.senderPrefix, key.sublist(0, 6));
|
||||
expect(ReviewScript.directReplies, contains(reply.text));
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('room login succeeds and repeater login fails promptly', () async {
|
||||
final h = _Harness(_fastRadio());
|
||||
final room = ReviewScript.contacts.firstWhere((c) => c.type == advTypeRoom);
|
||||
final roomKey = hexToPubKey(room.publicKeyHex);
|
||||
final sent = await h.request(buildSendLoginFrame(roomKey, 'any'));
|
||||
expect(sent.single[0], respCodeSent);
|
||||
h.frames.clear();
|
||||
await h.settle(const Duration(milliseconds: 150));
|
||||
final success = h.frames.single;
|
||||
expect(success[0], pushCodeLoginSuccess);
|
||||
expect(success.length, greaterThanOrEqualTo(12));
|
||||
expect(success.sublist(2, 8), roomKey.sublist(0, 6));
|
||||
expect(readUint32LE(success, 8), greaterThan(0));
|
||||
|
||||
final repeater = ReviewScript.contacts.firstWhere(
|
||||
(c) => c.type == advTypeRepeater,
|
||||
);
|
||||
final repeaterKey = hexToPubKey(repeater.publicKeyHex);
|
||||
expect(
|
||||
(await h.request(buildSendLoginFrame(repeaterKey, 'any'))).single[0],
|
||||
respCodeSent,
|
||||
);
|
||||
h.frames.clear();
|
||||
await h.settle(const Duration(milliseconds: 150));
|
||||
expect(h.frames.single[0], pushCodeLoginFail);
|
||||
expect(h.frames.single.sublist(2, 8), repeaterKey.sublist(0, 6));
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('unknown recipient prefix is answered with ERR', () async {
|
||||
final h = _Harness(ReviewRadio());
|
||||
final out = await h.request(
|
||||
buildSendTextMsgFrame(Uint8List(pubKeySize)..fillRange(0, 32, 3), 'hi'),
|
||||
);
|
||||
expect(out.single[0], respCodeErr);
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('channel send yields OK then a channel reply', () async {
|
||||
final h = _Harness(_fastRadio());
|
||||
final ok = await h.request(
|
||||
buildSendChannelTextMsgFrame(1, 'Review Radio: hi all'),
|
||||
);
|
||||
expect(ok.single[0], respCodeOk);
|
||||
|
||||
h.frames.clear();
|
||||
await h.settle(const Duration(milliseconds: 300));
|
||||
expect(h.frames.single[0], pushCodeMsgWaiting);
|
||||
|
||||
ChannelMessage? reply;
|
||||
for (var i = 0; i < 20; i++) {
|
||||
final f = (await h.request(buildSyncNextMessageFrame())).single;
|
||||
if (f[0] == respCodeNoMoreMessages) break;
|
||||
if (f[0] == respCodeChannelMsgRecvV3) reply = ChannelMessage.fromFrame(f);
|
||||
}
|
||||
expect(reply, isNotNull);
|
||||
expect(reply!.channelIndex, 1);
|
||||
expect(ReviewScript.channelMembers[1], contains(reply.senderName));
|
||||
expect(ReviewScript.channelReplies, contains(reply.text));
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('status commands get plausible replies', () async {
|
||||
final h = _Harness(ReviewRadio());
|
||||
expect(
|
||||
(await h.request(buildGetBattAndStorageFrame())).single[0],
|
||||
respCodeBattAndStorage,
|
||||
);
|
||||
final time = (await h.request(buildGetDeviceTimeFrame())).single;
|
||||
expect(time[0], respCodeCurrTime);
|
||||
expect(
|
||||
readUint32LE(time, 1),
|
||||
closeTo(DateTime.now().millisecondsSinceEpoch ~/ 1000, 5),
|
||||
);
|
||||
expect(
|
||||
(await h.request(buildGetCustomVarsFrame())).single[0],
|
||||
respCodeCustomVars,
|
||||
);
|
||||
expect(
|
||||
(await h.request(buildGetAutoAddFlagsFrame())).single[0],
|
||||
respCodeAutoAddConfig,
|
||||
);
|
||||
final freq = (await h.request(buildGetAllowedRepeatFreqFrame())).single;
|
||||
expect(parseAllowedRepeatFreqFrame(freq), isNotEmpty);
|
||||
expect(
|
||||
(await h.request(buildGetStatsFrame(statsTypeRadio))).single.length,
|
||||
14,
|
||||
);
|
||||
expect(
|
||||
(await h.request(buildSetFloodScopeFrame('#west'))).single[0],
|
||||
respCodeOk,
|
||||
);
|
||||
expect((await h.request(buildSendSelfAdvertFrame())).single[0], respCodeOk);
|
||||
expect(
|
||||
(await h.request(
|
||||
buildSendLoginFrame(Uint8List(pubKeySize), 'pw'),
|
||||
)).single[0],
|
||||
respCodeErr,
|
||||
);
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test(
|
||||
'sendTestMessage queues alternating direct and channel messages',
|
||||
() async {
|
||||
final h = _Harness(ReviewRadio());
|
||||
// Drain seed history first.
|
||||
for (var i = 0; i < 20; i++) {
|
||||
final f = (await h.request(buildSyncNextMessageFrame())).single;
|
||||
if (f[0] == respCodeNoMoreMessages) break;
|
||||
}
|
||||
|
||||
h.frames.clear();
|
||||
h.radio.sendTestMessage();
|
||||
h.radio.sendTestMessage();
|
||||
await h.settle();
|
||||
expect(h.frames.map((f) => f[0]), [
|
||||
pushCodeMsgWaiting,
|
||||
pushCodeMsgWaiting,
|
||||
]);
|
||||
|
||||
final first = (await h.request(buildSyncNextMessageFrame())).single;
|
||||
final second = (await h.request(buildSyncNextMessageFrame())).single;
|
||||
expect(first[0], respCodeContactMsgRecvV3);
|
||||
expect(second[0], respCodeChannelMsgRecvV3);
|
||||
expect(parseContactMessageText(first), isNotNull);
|
||||
expect(ChannelMessage.fromFrame(second), isNotNull);
|
||||
expect(
|
||||
(await h.request(buildSyncNextMessageFrame())).single[0],
|
||||
respCodeNoMoreMessages,
|
||||
);
|
||||
await h.close();
|
||||
},
|
||||
);
|
||||
|
||||
test('scheduled timer emits MSG_WAITING after start', () async {
|
||||
final h = _Harness(_fastRadio());
|
||||
await h.settle(const Duration(milliseconds: 150));
|
||||
expect(h.frames, isEmpty);
|
||||
h.radio.start();
|
||||
await h.settle(const Duration(milliseconds: 150));
|
||||
expect(h.frames.where((f) => f[0] == pushCodeMsgWaiting), isNotEmpty);
|
||||
await h.close();
|
||||
});
|
||||
|
||||
test('dispose cancels timers, closes the stream and is idempotent', () async {
|
||||
final radio = _fastRadio();
|
||||
final frames = <Uint8List>[];
|
||||
var done = false;
|
||||
radio.frames.listen(frames.add, onDone: () => done = true);
|
||||
radio.start();
|
||||
radio.handle(buildSendChannelTextMsgFrame(0, 'x: y'));
|
||||
radio.handle(
|
||||
buildSendTextMsgFrame(
|
||||
hexToPubKey(ReviewScript.contacts[0].publicKeyHex),
|
||||
'bye',
|
||||
),
|
||||
);
|
||||
radio.dispose();
|
||||
radio.dispose();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 400));
|
||||
expect(frames, isEmpty);
|
||||
expect(done, isTrue);
|
||||
radio.handle(buildAppStartFrame());
|
||||
radio.sendTestMessage();
|
||||
await Future<void>.delayed(_tick);
|
||||
expect(frames, isEmpty);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/screens/map_screen.dart';
|
||||
|
||||
void main() {
|
||||
test('parseMarkerText accepts in-range coordinates', () {
|
||||
final payload = parseMarkerText('m:45.5,-122.6|Camp|x');
|
||||
expect(payload, isNotNull);
|
||||
expect(payload!.position.latitude, 45.5);
|
||||
expect(payload.position.longitude, -122.6);
|
||||
expect(payload.label, 'Camp');
|
||||
});
|
||||
|
||||
test('parseMarkerText rejects out-of-range coordinates', () {
|
||||
expect(parseMarkerText('m:999,999|x|'), isNull);
|
||||
expect(parseMarkerText('m:90.1,0|x|'), isNull);
|
||||
expect(parseMarkerText('m:0,-180.5|x|'), isNull);
|
||||
expect(parseMarkerText('m:-90,180|edge|'), isNotNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/services/map_tile_cache_service.dart';
|
||||
|
||||
void main() {
|
||||
test('tile cache key drops api_key and keeps everything else', () {
|
||||
expect(
|
||||
MapTileCacheService.tileCacheKey(
|
||||
'https://tiles.stadiamaps.com/tiles/outdoors/10/1/2@2x.png?api_key=k1',
|
||||
),
|
||||
'https://tiles.stadiamaps.com/tiles/outdoors/10/1/2@2x.png',
|
||||
);
|
||||
expect(
|
||||
MapTileCacheService.tileCacheKey('https://x/t/1/2/3.png?a=1&api_key=k2'),
|
||||
'https://x/t/1/2/3.png?a=1',
|
||||
);
|
||||
expect(
|
||||
MapTileCacheService.tileCacheKey(
|
||||
'https://tile.openstreetmap.org/1/2/3.png',
|
||||
),
|
||||
'https://tile.openstreetmap.org/1/2/3.png',
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/models/message.dart';
|
||||
import 'package:meshcore_open/services/message_retry_service.dart';
|
||||
|
||||
Contact _contact() => Contact(
|
||||
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => 0xAA + i)),
|
||||
name: 'Test',
|
||||
type: 1,
|
||||
pathLength: -1,
|
||||
path: Uint8List(0),
|
||||
lastSeen: DateTime.now(),
|
||||
);
|
||||
|
||||
void main() {
|
||||
late MessageRetryService service;
|
||||
late Map<String, Message> latest;
|
||||
late List<String> sentTexts;
|
||||
late bool failSends;
|
||||
Uint8List? selfKey;
|
||||
|
||||
setUp(() {
|
||||
service = MessageRetryService();
|
||||
latest = {};
|
||||
sentTexts = [];
|
||||
failSends = false;
|
||||
selfKey = Uint8List(32);
|
||||
service.initialize(
|
||||
RetryServiceConfig(
|
||||
sendMessage: (_, text, _, _) async {
|
||||
if (failSends) throw StateError('Not connected');
|
||||
sentTexts.add(text);
|
||||
},
|
||||
addMessage: (_, m) => latest[m.messageId] = m,
|
||||
updateMessage: (m) => latest[m.messageId] = m,
|
||||
getSelfPublicKey: () => selfKey,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() => service.dispose());
|
||||
|
||||
Message byText(String text) =>
|
||||
latest.values.firstWhere((m) => m.text == text);
|
||||
|
||||
test('failed send fails the message and frees the contact slot', () async {
|
||||
failSends = true;
|
||||
final contact = _contact();
|
||||
await service.sendMessageWithRetry(contact: contact, text: 'a');
|
||||
await pumpEventQueue();
|
||||
expect(byText('a').status, MessageStatus.failed);
|
||||
|
||||
failSends = false;
|
||||
await service.sendMessageWithRetry(contact: contact, text: 'b');
|
||||
await pumpEventQueue();
|
||||
expect(sentTexts, ['b']);
|
||||
});
|
||||
|
||||
test('unknown self key fails instead of waiting forever', () async {
|
||||
selfKey = null;
|
||||
await service.sendMessageWithRetry(contact: _contact(), text: 'a');
|
||||
await pumpEventQueue();
|
||||
expect(byText('a').status, MessageStatus.failed);
|
||||
expect(sentTexts, isEmpty);
|
||||
expect(service.hasPendingMessages, isFalse);
|
||||
});
|
||||
|
||||
test('failAllPending fails in-flight and queued messages', () async {
|
||||
final contact = _contact();
|
||||
await service.sendMessageWithRetry(contact: contact, text: 'a');
|
||||
await service.sendMessageWithRetry(contact: contact, text: 'b');
|
||||
await pumpEventQueue();
|
||||
expect(sentTexts, ['a']);
|
||||
|
||||
service.failAllPending();
|
||||
await pumpEventQueue();
|
||||
|
||||
expect(byText('a').status, MessageStatus.failed);
|
||||
expect(byText('b').status, MessageStatus.failed);
|
||||
expect(service.hasPendingMessages, isFalse);
|
||||
expect(sentTexts, ['a']);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/services/notification_reply.dart';
|
||||
|
||||
void main() {
|
||||
group('NotificationReply.parse', () {
|
||||
test('parses a contact reply', () {
|
||||
final reply = NotificationReply.parse(
|
||||
actionId: notificationReplyActionId,
|
||||
payload: 'message:ab12cd',
|
||||
input: ' on my way ',
|
||||
)!;
|
||||
expect(reply.action, NotificationReplyAction.reply);
|
||||
expect(reply.isChannel, isFalse);
|
||||
expect(reply.contactKeyHex, 'ab12cd');
|
||||
expect(reply.text, 'on my way');
|
||||
});
|
||||
|
||||
test('parses a channel reply', () {
|
||||
final reply = NotificationReply.parse(
|
||||
actionId: notificationReplyActionId,
|
||||
payload: 'channel:3',
|
||||
input: 'ok',
|
||||
)!;
|
||||
expect(reply.isChannel, isTrue);
|
||||
expect(reply.channelIndex, 3);
|
||||
});
|
||||
|
||||
test('parses mark as read without input', () {
|
||||
final reply = NotificationReply.parse(
|
||||
actionId: notificationMarkReadActionId,
|
||||
payload: 'channel:0',
|
||||
)!;
|
||||
expect(reply.action, NotificationReplyAction.markRead);
|
||||
expect(reply.channelIndex, 0);
|
||||
});
|
||||
|
||||
test('parses mute for channels only', () {
|
||||
final reply = NotificationReply.parse(
|
||||
actionId: notificationMuteActionId,
|
||||
payload: 'channel:2',
|
||||
)!;
|
||||
expect(reply.action, NotificationReplyAction.mute);
|
||||
expect(reply.channelIndex, 2);
|
||||
expect(
|
||||
NotificationReply.parse(
|
||||
actionId: notificationMuteActionId,
|
||||
payload: 'message:ab12',
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
|
||||
test('ignores taps, unknown actions, empty replies and bad payloads', () {
|
||||
expect(
|
||||
NotificationReply.parse(actionId: null, payload: 'message:ab'),
|
||||
isNull,
|
||||
);
|
||||
expect(
|
||||
NotificationReply.parse(actionId: 'archive', payload: 'message:ab'),
|
||||
isNull,
|
||||
);
|
||||
expect(
|
||||
NotificationReply.parse(
|
||||
actionId: notificationReplyActionId,
|
||||
payload: 'message:ab',
|
||||
input: ' ',
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
for (final payload in [null, 'message:', 'message:null', 'channel:x']) {
|
||||
expect(
|
||||
NotificationReply.parse(
|
||||
actionId: notificationReplyActionId,
|
||||
payload: payload,
|
||||
input: 'hi',
|
||||
),
|
||||
isNull,
|
||||
reason: '$payload',
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
group('splitMessageToFit', () {
|
||||
bool fitsBytes(String s, int max) => utf8.encode(s).length <= max;
|
||||
|
||||
test('returns short text unchanged', () {
|
||||
expect(splitMessageToFit('hello there', (s) => fitsBytes(s, 20)), [
|
||||
'hello there',
|
||||
]);
|
||||
});
|
||||
|
||||
test('splits at word boundaries within the byte budget', () {
|
||||
final parts = splitMessageToFit(
|
||||
'one two three four five six',
|
||||
(s) => fitsBytes(s, 10),
|
||||
)!;
|
||||
expect(parts, ['one two', 'three four', 'five six']);
|
||||
expect(parts.every((p) => fitsBytes(p, 10)), isTrue);
|
||||
});
|
||||
|
||||
test('counts multi-byte characters by UTF-8 size', () {
|
||||
final parts = splitMessageToFit(
|
||||
'привет привет привет',
|
||||
(s) => fitsBytes(s, 13),
|
||||
)!;
|
||||
expect(parts, ['привет', 'привет', 'привет']);
|
||||
});
|
||||
|
||||
test('hard-splits a word that is too long on its own', () {
|
||||
final parts = splitMessageToFit('abcdefghij', (s) => fitsBytes(s, 4))!;
|
||||
expect(parts, ['abcd', 'efgh', 'ij']);
|
||||
});
|
||||
|
||||
test('returns null when a single character does not fit', () {
|
||||
expect(splitMessageToFit('aé', (s) => fitsBytes(s, 1)), isNull);
|
||||
});
|
||||
|
||||
test('returns null when more than maxParts are needed', () {
|
||||
expect(
|
||||
splitMessageToFit('a b c d e f g h', (s) => fitsBytes(s, 1)),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -823,4 +823,70 @@ void main() {
|
||||
expect(paths.first.routeWeight, closeTo(1.5, 0.001));
|
||||
});
|
||||
});
|
||||
|
||||
group('learned state is preserved', () {
|
||||
const sel = PathSelection(pathBytes: [0x01], hopCount: 1, useFlood: false);
|
||||
|
||||
test('recordPathAttempt keeps the learned route weight', () async {
|
||||
final pubKey = _hex('k001');
|
||||
await _seed(svc, pubKey, pathBytes: [0x01], weight: 1.0);
|
||||
svc.recordPathResult(pubKey, sel, success: true, successIncrement: 1.0);
|
||||
await _flush();
|
||||
|
||||
svc.recordPathAttempt(pubKey, sel);
|
||||
await _flush();
|
||||
|
||||
expect(svc.getRecentPaths(pubKey).first.routeWeight, closeTo(2.0, 1e-9));
|
||||
});
|
||||
|
||||
test('handlePathUpdated keeps the learned route weight', () async {
|
||||
final pubKey = _hex('k002');
|
||||
await _seed(svc, pubKey, pathBytes: [0x01], weight: 3.0);
|
||||
|
||||
svc.handlePathUpdated(
|
||||
_makeContact(publicKeyHex: pubKey, pathLength: 1, path: [0x01]),
|
||||
);
|
||||
await _flush();
|
||||
|
||||
expect(svc.getRecentPaths(pubKey).first.routeWeight, closeTo(3.0, 1e-9));
|
||||
});
|
||||
|
||||
test('recordPathResult after eviction merges with stored counts', () async {
|
||||
final pubKey = _hex('k003');
|
||||
await _seed(svc, pubKey, pathBytes: [0x01], weight: 1.0);
|
||||
for (var i = 0; i < 3; i++) {
|
||||
svc.recordPathResult(pubKey, sel, success: true, successIncrement: 0.5);
|
||||
}
|
||||
await _flush();
|
||||
|
||||
final fresh = PathHistoryService(storage);
|
||||
fresh.recordPathResult(pubKey, sel, success: true, successIncrement: 0.5);
|
||||
await _flush();
|
||||
|
||||
final record = fresh.getRecentPaths(pubKey).first;
|
||||
expect(record.successCount, equals(4));
|
||||
expect(record.routeWeight, closeTo(3.0, 1e-9));
|
||||
});
|
||||
|
||||
test('getRecentPaths load does not drop a concurrent add', () async {
|
||||
final pubKey = _hex('k004');
|
||||
await _seed(svc, pubKey, pathBytes: [0x01], weight: 1.0);
|
||||
|
||||
final fresh = PathHistoryService(storage);
|
||||
fresh.getRecentPaths(pubKey);
|
||||
fresh.handlePathUpdated(
|
||||
_makeContact(publicKeyHex: pubKey, pathLength: 1, path: [0x02]),
|
||||
);
|
||||
await _flush();
|
||||
|
||||
final paths = fresh.getRecentPaths(pubKey).map((p) => p.pathBytes);
|
||||
expect(
|
||||
paths,
|
||||
containsAll([
|
||||
[0x01],
|
||||
[0x02],
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -990,6 +990,16 @@ void main() {
|
||||
FileReceivedImageBlobStore newStore() =>
|
||||
FileReceivedImageBlobStore(baseDirectory: () async => tempDir);
|
||||
|
||||
test('concurrent sidecar writes for one id land the last one', () async {
|
||||
final blobs = newStore();
|
||||
await Future.wait<void>([
|
||||
for (var i = 0; i < 20; i++)
|
||||
blobs.writeSidecar('1a2b0700693f21', '{"n":$i}'),
|
||||
]);
|
||||
final sidecars = await blobs.readSidecars();
|
||||
expect(sidecars['1a2b0700693f21'], '{"n":19}');
|
||||
});
|
||||
|
||||
test('round-trips bytes and sidecars through real files', () async {
|
||||
final blobs = newStore();
|
||||
await blobs.writeBitstream('1a2b0700693f21', _payload(155));
|
||||
@@ -1170,6 +1180,109 @@ void main() {
|
||||
expect(listenable.value!.state, ReceivedImageState.decoded);
|
||||
},
|
||||
);
|
||||
|
||||
group('review fixes 2026-09-24', () {
|
||||
Future<ReceivedImageEntry> startTwoChunk(_Rig h, int imgId) async {
|
||||
final set = buildImageChunks(
|
||||
payload: _payload(kImageChunkFirstCapacity + 20, imgId),
|
||||
metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard),
|
||||
senderPrefix: kSender,
|
||||
imgId: imgId,
|
||||
);
|
||||
final entry = await h.store.handleOutcome(
|
||||
h.reassembler.addChunk(set.blobs[0], channelIndex: 3, now: h.clock()),
|
||||
channelIndex: 3,
|
||||
at: h.clock(),
|
||||
);
|
||||
return entry!;
|
||||
}
|
||||
|
||||
Future<void> failIt(_Rig h, ReceivedImageEntry entry) async {
|
||||
await h.store.handleFailure(
|
||||
ImageReassemblyFailure(
|
||||
key: entry.key,
|
||||
total: 2,
|
||||
receivedDataChunks: 1,
|
||||
hadParity: false,
|
||||
firstSeen: entry.firstSeen,
|
||||
expiredAt: h.clock(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
test('a reused img_id does not overwrite a decoded image', () async {
|
||||
final h = _build();
|
||||
final first = await _completeOne(h, imgId: 11, seed: 1);
|
||||
await h.store.settle();
|
||||
expect(
|
||||
h.store.entryFor(first.streamId)!.state,
|
||||
ReceivedImageState.decoded,
|
||||
);
|
||||
|
||||
h.advance(const Duration(minutes: 1));
|
||||
final second = await startTwoChunk(h, 11);
|
||||
expect(second.streamId, isNot(first.streamId));
|
||||
expect(second.state, ReceivedImageState.receiving);
|
||||
expect(
|
||||
h.store.entryFor(first.streamId)!.state,
|
||||
ReceivedImageState.decoded,
|
||||
);
|
||||
|
||||
h.advance(const Duration(minutes: 10));
|
||||
h.reassembler.clear();
|
||||
final third = await _completeOne(h, imgId: 11, seed: 9);
|
||||
expect(third.streamId, isNot(first.streamId));
|
||||
expect(
|
||||
h.store.entryFor(first.streamId)!.state,
|
||||
ReceivedImageState.decoded,
|
||||
);
|
||||
});
|
||||
|
||||
test('failed entries are capped by count, oldest first', () async {
|
||||
final h = _build(maxImages: 2);
|
||||
final ids = <String>[];
|
||||
for (var i = 0; i < 4; i++) {
|
||||
final entry = await startTwoChunk(h, 70 + i);
|
||||
await failIt(h, entry);
|
||||
ids.add(entry.streamId);
|
||||
h.advance(const Duration(seconds: 5));
|
||||
}
|
||||
expect(h.store.entries.length, 2);
|
||||
expect(h.store.entryFor(ids[0]), isNull);
|
||||
expect(h.blobs.hasSidecar(ids[0]), isFalse);
|
||||
expect(
|
||||
h.store.entryFor(ids[3])!.state,
|
||||
ReceivedImageState.failedIncomplete,
|
||||
);
|
||||
});
|
||||
|
||||
test('failed entries past maxAge are deleted outright', () async {
|
||||
final h = _build(maxAge: const Duration(days: 1));
|
||||
final entry = await startTwoChunk(h, 80);
|
||||
await failIt(h, entry);
|
||||
h.advance(const Duration(days: 2));
|
||||
await h.store.evictToBudget();
|
||||
expect(h.store.entryFor(entry.streamId), isNull);
|
||||
expect(h.blobs.hasSidecar(entry.streamId), isFalse);
|
||||
});
|
||||
|
||||
test('foreground memory pressure mid-decode parks, not corrupt', () async {
|
||||
final decoder = _FakeDecoder(mode: 'fail')
|
||||
..delay = const Duration(milliseconds: 50);
|
||||
final h = _build(decoder: decoder);
|
||||
final entry = await _completeOne(h);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
expect(
|
||||
h.store.entryFor(entry.streamId)!.state,
|
||||
ReceivedImageState.decoding,
|
||||
);
|
||||
await h.store.handleMemoryPressure();
|
||||
await h.store.settle();
|
||||
final after = h.store.entryFor(entry.streamId)!;
|
||||
expect(after.state, ReceivedImageState.reassembled);
|
||||
expect(after.needsManualDecode, isTrue);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Delivers a whole single-chunk image and returns its entry (state
|
||||
|
||||
@@ -1,6 +1,35 @@
|
||||
import 'dart:async';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_connector.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/models/path_selection.dart';
|
||||
import 'package:meshcore_open/services/repeater_command_service.dart';
|
||||
|
||||
class _FakeConnector extends MeshCoreConnector {
|
||||
@override
|
||||
Future<PathSelection> preparePathForContactSend(Contact contact) async =>
|
||||
const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
|
||||
|
||||
@override
|
||||
Future<void> sendFrame(
|
||||
Uint8List data, {
|
||||
String? channelSendQueueId,
|
||||
bool expectsGenericAck = false,
|
||||
bool waitForGenericAck = false,
|
||||
}) async {}
|
||||
}
|
||||
|
||||
Contact _repeater(int seed) => Contact(
|
||||
publicKey: Uint8List.fromList(List<int>.generate(32, (i) => seed + i)),
|
||||
name: 'R$seed',
|
||||
type: 2,
|
||||
pathLength: -1,
|
||||
path: Uint8List(0),
|
||||
lastSeen: DateTime.now(),
|
||||
);
|
||||
|
||||
void main() {
|
||||
group('normalizeRepeaterClockSyncCommand', () {
|
||||
test('translates "clock sync" to explicit time command', () {
|
||||
@@ -43,4 +72,50 @@ void main() {
|
||||
expect(epoch, inInclusiveRange(before, after));
|
||||
});
|
||||
});
|
||||
|
||||
group('RepeaterCommandService.handleResponse', () {
|
||||
late RepeaterCommandService service;
|
||||
|
||||
setUp(() => service = RepeaterCommandService(_FakeConnector()));
|
||||
tearDown(() => service.dispose());
|
||||
|
||||
test('unknown prefix does not complete the pending command', () async {
|
||||
final repeater = _repeater(1);
|
||||
String? result;
|
||||
unawaited(
|
||||
service
|
||||
.sendCommand(repeater, 'ver', retries: 1)
|
||||
.then((r) => result = r, onError: (_) {}),
|
||||
);
|
||||
await pumpEventQueue();
|
||||
|
||||
service.handleResponse(repeater, 'FE|late reply');
|
||||
await pumpEventQueue();
|
||||
expect(result, isNull);
|
||||
|
||||
service.handleResponse(repeater, '00|v1.0');
|
||||
await pumpEventQueue();
|
||||
expect(result, 'v1.0');
|
||||
});
|
||||
|
||||
test('prefix owned by another repeater is ignored', () async {
|
||||
final a = _repeater(1);
|
||||
final b = _repeater(100);
|
||||
String? result;
|
||||
unawaited(
|
||||
service
|
||||
.sendCommand(a, 'ver', retries: 1)
|
||||
.then((r) => result = r, onError: (_) {}),
|
||||
);
|
||||
await pumpEventQueue();
|
||||
|
||||
service.handleResponse(b, '00|wrong');
|
||||
await pumpEventQueue();
|
||||
expect(result, isNull);
|
||||
|
||||
service.handleResponse(a, 'unprefixed');
|
||||
await pumpEventQueue();
|
||||
expect(result, 'unprefixed');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/models/community.dart';
|
||||
import 'package:meshcore_open/services/storage_service.dart';
|
||||
import 'package:meshcore_open/storage/channel_message_store.dart';
|
||||
import 'package:meshcore_open/storage/community_store.dart';
|
||||
import 'package:meshcore_open/storage/message_store.dart';
|
||||
import 'package:meshcore_open/storage/prefs_manager.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
const _device = 'abcdef012345';
|
||||
|
||||
Future<void> _init(Map<String, Object> values) async {
|
||||
SharedPreferences.setMockInitialValues(values);
|
||||
PrefsManager.reset();
|
||||
await PrefsManager.initialize();
|
||||
}
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'message store skips a malformed record instead of dropping all',
|
||||
() async {
|
||||
final good = {
|
||||
'senderKey': base64Encode([1, 2, 3]),
|
||||
'text': 'hello',
|
||||
'timestamp': 1000,
|
||||
'status': 1,
|
||||
};
|
||||
await _init({
|
||||
'messages_${_device.substring(0, 10)}c1': jsonEncode([
|
||||
good,
|
||||
{'text': 'no timestamp'},
|
||||
]),
|
||||
});
|
||||
final store = MessageStore()..setPublicKeyHex = _device;
|
||||
final messages = await store.loadMessages('c1');
|
||||
expect(messages.map((m) => m.text), ['hello']);
|
||||
expect(messages.single.isOutgoing, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('channel message store skips a malformed record', () async {
|
||||
await _init({
|
||||
'channel_messages_${_device.substring(0, 10)}0': jsonEncode([
|
||||
{'text': 'hi', 'timestamp': 1000, 'status': 1},
|
||||
'garbage',
|
||||
]),
|
||||
});
|
||||
final store = ChannelMessageStore()..setPublicKeyHex = _device;
|
||||
final messages = await store.loadChannelMessages(0);
|
||||
expect(messages.map((m) => m.text), ['hi']);
|
||||
});
|
||||
|
||||
test('community store keeps valid communities next to a bad one', () async {
|
||||
final community = Community.create(id: 'c1', name: 'Ops');
|
||||
await _init({
|
||||
'communities_v1${_device.substring(0, 10)}': jsonEncode([
|
||||
community.toJson(),
|
||||
{'id': 'broken'},
|
||||
]),
|
||||
});
|
||||
final store = CommunityStore()..setPublicKeyHex = _device;
|
||||
final communities = await store.loadCommunities();
|
||||
expect(communities.map((c) => c.id), ['c1']);
|
||||
});
|
||||
|
||||
test('delivery observations skip malformed entries', () async {
|
||||
await _init({
|
||||
'delivery_observations': jsonEncode([
|
||||
{
|
||||
'contact_key': 'k',
|
||||
'path_length': 1,
|
||||
'message_bytes': 10,
|
||||
'delivery_ms': 500,
|
||||
'timestamp': DateTime(2026).toIso8601String(),
|
||||
},
|
||||
{'contact_key': 'bad'},
|
||||
]),
|
||||
});
|
||||
final observations = await StorageService().loadDeliveryObservations();
|
||||
expect(observations, hasLength(1));
|
||||
expect(observations.single.isFlood, isFalse);
|
||||
});
|
||||
|
||||
test('community hashtag normalization trims before stripping #', () {
|
||||
final community = Community.create(id: 'c1', name: 'Ops');
|
||||
expect(
|
||||
community.deriveCommunityHashtagPsk(' #ops'),
|
||||
community.deriveCommunityHashtagPsk('#ops'),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/connector/meshcore_protocol.dart';
|
||||
import 'package:meshcore_open/models/contact.dart';
|
||||
import 'package:meshcore_open/utils/contact_qr.dart';
|
||||
import 'package:meshcore_open/utils/contact_qr_frame.dart';
|
||||
|
||||
void main() {
|
||||
final publicKey = Uint8List.fromList(List<int>.filled(32, 0xAB));
|
||||
|
||||
Contact contactWith({required String name, required int flags}) {
|
||||
return Contact(
|
||||
publicKey: publicKey,
|
||||
name: name,
|
||||
type: advTypeChat,
|
||||
flags: flags,
|
||||
pathLength: 2,
|
||||
path: Uint8List.fromList([1, 2]),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
|
||||
);
|
||||
}
|
||||
|
||||
group('buildContactQrFrame advert packet', () {
|
||||
test('replays the advert with CMD_IMPORT_CONTACT', () {
|
||||
final advert = Uint8List.fromList(List<int>.filled(98, 7));
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(advertPacket: advert),
|
||||
existing: contactWith(name: 'Old', flags: 0x03),
|
||||
);
|
||||
|
||||
expect(frame[0], cmdImportContact);
|
||||
expect(frame.sublist(1), advert);
|
||||
});
|
||||
});
|
||||
|
||||
group('buildContactQrFrame contact card', () {
|
||||
test('writes an add/update frame with the unknown-path sentinel', () {
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey, name: 'Alice', type: 2),
|
||||
);
|
||||
|
||||
expect(frame[0], cmdAddUpdateContact);
|
||||
expect(frame.sublist(1, 33), publicKey);
|
||||
expect(frame[33], 2);
|
||||
expect(frame[34], 0);
|
||||
expect(frame[35], 0xFF, reason: 'path is unknown, not zero-hop');
|
||||
|
||||
final nameStart = 36 + maxPathSize;
|
||||
final name = String.fromCharCodes(
|
||||
frame
|
||||
.sublist(nameStart, nameStart + maxNameSize)
|
||||
.takeWhile((b) => b != 0),
|
||||
);
|
||||
expect(name, 'Alice');
|
||||
});
|
||||
|
||||
test('defaults a new contact without a type to Companion', () {
|
||||
final frame = buildContactQrFrame(ScannedContact(publicKey: publicKey));
|
||||
|
||||
expect(frame[33], advTypeChat);
|
||||
});
|
||||
|
||||
test('keeps the type of an existing contact when the card has none', () {
|
||||
final existing = Contact(
|
||||
publicKey: publicKey,
|
||||
name: 'Hilltop',
|
||||
type: advTypeRepeater,
|
||||
pathLength: -1,
|
||||
path: Uint8List(0),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
|
||||
);
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey),
|
||||
existing: existing,
|
||||
);
|
||||
|
||||
expect(frame[33], advTypeRepeater);
|
||||
});
|
||||
|
||||
test('writes a zero advert timestamp for a new contact', () {
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey, name: 'Alice'),
|
||||
);
|
||||
|
||||
final tsStart = 36 + maxPathSize + maxNameSize;
|
||||
expect(frame.sublist(tsStart, tsStart + 4), [0, 0, 0, 0]);
|
||||
});
|
||||
|
||||
test('keeps the advert timestamp of an existing contact', () {
|
||||
final existing = Contact(
|
||||
publicKey: publicKey,
|
||||
name: 'Alice',
|
||||
type: advTypeChat,
|
||||
pathLength: -1,
|
||||
path: Uint8List(0),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000 * 1000),
|
||||
);
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey, name: 'Alice'),
|
||||
existing: existing,
|
||||
);
|
||||
|
||||
final tsStart = 36 + maxPathSize + maxNameSize;
|
||||
final ts = ByteData.sublistView(
|
||||
frame,
|
||||
tsStart,
|
||||
tsStart + 4,
|
||||
).getUint32(0, Endian.little);
|
||||
expect(ts, 1700000000);
|
||||
});
|
||||
|
||||
test('preserves the flags of an existing contact', () {
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey, name: 'Alice'),
|
||||
existing: contactWith(name: 'Alice', flags: 0x05),
|
||||
);
|
||||
|
||||
expect(frame[34], 0x05);
|
||||
});
|
||||
|
||||
test('falls back to the existing name when the card has none', () {
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey),
|
||||
existing: contactWith(name: 'Existing', flags: 0),
|
||||
);
|
||||
|
||||
final nameStart = 36 + maxPathSize;
|
||||
final name = String.fromCharCodes(
|
||||
frame
|
||||
.sublist(nameStart, nameStart + maxNameSize)
|
||||
.takeWhile((b) => b != 0),
|
||||
);
|
||||
expect(name, 'Existing');
|
||||
});
|
||||
|
||||
test('drops whole characters when the name exceeds 31 bytes', () {
|
||||
// 16 three-byte characters = 48 encoded bytes; only 10 fit in 31.
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey, name: '☂' * 16),
|
||||
);
|
||||
|
||||
final nameStart = 36 + maxPathSize;
|
||||
final bytes = frame
|
||||
.sublist(nameStart, nameStart + maxNameSize)
|
||||
.takeWhile((b) => b != 0)
|
||||
.toList();
|
||||
expect(bytes.length, 30);
|
||||
expect(utf8.decode(bytes), '☂' * 10);
|
||||
});
|
||||
});
|
||||
|
||||
group('buildContactQrFrame route preservation', () {
|
||||
Contact contactWithPath(int pathLength, List<int> path) {
|
||||
return Contact(
|
||||
publicKey: publicKey,
|
||||
name: 'Alice',
|
||||
type: advTypeChat,
|
||||
pathLength: pathLength,
|
||||
path: Uint8List.fromList(path),
|
||||
lastSeen: DateTime.fromMillisecondsSinceEpoch(0),
|
||||
);
|
||||
}
|
||||
|
||||
test('keeps the route of a contact the device already knows', () {
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey, name: 'Alice'),
|
||||
existing: contactWithPath(2, [0x11, 0x22]),
|
||||
);
|
||||
|
||||
expect(frame[35], 0x02, reason: 'two hops, 1-byte hash mode');
|
||||
expect(frame.sublist(36, 38), [0x11, 0x22]);
|
||||
});
|
||||
|
||||
test('encodes the hash mode in bits 6-7 for wider path hashes', () {
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey, name: 'Alice'),
|
||||
existing: contactWithPath(2, [0x11, 0x22, 0x33, 0x44]),
|
||||
pathHashByteWidth: 2,
|
||||
);
|
||||
|
||||
expect(frame[35], 0x42);
|
||||
expect(frame.sublist(36, 40), [0x11, 0x22, 0x33, 0x44]);
|
||||
});
|
||||
|
||||
test('uses the unknown sentinel for a flood-only contact', () {
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey, name: 'Alice'),
|
||||
existing: contactWithPath(-1, const []),
|
||||
);
|
||||
|
||||
expect(frame[35], 0xFF);
|
||||
expect(frame.sublist(36, 36 + maxPathSize).every((b) => b == 0), isTrue);
|
||||
});
|
||||
|
||||
test('uses the unknown sentinel when the path does not fit the mode', () {
|
||||
final frame = buildContactQrFrame(
|
||||
ScannedContact(publicKey: publicKey, name: 'Alice'),
|
||||
existing: contactWithPath(2, [0x11, 0x22]),
|
||||
pathHashByteWidth: 2,
|
||||
);
|
||||
|
||||
expect(frame[35], 0xFF);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_open/utils/contact_qr.dart';
|
||||
|
||||
void main() {
|
||||
group('parseContactQr official contact card', () {
|
||||
test('parses name with + and percent-encoding, key, explicit type', () {
|
||||
final key = List.generate(
|
||||
32,
|
||||
(i) => i.toRadixString(16).padLeft(2, '0'),
|
||||
).join();
|
||||
final result = parseContactQr(
|
||||
'meshcore://contact/add?name=Jane+D%C3%B6e&public_key=$key&type=2',
|
||||
);
|
||||
|
||||
expect(result, isNotNull);
|
||||
expect(result!.isAdvertPacket, isFalse);
|
||||
expect(result.name, 'Jane Döe');
|
||||
expect(result.publicKey!.length, 32);
|
||||
expect(result.publicKey![0], 0x00);
|
||||
expect(result.publicKey![31], 0x1f);
|
||||
expect(result.type, 2);
|
||||
});
|
||||
|
||||
test('missing type is left unset', () {
|
||||
final key = 'ab' * 32;
|
||||
final result = parseContactQr(
|
||||
'meshcore://contact/add?name=Bob&public_key=$key',
|
||||
);
|
||||
|
||||
expect(result, isNotNull);
|
||||
expect(result!.type, isNull);
|
||||
});
|
||||
|
||||
test('garbage type is left unset', () {
|
||||
final key = 'ab' * 32;
|
||||
final result = parseContactQr(
|
||||
'meshcore://contact/add?name=Bob&public_key=$key&type=nope',
|
||||
);
|
||||
|
||||
expect(result, isNotNull);
|
||||
expect(result!.type, isNull);
|
||||
});
|
||||
|
||||
test('uppercase hex public key is accepted', () {
|
||||
final key = 'AB' * 32;
|
||||
final result = parseContactQr(
|
||||
'meshcore://contact/add?name=Bob&public_key=$key',
|
||||
);
|
||||
|
||||
expect(result, isNotNull);
|
||||
expect(result!.publicKey!.length, 32);
|
||||
expect(result.publicKey![0], 0xAB);
|
||||
});
|
||||
|
||||
test('63-char public key is rejected', () {
|
||||
final key = '${'ab' * 31}a';
|
||||
final result = parseContactQr(
|
||||
'meshcore://contact/add?name=Bob&public_key=$key',
|
||||
);
|
||||
|
||||
expect(result, isNull);
|
||||
});
|
||||
|
||||
test('non-hex public key is rejected', () {
|
||||
final key = ('zz' * 32);
|
||||
final result = parseContactQr(
|
||||
'meshcore://contact/add?name=Bob&public_key=$key',
|
||||
);
|
||||
|
||||
expect(result, isNull);
|
||||
});
|
||||
|
||||
test('signed public key digits are rejected', () {
|
||||
final result = parseContactQr(
|
||||
'meshcore://contact/add?name=Bob&public_key=${'+1' * 32}',
|
||||
);
|
||||
|
||||
expect(result, isNull);
|
||||
});
|
||||
|
||||
test('missing name defaults to empty string', () {
|
||||
final key = 'ab' * 32;
|
||||
final result = parseContactQr('meshcore://contact/add?public_key=$key');
|
||||
|
||||
expect(result, isNotNull);
|
||||
expect(result!.name, '');
|
||||
});
|
||||
});
|
||||
|
||||
group('parseContactQr legacy advert packet', () {
|
||||
test('legacy hex form yields advert packet bytes', () {
|
||||
final hex = '0a' * 98;
|
||||
final result = parseContactQr('meshcore://$hex');
|
||||
|
||||
expect(result, isNotNull);
|
||||
expect(result!.isAdvertPacket, isTrue);
|
||||
expect(result.advertPacket!.length, 98);
|
||||
expect(result.advertPacket![0], 0x0a);
|
||||
});
|
||||
|
||||
test('odd-length hex is rejected', () {
|
||||
final result = parseContactQr('meshcore://abc');
|
||||
|
||||
expect(result, isNull);
|
||||
});
|
||||
|
||||
test('non-hex payload is rejected', () {
|
||||
final result = parseContactQr('meshcore://zz${'00' * 97}');
|
||||
|
||||
expect(result, isNull);
|
||||
});
|
||||
|
||||
test('payload shorter than the 98 byte advert minimum is rejected', () {
|
||||
final result = parseContactQr('meshcore://${'ab' * 97}');
|
||||
|
||||
expect(result, isNull);
|
||||
});
|
||||
|
||||
test('payload longer than the 171 byte frame limit is rejected', () {
|
||||
final result = parseContactQr('meshcore://${'ab' * 172}');
|
||||
|
||||
expect(result, isNull);
|
||||
});
|
||||
|
||||
test('payload at the 171 byte frame limit is accepted', () {
|
||||
final result = parseContactQr('meshcore://${'ab' * 171}');
|
||||
|
||||
expect(result, isNotNull);
|
||||
expect(result!.advertPacket!.length, 171);
|
||||
});
|
||||
});
|
||||
|
||||
group('parseContactQr rejects unsupported input', () {
|
||||
test('channel add link is not a contact', () {
|
||||
final result = parseContactQr(
|
||||
'meshcore://channel/add?name=Public&secret=abcd',
|
||||
);
|
||||
|
||||
expect(result, isNull);
|
||||
});
|
||||
|
||||
test('non-meshcore scheme is rejected', () {
|
||||
final result = parseContactQr('https://example.com/contact/add');
|
||||
|
||||
expect(result, isNull);
|
||||
});
|
||||
|
||||
test('empty string is rejected', () {
|
||||
expect(parseContactQr(''), isNull);
|
||||
});
|
||||
|
||||
test('whitespace-only string is rejected', () {
|
||||
expect(parseContactQr(' \n\t '), isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user