frost: add refresh UI and stored-message resend

This commit is contained in:
Kgothatso Ngako committed 2026-11-20 00:37:00 +02:00
1 parent 2684b9459a
commit 4ef86fd78c
21 files changed
+5422 -12

No files matched your search

@@ -452,4 +452,21 @@
<string name="you_already_have_a_chat_with_s">You already have a chat with %1$s.</string>
<string name="checking_whether_s_can_receive_messages_here">Checking whether %1$s can receive messages here.</string>
<string name="s_hasn_t_set_up_encrypted_messaging_yet">%1$s hasn't set up encrypted messaging yet. Try again later, or ask them to open Giza.</string>
<string name="refresh_signing_shares">Refresh signing shares</string>
<string name="refresh_shares_description">Re-issue every member's share without changing the group's key or this room.</string>
<string name="current_share_epoch">Current share epoch: %1$s</string>
<string name="next_share_epoch">Next share epoch: %1$s</string>
<string name="refresh_backup_warning">Refreshing does not erase old backups. If a threshold of old shares is compromised, make a new group key instead.</string>
<string name="refresh_all_members_required">Every share holder must take part before the new shares can activate.</string>
<string name="commitments_received">Commitments: %1$s of %2$s</string>
<string name="evaluations_received">Private evaluations: %1$s of %2$s</string>
<string name="members_ready">Members ready: %1$s of %2$s</string>
<string name="join_share_refresh">Review and join</string>
<string name="propose_share_activation">Sign activation</string>
<string name="refresh_complete">Share refresh complete. New shares are active.</string>
<string name="refresh_failed">The refresh was abandoned. The previous shares are still active.</string>
<string name="refresh_error">This group cannot refresh its shares</string>
<string name="refresh_stage">Stage: %1$s</string>
<string name="refresh_pending_activation">The candidate is ready. A quorum now needs to sign it into the next epoch.</string>
<string name="refresh_waiting_on_members">Waiting on: %1$s</string>
</resources>
@@ -158,7 +158,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 39,
version = 40,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -409,6 +409,9 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// v39 adds the restart-safe refresh session and protocol-message tables. Existing
// rooms have no refresh rows, so nothing starts and no key material moves.
AutoMigration(from = 38, to = 39),
// v40 adds refresh resend cooldowns and the purpose/helper set for current-epoch
// repair. Existing refresh rows read as REFRESH with the full roster as helpers.
AutoMigration(from = 39, to = 40),
]
)
@ConstructedBy(GizaDatabaseConstructor::class)
@@ -1,5 +1,6 @@
package mobi.giza.compose.database.model
import androidx.room3.ColumnInfo
import androidx.room3.Entity
import androidx.room3.ForeignKey
import androidx.room3.Index
@@ -12,6 +13,7 @@ import kotlin.time.Clock
import kotlin.time.Instant
import mobi.giza.compose.database.model.traits.LocalStoreEntity
import mobi.giza.compose.database.model.traits.TimestampedEntity
import mobi.giza.compose.database.model.types.ReEnrollmentPurpose
import mobi.giza.compose.database.model.types.ReEnrollmentStage
/** One proactive FROST share refresh, as this device sees it. */
@@ -49,6 +51,13 @@ data class FrostReEnrollmentSession(
val stage: ReEnrollmentStage = ReEnrollmentStage.COLLECTING_COMMITMENTS,
/** Whether this is a proactive refresh or a current-epoch share repair. */
@ColumnInfo(defaultValue = "REFRESH")
val purpose: ReEnrollmentPurpose = ReEnrollmentPurpose.REFRESH,
/** The helpers for a repair, or null for a full-member refresh. */
val helperPublicKeys: String? = null,
/** Secret. This device's dealer seed, retained only while the refresh is unresolved. */
val dealerRandom: HexKey? = null,
@@ -66,6 +75,7 @@ data class FrostReEnrollmentSession(
val joinApprovedAt: Instant? = null,
val readyAt: Instant? = null,
val resentAt: Instant? = null,
val failureReason: String? = null,
override val createdAt: Instant = Clock.System.now(),
@@ -76,6 +86,12 @@ data class FrostReEnrollmentSession(
fun participantPublicKeySet(): Set<HexKey> = participantPublicKeys.split(",").filter { it.isNotBlank() }.toSet()
fun helperPublicKeySet(): Set<HexKey> = helperPublicKeys
?.split(",")
?.filter { it.isNotBlank() }
?.toSet()
?: participantPublicKeySet()
fun candidatePublicShareList(): List<PublicKey>? = candidatePublicShares
?.split(",")
?.filter { it.isNotBlank() }
@@ -0,0 +1,7 @@
package mobi.giza.compose.database.model.types
/** Why a re-enrollment session is exchanging secret shares. */
enum class ReEnrollmentPurpose {
REFRESH,
REPAIR,
}
@@ -0,0 +1,66 @@
package mobi.giza.compose.database.repository
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.flow.Flow
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.FrostReEnrollmentMessage
import mobi.giza.compose.database.model.FrostReEnrollmentSession
import mobi.giza.compose.database.model.FrostSigningSession
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.managers.FrostReEnrollmentManager
import mobi.giza.compose.repository.ReEnrollmentRepository
class DatabaseReEnrollmentRepository(
private val database: GizaDatabase,
) : ReEnrollmentRepository {
private val logger = Logger.withTag(TAG)
override fun observeSessionById(sessionId: String): Flow<FrostReEnrollmentSession?> =
database.frostReEnrollmentDao().observeSessionById(sessionId)
override fun observeMessages(sessionId: String): Flow<List<FrostReEnrollmentMessage>> =
database.frostReEnrollmentDao().observeMessages(sessionId)
override suspend fun pendingApproval(session: FrostReEnrollmentSession): Boolean =
FrostReEnrollmentManager.pendingApproval(database, session)
override suspend fun proposeReEnrollment(localChatRoom: LocalChatRoom, userPublicKey: HexKey): FrostReEnrollmentSession? = try {
FrostReEnrollmentManager.proposeReEnrollment(database, localChatRoom, userPublicKey)
} catch (e: Throwable) {
logger.e("Could not open share re-enrollment for ${localChatRoom.chatRoom.id}", e)
null
}
override suspend fun approve(localChatRoom: LocalChatRoom, sessionId: String) =
FrostReEnrollmentManager.approve(database, localChatRoom, sessionId)
override suspend fun abandon(localChatRoom: LocalChatRoom, sessionId: String): Boolean = try {
FrostReEnrollmentManager.abandon(database, localChatRoom, sessionId)
} catch (e: Throwable) {
logger.e("Could not abandon refresh $sessionId", e)
false
}
override suspend fun resend(localChatRoom: LocalChatRoom, sessionId: String): Boolean = try {
FrostReEnrollmentManager.resend(database, localChatRoom, sessionId)
} catch (e: Throwable) {
logger.e("Could not resend refresh $sessionId", e)
false
}
override suspend fun proposeActivation(
localChatRoom: LocalChatRoom,
userPublicKey: HexKey,
sessionId: String,
): FrostSigningSession? = try {
FrostReEnrollmentManager.proposeActivation(database, localChatRoom, userPublicKey, sessionId)
} catch (e: Throwable) {
logger.e("Could not propose activation for refresh $sessionId", e)
null
}
companion object {
private const val TAG = "DatabaseReEnrollmentRepository"
}
}
@@ -21,6 +21,7 @@ import fr.acinq.bitcoin.crypto.frost.RefreshCandidate
import fr.acinq.bitcoin.crypto.frost.RefreshDealerFault
import fr.acinq.bitcoin.utils.Either
import kotlin.time.Clock
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Instant
import kotlinx.coroutines.CancellationException
import mobi.giza.compose.database.GizaDatabase
@@ -46,6 +47,7 @@ object FrostReEnrollmentManager {
private const val PUBLIC_SHARES_TAG = "giza/frost-refresh/public-shares/v1"
private const val MAX_ID_SEARCH = 4
private val SCRUBBED_RANDOM = "00".repeat(32)
private val RESEND_COOLDOWN = 5.minutes
private val logger = Logger.withTag(TAG)
@@ -128,6 +130,12 @@ object FrostReEnrollmentManager {
} ?: return
if (session.stage == ReEnrollmentStage.COMPLETE || session.stage == ReEnrollmentStage.FAILED) return
if (innerEvent.kind == ReEnrollmentEvents.PROPOSAL &&
innerEvent.pubKey == session.coordinatorPublicKey &&
ReEnrollmentEvents.parseSilentMembers(innerEvent.tags)?.contains(session.userPublicKey) == true
) {
republishOwn(database, localChatRoom, session)
}
if (!record(database, localChatRoom, session, innerEvent)) return
advance(database, localChatRoom, session.id)
}
@@ -162,6 +170,53 @@ object FrostReEnrollmentManager {
return true
}
/** Re-publish stored protocol inputs without changing them or creating a new refresh. */
suspend fun resend(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
sessionId: String,
): Boolean {
val session = database.frostReEnrollmentDao().getSessionById(sessionId) ?: return false
if (session.joinApprovedAt == null || session.stage == ReEnrollmentStage.COMPLETE || session.stage == ReEnrollmentStage.FAILED) {
return false
}
val now = Clock.System.now()
session.resentAt?.let { if (now - it < RESEND_COOLDOWN) return false }
var sent = false
if (session.isCoordinator()) {
val silent = session.participantPublicKeySet() - database.frostReEnrollmentDao()
.getMessagesByKind(session.id, ReEnrollmentEvents.READY)
.map { it.senderPublicKey }
.toSet()
sent = broadcast(
database, localChatRoom, session, ReEnrollmentEvents.PROPOSAL,
activeKey(database, session).thresholdPublicKey.orEmpty(),
includeProposal = true,
silentMembers = silent.toList(),
) || sent
}
sent = republishOwn(database, localChatRoom, session) || sent
if (sent) update(database, session) { it.copy(resentAt = now) }
return sent
}
private suspend fun republishOwn(
database: GizaDatabase,
localChatRoom: LocalChatRoom,
session: FrostReEnrollmentSession,
): Boolean {
if (session.joinApprovedAt == null) return false
var sent = false
database.frostReEnrollmentDao().getMessagesForSession(session.id)
.filter { it.senderPublicKey == session.userPublicKey && it.payload.isNotEmpty() }
.forEach { message ->
val recipient = message.recipientPublicKey.ifBlank { null }
sent = broadcast(database, localChatRoom, session, message.kind, message.payload, recipient) || sent
}
return sent
}
/** Ask a quorum to sign the already-staged candidate into the next key epoch. */
suspend fun proposeActivation(
database: GizaDatabase,
@@ -517,6 +572,7 @@ object FrostReEnrollmentManager {
content: String,
directRecipient: HexKey? = null,
includeProposal: Boolean = false,
silentMembers: List<HexKey>? = null,
): Boolean {
val relayHints = localChatRoom.localParticipants.associate {
it.participant.participantPublicKey to it.participant.relayHint
@@ -539,6 +595,7 @@ object FrostReEnrollmentManager {
} else null,
transcriptHash = if (kind == ReEnrollmentEvents.READY) session.transcriptHash else null,
previousStateEventId = if (includeProposal) session.previousStateEventId else null,
silentMembers = silentMembers,
)
val createdAt = Clock.System.now().epochSeconds
repeat(MAX_ID_SEARCH) { attempt ->
@@ -2262,8 +2262,11 @@ object FrostSigningManager {
return false
}
if (refresh != null && (
refresh.nextShareEpoch != session.shareEpoch || refresh.candidateSecretShare == null ||
refresh.candidatePublicShareList() == null
refresh.nextShareEpoch != session.shareEpoch || refresh.candidatePublicShareList() == null ||
refresh.stage !in setOf(
mobi.giza.compose.database.model.types.ReEnrollmentStage.ACTIVATING,
mobi.giza.compose.database.model.types.ReEnrollmentStage.COMPLETE,
)
)
) {
logger.i("Activation session $sessionId has no staged candidate to resend")
@@ -5,6 +5,7 @@ import mobi.giza.compose.nostr.dkg.tags.DkgThresholdTag
import mobi.giza.compose.nostr.frost.tags.FrostDerivationPathTag
import mobi.giza.compose.nostr.frost.tags.FrostKeyTag
import mobi.giza.compose.nostr.frost.tags.FrostShareEpochTag
import mobi.giza.compose.nostr.frost.tags.FrostSilentMembersTag
import mobi.giza.compose.nostr.frost.tags.ReEnrollmentSessionIdTag
/** The encrypted inner-event kinds and tags used by proactive FROST share refresh. */
@@ -15,14 +16,20 @@ object ReEnrollmentEvents {
val READY: Kind = 30341
val FAILURE: Kind = 30342
val KEY_EPOCH_STATE: Kind = 30344
val REPAIR_PUBLIC_SHARES: Kind = 30346
val REPAIR_CONTRIBUTION: Kind = 30347
val REPAIR_AGGREGATED: Kind = 30348
private const val PARAMS_TAG = "re_enrollment_params"
private const val TRANSCRIPT_TAG = "re_enrollment_transcript"
private const val PREVIOUS_STATE_TAG = "re_enrollment_previous_state"
private const val PUBLIC_SHARES_TAG = "re_enrollment_public_shares"
val ALL: Set<Kind> = setOf(PROPOSAL, COMMITMENTS, PRIVATE_EVALUATION, READY, FAILURE, KEY_EPOCH_STATE)
val PRIVATE: Set<Kind> = setOf(PRIVATE_EVALUATION)
val ALL: Set<Kind> = setOf(
PROPOSAL, COMMITMENTS, PRIVATE_EVALUATION, READY, FAILURE, KEY_EPOCH_STATE,
REPAIR_PUBLIC_SHARES, REPAIR_CONTRIBUTION, REPAIR_AGGREGATED,
)
val PRIVATE: Set<Kind> = setOf(PRIVATE_EVALUATION, REPAIR_CONTRIBUTION, REPAIR_AGGREGATED)
fun isReEnrollmentKind(kind: Kind): Boolean = kind in ALL
@@ -36,6 +43,7 @@ object ReEnrollmentEvents {
previousStateEventId: String? = null,
publicSharesHash: String? = null,
derivationPath: List<Long>? = null,
silentMembers: List<String>? = null,
): Array<Array<String>> = buildList {
add(ReEnrollmentSessionIdTag.assemble(sessionId))
dkgSessionId?.let { add(FrostKeyTag.assemble(it)) }
@@ -46,6 +54,7 @@ object ReEnrollmentEvents {
previousStateEventId?.let { add(arrayOf(PREVIOUS_STATE_TAG, it)) }
publicSharesHash?.let { add(arrayOf(PUBLIC_SHARES_TAG, it)) }
derivationPath?.let { add(FrostDerivationPathTag.assemble(it)) }
silentMembers?.takeIf { it.isNotEmpty() }?.let { add(FrostSilentMembersTag.assemble(it)) }
}.toTypedArray()
fun parseSessionId(tags: Array<Array<String>>): String? =
@@ -55,6 +64,8 @@ object ReEnrollmentEvents {
fun parseTranscriptHash(tags: Array<Array<String>>): String? = tags.value(TRANSCRIPT_TAG)
fun parsePreviousStateEventId(tags: Array<Array<String>>): String? = tags.value(PREVIOUS_STATE_TAG)
fun parsePublicSharesHash(tags: Array<Array<String>>): String? = tags.value(PUBLIC_SHARES_TAG)
fun parseSilentMembers(tags: Array<Array<String>>): List<String>? =
tags.firstNotNullOfOrNull(FrostSilentMembersTag::parse)?.members
private fun Array<Array<String>>.value(name: String): String? =
firstOrNull { it.size > 1 && it[0] == name }?.get(1)?.ifBlank { null }
@@ -0,0 +1,33 @@
package mobi.giza.compose.repository
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import mobi.giza.compose.database.model.FrostReEnrollmentMessage
import mobi.giza.compose.database.model.FrostReEnrollmentSession
import mobi.giza.compose.database.model.FrostSigningSession
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
interface ReEnrollmentRepository {
fun observeSessionById(sessionId: String): Flow<FrostReEnrollmentSession?>
fun observeMessages(sessionId: String): Flow<List<FrostReEnrollmentMessage>>
suspend fun pendingApproval(session: FrostReEnrollmentSession): Boolean
suspend fun proposeReEnrollment(localChatRoom: LocalChatRoom, userPublicKey: HexKey): FrostReEnrollmentSession?
suspend fun approve(localChatRoom: LocalChatRoom, sessionId: String)
suspend fun abandon(localChatRoom: LocalChatRoom, sessionId: String): Boolean
suspend fun resend(localChatRoom: LocalChatRoom, sessionId: String): Boolean
suspend fun proposeActivation(localChatRoom: LocalChatRoom, userPublicKey: HexKey, sessionId: String): FrostSigningSession?
companion object {
val NO_OP_REENROLLMENT_REPOSITORY: ReEnrollmentRepository = object : ReEnrollmentRepository {
override fun observeSessionById(sessionId: String): Flow<FrostReEnrollmentSession?> = flowOf(null)
override fun observeMessages(sessionId: String): Flow<List<FrostReEnrollmentMessage>> = flowOf(emptyList())
override suspend fun pendingApproval(session: FrostReEnrollmentSession): Boolean = false
override suspend fun proposeReEnrollment(localChatRoom: LocalChatRoom, userPublicKey: HexKey): FrostReEnrollmentSession? = null
override suspend fun approve(localChatRoom: LocalChatRoom, sessionId: String) = Unit
override suspend fun abandon(localChatRoom: LocalChatRoom, sessionId: String): Boolean = false
override suspend fun resend(localChatRoom: LocalChatRoom, sessionId: String): Boolean = false
override suspend fun proposeActivation(localChatRoom: LocalChatRoom, userPublicKey: HexKey, sessionId: String): FrostSigningSession? = null
}
}
}
@@ -16,6 +16,7 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Key
import androidx.compose.material.icons.filled.AccountTree
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Autorenew
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.ContentCopy
@@ -68,6 +69,7 @@ import mobi.giza.compose.ui.composable.navigation.routes.ProfilePreviewRoute
import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.composable.navigation.routes.CreateSharedKeyRoute
import mobi.giza.compose.ui.composable.navigation.routes.ProposalListRoute
import mobi.giza.compose.ui.composable.navigation.routes.ReEnrollmentRoute
import mobi.giza.compose.ui.composable.navigation.routes.SearchMemberToAddToChatRoomRoute
import mobi.giza.compose.extensions.inComparableGroups
import mobi.giza.compose.extensions.toFormattedTimeAndDateString
@@ -109,6 +111,7 @@ import mobi.giza.compose.resources.member_removal_requested
import mobi.giza.compose.resources.members_2
import mobi.giza.compose.resources.proposals
import mobi.giza.compose.resources.reindex_events
import mobi.giza.compose.resources.refresh_signing_shares
import mobi.giza.compose.resources.shared_key
import mobi.giza.compose.resources.signing_key
import mobi.giza.compose.resources.the_key_this_room_signs_as
@@ -248,6 +251,25 @@ fun ChatRoomDetailScreen(
}
}
if (chatRoomDetailUIState.canRefreshShares) {
item {
TextButton(
onClick = {
onNavigateToRoute(
ReEnrollmentRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
)
)
}
) {
Icon(Icons.Default.Refresh, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.space125))
Text(stringResource(Res.string.refresh_signing_shares))
}
}
}
// Directly under the signing key, because between them
// they are what the room *is*: the identity it signs as
// and whose child it is. Absent on a group that is
@@ -0,0 +1,170 @@
package mobi.giza.compose.ui.composable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import mobi.giza.compose.database.model.types.ReEnrollmentStage
import mobi.giza.compose.extensions.memberName
import mobi.giza.compose.repository.ChatRepository
import mobi.giza.compose.repository.ReEnrollmentRepository
import mobi.giza.compose.resources.Res
import mobi.giza.compose.resources.abandon
import mobi.giza.compose.resources.ask_again
import mobi.giza.compose.resources.commitments_received
import mobi.giza.compose.resources.current_share_epoch
import mobi.giza.compose.resources.evaluations_received
import mobi.giza.compose.resources.join_share_refresh
import mobi.giza.compose.resources.members_ready
import mobi.giza.compose.resources.next_share_epoch
import mobi.giza.compose.resources.of_members_will_be_needed_to_sign_with_this
import mobi.giza.compose.resources.propose_share_activation
import mobi.giza.compose.resources.refresh_all_members_required
import mobi.giza.compose.resources.refresh_backup_warning
import mobi.giza.compose.resources.refresh_complete
import mobi.giza.compose.resources.refresh_error
import mobi.giza.compose.resources.refresh_failed
import mobi.giza.compose.resources.refresh_pending_activation
import mobi.giza.compose.resources.refresh_shares_description
import mobi.giza.compose.resources.refresh_signing_shares
import mobi.giza.compose.resources.refresh_stage
import mobi.giza.compose.resources.refresh_waiting_on_members
import mobi.giza.compose.ui.composable.navigation.routes.ReEnrollmentRoute
import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.composable.widgets.Decorative
import mobi.giza.compose.ui.composable.widgets.ErrorState
import mobi.giza.compose.ui.composable.widgets.LoadingDataIndicator
import mobi.giza.compose.ui.composable.widgets.LocalSnackbarHostState
import mobi.giza.compose.ui.composable.widgets.NavigateBackButton
import mobi.giza.compose.ui.composable.widgets.ScreenStateTransition
import mobi.giza.compose.ui.theme.readableContent
import mobi.giza.compose.ui.theme.spacing
import mobi.giza.compose.ui.view.model.ReEnrollmentViewModel
import mobi.giza.compose.ui.view.state.ReEnrollmentUIState
import org.jetbrains.compose.resources.stringResource
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ReEnrollmentScreen(
route: ReEnrollmentRoute,
chatRepository: ChatRepository,
reEnrollmentRepository: ReEnrollmentRepository,
onNavigateToRoute: (Route) -> Unit,
onNavigateBack: () -> Unit,
) {
val viewModel: ReEnrollmentViewModel = viewModel(
factory = ReEnrollmentViewModel.factory(
route.activeUserPublicKey,
route.chatRoomId,
route.reEnrollmentSessionId,
ReEnrollmentUIState.Loading,
chatRepository,
reEnrollmentRepository,
)
)
LaunchedEffect(Unit) { viewModel.initiate() }
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
TopAppBar(
title = { Text(stringResource(Res.string.refresh_signing_shares)) },
navigationIcon = { NavigateBackButton(onNavigateBack) },
)
},
) { innerPadding ->
ScreenStateTransition(viewModel.uiState) { state ->
when (state) {
is ReEnrollmentUIState.Loading -> LoadingDataIndicator()
is ReEnrollmentUIState.Error -> ErrorState(message = state.message)
is ReEnrollmentUIState.Loaded -> {
val session = state.session
val waiting = session.participantPublicKeySet() - state.messages
.filter { it.kind == mobi.giza.compose.nostr.frost.ReEnrollmentEvents.READY }
.map { it.senderPublicKey }
.toSet()
Column(
modifier = Modifier
.padding(innerPadding)
.readableContent()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.containerPadding),
) {
Text(stringResource(Res.string.refresh_shares_description))
Text(stringResource(Res.string.refresh_all_members_required))
Card(modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding)) {
Text(stringResource(Res.string.current_share_epoch, session.currentShareEpoch))
Text(stringResource(Res.string.next_share_epoch, session.nextShareEpoch))
Text(stringResource(Res.string.of_members_will_be_needed_to_sign_with_this, session.threshold, session.participantCount))
Text(stringResource(Res.string.refresh_stage, session.stage.name))
}
}
Text(stringResource(Res.string.refresh_backup_warning), style = MaterialTheme.typography.bodySmall)
Text(stringResource(Res.string.commitments_received, state.commitments, session.participantCount))
Text(stringResource(Res.string.evaluations_received, state.evaluations, session.participantCount))
Text(stringResource(Res.string.members_ready, state.ready, session.participantCount))
if (waiting.isNotEmpty() && session.stage != ReEnrollmentStage.COMPLETE) {
Text(
stringResource(
Res.string.refresh_waiting_on_members,
waiting.joinToString { it.memberName(state.localChatRoom.localParticipants, session.userPublicKey) },
),
style = MaterialTheme.typography.bodySmall,
)
}
when {
state.pendingApproval -> {
Button(enabled = !viewModel.isActionPending.value, onClick = viewModel::approve) {
Text(stringResource(Res.string.join_share_refresh))
}
}
session.stage == ReEnrollmentStage.ACTIVATING -> {
Text(stringResource(Res.string.refresh_pending_activation))
Button(
enabled = !viewModel.isActionPending.value,
onClick = { viewModel.activate(onNavigateToRoute) },
) {
Icon(Icons.Default.Refresh, contentDescription = Decorative)
Text(stringResource(Res.string.propose_share_activation))
}
}
session.stage == ReEnrollmentStage.COMPLETE -> Text(stringResource(Res.string.refresh_complete))
session.stage == ReEnrollmentStage.FAILED -> Text(stringResource(Res.string.refresh_failed))
}
if (session.stage != ReEnrollmentStage.COMPLETE && session.stage != ReEnrollmentStage.FAILED) {
TextButton(enabled = !viewModel.isActionPending.value, onClick = viewModel::resend) {
Text(stringResource(Res.string.ask_again))
}
if (session.readyAt == null) {
TextButton(enabled = !viewModel.isActionPending.value, onClick = viewModel::abandon) {
Text(stringResource(Res.string.abandon))
}
}
}
}
}
}
}
}
}
@@ -27,12 +27,14 @@ import mobi.giza.compose.database.repository.DatabaseChatRepository
import mobi.giza.compose.database.repository.DatabaseDkgRepository
import mobi.giza.compose.database.repository.DatabaseFrostSigningRepository
import mobi.giza.compose.database.repository.DatabaseMarmotRepository
import mobi.giza.compose.database.repository.DatabaseReEnrollmentRepository
import mobi.giza.compose.database.repository.DatabaseNostrRepository
import mobi.giza.compose.database.repository.DatabaseSearchRepository
import mobi.giza.compose.managers.AuxDatabaseManager
import mobi.giza.compose.ui.composable.ActiveProfileScreen
import mobi.giza.compose.ui.composable.AddMemberToChatRoomConfirmationScreen
import mobi.giza.compose.ui.composable.ChatRoomCreationScreen
import mobi.giza.compose.ui.composable.ReEnrollmentScreen
import mobi.giza.compose.ui.composable.ChatRoomDetailScreen
import mobi.giza.compose.ui.composable.ChatRoomMessagingScreen
import mobi.giza.compose.ui.composable.CreateProfileScreen
@@ -134,6 +136,7 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute
import mobi.giza.compose.ui.composable.navigation.routes.ReEnrollmentRoute
import mobi.giza.compose.ui.composable.navigation.routes.ProposalListRoute
import mobi.giza.compose.ui.composable.FrostSigningScreen
import mobi.giza.compose.ui.composable.ProposalListScreen
@@ -191,6 +194,9 @@ fun GizaNavHost(
applicationIOScope
)
}
val databaseReEnrollmentRepository = remember {
DatabaseReEnrollmentRepository(auxDatabaseManager.auxDatabase)
}
val databaseFrostSigningRepository = remember {
DatabaseFrostSigningRepository(
database = auxDatabaseManager.auxDatabase,
@@ -618,6 +624,16 @@ fun GizaNavHost(
}
)
}
composable<ReEnrollmentRoute> { backStackEntry ->
val route = backStackEntry.toRoute<ReEnrollmentRoute>()
ReEnrollmentScreen(
route = route,
chatRepository = databaseChatRepository,
reEnrollmentRepository = databaseReEnrollmentRepository,
onNavigateToRoute = { next -> navController.navigate(next) },
onNavigateBack = { navController.popBackStack() },
)
}
composable<DkgJoinApprovalRoute> { backStackEntry ->
val route = backStackEntry.toRoute<DkgJoinApprovalRoute>()
@@ -0,0 +1,11 @@
package mobi.giza.compose.ui.composable.navigation.routes
import kotlinx.serialization.Serializable
/** One proactive share-refresh ceremony, or the latest one for the room. */
@Serializable
data class ReEnrollmentRoute(
val activeUserPublicKey: String,
val chatRoomId: String,
val reEnrollmentSessionId: String? = null,
) : Route()
@@ -103,6 +103,8 @@ class ChatRoomDetailViewModel(
subgroups = chatRepository.subgroupsOf(chatRoomId),
parentChatRoomId = chatRepository.parentOf(chatRoomId),
canAddSubgroup = canSign && !subgroupsNeedAWallet,
canRefreshShares = canSign,
canRepairShare = groupKeyState != null && !canSign,
subgroupsNeedAWallet = canSign && subgroupsNeedAWallet,
canGovern = canGovern,
isDisbanded = isDisbanded,
@@ -0,0 +1,101 @@
package mobi.giza.compose.ui.view.model
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import mobi.giza.compose.repository.ChatRepository
import mobi.giza.compose.repository.ReEnrollmentRepository
import mobi.giza.compose.ui.composable.navigation.routes.FrostSigningRoute
import mobi.giza.compose.ui.composable.navigation.routes.Route
import mobi.giza.compose.ui.view.state.ReEnrollmentUIState
class ReEnrollmentViewModel(
val activeUserPublicKey: HexKey,
val chatRoomId: String,
val reEnrollmentSessionId: String?,
initialUIState: ReEnrollmentUIState,
private val chatRepository: ChatRepository,
private val reEnrollmentRepository: ReEnrollmentRepository,
) : ViewModel() {
var uiState: ReEnrollmentUIState by mutableStateOf(initialUIState)
private set
var isActionPending: MutableState<Boolean> = mutableStateOf(false)
private set
private var initiated = false
fun initiate() {
if (initiated) return
initiated = true
viewModelScope.launch(Dispatchers.IO) {
val room = chatRepository.getChatRoomByIdentifier(chatRoomId)
if (room == null) {
uiState = ReEnrollmentUIState.Error("Couldn't load this chat")
return@launch
}
val sessionId = reEnrollmentSessionId ?: reEnrollmentRepository.proposeReEnrollment(room, activeUserPublicKey)?.id
if (sessionId == null) {
uiState = ReEnrollmentUIState.Error("This group cannot refresh its shares")
return@launch
}
combine(
reEnrollmentRepository.observeSessionById(sessionId),
reEnrollmentRepository.observeMessages(sessionId),
) { session, messages ->
session?.let { ReEnrollmentUIState.Loaded(room, it, messages, reEnrollmentRepository.pendingApproval(it)) }
}.collect { state -> state?.let { uiState = it } }
}
}
fun approve() = action { room, sessionId -> reEnrollmentRepository.approve(room, sessionId) }
fun abandon() = action { room, sessionId -> reEnrollmentRepository.abandon(room, sessionId) }
fun resend() = action { room, sessionId -> reEnrollmentRepository.resend(room, sessionId) }
fun activate(onNavigateToRoute: (Route) -> Unit) = action { room, sessionId ->
reEnrollmentRepository.proposeActivation(room, activeUserPublicKey, sessionId)?.let { activation ->
onNavigateToRoute(FrostSigningRoute(activeUserPublicKey, chatRoomId, activation.id))
}
}
private fun action(run: suspend (mobi.giza.compose.database.model.intermdiate.LocalChatRoom, String) -> Unit) {
if (isActionPending.value) return
val session = (uiState as? ReEnrollmentUIState.Loaded)?.session ?: return
isActionPending.value = true
viewModelScope.launch(Dispatchers.IO) {
try {
val room = chatRepository.getChatRoomByIdentifier(chatRoomId) ?: return@launch
run(room, session.id)
} finally {
isActionPending.value = false
}
}
}
companion object {
fun factory(
activeUserPublicKey: HexKey,
chatRoomId: String,
reEnrollmentSessionId: String?,
initialUIState: ReEnrollmentUIState,
chatRepository: ChatRepository,
reEnrollmentRepository: ReEnrollmentRepository,
) = viewModelFactory {
initializer {
ReEnrollmentViewModel(
activeUserPublicKey, chatRoomId, reEnrollmentSessionId,
initialUIState, chatRepository, reEnrollmentRepository,
)
}
}
}
}
@@ -60,6 +60,10 @@ sealed interface ChatRoomDetailUIState {
* missing and what to do about it.
*/
val canAddSubgroup: Boolean = false,
/** Whether this device holds a current share and can start a proactive refresh. */
val canRefreshShares: Boolean = false,
/** Whether this device can ask current share holders to repair its missing share. */
val canRepairShare: Boolean = false,
/**
* Whether this device could open a subgroup here but for the room's own
* certificate saying `wallet=guarded`: a guarded group's subgroups are
@@ -0,0 +1,21 @@
package mobi.giza.compose.ui.view.state
import mobi.giza.compose.database.model.FrostReEnrollmentMessage
import mobi.giza.compose.database.model.FrostReEnrollmentSession
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.nostr.frost.ReEnrollmentEvents
sealed interface ReEnrollmentUIState {
data object Loading : ReEnrollmentUIState
data class Error(val message: String) : ReEnrollmentUIState
data class Loaded(
val localChatRoom: LocalChatRoom,
val session: FrostReEnrollmentSession,
val messages: List<FrostReEnrollmentMessage>,
val pendingApproval: Boolean,
) : ReEnrollmentUIState {
val commitments: Int get() = messages.count { it.kind == ReEnrollmentEvents.COMMITMENTS }
val evaluations: Int get() = messages.count { it.kind == ReEnrollmentEvents.PRIVATE_EVALUATION && it.payload.isNotEmpty() }
val ready: Int get() = messages.count { it.kind == ReEnrollmentEvents.READY }
}
}
@@ -37,13 +37,13 @@ import mobi.giza.compose.managers.OldEngineBlob
* uses, rather than a decoder in a test. Phase 8 added a table, so this branch is the
* first in a while whose upgrade can fail for a reason that has nothing to do with MLS.
*
* It is named for what it opens rather than for a migration, because 36 -> 39 consists of
* It is named for what it opens rather than for a migration, because 36 -> 40 consists of
* `AutoMigration`s and there is no `MIGRATION_36_38` to call: Room generates them, and
* the only way to run the generated one is to let Room decide it is needed. That is
* also the failure this catches. An entity added to the `@Database` list without an
* `AutoMigration` beside it builds, passes every test over an in-memory database, and
* installs perfectly on a phone that has never had the app -- and throws
* `IllegalStateException: A migration from 36 to 39 was required but not found` on
* `IllegalStateException: A migration from 36 to 40 was required but not found` on
* every phone that has.
*
* The v36 database is built from the exported schema rather than from copied SQL, so
@@ -62,7 +62,7 @@ class ShippedProfileUpgradeJvmTest {
private val shipped = 36
/** The schema version this branch builds. */
private val current = 39
private val current = 40
private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile()
private val file: File = File(directory, "aux.db")
@@ -225,13 +225,13 @@ class ShippedProfileUpgradeJvmTest {
// -- what it has to prove --------------------------------------------------------
/**
* Room finds the way from 36 to 39, runs it, and stamps the file with the hash the
* Room finds the way from 36 to 40, runs it, and stamps the file with the hash the
* generated code expects. The hash is the assertion that matters: Room writes it
* only after `validateMigration` has compared every table it was handed against the
* schema the entities declare.
*/
@Test
fun `a v36 profile opens at v39, with the table this branch adds`(): Unit = runBlocking {
fun `a v36 profile opens at v40, with the table this branch adds`(): Unit = runBlocking {
writeShippedProfile()
onDisk { connection ->
assertEquals(shipped.toLong(), connection.userVersion(), "the fixture is not at the shipped version")
@@ -247,7 +247,7 @@ class ShippedProfileUpgradeJvmTest {
assertEquals(
schema(current)["identityHash"]!!.jsonPrimitive.content,
connection.identityHash(),
"Room did not stamp the v39 identity hash, so it did not validate the migrated schema",
"Room did not stamp the v40 identity hash, so it did not validate the migrated schema",
)
val expected = entities(current).associateBy { it.tableName() }
assertEquals(expected.keys, connection.tables(), "the migrated file has a different set of tables")
@@ -12,6 +12,7 @@ import fr.acinq.bitcoin.crypto.frost.KeyMaterial
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
@@ -220,6 +221,36 @@ class FrostReEnrollmentManagerJvmTest {
assertEquals(participants * (participants - 1), direct.distinctBy { it.id }.size)
}
@Test
fun `a resend names missing members and republishes the same private bytes`() = runBlocking {
openDevices()
devices[0].let { FrostReEnrollmentManager.proposeReEnrollment(it.db, it.room, it.member) }
pump { it.kind == ReEnrollmentEvents.PROPOSAL }
devices.drop(1).forEach { device ->
FrostReEnrollmentManager.approve(device.db, device.room, device.session()!!.id)
}
pump { it.kind != ReEnrollmentEvents.READY }
val original = devices[1].db.marmotInnerEventDao()
.getByChatRoomAndKinds(roomId, listOf(ReEnrollmentEvents.PRIVATE_EVALUATION))
.single { it.publicKey == members[1] && it.directMessageRecipientPublicKey == members[0] }
val coordinator = devices[0]
assertTrue(FrostReEnrollmentManager.resend(coordinator.db, coordinator.room, coordinator.session()!!.id))
assertFalse(FrostReEnrollmentManager.resend(coordinator.db, coordinator.room, coordinator.session()!!.id))
val proposal = coordinator.db.marmotInnerEventDao()
.getByChatRoomAndKinds(roomId, listOf(ReEnrollmentEvents.PROPOSAL))
.last()
assertEquals(members.drop(1).toSet(), ReEnrollmentEvents.parseSilentMembers(proposal.tags)?.toSet())
pump { it.kind == ReEnrollmentEvents.PROPOSAL }
val repeated = devices[1].db.marmotInnerEventDao()
.getByChatRoomAndKinds(roomId, listOf(ReEnrollmentEvents.PRIVATE_EVALUATION))
.single { it.publicKey == members[1] && it.directMessageRecipientPublicKey == members[0] && it.id != original.id }
assertEquals(original.content, repeated.content)
assertTrue(repeated.id != original.id)
}
@Test
fun `candidate signatures activate the new epoch and sign afterward`() = runBlocking {
openDevices()