Merge pull request #1040 from permissionlesstech/claude/fix-nostr-panic-reconnect-568e3f

Reconnect Nostr relays after panic wipe
This commit is contained in:
callebtc authored and GitHub committed 2026-11-22 18:15:49 +01:00
commit c2db9b2efd
4 files changed
+234 -17

No files matched your search

@@ -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()
@@ -85,6 +93,7 @@ class NostrRelayManager private constructor() {
private val connections = ConcurrentHashMap<String, WebSocket>()
private val reconnectJobs = ConcurrentHashMap<String, Job>()
private val desiredConnected = AtomicBoolean(false)
private val panicReconnectWithheld = AtomicBoolean(false)
private val subscriptions = ConcurrentHashMap<String, Set<String>>() // relay URL -> subscription IDs
private val messageHandlers = ConcurrentHashMap<String, (NostrEvent) -> Unit>()
@@ -117,19 +126,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 +732,44 @@ 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()
val wantedConnected = desiredConnected.get() || panicReconnectWithheld.get()
clearAllSubscriptions()
clearDeduplicationCache()
disconnect()
if (wasConnected) {
desiredConnected.set(true)
forgetSessionRelays()
// 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")
} 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
*/
@@ -1494,7 +1494,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
@@ -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 && identityCleared) } catch (_: Exception) {}
try { com.bitchat.android.nostr.LocationNotesManager.getInstance().stop() } catch (_: Exception) {}
return identityCleared
}
@@ -0,0 +1,189 @@
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 `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)
dispatcher.scheduler.runCurrent()
assertTrue(factory.openedSinceReset.isEmpty())
}
private fun connectAndForgetInitialSockets(): List<FakeWebSocket> {
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<FakeWebSocket>()
@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<String>()
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://")
}
}