From 11f2cb2babe110f3ff0182ad721c43e1d5bd5965 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:12:23 +0200 Subject: [PATCH] feat: the Shares section, with one approval (rotate-shares-single-approval, Phase 6) Removing the second approval took away the only abandon button a member who had taken part could reach: it lived on the approval row. A running rotation is now a card above the members -- the step it is on (dealing, storing, the group signing the new key state), who it waits on and since when, and Abandon, behind a confirmation, for any member taking part. It counts as running until the new generation's key state is signed, while that signature is open, because the old shares wait on it. A rotation that ended without completing says why until the next one. The taking-part row now says what it decides: who is left out and as what, and that nothing more will be asked. REFRESH_CONFIRM and its string are gone from the UI state. ShareRefreshManager.progress reads the step and who is missing from stored messages. Those are now stored once, on first arrival, in record and publishOwn: a redelivery rewrote the row and reset the stall clock. Tests: the row names the withheld; the withheld member sees the rotation run and cannot abandon it; the waiting-on names at dealing and storing; the signing step, which nobody abandons; an abandoned rotation says why. The stall-clock test backdates the messages first, and fails with the old store-every-time behaviour put back. jvmTest 1250/1250; m3Audit at its budgets; brand and wallet audits. Not seen on a device. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 15 +- .../compose/database/dao/ShareRefreshDao.kt | 3 + .../repository/DatabaseChatRepository.kt | 76 +++++++++- .../compose/managers/ShareRefreshManager.kt | 51 ++++++- .../ui/composable/ChatRoomDetailScreen.kt | 142 +++++++++++++++++- .../compose/ui/view/state/SharesSummary.kt | 36 ++++- .../managers/ShareRefreshRitualJvmTest.kt | 117 +++++++++++++++ 7 files changed, 421 insertions(+), 19 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index d1cf168a..b6c68bbc 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -131,7 +131,20 @@ Ask to be brought back Approve Take part in rotating the shares - Store your new share + Every member takes part. + Without %1$s. + %1$s until they are brought back + %1$s for good + Your device then sends its part, stores your new share and signs the group\'s new key state without asking again. + Rotating the shares + Members are sending their parts of the new shares. + Members are storing their new shares. + The group is signing its new key state. The old shares are deleted once it has. + If someone has stopped answering, any member taking part can abandon the rotation. Every share stays as it was, and the group can start again. + Abandon rotation + Abandon this rotation? + It ends for every member. Nobody gets a new share, and the group keeps signing with the shares it has. + The last rotation ended: %1$s Help bring a member back Sent to the group Share rotation proposed; every remaining member is asked to take part diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt index d699c000..bb4d1fee 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt @@ -44,6 +44,9 @@ abstract class ShareRefreshDao { @Upsert abstract suspend fun upsert(message: ShareRefreshMessage) + @Query("SELECT * FROM ShareRefreshMessage WHERE sessionId = :sessionId") + abstract suspend fun getMessagesForSession(sessionId: String): List + @Query("SELECT * FROM ShareRefreshMessage WHERE sessionId = :sessionId AND kind = :kind") abstract suspend fun getMessagesByKind(sessionId: String, kind: Kind): List diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 0c99990f..cf1e27a4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -1,5 +1,8 @@ package mobi.giza.compose.database.repository +import mobi.giza.compose.database.model.ShareRefreshSession +import mobi.giza.compose.nostr.frost.GroupKeyStateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -667,30 +670,89 @@ class DatabaseChatRepository( val shares = ShareGenerations.active(database, key) if (shares.roster.isEmpty()) return null val names = localChatRoom.localParticipants.associate { it.participant.participantPublicKey to it.profile?.humanReadableNameOrPubkey() } + fun nameOf(member: HexKey) = names[member] ?: member.take(8) val refreshes = database.shareRefreshDao().getSessionsForKey(key.id) val repairs = database.shareRepairDao().getSessionsForKey(key.id) val pending = refreshes.mapNotNull { session -> when (ShareRefreshManager.pendingApproval(database, session)) { - ShareRefreshApprovalStep.DEAL -> SharesSummary.PendingApproval(session.id, SharesSummary.PendingApproval.Kind.REFRESH_DEAL) - ShareRefreshApprovalStep.CONFIRM -> SharesSummary.PendingApproval(session.id, SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM) - null -> null + ShareRefreshApprovalStep.DEAL -> { + val roster = ShareGenerations.at(database, key, session.baseGeneration)?.roster.orEmpty() + .associate { it.participantId to it.memberPublicKey } + SharesSummary.PendingApproval( + sessionId = session.id, + kind = SharesSummary.PendingApproval.Kind.REFRESH_DEAL, + withheld = session.withheldStandings().map { (id, standing) -> + SharesSummary.Withheld(roster[id]?.let(::nameOf) ?: id.toString(), standing) + }, + ) + } + // Never pending since docs/rotate-shares-single-approval.md. + ShareRefreshApprovalStep.CONFIRM, null -> null } } + repairs.filter { ShareRepairManager.isAwaitingApproval(database, it) } .map { SharesSummary.PendingApproval(it.id, SharesSummary.PendingApproval.Kind.REPAIR_HELP) } - val running = refreshes.any { it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED } + val runningRefresh = refreshes.firstOrNull { it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED } + val running = runningRefresh?.let { session -> + // The approval row covers a member not yet asked; this is everything after it. + if (ShareRefreshManager.pendingApproval(database, session) != null) return@let null + ShareRefreshManager.progress(database, session)?.let { progress -> + SharesSummary.Running( + sessionId = session.id, + step = when (progress.step) { + ShareRefreshManager.Progress.Step.DEALING -> SharesSummary.Running.Step.DEALING + ShareRefreshManager.Progress.Step.STORING -> SharesSummary.Running.Step.STORING + }, + waitingOn = progress.waitingOn.map(::nameOf), + since = progress.since, + canAbandon = progress.canAbandon, + ) + } + } ?: signingNewGeneration(localChatRoom, key, shares.generation, refreshes) val mine = shares.roster.firstOrNull { it.memberPublicKey == me } val repairing = repairs.any { it.targetPublicKey == me && it.stage != ShareRepairStage.FAILED && it.stage != ShareRepairStage.COMPLETE } SharesSummary( generation = shares.generation, members = shares.roster.map { entry -> - SharesSummary.Member(entry.memberPublicKey, names[entry.memberPublicKey] ?: entry.memberPublicKey.take(8), entry.standing, entry.memberPublicKey == me) + SharesSummary.Member(entry.memberPublicKey, nameOf(entry.memberPublicKey), entry.standing, entry.memberPublicKey == me) }, pending = if (ExperimentalFeatures.shareRefresh) pending else emptyList(), - canRotate = ExperimentalFeatures.shareRefresh && shares.secretShare != null && !running, + canRotate = ExperimentalFeatures.shareRefresh && shares.secretShare != null && runningRefresh == null, canAskToBeRepaired = ExperimentalFeatures.shareRefresh && mine?.standing == ShareStanding.STALE && !repairing, + running = running.takeIf { ExperimentalFeatures.shareRefresh }, + lastFailure = refreshes.firstOrNull()?.takeIf { it.stage == ShareRefreshStage.FAILED }?.failureReason + ?.takeIf { ExperimentalFeatures.shareRefresh }, ) }.getOrNull() + /** + * The last step of a rotation: complete, and the group signing the new + * generation's key state, which the old shares wait on before they are + * deleted. Shown only while that signature is actually open, so a key state + * nobody is asking for does not read as one under way. + */ + private suspend fun signingNewGeneration( + localChatRoom: LocalChatRoom, + key: DkgSession, + generation: Int, + refreshes: List, + ): SharesSummary.Running? { + val refresh = refreshes.firstOrNull { it.stage == ShareRefreshStage.COMPLETE && it.baseGeneration + 1 == generation } ?: return null + val signed = GroupKeyStateManager.signedStateFor(database, localChatRoom.chatRoom.id) + if ((signed?.generation ?: 0) >= generation) return null + val signing = database.frostSigningSessionDao() + val open = signing.getOpenSessionsForKey(key.id).firstOrNull { session -> + (session.generation ?: 0) == generation && signing.getItems(session.id).singleOrNull() + ?.let { Event.fromJsonOrNull(it.unsignedEventJson)?.kind } == GroupKeyStateEvent.KIND + } ?: return null + return SharesSummary.Running( + sessionId = refresh.id, + step = SharesSummary.Running.Step.SIGNING, + waitingOn = emptyList(), + since = open.createdAt, + canAbandon = false, + ) + } + private fun failureOf(t: Throwable?): String? = t?.let { it.message ?: it::class.simpleName ?: "Unknown error" } private fun privateKeyOrNull(): Pair? { @@ -723,7 +785,7 @@ class DatabaseChatRepository( val (_, privateKey) = privateKeyOrNull() ?: return "This identity cannot sign" return failureOf(runCatching { when (approval.kind) { - SharesSummary.PendingApproval.Kind.REFRESH_DEAL, SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM -> + SharesSummary.PendingApproval.Kind.REFRESH_DEAL -> ShareRefreshManager.approve(database, localChatRoom, approval.sessionId, privateKey) SharesSummary.PendingApproval.Kind.REPAIR_HELP -> ShareRepairManager.approve(database, localChatRoom, approval.sessionId, privateKey) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt index 61b551e2..84e1370a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -426,10 +426,14 @@ object ShareRefreshManager { logger.w("Refresh ${session.id}: kind ${innerEvent.kind} from ${innerEvent.pubKey.take(8)}, who is not a recipient; ignoring") return true } + // Stored once, on first arrival: its time is when the rotation last + // moved, and a relay repeating itself is not progress ([progress]). val known = database.shareRefreshDao().getMessage(session.id, innerEvent.kind, innerEvent.pubKey) != null - database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, innerEvent.pubKey, innerEvent.kind, innerEvent.content)) - if (!known && innerEvent.pubKey != session.userPublicKey) { - announce(database, session, stepType(innerEvent.kind), stepLine(innerEvent.kind), innerEvent.pubKey) + if (!known) { + database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, innerEvent.pubKey, innerEvent.kind, innerEvent.content)) + if (innerEvent.pubKey != session.userPublicKey) { + announce(database, session, stepType(innerEvent.kind), stepLine(innerEvent.kind), innerEvent.pubKey) + } } } @@ -686,6 +690,43 @@ object ShareRefreshManager { return if (session.dealApprovedAt == null) ShareRefreshApprovalStep.DEAL else null } + /** + * Where a running refresh stands, as the Shares section shows it once its one + * approval is given: which step, who it waits on, since when, and whether + * this device may abandon it (docs/rotate-shares-single-approval.md, Phase 6). + * Null once it has finished. + * + * With nothing left to approve, this is the only place a member who took part + * can see a rotation stall, and the only way they can end it. + */ + suspend fun progress(database: GizaDatabase, session: ShareRefreshSession): Progress? { + if (session.stage == ShareRefreshStage.COMPLETE || session.stage == ShareRefreshStage.FAILED) return null + val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return null + val base = ShareGenerations.at(database, key, session.baseGeneration) ?: return null + val memberOf = base.roster.associate { it.participantId to it.memberPublicKey } + val recipients = session.recipientIdList() + val messages = database.shareRefreshDao().getMessagesForSession(session.id) + fun missing(kind: Kind) = recipients + .filter { id -> messages.none { it.kind == kind && it.participantPublicKey == memberOf[id] } } + .mapNotNull { memberOf[it] } + val (step, waitingOn) = when { + session.coordinatorRound1 == null -> Progress.Step.DEALING to missing(ShareRefreshEvents.ROUND_1).ifEmpty { listOf(session.coordinatorPublicKey) } + else -> Progress.Step.STORING to missing(ShareRefreshEvents.ROUND_2).ifEmpty { listOf(session.coordinatorPublicKey) } + } + val myId = memberOf.entries.firstOrNull { it.value == session.userPublicKey }?.key + return Progress( + step = step, + waitingOn = waitingOn, + since = messages.maxOfOrNull { it.createdAt } ?: session.createdAt, + canAbandon = myId != null && myId in recipients, + ) + } + + /** See [progress]. */ + data class Progress(val step: Step, val waitingOn: List, val since: Instant, val canAbandon: Boolean) { + enum class Step { DEALING, STORING } + } + /** Approves the step this device's owner is being asked for, and moves on. */ suspend fun approve(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { val session = database.shareRefreshDao().getSessionById(sessionId) ?: return @@ -736,9 +777,9 @@ object ShareRefreshManager { /** Queues this device's own message and records it, so the coordinator's own is in its sums. */ private suspend fun publishOwn(database: GizaDatabase, localChatRoom: LocalChatRoom, session: ShareRefreshSession, kind: Kind, content: String) { broadcast(database, localChatRoom, session, kind, content, ShareRefreshEvents.assembleTags(session.id)) - val known = ownMessage(database, session, kind) != null + if (ownMessage(database, session, kind) != null) return database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, session.userPublicKey, kind, content)) - if (!known) announce(database, session, stepType(kind), stepLine(kind), session.userPublicKey) + announce(database, session, stepType(kind), stepLine(kind), session.userPublicKey) } /** One of this device's messages, as an inner event of the key's Marmot room. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index abbc23f5..10b8e07b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -104,7 +104,6 @@ import mobi.giza.compose.resources.leave_group import mobi.giza.compose.resources.remove_from_group import mobi.giza.compose.resources.shares_action_sent import mobi.giza.compose.resources.pending_repair_help -import mobi.giza.compose.resources.pending_rotation_confirm import mobi.giza.compose.resources.pending_rotation_deal import mobi.giza.compose.resources.abandon import mobi.giza.compose.resources.approve @@ -132,6 +131,23 @@ import mobi.giza.compose.resources.rotation_proposing_is_taking_part import mobi.giza.compose.resources.rotation_taking_part import mobi.giza.compose.resources.rotation_no_key import mobi.giza.compose.ui.view.state.RotationPreview +import androidx.compose.runtime.remember +import androidx.compose.material3.CardDefaults +import mobi.giza.compose.resources.waiting_on_s_since_s +import mobi.giza.compose.resources.rotation_ended +import mobi.giza.compose.resources.abandon_rotation_body +import mobi.giza.compose.resources.abandon_rotation_question +import mobi.giza.compose.resources.abandon_rotation +import mobi.giza.compose.resources.rotation_abandon_explainer +import mobi.giza.compose.resources.rotation_step_signing +import mobi.giza.compose.resources.rotation_step_storing +import mobi.giza.compose.resources.rotation_step_dealing +import mobi.giza.compose.resources.rotation_running +import mobi.giza.compose.resources.pending_rotation_commits +import mobi.giza.compose.resources.rotation_withheld_for_good +import mobi.giza.compose.resources.rotation_withheld_until_back +import mobi.giza.compose.resources.pending_rotation_without +import mobi.giza.compose.resources.pending_rotation_everyone import androidx.compose.material3.AlertDialog import mobi.giza.compose.resources.disband_group import mobi.giza.compose.resources.disband_group_explainer @@ -226,6 +242,33 @@ fun ChatRoomDetailScreen( ) } + var abandoningRotation by remember { mutableStateOf(null) } + abandoningRotation?.let { sessionId -> + AlertDialog( + onDismissRequest = { abandoningRotation = null }, + title = { Text(stringResource(Res.string.abandon_rotation_question)) }, + text = { Text(stringResource(Res.string.abandon_rotation_body)) }, + confirmButton = { + TextButton( + onClick = { + abandoningRotation = null + (chatRoomDetailViewModel.chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded)?.let { loaded -> + chatRoomDetailViewModel.abandonRotation(loaded.localChatRoom, sessionId) { failure -> notify(failure ?: sharesActionSent) } + } + }, + colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error) + ) { + Text(stringResource(Res.string.abandon_rotation)) + } + }, + dismissButton = { + TextButton(onClick = { abandoningRotation = null }) { + Text(stringResource(Res.string.not_now)) + } + }, + ) + } + // The proposer's one approval: the rotation as it will be proposed, with // everyone it leaves out named (docs/rotate-shares-single-approval.md, Phase 4). chatRoomDetailViewModel.rotationProposal?.let { proposal -> @@ -431,6 +474,28 @@ fun ChatRoomDetailScreen( style = MaterialTheme.typography.bodyMedium ) } + // Above the members: with nothing left to approve, this is + // where a member who took part sees a rotation stall, and the + // only way out of one (docs/rotate-shares-single-approval.md). + shares.running?.let { running -> + item(key = "rotation-running") { + RotationRunningCard( + running = running, + onAbandon = { abandoningRotation = running.sessionId }, + ) + } + } + if (shares.running == null) { + shares.lastFailure?.let { reason -> + item(key = "rotation-ended") { + Text( + text = stringResource(Res.string.rotation_ended, reason), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } items(items = shares.members, key = { member -> "share-${member.publicKey}" }) { member -> ListItem( headlineContent = { @@ -456,12 +521,18 @@ fun ChatRoomDetailScreen( stringResource( when (approval.kind) { SharesSummary.PendingApproval.Kind.REFRESH_DEAL -> Res.string.pending_rotation_deal - SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM -> Res.string.pending_rotation_confirm SharesSummary.PendingApproval.Kind.REPAIR_HELP -> Res.string.pending_repair_help } ) ) }, + // Taking part is agreeing to who is left out, and it is the + // only thing this rotation will ask: so the row says both. + supportingContent = if (approval.kind == SharesSummary.PendingApproval.Kind.REFRESH_DEAL) { + { RotationTakingPart(approval.withheld) } + } else { + null + }, trailingContent = { Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { if (approval.kind != SharesSummary.PendingApproval.Kind.REPAIR_HELP) { @@ -1394,3 +1465,70 @@ private fun RotationLeftOut(preview: RotationPreview) { Text(stringResource(Res.string.rotation_left_out_for_good, preview.forGood.joinToString(", "))) } } + +/** What taking part in a rotation agrees to: who it leaves out, and that nothing more will be asked. */ +@Composable +private fun RotationTakingPart(withheld: List) { + val leftOut = withheld.map { entry -> + stringResource( + if (entry.standing == ShareStanding.RETIRED) Res.string.rotation_withheld_for_good else Res.string.rotation_withheld_until_back, + entry.name + ) + } + Column { + Text( + if (leftOut.isEmpty()) stringResource(Res.string.pending_rotation_everyone) + else stringResource(Res.string.pending_rotation_without, leftOut.joinToString(", ")) + ) + Text(stringResource(Res.string.pending_rotation_commits)) + } +} + +/** + * A rotation past its one approval: the step it is on, who it waits on and since + * when, and abandon for a member taking part. Shown whether or not it has + * stalled -- unlike a ceremony, a rotation has no screen of its own to show it. + */ +@Composable +private fun RotationRunningCard(running: SharesSummary.Running, onAbandon: () -> Unit) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.secondaryContainer, + contentColor = MaterialTheme.colorScheme.onSecondaryContainer + ) + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + Text(stringResource(Res.string.rotation_running), style = MaterialTheme.typography.titleSmall) + Text( + stringResource( + when (running.step) { + SharesSummary.Running.Step.DEALING -> Res.string.rotation_step_dealing + SharesSummary.Running.Step.STORING -> Res.string.rotation_step_storing + SharesSummary.Running.Step.SIGNING -> Res.string.rotation_step_signing + } + ), + style = MaterialTheme.typography.bodyMedium + ) + if (running.waitingOn.isNotEmpty()) { + Text( + stringResource(Res.string.waiting_on_s_since_s, running.waitingOn.joinToString(", "), running.since.toFormattedTimeAndDateString()), + style = MaterialTheme.typography.bodyMedium + ) + } + if (running.canAbandon) { + Text(stringResource(Res.string.rotation_abandon_explainer), style = MaterialTheme.typography.bodyMedium) + TextButton( + onClick = onAbandon, + modifier = Modifier.align(Alignment.End), + colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error) + ) { + Text(stringResource(Res.string.abandon_rotation)) + } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt index 720377f0..af7dbc63 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt @@ -1,12 +1,13 @@ package mobi.giza.compose.ui.view.state import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant import mobi.giza.compose.database.model.types.ShareStanding /** * A room's key, as the Shares section shows it (docs/frost-share-refresh.md, * Phase 11): the generation the group signs with, who holds what, what this - * device is being asked, and what it may start. + * device is being asked, what is running, and what it may start. */ data class SharesSummary( val generation: Int, @@ -16,11 +17,38 @@ data class SharesSummary( val canRotate: Boolean, /** This device's own id is stale and nothing is bringing it back yet. */ val canAskToBeRepaired: Boolean, + /** A rotation under way, from its one approval until the group signs the new generation. */ + val running: Running? = null, + /** Why the newest rotation ended, when it ended without completing and nothing has run since. */ + val lastFailure: String? = null, ) { data class Member(val publicKey: HexKey, val name: String, val standing: ShareStanding, val isSelf: Boolean) - /** Something this device's owner is being asked, and the session it is for. */ - data class PendingApproval(val sessionId: String, val kind: Kind) { - enum class Kind { REFRESH_DEAL, REFRESH_CONFIRM, REPAIR_HELP } + /** + * Something this device's owner is being asked, and the session it is for. + * A rotation's carries who it leaves out, because agreeing to that is what + * taking part is (docs/rotate-shares-single-approval.md, Phase 6). + */ + data class PendingApproval(val sessionId: String, val kind: Kind, val withheld: List = emptyList()) { + /** A rotation asks one thing, to take part; storing the new share stopped being a question. */ + enum class Kind { REFRESH_DEAL, REPAIR_HELP } + } + + data class Withheld(val name: String, val standing: ShareStanding) + + /** + * A rotation running past its one approval. With nothing left to approve, + * this is the only place a member who took part sees it stall, and the only + * way out of one. + */ + data class Running( + val sessionId: String, + val step: Step, + val waitingOn: List, + val since: Instant, + /** This device is a recipient of a rotation not yet certified, so it may end it for everyone. */ + val canAbandon: Boolean, + ) { + enum class Step { DEALING, STORING, SIGNING } } } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt index fbe26bbd..9f504526 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -657,6 +657,123 @@ class ShareRefreshRitualJvmTest { assertEquals(0, FrostSigningManager.resumeVouched(member.db, member.publicKey), "once") } + // ---- Phase 6 of rotate-shares-single-approval: the Shares section ------------------------------------------------ + + private suspend fun summaryOn(device: Device): mobi.giza.compose.ui.view.state.SharesSummary { + val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined + kotlinx.coroutines.Job()) + return try { + assertNotNull(mobi.giza.compose.database.repository.DatabaseChatRepository(device.db, scope).sharesSummary(device.room), "device ${device.index}") + } finally { + scope.coroutineContext[kotlinx.coroutines.Job]?.cancel() + } + } + + private fun nameOf(device: Device) = device.publicKey.take(8) + + @Test + fun `a rotation asks one thing, to take part`() { + assertEquals( + listOf(mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.REFRESH_DEAL, mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.REPAIR_HELP), + mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.entries.toList(), + ) + } + + /** Taking part is agreeing to who is left out, so the row that asks it names them. */ + @Test + fun `the taking-part row names who is left out, and the withheld member sees the rotation run`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + propose(all[0], mapOf(group.idOf[2] to ShareStanding.STALE)) + pump(all) + + val asked = summaryOn(all[1]) + val row = asked.pending.single() + assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.REFRESH_DEAL, row.kind) + assertEquals(listOf(mobi.giza.compose.ui.view.state.SharesSummary.Withheld(nameOf(all[2]), ShareStanding.STALE)), row.withheld) + assertNull(asked.running, "the row covers a member not yet asked") + + val withheld = summaryOn(all[2]) + assertTrue(withheld.pending.isEmpty()) + val running = assertNotNull(withheld.running) + assertEquals(listOf(nameOf(all[1])), running.waitingOn) + assertTrue(!running.canAbandon, "only a member taking part may end it") + } + + /** + * Once a member has taken part there is nothing left to approve, so the + * running rotation is what they see: the step, who it waits on, and abandon. + */ + @Test + fun `a running rotation names who it waits on at each step`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val (alice, bob, carol) = all + val refresh = propose(alice) + pump(all) + ShareRefreshManager.approve(bob.db, bob.room, refresh.id, bob.privateKey) + pump(all) + + val dealing = assertNotNull(summaryOn(bob).running) + assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.Running.Step.DEALING, dealing.step) + assertEquals(listOf(nameOf(carol)), dealing.waitingOn) + assertTrue(dealing.canAbandon, "a member who took part can still end it") + assertTrue(summaryOn(bob).pending.isEmpty()) + assertTrue(!summaryOn(bob).canRotate) + + // Carol takes part; her confirmation is slow to arrive. + ShareRefreshManager.approve(carol.db, carol.room, refresh.id, carol.privateKey) + pump(all, hold = { it.kind == ShareRefreshEvents.ROUND_2 && it.publicKey == carol.publicKey }) + val storing = assertNotNull(summaryOn(bob).running) + assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.Running.Step.STORING, storing.step) + assertEquals(listOf(nameOf(carol)), storing.waitingOn) + + // A relay repeating itself is not progress. Dated a day back first, so a + // redelivery that rewrote a row would show, whatever the clock's precision. + val dao = bob.db.shareRefreshDao() + val dayAgo = kotlin.time.Clock.System.now() - kotlin.time.Duration.parse("1d") + dao.getMessagesForSession(refresh.id).forEach { dao.upsert(it.copy(createdAt = dayAgo, updatedAt = dayAgo, savedAt = dayAgo)) } + val since = assertNotNull(summaryOn(bob).running).since + assertTrue(kotlin.time.Clock.System.now() - since > kotlin.time.Duration.parse("23h")) + bob.received.clear() + pump(all, hold = { it.kind == ShareRefreshEvents.ROUND_2 && it.publicKey == carol.publicKey }) + assertEquals(since, summaryOn(bob).running?.since, "a redelivered message moved the stall clock") + } + + @Test + fun `the last step is the group signing the new key state, which nobody abandons`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) } + pump(all, hold = { FrostSigningEvents.isProposal(it.kind) }) + + val signing = assertNotNull(summaryOn(all[0]).running, "the coordinator's own key state is open") + assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.Running.Step.SIGNING, signing.step) + assertTrue(!signing.canAbandon) + + pump(all) + all.forEach { assertNull(summaryOn(it).running, "device ${it.index}: nothing is running once it is signed") } + } + + @Test + fun `an abandoned rotation says why until the next one`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + ShareRefreshManager.approve(all[1].db, all[1].room, refresh.id, all[1].privateKey) + ShareRefreshManager.abandon(all[1].db, all[1].room, refresh.id) + pump(all) + + all.forEach { device -> + val summary = summaryOn(device) + assertNull(summary.running) + assertTrue(summary.lastFailure!!.contains("Abandoned"), summary.lastFailure) + assertTrue(summary.canRotate) + } + } + @Test fun `a withheld member ends with the new table and no share, and declines to sign`() = runBlocking { val group = Group(3, 2)