diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 969837e7..7cdce1a8 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -377,6 +377,8 @@ Send your contribution to the key Check the combined result and confirm it The group has its key — finish setting it up + The Lightning wallet's key ceremony needs you + The Lightning wallet's key is ready Open Ask again diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt index 5d9e813a..9c8ee7da 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt @@ -42,6 +42,9 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr override suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean = GroupLightningWalletManager.unusedKey(database, chatRoomId, chain) != null + override suspend fun unusedKey(chatRoomId: String, chain: Chain): IcebergKeySession? = + GroupLightningWalletManager.unusedKey(database, chatRoomId, chain) + override suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator? = GroupLightningOperatorManager.current(database, chatRoomId, chain, wallet) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt index d4719acd..ee7b55b4 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt @@ -15,6 +15,7 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.Chain import com.machankura.bennu.compose.wallet.lightning.GroupSweep import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf /** * Reads, opens and approves a group's Lightning wallet: for now, the Iceberg ceremony its key comes @@ -58,6 +59,9 @@ interface GroupLightningRepository { /** Whether the room has a completed Lightning wallet key no wallet uses yet, for a new wallet to open under. */ suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean + /** That key itself, the newest of them, or null: what the chat's standing notice names. */ + suspend fun unusedKey(chatRoomId: String, chain: Chain): IcebergKeySession? + suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator? /** The LSP a Lightning wallet on [chain] opens channels with, or null for a network with none. */ @@ -95,4 +99,42 @@ interface GroupLightningRepository { /** Proposes sweeping [inputs] into the onchain wallet. */ suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession + + companion object { + /** + * For previews and for screens that only read: every flow empty, every read empty or + * null, and every proposal refused, since there is no room behind it to propose in. + */ + val NO_OP_GROUP_LIGHTNING_REPOSITORY: GroupLightningRepository = object : GroupLightningRepository { + override fun observeCeremony(sessionId: String): Flow = flowOf(null) + override fun observeCeremonies(chatRoomId: String): Flow> = flowOf(emptyList()) + override suspend fun ceremonyMessages(sessionId: String): List = emptyList() + override suspend fun pendingApproval(session: IcebergKeySession): IcebergApprovalStep? = null + override suspend fun ceremonyThresholds(chatRoomId: String): List = emptyList() + override suspend fun keyHolderCount(chatRoomId: String): Int = 0 + override suspend fun hasOnchainWallet(chatRoomId: String, chain: Chain): Boolean = false + override suspend fun proposeCeremony(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, threshold: Int, chain: Chain): IcebergKeySession = error("No room to propose in") + override suspend fun approveCeremony(localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray) = Unit + override suspend fun completedCeremony(chatRoomId: String): IcebergKeySession? = null + override suspend fun lightningWallet(chatRoomId: String, chain: Chain): GroupLightningWalletManager.Wallet? = null + override suspend fun earlierWallets(chatRoomId: String, chain: Chain): List = emptyList() + override suspend fun departed(wallet: GroupLightningWalletManager.Wallet): List = emptyList() + override suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean = false + override suspend fun unusedKey(chatRoomId: String, chain: Chain): IcebergKeySession? = null + override suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator? = null + override fun lspNodeId(chain: Chain): HexKey? = null + override suspend fun proposeWallet(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, chain: Chain): FrostSigningSession = error("No room to propose in") + override suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession = error("No room to propose in") + override suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession = error("No room to propose in") + override fun observeReport(chatRoomId: String, chain: Chain, wallet: Long): Flow = flowOf(null) + override fun observePayments(chatRoomId: String, chain: Chain, wallet: Long): Flow> = flowOf(emptyList()) + override suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String = error("No room to ask in") + override fun observeInvoice(chatRoomId: String, chain: Chain, wallet: Long, requestId: String): Flow = flowOf(null) + override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession = error("No room to propose in") + override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession = error("No room to propose in") + override suspend fun proposeCloseAll(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession = error("No room to propose in") + override suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List = emptyList() + override suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession = error("No room to propose in") + } + } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMessagingScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMessagingScreen.kt index 16df3349..f0ad86dd 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMessagingScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomMessagingScreen.kt @@ -1,6 +1,8 @@ package com.machankura.bennu.compose.ui.composable import com.machankura.bennu.compose.ui.composable.navigation.routes.IcebergCeremonyRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningWalletRoute +import com.machankura.bennu.compose.repository.GroupLightningRepository import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box @@ -88,6 +90,7 @@ fun ChatRoomMessagingScreen( chatRepository: ChatRepository, frostSigningRepository: FrostSigningRepository, dkgRepository: DkgRepository, + lightningRepository: GroupLightningRepository, onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, onNavigateToRoute: (Route) -> Unit, /** @@ -133,7 +136,8 @@ fun ChatRoomMessagingScreen( nostrRepository = nostrRepository, chatRepository = chatRepository, frostSigningRepository = frostSigningRepository, - dkgRepository = dkgRepository + dkgRepository = dkgRepository, + lightningRepository = lightningRepository, ) ) @@ -196,6 +200,14 @@ fun ChatRoomMessagingScreen( ) ) }, + onOpenLightningWallet = { + onNavigateToRoute.invoke( + GroupLightningWalletRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + ) + ) + }, onOpenSigning = { sessionId -> onNavigateToRoute.invoke( proposalDestination( @@ -501,6 +513,7 @@ private fun ChatRoomMessagingScreenPreview() { chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, + lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, onNavigateToRouteAndPopUpInclusive = {}, onNavigateToRoute = {}, onNavigateBack = {}, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/HomeScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/HomeScreen.kt index e056d4f8..de6a1458 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/HomeScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/HomeScreen.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.repository.GroupLightningRepository import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -101,6 +102,7 @@ fun HomeScreen( // loses its detail pane on a desktop is a worse failure than a compile error. frostSigningRepository: FrostSigningRepository, dkgRepository: DkgRepository, + lightningRepository: GroupLightningRepository, ) { val sheetState = rememberModalBottomSheetState() val scope = rememberCoroutineScope() @@ -344,6 +346,7 @@ fun HomeScreen( chatRepository = chatRepository, frostSigningRepository = frostSigningRepository, dkgRepository = dkgRepository, + lightningRepository = lightningRepository, // "Replace what is on screen" is a route push // on a phone and a change of selection here. // It fires when a conversation that did not @@ -443,6 +446,7 @@ It has survived not only five centuries, but also the leap into electronic types chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, + lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, ) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt index 25e4bdfd..79287337 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt @@ -1048,6 +1048,7 @@ fun BennuNavHost( chatRepository = databaseChatRepository, frostSigningRepository = databaseFrostSigningRepository, dkgRepository = databaseDkgRepository, + lightningRepository = databaseGroupLightningRepository, ) } composable { @@ -1206,6 +1207,7 @@ fun BennuNavHost( chatRepository = databaseChatRepository, frostSigningRepository = databaseFrostSigningRepository, dkgRepository = databaseDkgRepository, + lightningRepository = databaseGroupLightningRepository, onNavigateToRouteAndPopUpInclusive = { chatRoomDetailRoute -> navController.navigate( route = chatRoomDetailRoute diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt index c946d5ab..1a3674c8 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -27,6 +27,14 @@ import bennu.composeapp.generated.resources.the_subgroups_key_ceremony_needs_you import bennu.composeapp.generated.resources.the_key_ceremony_needs_you import bennu.composeapp.generated.resources.ceremonies_need_you import com.machankura.bennu.compose.database.model.types.DkgApprovalStep +import com.machankura.bennu.compose.database.model.types.IcebergApprovalStep +import androidx.compose.material.icons.filled.Bolt +import bennu.composeapp.generated.resources.the_lightning_wallet_s_key_ceremony_needs_you +import bennu.composeapp.generated.resources.the_lightning_wallet_s_key_is_ready +import bennu.composeapp.generated.resources.join_the_ceremony +import bennu.composeapp.generated.resources.send_your_contributions +import bennu.composeapp.generated.resources.confirm_what_you_saw +import bennu.composeapp.generated.resources.open_a_lightning_wallet import androidx.compose.material.icons.filled.AccessTime import androidx.compose.material.icons.filled.Block import androidx.compose.material.icons.filled.Check @@ -114,6 +122,8 @@ fun ChatTranscript( onOpenSharedKey: (dkgSessionId: String) -> Unit, /** Opens the Lightning wallet key ceremony an [ChatMessage.ICEBERG_TYPES] line is about. */ onOpenIcebergCeremony: (sessionId: String?) -> Unit = {}, + /** Opens the room's Lightning wallet, where a finished key is opened as a wallet. */ + onOpenLightningWallet: () -> Unit, /** * Opens the signing this line is about, by session id -- or the room's * whole list of proposals when the line predates [ChatMessage.frostSigningSessionId] @@ -204,8 +214,19 @@ fun ChatTranscript( item { CeremoniesAwaitingYouNotice( ceremonies = ceremoniesAwaitingYou, - onClick = { dkgSessionId -> - onOpenSharedKey(dkgSessionId) + // Each ceremony has its own screen, and a + // finished Lightning key is opened from the + // wallet's. + onClick = { ceremony -> + when (ceremony.ask) { + is ChatMessageListViewModel.Ask.SharedKeyStep, + is ChatMessageListViewModel.Ask.RoomCreation -> + onOpenSharedKey(ceremony.sessionId) + is ChatMessageListViewModel.Ask.LightningKeyStep -> + onOpenIcebergCeremony(ceremony.sessionId) + ChatMessageListViewModel.Ask.LightningWalletOpening -> + onOpenLightningWallet() + } } ) } @@ -613,12 +634,17 @@ fun ChatTranscript( @Composable private fun CeremoniesAwaitingYouNotice( ceremonies: List, - onClick: (dkgSessionId: String) -> Unit, + onClick: (ChatMessageListViewModel.AwaitingCeremony) -> Unit, ) { val single = ceremonies.singleOrNull() + val isLightning = single?.ask is ChatMessageListViewModel.Ask.LightningKeyStep || + single?.ask == ChatMessageListViewModel.Ask.LightningWalletOpening val headline = when { single == null -> stringResource(Res.string.ceremonies_need_you, ceremonies.size) + single.ask == ChatMessageListViewModel.Ask.LightningWalletOpening -> + stringResource(Res.string.the_lightning_wallet_s_key_is_ready) + isLightning -> stringResource(Res.string.the_lightning_wallet_s_key_ceremony_needs_you) single.isSubgroup -> stringResource(Res.string.the_subgroups_key_ceremony_needs_you) else -> stringResource(Res.string.the_key_ceremony_needs_you) } @@ -626,18 +652,27 @@ private fun CeremoniesAwaitingYouNotice( // What it wants, in the words the approval screens use for the same step, so // a member is not asked twice in two vocabularies. The gate comes first: an // approval is owed by this member and cannot be done by anybody else, while - // finishing the setup is work the coordinator can come back to. + // finishing the setup is work the coordinator can come back to. The Lightning + // wallet's gates are buttons on its ceremony screen, and say what those say. val detail = single?.let { - when (it.step) { - DkgApprovalStep.HOST_KEY -> stringResource(Res.string.join_the_ceremony_by_publishing_your_key) - DkgApprovalStep.ROUND_1 -> stringResource(Res.string.send_your_contribution_to_the_key) - DkgApprovalStep.ROUND_2 -> stringResource(Res.string.check_the_combined_result) - null -> stringResource(Res.string.the_group_has_its_key_finish_setting_it_up) + when (val ask = it.ask) { + is ChatMessageListViewModel.Ask.SharedKeyStep -> when (ask.step) { + DkgApprovalStep.HOST_KEY -> stringResource(Res.string.join_the_ceremony_by_publishing_your_key) + DkgApprovalStep.ROUND_1 -> stringResource(Res.string.send_your_contribution_to_the_key) + DkgApprovalStep.ROUND_2 -> stringResource(Res.string.check_the_combined_result) + } + is ChatMessageListViewModel.Ask.RoomCreation -> stringResource(Res.string.the_group_has_its_key_finish_setting_it_up) + is ChatMessageListViewModel.Ask.LightningKeyStep -> when (ask.step) { + IcebergApprovalStep.JOIN -> stringResource(Res.string.join_the_ceremony) + IcebergApprovalStep.REVEAL -> stringResource(Res.string.send_your_contributions) + IcebergApprovalStep.CONFIRM -> stringResource(Res.string.confirm_what_you_saw) + } + ChatMessageListViewModel.Ask.LightningWalletOpening -> stringResource(Res.string.open_a_lightning_wallet) } } Card( - onClick = { onClick(ceremonies.first().sessionId) }, + onClick = { onClick(ceremonies.first()) }, modifier = Modifier.fillMaxWidth().padding(horizontal = MaterialTheme.spacing.space50), colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.primaryContainer, @@ -649,7 +684,7 @@ private fun CeremoniesAwaitingYouNotice( horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125), verticalAlignment = Alignment.CenterVertically ) { - Icon(Icons.Default.Key, contentDescription = Decorative) + Icon(if (isLightning) Icons.Default.Bolt else Icons.Default.Key, contentDescription = Decorative) Column( modifier = Modifier.weight(1f), diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt index fadac727..e699463e 100755 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt @@ -28,6 +28,14 @@ import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.database.model.types.DkgRitualStage import com.machankura.bennu.compose.database.model.types.DkgApprovalStep import com.machankura.bennu.compose.repository.DkgRepository +import com.machankura.bennu.compose.repository.GroupLightningRepository +import com.machankura.bennu.compose.database.model.types.IcebergApprovalStep +import com.machankura.bennu.compose.database.model.types.IcebergRitualStage +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.database.model.intermdiate.LocalFrostSigningSession +import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent +import com.machankura.bennu.compose.wallet.GroupLightningRollout +import kotlinx.coroutines.flow.combine import com.machankura.bennu.compose.repository.FrostSigningRepository import com.machankura.bennu.compose.repository.NostrRepository import com.machankura.bennu.compose.text.ProposedEvent @@ -47,7 +55,8 @@ class ChatMessageListViewModel( val nostrRepository: NostrRepository, val chatRepository: ChatRepository, val frostSigningRepository: FrostSigningRepository, - val dkgRepository: DkgRepository + val dkgRepository: DkgRepository, + val lightningRepository: GroupLightningRepository, ): ViewModel() { val logger = Logger.withTag(TAG) var chatMessageListUIState: ChatMessageListUIState by mutableStateOf(initialChatMessageListUIState) @@ -108,27 +117,47 @@ class ChatMessageListViewModel( * before this the only way to find one that wanted you was to scroll the * transcript to its request line -- which for a subgroup means scrolling past * whatever else the room has been used for. + * + * Either of the room's two ceremonies: the shared key's, and the Lightning + * wallet's. They open different screens, so [ask] says which this is as well + * as what it wants. docs/group-lightning-transcript.md, Phase 2. */ data class AwaitingCeremony( val sessionId: String, - /** What it wants, or null when what it wants is the next step rather than a signature. */ - val step: DkgApprovalStep?, + val ask: Ask, + + /** Whether this ceremony is making a subgroup, for what the notice says. */ + val isSubgroup: Boolean, + ) + + /** What a ceremony wants of this member. */ + sealed interface Ask { + /** One of the shared key ceremony's approval gates. */ + data class SharedKeyStep(val step: DkgApprovalStep) : Ask /** - * The room this ceremony's key derives, when that room does not exist - * yet and this member is the one who would make it. + * The room the shared key derives, when that room does not exist yet and + * this member is the one who would make it. * * A ceremony reaching COMPLETE finishes nothing on its own: the group has * a key and somebody still has to get its state signed and create the * room. That somebody is whoever opened it, and nothing else in the app * would ever tell them so. */ - val roomAwaitingCreation: String?, + data class RoomCreation(val chatRoomId: String) : Ask - /** Whether this ceremony is making a subgroup, for what the notice says. */ - val isSubgroup: Boolean, - ) + /** One of the Lightning wallet's key ceremony's approval gates. */ + data class LightningKeyStep(val step: IcebergApprovalStep) : Ask + + /** + * The Lightning wallet's key, finished, that no wallet uses yet -- the + * Lightning counterpart to [RoomCreation], and asked of the same person: + * whoever opened the ceremony. A key is not a wallet until the group signs + * a statement for it, and until then nothing can be paid into it. + */ + data object LightningWalletOpening : Ask + } /** * The ceremonies in this room that still want something from this member. @@ -263,33 +292,74 @@ class ChatMessageListViewModel( * A ceremony whose room exists wants nothing from anybody, which is what * `roomAwaitingCreation` is asking. That keeps the notice from becoming * permanent furniture in every room that has ever held a ceremony. + * + * The Lightning wallet's ceremony is read the same way beside it: its gates + * from the same `pendingApproval` its screen reads, and its finished key from + * whether a wallet uses it -- see [lightningWalletAwaitingYou]. */ private fun observeCeremoniesAwaitingYou() { + val roomId = localChatRoom.chatRoom.id viewModelScope.launch(Dispatchers.IO) { - dkgRepository - .observeSessionsForChatRoom(localChatRoom.chatRoom.id) - .collect { sessions -> - ceremoniesAwaitingYou = sessions - .filter { it.stage != DkgRitualStage.FAILED } - .mapNotNull { session -> - val step = dkgRepository.pendingApproval(session) - val roomAwaitingCreation = session + combine( + dkgRepository.observeSessionsForChatRoom(roomId), + lightningRepository.observeCeremonies(roomId), + // Only for whether a wallet statement is already being signed: + // once it is, the key has been put to the group and asking its + // opener to open it again would start a second proposal. + frostSigningRepository.observeSessionsForChatRoom(roomId), + ::Triple, + ).collect { (sessions, lightningCeremonies, signings) -> + val sharedKey = sessions + .filter { it.stage != DkgRitualStage.FAILED } + .mapNotNull { session -> + val ask = dkgRepository.pendingApproval(session)?.let { Ask.SharedKeyStep(it) } + ?: session .takeIf { it.coordinatorPublicKey == it.userPublicKey } ?.let { dkgRepository.roomAwaitingCreation(it) } + ?.let { Ask.RoomCreation(it) } + ?: return@mapNotNull null - if (step == null && roomAwaitingCreation == null) return@mapNotNull null + AwaitingCeremony( + sessionId = session.id, + ask = ask, + isSubgroup = session.parentChatRoomId != null, + ) + } - AwaitingCeremony( - sessionId = session.id, - step = step, - roomAwaitingCreation = roomAwaitingCreation, - isSubgroup = session.parentChatRoomId != null, - ) + val lightningKey = lightningCeremonies + .filter { it.stage != IcebergRitualStage.FAILED } + .mapNotNull { session -> + lightningRepository.pendingApproval(session)?.let { + AwaitingCeremony(session.id, Ask.LightningKeyStep(it), isSubgroup = false) } - } + } + + ceremoniesAwaitingYou = sharedKey + lightningKey + listOfNotNull(lightningWalletAwaitingYou(signings)) + } } } + /** + * The finished Lightning wallet key this member opened the ceremony for, while no + * wallet uses it and no statement for it is being signed; null otherwise, and + * always on a build that does not offer the wallet. + */ + private suspend fun lightningWalletAwaitingYou(signings: List): AwaitingCeremony? { + if (!GroupLightningRollout.ENABLED) return null + val key = lightningRepository.unusedKey(localChatRoom.chatRoom.id, GroupLightningRollout.NETWORK) + ?.takeIf { it.coordinatorPublicKey.equals(it.userPublicKey, ignoreCase = true) } + ?: return null + + val beingSigned = signings + .filter { it.session.stage != FrostSigningStage.FAILED } + .flatMap { it.items } + .mapNotNull { Event.fromJsonOrNull(it.unsignedEventJson) } + .filter { it.kind == GroupLightningWalletStatementEvent.KIND } + .any { GroupLightningWalletStatementEvent.read(it.tags)?.ceremonyId == key.id } + + return if (beingSigned) null else AwaitingCeremony(key.id, Ask.LightningWalletOpening, isSubgroup = false) + } + /** * Ask the group for its signed record, if this device holds none of it. * @@ -477,7 +547,8 @@ class ChatMessageListViewModel( nostrRepository: NostrRepository, chatRepository: ChatRepository, frostSigningRepository: FrostSigningRepository, - dkgRepository: DkgRepository + dkgRepository: DkgRepository, + lightningRepository: GroupLightningRepository, ): ViewModelProvider.Factory = viewModelFactory { initializer { ChatMessageListViewModel( @@ -486,7 +557,8 @@ class ChatMessageListViewModel( nostrRepository = nostrRepository, chatRepository = chatRepository, frostSigningRepository = frostSigningRepository, - dkgRepository = dkgRepository + dkgRepository = dkgRepository, + lightningRepository = lightningRepository, ) } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatPaneLayoutJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatPaneLayoutJvmTest.kt index 901e99b0..22798713 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatPaneLayoutJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatPaneLayoutJvmTest.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.repository.GroupLightningRepository import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertWidthIsEqualTo @@ -98,6 +99,7 @@ class ChatPaneLayoutJvmTest { chatRepository = NoRooms, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, + lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, ) } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatPaneSelectionJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatPaneSelectionJvmTest.kt index e5172f12..29cdb7be 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatPaneSelectionJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ChatPaneSelectionJvmTest.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.repository.GroupLightningRepository import androidx.compose.runtime.Composable import androidx.compose.ui.test.ComposeUiTest import androidx.compose.ui.test.ExperimentalTestApi @@ -132,6 +133,7 @@ class ChatPaneSelectionJvmTest { chatRepository = TwoRooms, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, + lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, ) } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/NavigateBackButtonJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/NavigateBackButtonJvmTest.kt index 5f3ae814..278835cf 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/NavigateBackButtonJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/NavigateBackButtonJvmTest.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.repository.GroupLightningRepository import androidx.compose.runtime.Composable import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assertIsDisplayed @@ -92,6 +93,7 @@ class NavigateBackButtonJvmTest { chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, + lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, onNavigateToRouteAndPopUpInclusive = {}, onNavigateToRoute = {}, onNavigateBack = onNavigateBack, diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt index b8b2313d..48178443 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/ReadOnlyEntrancesJvmTest.kt @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.ui.composable +import com.machankura.bennu.compose.repository.GroupLightningRepository import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.test.ExperimentalTestApi @@ -282,6 +283,7 @@ class ReadOnlyEntrancesJvmTest { chatRepository = NoRooms, frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY, dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, + lightningRepository = GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY, ) } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt index 79bcf937..89dd4a8c 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt @@ -130,6 +130,7 @@ class GroupLightningWalletViewModelJvmTest { override suspend fun earlierWallets(chatRoomId: String, chain: Chain): List = earlier override suspend fun departed(wallet: GroupLightningWalletManager.Wallet): List = departedMembers override suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean = unusedKey + override suspend fun unusedKey(chatRoomId: String, chain: Chain): IcebergKeySession? = completed?.takeIf { unusedKey } override suspend fun proposeCloseAll(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession = error("unused") override suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List = report?.snapshot?.heldOutputs.orEmpty() override suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession = error("unused") diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/LightningCeremonyAwaitingYouJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/LightningCeremonyAwaitingYouJvmTest.kt new file mode 100644 index 00000000..acb00759 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/LightningCeremonyAwaitingYouJvmTest.kt @@ -0,0 +1,171 @@ +package com.machankura.bennu.compose.ui.view.model + +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.FrostSigningItem +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.IcebergKeySession +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.intermdiate.LocalFrostSigningSession +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.database.model.types.IcebergApprovalStep +import com.machankura.bennu.compose.database.model.types.IcebergRitualStage +import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.DkgRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.repository.GroupLightningRepository +import com.machankura.bennu.compose.repository.NostrRepository +import com.machankura.bennu.compose.ui.view.state.ChatMessageListUIState +import com.machankura.bennu.compose.wallet.GroupLightningRollout +import fr.acinq.bitcoin.Chain +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeoutOrNull +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The Lightning wallet's key ceremony, in the notice above the composer + * (docs/group-lightning-transcript.md, Phase 2): asked of the member at each of its + * gates, and of the member who opened it once the key is made and no wallet uses it. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class LightningCeremonyAwaitingYouJvmTest { + @BeforeTest + fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterTest + fun tearDown() = Dispatchers.resetMain() + + private val chatRoomId = "d4c3b2a1".repeat(8) + private val me = "a".repeat(64) + private val them = "b".repeat(64) + private val localChatRoom = LocalChatRoom(chatRoom = ChatRoom(id = chatRoomId, userPublicKey = me, subject = "Treasury", description = null, mlsGroupState = "state")) + + private fun ceremony( + stage: IcebergRitualStage, + coordinator: String = them, + id: String = "ab".repeat(32), + ) = IcebergKeySession( + id = id, chatRoomId = chatRoomId, coordinatorPublicKey = coordinator, userPublicKey = me, threshold = 2, participantCount = 4, + participantPublicKeys = IcebergKeySession.formatParticipants(listOf(me, them, "c".repeat(64), "d".repeat(64))), + onchainDkgSessionId = "x", stage = stage, + share = if (stage == IcebergRitualStage.COMPLETE) "00" else null, + ) + + private class Lightning( + val ceremonies: List, + val gate: IcebergApprovalStep? = null, + val unused: IcebergKeySession? = null, + ) : GroupLightningRepository by GroupLightningRepository.NO_OP_GROUP_LIGHTNING_REPOSITORY { + override fun observeCeremonies(chatRoomId: String): Flow> = flowOf(ceremonies) + override suspend fun pendingApproval(session: IcebergKeySession): IcebergApprovalStep? = + gate.takeIf { session.stage != IcebergRitualStage.COMPLETE } + override suspend fun unusedKey(chatRoomId: String, chain: Chain): IcebergKeySession? = unused + } + + private class Signings(val sessions: List) : + FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { + override fun observeSessionsForChatRoom(chatRoomId: String): Flow> = flowOf(sessions) + } + + /** A signing session proposing a wallet statement over [ceremonyId]. */ + private fun statementBeingSigned(ceremonyId: String): LocalFrostSigningSession { + val statement = GroupLightningWalletStatementEvent.Statement( + GroupLightningRollout.NETWORK, 0, 0, "02" + "11".repeat(32), ceremonyId, 2, + listOf(me, them), "02" + "33".repeat(32), "02" + "44".repeat(32), GroupLightningWalletStatementEvent.Policy.DEFAULT, + ) + val template = GroupLightningWalletStatementEvent.template(statement, createdAt = 1) + val tags = template.tags.joinToString(",", "[", "]") { tag -> tag.joinToString(",", "[", "]") { "\"$it\"" } } + return LocalFrostSigningSession( + session = FrostSigningSession( + id = "s1", chatRoomId = chatRoomId, coordinatorPublicKey = them, userPublicKey = me, dkgSessionId = "x", + threshold = 2, participantCount = 4, signerId = 1, stage = FrostSigningStage.COLLECTING_NONCES, + ), + unorderedItems = listOf( + FrostSigningItem( + sessionId = "s1", itemIndex = 0, eventId = "e".repeat(64), nonceRandom = "00".repeat(32), + unsignedEventJson = """{"id":"${"e".repeat(64)}","pubkey":"$chatRoomId","created_at":1,""" + + """"kind":${GroupLightningWalletStatementEvent.KIND},"tags":$tags,"content":"","sig":""}""", + ), + ), + ) + } + + private fun awaiting( + lightning: GroupLightningRepository, + signings: List = emptyList(), + expectNone: Boolean = false, + ): List { + val viewModel = ChatMessageListViewModel( + initialChatMessageListUIState = ChatMessageListUIState.Loading, + localChatRoom = localChatRoom, + nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, + chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, + frostSigningRepository = Signings(signings), + dkgRepository = DkgRepository.NO_OP_DKG_REPOSITORY, + lightningRepository = lightning, + ) + viewModel.initiate() + return runBlocking { + // Settles on the IO dispatcher. Nothing to wait for when the answer is none, + // so a short wait that finds nothing is the pass. + withTimeoutOrNull(if (expectNone) 500 else 5_000) { + while (viewModel.ceremoniesAwaitingYou.isEmpty()) delay(10) + } + viewModel.ceremoniesAwaitingYou + } + } + + @Test + fun `each of the ceremony's gates is asked of the member above the composer`() { + IcebergApprovalStep.entries.forEach { step -> + val running = ceremony(IcebergRitualStage.COLLECTING_REVEALS) + val asked = awaiting(Lightning(listOf(running), gate = step)).single() + + assertEquals(running.id, asked.sessionId) + assertEquals(ChatMessageListViewModel.Ask.LightningKeyStep(step), asked.ask) + assertEquals(false, asked.isSubgroup) + } + } + + @Test + fun `a ceremony waiting on others, or abandoned, asks nothing`() { + assertTrue(awaiting(Lightning(listOf(ceremony(IcebergRitualStage.COLLECTING_COMMITMENTS))), expectNone = true).isEmpty()) + assertTrue(awaiting(Lightning(listOf(ceremony(IcebergRitualStage.FAILED)), gate = IcebergApprovalStep.JOIN), expectNone = true).isEmpty()) + } + + @Test + fun `a finished key no wallet uses is asked of whoever opened the ceremony`() { + val mine = ceremony(IcebergRitualStage.COMPLETE, coordinator = me) + val asked = awaiting(Lightning(listOf(mine), unused = mine)).single() + + assertEquals(mine.id, asked.sessionId) + assertEquals(ChatMessageListViewModel.Ask.LightningWalletOpening, asked.ask) + } + + @Test + fun `and of nobody else`() { + val theirs = ceremony(IcebergRitualStage.COMPLETE, coordinator = them) + assertTrue(awaiting(Lightning(listOf(theirs), unused = theirs), expectNone = true).isEmpty()) + } + + @Test + fun `nor once a wallet statement for it is being signed`() { + val mine = ceremony(IcebergRitualStage.COMPLETE, coordinator = me) + assertTrue( + awaiting(Lightning(listOf(mine), unused = mine), signings = listOf(statementBeingSigned(mine.id)), expectNone = true).isEmpty(), + "the key has been put to the group; asking again would start a second proposal", + ) + } +}