diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 17414def..947431cd 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -458,4 +458,7 @@ Nothing has been published from this device yet. Declining leaves the ceremony for the others to abandon or wait on, and you can join later from the shared key screen. Once everyone has joined, each member's device commits to its part of the key. Nobody is asked. Each member's device checks the combined result against what it sent, and confirms it if they match. + The ceremony has stalled + Waiting on %1$s since %2$s. + If they have stopped answering, any member can abandon the ceremony. No key is made, and the group can start again. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt index 134cf43a..0bc80d03 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt @@ -664,16 +664,22 @@ object ChillDkgRitualManager { val known = database.dkgSessionDao() .getMessage(session.id, innerEvent.kind, innerEvent.pubKey) != null - database.dkgSessionDao().upsert( - DkgParticipantMessage( - sessionId = session.id, - participantPublicKey = innerEvent.pubKey, - kind = innerEvent.kind, - payload = innerEvent.content - ) - ) - + // Written once, on first arrival. Its `createdAt` is when this + // device first heard from that member at that step, and the ritual + // screen dates a stall from the newest of them -- rewriting the row + // on every redelivery would restart that clock each time a relay + // repeated itself. A member's message for a step is the same bytes + // every time it is sent, so keeping the first loses nothing. if (!known) { + database.dkgSessionDao().upsert( + DkgParticipantMessage( + sessionId = session.id, + participantPublicKey = innerEvent.pubKey, + kind = innerEvent.kind, + payload = innerEvent.content + ) + ) + announceStep(database, session, innerEvent.kind, innerEvent.pubKey) } } @@ -1448,16 +1454,20 @@ object ChillDkgRitualManager { // fall back on, so the check that matters lives next to the write. val known = ownMessage(database, session, kind) != null - database.dkgSessionDao().upsert( - DkgParticipantMessage( - sessionId = session.id, - participantPublicKey = session.userPublicKey, - kind = kind, - payload = content + // Once, as [record] does and for the same reason: the row's time is when + // this step first went out. + if (!known) { + database.dkgSessionDao().upsert( + DkgParticipantMessage( + sessionId = session.id, + participantPublicKey = session.userPublicKey, + kind = kind, + payload = content + ) ) - ) - if (!known) announceStep(database, session, kind, session.userPublicKey) + announceStep(database, session, kind, session.userPublicKey) + } } /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgRitualScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgRitualScreen.kt index 545f92ca..53bc9375 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgRitualScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/DkgRitualScreen.kt @@ -19,6 +19,15 @@ import androidx.compose.material.icons.filled.Groups import androidx.compose.material.icons.filled.ErrorOutline import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.RadioButtonUnchecked +import androidx.compose.material.icons.filled.HourglassEmpty +import androidx.compose.runtime.produceState +import kotlinx.coroutines.delay +import kotlin.time.Clock +import kotlin.time.Instant +import mobi.giza.compose.extensions.toFormattedTimeAndDateString +import mobi.giza.compose.resources.the_ceremony_has_stalled +import mobi.giza.compose.resources.waiting_on_s_since_s +import mobi.giza.compose.resources.if_they_have_stopped_answering_any_member_can_abandon import androidx.compose.material3.BottomAppBar import androidx.compose.material3.Button import androidx.compose.material3.Card @@ -264,6 +273,27 @@ fun DkgRitualScreen( .padding(MaterialTheme.spacing.space125), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125) ) { + // Re-read once a minute, so a screen left open notices the + // day go by rather than waiting for a message that, being + // stalled, is not coming. + val now by produceState(Clock.System.now()) { + while (true) { + delay(60_000) + value = Clock.System.now() + } + } + + dkgRitualUIState.stalledSince(now)?.let { since -> + StalledCeremonyCard( + waitingOn = dkgRitualUIState.waitingOn + .sorted() + .map { it.memberName(dkgRitualUIState.ritualMembers, activeUserPublicKey) }, + since = since, + isActionPending = isActionPending, + onAbandon = { isConfirmingAbandon = true }, + ) + } + RitualProgress( session = session, participantCount = participantCount, @@ -372,6 +402,72 @@ internal fun retryRoute(activeUserPublicKey: HexKey, chatRoomId: String, session ?: CreateSharedKeyRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId) /** The ladder, and the members it is climbing. */ +/** + * Says a ceremony has stopped moving, on whom, and that abandoning it is how it + * ends. + * + * Once everyone has joined the rounds run themselves, so a ceremony that sits + * still is waiting on a device that is not answering -- a member who never + * joined, or one whose phone has not been opened since. Nothing on this device + * can make that member answer. What it can do is put the way out beside the + * name, rather than leave it at the foot of the screen for a member to wonder + * whether it is too soon to use. The button opens the same confirmation the + * other one does. + */ +@Composable +private fun StalledCeremonyCard( + waitingOn: List, + since: Instant, + isActionPending: Boolean, + onAbandon: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.tertiaryContainer, + contentColor = MaterialTheme.colorScheme.onTertiaryContainer + ) + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.space200), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + Row( + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space125), + verticalAlignment = Alignment.CenterVertically + ) { + Icon(Icons.Default.HourglassEmpty, contentDescription = Decorative) + Text( + text = stringResource(Res.string.the_ceremony_has_stalled), + style = MaterialTheme.typography.titleSmall + ) + } + + Text( + text = stringResource( + Res.string.waiting_on_s_since_s, + waitingOn.joinToString(", "), + since.toFormattedTimeAndDateString() + ), + style = MaterialTheme.typography.bodyMedium + ) + + Text( + text = stringResource(Res.string.if_they_have_stopped_answering_any_member_can_abandon), + style = MaterialTheme.typography.bodyMedium + ) + + TextButton( + onClick = onAbandon, + enabled = !isActionPending, + modifier = Modifier.align(Alignment.End), + ) { + Text(stringResource(Res.string.abandon_ceremony)) + } + } + } +} + @Composable private fun RitualProgress( session: DkgSession, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt index 44d5094c..a003cfb0 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt @@ -49,6 +49,7 @@ import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.intermdiate.LocalFrostSigningSession import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch +import kotlin.time.Instant /** * Watches one ChillDKG ritual, and the steps that follow it. @@ -183,9 +184,7 @@ class DkgRitualViewModel( round1Participants = ceremony.round1Participants, round2Participants = ceremony.round2Participants, // Computed here, before the one write, rather than read and - // written around a suspension: whether round 1 can be asked - // for depends on how many host keys have arrived, which only - // the messages flow sees. + // written around a suspension. pendingApproval = dkgRepository.pendingApproval(session), adminGroupBlockedOn = snapshot.adminGroupBlockedOn, keyStateSession = snapshot.keyStateSession, @@ -193,6 +192,7 @@ class DkgRitualViewModel( parentChatRoomId = session.parentChatRoomId, isCertified = ceremony.isCertified, certificateSession = ceremony.certificateSession, + lastProgressAt = ceremony.lastProgressAt, ) } } @@ -257,6 +257,9 @@ class DkgRitualViewModel( isKeyStateSigned = isKeyStateSigned, isCertified = isCertified, certificateSession = certificate, + // Each row is dated by its first arrival, so the newest is when + // the ceremony last moved on this device. + lastProgressAt = messages.maxOfOrNull { it.createdAt }, ) } } @@ -286,6 +289,7 @@ class DkgRitualViewModel( val isKeyStateSigned: Boolean = false, val isCertified: Boolean = false, val certificateSession: FrostSigningSession? = null, + val lastProgressAt: Instant? = null, ) private data class Snapshot( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/DkgRitualUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/DkgRitualUIState.kt index c3f5c6b4..0bdb09ff 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/DkgRitualUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/DkgRitualUIState.kt @@ -10,6 +10,9 @@ import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.database.model.types.DkgRitualStage import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.managers.ChillDkgRitualManager +import kotlin.time.Duration +import kotlin.time.Duration.Companion.days +import kotlin.time.Instant sealed interface DkgRitualUIState { data class Loaded( @@ -79,6 +82,12 @@ sealed interface DkgRitualUIState { val parentChatRoomId: HexKey? = null, /** Whether the parent has certified the room this ceremony's key derives. */ val isCertified: Boolean = false, + /** + * When this device last heard anything of the ceremony: the newest of its + * stored messages, each dated by its first arrival. Null before any. + * What [stalledSince] dates a stall from. + */ + val lastProgressAt: Instant? = null, /** * The session asking the parent to certify, while it is running. * @@ -141,6 +150,61 @@ sealed interface DkgRitualUIState { session.stage != DkgRitualStage.FAILED && session.userPublicKey in ChillDkgRitualManager.participantsOf(session, localChatRoom) + /** + * Who the ceremony is waiting on, as far as this device can tell. + * + * Once a member has joined nobody is asked anything, so a ceremony that is + * not moving is waiting on somebody's device: a member who has not joined, + * or one whose device has not been opened since the step before. Those + * missing from the step this device is at -- or, once everyone has sent + * theirs, the coordinator, whose device combines them. + */ + val waitingOn: Set + get() { + val participants = ChillDkgRitualManager.participantsOf(session, localChatRoom) + + fun missingOr(coordinatorStep: Boolean, sent: Set): Set { + val missing = participants - sent + return when { + missing.isNotEmpty() -> missing + coordinatorStep -> setOf(session.coordinatorPublicKey) + else -> emptySet() + } + } + + return when (session.stage) { + DkgRitualStage.COLLECTING_HOST_KEYS -> participants - hostKeyParticipants + DkgRitualStage.COLLECTING_ROUND_1 -> + missingOr(session.coordinatorRound1 == null, round1Participants) + DkgRitualStage.COLLECTING_ROUND_2 -> + missingOr(session.certificate == null, round2Participants) + DkgRitualStage.COMPLETE, DkgRitualStage.FAILED -> emptySet() + } + } + + /** + * When the ceremony stopped moving, if it has been still for at least + * [STALL_AFTER] by [now] and this member can do something about it -- or + * null if it is moving, finished, or not theirs to end. + * + * Abandoning is the way out of a stall, because the rounds run themselves + * and the only thing a running ceremony can wait on is a device that is not + * answering. This is what tells the screen to say so beside the person it is + * waiting on. It never abandons anything itself: whether a day is too long + * is the group's call. + */ + fun stalledSince(now: Instant): Instant? { + if (!canAbandon) return null + + val since = lastProgressAt ?: session.createdAt + return since.takeIf { now - it >= STALL_AFTER && waitingOn.isNotEmpty() } + } + + companion object { + /** How long a ceremony sits still before the screen calls it stalled. */ + val STALL_AFTER: Duration = 1.days + } + /** * The `n` of the t-of-n, as the session has it, because that is the count * every device agreed to run the ritual on. diff --git a/composeApp/src/commonTest/kotlin/mobi/giza/compose/ui/view/state/DkgRitualStallTest.kt b/composeApp/src/commonTest/kotlin/mobi/giza/compose/ui/view/state/DkgRitualStallTest.kt new file mode 100644 index 00000000..cebde019 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/mobi/giza/compose/ui/view/state/DkgRitualStallTest.kt @@ -0,0 +1,136 @@ +package mobi.giza.compose.ui.view.state + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.time.Duration.Companion.hours +import kotlin.time.Instant +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage + +/** + * When the ritual screen calls a ceremony stalled, and who it says it is waiting on. + * + * Once everyone has joined nobody is asked anything, so the only thing a running + * ceremony can wait on is a device that is not answering, and abandoning is how + * that ends. These are the rules for putting that beside the name. + */ +class DkgRitualStallTest { + + private val ada = "a".repeat(64) + private val bob = "b".repeat(64) + private val cal = "c".repeat(64) + + private val started = Instant.fromEpochSeconds(1_800_000_000) + + private fun loaded( + stage: DkgRitualStage = DkgRitualStage.COLLECTING_HOST_KEYS, + user: String = ada, + hostKeys: Set = emptySet(), + round1: Set = emptySet(), + round2: Set = emptySet(), + coordinatorRound1: String? = null, + lastProgressAt: Instant? = null, + ) = DkgRitualUIState.Loaded( + localChatRoom = LocalChatRoom( + chatRoom = ChatRoom( + id = "room", + userPublicKey = user, + subject = "Checkers", + description = null, + mlsGroupState = null, + ) + ), + session = DkgSession( + id = "ceremony", + chatRoomId = "room", + coordinatorPublicKey = ada, + userPublicKey = user, + threshold = 2, + participantCount = 3, + participantPublicKeys = DkgSession.formatParticipants(setOf(ada, bob, cal)), + stage = stage, + hostPublicKey = "02".repeat(33), + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + coordinatorRound1 = coordinatorRound1, + createdAt = started, + ), + hostKeyParticipants = hostKeys, + round1Participants = round1, + round2Participants = round2, + lastProgressAt = lastProgressAt, + ) + + @Test + fun `a ceremony still for less than a day is not stalled`() { + val state = loaded(hostKeys = setOf(ada), lastProgressAt = started) + + assertNull(state.stalledSince(started + 23.hours)) + } + + @Test + fun `a ceremony still for a day is stalled since it last moved`() { + val moved = started + 2.hours + val state = loaded(hostKeys = setOf(ada, bob), lastProgressAt = moved) + + assertEquals(moved, state.stalledSince(moved + 24.hours)) + assertEquals(setOf(cal), state.waitingOn, "on the member who has not joined") + } + + @Test + fun `a ceremony that has heard nothing dates from when it was recorded`() { + val state = loaded() + + assertEquals(started, state.stalledSince(started + 30.hours)) + } + + /** Only a participant can abandon, so only a participant is told to. */ + @Test + fun `a member who is not in it is not told it has stalled`() { + val state = loaded(user = "d".repeat(64), lastProgressAt = started) + + assertNull(state.stalledSince(started + 48.hours)) + } + + @Test + fun `a finished or failed ceremony has not stalled`() { + listOf(DkgRitualStage.COMPLETE, DkgRitualStage.FAILED).forEach { stage -> + assertNull(loaded(stage = stage, lastProgressAt = started).stalledSince(started + 48.hours), "$stage") + } + } + + /** + * With every contribution in, nobody is missing from the round, and the device + * that has to act is the coordinator's, which combines them. + */ + @Test + fun `with every contribution in it is waiting on the coordinator`() { + val everyone = setOf(ada, bob, cal) + val state = loaded( + stage = DkgRitualStage.COLLECTING_ROUND_1, + user = bob, + hostKeys = everyone, + round1 = everyone, + lastProgressAt = started, + ) + + assertEquals(setOf(ada), state.waitingOn) + } + + @Test + fun `mid-round it is waiting on whoever has not sent theirs`() { + val everyone = setOf(ada, bob, cal) + val state = loaded( + stage = DkgRitualStage.COLLECTING_ROUND_2, + hostKeys = everyone, + round1 = everyone, + round2 = setOf(ada), + coordinatorRound1 = "00", + ) + + assertEquals(setOf(bob, cal), state.waitingOn) + } +} diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyAcrossDevicesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyAcrossDevicesJvmTest.kt index b8ce5d7a..e5e7100e 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyAcrossDevicesJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyAcrossDevicesJvmTest.kt @@ -141,6 +141,39 @@ class CeremonyAcrossDevicesJvmTest { } } + /** + * A message is dated by when it first arrived. The ritual screen dates a stall + * from the newest of them, and a relay repeating itself is not the ceremony + * moving. + */ + @Test + fun `a redelivered message keeps the time it first arrived`(): Unit = runBlocking { + CeremonyNetwork.nip17(size = 3).use { network -> + val member = network.devices[1] + val session = network.propose(threshold = 2) + network.deliverUntilQuiet() + + fun stored() = runBlocking { + assertNotNull( + member.db.dkgSessionDao() + .getMessage(session.id, DkgRitualEvents.HOST_KEY, network.coordinator.publicKey) + ) + } + val first = stored().createdAt + + kotlinx.coroutines.delay(20) + ChillDkgRitualManager.processRitualPayload( + database = member.db, + localChatRoom = network.room(member), + innerEvent = network.sent(network.coordinator, DkgRitualEvents.HOST_KEY).single(), + userPublicKey = member.publicKey, + nostrPrivateKey = member.privateKey, + ) + + assertEquals(first, stored().createdAt) + } + } + /** A round approval from a screen left open across the upgrade publishes nothing. */ @Test fun `approving a round does nothing`(): Unit = runBlocking {