diff --git a/app/src/main/java/com/bitchat/android/noise/NoiseSession.kt b/app/src/main/java/com/bitchat/android/noise/NoiseSession.kt index aee7aedb5..1edc8950c 100644 --- a/app/src/main/java/com/bitchat/android/noise/NoiseSession.kt +++ b/app/src/main/java/com/bitchat/android/noise/NoiseSession.kt @@ -633,24 +633,6 @@ class NoiseSession( appendLine(" Has receive cipher: ${receiveCipher != null}") } - internal fun configureTransportForTesting( - sendKey: ByteArray, - receiveKey: ByteArray, - initialSendNonce: Long = 0L - ) { - synchronized(cipherLock) { - sendCipher?.destroy() - receiveCipher?.destroy() - sendCipher = Noise.createCipher("ChaChaPoly").apply { initializeKey(sendKey, 0) } - receiveCipher = Noise.createCipher("ChaChaPoly").apply { initializeKey(receiveKey, 0) } - messagesSent = initialSendNonce - messagesReceived = 0L - highestReceivedNonce = 0L - replayWindow.fill(0) - state = NoiseSessionState.Established - } - } - /** * Reset session state */ diff --git a/app/src/main/java/com/bitchat/android/nostr/NostrBackgroundEventProcessor.kt b/app/src/main/java/com/bitchat/android/nostr/NostrBackgroundEventProcessor.kt index b5a3eb457..ee49fe52b 100644 --- a/app/src/main/java/com/bitchat/android/nostr/NostrBackgroundEventProcessor.kt +++ b/app/src/main/java/com/bitchat/android/nostr/NostrBackgroundEventProcessor.kt @@ -10,6 +10,7 @@ import com.bitchat.android.ui.DataManager import com.bitchat.android.ui.MessageManager import com.bitchat.android.ui.NoiseSessionDelegate import com.bitchat.android.ui.PrivateChatManager +import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -24,10 +25,12 @@ import kotlinx.coroutines.launch internal class NostrBackgroundEventProcessor( application: Application, parentScope: CoroutineScope, - participantStore: GeohashParticipantStore = NostrBackgroundRuntime.participants + participantStore: GeohashParticipantStore = NostrBackgroundRuntime.participants, + processingDispatcher: CoroutineDispatcher = Dispatchers.IO.limitedParallelism(1), + signatureVerificationDispatcher: CoroutineDispatcher = Dispatchers.Default ) { private val scope = CoroutineScope( - parentScope.coroutineContext + Dispatchers.IO.limitedParallelism(1) + parentScope.coroutineContext + processingDispatcher ) private val state = ChatState(scope) private val dataManager = DataManager(application.applicationContext).apply { @@ -53,7 +56,8 @@ internal class NostrBackgroundEventProcessor( repo = geohashRepository, scope = scope, dataManager = dataManager, - addChannelMessage = AppStateStore::addChannelMessage + addChannelMessage = AppStateStore::addChannelMessage, + signatureVerificationDispatcher = signatureVerificationDispatcher ) private val directMessageHandler = NostrDirectMessageHandler( application = application, diff --git a/app/src/main/java/com/bitchat/android/nostr/NostrClient.kt b/app/src/main/java/com/bitchat/android/nostr/NostrClient.kt index 0257c756b..0c651c6e4 100644 --- a/app/src/main/java/com/bitchat/android/nostr/NostrClient.kt +++ b/app/src/main/java/com/bitchat/android/nostr/NostrClient.kt @@ -234,6 +234,11 @@ class NostrClient private constructor(private val context: Context) { * Get relay information */ val relayInfo: StateFlow> = relayManager.relays + + /** + * Get a fresh snapshot of all relays including live message counters. + */ + fun getLiveRelayStatuses(): List = relayManager.getRelayStatuses() // MARK: - Private Methods diff --git a/app/src/main/java/com/bitchat/android/nostr/NostrIdentity.kt b/app/src/main/java/com/bitchat/android/nostr/NostrIdentity.kt index 4ad158435..24f0e525b 100644 --- a/app/src/main/java/com/bitchat/android/nostr/NostrIdentity.kt +++ b/app/src/main/java/com/bitchat/android/nostr/NostrIdentity.kt @@ -30,7 +30,7 @@ data class NostrIdentity( */ fun generate(): NostrIdentity { val (privateKeyHex, publicKeyHex) = NostrCrypto.generateKeyPair() - val npub = Bech32.encode("npub", publicKeyHex.hexToByteArrayLocal()) + val npub = Bech32.encode("npub", publicKeyHex.hexToByteArray()) Log.d(TAG, "Generated new Nostr identity: npub=$npub") @@ -51,7 +51,7 @@ data class NostrIdentity( } val publicKeyHex = NostrCrypto.derivePublicKey(privateKeyHex) - val npub = Bech32.encode("npub", publicKeyHex.hexToByteArrayLocal()) + val npub = Bech32.encode("npub", publicKeyHex.hexToByteArray()) return NostrIdentity( privateKeyHex = privateKeyHex, @@ -177,7 +177,7 @@ object NostrIdentityBridge { // Try a few iterations to ensure a valid key can be formed (exactly like iOS) for (i in 0 until 10) { val candidateKey = candidateKey(seed, geohashBytes, i.toUInt()) - val candidateKeyHex = candidateKey.toHexStringLocal() + val candidateKeyHex = candidateKey.toHexString() if (NostrCrypto.isValidPrivateKey(candidateKeyHex)) { val identity = NostrIdentity.fromPrivateKey(candidateKeyHex) @@ -192,7 +192,7 @@ object NostrIdentityBridge { val digest = MessageDigest.getInstance("SHA-256") val fallbackKey = digest.digest(combined) - val fallbackIdentity = NostrIdentity.fromPrivateKey(fallbackKey.toHexStringLocal()) + val fallbackIdentity = NostrIdentity.fromPrivateKey(fallbackKey.toHexString()) geohashIdentityCache[forGeohash] = fallbackIdentity Log.d(TAG, "Used fallback geohash identity derivation") @@ -319,11 +319,6 @@ object NostrIdentityBridge { } } -// Extension functions for data conversion -private fun String.hexToByteArrayLocal(): ByteArray = this.hexToByteArray() - -private fun ByteArray.toHexStringLocal(): String = this.toHexString() - private fun UInt.toLittleEndianBytes(): ByteArray { val bytes = ByteArray(4) bytes[0] = (this and 0xFFu).toByte() diff --git a/app/src/main/java/com/bitchat/android/nostr/NostrRelayManager.kt b/app/src/main/java/com/bitchat/android/nostr/NostrRelayManager.kt index e9bc0b87e..20a2cd95e 100644 --- a/app/src/main/java/com/bitchat/android/nostr/NostrRelayManager.kt +++ b/app/src/main/java/com/bitchat/android/nostr/NostrRelayManager.kt @@ -353,6 +353,7 @@ class NostrRelayManager internal constructor( } updateRelaysList() updateConnectionStatus() + wakeDegradedBackgroundRelays() } /** @@ -533,6 +534,7 @@ class NostrRelayManager internal constructor( liveLocationRelayTokens.clear() updateRelaysList() updateConnectionStatus() + wakeDegradedBackgroundRelays() } private fun ensureConnectionsFor( @@ -946,10 +948,10 @@ class NostrRelayManager internal constructor( } /** - * Get detailed status for all relays + * Get detailed status for all relays (immutable snapshots with live message counters). */ fun getRelayStatuses(): List { - return synchronized(relaysList) { relaysList.toList() } + return synchronized(relaysList) { relaysList.map { it.copy() } } } /** @@ -1316,13 +1318,17 @@ class NostrRelayManager internal constructor( // failure: "unable to resolve host" is what this device reports when it // simply has no network, so treating it as permanent turns a walk // through a tunnel into a dead relay layer for the rest of the process. - var extendedBackgroundThrottle = false - val backoffInterval = synchronized(relaysList) { + // Decide backoff AND register both throttle marker and reconnect job atomically under + // synchronized(relaysList) so a concurrent disconnect/release/revoke cannot interleave + // and miss waking this relay. + var backoffInterval = 0L + synchronized(relaysList) { val relay = relaysList.find { it.url == relayUrl } ?: return val previousAttempts = if (wasStable) 0 else relay.reconnectAttempts relay.reconnectAttempts = RelayReconnectPolicy.nextAttempt(previousAttempts) var delayMs = RelayReconnectPolicy.backoffMs(relay.reconnectAttempts) val isBackground = isAppBackgrounded() + var extendedBackgroundThrottle = false if (isBackground && relay.reconnectAttempts >= BACKGROUND_DEAD_RELAY_MIN_ATTEMPTS && hasHealthyAlternativeForRelayLocked(relayUrl) @@ -1331,54 +1337,57 @@ class NostrRelayManager internal constructor( extendedBackgroundThrottle = true } relay.nextReconnectTime = nowWall + delayMs - delayMs - } - if (extendedBackgroundThrottle) { - backgroundThrottledRelays.add(relayUrl) - } else { - backgroundThrottledRelays.remove(relayUrl) + backoffInterval = delayMs + + if (extendedBackgroundThrottle) { + backgroundThrottledRelays.add(relayUrl) + } else { + backgroundThrottledRelays.remove(relayUrl) + } + + reconnectJobs.remove(relayUrl)?.cancel() + val reconnectJob = scope.launch { + delay(delayMs) + backgroundThrottledRelays.remove(relayUrl) + val (stillAllowed, currentToken) = authorizeRelayConnection(relayUrl, connectionToken) + if (desiredConnected.get() && + networkAvailable.get() && + stillAllowed + ) { + connectToRelay(relayUrl, currentToken) + } + } + reconnectJobs[relayUrl] = reconnectJob + if (connectionToken != null) { + liveLocationConnectionJobs.add(reconnectJob) + } + reconnectJob.invokeOnCompletion { + reconnectJobs.remove(relayUrl, reconnectJob) + if (connectionToken != null) { + liveLocationConnectionJobs.remove(reconnectJob) + } + } } Log.d(TAG, "Scheduling Nostr relay reconnection in ${backoffInterval}ms") - - reconnectJobs.remove(relayUrl)?.cancel() - val reconnectJob = scope.launch { - delay(backoffInterval) - backgroundThrottledRelays.remove(relayUrl) - val (stillAllowed, currentToken) = authorizeRelayConnection(relayUrl, connectionToken) - if (desiredConnected.get() && - networkAvailable.get() && - stillAllowed - ) { - connectToRelay(relayUrl, currentToken) - } - } - reconnectJobs[relayUrl] = reconnectJob - if (connectionToken != null) { - liveLocationConnectionJobs.add(reconnectJob) - } - reconnectJob.invokeOnCompletion { - reconnectJobs.remove(relayUrl, reconnectJob) - if (connectionToken != null) { - liveLocationConnectionJobs.remove(reconnectJob) - } - } } /** * Cancel extended 15-minute background backoff timers for any throttled relay that no longer - * has a healthy connected alternative (for example after the healthy relay disconnects or a - * new subscription targets the throttled relay exclusively). + * has a healthy connected alternative (for example after the healthy relay disconnects, + * is released/revoked, or a new subscription targets the throttled relay exclusively). */ private fun wakeDegradedBackgroundRelays() { - if (backgroundThrottledRelays.isEmpty()) return if (!desiredConnected.get() || !networkAvailable.get()) return val relaysToWake = synchronized(relaysList) { + if (backgroundThrottledRelays.isEmpty()) return val toWake = mutableListOf() - for (url in backgroundThrottledRelays) { + for (url in backgroundThrottledRelays.toList()) { if (!hasHealthyAlternativeForRelayLocked(url)) { toWake.add(url) + backgroundThrottledRelays.remove(url) + reconnectJobs.remove(url)?.cancel() relaysList.find { it.url == url }?.nextReconnectTime = null } } @@ -1386,10 +1395,6 @@ class NostrRelayManager internal constructor( } if (relaysToWake.isEmpty()) return - relaysToWake.forEach { url -> - backgroundThrottledRelays.remove(url) - reconnectJobs.remove(url)?.cancel() - } updateRelaysList() scope.launch { diff --git a/app/src/main/java/com/bitchat/android/nostr/NostrTestManager.kt b/app/src/main/java/com/bitchat/android/nostr/NostrTestManager.kt index 76f422494..b3a60e645 100644 --- a/app/src/main/java/com/bitchat/android/nostr/NostrTestManager.kt +++ b/app/src/main/java/com/bitchat/android/nostr/NostrTestManager.kt @@ -258,7 +258,7 @@ class NostrTestManager(private val context: Context) { val isConnected = nostrClient.relayConnectionStatus.value ?: false appendLine("Relay Connected: $isConnected") - val relays = nostrClient.relayInfo.value ?: emptyList() + val relays = nostrClient.getLiveRelayStatuses() appendLine("Relays (${relays.size}):") relays.forEach { relay -> appendLine(" ${relay.url}: ${if (relay.isConnected) "✅" else "❌"} (sent: ${relay.messagesSent}, received: ${relay.messagesReceived})") diff --git a/app/src/main/java/com/bitchat/android/ui/GeohashPeopleList.kt b/app/src/main/java/com/bitchat/android/ui/GeohashPeopleList.kt index 046377323..2d91813f6 100644 --- a/app/src/main/java/com/bitchat/android/ui/GeohashPeopleList.kt +++ b/app/src/main/java/com/bitchat/android/ui/GeohashPeopleList.kt @@ -48,40 +48,46 @@ fun GeohashPeopleList( val palette = LocalBitchatPalette.current val colorScheme = MaterialTheme.colorScheme - val myHex by produceState( - initialValue = when (val channel = selectedLocationChannel) { - is com.bitchat.android.geohash.ChannelID.Location -> - com.bitchat.android.nostr.NostrIdentityBridge - .getCachedIdentity(channel.channel.geohash) - ?.publicKeyHex - ?.lowercase(Locale.ROOT) - else -> null + val currentGeohash = (selectedLocationChannel as? com.bitchat.android.geohash.ChannelID.Location) + ?.channel?.geohash + val derivedSelfIdentity by produceState?>( + initialValue = currentGeohash?.let { geo -> + geo to com.bitchat.android.nostr.NostrIdentityBridge + .getCachedIdentity(geo) + ?.publicKeyHex + ?.lowercase(Locale.ROOT) }, - key1 = selectedLocationChannel + key1 = currentGeohash ) { - val channel = selectedLocationChannel - if (channel !is com.bitchat.android.geohash.ChannelID.Location) { + if (currentGeohash == null) { value = null return@produceState } - val cached = com.bitchat.android.nostr.NostrIdentityBridge - .getCachedIdentity(channel.channel.geohash) - if (cached != null) { - value = cached.publicKeyHex.lowercase(Locale.ROOT) - return@produceState - } - value = try { + val cachedHex = com.bitchat.android.nostr.NostrIdentityBridge + .getCachedIdentity(currentGeohash) + ?.publicKeyHex + ?.lowercase(Locale.ROOT) + // Immediately bind state to the newly selected channel so a previous channel's pubkey + // can never appear as self while a cold derivation runs on Dispatchers.IO. + value = currentGeohash to cachedHex + if (cachedHex != null) return@produceState + + val derivedHex = try { kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { com.bitchat.android.nostr.NostrIdentityBridge.deriveIdentity( - forGeohash = channel.channel.geohash, + forGeohash = currentGeohash, context = viewModel.getApplication() ).publicKeyHex.lowercase(Locale.ROOT) } + } catch (e: kotlinx.coroutines.CancellationException) { + throw e } catch (e: Exception) { Log.e("GeohashPeopleList", "Failed to derive identity: ${e.message}") null } + value = currentGeohash to derivedHex } + val myHex = derivedSelfIdentity?.takeIf { it.first == currentGeohash }?.second val peopleIncludingSelf = remember(geohashPeople, myHex, nickname) { val currentMyHex = myHex if (currentMyHex != null && geohashPeople.none { it.id.equals(currentMyHex, ignoreCase = true) }) { diff --git a/app/src/main/java/com/bitchat/android/ui/GeohashViewModel.kt b/app/src/main/java/com/bitchat/android/ui/GeohashViewModel.kt index 1bec711bb..f559da4a6 100644 --- a/app/src/main/java/com/bitchat/android/ui/GeohashViewModel.kt +++ b/app/src/main/java/com/bitchat/android/ui/GeohashViewModel.kt @@ -370,13 +370,24 @@ class GeohashViewModel( notificationManager.clearNotificationsForGeohash(channel.channel.geohash) try { messageManager.clearChannelUnreadCount("geo:${channel.channel.geohash}") } catch (_: Exception) { } - try { - val identity = NostrIdentityBridge.deriveIdentity(channel.channel.geohash, getApplication()) - // We don't update participant here anymore; presence loop handles it via Kind 20001 - val teleported = locationChannelManager?.teleported?.value - ?: state.isTeleported.value - if (teleported) repo.markTeleported(identity.publicKeyHex) - } catch (e: Exception) { Log.w(TAG, "Failed identity setup: ${e.message}") } + val targetGeohash = channel.channel.geohash + val teleported = locationChannelManager?.teleported?.value + ?: state.isTeleported.value + val cachedIdentity = NostrIdentityBridge.getCachedIdentity(targetGeohash) + if (cachedIdentity != null) { + if (teleported) repo.markTeleported(cachedIdentity.publicKeyHex) + } else { + viewModelScope.launch(kotlinx.coroutines.Dispatchers.IO) { + try { + val identity = NostrIdentityBridge.deriveIdentity(targetGeohash, getApplication()) + if (teleported && activeChannelGeohash == targetGeohash) { + repo.markTeleported(identity.publicKeyHex) + } + } catch (e: Exception) { + Log.w(TAG, "Failed identity setup: ${e.message}") + } + } + } startGeoParticipantsTimer() val liveLocationToken = locationChannelManager diff --git a/app/src/main/java/com/bitchat/android/util/BinaryEncodingUtils.kt b/app/src/main/java/com/bitchat/android/util/BinaryEncodingUtils.kt index db24b056c..879d8c063 100644 --- a/app/src/main/java/com/bitchat/android/util/BinaryEncodingUtils.kt +++ b/app/src/main/java/com/bitchat/android/util/BinaryEncodingUtils.kt @@ -14,11 +14,12 @@ import java.util.* fun ByteArray.hexEncodedString(): String = toHexString() fun String.dataFromHexString(): ByteArray? { - // Match iOS Data(hexString:): trim, optional 0x/0X prefix, reject odd length. + // Match iOS Data(hexString:) and Kotlin String.trim(): Unicode whitespace only (never NUL), + // optional 0x/0X prefix, reject odd length. var start = 0 var end = length - while (start < end && this[start] <= ' ') start++ - while (end > start && this[end - 1] <= ' ') end-- + while (start < end && this[start].isWhitespace()) start++ + while (end > start && this[end - 1].isWhitespace()) end-- if (end - start >= 2 && this[start] == '0' && (this[start + 1] == 'x' || this[start + 1] == 'X')) { start += 2 } diff --git a/app/src/test/kotlin/com/bitchat/android/mesh/MeshPacketPipelineTest.kt b/app/src/test/kotlin/com/bitchat/android/mesh/MeshPacketPipelineTest.kt index 9a24bfdaf..319e9ffa3 100644 --- a/app/src/test/kotlin/com/bitchat/android/mesh/MeshPacketPipelineTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/mesh/MeshPacketPipelineTest.kt @@ -30,6 +30,9 @@ class MeshPacketPipelineTest { assertEquals("00010203", bytes.toHexString(4)) assertArrayEquals(bytes, hex.dataFromHexString()) assertArrayEquals(bytes, " 0x${hex.uppercase()} ".dataFromHexString()) + assertArrayEquals(byteArrayOf(0x01, 0x02), "\u20030102\u2003".dataFromHexString()) + assertNull("\u00000102".dataFromHexString()) + assertNull("0102\u0000".dataFromHexString()) assertNull("abc".dataFromHexString()) assertNull("zz".dataFromHexString()) assertEquals(-1, hexNibbleOrNegative('z')) diff --git a/app/src/test/kotlin/com/bitchat/android/noise/NoiseTransportFrameVectorTest.kt b/app/src/test/kotlin/com/bitchat/android/noise/NoiseTransportFrameVectorTest.kt index ab96ff0fb..46d7b696b 100644 --- a/app/src/test/kotlin/com/bitchat/android/noise/NoiseTransportFrameVectorTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/noise/NoiseTransportFrameVectorTest.kt @@ -11,6 +11,35 @@ import org.junit.Test class NoiseTransportFrameVectorTest { + private fun newTransportSession( + isInitiator: Boolean, + sendKey: ByteArray, + receiveKey: ByteArray, + initialSendNonce: Long = 0L + ): NoiseSession { + val dummyKey = ByteArray(32) { 0x11 } + val session = NoiseSession("0102030405060708", isInitiator, dummyKey, dummyKey) + val sendCipher = Noise.createCipher("ChaChaPoly").apply { initializeKey(sendKey, 0) } + val receiveCipher = Noise.createCipher("ChaChaPoly").apply { initializeKey(receiveKey, 0) } + NoiseSession::class.java.getDeclaredField("sendCipher").apply { + isAccessible = true + set(session, sendCipher) + } + NoiseSession::class.java.getDeclaredField("receiveCipher").apply { + isAccessible = true + set(session, receiveCipher) + } + NoiseSession::class.java.getDeclaredField("messagesSent").apply { + isAccessible = true + setLong(session, initialSendNonce) + } + NoiseSession::class.java.getDeclaredField("state").apply { + isAccessible = true + set(session, NoiseSession.NoiseSessionState.Established) + } + return session + } + @Test fun `NoiseSession transport encrypt and decrypt match independent RFC 8439 ChaCha20-Poly1305 golden vector with nonzero nonce`() { val transportKey = ByteArray(32) { it.toByte() } @@ -25,21 +54,18 @@ class NoiseTransportFrameVectorTest { "9d65ef2c2cb05224827ea8812ec2" ).dataFromHexString()!! - val dummyKey = ByteArray(32) { 0x11 } - val sender = NoiseSession("0102030405060708", true, dummyKey, dummyKey) - val receiver = NoiseSession("0102030405060708", false, dummyKey, dummyKey) + val sender = newTransportSession( + isInitiator = true, + sendKey = transportKey, + receiveKey = transportKey, + initialSendNonce = nonce + ) + val receiver = newTransportSession( + isInitiator = false, + sendKey = transportKey, + receiveKey = transportKey + ) try { - sender.configureTransportForTesting( - sendKey = transportKey, - receiveKey = transportKey, - initialSendNonce = nonce - ) - receiver.configureTransportForTesting( - sendKey = transportKey, - receiveKey = transportKey, - initialSendNonce = 0L - ) - val encrypted = sender.encrypt(plaintext) assertArrayEquals(expectedWireFrame, encrypted) @@ -51,12 +77,22 @@ class NoiseTransportFrameVectorTest { receiver.decrypt(expectedWireFrame) } - // Flipping a bit in nonce prefix, ciphertext, or Poly1305 tag must fail closed + // Flipping a bit in nonce prefix, ciphertext, or Poly1305 tag on a fresh receiver + // exercises AEAD authentication directly (before replay window marks nonce seen). for (bitOffset in listOf(3, 4, expectedWireFrame.lastIndex)) { - val tampered = expectedWireFrame.copyOf() - tampered[bitOffset] = (tampered[bitOffset].toInt() xor 0x01).toByte() - assertThrows(SessionError.DecryptionFailed::class.java) { - receiver.decrypt(tampered) + val freshReceiver = newTransportSession( + isInitiator = false, + sendKey = transportKey, + receiveKey = transportKey + ) + try { + val tampered = expectedWireFrame.copyOf() + tampered[bitOffset] = (tampered[bitOffset].toInt() xor 0x01).toByte() + assertThrows(SessionError.DecryptionFailed::class.java) { + freshReceiver.decrypt(tampered) + } + } finally { + freshReceiver.destroy() } } } finally { diff --git a/app/src/test/kotlin/com/bitchat/android/nostr/NostrBackgroundBlocklistTest.kt b/app/src/test/kotlin/com/bitchat/android/nostr/NostrBackgroundBlocklistRobolectricTest.kt similarity index 63% rename from app/src/test/kotlin/com/bitchat/android/nostr/NostrBackgroundBlocklistTest.kt rename to app/src/test/kotlin/com/bitchat/android/nostr/NostrBackgroundBlocklistRobolectricTest.kt index 587d90b86..8fef55ff0 100644 --- a/app/src/test/kotlin/com/bitchat/android/nostr/NostrBackgroundBlocklistTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/nostr/NostrBackgroundBlocklistRobolectricTest.kt @@ -5,11 +5,11 @@ import androidx.test.core.app.ApplicationProvider import com.bitchat.android.services.AppStateStore import com.bitchat.android.ui.DataManager import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestDispatcher import org.junit.After import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue @@ -19,17 +19,20 @@ import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +@OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricTestRunner::class) -class NostrBackgroundBlocklistTest { +class NostrBackgroundBlocklistRobolectricTest { private lateinit var app: Application + private lateinit var dispatcher: TestDispatcher private lateinit var scope: CoroutineScope @Before fun setUp() { app = ApplicationProvider.getApplicationContext() AppStateStore.clear() - scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + dispatcher = StandardTestDispatcher() + scope = CoroutineScope(SupervisorJob() + dispatcher) } @After @@ -41,46 +44,51 @@ class NostrBackgroundBlocklistTest { @Test @Config(sdk = [29]) - fun `DataManager clearAllData lifts geohash sender block through public event handling on API 29`() = runBlocking { + fun `DataManager clearAllData lifts geohash sender block through public event handling on API 29`() { val externalDataManager = DataManager(app) externalDataManager.clearAllData() - val blockedSender = NostrIdentity.generate() - val unblockedSender = NostrIdentity.generate() + val fixedNowMs = 1_700_000_000_000L + val fixedNowSec = (fixedNowMs / 1_000L).toInt() + val blockedSender = NostrIdentity.fromPrivateKey("11".repeat(32)) + val unblockedSender = NostrIdentity.fromPrivateKey("22".repeat(32)) externalDataManager.addGeohashBlockedUser(blockedSender.publicKeyHex) - val participantStore = GeohashParticipantStore() - val processor = NostrBackgroundEventProcessor(app, scope, participantStore) + val participantStore = GeohashParticipantStore(nowMillis = { fixedNowMs }) + val processor = NostrBackgroundEventProcessor( + application = app, + parentScope = scope, + participantStore = participantStore, + processingDispatcher = dispatcher, + signatureVerificationDispatcher = dispatcher + ) val geohash = "u4pruy" - val nowSec = (System.currentTimeMillis() / 1_000L).toInt() - // Send a presence event from the blocked sender followed by a sentinel presence event from - // an unblocked sender. Because processor serializes on a single-threaded IO dispatcher, - // once the sentinel lands in participantStore the earlier blocked event was already dropped. val blockedBeforeWipe = NostrEvent( pubkey = blockedSender.publicKeyHex, - createdAt = nowSec, + createdAt = fixedNowSec, kind = NostrKind.GEOHASH_PRESENCE, tags = listOf(listOf("g", geohash)), content = "" ).sign(blockedSender.privateKeyHex) - val sentinel = NostrEvent( + val unblockedBeforeWipe = NostrEvent( pubkey = unblockedSender.publicKeyHex, - createdAt = nowSec, + createdAt = fixedNowSec, kind = NostrKind.GEOHASH_PRESENCE, tags = listOf(listOf("g", geohash)), content = "" ).sign(unblockedSender.privateKeyHex) processor.onGeohashMessage(blockedBeforeWipe, geohash) - processor.onGeohashMessage(sentinel, geohash) + processor.onGeohashMessage(unblockedBeforeWipe, geohash) + // Drain every coroutine (including signature verification) deterministically before asserting. + dispatcher.scheduler.advanceUntilIdle() - withTimeout(5_000) { - while (unblockedSender.publicKeyHex !in participantStore.snapshots.value.participants[geohash].orEmpty()) { - kotlinx.coroutines.yield() - } - } val beforeParticipants = participantStore.snapshots.value.participants[geohash].orEmpty() + assertTrue( + "unblocked sender event must be recorded prior to wipe", + unblockedSender.publicKeyHex in beforeParticipants + ) assertFalse( "blocked sender event must be dropped prior to wipe", blockedSender.publicKeyHex in beforeParticipants @@ -92,18 +100,14 @@ class NostrBackgroundBlocklistTest { val afterWipe = NostrEvent( pubkey = blockedSender.publicKeyHex, - createdAt = nowSec + 1, + createdAt = fixedNowSec + 1, kind = NostrKind.GEOHASH_PRESENCE, tags = listOf(listOf("g", geohash)), content = "" ).sign(blockedSender.privateKeyHex) processor.onGeohashMessage(afterWipe, geohash) + dispatcher.scheduler.advanceUntilIdle() - withTimeout(5_000) { - while (blockedSender.publicKeyHex !in participantStore.snapshots.value.participants[geohash].orEmpty()) { - kotlinx.coroutines.yield() - } - } val afterParticipants = participantStore.snapshots.value.participants[geohash].orEmpty() assertTrue( "event from previously blocked sender must be accepted after API 29 clearAllData", diff --git a/app/src/test/kotlin/com/bitchat/android/nostr/NostrIdentityWipeTest.kt b/app/src/test/kotlin/com/bitchat/android/nostr/NostrIdentityWipeRobolectricTest.kt similarity index 98% rename from app/src/test/kotlin/com/bitchat/android/nostr/NostrIdentityWipeTest.kt rename to app/src/test/kotlin/com/bitchat/android/nostr/NostrIdentityWipeRobolectricTest.kt index f05576547..e9c4b1e93 100644 --- a/app/src/test/kotlin/com/bitchat/android/nostr/NostrIdentityWipeTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/nostr/NostrIdentityWipeRobolectricTest.kt @@ -13,7 +13,7 @@ import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) -class NostrIdentityWipeTest { +class NostrIdentityWipeRobolectricTest { private val app: Application = ApplicationProvider.getApplicationContext() diff --git a/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayBackgroundRecoveryTest.kt b/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayBackgroundRecoveryRobolectricTest.kt similarity index 58% rename from app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayBackgroundRecoveryTest.kt rename to app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayBackgroundRecoveryRobolectricTest.kt index 21a833a50..8199b9111 100644 --- a/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayBackgroundRecoveryTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayBackgroundRecoveryRobolectricTest.kt @@ -13,6 +13,7 @@ import okhttp3.WebSocket import okhttp3.WebSocketListener import okio.ByteString import org.junit.After +import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @@ -23,7 +24,7 @@ import java.util.concurrent.atomic.AtomicLong @OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricTestRunner::class) -class NostrRelayBackgroundRecoveryTest { +class NostrRelayBackgroundRecoveryRobolectricTest { private val dispatcher = StandardTestDispatcher() private val scope = CoroutineScope(dispatcher + SupervisorJob()) @@ -38,13 +39,7 @@ class NostrRelayBackgroundRecoveryTest { @Test fun `background-throttled relay wakes immediately when healthy alternative disconnects`() { - val manager = NostrRelayManager( - webSocketFactory = { factory }, - scope = scope, - monotonicClockMs = { fakeMonoMs.get() }, - awaitTorRoute = { true }, - backgroundStateFlow = isBackground - ) + val manager = newManager() val relays = NostrRelayManager.defaultRelays() val deadRelay = relays[0] val healthyRelays = relays.drop(1) @@ -52,43 +47,18 @@ class NostrRelayBackgroundRecoveryTest { manager.connect() dispatcher.scheduler.runCurrent() - // Mark all other relays open and healthy - val openResponse = Response.Builder() - .request(Request.Builder().url("https://relay.example").build()) - .protocol(Protocol.HTTP_1_1) - .code(101) - .message("Switching Protocols") - .build() - val healthyPairs = healthyRelays.map { url -> - factory.openedWithListeners.last { it.first.url == url }.also { (ws, listener) -> - listener.onOpen(ws, openResponse) - } - } - - // Fail deadRelay 4 times in background so it enters the 15-minute backoff - repeat(4) { attempt -> - val (ws, listener) = factory.openedWithListeners.last { it.first.url == deadRelay } - listener.onFailure(ws, IOException("scripted connect failure"), null) - if (attempt < 3) { - val backoff = RelayReconnectPolicy.backoffMs(attempt + 1) + 1L - dispatcher.scheduler.advanceTimeBy(backoff) - fakeMonoMs.addAndGet(backoff) - dispatcher.scheduler.runCurrent() - } - } + val healthyPairs = healthyRelays.map { url -> openRelay(url) } + failRelayIntoBackgroundThrottle(deadRelay) // Confirm deadRelay is throttled past normal attempt-4 backoff while healthy relays are up factory.reset() - val normalBackoff = RelayReconnectPolicy.backoffMs(4) + 1L - dispatcher.scheduler.advanceTimeBy(normalBackoff) - fakeMonoMs.addAndGet(normalBackoff) - dispatcher.scheduler.runCurrent() + advance(RelayReconnectPolicy.backoffMs(4) + 1L) assertFalse( "deadRelay should stay throttled while healthy alternatives are connected", factory.openedSinceReset.any { it.url == deadRelay } ) - // Now drop all healthy alternatives -> deadRelay must wake immediately without waiting 15m + // Drop all healthy alternatives -> deadRelay must wake immediately without waiting 15m factory.reset() healthyPairs.forEach { (ws, listener) -> listener.onFailure(ws, IOException("healthy relay lost"), null) @@ -103,13 +73,7 @@ class NostrRelayBackgroundRecoveryTest { @Test fun `background-throttled relay wakes immediately when a new subscription targets it exclusively`() { - val manager = NostrRelayManager( - webSocketFactory = { factory }, - scope = scope, - monotonicClockMs = { fakeMonoMs.get() }, - awaitTorRoute = { true }, - backgroundStateFlow = isBackground - ) + val manager = newManager() val relays = NostrRelayManager.defaultRelays() val deadRelay = relays[0] val healthyRelay = relays[1] @@ -117,34 +81,11 @@ class NostrRelayBackgroundRecoveryTest { manager.connect() dispatcher.scheduler.runCurrent() - val openResponse = Response.Builder() - .request(Request.Builder().url("https://relay.example").build()) - .protocol(Protocol.HTTP_1_1) - .code(101) - .message("Switching Protocols") - .build() - factory.openedWithListeners.last { it.first.url == healthyRelay }.let { (ws, listener) -> - listener.onOpen(ws, openResponse) - } + openRelay(healthyRelay) + failRelayIntoBackgroundThrottle(deadRelay) - // Fail deadRelay 4 times in background so it enters the 15-minute backoff - repeat(4) { attempt -> - val (ws, listener) = factory.openedWithListeners.last { it.first.url == deadRelay } - listener.onFailure(ws, IOException("scripted connect failure"), null) - if (attempt < 3) { - val backoff = RelayReconnectPolicy.backoffMs(attempt + 1) + 1L - dispatcher.scheduler.advanceTimeBy(backoff) - fakeMonoMs.addAndGet(backoff) - dispatcher.scheduler.runCurrent() - } - } - - // Confirm deadRelay is throttled past normal attempt-4 backoff factory.reset() - val normalBackoff = RelayReconnectPolicy.backoffMs(4) + 1L - dispatcher.scheduler.advanceTimeBy(normalBackoff) - fakeMonoMs.addAndGet(normalBackoff) - dispatcher.scheduler.runCurrent() + advance(RelayReconnectPolicy.backoffMs(4) + 1L) assertFalse( "deadRelay should stay throttled before sole-target subscription arrives", factory.openedSinceReset.any { it.url == deadRelay } @@ -166,6 +107,101 @@ class NostrRelayBackgroundRecoveryTest { ) } + @Test + fun `background-throttled relay wakes immediately when healthy extra relay is released`() { + val manager = newManager() + val relays = NostrRelayManager.defaultRelays() + val deadRelay = relays[0] + val extraHealthyRelay = "wss://extra-healthy.example" + + manager.connect() + dispatcher.scheduler.runCurrent() + manager.connectToRelays(listOf(extraHealthyRelay)) + dispatcher.scheduler.runCurrent() + + // Only the extra relay is connected; all default relays fail + openRelay(extraHealthyRelay) + failRelayIntoBackgroundThrottle(deadRelay) + + factory.reset() + advance(RelayReconnectPolicy.backoffMs(4) + 1L) + assertFalse(factory.openedSinceReset.any { it.url == deadRelay }) + + // Releasing the sole connected extra relay must wake throttled default relays immediately + factory.reset() + manager.releaseRelays(listOf(extraHealthyRelay)) + dispatcher.scheduler.runCurrent() + + assertTrue( + "releasing the last healthy alternative must wake throttled relays immediately", + factory.openedSinceReset.any { it.url == deadRelay } + ) + } + + @Test + fun `getRelayStatuses reports live sent and received counters without waiting for reconnect`() { + val manager = newManager() + val targetRelay = NostrRelayManager.defaultRelays()[0] + manager.connect() + dispatcher.scheduler.runCurrent() + + val (ws, listener) = openRelay(targetRelay) + val identity = NostrIdentity.fromPrivateKey("33".repeat(32)) + val event = NostrEvent( + pubkey = identity.publicKeyHex, + createdAt = 1_700_000_000, + kind = NostrKind.TEXT_NOTE, + tags = emptyList(), + content = "live-counter-check" + ).sign(identity.privateKeyHex) + + manager.sendEvent(event, relayUrls = listOf(targetRelay)) + dispatcher.scheduler.runCurrent() + + val inboundJson = """["EVENT","sub-1",{"id":"${event.id}","pubkey":"${event.pubkey}","created_at":${event.createdAt},"kind":${event.kind},"tags":[],"content":"live-counter-check","sig":"${event.sig}"}]""" + listener.onMessage(ws, inboundJson) + + val liveStatus = manager.getRelayStatuses().first { it.url == targetRelay } + assertEquals(1, liveStatus.messagesSent) + assertEquals(1, liveStatus.messagesReceived) + } + + private fun newManager() = NostrRelayManager( + webSocketFactory = { factory }, + scope = scope, + monotonicClockMs = { fakeMonoMs.get() }, + awaitTorRoute = { true }, + backgroundStateFlow = isBackground + ) + + private fun openRelay(url: String): Pair { + val openResponse = Response.Builder() + .request(Request.Builder().url("https://relay.example").build()) + .protocol(Protocol.HTTP_1_1) + .code(101) + .message("Switching Protocols") + .build() + return factory.openedWithListeners.last { it.first.url == url }.also { (ws, listener) -> + listener.onOpen(ws, openResponse) + } + } + + private fun failRelayIntoBackgroundThrottle(relayUrl: String) { + repeat(4) { attempt -> + val (ws, listener) = factory.openedWithListeners.last { it.first.url == relayUrl } + listener.onFailure(ws, IOException("scripted connect failure"), null) + if (attempt < 3) { + advance(RelayReconnectPolicy.backoffMs(attempt + 1) + 1L) + } + } + } + + private fun advance(ms: Long) { + dispatcher.scheduler.advanceTimeBy(ms) + fakeMonoMs.addAndGet(ms) + dispatcher.scheduler.runCurrent() + } + private class FakeWebSocketFactory : WebSocket.Factory { val openedSinceReset = mutableListOf() val openedWithListeners = mutableListOf>() diff --git a/app/src/test/kotlin/com/bitchat/android/services/SeenMessageStorePersistenceTest.kt b/app/src/test/kotlin/com/bitchat/android/services/SeenMessageStorePersistenceRobolectricTest.kt similarity index 99% rename from app/src/test/kotlin/com/bitchat/android/services/SeenMessageStorePersistenceTest.kt rename to app/src/test/kotlin/com/bitchat/android/services/SeenMessageStorePersistenceRobolectricTest.kt index f1dce453f..2050b62b5 100644 --- a/app/src/test/kotlin/com/bitchat/android/services/SeenMessageStorePersistenceTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/services/SeenMessageStorePersistenceRobolectricTest.kt @@ -20,7 +20,7 @@ import java.util.concurrent.atomic.AtomicInteger @OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricTestRunner::class) -class SeenMessageStorePersistenceTest { +class SeenMessageStorePersistenceRobolectricTest { private val app: Application = ApplicationProvider.getApplicationContext() private val gson = Gson()