From a8bf6c0c62849346da4dbb2a2856ab9d11576f88 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Fri, 2 Oct 2026 00:20:22 -0400 Subject: [PATCH] feat(#762): ask the radio for one contact, and trust "not found" only when it can be ours A forced resync (#703) needs to know whether a saved contact the radio did not stream is still on the radio. CMD_GET_CONTACT_BY_KEY answers with the contact or ERR_CODE_NOT_FOUND, but the ERR frame carries no key, so any other in-flight request could own it. checkContactOnRadio runs one check at a time with a timeout. A matching CONTACT means on the radio. NOT_FOUND counts as gone only when no contact stream, channel sync, caplog start, generic ack or other by-key request could have drawn it; everything else, including timeouts, send failures and disconnects, is unresolved. "Gone" is what may later let the owner remove a contact, so it is never guessed. Co-Authored-By: Claude Opus 5.5 --- lib/connector/meshcore_connector.dart | 93 ++++++++++++++ lib/connector/meshcore_protocol.dart | 4 + test/connector/contact_key_check_test.dart | 141 +++++++++++++++++++++ 3 files changed, 238 insertions(+) create mode 100644 test/connector/contact_key_check_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 4cb35bdd..634fc998 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -255,6 +255,18 @@ class ContactSyncShortfall { }); } +/// What the radio said when asked for one contact by key. (#762) +enum ContactKeyCheckResult { onRadio, notFound, unresolved } + +class _PendingKeyCheck { + final String keyHex; + final DateTime startedAt; + final Completer done = Completer(); + Timer? timer; + + _PendingKeyCheck({required this.keyHex, required this.startedAt}); +} + class MeshCoreConnector extends ChangeNotifier { // Message windowing to limit memory usage static const int _messageWindowSize = 200; @@ -455,6 +467,14 @@ class MeshCoreConnector extends ChangeNotifier { DateTime _contactRequestLastActivity = DateTime.fromMillisecondsSinceEpoch(0); ({int? since, bool preserveExisting})? _queuedContactRequest; Timer? _contactRequestWatchdog; + // One CMD_GET_CONTACT_BY_KEY check at a time. Its NOT_FOUND reply carries no + // key, so the check only trusts one that nothing else could own: see + // [_notFoundIsForKeyCheck]. (#762) + _PendingKeyCheck? _pendingKeyCheck; + DateTime? _untrackedByKeyAt; + + @visibleForTesting + Duration contactKeyCheckTimeout = const Duration(seconds: 5); @visibleForTesting DateTime Function() contactSyncClock = DateTime.now; @@ -3151,6 +3171,11 @@ class MeshCoreConnector extends ChangeNotifier { _contactRequestInFlight = false; _contactStreamStarted = false; _queuedContactRequest = null; + final keyCheck = _pendingKeyCheck; + if (keyCheck != null) { + _finishKeyCheck(keyCheck, ContactKeyCheckResult.unresolved); + } + _untrackedByKeyAt = null; _isLoadingContacts = false; _hasLoadedContacts = false; _isLoadingChannels = false; @@ -3951,9 +3976,67 @@ class MeshCoreConnector extends ChangeNotifier { Future getContactByKey(Uint8List pubKey) async { if (!isConnected) return; + _untrackedByKeyAt = contactSyncClock(); await sendFrame(buildGetContactByKeyFrame(pubKey)); } + /// Asks the radio whether it still holds [pubKey]. Only one check runs at a + /// time; a second call while one is pending returns + /// [ContactKeyCheckResult.unresolved] without sending. A timeout, a send + /// failure, a disconnect, or a NOT_FOUND that something else may own are all + /// unresolved, never [ContactKeyCheckResult.notFound]. (#762) + Future checkContactOnRadio(Uint8List pubKey) async { + if (!isConnected || _pendingKeyCheck != null) { + return ContactKeyCheckResult.unresolved; + } + final check = _PendingKeyCheck( + keyHex: pubKeyToHex(pubKey), + startedAt: contactSyncClock(), + ); + _pendingKeyCheck = check; + check.timer = Timer( + contactKeyCheckTimeout, + () => _finishKeyCheck(check, ContactKeyCheckResult.unresolved), + ); + try { + await sendFrame(buildGetContactByKeyFrame(pubKey)); + } catch (e) { + _appDebugLogService?.warn( + 'Contact check could not be sent: $e', + tag: 'ContactSync', + ); + _finishKeyCheck(check, ContactKeyCheckResult.unresolved); + } + return check.done.future; + } + + void _finishKeyCheck(_PendingKeyCheck check, ContactKeyCheckResult result) { + check.timer?.cancel(); + if (identical(_pendingKeyCheck, check)) _pendingKeyCheck = null; + if (!check.done.isCompleted) check.done.complete(result); + } + + void _resolveKeyCheckOnContact(Uint8List frame) { + final check = _pendingKeyCheck; + if (check == null || frame.length < 1 + pubKeySize) return; + if (pubKeyToHex(frame.sublist(1, 1 + pubKeySize)) == check.keyHex) { + _finishKeyCheck(check, ContactKeyCheckResult.onRadio); + } + } + + /// A NOT_FOUND belongs to the pending check only when no other request that + /// can draw an ERR is in flight, and no untracked by-key request was sent + /// since the check started. + bool _notFoundIsForKeyCheck(int errCode, _PendingKeyCheck check) { + final untracked = _untrackedByKeyAt; + return errCode == errCodeNotFound && + !_contactRequestInFlight && + !_isSyncingChannels && + !_channelSyncInFlight && + _pendingGenericAckQueue.isEmpty && + (untracked == null || untracked.isBefore(check.startedAt)); + } + Future sendMessage( Contact contact, String text, { @@ -5832,6 +5915,7 @@ class MeshCoreConnector extends ChangeNotifier { case respCodeContact: debugPrint('Got CONTACT'); _handleContact(frame); + _resolveKeyCheckOnContact(frame); break; case respCodeEndOfContacts: debugPrint('Got END_OF_CONTACTS'); @@ -5984,6 +6068,14 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Protocol', ); + final keyCheck = _pendingKeyCheck; + if (keyCheck != null && + !caplogWasAwaitingStart && + _notFoundIsForKeyCheck(errCode, keyCheck)) { + _finishKeyCheck(keyCheck, ContactKeyCheckResult.notFound); + return; + } + // An in-flight channel GET that draws an ERR means that slot is empty, // advance to the next index the instant the ERR lands instead of waiting // out the timeout + retry budget (mirrors the CHANNEL_INFO success path @@ -8842,6 +8934,7 @@ class MeshCoreConnector extends ChangeNotifier { _radioStatsPollTimer?.cancel(); _channelsChangedDebounce?.cancel(); _contactRequestWatchdog?.cancel(); + _pendingKeyCheck?.timer?.cancel(); radioStatsNotifier.dispose(); _receivedFramesController.close(); _usbManager.dispose(); diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index abadb3b6..42eaac68 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -493,6 +493,10 @@ const int errCodeIllegalArg = 6; /// it defensively against a stale or mis-gated client. (#304) const int errCodeUnsupportedCmd = 1; +/// `ERR_CODE_NOT_FOUND`: e.g. `CMD_GET_CONTACT_BY_KEY` for a key the radio does +/// not hold. (#762) +const int errCodeNotFound = 2; + Uint8List buildOffbandBlockAddFrame(Uint8List pubKey) => Uint8List.fromList([cmdOffbandBlock, offbandBlockAdd, ...pubKey]); Uint8List buildOffbandBlockRemoveFrame(Uint8List pubKey) => diff --git a/test/connector/contact_key_check_test.dart b/test/connector/contact_key_check_test.dart new file mode 100644 index 00000000..de00e13e --- /dev/null +++ b/test/connector/contact_key_check_test.dart @@ -0,0 +1,141 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #762: asking the radio for one contact by key. "Not found" is the only +/// proof a contact is gone from the radio, so it must never be inferred from +/// an ERR that something else could own. +Uint8List _key(int b) => Uint8List.fromList(List.filled(32, b)); + +Uint8List _contactFrame(int keyByte, String name) { + final b = BytesBuilder() + ..addByte(respCodeContact) + ..add(_key(keyByte)) + ..addByte(advTypeChat) + ..addByte(0) + ..addByte(0xFF) + ..add(List.filled(64, 0)) + ..add(Uint8List(32)..setRange(0, name.length, utf8.encode(name))) + ..add(_u32(1790000000)) + ..add(_u32(0)) + ..add(_u32(0)) + ..add(_u32(1790000000)); + return b.toBytes(); +} + +Uint8List _u32(int v) => + Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little); + +Uint8List _err(int code) => Uint8List.fromList([respCodeErr, code]); + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + connector = MeshCoreConnector(); + connector.contactsForTest.clear(); + connector.contactKeyCheckTimeout = const Duration(milliseconds: 50); + sent = []; + connector.sendFrameOverrideForTest = sent.add; + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + int byKeyRequests() => + sent.where((f) => f.isNotEmpty && f[0] == cmdGetContactByKey).length; + + test('a CONTACT for the key means it is on the radio', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + expect(byKeyRequests(), 1); + connector.handleFrameForTest(_contactFrame(0x11, 'Alpha')); + expect(await result, ContactKeyCheckResult.onRadio); + }); + + test('NOT_FOUND with nothing else in flight means gone', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + connector.handleFrameForTest(_err(errCodeNotFound)); + expect(await result, ContactKeyCheckResult.notFound); + }); + + test('a CONTACT for another key does not answer the check', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + connector.handleFrameForTest(_contactFrame(0x22, 'Bravo')); + expect(await result, ContactKeyCheckResult.unresolved); + }); + + test('BAD_STATE is never read as not found', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + connector.handleFrameForTest(_err(4)); + expect(await result, ContactKeyCheckResult.unresolved); + }); + + test('no reply times out as unresolved', () async { + expect( + await connector.checkContactOnRadio(_key(0x11)), + ContactKeyCheckResult.unresolved, + ); + }); + + test('NOT_FOUND after another by-key request is not trusted', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + await connector.getContactByKey(_key(0x22)); + connector.handleFrameForTest(_err(errCodeNotFound)); + expect(await result, ContactKeyCheckResult.unresolved); + }); + + test('NOT_FOUND during a contact stream is not trusted', () async { + await connector.getContacts(); + final result = connector.checkContactOnRadio(_key(0x11)); + connector.handleFrameForTest(_err(errCodeNotFound)); + expect(await result, ContactKeyCheckResult.unresolved); + }); + + test('a second check while one is pending sends nothing', () async { + final first = connector.checkContactOnRadio(_key(0x11)); + expect( + await connector.checkContactOnRadio(_key(0x22)), + ContactKeyCheckResult.unresolved, + ); + expect(byKeyRequests(), 1); + connector.handleFrameForTest(_contactFrame(0x11, 'Alpha')); + expect(await first, ContactKeyCheckResult.onRadio); + }); + + test('a send failure is unresolved and frees the next check', () async { + connector.sendFrameOverrideForTest = (_) => throw Exception('usb gone'); + expect( + await connector.checkContactOnRadio(_key(0x11)), + ContactKeyCheckResult.unresolved, + ); + connector.sendFrameOverrideForTest = sent.add; + final next = connector.checkContactOnRadio(_key(0x22)); + connector.handleFrameForTest(_contactFrame(0x22, 'Bravo')); + expect(await next, ContactKeyCheckResult.onRadio); + }); + + test('a disconnect mid-check ends it unresolved', () async { + final result = connector.checkContactOnRadio(_key(0x11)); + connector.resetConnectionHandshakeStateForTest(); + expect(await result, ContactKeyCheckResult.unresolved); + }); +}