From 159ae402dbfadf0390aef3ab4890767d6d4619a0 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:42:59 +0200 Subject: [PATCH] feat: a rotation waits for the group to sign the last one (Phase 1) A rotation is over when the group has signed the key state at the new generation, not when its refresh completes. ShareRefreshManager.rotationHold says why this device must not propose one now: a refresh still running, a key state the group has not signed (or a key-state proposal still open here, unless this device declined it), or a device behind the group. proposeRefresh, and so proposeWithout, refuses on it. The recovery walk test ran three rotations back to back with nothing signed between; it signs each key state now. ShareRefreshRitualJvmTest 22/22. Co-Authored-By: Claude Opus 5.5 --- .../giza/compose/managers/RotationHold.kt | 29 +++++ .../compose/managers/ShareRefreshManager.kt | 50 ++++++++ .../managers/ShareRefreshRitualJvmTest.kt | 112 ++++++++++++++++++ 3 files changed, 191 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt new file mode 100644 index 00000000..f7047f3a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/RotationHold.kt @@ -0,0 +1,29 @@ +package mobi.giza.compose.managers + +/** + * Why this device must not propose a share rotation now + * (docs/rotation-waits-for-key-state.md). [ShareRefreshManager.rotationHold] + * answers it; [reason] is the refusal the propose paths give. + */ +sealed interface RotationHold { + val reason: String + + /** A refresh of the key is still running here. */ + data class Running(val refreshId: String) : RotationHold { + override val reason get() = "a rotation is still running" + } + + /** + * The group has not signed the key state at [generation] -- the proof that + * the shares the last rotation dealt can sign -- or a key-state proposal is + * open, [signingSessionId] when this device holds it. + */ + data class AwaitingKeyState(val generation: Int, val signingSessionId: String?) : RotationHold { + override val reason get() = "the group has not yet signed the key state at generation $generation" + } + + /** The group signs at a generation this device has not reached: it missed a certificate. */ + data class Behind(val groupGeneration: Int, val localGeneration: Int) : RotationHold { + override val reason get() = "the group is at generation $groupGeneration and this device at $localGeneration" + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt index 2cc97bd7..fcbe2900 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -22,6 +22,7 @@ import kotlinx.coroutines.CancellationException import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ChatMessage import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.FrostSigningSession import mobi.giza.compose.database.model.KeyShareGeneration import mobi.giza.compose.database.model.KeyShareMember import mobi.giza.compose.database.model.MarmotInnerEvent @@ -36,6 +37,7 @@ import mobi.giza.compose.database.model.types.ShareRefreshStage import mobi.giza.compose.database.model.types.ShareStanding import mobi.giza.compose.ExperimentalFeatures import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.frost.GroupKeyStateEvent import mobi.giza.compose.nostr.frost.ShareRefreshEvents /** @@ -128,6 +130,7 @@ object ShareRefreshManager { require(isKeysRoom(database, localChatRoom, key)) { "${localChatRoom.chatRoom.id} is not the room key ${key.id} signs as" } running(database, key)?.let { return it } + rotationHold(database, localChatRoom, key)?.let { throw IllegalStateException("Cannot rotate yet: ${it.reason}") } val shares = ShareGenerations.active(database, key) requireNotNull(shares.secretShare) { "This device holds no share of generation ${shares.generation}" } @@ -203,6 +206,53 @@ object ShareRefreshManager { return proposeRefresh(database, localChatRoom, userPublicKey, nostrPrivateKey, key, mapOf(id to ShareStanding.RETIRED)) } + /** + * Why this device must not propose a rotation of [key] now, or null when it may + * (docs/rotation-waits-for-key-state.md). The Shares section and [proposeRefresh] + * both read this, so the button and the protocol cannot disagree. + * + * A rotation is not over when its refresh is: it is over when the group has + * signed the key state at the new generation, the first signature the new + * shares make and what every device waits on before deleting the old ones + * (D6). Rotating again before then stacks a second unproven generation on the + * first, and leaves the first one's key-state proposal to fail under its + * signers. + * + * Checked on the proposer's device only. A recipient a few seconds behind on + * the signature would refuse out loud and end a rotation that was fine. + */ + suspend fun rotationHold(database: GizaDatabase, localChatRoom: LocalChatRoom, key: DkgSession): RotationHold? { + running(database, key)?.let { return RotationHold.Running(it.id) } + + val active = ShareGenerations.active(database, key).generation + val signed = GroupKeyStateManager.keyStateFor(database, localChatRoom.chatRoom.id) + ?.takeIf { it.dkgSessionId == key.id } + ?.generation ?: 0 + if (signed > active) return RotationHold.Behind(groupGeneration = signed, localGeneration = active) + + val open = openKeyStateSession(database, key) + if (signed < active || open != null) return RotationHold.AwaitingKeyState(active, open?.id) + return null + } + + /** + * A key-state signing session of [key] still open on this device -- a + * rotation's, a rebind's, or the ceremony's first -- unless this device has + * declined it. A session fails only once enough members decline, so one this + * device has refused can sit open for as long as the others stay quiet; it + * does not hold this device's hand for that long. + */ + private suspend fun openKeyStateSession(database: GizaDatabase, key: DkgSession): FrostSigningSession? { + val dao = database.frostSigningSessionDao() + return dao.getOpenSessionsForKey(key.id) + .filter { it.signDeclinedAt == null } + .firstOrNull { session -> + dao.getItems(session.id).singleOrNull() + ?.let { Event.fromJsonOrNull(it.unsignedEventJson) } + ?.kind == GroupKeyStateEvent.KIND + } + } + /** A refresh of [key] still running on this device, if there is one. One at a time per key. */ private suspend fun running(database: GizaDatabase, key: DkgSession): ShareRefreshSession? = database.shareRefreshDao().getSessionsForKey(key.id).firstOrNull { diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt index a135d260..39694888 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -474,6 +474,116 @@ class ShareRefreshRitualJvmTest { assertTrue(error.message!!.contains("fewer than the 2 it takes to sign"), error.message) } + // ---- a rotation waits for the last one to be signed (docs/rotation-waits-for-key-state.md) ------------------- + + @Test + fun `the next rotation waits until the group has signed the last one`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val (alice, bob) = all + assertNull(ShareRefreshManager.rotationHold(alice.db, alice.room, alice.key()), "generation 0 waits on nothing") + + val first = propose(alice) + pump(all) + assertEquals(RotationHold.Running(first.id), ShareRefreshManager.rotationHold(bob.db, bob.room, bob.key())) + approveAll(all, first.id) + + // The refresh is complete and its key state is out for signatures: everyone waits. + all.forEach { device -> + val hold = ShareRefreshManager.rotationHold(device.db, device.room, device.key()) + assertTrue(hold is RotationHold.AwaitingKeyState && hold.generation == 1 && hold.signingSessionId != null, "device ${device.index}: $hold") + } + val refused = assertFailsWith { propose(bob) } + assertTrue(refused.message!!.contains("generation 1"), refused.message) + assertEquals(listOf(first.id), bob.db.shareRefreshDao().getSessionsForKey(ceremonyId).map { it.id }, "nothing new was opened") + + approveSigning(all) + all.forEach { assertNull(ShareRefreshManager.rotationHold(it.db, it.room, it.key()), "device ${it.index}") } + assertNotEquals(first.id, propose(bob).id) + } + + @Test + fun `rotating without a member waits as well`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val (alice, _, carol) = all + val first = propose(alice) + pump(all) + approveAll(all, first.id) + + val refused = assertFailsWith { + ShareRefreshManager.proposeWithout(alice.db, alice.room, alice.publicKey, alice.privateKey, carol.publicKey) + } + assertTrue(refused.message!!.contains("not yet signed"), refused.message) + } + + @Test + fun `a key state with nobody asking for it still holds the next rotation`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val first = propose(all[0]) + pump(all) + approveAll(all, first.id) + // The coordinator's key-state proposal failed, or its device went away. + all.forEach { device -> + device.db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).forEach { + device.db.frostSigningSessionDao().upsert(it.copy(stage = FrostSigningStage.FAILED)) + } + } + val hold = ShareRefreshManager.rotationHold(all[1].db, all[1].room, all[1].key()) + assertEquals(RotationHold.AwaitingKeyState(1, signingSessionId = null), hold) + } + + @Test + fun `a rebind waiting on signatures holds a rotation, until this device declines it`() = runBlocking { + // Four members, one left stale: three live signers of a 2-of-n key, so a + // single refusal leaves a session open rather than ending it. + val group = Group(4, 2) + val all = devicesFor(group) + val (alice, bob, carol) = all + val staleId = group.idOf[3] + val refresh = propose(alice, mapOf(staleId to ShareStanding.STALE)) + pump(all) + approveAll(all, refresh.id) + approveSigning(all) + assertNull(ShareRefreshManager.rotationHold(alice.db, alice.room, alice.key())) + + val daveKeys = KeyPair() + val daveHost = ChillDkgRitualManager.deriveHostPublicKey(daveKeys.privKey!!).value.toHex() + val rebind = GroupKeyStateManager.proposeRebind(alice.db, alice.room, alice.publicKey, alice.key(), staleId, daveKeys.pubKey.toHexKey(), daveHost) + pump(all) + + listOf(alice, bob, carol).forEach { device -> + assertEquals(RotationHold.AwaitingKeyState(1, rebind.id), ShareRefreshManager.rotationHold(device.db, device.room, device.key()), "device ${device.index}") + } + + // One refusal does not end it, so it sits open; it no longer holds Bob, who refused it. + FrostSigningManager.decline(bob.db, bob.room, rebind.id) + pump(all) + assertNotEquals(FrostSigningStage.FAILED, bob.db.frostSigningSessionDao().getSessionById(rebind.id)!!.stage) + assertNull(ShareRefreshManager.rotationHold(bob.db, bob.room, bob.key())) + assertEquals(RotationHold.AwaitingKeyState(1, rebind.id), ShareRefreshManager.rotationHold(carol.db, carol.room, carol.key())) + } + + @Test + fun `a device that missed the certificate cannot propose from the old generation`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val first = propose(all[0]) + pump(all) + approveAll(all, first.id) + approveSigning(all) + + // Alice on a second device that heard the group's signature but none of the refresh. + val late = device(group, 0) + val signed = assertNotNull(GroupKeyStateManager.signedEventFor(all[1].db, group.roomId)).toEvent() + assertNotNull(GroupKeyStateManager.record(late.db, group.roomId, signed)) + assertEquals(0, late.active().generation) + + assertEquals(RotationHold.Behind(groupGeneration = 1, localGeneration = 0), ShareRefreshManager.rotationHold(late.db, late.room, late.key())) + assertFailsWith { propose(late) } + } + // ---- Phase 10: re-enrollment ----------------------------------------------------------------------------------- /** Every helper approves every repair waiting on them. */ @@ -641,6 +751,8 @@ class ShareRefreshRitualJvmTest { val refresh = propose(all[round % 3]) pump(all) approveAll(all, refresh.id) + // The next rotation waits for this one's key state, and the old shares go. + approveSigning(all) } all.forEach { device -> assertEquals(3, device.active().generation)