feat: the coordinator's device takes a finished ceremony to its room (automatic ceremony, Phase 6)

CeremonyFollowThrough asks a subgroup's parent to certify it, asks the
group to sign the key state, and creates the room, from stored rows and
one step at a time. It runs beside the live subscription, outside the
inbound lock, since creating a room waits on key packages the inbound
path delivers. It looks again when a ceremony finishes, a certificate
or key state is signed, or a key package arrives.

Only the coordinator's device acts on its own, and never again after a
signing session failed; the ladder keeps the buttons for both. Once the
room exists the ladder's last rung opens it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-19 23:10:56 +02:00
1 parent 4c75ca1b03
commit 73fcfff0da
11 files changed
+660 -14

No files matched your search

@@ -461,4 +461,5 @@
<string name="the_ceremony_has_stalled">The ceremony has stalled</string>
<string name="waiting_on_s_since_s">Waiting on %1$s since %2$s.</string>
<string name="if_they_have_stopped_answering_any_member_can_abandon">If they have stopped answering, any member can abandon the ceremony. No key is made, and the group can start again.</string>
<string name="open_the_room">Open the room</string>
</resources>
@@ -170,6 +170,17 @@ interface DkgSessionDao {
)
suspend fun getRunningSessionsFor(userPublicKey: HexKey): List<DkgSession>
/**
* Every ceremony [userPublicKey] opened that has finished with a key: what
* `CeremonyFollowThrough` takes on to a working room.
*/
@Query(
"SELECT * FROM DkgSession WHERE userPublicKey = :userPublicKey AND " +
"coordinatorPublicKey = :userPublicKey AND stage = 'COMPLETE' AND " +
"thresholdPublicKey IS NOT NULL ORDER BY createdAt ASC"
)
fun observeCompletedSessionsCoordinatedBy(userPublicKey: HexKey): Flow<List<DkgSession>>
@Upsert
suspend fun upsert(dkgSession: DkgSession)
@@ -37,6 +37,14 @@ interface MarmotKeyPackageDao {
@Query("SELECT * FROM MarmotKeyPackage WHERE id = :id ORDER BY createdAt DESC")
suspend fun getMarmotKeyPackageById(id: HexKey): MarmotKeyPackage?
/**
* How many key packages this device holds, as a signal that one arrived.
* `CeremonyFollowThrough` watches it to retry a room that was blocked on a
* member's missing package; it reads the packages themselves when it does.
*/
@Query("SELECT COUNT(*) FROM MarmotKeyPackage")
fun observeCount(): Flow<Int>
@Upsert
suspend fun upsert(marmotKeyPackage: MarmotKeyPackage)
}
@@ -7,6 +7,7 @@ import com.vitorpamplona.quartz.nip01Core.core.Kind
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import mobi.giza.compose.managers.CeremonyFollowThrough
import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl
import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync
@@ -81,6 +82,10 @@ class DatabaseChatRepository(
path = path,
parentChatRoomId = parentChatRoomId,
)
override suspend fun followThroughCeremonies(keyPair: KeyPair) =
CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair)
override suspend fun observeChatRoomListByPublicKey(publicKey: String): Flow<List<LocalChatRoom>> {
return database.chatRoomDao().observeChatRoomListByUserPublicKey(publicKey)
}
@@ -0,0 +1,296 @@
package mobi.giza.compose.managers
import co.touchlab.kermit.Logger
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.Kind
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.conflate
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.DkgSession
import mobi.giza.compose.database.model.FrostSigningSession
import mobi.giza.compose.database.model.types.FrostSigningStage
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
import mobi.giza.compose.repository.ChatRepository
/**
* Takes a finished ceremony the rest of the way to a working room, without the
* coordinator pressing anything.
*
* A ceremony reaching COMPLETE gives the group a key and nothing else. Three steps
* follow, in an order nothing can change (docs/subgroups.md, "The order"):
*
* 1. a subgroup's parent certifies the room the key derives -- proposed here, and
* signed by the parent's own quorum, which stays their decision;
* 2. the group signs what that room will sign with, its key state;
* 3. the room is created and the members welcomed into it.
*
* None of the three proposals asks anybody anything: each is a request to the
* group, and the coordinator agreed to make it when they opened the ceremony. So
* they are taken here, the same way the rounds are taken by `ChillDkgRitualManager`
* -- from stored rows, one step at a time, repeating nothing. See
* docs/automatic-key-ceremony.md, Phase 6.
*
* **Only the coordinator's device does this on its own.** Every participant could,
* and the ladder still offers the buttons to any of them, but `n` devices each
* proposing the same key state is `n` sessions for the group to sign.
*
* **It never proposes again after a failure.** A signing session that failed did
* so because members declined or could not sign, and asking again on its own would
* ask them again on a loop. The ladder offers that retry to a person.
*
* Not run under the inbound path's lock: creating a room waits on relays for key
* packages, and the inbound path is what delivers them.
*/
object CeremonyFollowThrough {
private const val TAG = "CeremonyFollowThrough"
private val logger = Logger.withTag(TAG)
/** The most steps one pass takes for one ceremony before looking again. */
private const val MAX_STEPS_PER_PASS = 4
/** One device follows through one step at a time, whichever trigger asked. */
private val mutex = Mutex()
/** What one call to [takeNextStep] did. */
sealed interface Step {
/** Not this device's to do, or nothing left: not the coordinator, not finished, or the room exists. */
data object NothingToDo : Step
/** Waiting on signatures somebody else gives. */
data object Waiting : Step
/** A request went out: [what] the group or its parent is now being asked to sign. */
data class Proposed(val what: String) : Step
/** The room exists now. */
data class Created(val chatRoomId: String) : Step
/** The room cannot be created until these members' devices publish a key package. */
data class BlockedOn(val missing: List<HexKey>) : Step
/** It cannot go on by itself; the ladder offers the step to a person. */
data class Stuck(val reason: String) : Step
}
/**
* What a ceremony's room is called: the name the coordinator gave a subgroup,
* or the name of the group an admin room administers. The bare name; the
* room puts it under `MarmotGroupName`.
*/
fun roomName(session: DkgSession): String =
session.subject ?: if (session.parentChatRoomId != null) "Subgroup" else "Group"
/** The human half of the room's description. */
fun roomPurpose(session: DkgSession): String =
if (session.parentChatRoomId != null) {
"A subgroup of the group that certified it."
} else {
"Admins of ${session.subject ?: "the group"}."
}
/**
* Follows every finished ceremony this device coordinated, until cancelled.
*
* Looks again whenever something it waits on may have changed: a ceremony
* finishing, a certificate or key state being signed, a key package arriving
* for a member a room was blocked on. Intermediate changes are skipped -- each
* pass reads everything again from the database.
*/
suspend fun observe(database: GizaDatabase, chatRepository: ChatRepository, keyPair: KeyPair) {
val userPublicKey = keyPair.pubKey.toHexKey()
triggers(database, userPublicKey)
.conflate()
.collect { sessions ->
sessions.forEach { session ->
try {
followThrough(database, chatRepository, session, keyPair)
} catch (e: CancellationException) {
throw e
} catch (e: Throwable) {
logger.e("Following ceremony ${session.id} through failed", e)
}
}
}
}
private fun triggers(database: GizaDatabase, userPublicKey: HexKey): Flow<List<DkgSession>> = combine(
database.dkgSessionDao().observeCompletedSessionsCoordinatedBy(userPublicKey),
database.groupSignedEventDao().observeByKind(GroupKeyStateEvent.KIND),
database.groupSignedEventDao().observeByKind(SubgroupBirthCertificateEvent.KIND),
database.marmotKeyPackageDao().observeCount(),
) { sessions, _, _, _ -> sessions }
/**
* Takes steps for [session] until one has to wait on somebody else. Returns the
* last step taken.
*/
suspend fun followThrough(
database: GizaDatabase,
chatRepository: ChatRepository,
session: DkgSession,
keyPair: KeyPair,
): Step {
var step: Step = Step.NothingToDo
repeat(MAX_STEPS_PER_PASS) {
step = takeNextStep(database, chatRepository, session, keyPair)
if (step !is Step.Proposed) return step
}
return step
}
/**
* Takes the one step [session] is ready for, if it is this device's to take.
*
* Each step reads whether its output already exists rather than remembering
* that it ran, so a step interrupted halfway, or asked for twice, does no harm.
*/
suspend fun takeNextStep(
database: GizaDatabase,
chatRepository: ChatRepository,
session: DkgSession,
keyPair: KeyPair,
): Step = mutex.withLock {
val current = database.dkgSessionDao().getSessionById(session.id) ?: return@withLock Step.NothingToDo
if (!current.isCoordinator()) return@withLock Step.NothingToDo
val thresholdPublicKey = current.thresholdPublicKey ?: return@withLock Step.NothingToDo
val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey)
if (database.chatRoomDao().findChatRoomById(roomId) != null) return@withLock Step.NothingToDo
val ceremonyRoom = database.chatRoomDao().findChatRoomById(current.chatRoomId)
?: return@withLock Step.Stuck("The room ceremony ${current.id} ran in is gone")
val participants = ChillDkgRitualManager.participantsOf(current, ceremonyRoom)
val parent = current.parentChatRoomId
// 1. A subgroup's parent certifies the room the key derives.
if (parent != null && !isCertified(database, roomId, parent)) {
val asked = latestSessionCarrying(database, parent, SubgroupBirthCertificateEvent.KIND) {
SubgroupBirthCertificateEvent.parseThresholdPublicKey(it.tags)
.equals(thresholdPublicKey, ignoreCase = true)
}
return@withLock when {
asked == null -> {
val parentRoom = database.chatRoomDao().findChatRoomById(parent)
?: return@withLock Step.Stuck("No parent room $parent to ask for a certificate")
SubgroupManager.proposeBirthCertificate(
database = database,
parentRoom = parentRoom,
userPublicKey = current.userPublicKey,
key = current,
adminPublicKeys = participants.toList(),
name = current.subject ?: "Subgroup",
)
logger.i("Ceremony ${current.id}: asked $parent to certify $roomId")
Step.Proposed("birth certificate")
}
asked.stage == FrostSigningStage.FAILED ->
Step.Stuck("The parent group could not certify $roomId")
else -> Step.Waiting
}
}
// 2. The group signs what the room will sign with.
if (!isKeyStateSigned(database, roomId)) {
val asked = latestSessionCarrying(database, current.chatRoomId, GroupKeyStateEvent.KIND) {
GroupKeyStateEvent.parseDkgSessionId(it.tags) == current.id
}
return@withLock when {
asked == null -> {
if (parent != null) {
SubgroupManager.proposeSubgroupKeyState(
database = database,
ceremonyRoom = ceremonyRoom,
userPublicKey = current.userPublicKey,
key = current,
parentChatRoomId = parent,
)
} else {
GroupKeyStateManager.propose(
database = database,
localChatRoom = ceremonyRoom,
userPublicKey = current.userPublicKey,
key = current,
)
}
logger.i("Ceremony ${current.id}: asked the group to sign $roomId's key state")
Step.Proposed("key state")
}
asked.stage == FrostSigningStage.FAILED ->
Step.Stuck("The group could not agree $roomId's key state")
else -> Step.Waiting
}
}
// 3. The room, with everyone the ceremony was run with as its admins.
when (
val outcome = chatRepository.createMarmotGroup(
groupId = roomId,
name = roomName(current),
purpose = roomPurpose(current),
adminPublicKeys = participants,
userPublicKey = current.userPublicKey,
keyPair = keyPair,
// Verified by the time it is written: the key state this room was
// gated on carries the certificate, and `stateFrom` refused it
// otherwise.
parentChatRoomId = parent,
)
) {
is MarmotGroupCreation.Outcome.Created -> {
logger.i("Ceremony ${current.id}: created $roomId")
Step.Created(outcome.room.chatRoom.id)
}
is MarmotGroupCreation.Outcome.Existing -> Step.NothingToDo
is MarmotGroupCreation.Outcome.BlockedOn -> Step.BlockedOn(outcome.missing)
is MarmotGroupCreation.Outcome.Failed -> Step.Stuck(outcome.reason)
}
}
private suspend fun isCertified(database: GizaDatabase, roomId: String, parentChatRoomId: HexKey): Boolean =
database.groupSignedEventDao()
.getByKind(SubgroupBirthCertificateEvent.KIND)
.any { SubgroupBirthCertificateEvent.certifies(it.toEvent(), roomId, parentChatRoomId) }
private suspend fun isKeyStateSigned(database: GizaDatabase, roomId: String): Boolean =
GroupKeyStateManager.stateAmong(
database.groupSignedEventDao().getByKind(GroupKeyStateEvent.KIND),
roomId
) != null
/**
* The newest signing session in [chatRoomId] carrying an event of [kind] that
* is [about] what is being asked, or null if nobody has asked.
*/
private suspend fun latestSessionCarrying(
database: GizaDatabase,
chatRoomId: String,
kind: Kind,
about: (Event) -> Boolean,
): FrostSigningSession? = database.frostSigningSessionDao()
.getSessionsForChatRoom(chatRoomId)
.sortedByDescending { it.createdAt }
.firstOrNull { session ->
database.frostSigningSessionDao().getItems(session.id).any { item ->
Event.fromJsonOrNull(item.unsignedEventJson)?.let { it.kind == kind && about(it) } == true
}
}
}
@@ -218,6 +218,14 @@ interface ChatRepository {
parentChatRoomId: HexKey? = null,
): MarmotGroupCreation.Outcome
/**
* Takes every key ceremony [keyPair] coordinated from a key to a working room,
* until cancelled: asks the group to sign its key state (a subgroup's parent to
* certify it first) and creates the room. See `CeremonyFollowThrough` and
* docs/automatic-key-ceremony.md, Phase 6.
*/
suspend fun followThroughCeremonies(keyPair: KeyPair)
/**
* Sends [text] to the room, or -- when [directMessageRecipientPublicKey] is given --
* to that one member of it.
@@ -413,6 +421,8 @@ interface ChatRepository {
): MarmotGroupCreation.Outcome =
MarmotGroupCreation.Outcome.Failed("No database")
override suspend fun followThroughCeremonies(keyPair: KeyPair) = Unit
override suspend fun sendChatMessage(
text: String,
@@ -26,6 +26,7 @@ import kotlin.time.Clock
import kotlin.time.Instant
import mobi.giza.compose.extensions.toFormattedTimeAndDateString
import mobi.giza.compose.resources.the_ceremony_has_stalled
import mobi.giza.compose.resources.open_the_room
import mobi.giza.compose.resources.waiting_on_s_since_s
import mobi.giza.compose.resources.if_they_have_stopped_answering_any_member_can_abandon
import androidx.compose.material3.BottomAppBar
@@ -306,6 +307,7 @@ fun DkgRitualScreen(
adminGroupBlockedOn = dkgRitualUIState.adminGroupBlockedOn,
keyStateSession = dkgRitualUIState.keyStateSession,
isKeyStateSigned = dkgRitualUIState.isKeyStateSigned,
isRoomCreated = dkgRitualUIState.isRoomCreated,
parentChatRoomId = dkgRitualUIState.parentChatRoomId,
isCertified = dkgRitualUIState.isCertified,
certificateSession = dkgRitualUIState.certificateSession,
@@ -481,6 +483,7 @@ private fun RitualProgress(
adminGroupBlockedOn: List<String>,
keyStateSession: FrostSigningSession?,
isKeyStateSigned: Boolean,
isRoomCreated: Boolean,
parentChatRoomId: String?,
isCertified: Boolean,
certificateSession: FrostSigningSession?,
@@ -745,11 +748,28 @@ private fun RitualProgress(
)
}
// Offered to whoever ran the ceremony. Any member's device could
// derive the same room id and create it, but one of them has to go
// first, and the coordinator is the member the group already watched
// do the work.
if (session.isCoordinator()) {
// The coordinator's device makes the room on its own once the group
// has signed (docs/automatic-key-ceremony.md, Phase 6), so the rung
// usually ends here: a way in, for anyone the room has reached. The
// same action as creating it -- an existing room is opened.
if (isRoomCreated) {
Button(
onClick = { onCreateAdminGroup() },
enabled = !isActionPending,
modifier = Modifier.fillMaxWidth()
) {
Icon(Icons.Default.Groups, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.space100))
Text(text = stringResource(Res.string.open_the_room))
}
}
// Offered to whoever ran the ceremony, as the way to retry what the
// device did not manage on its own. Any member's device could derive
// the same room id and create it, but one of them has to go first,
// and the coordinator is the member the group already watched do
// the work.
if (session.isCoordinator() && !isRoomCreated) {
// Nothing is created until every member's key package is in
// hand, so this is the whole reason there is no room yet.
if (adminGroupBlockedOn.isNotEmpty()) {
@@ -41,6 +41,9 @@ import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import mobi.giza.compose.database.model.DkgSession
@@ -50,6 +53,7 @@ import mobi.giza.compose.database.model.intermdiate.LocalFrostSigningSession
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlin.time.Instant
import mobi.giza.compose.managers.CeremonyFollowThrough
/**
* Watches one ChillDKG ritual, and the steps that follow it.
@@ -156,13 +160,22 @@ class DkgRitualViewModel(
.distinctUntilChanged()
.flatMapLatest { (sessionId, parent, key) -> ceremonyParts(sessionId, parent, key) }
// Which rooms this member is in, so the ladder can tell a room the
// coordinator's device made on its own from one still to be made. Starts
// empty: a repository with nothing to say must not hold the screen back.
val roomIds = flow { emitAll(chatRepository.observeChatRoomListByPublicKey(activeUserPublicKey)) }
.map { rooms -> rooms.map { it.chatRoom.id }.toSet() }
.onStart { emit(emptySet()) }
.distinctUntilChanged()
return combine(
sessions,
parts,
keyStateSession,
adminGroupBlockedOn,
) { session, ceremony, keyState, blockedOn ->
Snapshot(session, ceremony, keyState, blockedOn)
roomIds,
) { session, ceremony, keyState, blockedOn, rooms ->
Snapshot(session, ceremony, keyState, blockedOn, rooms)
}
// The parts lag the session by one emission when the ceremony changes;
// a state that drew one ceremony's counts under another's name is the
@@ -193,6 +206,9 @@ class DkgRitualViewModel(
isCertified = ceremony.isCertified,
certificateSession = ceremony.certificateSession,
lastProgressAt = ceremony.lastProgressAt,
isRoomCreated = session.thresholdPublicKey
?.let { runCatching { SharedKeyDerivation.marmotGroupId(it) }.getOrNull() }
?.let { it in snapshot.roomIds } == true,
)
}
}
@@ -297,6 +313,7 @@ class DkgRitualViewModel(
val ceremony: CeremonyParts,
val keyStateSession: FrostSigningSession?,
val adminGroupBlockedOn: List<String>,
val roomIds: Set<String>,
)
/**
@@ -533,10 +550,12 @@ class DkgRitualViewModel(
// own to be given. Either way the bare name goes down and
// `MarmotGroupCreation` puts it under `MarmotGroupName`, so a NIP-17 room
// called `Ekklesia` stands up a Marmot room called `#Ekklesia`.
// The same name and description the coordinator's device uses when it
// creates the room on its own -- see `CeremonyFollowThrough` -- so the two
// ways of making it cannot make two different rooms.
val subgroupParent = loaded.parentChatRoomId
val name = session.subject
?: if (subgroupParent != null) "Subgroup" else "Group"
val name = CeremonyFollowThrough.roomName(session)
isActionPending.value = true
adminGroupBlockedOn.value = emptyList()
@@ -545,11 +564,7 @@ class DkgRitualViewModel(
val outcome = chatRepository.createMarmotGroup(
groupId = groupId,
name = name,
purpose = if (subgroupParent != null) {
"A subgroup of the group that certified it."
} else {
"Admins of ${session.subject ?: "the group"}."
},
purpose = CeremonyFollowThrough.roomPurpose(session),
adminPublicKeys = members,
userPublicKey = activeUserPublicKey,
keyPair = keyPair,
@@ -251,6 +251,19 @@ class SynchronizationViewModel(
// belongs here for the same reason the pumps do: it needs the
// active wallet's key pair, and a wallet switch must tear it down.
launch(Dispatchers.IO) { liveSubscriptionManager.observe(keyPair) }
// A key ceremony this profile opened, taken from a key to a
// working room without anybody pressing a button: the key
// state proposed, a subgroup's certificate asked for, the
// room created. Here for the reason the live subscription
// is -- it needs the active key pair and must stop with it.
// docs/automatic-key-ceremony.md, Phase 6.
launch(Dispatchers.IO) {
runCatching { chatRepository.followThroughCeremonies(keyPair) }
.onFailure {
if (it is CancellationException) throw it
logger.e("Following key ceremonies through stopped", it)
}
}
}
}
}
@@ -88,6 +88,12 @@ sealed interface DkgRitualUIState {
* What [stalledSince] dates a stall from.
*/
val lastProgressAt: Instant? = null,
/**
* Whether the room this ceremony's key derives is on this device yet.
* The coordinator's device creates it without being asked, so the ladder's
* last rung is usually a way into the room rather than a button to make it.
*/
val isRoomCreated: Boolean = false,
/**
* The session asking the parent to certify, while it is running.
*
@@ -0,0 +1,261 @@
package mobi.giza.compose.managers
import androidx.room3.Room
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.builder.getRoomDatabase
import mobi.giza.compose.database.model.DkgSession
import mobi.giza.compose.database.model.GroupSignedEvent
import mobi.giza.compose.database.model.types.DkgApprovalStep
import mobi.giza.compose.database.model.types.DkgRitualStage
import mobi.giza.compose.database.model.types.FrostSigningStage
import mobi.giza.compose.managers.GroupFixtures.keyMaterial
import mobi.giza.compose.managers.GroupFixtures.owner
import mobi.giza.compose.managers.GroupFixtures.roomOf
import mobi.giza.compose.managers.GroupFixtures.thresholdKeyOf
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
import mobi.giza.compose.repository.ChatRepository
/**
* A finished ceremony taken on to a working room by the coordinator's device, with
* nobody pressing anything -- docs/automatic-key-ceremony.md, Phase 6.
*
* The room itself is created through the repository, which is faked here: what
* `MarmotGroupCreation` does with a call is its own test's business, and what this
* covers is that the call is made, once, with the right room and the right admins,
* and only when the group has signed what the room signs with.
*/
class CeremonyFollowThroughJvmTest {
private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
@AfterTest
fun closeDb() = db.close()
private val alice = KeyPair().pubKey.toHexKey()
private val bob = KeyPair().pubKey.toHexKey()
/** The room creations asked for, and what the next one answers. */
private val created = mutableListOf<Pair<String, Set<HexKey>>>()
private var outcome: (String) -> MarmotGroupCreation.Outcome = { MarmotGroupCreation.Outcome.Failed("unset") }
private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY {
override suspend fun createMarmotGroup(
groupId: String,
name: String,
purpose: String,
adminPublicKeys: Set<HexKey>,
userPublicKey: HexKey,
keyPair: KeyPair,
path: List<Long>,
parentChatRoomId: HexKey?,
): MarmotGroupCreation.Outcome {
created += groupId to adminPublicKeys
return outcome(groupId)
}
}
private val material = keyMaterial("5eed0000000000000000000000000000000000000000000000000000000000e5")
private val ceremonyRoomId = "ce1e".repeat(16)
/** A ceremony this device coordinated, finished, with [material]'s key. */
private suspend fun finishedCeremony(): DkgSession {
GroupFixtures.seedRoom(db, ceremonyRoomId, subject = "Checkers")
val session = DkgSession(
id = "finished-ceremony",
chatRoomId = ceremonyRoomId,
coordinatorPublicKey = owner,
userPublicKey = owner,
threshold = 2,
participantCount = 3,
participantPublicKeys = DkgSession.formatParticipants(setOf(owner, alice, bob)),
subject = "Checkers",
stage = DkgRitualStage.COMPLETE,
hostPublicKey = owner,
round1Random = "aa".repeat(32),
round2AuxRandom = "bb".repeat(32),
thresholdPublicKey = thresholdKeyOf(material),
secretShare = "cc".repeat(32),
)
db.dkgSessionDao().upsert(session)
return session
}
/** The group's signature on what [material]'s room signs with, on file. */
private suspend fun signKeyState(session: DkgSession) {
val event = GroupFixtures.signedAsRoom(
material = material,
kind = GroupKeyStateEvent.KIND,
tags = GroupKeyStateEvent.assembleTags(chatRoomId = roomOf(material), dkgSessionId = session.id),
content = thresholdKeyOf(material),
)
db.groupSignedEventDao().record(
GroupSignedEvent.fromEvent(
event = event,
chatRoomId = ceremonyRoomId,
derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path),
)
)
}
private suspend fun next(session: DkgSession, database: GizaDatabase = db) =
CeremonyFollowThrough.takeNextStep(database, chatRepository, session, KeyPair())
/**
* A real ceremony, run across devices: the coordinator's device asks the group
* to sign its key state as soon as it has a key, and then waits. The members'
* devices propose nothing.
*/
@Test
fun `the coordinator's device asks the group to sign the key state`(): Unit = runBlocking {
CeremonyNetwork.nip17(size = 3).use { network ->
val session = network.propose(threshold = 2)
network.deliverUntilQuiet()
network.devices.drop(1).forEach { network.approve(it, session.id, DkgApprovalStep.HOST_KEY) }
network.deliverUntilQuiet()
val coordinator = network.coordinator
val finished = assertNotNull(network.session(coordinator, session.id))
assertEquals(DkgRitualStage.COMPLETE, finished.stage)
assertEquals(CeremonyFollowThrough.Step.Proposed("key state"), next(finished, coordinator.db))
assertEquals(CeremonyFollowThrough.Step.Waiting, next(finished, coordinator.db), "and asks once")
assertEquals(1, keyStateSessions(coordinator.db, network.roomId, session.id).size)
network.devices.drop(1).forEach { member ->
val theirs = assertNotNull(network.session(member, session.id))
assertEquals(CeremonyFollowThrough.Step.NothingToDo, next(theirs, member.db))
assertTrue(keyStateSessions(member.db, network.roomId, session.id).isEmpty())
}
}
}
/** A refusal is the group's answer; asking again on its own would ask on a loop. */
@Test
fun `a key state the group did not sign is not asked for again`(): Unit = runBlocking {
CeremonyNetwork.nip17(size = 3).use { network ->
val session = network.propose(threshold = 2)
network.deliverUntilQuiet()
network.devices.drop(1).forEach { network.approve(it, session.id, DkgApprovalStep.HOST_KEY) }
network.deliverUntilQuiet()
val coordinator = network.coordinator
val finished = assertNotNull(network.session(coordinator, session.id))
next(finished, coordinator.db)
val asked = keyStateSessions(coordinator.db, network.roomId, session.id).single()
coordinator.db.frostSigningSessionDao().upsert(asked.copy(stage = FrostSigningStage.FAILED))
assertIs<CeremonyFollowThrough.Step.Stuck>(next(finished, coordinator.db))
assertEquals(1, keyStateSessions(coordinator.db, network.roomId, session.id).size)
}
}
@Test
fun `once the key state is signed the room is created with the ceremony's members`(): Unit =
runBlocking {
val session = finishedCeremony()
signKeyState(session)
outcome = { MarmotGroupCreation.Outcome.Failed("not needed") }
next(session)
assertEquals(listOf(roomOf(material) to setOf(owner, alice, bob)), created)
}
@Test
fun `a room is not created before the group has signed`(): Unit = runBlocking {
val session = finishedCeremony()
// Nothing signed: it asks the group for the key state, or fails trying for
// want of the messages a real ceremony leaves -- either way, no room.
runCatching { next(session) }
assertTrue(created.isEmpty())
}
@Test
fun `a room blocked on key packages says on whom`(): Unit = runBlocking {
val session = finishedCeremony()
signKeyState(session)
outcome = { MarmotGroupCreation.Outcome.BlockedOn(listOf(bob)) }
assertEquals(CeremonyFollowThrough.Step.BlockedOn(listOf(bob)), next(session))
}
@Test
fun `a room that exists is left alone`(): Unit = runBlocking {
val session = finishedCeremony()
signKeyState(session)
GroupFixtures.seedRoom(db, roomOf(material))
assertEquals(CeremonyFollowThrough.Step.NothingToDo, next(session))
assertTrue(created.isEmpty())
}
/**
* A subgroup's room needs its parent's certificate before its key state can
* even be proposed, so that is asked for first -- and then the parent's
* quorum decides, which nothing here does for them.
*/
@Test
fun `a subgroup asks its parent to certify it first`(): Unit = runBlocking {
val parentMaterial = keyMaterial("9a7e0000000000000000000000000000000000000000000000000000000000f6")
val parentRoom = GroupFixtures.signingRoom(db, parentMaterial, members = listOf(alice, bob))
val parentRoomId = parentRoom.chatRoom.id
val session = DkgSession(
id = "subgroup-ceremony",
chatRoomId = parentRoomId,
coordinatorPublicKey = owner,
userPublicKey = owner,
threshold = 2,
participantCount = 3,
participantPublicKeys = DkgSession.formatParticipants(setOf(owner, alice, bob)),
subject = "Translation",
stage = DkgRitualStage.COMPLETE,
hostPublicKey = owner,
round1Random = "aa".repeat(32),
round2AuxRandom = "bb".repeat(32),
thresholdPublicKey = thresholdKeyOf(material),
secretShare = "dd".repeat(32),
parentChatRoomId = parentRoomId,
)
db.dkgSessionDao().upsert(session)
assertEquals(CeremonyFollowThrough.Step.Proposed("birth certificate"), next(session))
assertEquals(CeremonyFollowThrough.Step.Waiting, next(session), "and waits on the parent")
val certificates = sessionsCarrying(db, parentRoomId, SubgroupBirthCertificateEvent.KIND)
assertEquals(1, certificates.size)
assertTrue(keyStateSessions(db, parentRoomId, session.id).isEmpty(), "no key state before it")
assertTrue(created.isEmpty())
}
private suspend fun keyStateSessions(database: GizaDatabase, roomId: String, dkgSessionId: String) =
sessionsCarrying(database, roomId, GroupKeyStateEvent.KIND) {
GroupKeyStateEvent.parseDkgSessionId(it.tags) == dkgSessionId
}
private suspend fun sessionsCarrying(
database: GizaDatabase,
roomId: String,
kind: Int,
about: (Event) -> Boolean = { true },
) = database.frostSigningSessionDao().getSessionsForChatRoom(roomId).filter { session ->
database.frostSigningSessionDao().getItems(session.id).any { item ->
Event.fromJsonOrNull(item.unsignedEventJson)?.let { it.kind == kind && about(it) } == true
}
}
}