From 1e3515ddf3a918496f51054991905b608a30e56b Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:14:49 -0500 Subject: [PATCH 1/2] Reconnect Nostr relays after panic wipe clearAllOnPanic restored the desired-connected flag but never reconnected, so the default relays and the subscription validation loop stayed down until the process restarted. Reconnect from scratch on the default relays, dropping relays the wiped session added so the fresh identity is not tied to its geohash relays. Stay offline when the conversation wipe could not be confirmed, matching the mesh transports. --- .../android/nostr/NostrRelayManager.kt | 51 ++++-- .../com/bitchat/android/ui/ChatViewModel.kt | 2 +- .../bitchat/android/ui/GeohashViewModel.kt | 4 +- ...layManagerPanicReconnectRobolectricTest.kt | 172 ++++++++++++++++++ 4 files changed, 213 insertions(+), 16 deletions(-) create mode 100644 app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayManagerPanicReconnectRobolectricTest.kt 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 5b294825c..12f646144 100644 --- a/app/src/main/java/com/bitchat/android/nostr/NostrRelayManager.kt +++ b/app/src/main/java/com/bitchat/android/nostr/NostrRelayManager.kt @@ -19,8 +19,16 @@ import java.util.concurrent.atomic.AtomicBoolean * Manages WebSocket connections to Nostr relays * Compatible with iOS implementation with Android-specific optimizations */ -class NostrRelayManager private constructor() { - +class NostrRelayManager internal constructor( + private val webSocketFactory: () -> WebSocket.Factory, + private val scope: CoroutineScope +) { + + private constructor() : this( + webSocketFactory = { com.bitchat.android.net.OkHttpProvider.webSocketClient() }, + scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + ) + companion object { @JvmStatic val shared = NostrRelayManager() @@ -117,19 +125,16 @@ class NostrRelayManager private constructor() { // Bounded per-relay delivery queue for reconnect reliability. private val messageQueue = NostrPendingEventQueue(MAX_QUEUED_EVENTS) - // Coroutine scope for background operations - private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) - // Subscription validation timer private var subscriptionValidationJob: Job? = null private val powerManager: com.bitchat.android.mesh.PowerManager? get() = appContext?.let { com.bitchat.android.mesh.PowerManager.getInstance(it) } @Volatile private var appContext: android.content.Context? = null - // OkHttp client for WebSocket connections (via provider to honor Tor) - private val httpClient: OkHttpClient - get() = com.bitchat.android.net.OkHttpProvider.webSocketClient() - + // WebSocket factory, resolved per connection (via provider to honor Tor) + private val httpClient: WebSocket.Factory + get() = webSocketFactory() + private val gson by lazy { NostrRequest.createGson() } // Per-geohash relay selection @@ -726,22 +731,42 @@ class NostrRelayManager private constructor() { /** * Clear all subscription tracking, deduplication cache, message queue, and connections for panic mode. + * + * When [reconnect] is true and connectivity was desired, comes back online from scratch on the + * default relays. Pass false to stay offline when the wipe could not be confirmed. */ - fun clearAllOnPanic() { + fun clearAllOnPanic(reconnect: Boolean) { try { val wasConnected = desiredConnected.get() clearAllSubscriptions() clearDeduplicationCache() disconnect() - if (wasConnected) { - desiredConnected.set(true) + forgetSessionRelays() + if (wasConnected && reconnect) { + connect() } Log.w(TAG, "🚨 Cleared NostrRelayManager subscriptions, cache, and connections for panic mode") } catch (e: Exception) { Log.e(TAG, "Failed to clear NostrRelayManager on panic: ${e.message}") } } - + + /** + * Drop every relay the wiped session added. Geohash-selected relays are chosen by proximity, + * so reconnecting to them would tie the fresh identity to the previous session's locations. + */ + private fun forgetSessionRelays() { + liveGeohashTokens.clear() + liveLocationRelayTokens.clear() + nonLiveRelayUrls.retainAll(DEFAULT_RELAYS.toSet()) + synchronized(relaysList) { + relaysList.clear() + relaysList.addAll(DEFAULT_RELAYS.map { Relay(it) }) + } + updateRelaysList() + updateConnectionStatus() + } + /** * Get detailed status for all relays */ 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 b7f38eb07..317c90fbf 100644 --- a/app/src/main/java/com/bitchat/android/ui/ChatViewModel.kt +++ b/app/src/main/java/com/bitchat/android/ui/ChatViewModel.kt @@ -1513,7 +1513,7 @@ class ChatViewModel( wipeComplete = false } - if (!geohashViewModel.panicReset()) wipeComplete = false + if (!geohashViewModel.panicReset(reconnectRelays = conversationsCleared)) wipeComplete = false } catch (e: Exception) { Log.e(TAG, "Failed to reset Nostr/geohash: ${e.message}") wipeComplete = false 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 48c8b6056..7981a2127 100644 --- a/app/src/main/java/com/bitchat/android/ui/GeohashViewModel.kt +++ b/app/src/main/java/com/bitchat/android/ui/GeohashViewModel.kt @@ -112,7 +112,7 @@ class GeohashViewModel( } /** Returns true only when the persisted Nostr identity was wiped; the rest is in-memory teardown. */ - fun panicReset(): Boolean { + fun panicReset(reconnectRelays: Boolean): Boolean { repo.clearAll() GeohashAliasRegistry.clear() GeohashConversationRegistry.clear() @@ -127,7 +127,7 @@ class GeohashViewModel( false } NostrBackgroundRuntime.resetSubscriptions() - try { com.bitchat.android.nostr.NostrRelayManager.getInstance(getApplication()).clearAllOnPanic() } catch (_: Exception) {} + try { com.bitchat.android.nostr.NostrRelayManager.getInstance(getApplication()).clearAllOnPanic(reconnect = reconnectRelays) } catch (_: Exception) {} try { com.bitchat.android.nostr.LocationNotesManager.getInstance().stop() } catch (_: Exception) {} return identityCleared } diff --git a/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayManagerPanicReconnectRobolectricTest.kt b/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayManagerPanicReconnectRobolectricTest.kt new file mode 100644 index 000000000..6949c93bb --- /dev/null +++ b/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayManagerPanicReconnectRobolectricTest.kt @@ -0,0 +1,172 @@ +package com.bitchat.android.nostr + +import com.bitchat.android.util.AppConstants +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.test.StandardTestDispatcher +import okhttp3.Request +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 +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@OptIn(ExperimentalCoroutinesApi::class) +@RunWith(RobolectricTestRunner::class) +class NostrRelayManagerPanicReconnectRobolectricTest { + private val dispatcher = StandardTestDispatcher() + private val scope = CoroutineScope(dispatcher + SupervisorJob()) + private val factory = FakeWebSocketFactory() + private val manager = NostrRelayManager(webSocketFactory = { factory }, scope = scope) + + @After + fun tearDown() { + scope.cancel() + } + + @Test + fun `panic wipe reconnects default relays on new sockets when connectivity was desired`() { + val oldSockets = connectAndForgetInitialSockets() + + manager.clearAllOnPanic(reconnect = true) + dispatcher.scheduler.runCurrent() + + assertEquals( + NostrRelayManager.defaultRelays().toSet(), + factory.openedSinceReset.map { it.url }.toSet() + ) + assertTrue(oldSockets.all { it.closed }) + } + + @Test + fun `panic wipe does not reconnect relays that only the wiped session used`() { + connectAndForgetInitialSockets() + manager.connectToRelays(listOf(SESSION_RELAY)) + dispatcher.scheduler.runCurrent() + assertEquals(listOf(SESSION_RELAY), factory.openedSinceReset.map { it.url }) + factory.reset() + + manager.clearAllOnPanic(reconnect = true) + dispatcher.scheduler.runCurrent() + + assertFalse(factory.openedSinceReset.any { it.url == SESSION_RELAY }) + assertEquals( + NostrRelayManager.defaultRelays().toSet(), + manager.getRelayStatuses().map { it.url }.toSet() + ) + } + + @Test + fun `panic wipe resumes periodic subscription repair`() { + connectAndForgetInitialSockets() + manager.clearAllOnPanic(reconnect = true) + dispatcher.scheduler.runCurrent() + + // The first delivery is refused, leaving the logical subscription unsent on the socket. + factory.acceptSends = false + manager.subscribe( + filter = NostrFilter(kinds = listOf(NostrKind.TEXT_NOTE)), + id = "post-panic", + handler = {} + ) + dispatcher.scheduler.runCurrent() + assertFalse(anySocketSent("post-panic")) + + factory.acceptSends = true + dispatcher.scheduler.advanceTimeBy( + AppConstants.Nostr.SUBSCRIPTION_VALIDATION_INTERVAL_MS + 1 + ) + dispatcher.scheduler.runCurrent() + + assertTrue(anySocketSent("post-panic")) + } + + @Test + fun `panic wipe keeps relays offline when reconnect is withheld`() { + connectAndForgetInitialSockets() + + manager.clearAllOnPanic(reconnect = false) + dispatcher.scheduler.runCurrent() + // A later relay request must not revive connectivity after a wipe that failed closed. + manager.connectToRelays(listOf(SESSION_RELAY)) + dispatcher.scheduler.runCurrent() + + assertTrue(factory.openedSinceReset.isEmpty()) + } + + @Test + fun `panic wipe leaves a manager that was never connected offline`() { + manager.clearAllOnPanic(reconnect = true) + dispatcher.scheduler.runCurrent() + + assertTrue(factory.openedSinceReset.isEmpty()) + } + + private fun connectAndForgetInitialSockets(): List { + manager.connect() + dispatcher.scheduler.runCurrent() + val initialSockets = factory.openedSinceReset.toList() + assertEquals(NostrRelayManager.defaultRelays().size, initialSockets.size) + factory.reset() + return initialSockets + } + + private fun anySocketSent(subscriptionId: String): Boolean = + factory.openedSinceReset.any { socket -> + socket.sent.any { it.contains("\"$subscriptionId\"") } + } + + private class FakeWebSocketFactory : WebSocket.Factory { + val openedSinceReset = mutableListOf() + + @Volatile + var acceptSends = true + + fun reset() { + openedSinceReset.clear() + } + + override fun newWebSocket(request: Request, listener: WebSocketListener): WebSocket = + FakeWebSocket(request, this).also(openedSinceReset::add) + } + + private class FakeWebSocket( + private val originalRequest: Request, + private val factory: FakeWebSocketFactory + ) : WebSocket { + val url: String = RELAY_URL_PATTERN.replace(originalRequest.url.toString(), "wss://") + .trimEnd('/') + val sent = mutableListOf() + var closed = false + + override fun request(): Request = originalRequest + override fun queueSize(): Long = 0 + override fun send(text: String): Boolean { + if (!factory.acceptSends) return false + sent += text + return true + } + override fun send(bytes: ByteString): Boolean = factory.acceptSends + override fun close(code: Int, reason: String?): Boolean { + closed = true + return true + } + override fun cancel() { + closed = true + } + } + + private companion object { + const val SESSION_RELAY = "wss://session-relay.example" + + // OkHttp canonicalizes ws/wss request URLs to http/https. + val RELAY_URL_PATTERN = Regex("^https://") + } +} From c1b2e1be2a85e22bc9321ef1fd806ad590361222 Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Sun, 8 Nov 2026 02:37:29 -0500 Subject: [PATCH 2/2] Withhold panic reconnect until the identity wipe is confirmed A surviving Nostr key would be loaded and re-subscribed by the post-panic reset, so stay offline unless the identity wipe also committed. Remember the withheld reconnect so a retried wipe that is confirmed still comes back online; disconnect() clears desiredConnected on the failed attempt. --- .../bitchat/android/nostr/NostrRelayManager.kt | 7 +++++-- .../com/bitchat/android/ui/GeohashViewModel.kt | 2 +- ...RelayManagerPanicReconnectRobolectricTest.kt | 17 +++++++++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) 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 12f646144..d42226dee 100644 --- a/app/src/main/java/com/bitchat/android/nostr/NostrRelayManager.kt +++ b/app/src/main/java/com/bitchat/android/nostr/NostrRelayManager.kt @@ -93,6 +93,7 @@ class NostrRelayManager internal constructor( private val connections = ConcurrentHashMap() private val reconnectJobs = ConcurrentHashMap() private val desiredConnected = AtomicBoolean(false) + private val panicReconnectWithheld = AtomicBoolean(false) private val subscriptions = ConcurrentHashMap>() // relay URL -> subscription IDs private val messageHandlers = ConcurrentHashMap Unit>() @@ -737,12 +738,14 @@ class NostrRelayManager internal constructor( */ fun clearAllOnPanic(reconnect: Boolean) { try { - val wasConnected = desiredConnected.get() + val wantedConnected = desiredConnected.get() || panicReconnectWithheld.get() clearAllSubscriptions() clearDeduplicationCache() disconnect() forgetSessionRelays() - if (wasConnected && reconnect) { + // Remembered so a retried wipe that is confirmed can still come back online. + panicReconnectWithheld.set(wantedConnected && !reconnect) + if (wantedConnected && reconnect) { connect() } Log.w(TAG, "🚨 Cleared NostrRelayManager subscriptions, cache, and connections for panic mode") 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 7981a2127..1bec711bb 100644 --- a/app/src/main/java/com/bitchat/android/ui/GeohashViewModel.kt +++ b/app/src/main/java/com/bitchat/android/ui/GeohashViewModel.kt @@ -127,7 +127,7 @@ class GeohashViewModel( false } NostrBackgroundRuntime.resetSubscriptions() - try { com.bitchat.android.nostr.NostrRelayManager.getInstance(getApplication()).clearAllOnPanic(reconnect = reconnectRelays) } catch (_: Exception) {} + try { com.bitchat.android.nostr.NostrRelayManager.getInstance(getApplication()).clearAllOnPanic(reconnect = reconnectRelays && identityCleared) } catch (_: Exception) {} try { com.bitchat.android.nostr.LocationNotesManager.getInstance().stop() } catch (_: Exception) {} return identityCleared } diff --git a/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayManagerPanicReconnectRobolectricTest.kt b/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayManagerPanicReconnectRobolectricTest.kt index 6949c93bb..dc64f6edb 100644 --- a/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayManagerPanicReconnectRobolectricTest.kt +++ b/app/src/test/kotlin/com/bitchat/android/nostr/NostrRelayManagerPanicReconnectRobolectricTest.kt @@ -101,6 +101,23 @@ class NostrRelayManagerPanicReconnectRobolectricTest { assertTrue(factory.openedSinceReset.isEmpty()) } + @Test + fun `confirmed panic retry reconnects after earlier wipes withheld reconnect`() { + connectAndForgetInitialSockets() + manager.clearAllOnPanic(reconnect = false) + manager.clearAllOnPanic(reconnect = false) + dispatcher.scheduler.runCurrent() + assertTrue(factory.openedSinceReset.isEmpty()) + + manager.clearAllOnPanic(reconnect = true) + dispatcher.scheduler.runCurrent() + + assertEquals( + NostrRelayManager.defaultRelays().toSet(), + factory.openedSinceReset.map { it.url }.toSet() + ) + } + @Test fun `panic wipe leaves a manager that was never connected offline`() { manager.clearAllOnPanic(reconnect = true)