Merge branch 'giza' into claude/nip17-multiple-chilldkg-6903b0

This commit is contained in:
Kgothatso Ngako committed 2026-11-22 23:32:43 +02:00
commit e188c2f378
14 files changed
+266 -16

No files matched your search

@@ -744,6 +744,10 @@
<string name="joining_gives_you_a_share">Joining gives you a share of the confederation's key for each group you are an admin of. Everything after joining runs by itself.</string>
<string name="abandon_the_key_ceremony">Abandon the key ceremony</string>
<string name="this_device_holds_no_key_ceremony">This device holds no key ceremony for this proposal</string>
<string name="the_others_have_started_without_you">The others have started the key ceremony. It cannot go on until you join.</string>
<string name="this_room_runs_a_key_ceremony">This room runs a confederation's key ceremony.</string>
<string name="this_room_waits_for_you_to_join">This room runs a confederation's key ceremony, and it cannot go on until you join.</string>
<string name="open_the_key_ceremony">Open the key ceremony</string>
<string name="ceremony_step_host_keys">Host keys</string>
<string name="ceremony_step_contributions">Contributions</string>
<string name="ceremony_step_authorizations">Authorizations</string>
@@ -391,6 +391,12 @@ class DatabaseChatRepository(
return proposeAsConfederation(localChatRoom, kind, tags, content)
}
override suspend fun keyCeremonyOfRoom(chatRoomId: String): mobi.giza.compose.ui.view.state.KeyCeremonyLink? {
val proposalId = ConfederationRitualManager.proposalOfRoom(database, chatRoomId) ?: return null
val joined = database.confederationCeremonyDao().getLatestForProposal(proposalId)?.approvedAt != null
return mobi.giza.compose.ui.view.state.KeyCeremonyLink(proposalId = proposalId, joined = joined)
}
override suspend fun confederationOfRoom(chatRoomId: String): String? =
database.confederationCeremonyDao().getConfederation(chatRoomId)
?.takeIf { ConfederationFormation.verifies(it) }
@@ -55,6 +55,12 @@ class DatabaseConfederationRepository(
return ConfederationRitualManager.join(database, proposalId, secret.publicKey().xOnly().value.toHex(), secret.value.toByteArray())
}
override suspend fun joinablePlan(proposalId: HexKey): ConfederationRosterBuilder.Plan? {
val secret = activeIdentity.value?.nostrPrivateKey ?: return null
val joinable = ConfederationRitualManager.joinable(database, proposalId, secret.publicKey().xOnly().value.toHex())
return (joinable as? Either.Right)?.value
}
override suspend fun abandonCeremony(sessionId: String) = ConfederationRitualManager.abandon(database, sessionId)
override fun observeSigningAttempt(attemptId: String): Flow<ConfederationSigningAttempt?> =
@@ -151,6 +151,30 @@ object ConfederationRitualManager {
/** Whether this ceremony is waiting on its member to join. */
fun isAwaitingJoin(ceremony: ConfederationCeremony): Boolean = ceremony.isRunning && ceremony.approvedAt == null
/**
* The roster [userPublicKey] would join [proposalId]'s ceremony over, or why they cannot: what
* [join] checks before it makes anything. Lets a screen offer the join on a device that holds
* no ceremony yet, since nothing is made here until its owner joins.
*/
suspend fun joinable(database: GizaDatabase, proposalId: HexKey, userPublicKey: HexKey): Either<String, Plan> =
when (val built = basisFor(database, proposalId)) {
is Either.Left -> built
is Either.Right -> eligibility(database, built.value, userPublicKey)
}
/**
* The proposal whose key ceremony runs in [chatRoomId], or null when it carries none this device
* holds the proposal for. Read from the ceremony messages filed there, sent or received: the
* room is made by the first one to arrive, so on a device whose owner has not joined, those
* messages are all the room has to say what it is for.
*/
suspend fun proposalOfRoom(database: GizaDatabase, chatRoomId: String): HexKey? =
database.giftWrapPayloadDao()
.getByChatRoomAndKinds(chatRoomId, ConfederationRitualEvents.ALL.toList())
.mapNotNull { ConfederationRitualEvents.parseProposalId(it.tags) }
.distinct()
.lastOrNull { database.confederationDao().getEvent(it) != null }
/**
* Joins the key ceremony for [proposalId] as [userPublicKey]: the one thing a member is asked,
* offered to every admin of every group once every group has accepted (D7). Makes the ceremony
@@ -154,6 +154,13 @@ interface ChatRepository {
*/
suspend fun inboxSummary(localChatRoom: LocalChatRoom): mobi.giza.compose.ui.view.state.InboxRowSummary? = null
/**
* The confederation key ceremony that runs in [chatRoomId], if it is one's room, and whether this
* device has joined it. The room is made by the first ceremony message to arrive, before its owner
* has joined, and it is where they look for the ceremony.
*/
suspend fun keyCeremonyOfRoom(chatRoomId: String): mobi.giza.compose.ui.view.state.KeyCeremonyLink? = null
/** The confederation whose room [chatRoomId] is, by name, if its record verifies here. docs/confederation.md, Phase 13. */
suspend fun confederationOfRoom(chatRoomId: String): String? = null
@@ -87,6 +87,12 @@ interface ConfederationRepository {
*/
suspend fun joinCeremony(proposalId: HexKey): ConfederationCeremony
/**
* The roster this identity would join [proposalId]'s ceremony over, or null when it cannot join
* from here: the same checks [joinCeremony] makes, run without making anything.
*/
suspend fun joinablePlan(proposalId: HexKey): ConfederationRosterBuilder.Plan?
suspend fun abandonCeremony(sessionId: String)
/** One attempt by a confederation to sign an event, as it changes. docs/confederation.md, Phase 14. */
@@ -138,6 +144,7 @@ interface ConfederationRepository {
override fun ceremonyPlan(ceremony: ConfederationCeremony): ConfederationRosterBuilder.Plan? = null
override suspend fun joinCeremony(proposalId: HexKey): ConfederationCeremony =
throw UnsupportedOperationException("No confederation here")
override suspend fun joinablePlan(proposalId: HexKey): ConfederationRosterBuilder.Plan? = null
override suspend fun abandonCeremony(sessionId: String) = Unit
override fun observeConfederationsOf(groupPublicKey: HexKey): Flow<List<Confederation>> = flowOf(emptyList())
override fun observeSigningAttempt(attemptId: String): Flow<ConfederationSigningAttempt?> = flowOf(null)
@@ -16,6 +16,7 @@ import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Key
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Mic
import androidx.compose.material.icons.filled.MoreVert
@@ -29,6 +30,7 @@ import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.TextButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
@@ -50,6 +52,11 @@ import mobi.giza.compose.repository.NostrRepository
import mobi.giza.compose.ui.composable.navigation.routes.ConfederationSigningRoute
import mobi.giza.compose.ui.composable.navigation.routes.ChatRoomDetailRoute
import mobi.giza.compose.ui.composable.navigation.routes.DkgRitualRoute
import mobi.giza.compose.ui.composable.navigation.routes.ConfederationRitualRoute
import mobi.giza.compose.ui.view.state.KeyCeremonyLink
import mobi.giza.compose.resources.open_the_key_ceremony
import mobi.giza.compose.resources.this_room_runs_a_key_ceremony
import mobi.giza.compose.resources.this_room_waits_for_you_to_join
import mobi.giza.compose.ui.composable.navigation.routes.ProposalListRoute
import mobi.giza.compose.ui.composable.navigation.routes.proposalDestination
import mobi.giza.compose.ui.composable.navigation.routes.Route
@@ -180,6 +187,20 @@ fun ChatRoomMessagingScreen(
Column(
modifier = Modifier.padding(innerPadding).readableContent().fillMaxSize()
) {
// A confederation's key ceremony runs in this room. The room is made by the
// first message to arrive, before its owner has joined, and the join is not
// in the transcript, so this is the way from here to it.
chatRoomDetailUIState.keyCeremony?.let { link ->
KeyCeremonyBanner(
link = link,
onOpen = {
onNavigateToRoute.invoke(
ConfederationRitualRoute(activeUserPublicKey = activeUserPublicKey, proposalId = link.proposalId)
)
},
)
}
Column(
modifier = Modifier.weight(1f).fillMaxWidth()
) {
@@ -511,4 +532,28 @@ private fun ChatRoomMessagingScreenPreview() {
)
}
}
}
}
/** Where a key ceremony's room leads: to the ceremony, and, until its owner joins, to the join. */
@Composable
private fun KeyCeremonyBanner(link: KeyCeremonyLink, onOpen: () -> Unit) {
val container = if (link.joined) MaterialTheme.colorScheme.surfaceContainerHigh else MaterialTheme.colorScheme.secondaryContainer
val content = if (link.joined) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSecondaryContainer
Surface(modifier = Modifier.fillMaxWidth(), color = container, contentColor = content) {
Row(
modifier = Modifier.padding(start = MaterialTheme.spacing.containerPadding, end = MaterialTheme.spacing.compactPadding),
horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(Icons.Default.Key, contentDescription = Decorative)
Text(
modifier = Modifier.weight(1f).padding(vertical = MaterialTheme.spacing.compactPadding),
text = stringResource(if (link.joined) Res.string.this_room_runs_a_key_ceremony else Res.string.this_room_waits_for_you_to_join),
style = MaterialTheme.typography.bodyMedium,
)
TextButton(onClick = onOpen) {
Text(stringResource(Res.string.open_the_key_ceremony))
}
}
}
}
@@ -25,6 +25,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.viewmodel.compose.viewModel
@@ -39,6 +40,8 @@ import mobi.giza.compose.resources.ceremony_step_done
import mobi.giza.compose.resources.ceremony_step_host_keys
import mobi.giza.compose.resources.ceremony_step_shares_stored
import mobi.giza.compose.resources.ceremony_waiting_on
import mobi.giza.compose.resources.could_not_join_the_key_ceremony
import mobi.giza.compose.resources.the_others_have_started_without_you
import mobi.giza.compose.resources.confederation_groups
import mobi.giza.compose.resources.confederation_groups_to_act
import mobi.giza.compose.resources.group_signs_with
@@ -56,6 +59,7 @@ import mobi.giza.compose.ui.composable.widgets.LocalCanSign
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.composable.widgets.rememberNotifier
import mobi.giza.compose.ui.theme.readableContent
import mobi.giza.compose.ui.theme.spacing
import mobi.giza.compose.ui.view.model.ConfederationRitualViewModel
@@ -91,6 +95,8 @@ fun ConfederationRitualScreen(
}
val state by viewModel.uiState.collectAsState()
val identityCanSign = LocalCanSign.current
val notify = rememberNotifier(rememberCoroutineScope())
val couldNotJoin = stringResource(Res.string.could_not_join_the_key_ceremony)
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
@@ -110,6 +116,35 @@ fun ConfederationRitualScreen(
message = stringResource(Res.string.this_device_holds_no_key_ceremony),
)
// A device that heard the others start without it: nothing is made here until its
// owner joins, so this is the join, offered where they came looking for it.
is ConfederationRitualUIState.Joinable -> Column(
modifier = Modifier.padding(padding).readableContent().fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(MaterialTheme.spacing.screenMargin),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
) {
Text(text = current.name, style = MaterialTheme.typography.headlineSmall)
Text(text = stringResource(Res.string.confederation_groups_to_act, current.threshold, current.groups.size))
Text(text = stringResource(Res.string.the_others_have_started_without_you))
if (identityCanSign) {
Text(
text = stringResource(Res.string.joining_gives_you_a_share),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Button(
modifier = Modifier.fillMaxWidth(),
enabled = !current.isActing,
onClick = { viewModel.joinFirst(onFailure = { notify(couldNotJoin) }) },
) {
Text(stringResource(Res.string.join_the_key_ceremony))
}
}
HorizontalDivider()
GroupRolesList(current.groups)
}
is ConfederationRitualUIState.Loaded -> Column(
modifier = Modifier.padding(padding).readableContent().fillMaxSize()
.verticalScroll(rememberScrollState())
@@ -153,13 +188,7 @@ fun ConfederationRitualScreen(
}
HorizontalDivider()
Text(text = stringResource(Res.string.confederation_groups), style = MaterialTheme.typography.titleSmall)
current.groups.forEach { group ->
ListItem(
headlineContent = { Text(stringResource(Res.string.group_signs_with, group.name, group.threshold, group.admins.size)) },
supportingContent = { Text(group.admins.joinToString()) },
)
}
GroupRolesList(current.groups)
if (ceremony.isRunning) {
HorizontalDivider()
@@ -188,6 +217,18 @@ fun ConfederationRitualScreen(
}
}
/** Each group, its threshold, and the admins who hold a role for it. */
@Composable
private fun GroupRolesList(groups: List<ConfederationRitualUIState.GroupRoles>) {
Text(text = stringResource(Res.string.confederation_groups), style = MaterialTheme.typography.titleSmall)
groups.forEach { group ->
ListItem(
headlineContent = { Text(stringResource(Res.string.group_signs_with, group.name, group.threshold, group.admins.size)) },
supportingContent = { Text(group.admins.joinToString()) },
)
}
}
@Composable
private fun stepLabel(kind: StepKind): String = stringResource(
when (kind) {
@@ -55,7 +55,10 @@ class ChatRoomMessagingViewModel(
ChatRoomMessagingUIState.InitiatingNewChat
} else {
ChatRoomMessagingUIState.Loaded(
localChatRoom = localChatRoom
localChatRoom = localChatRoom,
keyCeremony = runCatching { chatRepository.keyCeremonyOfRoom(chatRoomId) }
.onFailure { logger.e("Could not read the key ceremony of $chatRoomId", it) }
.getOrNull(),
)
}
}
@@ -19,6 +19,7 @@ import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import mobi.giza.compose.nostr.confederation.ConfederationRitualEvents
import mobi.giza.compose.nostr.confederation.ConfederationRosterBuilder
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.repository.ConfederationRepository
import mobi.giza.compose.ui.view.state.ConfederationRitualUIState
@@ -51,24 +52,35 @@ class ConfederationRitualViewModel(
}
.collectLatest { (ceremony, messages) ->
if (ceremony == null) {
state.value = ConfederationRitualUIState.NotHeld
// Nothing is made on a device until its owner joins, so a device that heard
// the others start holds no ceremony: offer the join here, where they look.
val joinable = runCatching { confederationRepository.joinablePlan(proposalId) }
.onFailure { logger.e("Could not check whether $proposalId can be joined", it) }
.getOrNull()
state.value = if (joinable == null) {
ConfederationRitualUIState.NotHeld
} else {
val names = namesOf(joinable)
ConfederationRitualUIState.Joinable(
name = joinable.proposal.name,
groups = rolesOf(joinable, names),
threshold = joinable.proposal.threshold,
)
}
return@collectLatest
}
val plan = confederationRepository.ceremonyPlan(ceremony) ?: run {
state.value = ConfederationRitualUIState.NotHeld
return@collectLatest
}
val names = (plan.people + plan.groups).associateWith { confederationRepository.nameOf(it) }
val names = namesOf(plan)
val sent = { kind: Int -> messages.filter { it.kind == kind }.map { it.senderPublicKey }.toSet() }
val waiting = { kind: Int -> plan.people.filterNot { it in sent(kind) }.map { names.getValue(it) } }
val acting = (state.value as? ConfederationRitualUIState.Loaded)?.isActing == true
state.value = ConfederationRitualUIState.Loaded(
ceremony = ceremony,
name = plan.proposal.name,
groups = plan.groups.map { group ->
val list = plan.adminLists.getValue(group)
ConfederationRitualUIState.GroupRoles(names.getValue(group), list.threshold, list.admins.map { names[it] ?: it.take(8) })
},
groups = rolesOf(plan, names),
threshold = plan.proposal.threshold,
steps = listOf(
Step(StepKind.HOST_KEYS, waiting(ConfederationRitualEvents.HOST_KEYS)),
@@ -83,9 +95,34 @@ class ConfederationRitualViewModel(
}
}
private suspend fun namesOf(plan: ConfederationRosterBuilder.Plan): Map<HexKey, String> =
(plan.people + plan.groups).associateWith { confederationRepository.nameOf(it) }
private fun rolesOf(plan: ConfederationRosterBuilder.Plan, names: Map<HexKey, String>) = plan.groups.map { group ->
val list = plan.adminLists.getValue(group)
ConfederationRitualUIState.GroupRoles(names.getValue(group), list.threshold, list.admins.map { names[it] ?: it.take(8) })
}
/** Joins this attempt, or after a failed one joins the next: Try again (docs/confederation-without-coordinator.md, D10). */
fun join() = act { confederationRepository.joinCeremony(it.proposalId) }
/**
* Joins from a device that holds no ceremony yet. The ceremony it makes arrives through
* [initiate]'s flow and replaces this state, so only a failure is reported back.
*/
fun joinFirst(onFailure: () -> Unit) {
val joinable = state.value as? ConfederationRitualUIState.Joinable ?: return
if (joinable.isActing) return
state.update { (it as? ConfederationRitualUIState.Joinable)?.copy(isActing = true) ?: it }
viewModelScope.launch(Dispatchers.IO) {
val joined = runCatching { confederationRepository.joinCeremony(proposalId) }
.onFailure { logger.e("Could not join the key ceremony for $proposalId", it) }
.isSuccess
state.update { (it as? ConfederationRitualUIState.Joinable)?.copy(isActing = false) ?: it }
if (!joined) viewModelScope.launch(Dispatchers.Main) { onFailure() }
}
}
fun abandon() = act { confederationRepository.abandonCeremony(it.id) }
private fun act(action: suspend (ConfederationCeremony) -> Unit) {
@@ -1,10 +1,13 @@
package mobi.giza.compose.ui.view.state
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
sealed interface ChatRoomMessagingUIState {
data class Loaded(
val localChatRoom: LocalChatRoom
val localChatRoom: LocalChatRoom,
/** The confederation key ceremony this room carries, if it is one's room. */
val keyCeremony: KeyCeremonyLink? = null,
): ChatRoomMessagingUIState
data class Error(
@@ -14,3 +17,13 @@ sealed interface ChatRoomMessagingUIState {
data object InitiatingNewChat: ChatRoomMessagingUIState
}
/**
* A confederation's key ceremony, from the room it runs in: the way to it from there, since the room
* is made by the first message to arrive, before its owner has joined (docs/confederation.md, Phase 11).
*/
data class KeyCeremonyLink(
val proposalId: HexKey,
/** Whether this device's owner has joined the latest attempt. */
val joined: Boolean,
)
@@ -22,6 +22,17 @@ sealed interface ConfederationRitualUIState {
data class Step(val kind: StepKind, val waitingOn: List<String>)
/**
* No ceremony on this device yet, and its owner can join one: nothing is made here until they
* do, so this is what a device sees that heard the others start without it.
*/
data class Joinable(
val name: String,
val groups: List<GroupRoles>,
val threshold: Int,
val isActing: Boolean = false,
) : ConfederationRitualUIState
data object NotHeld : ConfederationRitualUIState
data object Loading : ConfederationRitualUIState
@@ -198,6 +198,35 @@ class ConfederationCeremonyJvmTest {
assertEquals(ConfederationCeremonyStage.FAILED, ceremonies()[holdout]?.stage, "the abandonment it missed is replayed")
}
@Test
fun `a member who has not joined finds the ceremony from the room the others' messages made, and can join from it`() {
setUp()
val late = network.device(32)
joinAll(except = setOf(late.person))
pump()
runBlocking {
assertNull(ceremonies()[late.person], "nothing is made on a device until its owner joins")
val link = assertNotNull(repository(late).keyCeremonyOfRoom(late.room.chatRoom.id), "the room says what it is for")
assertEquals(network.proposalId, link.proposalId)
assertFalse(link.joined)
assertNull(repository(late).keyCeremonyOfRoom(groups[0]), "a room with no ceremony messages carries none")
val plan = assertIs<fr.acinq.bitcoin.utils.Either.Right<ConfederationRosterBuilder.Plan>>(
ConfederationRitualManager.joinable(late.db, network.proposalId, late.person)
).value
assertTrue(late.person in plan.people)
assertIs<fr.acinq.bitcoin.utils.Either.Left<String>>(
ConfederationRitualManager.joinable(late.db, network.proposalId, ConfederationStatementFixture.npub(99)),
"someone who holds no role is not offered the join",
)
network.join(late)
assertTrue(repository(late).keyCeremonyOfRoom(late.room.chatRoom.id)!!.joined)
}
pump()
ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) }
}
@Test
fun `an abandoned attempt is tried again as the next, with a new seed, and forms`() {
setUp()
@@ -292,6 +292,23 @@ class ConfederationScreensJvmTest {
onNodeWithText("Polis: 2 of 3 admins to sign").assertIsDisplayed()
}
@Test
fun `a device that holds no ceremony yet is offered the join, and told the others wait on it`() = renderRitual(
ConfederationRitualUIState.Joinable(
name = "Atlas",
groups = listOf(
ConfederationRitualUIState.GroupRoles("Polis", 2, listOf("Ana", "Bo", "Cy")),
ConfederationRitualUIState.GroupRoles("Agora", 2, listOf("Di", "Ed", "Fi")),
),
threshold = 2,
)
) {
onNodeWithText("The others have started the key ceremony", substring = true).assertIsDisplayed()
onNodeWithText("Join the key ceremony").assertIsDisplayed()
onNodeWithText("Agora: 2 of 3 admins to sign").assertIsDisplayed()
onAllNodesWithText("This device holds no key ceremony for this proposal").assertCountEquals(0)
}
@Test
fun `a running ceremony names whom each step waits on, and can be abandoned`() = renderRitual(ritual(ConfederationCeremonyStage.COLLECTING_HOST_KEYS, approved = true)) {
onAllNodesWithText("Join the key ceremony").assertCountEquals(0)