fix(#1128): a key change asks keep or delete; no history stays hidden

Owner ruling: a channel's message history either stays or goes, never
kept hidden for a later re-add.

- Edit Channel asks Keep or Delete when the key changes (hashtag rename,
  new private key). Cancel writes nothing. Same-key renames ask nothing.
- The answer is applied once the radio confirms the clear. Keep moves the
  rows (copy, verify, delete only what was copied, repeat) and the phone
  notify mode; Delete removes the old key's history.
- After a sync that saw every slot, confirmed them all, found none erased
  and had no write in flight, history no channel on the radio shows is
  deleted, each key logged. Restore's case (erased slots) and partial
  syncs delete nothing; a radio with no channels deletes nothing.
- A different channel over a slot is settled by that sync, since 1.7.0
  firmware may move the occupant rather than wipe it.
- Keep history that could not land (add refused, move failed) is spared
  for the connection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/1133/head
diffwireauto 3 weeks ago committed by Strycher
parent c512c39a6e
commit f12d5064c5

@ -235,8 +235,16 @@ enum ChannelWrite {
/// An edit to a new key cleared the old channel, but the new one was not
/// confirmed, so the slot is now empty. (#1026)
clearedNotAdded,
/// The radio took the new key, but the old key's message history, which
/// the user chose to keep, could not be moved to it. (#1128)
historyNotMoved,
}
/// What a channel key change does with the old key's message history. The
/// user is asked; history is never kept hidden (#1128).
enum KeyChangeHistory { keep, delete }
/// Result of [MeshCoreConnector.exportPrivateKey]. [identity] is
/// non-null only when [outcome] is [IdentityTransfer.ok]. (#578)
class IdentityExportResult {
@ -538,6 +546,11 @@ class MeshCoreConnector extends ChangeNotifier {
bool _batteryRequested = false;
bool _awaitingSelfInfo = false;
bool _hasReceivedDeviceInfo = false;
/// This connection's device info has said how many channel slots the radio
/// has, on every transport ([_hasReceivedDeviceInfo] is set only where the
/// initial sync is gated on it). (#1128)
bool _slotCountKnown = false;
// Initial sync is serialized for predictable progress. Firmware exposes one
// FIFO queued-message stream, so direct/room frames are buffered until after
// contacts are known.
@ -4587,6 +4600,8 @@ class MeshCoreConnector extends ChangeNotifier {
storageService?.setPublicKeyHex = '';
// Device-scoped: the next radio's device info supplies its own pin (#1100).
_deviceBlePin = null;
// Kept history a key change could not land belongs to this radio (#1128).
_sparedFromPurge.clear();
_applySelfKeyToBlockService();
}
@ -4601,6 +4616,7 @@ class MeshCoreConnector extends ChangeNotifier {
_selfInfoRetryTimer?.cancel();
_selfInfoRetryTimer = null;
_hasReceivedDeviceInfo = false;
_slotCountKnown = false;
// Drop the previous radio's in-memory history before a new connection loads
// its own. These caches are keyed by channel index / contact key, not by
// radio, so without this a radio switch would keep showing the prior
@ -4689,6 +4705,10 @@ class MeshCoreConnector extends ChangeNotifier {
void setAppDebugLogServiceForTest(AppDebugLogService service) =>
_appDebugLogService = service;
@visibleForTesting
void setAppSettingsServiceForTest(AppSettingsService service) =>
_appSettingsService = service;
/// The state a BLE link leaves behind: a radio to go back to. (#997)
@visibleForTesting
void primeAutoReconnectForTest(String deviceId) {
@ -5084,6 +5104,7 @@ class MeshCoreConnector extends ChangeNotifier {
_batteryRequested = false;
_awaitingSelfInfo = false;
_hasReceivedDeviceInfo = false;
_slotCountKnown = false;
_maxContacts = _defaultMaxContacts;
_maxChannels = _defaultMaxChannels;
_resetSyncProgressState();
@ -7108,6 +7129,10 @@ class MeshCoreConnector extends ChangeNotifier {
'[ChannelSync] Sync complete: received ${_channels.length}/$_totalChannelsToRequest channels'
'${_unconfirmedChannelSlots.isEmpty ? '' : ', unconfirmed slots: $_unconfirmedChannelSlots'}',
);
// A sync before device info, or one asked for fewer slots, has not seen
// every channel, so it cannot say what the radio does not hold (#1128).
final sawEverySlot =
_slotCountKnown && _totalChannelsToRequest >= _maxChannels;
_cleanupChannelSync(completed: true);
@ -7165,6 +7190,10 @@ class MeshCoreConnector extends ChangeNotifier {
);
}),
);
// Only here: an erased slot means the radio lost channels that Restore
// can put back with their history, and a hole means the list is not
// known. Neither is a list to judge history against (#1128).
if (sawEverySlot) unawaited(_purgeHistoryNotOnRadio());
} else {
// Holes: keep the last fully-confirmed persisted list for offline use
// rather than overwriting it with a partial one. The holes are surfaced
@ -7342,6 +7371,7 @@ class MeshCoreConnector extends ChangeNotifier {
int _channelWritesInFlight = 0;
bool _channelSyncDeferredByWrite = false;
final Set<String> _sparedFromPurge = {};
/// True while the channel list cannot be trusted to show which slots are
/// free: a sync is re-reading it, or a write has not been answered yet. A
@ -7480,9 +7510,11 @@ class MeshCoreConnector extends ChangeNotifier {
/// OffbandMesh/meshcore-firmware#1864 refuses a different channel over an
/// occupied slot, and that is what a new key in place is.
///
/// A new key is a slot reassignment for history purposes, the same as
/// before the clear-then-add: the old key's PSK-keyed history is kept, so
/// it comes back if that key is ever re-added (#1063).
/// A new key needs [history], the user's answer to what happens to the old
/// key's messages (#1128). It is applied as soon as the radio confirms the
/// clear, never waiting on the add, so the old key's history is never left
/// hidden: Keep moves it and the notify mode to the new key, Delete removes
/// it as Delete Channel would.
///
/// If the clear lands and the add does not, the slot is left empty and this
/// returns [ChannelWrite.clearedNotAdded], so the user is told the channel is
@ -7490,10 +7522,17 @@ class MeshCoreConnector extends ChangeNotifier {
Future<ChannelWrite> editChannel(
Channel channel,
String name,
Uint8List psk,
) async {
Uint8List psk, {
KeyChangeHistory? history,
}) async {
if (!isConnected) return ChannelWrite.noReply;
if (listEquals(channel.psk, psk)) {
final keyChanges = !listEquals(channel.psk, psk);
if (keyChanges && history == null) {
throw ArgumentError(
'A key change needs the keep-or-delete history answer (#1128)',
);
}
if (!keyChanges) {
return _setChannel(
channel.index,
name,
@ -7509,6 +7548,15 @@ class MeshCoreConnector extends ChangeNotifier {
_syncAfterChannelWrites();
return cleared;
}
final newPskHex = Channel(
index: channel.index,
name: name,
psk: psk,
).pskHex;
final moved = await _applyKeyChangeHistory(channel, newPskHex, history!);
// The user said keep. What could not be moved stays under the old key,
// and the sync after this write must not delete it as hidden.
if (!moved) _sparedFromPurge.add(channel.pskHex);
await _retireSlotOccupant(channel.index);
final added = await _setChannel(
channel.index,
@ -7517,9 +7565,14 @@ class MeshCoreConnector extends ChangeNotifier {
occupantPsk: null,
refresh: true,
);
return added == ChannelWrite.ok
? ChannelWrite.ok
: ChannelWrite.clearedNotAdded;
if (added != ChannelWrite.ok) {
// The kept history now waits under a key the radio does not hold, for
// the user to add the channel again; the sync after this write must
// not delete it as hidden (#1128).
if (history == KeyChangeHistory.keep) _sparedFromPurge.add(newPskHex);
return ChannelWrite.clearedNotAdded;
}
return moved ? ChannelWrite.ok : ChannelWrite.historyNotMoved;
} finally {
_endChannelWrite();
}
@ -7633,13 +7686,69 @@ class MeshCoreConnector extends ChangeNotifier {
/// - legacy slot-index keys (pre-#194) would be adopted onto the new
/// occupant by the store's one-time migration; purge them (#193/#1063).
/// - the in-memory conversation map is slot-keyed; drop this slot's entry.
/// The old occupant's PSK-keyed history is deliberately left intact: if
/// that channel is ever re-added (any slot), its history comes back (#1063).
/// The old occupant's PSK-keyed history is settled by the full sync every
/// write ends with, not here: firmware that moves a channel out of the way
/// (#1896) still holds it, so it keeps its history, and a channel the radio
/// no longer holds has its history deleted by that sync (#1128).
Future<void> _retireSlotOccupant(int index) async {
await _channelMessageStore.clearLegacySlotHistory(index);
_channelMessages.remove(index);
}
/// Applies the user's keep-or-delete answer for a key change once the radio
/// has confirmed the clear (#1128). Returns false when Keep could not move
/// the history; the store has logged why and left it under the old key.
Future<bool> _applyKeyChangeHistory(
Channel channel,
String newPskHex,
KeyChangeHistory history,
) async {
_appDebugLogService?.info(
'Key change on slot ${channel.index} "${channel.name}": user chose to '
'${history.name} its message history',
tag: 'ChannelWrite',
);
if (history == KeyChangeHistory.delete) {
await _channelMessageStore.deleteChannelHistory(channel.pskHex);
return true;
}
final moved = await _channelMessageStore.moveChannelHistory(
channel.pskHex,
newPskHex,
);
await _appSettingsService?.moveChannelNotifyMode(
devicePrefix: selfPublicKeyHex,
fromPskHex: channel.pskHex,
toPskHex: newPskHex,
);
return moved != null;
}
/// Deletes this radio's channel history that no channel on it shows, after
/// a sync the radio fully confirmed with nothing erased (#1128). Not while a
/// write is waiting on the radio: the list could be mid-change.
///
/// [_sparedFromPurge] holds keys whose kept history a key change could not
/// put on the radio: the add was not confirmed, or the move failed. It lasts
/// for this connection, and a key leaves it once the radio holds it again,
/// so a later delete of that channel is judged normally.
Future<void> _purgeHistoryNotOnRadio() async {
if (_channelWritesInFlight > 0) return;
final onRadio = _channels.where((c) => !c.isUnusable).toList();
_sparedFromPurge.removeAll(onRadio.map((c) => c.pskHex));
try {
await _channelMessageStore.purgeHistoryNotOnRadio(
radioPskHex: {...onRadio.map((c) => c.pskHex), ..._sparedFromPurge},
occupiedSlots: onRadio.map((c) => c.index).toSet(),
);
} catch (e) {
_appDebugLogService?.error(
'Could not delete history no channel on the radio shows: $e',
tag: 'Storage',
);
}
}
// --- Offband GPS query (CMD_OFFBAND_GPS / RESP_CODE_OFFBAND_GPS = 0xC1) (#135)
OffbandGpsStatus? _latestOffbandGpsStatus;
Completer<OffbandGpsStatus?>? _offbandGpsCompleter;
@ -9105,6 +9214,7 @@ class MeshCoreConnector extends ChangeNotifier {
if (_shouldGateInitialChannelSync) {
_hasReceivedDeviceInfo = true;
}
_slotCountKnown = true;
_firmwareVerCode = frame[1];
// Readable build date / model / firmware version, NUL-terminated strings
@ -11765,6 +11875,7 @@ class MeshCoreConnector extends ChangeNotifier {
// Preserve deviceId and displayName for UI display during reconnection
// They're only cleared on manual disconnect via disconnect() method
_hasReceivedDeviceInfo = false;
_slotCountKnown = false;
// But NOT the identity that scopes stored data (#158). A manual
// disconnect() clears _selfPublicKey; an unexpected drop did not, so
// every per-radio store, and the one channels_screen builds from

@ -85,12 +85,51 @@ bool explainUnconfirmedChannelWrite(BuildContext context, ChannelWrite result) {
ChannelWrite.rejected => l10n.channels_writeRejected,
ChannelWrite.noReply => l10n.channels_writeNoReply,
ChannelWrite.clearedNotAdded => l10n.channels_writeClearedNotAdded,
ChannelWrite.historyNotMoved => l10n.channels_writeHistoryNotMoved,
};
if (message == null) return false;
showChannelBlockedMessage(context, message);
return true;
}
/// Asks what a key change does with [channelName]'s message history: kept
/// under the new key, or deleted. Null means the user backed out, and nothing
/// may be written (#1128).
Future<KeyChangeHistory?> askKeyChangeHistory(
BuildContext context,
String channelName,
) {
return showDialog<KeyChangeHistory>(
context: context,
builder: (dialogContext) {
final l10n = dialogContext.l10n;
return AlertDialog(
title: Text(l10n.channels_keyChangeHistoryTitle),
content: Text(l10n.channels_keyChangeHistoryBody(channelName)),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(l10n.common_cancel),
),
TextButton(
style: TextButton.styleFrom(
foregroundColor: Theme.of(dialogContext).colorScheme.error,
),
onPressed: () =>
Navigator.pop(dialogContext, KeyChangeHistory.delete),
child: Text(l10n.channels_keyChangeDeleteHistory),
),
FilledButton(
onPressed: () =>
Navigator.pop(dialogContext, KeyChangeHistory.keep),
child: Text(l10n.channels_keyChangeKeepHistory),
),
],
);
},
);
}
/// Refuses a second Public channel, and says so. Returns true if it refused.
///
/// Public is identified by its PSK (`Channel.isPublicChannel`), not by name or

@ -1093,6 +1093,31 @@
"@channels_writeClearedNotAdded": {
"description": "A channel key change is clear-then-add; the clear landed and the add did not, so the edited channel is gone from the radio. Persistent (#1026)."
},
"channels_writeHistoryNotMoved": "The channel was changed, but its message history could not be moved to it. The app log has the details.",
"@channels_writeHistoryNotMoved": {
"description": "The user chose to keep message history across a key change; the radio took the new key but the app could not move the stored messages. Persistent (#1128)."
},
"channels_keyChangeHistoryTitle": "Keep message history?",
"@channels_keyChangeHistoryTitle": {
"description": "Title of the question asked before a channel's key changes (a hashtag rename, or a new private key) (#1128)."
},
"channels_keyChangeHistoryBody": "This gives \"{name}\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.",
"@channels_keyChangeHistoryBody": {
"description": "Body of the keep-or-delete question for a channel key change (#1128).",
"placeholders": {
"name": {
"type": "String"
}
}
},
"channels_keyChangeKeepHistory": "Keep message history",
"@channels_keyChangeKeepHistory": {
"description": "Moves the channel's stored messages to its new key (#1128)."
},
"channels_keyChangeDeleteHistory": "Delete message history",
"@channels_keyChangeDeleteHistory": {
"description": "Deletes the channel's stored messages, as Delete Channel does (#1128)."
},
"channels_sortBy": "Sort by",
"channels_sortManual": "Manual",
"channels_sortAZ": "A-Z",

@ -3382,6 +3382,36 @@ abstract class AppLocalizations {
/// **'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.'**
String get channels_writeClearedNotAdded;
/// The user chose to keep message history across a key change; the radio took the new key but the app could not move the stored messages. Persistent (#1128).
///
/// In en, this message translates to:
/// **'The channel was changed, but its message history could not be moved to it. The app log has the details.'**
String get channels_writeHistoryNotMoved;
/// Title of the question asked before a channel's key changes (a hashtag rename, or a new private key) (#1128).
///
/// In en, this message translates to:
/// **'Keep message history?'**
String get channels_keyChangeHistoryTitle;
/// Body of the keep-or-delete question for a channel key change (#1128).
///
/// In en, this message translates to:
/// **'This gives \"{name}\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.'**
String channels_keyChangeHistoryBody(String name);
/// Moves the channel's stored messages to its new key (#1128).
///
/// In en, this message translates to:
/// **'Keep message history'**
String get channels_keyChangeKeepHistory;
/// Deletes the channel's stored messages, as Delete Channel does (#1128).
///
/// In en, this message translates to:
/// **'Delete message history'**
String get channels_keyChangeDeleteHistory;
/// No description provided for @channels_sortBy.
///
/// In en, this message translates to:

@ -1933,6 +1933,24 @@ class AppLocalizationsBg extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Сортирай по';

@ -1928,6 +1928,24 @@ class AppLocalizationsDe extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Sortiere nach';

@ -1906,6 +1906,24 @@ class AppLocalizationsEn extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Sort by';

@ -1929,6 +1929,24 @@ class AppLocalizationsEs extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Ordenar por';

@ -1934,6 +1934,24 @@ class AppLocalizationsFr extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Trier par';

@ -1934,6 +1934,24 @@ class AppLocalizationsHu extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Szűrés';

@ -1931,6 +1931,24 @@ class AppLocalizationsIt extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Ordina per';

@ -1872,6 +1872,24 @@ class AppLocalizationsJa extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => '並び替え';

@ -1867,6 +1867,24 @@ class AppLocalizationsKo extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => '정렬 기준 선택';

@ -1919,6 +1919,24 @@ class AppLocalizationsNl extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Sorteren door';

@ -1940,6 +1940,24 @@ class AppLocalizationsPl extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Sortuj po';

@ -1928,6 +1928,24 @@ class AppLocalizationsPt extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Ordenar por';

@ -1929,6 +1929,24 @@ class AppLocalizationsRu extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Сортировка';

@ -1920,6 +1920,24 @@ class AppLocalizationsSk extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Triediť podľa';

@ -1917,6 +1917,24 @@ class AppLocalizationsSl extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Sortiraj po';

@ -1909,6 +1909,24 @@ class AppLocalizationsSv extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Sortera efter';

@ -1924,6 +1924,24 @@ class AppLocalizationsUk extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => 'Сортувати за';

@ -1853,6 +1853,24 @@ class AppLocalizationsZh extends AppLocalizations {
String get channels_writeClearedNotAdded =>
'The old channel was removed, but the radio did not confirm the new one, so that slot is now empty. Add the channel again.';
@override
String get channels_writeHistoryNotMoved =>
'The channel was changed, but its message history could not be moved to it. The app log has the details.';
@override
String get channels_keyChangeHistoryTitle => 'Keep message history?';
@override
String channels_keyChangeHistoryBody(String name) {
return 'This gives \"$name\" a new key. Keep its message history under the new key, or delete it? Deleted history cannot be recovered.';
}
@override
String get channels_keyChangeKeepHistory => 'Keep message history';
@override
String get channels_keyChangeDeleteHistory => 'Delete message history';
@override
String get channels_sortBy => '排序方式';

@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:math';
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
@ -1823,12 +1824,29 @@ class _ChannelsScreenState extends State<ChannelsScreen>
return;
}
// #1128: a new key asks what happens to the old key's history.
// Backing out leaves this dialog open and writes nothing.
KeyChangeHistory? history;
if (!listEquals(psk, channel.psk)) {
history = await askKeyChangeHistory(
dialogContext,
channel.name,
);
appLogger.info(
'Key change for slot ${channel.index} "${channel.name}": '
'history answer ${history?.name ?? 'cancelled'}',
tag: 'ChannelWrite',
);
if (history == null || !dialogContext.mounted) return;
}
Navigator.pop(dialogContext);
try {
final result = await connector.editChannel(
channel,
name,
psk,
history: history,
);
if (result != ChannelWrite.ok) {
if (!context.mounted) return;

@ -404,6 +404,30 @@ class AppSettingsService extends ChangeNotifier {
);
}
/// Carries a channel's notify mode from its old key to its new one, when a
/// key change keeps the channel's history (#1128).
Future<void> moveChannelNotifyMode({
required String devicePrefix,
required String fromPskHex,
required String toPskHex,
}) async {
final prefix = radioScopePrefix(devicePrefix);
final mode = _settings.channelNotifyModesByRadio[prefix]?[fromPskHex];
if (prefix.isEmpty || fromPskHex == toPskHex || mode == null) return;
final byRadio = _copyByRadio();
final radioModes = byRadio[prefix]!;
radioModes.remove(fromPskHex);
radioModes[toPskHex] = mode;
await updateSettings(
_settings.copyWith(channelNotifyModesByRadio: byRadio),
);
appLogger.info(
'Notify mode ${mode.name} moved with the channel on radio $prefix: psk '
'${pskFingerprint(fromPskHex)} -> ${pskFingerprint(toPskHex)}',
tag: 'NotifyMode',
);
}
/// Drops [devicePrefix]'s notify modes, the per-radio part of this global
/// blob, after that radio was factory reset (#1054).
Future<void> forgetRadio(String devicePrefix) async {

@ -1,4 +1,5 @@
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:meshcore_open/utils/app_logger.dart';
@ -405,6 +406,193 @@ class ChannelMessageStore {
}
}
String _pskKey(String pskHex) => '$keyFor$_pskMarker$pskHex';
/// Moves every message stored under [fromPskHex] to [toPskHex], for a key
/// change the user chose to keep history across (#1128).
///
/// Copy, verify, then delete: an interruption leaves the history under both
/// keys, never under neither. A message already under the new key keeps
/// that copy. Only the copied rows are deleted, and the pass repeats, so a
/// message saved to the old key mid-move is moved too rather than lost.
/// Returns how many messages the new key gained, or null when the move
/// could not be done safely, in which case whatever was not yet moved is
/// left under the old key and the reason is logged as an error.
Future<int?> moveChannelHistory(String fromPskHex, String toPskHex) async {
final what =
'channel history psk ${_fingerprint(fromPskHex)} -> '
'${_fingerprint(toPskHex)}';
if (publicKeyHex.isEmpty || fromPskHex.isEmpty || toPskHex.isEmpty) {
appLogger.error(
'NOT moving $what: no radio key or no channel key',
tag: 'Storage',
);
return null;
}
if (fromPskHex == toPskHex) return 0;
final from = _pskKey(fromPskHex);
final to = _pskKey(toPskHex);
final blobs = BlobStore.instance;
for (final key in [from, to]) {
if (!await blobs.ensureMessageRowsMigrated(key, channelHistoryToRows)) {
appLogger.error(
'NOT moving $what: $key could not be moved onto rows. Both keys '
'are unchanged.',
tag: 'Storage',
);
return null;
}
}
var moved = 0;
var gained = 0;
for (var pass = 0; pass < 3; pass++) {
final payloads = await blobs.messagePayloads(from);
if (payloads.isEmpty) break;
final already = await blobs.messageMergeKeys(to);
final sourceKeys = <String>{};
final rows = <MessageRowInput>[];
for (final payload in payloads) {
final ChannelMessage m;
try {
m = _messageFromJson(jsonDecode(payload) as Map<String, dynamic>);
} catch (e) {
appLogger.error(
'NOT moving $what: a stored message will not decode ($e). '
'$moved message(s) were moved before this; the rest stay under '
'the old key.',
tag: 'Storage',
);
return null;
}
final mergeKey = _mergeKey(m);
sourceKeys.add(mergeKey);
if (already.contains(mergeKey)) continue;
rows.add(
MessageRowInput(
mergeKey: mergeKey,
timestampMs: m.timestamp.millisecondsSinceEpoch,
payload: payload,
),
);
}
await blobs.upsertMessageRows(to, rows);
final missing = sourceKeys.difference(await blobs.messageMergeKeys(to));
if (missing.isNotEmpty) {
appLogger.error(
'NOT finishing $what: ${missing.length} of ${sourceKeys.length} '
'messages did not read back under the new key. They stay under the '
'old key.',
tag: 'Storage',
);
return null;
}
await blobs.deleteMessageRowsIn(from, sourceKeys);
moved += sourceKeys.length;
gained += rows.length;
}
final left = await blobs.messageRowCount(from);
if (left > 0) {
appLogger.error(
'NOT finishing $what: $left message(s) kept arriving under the old '
'key; they stay there.',
tag: 'Storage',
);
return null;
}
await blobs.deleteEverywhere(from);
appLogger.info(
'Moved $what: $moved message(s), $gained new to the new key (#1128)',
tag: 'Storage',
);
return gained;
}
/// Deletes everything stored under [pskHex] for this radio, the history
/// half of Delete Channel, addressed by key rather than slot (#1128).
Future<void> deleteChannelHistory(String pskHex) async {
if (publicKeyHex.isEmpty || pskHex.isEmpty) {
appLogger.error(
'NOT deleting channel history psk ${_fingerprint(pskHex)}: no radio '
'key or no channel key',
tag: 'Storage',
);
return;
}
final key = _pskKey(pskHex);
final blobs = BlobStore.instance;
final count = await blobs.messageRowCount(key);
await blobs.deleteEverywhere(key);
await blobs.deleteMessageRows(key);
appLogger.info(
'Deleted channel history psk ${_fingerprint(pskHex)}: $count message '
'row(s) (#1128)',
tag: 'Storage',
);
}
/// Deletes this radio's channel history that no channel on it can show:
/// history under a key the radio does not hold, and pre-#194 slot history
/// for a slot that holds nothing. History is never kept hidden (#1128).
///
/// The caller passes the radio's fully confirmed channel list, with no
/// erased slots. Restore (#1117) only has work when slots are erased, so
/// its channels' history is never what this sees.
///
/// Returns the deleted keys, each logged with its row count.
Future<List<String>> purgeHistoryNotOnRadio({
required Set<String> radioPskHex,
required Set<int> occupiedSlots,
}) async {
if (publicKeyHex.isEmpty) return const [];
if (radioPskHex.isEmpty) {
appLogger.warn(
'Radio $publicKeyHex reports no channels at all; not deleting any '
'channel history on that (#1128)',
tag: 'Storage',
);
return const [];
}
final blobs = BlobStore.instance;
final pskPrefix = '$keyFor$_pskMarker';
final slotKey = RegExp('^${RegExp.escape(keyFor)}(\\d+)\$');
final candidates = {
...await blobs.keysWithPrefix(keyFor),
...(await blobs.messageStoreKeys()).where((k) => k.startsWith(keyFor)),
};
final deleted = <String>[];
for (final key in candidates.toList()..sort()) {
final String label;
if (key.startsWith(pskPrefix)) {
final pskHex = key.substring(pskPrefix.length);
if (radioPskHex.contains(pskHex)) continue;
label = 'psk ${_fingerprint(pskHex)}';
} else {
final slot = slotKey.firstMatch(key)?.group(1);
if (slot == null || occupiedSlots.contains(int.parse(slot))) continue;
label = 'empty slot $slot (pre-#194)';
}
final count = await blobs.messageRowCount(key);
await blobs.deleteEverywhere(key);
await blobs.deleteMessageRows(key);
deleted.add(key);
appLogger.info(
'Deleted hidden channel history of radio $publicKeyHex, $label: '
'$count message row(s), no channel on the radio shows it (#1128)',
tag: 'Storage',
);
}
return deleted;
}
static String _fingerprint(String pskHex) => pskHex.isEmpty
? 'none'
: sha256.convert(utf8.encode(pskHex)).toString().substring(0, 8);
/// Clear all channel messages
Future<void> clearAllChannelMessages() async {
final blobs = BlobStore.instance;

@ -381,6 +381,26 @@ class BlobStore {
.go();
}
/// Removes the messages under [storeKey] whose identity is in [mergeKeys],
/// and no others, so a message saved meanwhile survives (#1128). Chunked
/// under SQLite's bound-variable limit.
Future<void> deleteMessageRowsIn(
String storeKey,
Iterable<String> mergeKeys,
) async {
final keys = mergeKeys.toList();
for (var i = 0; i < keys.length; i += 500) {
final chunk = keys.sublist(
i,
i + 500 > keys.length ? keys.length : i + 500,
);
await (_db.delete(
_db.messageRecords,
)..where((t) => t.storeKey.equals(storeKey) & t.mergeKey.isIn(chunk)))
.go();
}
}
/// Removes every message under [storeKey], for the stores' clear paths.
Future<void> deleteMessageRows(String storeKey) async {
await (_db.delete(

@ -1,11 +1,13 @@
// #1026 on top of #1063: what a confirmed channel write does to PSK-keyed
// history.
// #1128 on top of #1026/#1063: what a confirmed channel write does to
// PSK-keyed history.
//
// History is keyed by the channel's PSK (#194). Giving a slot to a different
// channel is a reassignment: the old channel's history is kept, so it comes
// back if that channel is ever re-added (#1063). Deleting a channel is the one
// path that removes its history outright. Both happen only after the radio's
// OK (#1026). Exercised through the real store, not the in-memory map.
// History is never kept hidden. A key change asks: Keep moves the old key's
// history (and phone notify mode) to the new key, Delete removes it, both as
// soon as the radio confirms the clear. A different channel written over a
// slot is settled by the next sync that saw every slot: history no channel on
// the radio shows is deleted, and a channel the firmware moved keeps its own.
// A radio with erased slots (the Restore case) or a partial sync deletes
// nothing. Exercised through the real store, not the in-memory map.
import 'dart:typed_data';
@ -13,8 +15,10 @@ import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/connector/meshcore_protocol.dart';
import 'package:meshcore_open/models/app_settings.dart';
import 'package:meshcore_open/models/channel.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/services/app_settings_service.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/drift/blob_store.dart';
import 'package:meshcore_open/storage/drift/offband_database.dart';
@ -40,19 +44,45 @@ ChannelMessage msg(String text) => ChannelMessage(
messageId: text,
);
const int slots = 2;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late OffbandDatabase db;
late MeshCoreConnector connector;
late AppSettingsService settings;
late List<Uint8List> sent;
final weather = Channel(index: 0, name: 'Weather', psk: psk(0x22));
final empty = Uint8List(16);
/// History stored under a key, whatever slot that channel is in.
ChannelMessageStore historyOf(Uint8List key) => ChannelMessageStore()
..setPublicKeyHex = connector.selfPublicKeyHex
..channelPskResolver = (_) => Channel(index: 0, name: '', psk: key).pskHex;
/// Reads the history stored under [weather]'s PSK, whatever slot it is in.
late ChannelMessageStore weatherHistory;
Future<void> settle([int turns = 1]) async {
for (var i = 0; i < turns; i++) {
await Future<void>.delayed(Duration.zero);
}
}
Future<void> settle() => Future<void>.delayed(Duration.zero);
void ok() => connector.handleFrameForTest([respCodeOk]);
/// The radio answers a sync of every slot with [bySlot] (null = empty).
Future<void> radioHolds(
List<(String, Uint8List)?> bySlot, {
bool start = true,
}) async {
if (start) await connector.getChannels(maxChannels: slots, force: true);
for (var i = 0; i < slots; i++) {
final c = bySlot[i];
connector.handleFrameForTest(channelInfo(i, c?.$1 ?? '', c?.$2 ?? empty));
await settle();
}
await settle(50);
}
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
@ -60,25 +90,27 @@ void main() {
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
sent = [];
connector = MeshCoreConnector();
connector.sendFrameOverrideForTest = (_) {};
connector.sendFrameOverrideForTest = sent.add;
connector.setConnectedForTest();
connector.setSelfPublicKeyForTest(
Uint8List.fromList(List<int>.generate(32, (i) => i)),
);
connector.wireMessageStoreForTest();
settings = AppSettingsService();
await settings.loadSettings();
connector.setAppSettingsServiceForTest(settings);
// The radio holds Weather in slot 0.
await connector.getChannels(maxChannels: 1, force: true);
connector.handleFrameForTest(channelInfo(0, weather.name, weather.psk));
// Device info says the radio has [slots] channel slots.
connector.handleFrameForTest([respCodeDeviceInfo, 14, 100, slots]);
await settle();
expect(connector.channels.single.pskHex, weather.pskHex);
weatherHistory = ChannelMessageStore()
..setPublicKeyHex = connector.selfPublicKeyHex
..channelPskResolver = (_) => weather.pskHex;
await weatherHistory.saveChannelMessages(0, [msg('kept')]);
expect(await weatherHistory.loadChannelMessages(0), hasLength(1));
await radioHolds([(weather.name, weather.psk), null]);
expect(connector.channels.first.pskHex, weather.pskHex);
await historyOf(weather.psk).saveChannelMessages(0, [msg('kept')]);
expect(await historyOf(weather.psk).loadChannelMessages(0), hasLength(1));
});
tearDown(() async {
@ -86,28 +118,231 @@ void main() {
await db.close();
});
test(
'a slot given to another channel keeps the old one\'s history',
() async {
final write = connector.setChannel(0, 'Other', psk(0x33), refresh: false);
/// Runs a key-change edit of Weather to [newKey], with the radio answering
/// the clear OK and the add with [addReply].
Future<ChannelWrite> changeKey(
Uint8List newKey,
KeyChangeHistory history, {
List<int>? addReply,
}) async {
final edit = connector.editChannel(
weather,
'Weather',
newKey,
history: history,
);
await settle();
ok(); // the clear
await settle(50);
connector.handleFrameForTest(addReply ?? [respCodeOk]);
return edit;
}
group('key change', () {
test(
'Keep moves the history to the new key, none left under the old',
() async {
expect(
await changeKey(psk(0x99), KeyChangeHistory.keep),
ChannelWrite.ok,
);
await radioHolds([('Weather', psk(0x99)), null], start: false);
expect(await historyOf(psk(0x99)).loadChannelMessages(0), hasLength(1));
expect(await historyOf(weather.psk).loadChannelMessages(0), isEmpty);
},
);
test('Keep carries the phone notify mode to the new key', () async {
await settings.setChannelNotifyMode(
devicePrefix: connector.selfPublicKeyHex,
pskHex: weather.pskHex,
channelName: 'Weather',
mode: ChannelNotifyMode.off,
);
await changeKey(psk(0x99), KeyChangeHistory.keep);
final newHex = Channel(index: 0, name: '', psk: psk(0x99)).pskHex;
expect(
settings.channelNotifyMode(
devicePrefix: connector.selfPublicKeyHex,
pskHex: newHex,
),
ChannelNotifyMode.off,
);
expect(
settings
.resolveChannelNotifyMode(
devicePrefix: connector.selfPublicKeyHex,
pskHex: weather.pskHex,
)
.source,
'default, nothing saved',
);
});
test('Delete removes the old key\'s history and moves nothing', () async {
expect(
await changeKey(psk(0x99), KeyChangeHistory.delete),
ChannelWrite.ok,
);
expect(await historyOf(weather.psk).loadChannelMessages(0), isEmpty);
expect(await historyOf(psk(0x99)).loadChannelMessages(0), isEmpty);
});
test(
'a key change with no answer is refused before anything is sent',
() async {
sent.clear();
expect(
() => connector.editChannel(weather, 'Weather', psk(0x99)),
throwsArgumentError,
);
expect(sent, isEmpty);
expect(
await historyOf(weather.psk).loadChannelMessages(0),
hasLength(1),
);
},
);
test('a refused clear leaves history where it was', () async {
final edit = connector.editChannel(
weather,
'Weather',
psk(0x99),
history: KeyChangeHistory.delete,
);
await settle();
connector.handleFrameForTest([respCodeErr, errCodeNotFound]);
expect(await edit, ChannelWrite.rejected);
expect(await historyOf(weather.psk).loadChannelMessages(0), hasLength(1));
});
test('a same-key rename asks nothing and keeps history', () async {
final edit = connector.editChannel(weather, 'Wx', weather.psk);
await settle();
ok();
expect(await edit, ChannelWrite.ok);
expect(await historyOf(weather.psk).loadChannelMessages(0), hasLength(1));
});
test('Keep with a failed add holds the history for a re-add, '
'through the sync that follows', () async {
expect(
await changeKey(
psk(0x99),
KeyChangeHistory.keep,
addReply: [respCodeErr, errCodeNotFound],
),
ChannelWrite.clearedNotAdded,
);
// The write's own re-read: the slot is empty on the radio now. Another
// channel is there, so the no-channels guard is not what spares it.
await radioHolds([null, ('Other', psk(0x33))], start: false);
expect(await historyOf(psk(0x99)).loadChannelMessages(0), hasLength(1));
});
});
group('kept history a key change could not land', () {
test('a Keep whose move fails says so, and the old key survives the '
'sync that follows', () async {
final oldKey =
'channel_messages_${connector.selfPublicKeyHex.substring(0, 10)}'
'psk_${weather.pskHex}';
await BlobStore.instance.deleteMessageRows(oldKey);
BlobStore.instance.resetMigratedKeyCache();
await BlobStore.instance.write('__msgrows_migrated', '[]');
await BlobStore.instance.write(oldKey, 'not json');
BlobStore.instance.resetMigratedKeyCache();
expect(
await changeKey(psk(0x99), KeyChangeHistory.keep),
ChannelWrite.historyNotMoved,
);
await radioHolds([('Weather', psk(0x99)), null], start: false);
expect(await BlobStore.instance.read(oldKey), 'not json');
});
test(
'a spared key is judged normally once the radio holds it again',
() async {
await changeKey(
psk(0x99),
KeyChangeHistory.keep,
addReply: [respCodeErr, errCodeNotFound],
);
await radioHolds([null, ('Other', psk(0x33))], start: false);
// Re-added (here: the radio reports it), then deleted elsewhere.
await radioHolds([('Weather', psk(0x99)), null]);
await radioHolds([('Other', psk(0x33)), null]);
expect(await historyOf(psk(0x99)).loadChannelMessages(0), isEmpty);
},
);
});
group('a different channel written over a slot', () {
test('its old occupant\'s history goes once a full sync shows the radio '
'no longer holds it', () async {
final write = connector.setChannel(0, 'Other', psk(0x33), refresh: false);
ok();
expect(await write, ChannelWrite.ok);
expect(await weatherHistory.loadChannelMessages(0), hasLength(1));
},
);
test('a new key by edit keeps the old key\'s history too', () async {
final edit = connector.editChannel(weather, 'Weather', psk(0x99));
await settle();
ok(); // the clear
for (var i = 0; i < 50; i++) {
await settle();
}
ok(); // the add
await radioHolds([('Other', psk(0x33)), null]);
expect(await historyOf(weather.psk).loadChannelMessages(0), isEmpty);
});
test(
'a channel the firmware moved out of the way keeps its history',
() async {
final write = connector.setChannel(
0,
'Other',
psk(0x33),
refresh: false,
);
ok();
expect(await write, ChannelWrite.ok);
await radioHolds([('Other', psk(0x33)), (weather.name, weather.psk)]);
expect(
await historyOf(weather.psk).loadChannelMessages(0),
hasLength(1),
);
},
);
});
group('syncs that cannot judge history delete nothing', () {
test('erased slots (the Restore case)', () async {
await radioHolds([('\u{FFFD}', psk(0xFF)), null]);
expect(connector.canRestoreChannelsToRadio, isTrue);
expect(await historyOf(weather.psk).loadChannelMessages(0), hasLength(1));
});
test('a sync asked for fewer slots than the radio has', () async {
await connector.getChannels(maxChannels: 1, force: true);
connector.handleFrameForTest(channelInfo(0, 'Other', psk(0x33)));
await settle(50);
expect(await historyOf(weather.psk).loadChannelMessages(0), hasLength(1));
});
test('a radio that reports no channels at all', () async {
await radioHolds([null, null]);
expect(await edit, ChannelWrite.ok);
expect(await weatherHistory.loadChannelMessages(0), hasLength(1));
expect(await historyOf(weather.psk).loadChannelMessages(0), hasLength(1));
});
});
test('a confirmed delete removes the channel\'s history', () async {
@ -115,7 +350,7 @@ void main() {
ok();
expect(await delete, ChannelWrite.ok);
expect(await weatherHistory.loadChannelMessages(0), isEmpty);
expect(await historyOf(weather.psk).loadChannelMessages(0), isEmpty);
});
test('a refused delete keeps it', () async {
@ -123,6 +358,6 @@ void main() {
connector.handleFrameForTest([respCodeErr, errCodeNotFound]);
expect(await delete, ChannelWrite.rejected);
expect(await weatherHistory.loadChannelMessages(0), hasLength(1));
expect(await historyOf(weather.psk).loadChannelMessages(0), hasLength(1));
});
}

@ -183,7 +183,12 @@ void main() {
});
test('a new key is clear-then-add, so #1864 firmware accepts it', () async {
final edit = connector.editChannel(current, 'Weather', psk(0x99));
final edit = connector.editChannel(
current,
'Weather',
psk(0x99),
history: KeyChangeHistory.delete,
);
await untilSetFrames(1);
// The clear: an empty name.
expect(setFrames()[0][2], 0);
@ -198,7 +203,12 @@ void main() {
});
test('a refused clear writes nothing more and keeps the history', () async {
final edit = connector.editChannel(current, 'Weather', psk(0x99));
final edit = connector.editChannel(
current,
'Weather',
psk(0x99),
history: KeyChangeHistory.delete,
);
await untilSetFrames(1);
err(errCodeNotFound);
@ -210,7 +220,12 @@ void main() {
test(
'a clear that lands and an add that fails says the slot is empty',
() async {
final edit = connector.editChannel(current, 'Weather', psk(0x99));
final edit = connector.editChannel(
current,
'Weather',
psk(0x99),
history: KeyChangeHistory.keep,
);
await untilSetFrames(1);
ok(); // the clear lands

@ -9,9 +9,9 @@ import 'package:shared_preferences/shared_preferences.dart';
/// #1063 (Epic B of #1061): slot reassignment must not move history between
/// channel identities. Persisted history is PSK-keyed (#194); the remnants a
/// reassignment has to deal with are the LEGACY slot-index keys, and only
/// those - the outgoing occupant's PSK-keyed history survives so re-adding
/// that channel brings its messages back.
/// reassignment clears are the LEGACY slot-index keys. Whether the outgoing
/// occupant's PSK-keyed history stays is the full sync's call (#1128): it is
/// deleted when no channel on the radio shows it, never kept hidden.
void main() {
late OffbandDatabase db;
late BlobStore blobs;
@ -93,21 +93,164 @@ void main() {
expect(await store(psk: pskB).loadChannelMessages(0), isEmpty);
});
test('the outgoing occupant\'s history survives a reassignment and comes '
'back when the channel is re-added', () async {
test('clearing a slot\'s legacy keys leaves PSK-keyed history for the sync '
'to judge', () async {
// Channel A lives in slot 0 with PSK-keyed history.
final asA = store(psk: pskA);
await asA.saveChannelMessages(0, [chan(1, text: 'kept')]);
// Slot 0 is reassigned to channel B.
// Slot 0 is reassigned to channel B. Firmware may have moved A rather
// than overwritten it (#1896), so the write alone must not delete A's.
await store(psk: pskB).clearLegacySlotHistory(0);
await store(psk: pskB).saveChannelMessages(0, [chan(9, text: 'b-msg')]);
// Channel A is re-added (any slot; identity is the PSK, not the slot).
final loaded = await store(psk: pskA).loadChannelMessages(5);
expect(loaded.single.text, 'kept');
});
group('#1128 move, delete and purge by key', () {
test(
'a move lands every message under the new key and empties the old',
() async {
await store(psk: pskA).saveChannelMessages(0, [chan(1), chan(2)]);
expect(await store().moveChannelHistory(pskA, pskB), 2);
expect(await store(psk: pskB).loadChannelMessages(0), hasLength(2));
expect(await store(psk: pskA).loadChannelMessages(0), isEmpty);
expect(
await blobs.readWithPrefsFallback(
'channel_messages_ddddddddddpsk_$pskA',
),
isNull,
);
},
);
test('a move merges into what the new key already holds, keeping its '
'copy of a shared message', () async {
await store(
psk: pskA,
).saveChannelMessages(0, [chan(1, text: 'old copy'), chan(2)]);
await store(
psk: pskB,
).saveChannelMessages(0, [chan(1, text: 'new copy')]);
expect(await store().moveChannelHistory(pskA, pskB), 1);
final moved = await store(psk: pskB).loadChannelMessages(0);
expect(moved.map((m) => m.text), unorderedEquals(['new copy', 'm2']));
});
test('the move\'s delete takes only the rows it copied', () async {
const key = 'channel_messages_ddddddddddpsk_$pskA';
await store(psk: pskA).saveChannelMessages(0, [chan(1), chan(2)]);
await blobs.deleteMessageRowsIn(key, ['id:id1']);
expect(await blobs.messageMergeKeys(key), {'id:id2'});
});
test('a move reads an old key still on the blob', () async {
await blobs.write(
'channel_messages_ddddddddddpsk_$pskA',
ChannelMessageStore.encodeHistoryForTest([chan(1), chan(2), chan(3)]),
);
expect(await store().moveChannelHistory(pskA, pskB), 3);
expect(await store(psk: pskB).loadChannelMessages(0), hasLength(3));
expect(await store(psk: pskA).loadChannelMessages(0), isEmpty);
});
test('a move that cannot read the old key changes neither key', () async {
await blobs.write('channel_messages_ddddddddddpsk_$pskA', 'not json');
expect(await store().moveChannelHistory(pskA, pskB), isNull);
expect(
await blobs.readWithPrefsFallback(
'channel_messages_ddddddddddpsk_$pskA',
),
'not json',
);
expect(await store(psk: pskB).loadChannelMessages(0), isEmpty);
});
test(
'deleteChannelHistory removes rows and blob for that key only',
() async {
await store(psk: pskA).saveChannelMessages(0, [chan(1)]);
await store(psk: pskB).saveChannelMessages(1, [chan(2)]);
await store().deleteChannelHistory(pskA);
expect(await store(psk: pskA).loadChannelMessages(0), isEmpty);
expect(await store(psk: pskB).loadChannelMessages(1), hasLength(1));
},
);
test('the purge deletes keys no radio channel shows and empty-slot '
'legacy keys, and nothing else', () async {
const pskC = 'cccccccccccccccccccccccccccccccc';
await store(psk: pskA).saveChannelMessages(0, [chan(1)]);
await store(psk: pskB).saveChannelMessages(1, [chan(2)]);
await blobs.write(
'channel_messages_ddddddddddpsk_$pskC',
ChannelMessageStore.encodeHistoryForTest([chan(3)]),
);
// Legacy slot keys: slot 0 holds a channel, slot 7 holds nothing.
for (final slot in [0, 7]) {
await blobs.write(
'channel_messages_dddddddddd$slot',
ChannelMessageStore.encodeHistoryForTest([chan(4)]),
);
}
// Another radio's history is never this radio's to judge.
await (ChannelMessageStore()
..setPublicKeyHex = 'e' * 20
..channelPskResolver = (_) => pskB)
.saveChannelMessages(0, [chan(5)]);
final deleted = await store().purgeHistoryNotOnRadio(
radioPskHex: {pskA},
occupiedSlots: {0},
);
expect(
deleted,
unorderedEquals([
'channel_messages_ddddddddddpsk_$pskB',
'channel_messages_ddddddddddpsk_$pskC',
'channel_messages_dddddddddd7',
]),
);
expect(await store(psk: pskA).loadChannelMessages(0), hasLength(1));
expect(
await blobs.readWithPrefsFallback('channel_messages_dddddddddd0'),
isNotNull,
);
expect(
await (ChannelMessageStore()
..setPublicKeyHex = 'e' * 20
..channelPskResolver = (_) => pskB)
.loadChannelMessages(0),
hasLength(1),
);
});
test('the purge deletes nothing for a radio with no channels', () async {
await store(psk: pskA).saveChannelMessages(0, [chan(1)]);
expect(
await store().purgeHistoryNotOnRadio(
radioPskHex: {},
occupiedSlots: {},
),
isEmpty,
);
expect(await store(psk: pskA).loadChannelMessages(0), hasLength(1));
});
});
test('clearChannelMessages (true delete) removes the PSK-keyed history '
'and the legacy index key', () async {
final s = store(psk: pskA);

@ -179,6 +179,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -574,6 +579,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -969,6 +979,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -1364,6 +1379,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -1759,6 +1779,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -2154,6 +2179,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -2549,6 +2579,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -2944,6 +2979,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -3339,6 +3379,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -3734,6 +3779,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -4129,6 +4179,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -4524,6 +4579,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -4919,6 +4979,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -5314,6 +5379,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -5709,6 +5779,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -6104,6 +6179,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",
@ -6499,6 +6579,11 @@
"channels_writeRejected",
"channels_writeNoReply",
"channels_writeClearedNotAdded",
"channels_writeHistoryNotMoved",
"channels_keyChangeHistoryTitle",
"channels_keyChangeHistoryBody",
"channels_keyChangeKeepHistory",
"channels_keyChangeDeleteHistory",
"composerBudgetBlockedTitle",
"composerBudgetLimitedTitle",
"composerBudgetBluetoothCause",

Loading…
Cancel
Save

Powered by TurnKey Linux.