diff --git a/src/commonMain/kotlin/fr/acinq/eclair/blockchain/electrum/ElectrumClient.kt b/src/commonMain/kotlin/fr/acinq/eclair/blockchain/electrum/ElectrumClient.kt index 59ab4f8e6..fa3cdb1b0 100644 --- a/src/commonMain/kotlin/fr/acinq/eclair/blockchain/electrum/ElectrumClient.kt +++ b/src/commonMain/kotlin/fr/acinq/eclair/blockchain/electrum/ElectrumClient.kt @@ -29,6 +29,7 @@ internal sealed class ClientEvent internal data class Start(val serverAddress: ServerAddress) : ClientEvent() internal object Connected : ClientEvent() internal object Disconnected : ClientEvent() +internal object Close : ClientEvent() internal data class ReceivedResponse(val response: Either) : ClientEvent() internal data class SendElectrumApiCall(val electrumRequest: ElectrumRequest) : ClientEvent() internal object AskForStatus : ClientEvent() @@ -160,6 +161,10 @@ private fun ClientState.unhandled(event: ClientEvent): Pair newState { + state = ClientClosed + actions = listOf(BroadcastStatus(Connection.CLOSED)) + } AskForStatus, AskForHeader -> returnState() // TODO something else ? else -> { logger.warning { "cannot process event ${event::class} in state ${this::class}" } @@ -228,7 +233,7 @@ class ElectrumClient( is SendResponse -> notificationsChannel.send(action.response) is BroadcastStatus -> _connectionState.value = action.connection StartPing -> pingJob = pingScheduler() - is Shutdown -> closeConnection() + is Shutdown -> disconnect() } } } @@ -240,7 +245,9 @@ class ElectrumClient( } fun disconnect() { - launch { eventChannel.send(Disconnected) } + pingJob?.cancel() + connectionJob?.cancel() ?: launch { eventChannel.send(Close) } + if (this::socket.isInitialized) socket.close() } private var connectionJob: Job? = null @@ -261,12 +268,6 @@ class ElectrumClient( } } - private fun closeConnection() { - pingJob?.cancel() - connectionJob?.cancel() - if (this::socket.isInitialized) socket.close() - } - private suspend fun send(message: ByteArray) { try { socket.send(message) @@ -298,7 +299,7 @@ class ElectrumClient( fun stop() { logger.info { "electrum client stopping" } - closeConnection() + disconnect() // Cancel event consumer runJob?.cancel() // Cancel broadcast channels