Key per-channel storage by PSK-derived channel ID

Channel messages, settings, region, order and images were persisted by
radio slot index, so a slot reused for a different channel inherited the
old channel's history and settings (#359).

- Channel.storageId: first 8 bytes of SHA-256("meshcore-channel:" + psk).
- All per-channel stores key by channel ID; in-memory state stays by slot.
- The connector keeps a slot -> channel ID map, diffs it against the saved
  map on every channel sync and reloads slots whose channel changed.
- Queued channel frames wait until this session's map is confirmed.
- One-shot per-radio migration from slot keys, using the cached channel
  list the legacy data was written under; rerun-safe if interrupted.
- Deleting a channel clears its data; a channel removed elsewhere keeps its
  history and gets it back when re-added. A PSK edit keeps its place in
  the custom order.
- Slots sharing a PSK share history and settings.
- Image entries record their channel ID; a slot change resets that slot's
  in-progress reassembly.
This commit is contained in:
zjs81 committed 2026-10-11 17:52:59 -07:00
1 parent d30744aa31
commit 679116ed03
24 files changed
+1794 -340

No files matched your search

+346
View File
@@ -0,0 +1,346 @@
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_connector.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/review_mode/review_frames.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';
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:pointycastle/export.dart';
import 'package:shared_preferences/shared_preferences.dart';
final _scope = ReviewRadio.storagePrefix;
const _queuedHikingText = 'Planning to leave the trailhead at 8 on Saturday.';
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: 20));
}
}
Uint8List _psk(int slot) =>
Channel.parsePskHex(ReviewScript.channels[slot].pskHex);
String _id(Uint8List psk) => Channel.storageIdForPsk(psk)!;
String _messagesKey(String channelId) =>
'channel_messages_${_scope}_$channelId';
List<String> _storedTexts(String channelId) {
final raw = PrefsManager.instance.getString(_messagesKey(channelId));
if (raw == null) return [];
return [
for (final entry in jsonDecode(raw) as List<dynamic>)
(entry as Map<String, dynamic>)['text'] as String,
];
}
// SharedPreferences updates its in-memory cache synchronously.
void _seedMessages(String channelId, List<String> texts) =>
PrefsManager.instance.setString(
_messagesKey(channelId),
jsonEncode([
for (var i = 0; i < texts.length; i++)
{
'senderName': 'Ghost',
'text': texts[i],
'timestamp': 1000 * (i + 1),
'isOutgoing': false,
'status': ChannelMessageStatus.sent.index,
'messageId': 'seed-$channelId-$i',
'plainText': true,
},
]),
);
void _seedSlotMap(Map<int, String> slotIds) => PrefsManager.instance.setString(
'channel_slot_ids_$_scope',
jsonEncode({for (final e in slotIds.entries) '${e.key}': e.value}),
);
/// Review radio that records every frame the app sends and can swallow some.
class _TestRadio extends ReviewRadio {
_TestRadio({this.swallow, this.afterHandle})
: super(
scheduledMessageInterval: const Duration(hours: 1),
ackDelay: const Duration(milliseconds: 50),
replyDelay: const Duration(hours: 1),
);
final bool Function(Uint8List frame)? swallow;
final void Function(_TestRadio radio, Uint8List frame)? afterHandle;
final List<Uint8List> sent = [];
@override
void handle(Uint8List frame) {
sent.add(Uint8List.fromList(frame));
if (swallow?.call(frame) ?? false) return;
super.handle(frame);
afterHandle?.call(this, frame);
}
void deliver(Uint8List frame) => super.handle(frame);
List<int> codes() => [for (final f in sent) f.isEmpty ? -1 : f[0]];
}
late MeshCoreConnector _connector;
/// Connects a fresh review radio. [seed] runs after review mode has cleared
/// its storage and before SELF_INFO, standing in for a previous session.
Future<void> _connect(_TestRadio radio, {void Function()? seed}) async {
_connector.reviewRadioFactoryForTest = () {
// beginReviewModeSession wipes the review scope before this runs.
seed?.call();
return radio;
};
await _connector.connectReview();
addTearDown(_connector.disconnect);
await _waitFor(() => _connector.channelMapConfirmed);
}
Channel _channelAt(int slot) =>
_connector.channels.firstWhere((c) => c.index == slot);
List<String> _texts(int slot) =>
_connector.getChannelMessages(_channelAt(slot)).map((m) => m.text).toList();
Uint8List _logRxGroupText(Uint8List psk, String text, int timestampSecs) {
final plain = BytesBuilder()
..add(
Uint8List(4)
..buffer.asByteData().setUint32(0, timestampSecs, Endian.little),
)
..addByte(0)
..add(utf8.encode(text))
..addByte(0);
final padded = Uint8List(((plain.length + 15) ~/ 16) * 16)
..setRange(0, plain.length, plain.toBytes());
final cipher = ECBBlockCipher(AESEngine())..init(true, KeyParameter(psk));
final encrypted = Uint8List(padded.length);
for (var i = 0; i < padded.length; i += 16) {
cipher.processBlock(padded, i, encrypted, i);
}
final key32 = Uint8List(32)..setRange(0, 16, psk);
final mac = crypto.Hmac(crypto.sha256, key32).convert(encrypted).bytes;
final channelHash = crypto.sha256.convert(psk).bytes[0];
return Uint8List.fromList([
pushCodeLogRxData,
40, // snr
0xA0, // rssi
0x15, // flood route, GRP_TXT payload
0x00, // no path
channelHash,
mac[0],
mac[1],
...encrypted,
]);
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
_connector = MeshCoreConnector();
final retryService = MessageRetryService();
_connector.initialize(
retryService: retryService,
pathHistoryService: PathHistoryService(StorageService()),
);
addTearDown(() {
_connector.dispose();
retryService.dispose();
});
});
tearDown(() => _connector.channelSyncTimeoutMs = 2000);
final hikingId = _id(_psk(1));
final ghostPsk = Uint8List.fromList(List<int>.generate(16, (i) => 200 - i));
final ghostId = _id(ghostPsk);
test('a slot reused by another channel while away starts clean', () async {
await _connect(
_TestRadio(),
seed: () {
// Last session slot 1 held the ghost channel.
_seedSlotMap({0: _id(_psk(0)), 1: ghostId, 2: _id(_psk(2))});
_seedMessages(ghostId, ['ghost message']);
},
);
await _waitFor(() => _texts(1).contains(_queuedHikingText));
expect(_channelAt(1).name, 'Hiking Group');
expect(_texts(1), isNot(contains('ghost message')));
// The old channel's history is kept under its own ID.
expect(_storedTexts(ghostId), ['ghost message']);
expect(_storedTexts(hikingId), contains(_queuedHikingText));
expect(_connector.channelIdForSlot(1), hikingId);
expect(
jsonDecode(PrefsManager.instance.getString('channel_slot_ids_$_scope')!),
containsPair('1', hikingId),
);
});
test('a PSK edit in place starts clean, and re-adding the old PSK in '
'another slot brings its history back', () async {
await _connect(_TestRadio());
await _waitFor(() => _texts(1).contains(_queuedHikingText));
await _connector.setChannelSmazEnabled(1, true);
await _connector.setChannel(1, 'Hiking Group', ghostPsk);
expect(_connector.channelIdForSlot(1), ghostId);
expect(_texts(1), isEmpty);
expect(_connector.isChannelSmazEnabled(1), isFalse);
expect(_storedTexts(hikingId), contains(_queuedHikingText));
await _connector.setChannel(6, 'Hiking Group', _psk(1));
expect(_connector.channelIdForSlot(6), hikingId);
expect(_texts(6), contains(_queuedHikingText));
expect(_connector.isChannelSmazEnabled(6), isTrue);
// Restored history belongs to slot 6 now, so deleting from it works.
final restored = _connector
.getChannelMessages(_channelAt(6))
.firstWhere((m) => m.text == _queuedHikingText);
expect(restored.channelIndex, 6);
await _connector.deleteChannelMessage(restored);
expect(_texts(6), isNot(contains(_queuedHikingText)));
expect(_storedTexts(hikingId), isNot(contains(_queuedHikingText)));
});
test(
'a PSK edit in place keeps the channel\'s place in the custom order',
() async {
await _connect(_TestRadio());
await _connector.setChannelOrder([1, 0, 2]);
expect(_connector.channels.first.index, 1);
await _connector.setChannel(1, 'Hiking Group', ghostPsk);
expect(_connector.channels.first.index, 1);
},
);
test('deleting a channel clears its stored history', () async {
await _connect(_TestRadio());
await _waitFor(() => _texts(1).contains(_queuedHikingText));
expect(_storedTexts(hikingId), isNotEmpty);
await _connector.deleteChannel(1);
expect(_storedTexts(hikingId), isEmpty);
});
test('MSG_WAITING before the channel sync waits for the slot map', () async {
// DEVICE_INFO is held back so MSG_WAITING lands between SELF_INFO and the
// start of the channel sync.
late final _TestRadio radio;
var deviceInfoHeld = false;
radio = _TestRadio(
swallow: (frame) {
if (frame[0] != cmdDeviceQuery || deviceInfoHeld) return false;
deviceInfoHeld = true;
Future<void>.delayed(
const Duration(milliseconds: 400),
() => radio.deliver(frame),
);
return true;
},
afterHandle: (radio, frame) {
if (frame[0] == cmdAppStart) {
radio.emitForTest(ReviewFrames.msgWaiting());
}
},
);
await _connect(radio);
await _waitFor(() => _texts(1).contains(_queuedHikingText));
final codes = radio.codes();
final firstSync = codes.indexOf(cmdSyncNextMessage);
final lastGetChannel = codes.lastIndexOf(cmdGetChannel);
expect(firstSync, isNonNegative);
expect(lastGetChannel, isNonNegative);
expect(firstSync, greaterThan(lastGetChannel));
});
test('a slot that never answers retries the sync, then releases the '
'queue with the saved map', () async {
_connector.channelSyncTimeoutMs = 30;
final radio = _TestRadio(
swallow: (frame) => frame[0] == cmdGetChannel && frame[1] == 1,
);
await _connect(
radio,
seed: () => _seedSlotMap({0: _id(_psk(0)), 1: hikingId, 2: _id(_psk(2))}),
);
await _waitFor(() => _storedTexts(hikingId).contains(_queuedHikingText));
final firstSync = radio.codes().indexOf(cmdSyncNextMessage);
final passes = radio.sent
.take(firstSync)
.where((f) => f[0] == cmdGetChannel && f[1] == 0)
.length;
expect(passes, 3);
expect(_connector.channelIdForSlot(1), hikingId);
});
test('two slots with the same PSK share one history', () async {
final radio = _TestRadio();
await _connect(
radio,
seed: () => radio.handle(buildSetChannelFrame(5, 'Hiking Twin', _psk(1))),
);
await _waitFor(() => _texts(1).contains(_queuedHikingText));
expect(_connector.channelIdForSlot(5), hikingId);
expect(_texts(5), _texts(1));
// Settings are stored per channel, so both slots see a change.
await _connector.setChannelSmazEnabled(5, true);
expect(_connector.isChannelSmazEnabled(1), isTrue);
await _connector.setChannelRegion(1, 'test-region');
expect(_connector.getChannelRegion(5), 'test-region');
radio.emitForTest(
ReviewFrames.channelMessage(
channelIndex: 5,
sender: 'Sam',
message: 'from the twin slot',
timestampSecs: DateTime.now().millisecondsSinceEpoch ~/ 1000,
),
);
await _waitFor(() => _texts(1).contains('from the twin slot'));
expect(_texts(5), contains('from the twin slot'));
expect(
_storedTexts(hikingId).where((t) => t == 'from the twin slot'),
hasLength(1),
);
});
test('an RX-log message is filed by its PSK-derived channel ID', () async {
final radio = _TestRadio();
await _connect(radio);
final localId = _id(_psk(2));
radio.emitForTest(
_logRxGroupText(
_psk(2),
'Ranger Pat: heard over the air',
DateTime.now().millisecondsSinceEpoch ~/ 1000,
),
);
await _waitFor(() => _texts(2).contains('heard over the air'));
expect(_storedTexts(localId), contains('heard over the air'));
expect(_texts(1), isNot(contains('heard over the air')));
});
}
+34
View File
@@ -330,6 +330,40 @@ void main() {
);
expect(r.pendingCount, 2);
});
test('clearChannel stops a reused slot finishing with old bytes', () {
final oldSet = buildImageChunks(
payload: payloadOf(300, seed: 1),
metadata: stdMeta,
senderPrefix: senderA,
imgId: 9,
);
final newPayload = payloadOf(300, seed: 2);
final newSet = buildImageChunks(
payload: newPayload,
metadata: stdMeta,
senderPrefix: senderA,
imgId: 9,
);
expect(newSet.dataChunkCount, greaterThanOrEqualTo(2));
final failures = <ImageReassemblyFailure>[];
final r = ImageReassembler(onFailed: failures.add);
r.addChunk(oldSet.blobs[0], channelIndex: 3);
r.addChunk(oldSet.blobs[0], channelIndex: 4);
r.clearChannel(3);
expect(failures.single.key.channelIndex, 3);
expect(
failures.single.reason,
ImageReassemblyFailureReason.channelChanged,
);
expect(r.pendingKeys.single.channelIndex, 4);
// Without the clear, these would complete with the old chunk 0.
final dataBlobs = newSet.blobs.sublist(0, newSet.dataChunkCount);
expect(feed(r, dataBlobs.sublist(1), channelIndex: 3), isNull);
expect(feed(r, [dataBlobs[0]], channelIndex: 3)!.data, newPayload);
});
});
group('parity recovery', () {
+3 -2
View File
@@ -604,6 +604,7 @@ void main() {
() async {
final store = ChannelMessageStore()..publicKeyHex = '1234567890';
final channelIndex = 1;
const channelId = '0123456789abcdef';
final rawPath = Uint8List(64)
..[0] = 0xBB
@@ -623,11 +624,11 @@ void main() {
final prefs = PrefsManager.instance;
await prefs.setString(
'${store.keyFor}$channelIndex',
'${store.keyFor}_$channelId',
jsonEncode(messageJson),
);
final messages = await store.loadChannelMessages(channelIndex);
final messages = await store.loadChannelMessages(channelId);
expect(messages, hasLength(1));
expect(messages.first.pathLength, equals(1));
expect(
+6 -4
View File
@@ -36,6 +36,8 @@ ChannelMessage _ch(
channelIndex: 0,
);
const _channelId = '0123456789abcdef';
void main() {
final base = DateTime(2026, 10, 1, 12);
@@ -127,10 +129,10 @@ void main() {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final received = base.add(const Duration(seconds: 42));
await store.saveChannelMessages(0, [
await store.saveChannelMessages(_channelId, [
_ch('one', timestamp: base, receivedAt: received),
]);
final loaded = await store.loadChannelMessages(0);
final loaded = await store.loadChannelMessages(_channelId);
expect(loaded.single.receivedAt, received);
expect(loaded.single.timestamp, base);
});
@@ -167,14 +169,14 @@ void main() {
'plainText': true,
};
await _init({
'channel_messages_${_device.substring(0, 10)}0': jsonEncode([
'channel_messages_${_device.substring(0, 10)}_$_channelId': jsonEncode([
record('old', past),
record('ahead', future),
]),
});
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final before = DateTime.now();
final loaded = await store.loadChannelMessages(0);
final loaded = await store.loadChannelMessages(_channelId);
expect(loaded, hasLength(2));
expect(
loaded[0].receivedAt.millisecondsSinceEpoch,
+54 -2
View File
@@ -210,6 +210,54 @@ void main() {
expect(h.decoder.calls, 1);
});
test('a stream started before its slot had an ID picks one up', () async {
final h = _build();
final set = buildImageChunks(
payload: _payload(kImageChunkFirstCapacity + kImageChunkCapacity + 1),
metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard),
senderPrefix: kSender,
imgId: 5,
);
expect(set.dataChunkCount, 3);
final first = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[0], channelIndex: 3),
channelIndex: 3,
);
expect(first!.channelId, isNull);
// A second data chunk of three neither completes nor recovers it.
final second = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[1], channelIndex: 3),
channelIndex: 3,
channelId: 'chan-id',
);
expect(second!.state, ReceivedImageState.receiving);
expect(second.streamId, first.streamId);
expect(second.channelId, 'chan-id');
});
test('a stream completed after its slot got an ID keeps it', () async {
final h = _build();
final set = buildImageChunks(
payload: _payload(kImageChunkFirstCapacity + 1),
metadata: const ImageStreamMetadata(rate: ImageCodecRatePoint.standard),
senderPrefix: kSender,
imgId: 6,
);
final first = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[0], channelIndex: 3),
channelIndex: 3,
);
expect(first!.channelId, isNull);
final done = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[1], channelIndex: 3),
channelIndex: 3,
channelId: 'chan-id',
);
expect(done!.streamId, first.streamId);
expect(done.channelId, 'chan-id');
});
test('two-chunk image reports 1 of 2 while incomplete', () async {
final h = _build();
final set = buildImageChunks(
@@ -962,7 +1010,7 @@ void main() {
group('deletion hooks', () {
test(
'deleteImagesForChannel reclaims every image of one conversation',
'deleteImagesForChannelId reclaims every image of one conversation',
() async {
final h = _build();
final a = await _completeOne(h, imgId: 130);
@@ -972,6 +1020,7 @@ void main() {
// A third image on another channel must survive.
final other = await h.store.registerOutgoing(
channelIndex: 9,
channelId: 'fedcba9876543210',
senderPrefix: kSelf,
imgId: 5,
previewPng: Uint8List.fromList(List<int>.filled(32, 2)),
@@ -979,7 +1028,7 @@ void main() {
chunkCount: 1,
);
final removed = await h.store.deleteImagesForChannel(3);
final removed = await h.store.deleteImagesForChannelId(_channel3Id);
expect(removed, containsAll(<String>[a.streamId, b.streamId]));
expect(h.store.entryFor(a.streamId), isNull);
expect(h.store.entryFor(b.streamId), isNull);
@@ -1480,7 +1529,10 @@ Future<ReceivedImageEntry> _completeOne(
final entry = await h.store.handleOutcome(
h.reassembler.addChunk(set.blobs[0], channelIndex: 3, now: h.clock()),
channelIndex: 3,
channelId: _channel3Id,
at: h.clock(),
);
return entry!;
}
const _channel3Id = '0123456789abcdef';
@@ -0,0 +1,351 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/models/image_codec_support.dart';
import 'package:meshcore_open/services/received_image_store.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/channel_order_store.dart';
import 'package:meshcore_open/storage/channel_region_store.dart';
import 'package:meshcore_open/storage/channel_settings_store.dart';
import 'package:meshcore_open/storage/channel_storage_migration.dart';
import 'package:meshcore_open/storage/channel_store.dart';
import 'package:meshcore_open/storage/legacy_key_migration.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _deviceA = 'aaaaaaaaaa0123456789';
const _deviceB = 'bbbbbbbbbb0123456789';
const _scopeA = 'aaaaaaaaaa';
final _pskOne = Uint8List.fromList(List<int>.generate(16, (i) => i + 1));
final _pskTwo = Uint8List.fromList(List<int>.generate(16, (i) => 100 + i));
final _idOne = Channel.storageIdForPsk(_pskOne)!;
final _idTwo = Channel.storageIdForPsk(_pskTwo)!;
Future<void> _init([Map<String, Object> values = const {}]) async {
SharedPreferences.setMockInitialValues(values);
PrefsManager.reset();
await PrefsManager.initialize();
ChannelMessageStore().forgetArchive();
}
ChannelMessage _ch(String text, int i) => ChannelMessage(
senderKey: null,
senderName: 'Bob',
text: text,
timestamp: DateTime.fromMillisecondsSinceEpoch(1000 * i),
isOutgoing: false,
status: ChannelMessageStatus.sent,
channelIndex: 0,
messageId: '$text-$i',
);
String _storedMessages(List<String> texts) => jsonEncode([
for (var i = 0; i < texts.length; i++)
{
'senderName': 'Bob',
'text': texts[i],
'timestamp': 1000 * (i + 1),
'isOutgoing': false,
'status': ChannelMessageStatus.sent.index,
'messageId': '${texts[i]}-$i',
'plainText': true,
},
]);
String _cachedChannels(Map<int, Uint8List> slots) => jsonEncode([
for (final entry in slots.entries)
{
'index': entry.key,
'name': 'ch${entry.key}',
'psk': base64Encode(entry.value),
'unreadCount': 0,
},
]);
void main() {
tearDown(scopesWithoutLegacyMigration.clear);
group('channel ID', () {
test('is stable, 16 hex chars, and absent for an empty slot', () {
expect(_idOne, hasLength(16));
expect(_idOne, matches(RegExp(r'^[0-9a-f]{16}$')));
expect(Channel.storageIdForPsk(Uint8List.fromList(_pskOne)), _idOne);
expect(_idOne, isNot(_idTwo));
expect(Channel.storageIdForPsk(Uint8List(16)), isNull);
expect(Channel.empty(3).storageId, isNull);
expect(Channel(index: 5, name: 'x', psk: _pskOne).storageId, _idOne);
});
});
group('ID-keyed stores', () {
test('messages save, load and clear by channel ID', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _deviceA;
await store.saveChannelMessages(_idOne, [_ch('one', 1)]);
await store.saveChannelMessages(_idTwo, [_ch('two', 1)]);
expect((await store.loadChannelMessages(_idOne)).single.text, 'one');
expect((await store.loadChannelMessages(_idTwo)).single.text, 'two');
expect(
PrefsManager.instance.containsKey(
'channel_messages_${_scopeA}_$_idOne',
),
isTrue,
);
await store.clearChannelMessages(_idOne);
expect(await store.loadChannelMessages(_idOne), isEmpty);
expect(await store.loadChannelMessages(_idTwo), hasLength(1));
});
test('the same channel ID is isolated per radio scope', () async {
await _init();
final a = ChannelMessageStore()..setPublicKeyHex = _deviceA;
final b = ChannelMessageStore()..setPublicKeyHex = _deviceB;
await a.saveChannelMessages(_idOne, [_ch('a', 1)]);
expect(await b.loadChannelMessages(_idOne), isEmpty);
final settingsB = ChannelSettingsStore()..setPublicKeyHex = _deviceB;
final settingsA = ChannelSettingsStore()..setPublicKeyHex = _deviceA;
await settingsA.saveSmazEnabled(_idOne, true);
expect(await settingsA.loadSmazEnabled(_idOne), isTrue);
expect(await settingsB.loadSmazEnabled(_idOne), isFalse);
});
test('the archive follows the channel ID', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _deviceA;
store.setArchived(_idOne, [_ch('old', 1), _ch('older', 2)]);
expect(store.archivedCount(_idOne), 2);
expect(store.archivedCount(_idTwo), isNull);
await store.saveChannelMessages(_idOne, [_ch('new', 3)]);
expect((await store.loadChannelMessages(_idOne)).map((m) => m.text), [
'old',
'older',
'new',
]);
store.forgetArchive(_idOne);
expect(store.archivedCount(_idOne), isNull);
});
test('settings, region and order are keyed by channel ID', () async {
await _init();
final settings = ChannelSettingsStore()..setPublicKeyHex = _deviceA;
await settings.saveCyr2LatEnabled(_idOne, true);
await settings.saveUrlImagesEnabled(_idOne, true);
await settings.saveCyr2LatProfileId(_idOne, 'sr');
expect(await settings.loadCyr2LatEnabled(_idOne), isTrue);
expect(await settings.loadUrlImagesEnabled(_idOne), isTrue);
expect(await settings.loadCyr2LatProfileId(_idOne), 'sr');
expect(await settings.loadCyr2LatEnabled(_idTwo), isFalse);
await settings.clearChannel(_idOne);
expect(await settings.loadCyr2LatEnabled(_idOne), isFalse);
expect(await settings.loadCyr2LatProfileId(_idOne), isNull);
final region = ChannelRegionStore()..setPublicKeyHex = _deviceA;
await region.saveRegion(_idOne, 'EU');
expect(await region.loadRegion(_idOne), 'EU');
expect(await region.loadRegion(_idTwo), '');
await ChannelRegionStore.clearRegionEverywhere('EU');
expect(await region.loadRegion(_idOne), '');
final order = ChannelOrderStore()..setPublicKeyHex = _deviceA;
await order.saveChannelOrder([_idTwo, _idOne]);
expect(await order.loadChannelOrder(), [_idTwo, _idOne]);
});
});
group('migration', () {
Map<String, Object> legacyValues() => {
'channels$_scopeA': _cachedChannels({0: _pskOne, 2: _pskTwo}),
'channel_messages_${_scopeA}0': _storedMessages(['hello']),
'channel_messages_2': _storedMessages(['unscoped']),
'channel_messages_${_scopeA}5': _storedMessages(['orphan']),
'channel_smaz_${_scopeA}0': true,
'channel_cyr2lat_${_scopeA}2': true,
'channel_url_images_${_scopeA}2': true,
'channel_cyr2lat_${_scopeA}profile_2': 'sr',
'channel_region_${_scopeA}0': 'EU',
'channel_order_$_scopeA': jsonEncode([2, 5, 0]),
};
test('moves messages, settings, region and order to channel IDs', () async {
await _init(legacyValues());
final mapping = await ChannelStorageMigration.migrate(_scopeA);
expect(mapping, {0: _idOne, 2: _idTwo});
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
expect((await messages.loadChannelMessages(_idOne)).single.text, 'hello');
// The unscoped legacy key migrates too.
expect(
(await messages.loadChannelMessages(_idTwo)).single.text,
'unscoped',
);
final settings = ChannelSettingsStore()..setPublicKeyHex = _deviceA;
expect(await settings.loadSmazEnabled(_idOne), isTrue);
expect(await settings.loadSmazEnabled(_idTwo), isFalse);
expect(await settings.loadCyr2LatEnabled(_idTwo), isTrue);
expect(await settings.loadUrlImagesEnabled(_idTwo), isTrue);
expect(await settings.loadCyr2LatProfileId(_idTwo), 'sr');
final region = ChannelRegionStore()..setPublicKeyHex = _deviceA;
expect(await region.loadRegion(_idOne), 'EU');
final order = ChannelOrderStore()..setPublicKeyHex = _deviceA;
expect(await order.loadChannelOrder(), [_idTwo, _idOne]);
final prefs = PrefsManager.instance;
expect(prefs.containsKey('channel_messages_${_scopeA}0'), isFalse);
expect(prefs.containsKey('channel_messages_2'), isFalse);
expect(prefs.containsKey('channel_smaz_${_scopeA}0'), isFalse);
expect(prefs.containsKey('channel_region_${_scopeA}0'), isFalse);
// A slot with no cached PSK is left alone.
expect(prefs.containsKey('channel_messages_${_scopeA}5'), isTrue);
// The slot map is seeded for the first post-migration diff.
expect(
await (ChannelStore()..setPublicKeyHex = _scopeA).loadSlotChannelIds(),
{0: _idOne, 2: _idTwo},
);
});
test('runs once per radio', () async {
await _init(legacyValues());
await ChannelStorageMigration.migrate(_scopeA);
await PrefsManager.instance.setString(
'channel_messages_${_scopeA}0',
_storedMessages(['late']),
);
expect(await ChannelStorageMigration.migrate(_scopeA), isEmpty);
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
expect((await messages.loadChannelMessages(_idOne)).single.text, 'hello');
expect(
PrefsManager.instance.containsKey('channel_messages_${_scopeA}0'),
isTrue,
);
});
test('a rerun after an interrupted migration loses and duplicates '
'nothing', () async {
// Killed after the new keys were written but before the old ones
// were removed and the done flag set.
await _init({
'channels$_scopeA': _cachedChannels({0: _pskOne, 2: _pskTwo}),
'channel_messages_${_scopeA}0': _storedMessages(['hello']),
'channel_messages_${_scopeA}_$_idOne': _storedMessages(['hello']),
'channel_order_$_scopeA': jsonEncode([_idTwo, _idOne]),
});
await ChannelStorageMigration.migrate(_scopeA);
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
expect((await messages.loadChannelMessages(_idOne)).map((m) => m.text), [
'hello',
]);
final order = ChannelOrderStore()..setPublicKeyHex = _deviceA;
expect(await order.loadChannelOrder(), [_idTwo, _idOne]);
expect(
PrefsManager.instance.containsKey('channel_messages_${_scopeA}0'),
isFalse,
);
});
test('skips a scope that must not adopt legacy data', () async {
await _init(legacyValues());
scopesWithoutLegacyMigration.add(_scopeA);
expect(await ChannelStorageMigration.migrate(_scopeA), isEmpty);
final prefs = PrefsManager.instance;
expect(prefs.containsKey('channel_messages_${_scopeA}0'), isTrue);
expect(prefs.containsKey('channel_storage_v2_$_scopeA'), isFalse);
expect(prefs.containsKey('channel_messages_2'), isTrue);
});
test('two slots with the same PSK merge into one history', () async {
await _init({
'channels$_scopeA': _cachedChannels({1: _pskOne, 4: _pskOne}),
'channel_messages_${_scopeA}1': _storedMessages(['first']),
'channel_messages_${_scopeA}4': _storedMessages(['second', 'third']),
});
expect(await ChannelStorageMigration.migrate(_scopeA), {
1: _idOne,
4: _idOne,
});
final messages = ChannelMessageStore()..setPublicKeyHex = _deviceA;
expect(
(await messages.loadChannelMessages(_idOne)).map((m) => m.text),
unorderedEquals(['first', 'second', 'third']),
);
});
});
group('received images', () {
final png = Uint8List.fromList(List<int>.filled(32, 7));
Future<ReceivedImageEntry> outgoing(
ReceivedImageStore store, {
required int slot,
String? channelId,
int imgId = 1,
}) => store.registerOutgoing(
channelIndex: slot,
channelId: channelId,
senderPrefix: 0x1234,
imgId: imgId,
previewPng: png,
rate: AeicRatePoint.ft32,
chunkCount: 1,
);
test('an entry round-trips its channel ID', () async {
final store = ReceivedImageStore(decoder: null);
final entry = await outgoing(store, slot: 2, channelId: _idOne);
final json = entry.toJson();
expect(json['channelId'], _idOne);
expect(ReceivedImageEntry.fromJson(json).channelId, _idOne);
expect(ReceivedImageEntry.fromJson({'streamId': 'x'}).channelId, isNull);
});
test('legacy entries get the ID their slot held', () async {
final blobs = InMemoryReceivedImageBlobStore();
final first = ReceivedImageStore(blobs: blobs, decoder: null);
final onSlot2 = await outgoing(first, slot: 2, imgId: 1);
final onSlot6 = await outgoing(first, slot: 6, imgId: 2);
final stamped = await outgoing(first, slot: 2, imgId: 3, channelId: 'x');
final store = ReceivedImageStore(blobs: blobs, decoder: null);
await store.load();
await store.stampLegacyChannelIds({2: _idOne, 3: _idTwo});
expect(store.entryFor(onSlot2.streamId)!.channelId, _idOne);
expect(store.entryFor(onSlot6.streamId)!.channelId, isNull);
expect(store.entryFor(stamped.streamId)!.channelId, 'x');
// Persisted, so the next launch keeps the stamp.
final reloaded = ReceivedImageStore(blobs: blobs, decoder: null);
await reloaded.load();
expect(reloaded.entryFor(onSlot2.streamId)!.channelId, _idOne);
});
test('delete by channel ID leaves a reused slot alone', () async {
final store = ReceivedImageStore(decoder: null);
final old = await outgoing(store, slot: 1, channelId: _idOne, imgId: 1);
final reused = await outgoing(
store,
slot: 1,
channelId: _idTwo,
imgId: 2,
);
expect(store.entriesForChannel(_idTwo).map((e) => e.streamId), [
reused.streamId,
]);
final removed = await store.deleteImagesForChannelId(_idOne);
expect(removed, [old.streamId]);
expect(store.entryFor(old.streamId), isNull);
expect(store.entryFor(reused.streamId), isNotNull);
});
});
}
+15 -10
View File
@@ -43,6 +43,8 @@ ChannelMessage _ch(int i) => ChannelMessage(
MessageStore _messageStore() => MessageStore()..setPublicKeyHex = _device;
const _channelId = '0123456789abcdef';
void main() {
group('MessageStore window persistence', () {
test('saving the window keeps archived history ahead of it', () async {
@@ -179,27 +181,30 @@ void main() {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final all = [for (var i = 0; i < 8; i++) _ch(i)];
await store.saveChannelMessages(0, all);
await store.saveChannelMessages(_channelId, all);
final loaded = await store.loadChannelMessages(0);
store.setArchived(0, loaded.sublist(0, 5));
await store.saveChannelMessages(0, [...loaded.sublist(5), _ch(8)]);
final loaded = await store.loadChannelMessages(_channelId);
store.setArchived(_channelId, loaded.sublist(0, 5));
await store.saveChannelMessages(_channelId, [
...loaded.sublist(5),
_ch(8),
]);
final reloaded = await store.loadChannelMessages(0);
final reloaded = await store.loadChannelMessages(_channelId);
expect(reloaded.map((m) => m.text), [for (var i = 0; i <= 8; i++) 'c$i']);
});
test('clearing through another instance resets the archive', () async {
await _init();
final store = ChannelMessageStore()..setPublicKeyHex = _device;
store.setArchived(0, [_ch(0), _ch(1)]);
await store.saveChannelMessages(0, [_ch(2)]);
store.setArchived(_channelId, [_ch(0), _ch(1)]);
await store.saveChannelMessages(_channelId, [_ch(2)]);
await (ChannelMessageStore()..setPublicKeyHex = _device)
.clearChannelMessages(0);
await store.saveChannelMessages(0, [_ch(3)]);
.clearChannelMessages(_channelId);
await store.saveChannelMessages(_channelId, [_ch(3)]);
final reloaded = await store.loadChannelMessages(0);
final reloaded = await store.loadChannelMessages(_channelId);
expect(reloaded.map((m) => m.text), ['c3']);
});
});
@@ -17,6 +17,8 @@ Future<void> _init(Map<String, Object> values) async {
await PrefsManager.initialize();
}
const _channelId = '0123456789abcdef';
void main() {
test(
'message store skips a malformed record instead of dropping all',
@@ -42,13 +44,13 @@ void main() {
test('channel message store skips a malformed record', () async {
await _init({
'channel_messages_${_device.substring(0, 10)}0': jsonEncode([
'channel_messages_${_device.substring(0, 10)}_$_channelId': jsonEncode([
{'text': 'hi', 'timestamp': 1000, 'status': 1},
'garbage',
]),
});
final store = ChannelMessageStore()..setPublicKeyHex = _device;
final messages = await store.loadChannelMessages(0);
final messages = await store.loadChannelMessages(_channelId);
expect(messages.map((m) => m.text), ['hi']);
});