From 85cbe20b3902e249fc3e1d3c78e5c7f1cffba0b3 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Mon, 27 Jul 2026 17:56:48 +0200 Subject: [PATCH 1/6] fix: use authenticated timestamps for Nostr DMs --- .../nostr/NostrDirectMessageHandler.kt | 9 +- .../nostr/NostrDirectMessageHandlerTest.kt | 179 ++++++++++++++++++ 2 files changed, 185 insertions(+), 3 deletions(-) create mode 100644 app/src/test/kotlin/com/bitchat/android/nostr/NostrDirectMessageHandlerTest.kt diff --git a/app/src/main/java/com/bitchat/android/nostr/NostrDirectMessageHandler.kt b/app/src/main/java/com/bitchat/android/nostr/NostrDirectMessageHandler.kt index 7a49057d..469972c8 100644 --- a/app/src/main/java/com/bitchat/android/nostr/NostrDirectMessageHandler.kt +++ b/app/src/main/java/com/bitchat/android/nostr/NostrDirectMessageHandler.kt @@ -31,11 +31,14 @@ class NostrDirectMessageHandler( private val meshDelegateHandler: MeshDelegateHandler, private val scope: CoroutineScope, private val repo: GeohashRepository, - private val dataManager: com.bitchat.android.ui.DataManager + private val dataManager: com.bitchat.android.ui.DataManager, + private val seenStoreProvider: () -> SeenMessageStore = { + SeenMessageStore.getInstance(application) + } ) { companion object { private const val TAG = "NostrDirectMessageHandler" } - private val seenStore by lazy { SeenMessageStore.getInstance(application) } + private val seenStore by lazy(seenStoreProvider) // Simple event deduplication private val processedIds = ArrayDeque() @@ -82,7 +85,7 @@ class NostrDirectMessageHandler( if (packet.type != com.bitchat.android.protocol.MessageType.NOISE_ENCRYPTED.value) return@launch val noisePayload = NoisePayload.decode(packet.payload) ?: return@launch - val messageTimestamp = Date(giftWrap.createdAt * 1000L) + val messageTimestamp = Date(rumorTimestamp * 1000L) val convKey = "nostr_${senderPubkey.take(16)}" repo.putNostrKeyMapping(convKey, senderPubkey) com.bitchat.android.nostr.GeohashAliasRegistry.put(convKey, senderPubkey) diff --git a/app/src/test/kotlin/com/bitchat/android/nostr/NostrDirectMessageHandlerTest.kt b/app/src/test/kotlin/com/bitchat/android/nostr/NostrDirectMessageHandlerTest.kt new file mode 100644 index 00000000..738b3231 --- /dev/null +++ b/app/src/test/kotlin/com/bitchat/android/nostr/NostrDirectMessageHandlerTest.kt @@ -0,0 +1,179 @@ +package com.bitchat.android.nostr + +import android.os.Build +import com.bitchat.android.services.AppStateStore +import com.bitchat.android.services.SeenMessageStore +import com.bitchat.android.ui.ChatState +import com.bitchat.android.ui.DataManager +import com.bitchat.android.ui.MeshDelegateHandler +import com.bitchat.android.ui.MessageManager +import com.bitchat.android.ui.NoiseSessionDelegate +import com.bitchat.android.ui.PrivateChatManager +import com.google.gson.Gson +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.any +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [Build.VERSION_CODES.P], manifest = Config.NONE) +@OptIn(ExperimentalCoroutinesApi::class) +class NostrDirectMessageHandlerTest { + private val gson = Gson() + private lateinit var scope: CoroutineScope + + @Before + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined) + AppStateStore.clear() + } + + @After + fun tearDown() { + AppStateStore.clear() + scope.cancel() + Dispatchers.resetMain() + } + + @Test + fun `private messages use authenticated rumor time instead of randomized gift wrap time`() { + val application = RuntimeEnvironment.getApplication() + val state = ChatState(scope).apply { setNickname("recipient") } + val dataManager = DataManager(application) + val messageManager = MessageManager(state) + val privateChatManager = PrivateChatManager( + state = state, + messageManager = messageManager, + dataManager = dataManager, + noiseSessionDelegate = mock() + ) + val seenStore = mock() + whenever(seenStore.hasDelivered(any())).thenReturn(true) + whenever(seenStore.hasRead(any())).thenReturn(false) + val handler = NostrDirectMessageHandler( + application = application, + state = state, + privateChatManager = privateChatManager, + meshDelegateHandler = mock(), + scope = scope, + repo = GeohashRepository(application, state, dataManager), + dataManager = dataManager, + seenStoreProvider = { seenStore } + ) + val sender = NostrIdentity.generate() + val recipient = NostrIdentity.generate() + val now = (System.currentTimeMillis() / 1000).toInt() + val firstRumorTime = now - 120 + val secondRumorTime = now - 60 + val firstId = "first-real-time" + val secondId = "second-real-time" + + val first = privateMessageGiftWrap( + content = requireNotNull( + NostrEmbeddedBitChat.encodePMForNostrNoRecipient( + content = "first", + messageID = firstId, + senderPeerID = "0011223344556677" + ) + ), + sender = sender, + recipient = recipient, + rumorCreatedAt = firstRumorTime, + giftWrapCreatedAt = now - 5 + ) + val second = privateMessageGiftWrap( + content = requireNotNull( + NostrEmbeddedBitChat.encodePMForNostrNoRecipient( + content = "second", + messageID = secondId, + senderPeerID = "0011223344556677" + ) + ), + sender = sender, + recipient = recipient, + rumorCreatedAt = secondRumorTime, + giftWrapCreatedAt = now - 86_400 + ) + + handler.onGiftWrap(first, "", recipient) + waitForMessage(state, firstId) + handler.onGiftWrap(second, "", recipient) + waitForMessage(state, secondId) + + val messages = state.getPrivateChatsValue().values.single() + assertEquals(listOf(firstId, secondId), messages.map { it.id }) + assertEquals(firstRumorTime * 1000L, messages[0].timestamp.time) + assertEquals(secondRumorTime * 1000L, messages[1].timestamp.time) + } + + private fun waitForMessage(state: ChatState, messageId: String) { + kotlinx.coroutines.runBlocking { + withTimeout(5_000) { + while (state.getPrivateChatsValue().values.flatten().none { it.id == messageId }) { + delay(10) + } + } + } + } + + private fun privateMessageGiftWrap( + content: String, + sender: NostrIdentity, + recipient: NostrIdentity, + rumorCreatedAt: Int, + giftWrapCreatedAt: Int + ): NostrEvent { + val rumorBase = NostrEvent( + pubkey = sender.publicKeyHex, + createdAt = rumorCreatedAt, + kind = NostrKind.DIRECT_MESSAGE, + tags = listOf(listOf("p", recipient.publicKeyHex)), + content = content + ) + val rumor = rumorBase.copy(id = rumorBase.computeEventIdHex()) + val sealContent = NostrCrypto.encryptNIP44( + plaintext = gson.toJson(rumor), + recipientPublicKeyHex = recipient.publicKeyHex, + senderPrivateKeyHex = sender.privateKeyHex + ) + val seal = NostrEvent( + pubkey = sender.publicKeyHex, + createdAt = giftWrapCreatedAt, + kind = NostrKind.SEAL, + tags = emptyList(), + content = sealContent + ).sign(sender.privateKeyHex) + + val (wrapPrivateKey, wrapPublicKey) = NostrCrypto.generateKeyPair() + val giftWrapContent = NostrCrypto.encryptNIP44( + plaintext = gson.toJson(seal), + recipientPublicKeyHex = recipient.publicKeyHex, + senderPrivateKeyHex = wrapPrivateKey + ) + return NostrEvent( + pubkey = wrapPublicKey, + createdAt = giftWrapCreatedAt, + kind = NostrKind.GIFT_WRAP, + tags = listOf(listOf("p", recipient.publicKeyHex)), + content = giftWrapContent + ).sign(wrapPrivateKey) + } +} From 81a35d9dba0641ae50a5526f538a6a19c5d51f49 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Mon, 27 Jul 2026 17:58:36 +0200 Subject: [PATCH 2/6] ui: use shared green CloseButton in private and channel headers Align conversation exit controls with bottom-sheet close chrome so the X reads as primary green rather than muted grey. Co-authored-by: Cursor --- .../main/java/com/bitchat/android/ui/ChatHeader.kt | 13 ++----------- .../com/bitchat/android/ui/MeshPeerListSheet.kt | 12 +----------- 2 files changed, 3 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt b/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt index af38ea1d..fe3ad343 100644 --- a/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt +++ b/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt @@ -47,6 +47,7 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.foundation.layout.RowScope import com.bitchat.android.R import com.bitchat.android.core.ui.component.button.BitChatBrandButton +import com.bitchat.android.core.ui.component.button.CloseButton import com.bitchat.android.net.ArtiTorManager import com.bitchat.android.net.TorMode import com.bitchat.android.ui.theme.BitchatMotion @@ -620,17 +621,7 @@ private fun ChannelHeader( title = "#$channel", onTitleClick = onSidebarClick ) { - ConversationHeaderAction( - onClick = onBackClick, - contentDescription = stringResource(R.string.close_plain) - ) { - Icon( - painter = painterResource(R.drawable.ic_spec_close), - contentDescription = stringResource(R.string.close_plain), - modifier = Modifier.size(HeaderIconSize), - tint = colorScheme.onSurfaceVariant - ) - } + CloseButton(onClick = onBackClick) } } diff --git a/app/src/main/java/com/bitchat/android/ui/MeshPeerListSheet.kt b/app/src/main/java/com/bitchat/android/ui/MeshPeerListSheet.kt index d9a8d035..c496938e 100644 --- a/app/src/main/java/com/bitchat/android/ui/MeshPeerListSheet.kt +++ b/app/src/main/java/com/bitchat/android/ui/MeshPeerListSheet.kt @@ -1024,17 +1024,7 @@ fun PrivateChatSheet( } val dismiss = LocalSheetDismiss.current - ConversationHeaderAction( - onClick = { dismiss?.invoke() ?: onDismiss() }, - contentDescription = stringResource(R.string.close_plain) - ) { - Icon( - painter = painterResource(R.drawable.ic_spec_close), - contentDescription = null, - modifier = Modifier.size(HeaderIconSize), - tint = colorScheme.onSurfaceVariant - ) - } + CloseButton(onClick = { dismiss?.invoke() ?: onDismiss() }) } } } From 1a390b5a1f59495986f2db1e0ab1833cffe13c04 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Mon, 27 Jul 2026 18:13:46 +0200 Subject: [PATCH 3/6] ui: glow lock for Noise handshake instead of sync icon MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Match private-chat Noise status to the Tor globe treatment: one lock glyph with an orange pulse while handshaking, then green or red with smooth tint cross-fades — no sync/recycle swap. Co-authored-by: Cursor --- .../java/com/bitchat/android/ui/ChatHeader.kt | 97 ++++++++++++------- 1 file changed, 63 insertions(+), 34 deletions(-) diff --git a/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt b/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt index fe3ad343..8d4fdfa1 100644 --- a/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt +++ b/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt @@ -8,6 +8,7 @@ import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat +import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween @@ -157,7 +158,8 @@ internal fun rememberTorConnectionVisual(normal: Color): TorConnectionVisual { /** * Soft, slow brightness pulse used while Tor is connecting. Keeps scale fixed so layout - * does not shift; only opacity / a faint halo breathe. + * does not shift; only opacity / a faint halo breathe. Glow strength itself cross-fades so + * starting/stopping progress never pops. */ @Composable internal fun TorAwareHeaderIcon( @@ -167,7 +169,12 @@ internal fun TorAwareHeaderIcon( contentDescription: String?, modifier: Modifier = Modifier, ) { - val pulse = if (isProgress) { + val progressFade by animateFloatAsState( + targetValue = if (isProgress) 1f else 0f, + animationSpec = tween(BitchatMotion.EMPHASIZED_MS, easing = FastOutSlowInEasing), + label = "torGlowFade" + ) + val pulse = if (progressFade > 0.01f) { val transition = rememberInfiniteTransition(label = "torGlow") transition.animateFloat( initialValue = 0.42f, @@ -188,7 +195,7 @@ internal fun TorAwareHeaderIcon( contentAlignment = Alignment.Center, modifier = modifier.size(HeaderIconSize) ) { - if (isProgress) { + if (progressFade > 0.01f) { val glowBrush = remember(tint) { Brush.radialGradient( colorStops = arrayOf( @@ -201,7 +208,7 @@ internal fun TorAwareHeaderIcon( Box( modifier = Modifier .requiredSize(HeaderIconSize + 14.dp) - .graphicsLayer { alpha = pulse * 0.85f } + .graphicsLayer { alpha = pulse * 0.85f * progressFade } .background(glowBrush) ) } @@ -211,7 +218,9 @@ internal fun TorAwareHeaderIcon( modifier = Modifier .size(HeaderIconSize) .graphicsLayer { - alpha = if (isProgress) 0.55f + pulse * 0.45f else 1f + // Idle = solid; in-progress = breathing opacity, lerped by [progressFade]. + val breathing = 0.55f + pulse * 0.45f + alpha = 1f - progressFade * (1f - breathing) }, tint = tint ) @@ -227,7 +236,12 @@ internal fun TorAwareHeaderIcon( contentDescription: String?, modifier: Modifier = Modifier, ) { - val pulse = if (isProgress) { + val progressFade by animateFloatAsState( + targetValue = if (isProgress) 1f else 0f, + animationSpec = tween(BitchatMotion.EMPHASIZED_MS, easing = FastOutSlowInEasing), + label = "torPainterGlowFade" + ) + val pulse = if (progressFade > 0.01f) { val transition = rememberInfiniteTransition(label = "torPainterGlow") transition.animateFloat( initialValue = 0.42f, @@ -246,7 +260,7 @@ internal fun TorAwareHeaderIcon( contentAlignment = Alignment.Center, modifier = modifier.size(HeaderIconSize) ) { - if (isProgress) { + if (progressFade > 0.01f) { val glowBrush = remember(tint) { Brush.radialGradient( colorStops = arrayOf( @@ -259,7 +273,7 @@ internal fun TorAwareHeaderIcon( Box( modifier = Modifier .requiredSize(HeaderIconSize + 14.dp) - .graphicsLayer { alpha = pulse * 0.85f } + .graphicsLayer { alpha = pulse * 0.85f * progressFade } .background(glowBrush) ) } @@ -269,13 +283,22 @@ internal fun TorAwareHeaderIcon( modifier = Modifier .size(HeaderIconSize) .graphicsLayer { - alpha = if (isProgress) 0.55f + pulse * 0.45f else 1f + val breathing = 0.55f + pulse * 0.45f + alpha = 1f - progressFade * (1f - breathing) }, tint = tint ) } } +/** + * Noise session status for private-chat headers. + * + * Same visual language as the main header's Tor-aware globe: one lock glyph throughout, tint + * cross-fades between states, and a soft radial glow pulse while the handshake is in flight. + * The old sync/recycle glyph is gone — progress is carried by colour and motion, not by swapping + * icons. + */ @Composable fun NoiseSessionIcon( sessionState: String?, @@ -283,39 +306,45 @@ fun NoiseSessionIcon( ) { val palette = LocalBitchatPalette.current val colorScheme = MaterialTheme.colorScheme - // The pre-redesign colours for the first two states were `0x87878700`, i.e. alpha 0x87 with - // an all-but-transparent RGB - the icons were effectively invisible. They now use the - // palette's secondary text colour. - val (iconRes, color, contentDescription) = when (sessionState) { - "uninitialized" -> Triple( - R.drawable.ic_spec_lock_open, - colorScheme.onSurfaceVariant, - stringResource(R.string.cd_ready_for_handshake) - ) - "handshaking" -> Triple( - R.drawable.ic_spec_sync, - colorScheme.onSurfaceVariant, + + val (targetTint, isProgress, contentDescription) = when { + sessionState == "handshaking" -> Triple( + palette.accentOrange, + true, stringResource(R.string.cd_handshake_in_progress) ) - "established" -> Triple( - R.drawable.ic_spec_lock, + sessionState == "established" -> Triple( colorScheme.primary, + false, stringResource(R.string.cd_encrypted) ) - else -> { // "failed" or any other state - Triple( - R.drawable.ic_spec_warning, - colorScheme.error, - stringResource(R.string.cd_handshake_failed) - ) - } + sessionState?.startsWith("failed") == true -> Triple( + colorScheme.error, + false, + stringResource(R.string.cd_handshake_failed) + ) + else -> Triple( + // Not yet started — quiet grey lock, same glyph as every other state. + colorScheme.onSurfaceVariant, + false, + stringResource(R.string.cd_ready_for_handshake) + ) } - Icon( - painter = painterResource(iconRes), + // Longer than the usual chrome tint so grey → orange → green reads as a continuous wash, + // not a snap between discrete states. + val animatedTint by animateColorAsState( + targetValue = targetTint, + animationSpec = tween(durationMillis = 480, easing = FastOutSlowInEasing), + label = "noiseSessionTint" + ) + + TorAwareHeaderIcon( + painter = painterResource(R.drawable.ic_spec_lock), + tint = animatedTint, + isProgress = isProgress, contentDescription = contentDescription, - modifier = modifier, - tint = color + modifier = modifier ) } From 6dff0844bbc6971175d1401f286708c7360a2924 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Mon, 27 Jul 2026 18:44:49 +0200 Subject: [PATCH 4/6] revert noise --- .../mesh/AuthenticatedBleLinkPolicy.kt | 14 -- .../mesh/BluetoothConnectionManager.kt | 4 +- .../mesh/BluetoothConnectionTracker.kt | 26 +-- .../android/mesh/BluetoothMeshService.kt | 97 +++------- .../java/com/bitchat/android/mesh/MeshCore.kt | 52 +----- .../bitchat/android/mesh/SecurityManager.kt | 2 +- .../com/bitchat/android/ui/ChatViewModel.kt | 7 +- .../AuthenticatedIngressLinkPolicy.kt | 39 ---- .../wifi-aware/WifiAwareConnectionTracker.kt | 6 +- .../wifi-aware/WifiAwareMeshService.kt | 170 ++++++------------ .../mesh/AuthenticatedBleLinkPolicyTest.kt | 40 ----- ...etoothConnectionTrackerLinkIdentityTest.kt | 53 ------ .../android/ui/PrivateChatManagerTest.kt | 27 +++ .../AuthenticatedIngressLinkPolicyTest.kt | 93 ---------- .../WifiAwareConnectionTrackerTest.kt | 10 +- 15 files changed, 143 insertions(+), 497 deletions(-) delete mode 100644 app/src/main/java/com/bitchat/android/mesh/AuthenticatedBleLinkPolicy.kt delete mode 100644 app/src/main/java/com/bitchat/android/wifi-aware/AuthenticatedIngressLinkPolicy.kt delete mode 100644 app/src/test/kotlin/com/bitchat/android/mesh/AuthenticatedBleLinkPolicyTest.kt delete mode 100644 app/src/test/kotlin/com/bitchat/android/mesh/BluetoothConnectionTrackerLinkIdentityTest.kt delete mode 100644 app/src/test/kotlin/com/bitchat/android/wifi-aware/AuthenticatedIngressLinkPolicyTest.kt diff --git a/app/src/main/java/com/bitchat/android/mesh/AuthenticatedBleLinkPolicy.kt b/app/src/main/java/com/bitchat/android/mesh/AuthenticatedBleLinkPolicy.kt deleted file mode 100644 index f2aa1db2..00000000 --- a/app/src/main/java/com/bitchat/android/mesh/AuthenticatedBleLinkPolicy.kt +++ /dev/null @@ -1,14 +0,0 @@ -package com.bitchat.android.mesh - -/** - * Ensures a Noise completion promotes only the BLE connection whose ANNOUNCE started that - * authentication attempt. - */ -internal object AuthenticatedBleLinkPolicy { - data class Claim(val deviceAddress: String, val linkID: String) - - fun matches(claim: Claim?, authenticatedAddress: String?, authenticatedLinkID: String?): Boolean = - claim != null && - claim.deviceAddress == authenticatedAddress && - claim.linkID == authenticatedLinkID -} diff --git a/app/src/main/java/com/bitchat/android/mesh/BluetoothConnectionManager.kt b/app/src/main/java/com/bitchat/android/mesh/BluetoothConnectionManager.kt index 17e4ce28..3a75188c 100644 --- a/app/src/main/java/com/bitchat/android/mesh/BluetoothConnectionManager.kt +++ b/app/src/main/java/com/bitchat/android/mesh/BluetoothConnectionManager.kt @@ -92,8 +92,8 @@ class BluetoothConnectionManager( // Public property for address-peer mapping val addressPeerMap get() = connectionTracker.addressPeerMap - fun bindPeerIfCurrent(deviceAddress: String, linkID: String, peerID: String): Boolean = - connectionTracker.bindPeerIfCurrent(deviceAddress, linkID, peerID) + fun observePeerIfCurrent(deviceAddress: String, linkID: String, peerID: String): Boolean = + connectionTracker.observePeerIfCurrent(deviceAddress, linkID, peerID) fun getCurrentLinkID(deviceAddress: String): String? = connectionTracker.getCurrentLinkID(deviceAddress) diff --git a/app/src/main/java/com/bitchat/android/mesh/BluetoothConnectionTracker.kt b/app/src/main/java/com/bitchat/android/mesh/BluetoothConnectionTracker.kt index f37d8574..94feb68d 100644 --- a/app/src/main/java/com/bitchat/android/mesh/BluetoothConnectionTracker.kt +++ b/app/src/main/java/com/bitchat/android/mesh/BluetoothConnectionTracker.kt @@ -32,7 +32,7 @@ class BluetoothConnectionTracker( private val firstAnnounceSeen = ConcurrentHashMap() // RSSI tracking from scan results (for devices we discover but may connect as servers) private val scanRSSI = ConcurrentHashMap() - private val peerBindingLock = Any() + private val connectionStateLock = Any() /** * Consolidated device connection information @@ -77,9 +77,9 @@ class BluetoothConnectionTracker( */ fun addDeviceConnection(deviceAddress: String, deviceConn: DeviceConnection) { Log.d(TAG, "Tracker: Adding device connection for $deviceAddress (isClient: ${deviceConn.isClient}") - synchronized(peerBindingLock) { + synchronized(connectionStateLock) { connectedDevices[deviceAddress] = deviceConn - // A mapping authenticates a GATT connection, not a reusable Bluetooth address. + // A route observation belongs to this GATT generation, not its reusable address. addressPeerMap.remove(deviceAddress) } removePendingConnection(deviceAddress) @@ -91,7 +91,7 @@ class BluetoothConnectionTracker( * Update a device connection */ fun updateDeviceConnection(deviceAddress: String, deviceConn: DeviceConnection) { - synchronized(peerBindingLock) { + synchronized(connectionStateLock) { connectedDevices[deviceAddress] = deviceConn } } @@ -100,7 +100,7 @@ class BluetoothConnectionTracker( deviceAddress: String, linkID: String, update: (DeviceConnection) -> DeviceConnection - ): Boolean = synchronized(peerBindingLock) { + ): Boolean = synchronized(connectionStateLock) { val current = connectedDevices[deviceAddress] ?: return@synchronized false if (current.linkID != linkID) return@synchronized false connectedDevices[deviceAddress] = update(current) @@ -117,10 +117,16 @@ class BluetoothConnectionTracker( fun getCurrentLinkID(deviceAddress: String): String? = connectedDevices[deviceAddress]?.linkID - fun bindPeerIfCurrent(deviceAddress: String, linkID: String, peerID: String): Boolean = - synchronized(peerBindingLock) { + /** + * Records that the current link delivered a validated, non-relayed ANNOUNCE for [peerID]. + * + * A peer may be reachable over more than one link, so observing one link must not discard the + * other observations. The link generation check prevents a late packet from an old GATT + * connection from being applied to a replacement connection that reused the same address. + */ + fun observePeerIfCurrent(deviceAddress: String, linkID: String, peerID: String): Boolean = + synchronized(connectionStateLock) { if (connectedDevices[deviceAddress]?.linkID != linkID) return@synchronized false - addressPeerMap.entries.removeIf { it.value == peerID && it.key != deviceAddress } addressPeerMap[deviceAddress] = peerID true } @@ -265,7 +271,7 @@ class BluetoothConnectionTracker( * Clean up a specific device connection */ fun cleanupDeviceConnection(deviceAddress: String) { - synchronized(peerBindingLock) { + synchronized(connectionStateLock) { connectedDevices.remove(deviceAddress) subscribedDevices.removeAll { it.address == deviceAddress } addressPeerMap.remove(deviceAddress) @@ -277,7 +283,7 @@ class BluetoothConnectionTracker( fun cleanupDeviceConnectionIfCurrent( deviceAddress: String, expectedLinkID: String - ): Boolean = synchronized(peerBindingLock) { + ): Boolean = synchronized(connectionStateLock) { val current = connectedDevices[deviceAddress] ?: return@synchronized false if (current.linkID != expectedLinkID) { return@synchronized false diff --git a/app/src/main/java/com/bitchat/android/mesh/BluetoothMeshService.kt b/app/src/main/java/com/bitchat/android/mesh/BluetoothMeshService.kt index 55cdb6df..432d9a1e 100644 --- a/app/src/main/java/com/bitchat/android/mesh/BluetoothMeshService.kt +++ b/app/src/main/java/com/bitchat/android/mesh/BluetoothMeshService.kt @@ -21,7 +21,6 @@ import com.bitchat.android.services.VerificationService import com.bitchat.android.service.TransportBridgeService import kotlinx.coroutines.* import java.util.* -import java.util.concurrent.ConcurrentHashMap import kotlin.math.sign import kotlin.random.Random @@ -43,7 +42,6 @@ class BluetoothMeshService(private val context: Context) : TransportBridgeServic companion object { private const val TAG = "BluetoothMeshService" - private const val BLE_AUTHENTICATION_TIMEOUT_MS = 20_000L private val MAX_TTL: UByte = com.bitchat.android.util.AppConstants.MESSAGE_TTL_HOPS } @@ -129,8 +127,6 @@ class BluetoothMeshService(private val context: Context) : TransportBridgeServic private var announceJob: Job? = null // Tracks whether this instance has been terminated via stopServices() private var terminated = false - private val provisionalBleClaims = - ConcurrentHashMap() init { Log.i(TAG, "Initializing BluetoothMeshService for peer=$myPeerID") @@ -253,7 +249,6 @@ class BluetoothMeshService(private val context: Context) : TransportBridgeServic delegate?.didUpdatePeerList(peerIDs) } override fun onPeerRemoved(peerID: String) { - provisionalBleClaims.remove(peerID) authenticatedPeerState.clear(peerID) try { gossipSyncManager.removeAnnouncementForPeer(peerID) } catch (_: Exception) { } // Remove from mesh graph topology to prevent routing through stale peers @@ -282,22 +277,6 @@ class BluetoothMeshService(private val context: Context) : TransportBridgeServic authenticatedRemoteStaticKey, authenticatedSessionToken ) - val expectedClaim = provisionalBleClaims.remove(peerID) - if (AuthenticatedBleLinkPolicy.matches(expectedClaim, directRelayAddress, ingressLinkID)) { - val authenticatedClaim = checkNotNull(expectedClaim) - if (connectionManager.bindPeerIfCurrent( - authenticatedClaim.deviceAddress, - authenticatedClaim.linkID, - peerID - ) - ) { - Log.i(TAG, "Authenticated BLE link $directRelayAddress as $peerID") - try { peerManager.refreshPeerList() } catch (_: Exception) { } - try { gossipSyncManager.scheduleInitialSyncToPeer(peerID, 1_000) } catch (_: Exception) { } - } else { - Log.w(TAG, "Ignoring Noise completion for stale BLE link $directRelayAddress") - } - } // Send announcement and cached messages after key exchange serviceScope.launch { delay(100) @@ -572,40 +551,23 @@ class BluetoothMeshService(private val context: Context) : TransportBridgeServic val result = messageHandler.handleAnnounceWithResult(routed) if (result !is AnnounceHandlingResult.Accepted) return false - val deviceAddress = routed.relayAddress - val pid = routed.peerID - val linkID = routed.ingressLinkID - val isDirect = routed.packet.ttl == com.bitchat.android.util.AppConstants.MESSAGE_TTL_HOPS - val alreadyAuthenticated = deviceAddress != null && - pid != null && - connectionManager.addressPeerMap[deviceAddress] == pid - if (deviceAddress != null && linkID != null && pid != null && isDirect && !alreadyAuthenticated) { - try { - val claim = AuthenticatedBleLinkPolicy.Claim(deviceAddress, linkID) - registerProvisionalBleClaim(pid, claim) - val handshakeData = encryptionService.initiateHandshake(pid, replaceEstablished = true) - if (handshakeData != null) { - val handshake = signPacketBeforeBroadcast( - BitchatPacket( - version = 1u, - type = MessageType.NOISE_HANDSHAKE.value, - senderID = hexStringToByteArray(myPeerID), - recipientID = hexStringToByteArray(pid), - timestamp = System.currentTimeMillis().toULong(), - payload = handshakeData, - ttl = MAX_TTL - ) - ) - if (!connectionManager.sendPacketToLink(deviceAddress, linkID, handshake)) { - provisionalBleClaims.remove(pid, claim) - Log.w(TAG, "Could not send Noise handshake on BLE link $deviceAddress") - } - } else { - provisionalBleClaims.remove(pid, claim) - } - } catch (e: Exception) { - provisionalBleClaims.remove(pid, AuthenticatedBleLinkPolicy.Claim(deviceAddress, linkID)) - Log.w(TAG, "Could not authenticate provisional BLE claim for $pid: ${e.message}") + DirectLinkAnnouncementPolicy.observationFor(routed, MAX_TTL)?.let { observation -> + if (connectionManager.observePeerIfCurrent( + observation.relayAddress, + observation.ingressLinkID, + observation.peerID + ) + ) { + Log.d( + TAG, + "Observed direct BLE route ${observation.relayAddress} to ${observation.peerID}" + ) + try { peerManager.refreshPeerList() } catch (_: Exception) { } + try { + gossipSyncManager.scheduleInitialSyncToPeer(observation.peerID, 1_000) + } catch (_: Exception) { } + } else { + Log.d(TAG, "Ignoring ANNOUNCE from stale BLE link ${observation.relayAddress}") } } try { gossipSyncManager.onPublicPacketSeen(routed.packet) } catch (_: Exception) { } @@ -710,13 +672,11 @@ class BluetoothMeshService(private val context: Context) : TransportBridgeServic linkID: String? ) { Log.i(TAG, "Device disconnected: ${device.address}") - val addr = device.address - clearProvisionalBleClaimsForLink(addr, linkID) // refresh peer list on disconnect. try { peerManager.refreshPeerList() } catch (_: Exception) { } - // ConnectionTracker already removes an authenticated mapping only when this exact + // ConnectionTracker already removes an observed mapping only when this exact // link is still current. Do not remove by reusable address here: this may be a late // disconnect callback from a replaced GATT connection. } @@ -730,24 +690,6 @@ class BluetoothMeshService(private val context: Context) : TransportBridgeServic } } - private fun registerProvisionalBleClaim( - peerID: String, - claim: AuthenticatedBleLinkPolicy.Claim - ) { - provisionalBleClaims[peerID] = claim - serviceScope.launch { - delay(BLE_AUTHENTICATION_TIMEOUT_MS) - provisionalBleClaims.remove(peerID, claim) - } - } - - private fun clearProvisionalBleClaimsForLink(deviceAddress: String, linkID: String?) { - if (linkID == null) return - provisionalBleClaims.entries.removeIf { (_, claim) -> - claim.deviceAddress == deviceAddress && claim.linkID == linkID - } - } - /** * Start the mesh service */ @@ -1023,7 +965,8 @@ class BluetoothMeshService(private val context: Context) : TransportBridgeServic */ fun sendPrivateMessage(content: String, recipientPeerID: String, recipientNickname: String, messageID: String? = null) { if (content.isEmpty() || recipientPeerID.isEmpty()) return - if (recipientNickname.isEmpty()) return + // Nicknames are presentation metadata. Routing and encryption are bound to the peer ID, + // so a temporarily unresolved nickname must never suppress a private message. serviceScope.launch { val finalMessageID = messageID ?: java.util.UUID.randomUUID().toString() diff --git a/app/src/main/java/com/bitchat/android/mesh/MeshCore.kt b/app/src/main/java/com/bitchat/android/mesh/MeshCore.kt index 375e6531..2387e939 100644 --- a/app/src/main/java/com/bitchat/android/mesh/MeshCore.kt +++ b/app/src/main/java/com/bitchat/android/mesh/MeshCore.kt @@ -44,7 +44,6 @@ class MeshCore( data class Hooks( val onMessageReceived: ((BitchatMessage) -> Unit)? = null, val onAnnounceProcessed: ((RoutedPacket, Boolean) -> Unit)? = null, - val onDirectNoiseAuthenticated: ((String, String, String, ByteArray) -> Unit)? = null, val readReceiptInterceptor: ((String, String) -> Boolean)? = null, val onReadReceiptSent: ((String) -> Unit)? = null, val announcementNicknameProvider: (() -> String?)? = null, @@ -156,12 +155,14 @@ class MeshCore( isActive = false announceJob?.cancel() announceJob = null + directPeers.clear() if (ownsGossipManager) { gossipSyncManager.stop() } } fun shutdown() { + directPeers.clear() peerManager.shutdown() fragmentManager.shutdown() securityManager.shutdown() @@ -215,6 +216,7 @@ class MeshCore( } override fun onPeerRemoved(peerID: String) { + directPeers.remove(peerID) authenticatedPeerState.clear(peerID) try { gossipSyncManager.removeAnnouncementForPeer(peerID) } catch (_: Exception) { } try { encryptionService.removePeer(peerID) } catch (_: Exception) { } @@ -235,14 +237,6 @@ class MeshCore( authenticatedRemoteStaticKey, authenticatedSessionToken ) - if (directRelayAddress != null && ingressLinkID != null) { - hooks.onDirectNoiseAuthenticated?.invoke( - peerID, - directRelayAddress, - ingressLinkID, - authenticatedRemoteStaticKey - ) - } scope.launch { delay(100) sendAnnouncementToPeer(peerID) @@ -845,6 +839,7 @@ class MeshCore( } fun removePeer(peerID: String) { + directPeers.remove(peerID) peerManager.removePeer(peerID) } @@ -898,44 +893,6 @@ class MeshCore( } } - /** - * Starts a fresh replacement handshake on one exact direct transport generation. - * This authenticates provisional transport claims without broadcasting the challenge or - * accidentally sending it through a socket that later reused the same alias. - */ - fun initiateNoiseHandshakeOnLink( - peerID: String, - relayAddress: String, - ingressLinkID: String - ): Boolean { - return try { - val handshakeData = encryptionService.initiateHandshake( - peerID, - replaceEstablished = true - ) ?: return false - val packet = BitchatPacket( - version = 1u, - type = MessageType.NOISE_HANDSHAKE.value, - senderID = MeshPacketUtils.hexStringToByteArray(myPeerID), - recipientID = MeshPacketUtils.hexStringToByteArray(peerID), - timestamp = System.currentTimeMillis().toULong(), - payload = handshakeData, - ttl = maxTtl - ) - transport.sendPacketToLink( - relayAddress, - ingressLinkID, - signPacketBeforeBroadcast(packet) - ) - } catch (e: Exception) { - Log.e( - "MeshCore", - "Failed to initiate link-bound Noise handshake with $peerID: ${e.message}" - ) - false - } - } - fun getPeerFingerprint(peerID: String): String? = peerManager.getFingerprintForPeer(peerID) fun getPeerInfo(peerID: String): PeerInfo? = peerManager.getPeerInfo(peerID) @@ -989,6 +946,7 @@ class MeshCore( } fun clearAllInternalData() { + directPeers.clear() fragmentManager.clearAllFragments() storeForwardManager.clearAllCache() securityManager.clearAllData() diff --git a/app/src/main/java/com/bitchat/android/mesh/SecurityManager.kt b/app/src/main/java/com/bitchat/android/mesh/SecurityManager.kt index 5922ff5e..66698049 100644 --- a/app/src/main/java/com/bitchat/android/mesh/SecurityManager.kt +++ b/app/src/main/java/com/bitchat/android/mesh/SecurityManager.kt @@ -76,7 +76,7 @@ class SecurityManager(private val encryptionService: EncryptionService, private if (processedMessages.contains(messageID)) { // Check for ANNOUNCE exception: allow if it looks like a direct neighbor (max TTL) - // This ensures we catch the "first announce" on a new connection for binding, + // This ensures we observe the same peer on a new direct transport connection, // while still dropping looped/relayed duplicates. val isFreshAnnounce = messageType == MessageType.ANNOUNCE && packet.ttl >= com.bitchat.android.util.AppConstants.MESSAGE_TTL_HOPS diff --git a/app/src/main/java/com/bitchat/android/ui/ChatViewModel.kt b/app/src/main/java/com/bitchat/android/ui/ChatViewModel.kt index 3017b20c..d0358a78 100644 --- a/app/src/main/java/com/bitchat/android/ui/ChatViewModel.kt +++ b/app/src/main/java/com/bitchat/android/ui/ChatViewModel.kt @@ -664,8 +664,11 @@ class ChatViewModel( } private fun nicknameForPeer(peerID: String): String? { - return state.peerNicknames.value[peerID] - ?: try { mesh.getPeerNicknames()[peerID] } catch (_: Exception) { null } + val contact = ContactDirectory.resolve(peerID) + val meshPeerID = contact.meshPeerID ?: peerID + return contact.displayName + ?: state.peerNicknames.value[meshPeerID] + ?: try { mesh.getPeerNicknames()[meshPeerID] } catch (_: Exception) { null } } private fun sessionStateForPeer(peerID: String): NoiseSession.NoiseSessionState { diff --git a/app/src/main/java/com/bitchat/android/wifi-aware/AuthenticatedIngressLinkPolicy.kt b/app/src/main/java/com/bitchat/android/wifi-aware/AuthenticatedIngressLinkPolicy.kt deleted file mode 100644 index d522c812..00000000 --- a/app/src/main/java/com/bitchat/android/wifi-aware/AuthenticatedIngressLinkPolicy.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.bitchat.android.wifiaware - -/** - * Resolves an authenticated callback to the exact still-active ingress link that completed Noise. - * A relay/discovery ID alone is not sufficient because a replacement socket may reuse it. - */ -internal object AuthenticatedIngressLinkPolicy { - data class Claim( - val relayAddress: String, - val linkID: String - ) - - data class Link( - val relayAddress: String, - val transport: T - ) - - fun matches( - expected: Claim?, - authenticatedRelayAddress: String?, - authenticatedLinkID: String? - ): Boolean = - expected != null && - expected.relayAddress == authenticatedRelayAddress && - expected.linkID == authenticatedLinkID - - fun resolve( - authenticatedLinkID: String?, - authenticatedRelayAddress: String?, - links: Map>, - currentTransportForRelay: (String) -> T? - ): Link? { - val linkID = authenticatedLinkID ?: return null - val relayAddress = authenticatedRelayAddress ?: return null - val link = links[linkID] ?: return null - if (link.relayAddress != relayAddress) return null - return link.takeIf { currentTransportForRelay(relayAddress) === it.transport } - } -} diff --git a/app/src/main/java/com/bitchat/android/wifi-aware/WifiAwareConnectionTracker.kt b/app/src/main/java/com/bitchat/android/wifi-aware/WifiAwareConnectionTracker.kt index 9376b078..2b5ab61f 100644 --- a/app/src/main/java/com/bitchat/android/wifi-aware/WifiAwareConnectionTracker.kt +++ b/app/src/main/java/com/bitchat/android/wifi-aware/WifiAwareConnectionTracker.kt @@ -100,9 +100,9 @@ class WifiAwareConnectionTracker( } /** - * Atomically require that [expectedSocket] is still the active provisional transport and, only - * then, promote it. This closes the gap where a replacement socket could land after validation - * but before mutation and the stale authenticated socket would become canonical. + * Atomically require that [expectedSocket] is still the active provisional transport before + * rebinding it. This closes the gap where a replacement socket could land after ANNOUNCE + * validation but before mutation and the stale socket would become canonical. */ fun rebindPeerIdIfCurrent( previousPeerId: String, diff --git a/app/src/main/java/com/bitchat/android/wifi-aware/WifiAwareMeshService.kt b/app/src/main/java/com/bitchat/android/wifi-aware/WifiAwareMeshService.kt index d6cbf981..c5014456 100644 --- a/app/src/main/java/com/bitchat/android/wifi-aware/WifiAwareMeshService.kt +++ b/app/src/main/java/com/bitchat/android/wifi-aware/WifiAwareMeshService.kt @@ -13,6 +13,7 @@ import android.util.Log import androidx.annotation.RequiresApi import androidx.annotation.RequiresPermission import com.bitchat.android.crypto.EncryptionService +import com.bitchat.android.mesh.DirectLinkAnnouncementPolicy import com.bitchat.android.mesh.FragmentingPacketSender import com.bitchat.android.mesh.MeshCore import com.bitchat.android.mesh.MeshService @@ -75,7 +76,6 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor private const val CLIENT_SOCKET_RETRY_DELAY_MS = 750L private const val CLIENT_SOCKET_ATTEMPTS = 3 private const val CLIENT_ROLE_REVERSAL_FAILURES = 3 - private const val WIFI_AUTHENTICATION_TIMEOUT_MS = 30_000L // Discovery freshness window for reconnection maintenance private const val DISCOVERY_STALE_MS = 5L * 60 * 1000 private const val DISCOVERY_IDLE_REFRESH_MS = 2L * 60 * 1000 @@ -125,12 +125,8 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor private val connectionTracker = WifiAwareConnectionTracker(serviceScope, cm) private val ingressLinks = ConcurrentHashMap< String, - AuthenticatedIngressLinkPolicy.Link + IngressLinkPolicy.Link >() - private val provisionalWifiClaims = - ConcurrentHashMap() - private val authenticatedWifiLinks = - ConcurrentHashMap() private val handleToPeerId = ConcurrentHashMap() // discovery mapping private val discoveredTimestamps = ConcurrentHashMap() // peerID -> last seen time // Subscribe-session-scoped handles only. PeerHandles are session-scoped, so a handle obtained @@ -176,38 +172,13 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor onMessageReceived = { message -> handleMessageReceived(message) }, onAnnounceProcessed = { routed, _ -> routed.peerID?.let { pid -> - try { meshCore.gossipSyncManager.scheduleInitialSyncToPeer(pid, 1_000) } catch (_: Exception) { } - - // Discovery IDs from older clients can be provisional. A verified direct - // announce is enough to start a handshake for the canonical ID, but not to - // rebind the socket. A fresh challenge is sent through the exact transport - // generation, and only its same-link completion may promote that alias. - val relay = routed.relayAddress - val linkID = routed.ingressLinkID - if ( - routed.packet.ttl == MAX_TTL && - relay != null && - linkID != null - ) { - val claim = AuthenticatedIngressLinkPolicy.Claim(relay, linkID) - if (!AuthenticatedIngressLinkPolicy.matches( - authenticatedWifiLinks[pid], - relay, - linkID - ) - ) { - registerProvisionalWifiClaim(pid, claim) - if (!meshCore.initiateNoiseHandshakeOnLink(pid, relay, linkID)) { - provisionalWifiClaims.remove(pid, claim) - Log.w(TAG, "Could not send Noise challenge on Wi-Fi link for ${pid.take(8)}") - } - } - } + DirectLinkAnnouncementPolicy.observationFor(routed, MAX_TTL) + ?.let(::observeDirectIngressLink) + try { + meshCore.gossipSyncManager.scheduleInitialSyncToPeer(pid, 1_000) + } catch (_: Exception) { } } }, - onDirectNoiseAuthenticated = { peerID, relayAddress, ingressLinkID, _ -> - promoteAuthenticatedIngressLink(peerID, relayAddress, ingressLinkID) - }, announcementNicknameProvider = { try { com.bitchat.android.services.NicknameProvider.getNickname(context, myPeerID) } catch (_: Exception) { null } }, @@ -587,8 +558,6 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor publishHandles.clear() discoveredTimestamps.clear() ingressLinks.clear() - provisionalWifiClaims.clear() - authenticatedWifiLinks.clear() meshCore.shutdown() @@ -634,8 +603,6 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor publishHandles.clear() discoveredTimestamps.clear() ingressLinks.clear() - provisionalWifiClaims.clear() - authenticatedWifiLinks.clear() } } finally { recoveryInProgress = false @@ -901,7 +868,6 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor // presence makes hasOpenServerSocket() true for the life of the process) // and so we free the fd/port promptly. connectionTracker.closeServerSocket(peerId) - try { meshCore.setDirectConnection(peerId, true) } catch (_: Exception) {} try { meshCore.addOrUpdatePeer(peerId, peerId) } catch (_: Exception) {} listenerExec.execute { listenToPeer(synced, peerId) } handleSubscriberKeepAlive(synced, peerId, pubSession, peerHandle) @@ -1156,7 +1122,6 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor activeSocket = synced connectionTracker.onClientConnected(peerId, synced) clientSocketFailures.remove(peerId) - try { meshCore.setDirectConnection(peerId, true) } catch (_: Exception) {} try { meshCore.addOrUpdatePeer(peerId, peerId) } catch (_: Exception) {} listenerExec.execute { listenToPeer(synced, peerId) } handleServerKeepAlive(synced, peerId, peerHandle) @@ -1235,70 +1200,74 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor } /** - * Promote a provisional discovery alias only when the exact, still-active socket delivered the - * Noise frame that completed authentication for the canonical peer ID. + * Records a validated, non-relayed ANNOUNCE as a direct route. The exact-link check keeps stale + * socket readers from rebinding a replacement connection, but Noise remains peer-scoped and is + * not restarted or coupled to this routing observation. */ - private fun promoteAuthenticatedIngressLink( - canonicalPeerId: String, - relayAddress: String, - ingressLinkID: String + private fun observeDirectIngressLink( + observation: DirectLinkAnnouncementPolicy.Observation ) { - val expectedClaim = provisionalWifiClaims[canonicalPeerId] - if (!AuthenticatedIngressLinkPolicy.matches( - expectedClaim, - relayAddress, - ingressLinkID - ) - ) { - Log.w(TAG, "Ignoring unsolicited or cross-link Noise promotion for ${canonicalPeerId.take(8)}") - return - } - provisionalWifiClaims.remove(canonicalPeerId, expectedClaim) - - val link = AuthenticatedIngressLinkPolicy.resolve( - authenticatedLinkID = ingressLinkID, - authenticatedRelayAddress = relayAddress, + val link = IngressLinkPolicy.resolve( + ingressLinkID = observation.ingressLinkID, + relayAddress = observation.relayAddress, links = ingressLinks, currentTransportForRelay = connectionTracker::getSocketForPeer ) ?: run { - Log.w(TAG, "Ignoring Noise link promotion for ${canonicalPeerId.take(8)}: ingress link is stale or mismatched") + Log.d( + TAG, + "Ignoring direct ANNOUNCE for ${observation.peerID.take(8)}: ingress link is stale" + ) return } val provisionalPeerId = link.relayAddress val existingCanonical = connectionTracker.canonicalPeerId(provisionalPeerId) - if (existingCanonical == canonicalPeerId) { - authenticatedWifiLinks[canonicalPeerId] = - AuthenticatedIngressLinkPolicy.Claim(relayAddress, ingressLinkID) - try { meshCore.setDirectConnection(canonicalPeerId, true) } catch (_: Exception) { } + if (existingCanonical == observation.peerID) { + try { meshCore.setDirectConnection(observation.peerID, true) } catch (_: Exception) { } return } if (existingCanonical != provisionalPeerId) { - Log.w(TAG, "Refusing authenticated Wi-Fi rebind ${existingCanonical.take(8)} -> ${canonicalPeerId.take(8)} on existing alias") + Log.w( + TAG, + "Refusing Wi-Fi route change ${existingCanonical.take(8)} -> ${observation.peerID.take(8)} on existing alias" + ) return } - if (!connectionTracker.rebindPeerIdIfCurrent(provisionalPeerId, canonicalPeerId, link.transport)) { - Log.w(TAG, "Ignoring Noise link promotion for ${canonicalPeerId.take(8)}: provisional socket changed") + if (!connectionTracker.rebindPeerIdIfCurrent( + provisionalPeerId, + observation.peerID, + link.transport + ) + ) { + Log.d( + TAG, + "Ignoring direct ANNOUNCE for ${observation.peerID.take(8)}: provisional socket changed" + ) return } - authenticatedWifiLinks[canonicalPeerId] = - AuthenticatedIngressLinkPolicy.Claim(relayAddress, ingressLinkID) handleToPeerId.forEach { (handle, peerId) -> - if (peerId == provisionalPeerId) handleToPeerId[handle] = canonicalPeerId + if (peerId == provisionalPeerId) handleToPeerId[handle] = observation.peerID } - subscribeHandles.remove(provisionalPeerId)?.let { subscribeHandles[canonicalPeerId] = it } - publishHandles.remove(provisionalPeerId)?.let { publishHandles[canonicalPeerId] = it } + subscribeHandles.remove(provisionalPeerId)?.let { subscribeHandles[observation.peerID] = it } + publishHandles.remove(provisionalPeerId)?.let { publishHandles[observation.peerID] = it } val discoveredAt = discoveredTimestamps.remove(provisionalPeerId) ?: System.currentTimeMillis() - discoveredTimestamps[canonicalPeerId] = discoveredAt + discoveredTimestamps[observation.peerID] = discoveredAt try { meshCore.setDirectConnection(provisionalPeerId, false) } catch (_: Exception) { } try { meshCore.removePeer(provisionalPeerId) } catch (_: Exception) { } - try { meshCore.addOrUpdatePeer(canonicalPeerId, meshCore.getPeerNickname(canonicalPeerId) ?: canonicalPeerId) } catch (_: Exception) { } - try { meshCore.setDirectConnection(canonicalPeerId, true) } catch (_: Exception) { } - try { meshCore.gossipSyncManager.scheduleInitialSyncToPeer(canonicalPeerId, 1_000) } catch (_: Exception) { } + try { + meshCore.addOrUpdatePeer( + observation.peerID, + meshCore.getPeerNickname(observation.peerID) ?: observation.peerID + ) + } catch (_: Exception) { } + try { meshCore.setDirectConnection(observation.peerID, true) } catch (_: Exception) { } - Log.i(TAG, "Noise-authenticated Wi-Fi peer ${provisionalPeerId.take(8)} -> ${canonicalPeerId.take(8)}") + Log.i( + TAG, + "Observed direct Wi-Fi route ${provisionalPeerId.take(8)} -> ${observation.peerID.take(8)}" + ) } /** @@ -1311,7 +1280,7 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor private fun listenToPeer(socket: SyncedSocket, initialLogicalPeerId: String) { val logicalPeerId = initialLogicalPeerId val ingressLinkID = UUID.randomUUID().toString() - val ingressLink = AuthenticatedIngressLinkPolicy.Link(logicalPeerId, socket) + val ingressLink = IngressLinkPolicy.Link(logicalPeerId, socket) ingressLinks[ingressLinkID] = ingressLink while (isActive) { val raw = socket.read() ?: break @@ -1326,10 +1295,11 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor val senderPeerHex = pkt.senderID?.toHexString()?.take(16) ?: continue if (pkt.type == MessageType.ANNOUNCE.value && pkt.ttl >= MAX_TTL && senderPeerHex != logicalPeerId) { - // The socket's discovery identity remains provisional until Noise proves possession - // of the claimed static key on this link. A canonical self-signed announcement is - // only TOFU and cannot safely rebind/remove transport state on its own. - Log.d(TAG, "RX: deferred Wi-Fi peer rebind ${logicalPeerId.take(8)} -> ${senderPeerHex.take(8)} pending Noise proof") + // Rebinding happens only after MeshCore validates and accepts this ANNOUNCE. + Log.d( + TAG, + "RX: Wi-Fi peer observation ${logicalPeerId.take(8)} -> ${senderPeerHex.take(8)} pending ANNOUNCE validation" + ) } // Route the packet: @@ -1339,7 +1309,6 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor } ingressLinks.remove(ingressLinkID, ingressLink) - clearProvisionalWifiClaimsForLink(logicalPeerId, ingressLinkID) // Breaking out of the loop means the socket is dead or service is stopping. Log.i(TAG, "Disconnected from ${logicalPeerId.take(8)} (socket closed)") @@ -1347,27 +1316,6 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor socket.close() } - private fun registerProvisionalWifiClaim( - peerID: String, - claim: AuthenticatedIngressLinkPolicy.Claim - ) { - provisionalWifiClaims[peerID] = claim - serviceScope.launch { - delay(WIFI_AUTHENTICATION_TIMEOUT_MS) - if (provisionalWifiClaims.remove(peerID, claim)) { - Log.d(TAG, "Expired provisional Wi-Fi authentication claim for ${peerID.take(8)}") - } } - } - - private fun clearProvisionalWifiClaimsForLink(relayAddress: String, linkID: String) { - provisionalWifiClaims.entries.removeIf { (_, claim) -> - claim.relayAddress == relayAddress && claim.linkID == linkID - } - authenticatedWifiLinks.entries.removeIf { (_, claim) -> - claim.relayAddress == relayAddress && claim.linkID == linkID - } - } - private fun handleNetworkFailure(peerId: String) { serviceScope.launch { if (!connectionTracker.isConnected(peerId)) { @@ -1655,9 +1603,9 @@ class WifiAwareMeshService(private val context: Context) : MeshService, Transpor ingressLinkID: String, packet: BitchatPacket ): Boolean { - val link = AuthenticatedIngressLinkPolicy.resolve( - authenticatedLinkID = ingressLinkID, - authenticatedRelayAddress = relayAddress, + val link = IngressLinkPolicy.resolve( + ingressLinkID = ingressLinkID, + relayAddress = relayAddress, links = ingressLinks, currentTransportForRelay = connectionTracker::getSocketForPeer ) ?: return false diff --git a/app/src/test/kotlin/com/bitchat/android/mesh/AuthenticatedBleLinkPolicyTest.kt b/app/src/test/kotlin/com/bitchat/android/mesh/AuthenticatedBleLinkPolicyTest.kt deleted file mode 100644 index 81ba5f7a..00000000 --- a/app/src/test/kotlin/com/bitchat/android/mesh/AuthenticatedBleLinkPolicyTest.kt +++ /dev/null @@ -1,40 +0,0 @@ -package com.bitchat.android.mesh - -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class AuthenticatedBleLinkPolicyTest { - private val claim = AuthenticatedBleLinkPolicy.Claim( - deviceAddress = "AA:BB:CC:DD:EE:FF", - linkID = "connection-a" - ) - - @Test - fun `accepts completion from exact claimed connection`() { - assertTrue( - AuthenticatedBleLinkPolicy.matches( - claim, - authenticatedAddress = claim.deviceAddress, - authenticatedLinkID = claim.linkID - ) - ) - } - - @Test - fun `rejects replacement connection reusing device address`() { - assertFalse( - AuthenticatedBleLinkPolicy.matches( - claim, - authenticatedAddress = claim.deviceAddress, - authenticatedLinkID = "connection-b" - ) - ) - } - - @Test - fun `rejects completion on another address or without a claim`() { - assertFalse(AuthenticatedBleLinkPolicy.matches(claim, "11:22:33:44:55:66", claim.linkID)) - assertFalse(AuthenticatedBleLinkPolicy.matches(null, claim.deviceAddress, claim.linkID)) - } -} diff --git a/app/src/test/kotlin/com/bitchat/android/mesh/BluetoothConnectionTrackerLinkIdentityTest.kt b/app/src/test/kotlin/com/bitchat/android/mesh/BluetoothConnectionTrackerLinkIdentityTest.kt deleted file mode 100644 index 16d2d286..00000000 --- a/app/src/test/kotlin/com/bitchat/android/mesh/BluetoothConnectionTrackerLinkIdentityTest.kt +++ /dev/null @@ -1,53 +0,0 @@ -package com.bitchat.android.mesh - -import android.bluetooth.BluetoothDevice -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.SupervisorJob -import kotlinx.coroutines.cancel -import org.junit.After -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertSame -import org.junit.Assert.assertTrue -import org.junit.Test -import org.mockito.kotlin.mock -import org.mockito.kotlin.whenever - -class BluetoothConnectionTrackerLinkIdentityTest { - private val scope = CoroutineScope(Dispatchers.Unconfined + SupervisorJob()) - private val tracker = BluetoothConnectionTracker(scope, mock()) - - @After - fun tearDown() { - scope.cancel() - } - - @Test - fun `stale connection callbacks cannot mutate or remove replacement link`() { - val address = "AA:BB:CC:DD:EE:FF" - val device = mock() - whenever(device.address).thenReturn(address) - - tracker.addDeviceConnection( - address, - BluetoothConnectionTracker.DeviceConnection(device = device, linkID = "link-a") - ) - tracker.addDeviceConnection( - address, - BluetoothConnectionTracker.DeviceConnection(device = device, linkID = "link-b") - ) - - assertFalse( - tracker.updateDeviceConnectionIfCurrent(address, "link-a") { - it.copy(rssi = -10) - } - ) - assertFalse(tracker.cleanupDeviceConnectionIfCurrent(address, "link-a")) - assertEquals("link-b", tracker.getCurrentLinkID(address)) - - assertTrue(tracker.bindPeerIfCurrent(address, "link-b", "0011223344556677")) - assertEquals("0011223344556677", tracker.addressPeerMap[address]) - assertSame(device, tracker.getDeviceConnection(address)?.device) - } -} diff --git a/app/src/test/kotlin/com/bitchat/android/ui/PrivateChatManagerTest.kt b/app/src/test/kotlin/com/bitchat/android/ui/PrivateChatManagerTest.kt index 852411e8..8e590949 100644 --- a/app/src/test/kotlin/com/bitchat/android/ui/PrivateChatManagerTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/ui/PrivateChatManagerTest.kt @@ -10,6 +10,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestScope import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @@ -104,4 +105,30 @@ class PrivateChatManagerTest { verify(meshService).sendReadReceipt(message.id, meshPeerID, "bob") } + + @Test + fun `canonical conversation send does not require resolved nickname`() { + val conversationID = + ContactIdentityResolver.contactConversationIdForNoiseKey(ByteArray(32) { 4 }) + var callbackInvoked = false + + manager.sendPrivateMessage( + content = "hello", + peerID = conversationID, + recipientNickname = null, + senderNickname = "bob", + myPeerID = "self" + ) { content, recipientID, nickname, _ -> + callbackInvoked = true + assertEquals("hello", content) + assertEquals(conversationID, recipientID) + assertEquals("", nickname) + } + + assertTrue(callbackInvoked) + assertEquals( + "hello", + state.getPrivateChatsValue()[conversationID]?.single()?.content + ) + } } diff --git a/app/src/test/kotlin/com/bitchat/android/wifi-aware/AuthenticatedIngressLinkPolicyTest.kt b/app/src/test/kotlin/com/bitchat/android/wifi-aware/AuthenticatedIngressLinkPolicyTest.kt deleted file mode 100644 index 1f483543..00000000 --- a/app/src/test/kotlin/com/bitchat/android/wifi-aware/AuthenticatedIngressLinkPolicyTest.kt +++ /dev/null @@ -1,93 +0,0 @@ -package com.bitchat.android.wifiaware - -import org.junit.Assert.assertNull -import org.junit.Assert.assertSame -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class AuthenticatedIngressLinkPolicyTest { - @Test - fun `promotion claim must match the challenged relay and link`() { - val claim = AuthenticatedIngressLinkPolicy.Claim("provisional", "challenged-link") - - assertTrue( - AuthenticatedIngressLinkPolicy.matches( - claim, - authenticatedRelayAddress = "provisional", - authenticatedLinkID = "challenged-link" - ) - ) - assertFalse( - AuthenticatedIngressLinkPolicy.matches( - claim, - authenticatedRelayAddress = "provisional", - authenticatedLinkID = "different-link" - ) - ) - assertFalse( - AuthenticatedIngressLinkPolicy.matches( - expected = null, - authenticatedRelayAddress = "provisional", - authenticatedLinkID = "challenged-link" - ) - ) - } - - @Test - fun `authentication promotes only the exact ingress link`() { - val attackerSocket = Any() - val victimSocket = Any() - val links = mapOf( - "attacker-link" to AuthenticatedIngressLinkPolicy.Link("provisional-attacker", attackerSocket), - "victim-link" to AuthenticatedIngressLinkPolicy.Link("provisional-victim", victimSocket) - ) - val current = mapOf( - "provisional-attacker" to attackerSocket, - "provisional-victim" to victimSocket - ) - - val resolved = AuthenticatedIngressLinkPolicy.resolve( - authenticatedLinkID = "victim-link", - authenticatedRelayAddress = "provisional-victim", - links = links, - currentTransportForRelay = current::get - ) - - assertSame(victimSocket, resolved?.transport) - } - - @Test - fun `stale replaced or mismatched ingress links cannot be promoted`() { - val completedSocket = Any() - val replacementSocket = Any() - val links = mapOf( - "completed-link" to AuthenticatedIngressLinkPolicy.Link("provisional", completedSocket) - ) - - assertNull( - AuthenticatedIngressLinkPolicy.resolve( - authenticatedLinkID = "missing-link", - authenticatedRelayAddress = "provisional", - links = links, - currentTransportForRelay = { completedSocket } - ) - ) - assertNull( - AuthenticatedIngressLinkPolicy.resolve( - authenticatedLinkID = "completed-link", - authenticatedRelayAddress = "different-provisional", - links = links, - currentTransportForRelay = { completedSocket } - ) - ) - assertNull( - AuthenticatedIngressLinkPolicy.resolve( - authenticatedLinkID = "completed-link", - authenticatedRelayAddress = "provisional", - links = links, - currentTransportForRelay = { replacementSocket } - ) - ) - } -} diff --git a/app/src/test/kotlin/com/bitchat/android/wifi-aware/WifiAwareConnectionTrackerTest.kt b/app/src/test/kotlin/com/bitchat/android/wifi-aware/WifiAwareConnectionTrackerTest.kt index b1b12d0e..5cd2cbf7 100644 --- a/app/src/test/kotlin/com/bitchat/android/wifi-aware/WifiAwareConnectionTrackerTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/wifi-aware/WifiAwareConnectionTrackerTest.kt @@ -17,21 +17,21 @@ import java.net.Socket class WifiAwareConnectionTrackerTest { @Test - fun `compare and rebind rejects stale authenticated socket after replacement`() { + fun `compare and rebind rejects stale observed socket after replacement`() { val tracker = WifiAwareConnectionTracker( CoroutineScope(SupervisorJob() + Dispatchers.Unconfined), mock() ) - val authenticatedSocket = syncedSocket() + val observedSocket = syncedSocket() val replacementSocket = syncedSocket() - tracker.onClientConnected("provisional", authenticatedSocket) + tracker.onClientConnected("provisional", observedSocket) tracker.onClientConnected("provisional", replacementSocket) assertFalse( tracker.rebindPeerIdIfCurrent( previousPeerId = "provisional", resolvedPeerId = "canonical", - expectedSocket = authenticatedSocket + expectedSocket = observedSocket ) ) assertSame(replacementSocket, tracker.getSocketForPeer("provisional")) @@ -49,7 +49,7 @@ class WifiAwareConnectionTrackerTest { } @Test - fun `authenticated provisional socket cannot displace existing canonical socket`() { + fun `observed provisional socket cannot displace existing canonical socket`() { val tracker = WifiAwareConnectionTracker( CoroutineScope(SupervisorJob() + Dispatchers.Unconfined), mock() From 58c56a8082f5f0166b879bad2c692fa541946c96 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Mon, 27 Jul 2026 18:45:29 +0200 Subject: [PATCH 5/6] ui: open lock until Noise session is established MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Show ic_spec_lock_open while idle or handshaking, then Crossfade to the closed lock on success or failure — timed with the existing tint wash so the shackle settling reads as one smooth transition. Co-authored-by: Cursor --- .../java/com/bitchat/android/ui/ChatHeader.kt | 45 ++++++++++++------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt b/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt index 8d4fdfa1..f8820e91 100644 --- a/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt +++ b/app/src/main/java/com/bitchat/android/ui/ChatHeader.kt @@ -4,6 +4,7 @@ import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.filled.* import androidx.compose.material.icons.outlined.* +import androidx.compose.animation.Crossfade import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.RepeatMode @@ -294,10 +295,10 @@ internal fun TorAwareHeaderIcon( /** * Noise session status for private-chat headers. * - * Same visual language as the main header's Tor-aware globe: one lock glyph throughout, tint - * cross-fades between states, and a soft radial glow pulse while the handshake is in flight. - * The old sync/recycle glyph is gone — progress is carried by colour and motion, not by swapping - * icons. + * Same visual language as the main header's Tor-aware globe: tint cross-fades between states, + * and a soft radial glow pulse while the handshake is in flight. The glyph itself is the open + * lock until a session is established (or fails), then the closed lock — both share the same + * baseline so a [Crossfade] reads as the shackle settling shut rather than an icon swap. */ @Composable fun NoiseSessionIcon( @@ -324,28 +325,42 @@ fun NoiseSessionIcon( stringResource(R.string.cd_handshake_failed) ) else -> Triple( - // Not yet started — quiet grey lock, same glyph as every other state. + // Not yet started — quiet grey open lock. colorScheme.onSurfaceVariant, false, stringResource(R.string.cd_ready_for_handshake) ) } - // Longer than the usual chrome tint so grey → orange → green reads as a continuous wash, - // not a snap between discrete states. + // Closed once the handshake resolves (success or failure); open while idle or in flight. + val lockIconRes = when { + sessionState == "established" || sessionState?.startsWith("failed") == true -> + R.drawable.ic_spec_lock + else -> R.drawable.ic_spec_lock_open + } + + // Match the tint wash so open → closed and grey → orange → green land together. + val lockTransitionMs = 480 + val animatedTint by animateColorAsState( targetValue = targetTint, - animationSpec = tween(durationMillis = 480, easing = FastOutSlowInEasing), + animationSpec = tween(durationMillis = lockTransitionMs, easing = FastOutSlowInEasing), label = "noiseSessionTint" ) - TorAwareHeaderIcon( - painter = painterResource(R.drawable.ic_spec_lock), - tint = animatedTint, - isProgress = isProgress, - contentDescription = contentDescription, - modifier = modifier - ) + Crossfade( + targetState = lockIconRes, + animationSpec = tween(durationMillis = lockTransitionMs, easing = FastOutSlowInEasing), + modifier = modifier, + label = "noiseLockGlyph" + ) { iconRes -> + TorAwareHeaderIcon( + painter = painterResource(iconRes), + tint = animatedTint, + isProgress = isProgress, + contentDescription = contentDescription, + ) + } } /** From 62dd3ca90e09fc193ad2b45011ad87b462895b69 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Mon, 27 Jul 2026 18:47:17 +0200 Subject: [PATCH 6/6] fix: complete direct-link routing rollback --- .../mesh/DirectLinkAnnouncementPolicy.kt | 26 ++++++ .../android/wifi-aware/IngressLinkPolicy.kt | 22 +++++ ...othConnectionTrackerLinkObservationTest.kt | 85 +++++++++++++++++++ .../mesh/DirectLinkAnnouncementPolicyTest.kt | 64 ++++++++++++++ .../wifi-aware/IngressLinkPolicyTest.kt | 64 ++++++++++++++ 5 files changed, 261 insertions(+) create mode 100644 app/src/main/java/com/bitchat/android/mesh/DirectLinkAnnouncementPolicy.kt create mode 100644 app/src/main/java/com/bitchat/android/wifi-aware/IngressLinkPolicy.kt create mode 100644 app/src/test/kotlin/com/bitchat/android/mesh/BluetoothConnectionTrackerLinkObservationTest.kt create mode 100644 app/src/test/kotlin/com/bitchat/android/mesh/DirectLinkAnnouncementPolicyTest.kt create mode 100644 app/src/test/kotlin/com/bitchat/android/wifi-aware/IngressLinkPolicyTest.kt diff --git a/app/src/main/java/com/bitchat/android/mesh/DirectLinkAnnouncementPolicy.kt b/app/src/main/java/com/bitchat/android/mesh/DirectLinkAnnouncementPolicy.kt new file mode 100644 index 00000000..e0be2835 --- /dev/null +++ b/app/src/main/java/com/bitchat/android/mesh/DirectLinkAnnouncementPolicy.kt @@ -0,0 +1,26 @@ +package com.bitchat.android.mesh + +import com.bitchat.android.model.RoutedPacket + +/** + * Describes transport reachability learned from an already-validated ANNOUNCE. + * + * This is deliberately only a routing observation. Noise authenticates the peer independently and + * must not be restarted merely to associate the current transport link with that peer. + */ +internal object DirectLinkAnnouncementPolicy { + data class Observation( + val peerID: String, + val relayAddress: String, + val ingressLinkID: String + ) + + fun observationFor(routed: RoutedPacket, maxTtl: UByte): Observation? { + if (routed.packet.ttl != maxTtl) return null + return Observation( + peerID = routed.peerID ?: return null, + relayAddress = routed.relayAddress ?: return null, + ingressLinkID = routed.ingressLinkID ?: return null + ) + } +} diff --git a/app/src/main/java/com/bitchat/android/wifi-aware/IngressLinkPolicy.kt b/app/src/main/java/com/bitchat/android/wifi-aware/IngressLinkPolicy.kt new file mode 100644 index 00000000..f5572e17 --- /dev/null +++ b/app/src/main/java/com/bitchat/android/wifi-aware/IngressLinkPolicy.kt @@ -0,0 +1,22 @@ +package com.bitchat.android.wifiaware + +/** Resolves a packet to the exact still-active ingress link that delivered it. */ +internal object IngressLinkPolicy { + data class Link( + val relayAddress: String, + val transport: T + ) + + fun resolve( + ingressLinkID: String?, + relayAddress: String?, + links: Map>, + currentTransportForRelay: (String) -> T? + ): Link? { + val linkID = ingressLinkID ?: return null + val relayAddress = relayAddress ?: return null + val link = links[linkID] ?: return null + if (link.relayAddress != relayAddress) return null + return link.takeIf { currentTransportForRelay(relayAddress) === it.transport } + } +} diff --git a/app/src/test/kotlin/com/bitchat/android/mesh/BluetoothConnectionTrackerLinkObservationTest.kt b/app/src/test/kotlin/com/bitchat/android/mesh/BluetoothConnectionTrackerLinkObservationTest.kt new file mode 100644 index 00000000..bde80cdc --- /dev/null +++ b/app/src/test/kotlin/com/bitchat/android/mesh/BluetoothConnectionTrackerLinkObservationTest.kt @@ -0,0 +1,85 @@ +package com.bitchat.android.mesh + +import android.bluetooth.BluetoothDevice +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever + +class BluetoothConnectionTrackerLinkObservationTest { + private val scope = CoroutineScope(Dispatchers.Unconfined + SupervisorJob()) + private val tracker = BluetoothConnectionTracker(scope, mock()) + + @After + fun tearDown() { + scope.cancel() + } + + @Test + fun `stale connection callbacks cannot mutate or remove replacement link`() { + val address = "AA:BB:CC:DD:EE:FF" + val device = mock() + whenever(device.address).thenReturn(address) + + tracker.addDeviceConnection( + address, + BluetoothConnectionTracker.DeviceConnection(device = device, linkID = "link-a") + ) + tracker.addDeviceConnection( + address, + BluetoothConnectionTracker.DeviceConnection(device = device, linkID = "link-b") + ) + + assertFalse( + tracker.updateDeviceConnectionIfCurrent(address, "link-a") { + it.copy(rssi = -10) + } + ) + assertFalse(tracker.cleanupDeviceConnectionIfCurrent(address, "link-a")) + assertEquals("link-b", tracker.getCurrentLinkID(address)) + + assertTrue(tracker.observePeerIfCurrent(address, "link-b", "0011223344556677")) + assertEquals("0011223344556677", tracker.addressPeerMap[address]) + assertSame(device, tracker.getDeviceConnection(address)?.device) + } + + @Test + fun `one peer can remain directly observed over multiple current links`() { + val firstAddress = "AA:BB:CC:DD:EE:01" + val secondAddress = "AA:BB:CC:DD:EE:02" + val firstDevice = mock() + val secondDevice = mock() + whenever(firstDevice.address).thenReturn(firstAddress) + whenever(secondDevice.address).thenReturn(secondAddress) + + tracker.addDeviceConnection( + firstAddress, + BluetoothConnectionTracker.DeviceConnection(device = firstDevice, linkID = "link-a") + ) + tracker.addDeviceConnection( + secondAddress, + BluetoothConnectionTracker.DeviceConnection(device = secondDevice, linkID = "link-b") + ) + + assertTrue(tracker.observePeerIfCurrent(firstAddress, "link-a", PEER_ID)) + assertTrue(tracker.observePeerIfCurrent(secondAddress, "link-b", PEER_ID)) + assertTrue(tracker.observePeerIfCurrent(secondAddress, "link-b", PEER_ID)) + assertEquals(2, tracker.addressPeerMap.values.count { it == PEER_ID }) + + assertTrue(tracker.cleanupDeviceConnectionIfCurrent(firstAddress, "link-a")) + assertEquals(PEER_ID, tracker.addressPeerMap[secondAddress]) + assertTrue(tracker.addressPeerMap.containsValue(PEER_ID)) + } + + private companion object { + const val PEER_ID = "0011223344556677" + } +} diff --git a/app/src/test/kotlin/com/bitchat/android/mesh/DirectLinkAnnouncementPolicyTest.kt b/app/src/test/kotlin/com/bitchat/android/mesh/DirectLinkAnnouncementPolicyTest.kt new file mode 100644 index 00000000..8c0f2ad4 --- /dev/null +++ b/app/src/test/kotlin/com/bitchat/android/mesh/DirectLinkAnnouncementPolicyTest.kt @@ -0,0 +1,64 @@ +package com.bitchat.android.mesh + +import com.bitchat.android.model.RoutedPacket +import com.bitchat.android.protocol.BitchatPacket +import com.bitchat.android.protocol.MessageType +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class DirectLinkAnnouncementPolicyTest { + @Test + fun `accepted max ttl announce is a direct routing observation`() { + val routed = announce(ttl = MAX_TTL) + + assertEquals( + DirectLinkAnnouncementPolicy.Observation(PEER_ID, RELAY_ADDRESS, LINK_ID), + DirectLinkAnnouncementPolicy.observationFor(routed, MAX_TTL) + ) + } + + @Test + fun `relayed announce is not a direct routing observation`() { + assertNull( + DirectLinkAnnouncementPolicy.observationFor( + announce(ttl = (MAX_TTL - 1u).toUByte()), + MAX_TTL + ) + ) + } + + @Test + fun `repeated announce remains the same observation without transport authentication state`() { + val routed = announce(ttl = MAX_TTL) + + val first = DirectLinkAnnouncementPolicy.observationFor(routed, MAX_TTL) + val second = DirectLinkAnnouncementPolicy.observationFor(routed, MAX_TTL) + + assertEquals(first, second) + } + + private fun announce(ttl: UByte) = RoutedPacket( + packet = BitchatPacket( + version = 1u, + type = MessageType.ANNOUNCE.value, + senderID = PEER_ID.hexToBytes(), + timestamp = 1u, + payload = byteArrayOf(1), + ttl = ttl + ), + peerID = PEER_ID, + relayAddress = RELAY_ADDRESS, + ingressLinkID = LINK_ID + ) + + private fun String.hexToBytes(): ByteArray = + chunked(2).map { it.toInt(16).toByte() }.toByteArray() + + private companion object { + const val PEER_ID = "0011223344556677" + const val RELAY_ADDRESS = "transport-neighbor" + const val LINK_ID = "current-link" + val MAX_TTL: UByte = 7u + } +} diff --git a/app/src/test/kotlin/com/bitchat/android/wifi-aware/IngressLinkPolicyTest.kt b/app/src/test/kotlin/com/bitchat/android/wifi-aware/IngressLinkPolicyTest.kt new file mode 100644 index 00000000..cf352d7c --- /dev/null +++ b/app/src/test/kotlin/com/bitchat/android/wifi-aware/IngressLinkPolicyTest.kt @@ -0,0 +1,64 @@ +package com.bitchat.android.wifiaware + +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Test + +class IngressLinkPolicyTest { + @Test + fun `observation resolves only the exact ingress link`() { + val attackerSocket = Any() + val victimSocket = Any() + val links = mapOf( + "attacker-link" to IngressLinkPolicy.Link("provisional-attacker", attackerSocket), + "victim-link" to IngressLinkPolicy.Link("provisional-victim", victimSocket) + ) + val current = mapOf( + "provisional-attacker" to attackerSocket, + "provisional-victim" to victimSocket + ) + + val resolved = IngressLinkPolicy.resolve( + ingressLinkID = "victim-link", + relayAddress = "provisional-victim", + links = links, + currentTransportForRelay = current::get + ) + + assertSame(victimSocket, resolved?.transport) + } + + @Test + fun `stale replaced or mismatched ingress links cannot be observed`() { + val completedSocket = Any() + val replacementSocket = Any() + val links = mapOf( + "completed-link" to IngressLinkPolicy.Link("provisional", completedSocket) + ) + + assertNull( + IngressLinkPolicy.resolve( + ingressLinkID = "missing-link", + relayAddress = "provisional", + links = links, + currentTransportForRelay = { completedSocket } + ) + ) + assertNull( + IngressLinkPolicy.resolve( + ingressLinkID = "completed-link", + relayAddress = "different-provisional", + links = links, + currentTransportForRelay = { completedSocket } + ) + ) + assertNull( + IngressLinkPolicy.resolve( + ingressLinkID = "completed-link", + relayAddress = "provisional", + links = links, + currentTransportForRelay = { replacementSocket } + ) + ) + } +}