feat: a rotation's key state signs itself (rotate-shares-single-approval, Phase 5)

GroupKeyStateManager.vouchesFor refused every key state naming a share
generation (fc437d05), so each recipient was asked to sign the new
generation before anyone's old share was deleted. vouchesForGeneration
now accepts the one state a rotation this device completed implies: the
generation it signs with and holds a share of, the rotation named and
complete here, its own table's hash, the ids its roster retires, a
session at that generation, and the path and parent of the room's
signed state. Rule 7 becomes 'nothing signed at h or later'. A state
that binds an id to a new identity is still never vouched for.

Vouching was decided once, on the proposal's arrival, and the
coordinator proposes the moment its own certificate verifies -- often
before a recipient's. resumeAt, which the rotation already calls on
activation, now asks again; resumeVouched does the same from the sync
sweep for a state an older build left asking.

Tests: one approval each and the group signs generation 1 and wipes the
old shares; a state heard before the certificate is vouched for once it
arrives; each rule broken on its own leaves the state asked; a withheld
member does not vouch; the sweep answers a state left asking, once. The
cutover test holds the proposal to keep checking that nothing is wiped
before the signature. jvmTest 1245/1245.

One earlier full run died on a SIGSEGV in SQLite's native code, in a
background key-package write unrelated to this change; the rerun was
clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-20 01:06:39 +02:00
1 parent 69871c68a5
commit 46eb23b777
5 files changed
+264 -35

No files matched your search

@@ -83,6 +83,13 @@ interface FrostSigningSessionDao {
suspend fun getSessionsForChatRoom(chatRoomId: String): List<FrostSigningSession>
/** Sessions of one key still running: what a share rotation has to end. */
/** Sessions still running that [userPublicKey]'s owner has neither approved nor declined. */
@Query(
"SELECT * FROM FrostSigningSession WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED') " +
"AND signApprovedAt IS NULL AND signDeclinedAt IS NULL ORDER BY createdAt ASC"
)
suspend fun getOpenUnansweredSessionsFor(userPublicKey: HexKey): List<FrostSigningSession>
@Query("SELECT * FROM FrostSigningSession WHERE dkgSessionId = :dkgSessionId AND stage NOT IN ('COMPLETE', 'FAILED')")
suspend fun getOpenSessionsForKey(dkgSessionId: String): List<FrostSigningSession>
@@ -59,6 +59,7 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import mobi.giza.compose.managers.ChillDkgRitualManager
import mobi.giza.compose.managers.FrostSigningManager
import mobi.giza.compose.managers.ShareRefreshManager
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import mobi.giza.compose.identity.Identity
@@ -154,6 +155,9 @@ class DatabaseNostrRepository(
database = database,
userPublicKey = userPublicKey,
nostrPrivateKey = privateKey
) + FrostSigningManager.resumeVouched(
database = database,
userPublicKey = userPublicKey,
)
}
}
@@ -441,14 +441,14 @@ object FrostSigningManager {
}
// The other answer a device can give on its owner's behalf, and only to one
// question: what the room a ceremony it finished signs with. For that there
// is exactly one true statement, and `vouchesFor` signs nothing else --
// any other proposal, a key state included, is asked about as before.
// docs/automatic-key-ceremony.md, Phase 7.
if (FrostSigningEvents.isProposal(innerEvent.kind) && signsAsItsOwnKeyState(database, session)) {
logger.i("Session ${session.id} is the key state of a ceremony this device finished; signing")
update(database, session) { it.copy(signApprovedAt = Clock.System.now()) }
}
// question: what the room a ceremony it finished signs with, or a rotation
// it completed. For that there is exactly one true statement, and
// `vouchesFor` signs nothing else -- any other proposal, a key state
// included, is asked about as before. docs/automatic-key-ceremony.md,
// Phase 7, and docs/rotate-shares-single-approval.md, Phase 5.
// A rotation's key state can arrive before the rotation completes here, and
// is asked again then ([resumeAt]).
if (FrostSigningEvents.isProposal(innerEvent.kind)) approveIfVouched(database, session)
if (session.stage == FrostSigningStage.FAILED) {
logger.i("Session $sessionId already failed; ignoring kind ${innerEvent.kind}")
@@ -1941,11 +1941,45 @@ object FrostSigningManager {
* [generation], which has just become signable here. A session proposed while
* this device still waited on that generation's certificate stops at the share
* it did not yet have; nothing else would wake it until the next message.
*
* That includes the generation's own key state, which the coordinator proposes
* the moment its certificate verifies -- often before this device's. On arrival
* this device could not vouch for it, since the rotation it names was not yet
* complete here; now it can, so it asks again rather than leaving the owner a
* question the device can answer (docs/rotate-shares-single-approval.md, Phase 5).
*/
suspend fun resumeAt(database: GizaDatabase, localChatRoom: LocalChatRoom, dkgSessionId: String, generation: Int) {
database.frostSigningSessionDao().getOpenSessionsForKey(dkgSessionId)
.filter { (it.generation ?: 0) == generation && it.chatRoomId == localChatRoom.chatRoom.id }
.forEach { advance(database, localChatRoom, it.id) }
.forEach { session ->
approveIfVouched(database, session)
advance(database, localChatRoom, session.id)
}
}
/**
* Signs every open key state this user's device can now vouch for and has not
* been answered about -- what a build that asked about them left waiting. Run
* by the sweep beside the rituals' (docs/rotate-shares-single-approval.md,
* Phase 5). Returns how many it approved.
*/
suspend fun resumeVouched(database: GizaDatabase, userPublicKey: HexKey): Int {
var approved = 0
database.frostSigningSessionDao().getOpenUnansweredSessionsFor(userPublicKey).forEach { session ->
if (!approveIfVouched(database, session)) return@forEach
val localChatRoom = database.chatRoomDao().findChatRoomById(session.chatRoomId) ?: return@forEach
advance(database, localChatRoom, session.id)
approved += 1
}
return approved
}
/** Approves [session] on its owner's behalf when [signsAsItsOwnKeyState] says this device can. */
private suspend fun approveIfVouched(database: GizaDatabase, session: FrostSigningSession): Boolean {
if (!signsAsItsOwnKeyState(database, session)) return false
logger.i("Session ${session.id} is a key state this device can vouch for; signing")
update(database, session) { it.copy(signApprovedAt = Clock.System.now()) }
return true
}
/**
@@ -13,6 +13,7 @@ import mobi.giza.compose.database.model.types.DkgRitualStage
import mobi.giza.compose.database.model.GroupKeyState
import mobi.giza.compose.database.model.GroupSignedEvent
import mobi.giza.compose.database.model.intermdiate.LocalChatRoom
import mobi.giza.compose.database.model.types.ShareRefreshStage
import mobi.giza.compose.database.model.types.ShareStanding
import mobi.giza.compose.nostr.frost.GroupKeyStateEvent
import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent
@@ -616,11 +617,13 @@ object GroupKeyStateManager {
* [claimFrom] checks the derivation, the same check [stateFrom] makes;
* 6. claiming the parent the ceremony was run for, or none for a group's own,
* with a certificate that parent's quorum signed -- [claimFrom] again;
* 7. with no state for that room already signed on this device;
* 8. and naming no share generation and no member binding. A rotation's key
* state, or one binding an id to a new identity, says more than the
* ceremony did -- which shares the group now signs with, who holds an id --
* and that is its owner's to agree to (docs/frost-share-refresh.md).
* 7. with no state for that room already signed on this device -- or, for a
* state naming share generation `h`, none signed at `h` or later;
* 8. and naming no share generation and no member binding -- **unless** it
* is the one key state a rotation this device completed implies
* ([vouchesForGeneration], docs/rotate-shares-single-approval.md, Phase 5).
* A state binding an id to a new identity is never vouched for: who holds
* an id is governance, not arithmetic, and its owner decides it.
*/
suspend fun vouchesFor(
database: GizaDatabase,
@@ -652,13 +655,72 @@ object GroupKeyStateManager {
// 6's parent
if (claim.parentChatRoomId != key.parentChatRoomId) return false
// 7
val signed = stateAmong(database.groupSignedEventDao().getByKind(GroupKeyStateEvent.KIND), claim.chatRoomId)
if (signed != null) return false
val generation = claim.generation
if (generation == null) {
// 7, for a ceremony's state
if (signed != null) return false
// 8: a binding is never vouched for
return claim.memberBindings == null
}
// 7, for a rotation's
if (signed != null && (signed.generation ?: 0) >= generation) return false
// 8
if (claim.generation != null || claim.memberBindings != null) return false
return vouchesForGeneration(database, session, key, unsigned, claim, signed)
}
/**
* Whether a key state naming share generation `h` is exactly the one a
* rotation this device completed implies (docs/rotate-shares-single-approval.md,
* Phase 5). For such a rotation every fact the state names is one this device
* holds and has checked against the certificate: the table, the rotation, who
* it retired. So there is one true statement, and a person shown it has
* nothing to add. Every one of these has to hold:
*
* - generation `h` is the one this device signs with, and it holds a share
* of it -- a device withheld from `h` neither signs at `h` nor vouches for
* a table it did not help make;
* - the rotation that made `h` is the one the state names, and it is
* complete here;
* - the state's public-share hash is this device's table at `h`;
* - the ids it retires are the ids this device's roster at `h` retires;
* - it binds no id to a new identity;
* - the signing session is at `h`;
* - its path and parent are the ones the room's signed state already names,
* when there is one -- [proposeGeneration] copies them from it.
*/
private suspend fun vouchesForGeneration(
database: GizaDatabase,
session: FrostSigningSession,
key: DkgSession,
unsigned: Event,
claim: GroupKeyState,
signed: GroupKeyState?,
): Boolean {
val generation = claim.generation ?: return false
val tags = GroupKeyStateEvent.parseShareGeneration(unsigned.tags).getOrNull() ?: return false
if (tags.bindings.isNotEmpty() || claim.memberBindings != null) return false
if ((session.generation ?: 0) != generation) return false
val active = ShareGenerations.active(database, key)
if (active.generation != generation || active.secretShare == null) return false
val publicShares = active.publicShares ?: return false
if (ShareGenerations.publicSharesHash(publicShares) != claim.publicSharesHash) return false
if (tags.retiredIds.sorted() != active.roster.filter { it.standing == ShareStanding.RETIRED }.map { it.participantId }.sorted()) return false
val refreshId = tags.refreshId ?: return false
val row = database.keyShareDao().getGeneration(key.id, generation) ?: return false
if (row.refreshSessionId != refreshId) return false
val refresh = database.shareRefreshDao().getSessionById(refreshId) ?: return false
if (refresh.stage != ShareRefreshStage.COMPLETE || refresh.dkgSessionId != key.id || refresh.baseGeneration + 1 != generation) return false
if (signed != null) {
if (claim.derivationPath != signed.derivationPath) return false
if (claim.parentChatRoomId != signed.parentChatRoomId) return false
val certificate = { json: String? -> json?.let { Event.fromJsonOrNull(it)?.id } }
if (certificate(claim.birthCertificateJson) != certificate(signed.birthCertificateJson)) return false
}
return true
}
@@ -493,13 +493,13 @@ class ShareRefreshRitualJvmTest {
}
/**
* What a recipient is asked before the old shares are deleted: to take part,
* and -- until Phase 5 -- to sign the new generation's key state. The
* proposer is asked nothing: proposing was taking part, its device proposes
* the key state, and a proposer's signature is its proposal.
* The whole of the change: a recipient is asked one thing before the old
* shares are deleted -- to take part. Storing the new share and signing the
* new generation's key state follow from it. The proposer is asked nothing:
* proposing was taking part.
*/
@Test
fun `a recipient is asked to take part and to sign the new key state`() = runBlocking<Unit> {
fun `a recipient is asked only to take part`() = runBlocking<Unit> {
val group = Group(3, 2)
val all = devicesFor(group)
val refresh = propose(all[0])
@@ -508,7 +508,7 @@ class ShareRefreshRitualJvmTest {
val rotation = listOf(Ask.Rotation(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.DEAL))
assertEquals(emptyList(), asks[0], "the proposer, whose proposal was its answer")
all.drop(1).forEach { device -> assertEquals(rotation + Ask.KeyState, asks[device.index], "device ${device.index}") }
all.drop(1).forEach { device -> assertEquals(rotation, asks[device.index], "device ${device.index}") }
all.forEach { device ->
assertEquals(1, device.db.groupKeyStateDao().getByChatRoomId(group.roomId)?.generation, "device ${device.index}")
assertNull(device.key().secretShare, "device ${device.index} kept the old share")
@@ -516,29 +516,147 @@ class ShareRefreshRitualJvmTest {
}
/**
* Today's key state, pinned: a rotation complete on every device still waits
* on each owner but the proposer's to sign the new generation, and until a quorum has, every
* device keeps the share it was meant to delete.
* A completed rotation's key state is the one statement its recipients'
* devices can vouch for, so they sign it with nobody asked, and every device
* deletes the share it was meant to delete.
*/
@Test
fun `a completed rotation waits on its owners to sign the new key state`() = runBlocking<Unit> {
fun `a completed rotation signs its new key state and the old shares go, with nobody asked`() = runBlocking<Unit> {
val group = Group(3, 2)
val all = devicesFor(group)
val refresh = propose(all[0])
pump(all)
approveAll(all, refresh.id)
all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
pump(all)
all.forEach { assertEquals(ShareRefreshStage.COMPLETE, it.refresh(refresh.id)?.stage) }
all.drop(1).forEach { device ->
all.forEach { device ->
assertEquals(ShareRefreshStage.COMPLETE, device.refresh(refresh.id)?.stage)
assertEquals(1, device.db.groupKeyStateDao().getByChatRoomId(group.roomId)?.generation, "device ${device.index}")
assertNull(device.key().secretShare, "device ${device.index} kept the old share")
val signing = device.db.frostSigningSessionDao()
val keyState = signing.getSessionsForChatRoom(group.roomId).single()
assertEquals(1, keyState.generation)
assertTrue(FrostSigningManager.isAwaitingApproval(keyState, signing.getItems(keyState.id)), "device ${device.index} was not asked")
assertNotNull(device.key().secretShare, "device ${device.index} deleted before the group signed")
assertTrue(signing.getSessionsForChatRoom(group.roomId).none { FrostSigningManager.isAwaitingApproval(it, signing.getItems(it.id)) }, "device ${device.index} was asked")
}
}
/**
* The coordinator proposes the key state the moment its own certificate
* verifies, so a recipient can hear the proposal first. It cannot vouch for a
* rotation not yet complete here; once the certificate arrives, it can, and
* does, without its owner.
*/
@Test
fun `a key state heard before the certificate is vouched for once the certificate arrives`() = runBlocking<Unit> {
val group = Group(3, 2)
val all = devicesFor(group)
val refresh = propose(all[0])
pump(all)
all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
pump(all, hold = { it.kind == ShareRefreshEvents.CERTIFICATE })
val member = all[1]
val signing = member.db.frostSigningSessionDao()
val keyState = signing.getSessionsForChatRoom(group.roomId).single()
assertEquals(1, keyState.generation)
assertNull(keyState.signApprovedAt, "not vouched for before the rotation completes here")
assertTrue(member.refresh(refresh.id)!!.stage != ShareRefreshStage.COMPLETE)
pump(all)
assertNotNull(signing.getSessionById(keyState.id)?.signApprovedAt, "vouched for once it completes")
all.forEach { device ->
assertEquals(1, device.db.groupKeyStateDao().getByChatRoomId(group.roomId)?.generation, "device ${device.index}")
assertNull(device.key().secretShare, "device ${device.index}")
}
}
/** Each rule, broken on its own, leaves a rotation's key state with the member. */
@Test
fun `a device vouches for its rotation's key state and nothing else`() = runBlocking<Unit> {
val group = Group(3, 2)
val all = devicesFor(group)
val refresh = propose(all[0])
pump(all)
// Every device completes the rotation; the key state is proposed, and held.
all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
pump(all, hold = { FrostSigningEvents.isProposal(it.kind) })
val (coordinator, member) = all
assertEquals(ShareRefreshStage.COMPLETE, member.refresh(refresh.id)?.stage)
val proposed = coordinator.db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).single()
val session = proposed.copy(userPublicKey = member.publicKey, signApprovedAt = null)
val item = coordinator.db.frostSigningSessionDao().getItems(proposed.id).single()
val event = Event.fromJson(item.unsignedEventJson)
fun with(tags: Array<Array<String>>) = listOf(item.copy(unsignedEventJson = Event(event.id, event.pubKey, event.createdAt, event.kind, tags, event.content, event.sig).toJson()))
fun replacing(name: String, value: String) = with(event.tags.map { if (it.firstOrNull() == name) arrayOf(name, value) else it }.toTypedArray())
suspend fun vouches(on: Device = member, s: mobi.giza.compose.database.model.FrostSigningSession = session, items: List<mobi.giza.compose.database.model.FrostSigningItem> = listOf(item)) =
GroupKeyStateManager.vouchesFor(on.db, s.copy(userPublicKey = on.publicKey), items)
assertTrue(vouches(), "the one true statement")
assertTrue(!vouches(items = replacing("frost_pubshares", "ab".repeat(32))), "another table")
assertTrue(!vouches(items = replacing("frost_refresh", "cd".repeat(32))), "another rotation")
assertTrue(!vouches(items = with(event.tags + arrayOf("frost_retired", group.idOf[2].toString()))), "retiring someone this rotation did not")
val binding = mobi.giza.compose.nostr.frost.GroupKeyStateEvent.MemberBinding(group.idOf[2], KeyPair().pubKey.toHexKey(), group.hostKeys[0])
assertTrue(!vouches(items = with(event.tags + arrayOf("frost_member", binding.encode()))), "binding an id to a new identity")
assertTrue(!vouches(s = session.copy(generation = 0)), "a session at another generation")
assertTrue(!vouches(items = replacing("frost_generation", "2")), "a generation this device does not sign with")
assertTrue(!vouches(s = session.copy(derivationPath = SharedKeyDerivation.formatPath(listOf(9420L, 0L, 1L)))), "at another path")
// A rotation not complete here: the same statement, from a device that has not finished.
member.db.shareRefreshDao().upsert(member.refresh(refresh.id)!!.copy(stage = ShareRefreshStage.COLLECTING_ROUND_2))
assertTrue(!vouches(), "a rotation that is not complete here")
member.db.shareRefreshDao().upsert(member.refresh(refresh.id)!!.copy(stage = ShareRefreshStage.COMPLETE))
// Once the group has signed it, the next statement at the same generation is not the one true one.
all.forEach { it.received.clear() }
pump(all)
assertEquals(1, member.db.groupKeyStateDao().getByChatRoomId(group.roomId)?.generation)
assertTrue(!vouches(), "a room already holding a state at this generation")
}
/** A member withheld from the rotation holds no share of it, and vouches for nothing it did not help make. */
@Test
fun `a withheld member does not vouch for the new key state`() = runBlocking<Unit> {
val group = Group(3, 2)
val all = devicesFor(group)
val withheld = all[2]
val refresh = propose(all[0], mapOf(group.idOf[2] to ShareStanding.STALE))
pump(all)
all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
pump(all, hold = { FrostSigningEvents.isProposal(it.kind) })
assertEquals(ShareRefreshStage.COMPLETE, withheld.refresh(refresh.id)?.stage)
val proposed = all[0].db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).single()
val items = all[0].db.frostSigningSessionDao().getItems(proposed.id)
assertTrue(GroupKeyStateManager.vouchesFor(all[1].db, proposed.copy(userPublicKey = all[1].publicKey), items), "a recipient does")
assertTrue(!GroupKeyStateManager.vouchesFor(withheld.db, proposed.copy(userPublicKey = withheld.publicKey), items), "the withheld member does not")
}
/** A key state an older build left asking is answered by the sweep, once. */
@Test
fun `a key state left asking by an older build is signed from the sweep`() = runBlocking<Unit> {
val group = Group(3, 2)
val all = devicesFor(group)
val refresh = propose(all[0])
pump(all)
all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
pump(all, hold = { FrostSigningEvents.isProposal(it.kind) })
// The proposal arrives at a member as an older build filed it: stored, asked, not vouched for.
val member = all[1]
val proposal = outbox(all[0]).first { FrostSigningEvents.isProposal(it.kind) }
member.received += proposal.id
member.db.marmotInnerEventDao().upsert(proposal.copy(chatRoomId = group.roomId))
val shareRefresh = member.refresh(refresh.id)!!
member.db.shareRefreshDao().upsert(shareRefresh.copy(stage = ShareRefreshStage.COLLECTING_ROUND_2))
FrostSigningManager.processSigningPayload(member.db, member.room, Event(proposal.id, proposal.publicKey, proposal.createdAt.epochSeconds, proposal.kind, proposal.tags, proposal.content, ""), member.publicKey)
member.db.shareRefreshDao().upsert(shareRefresh)
val filed = member.db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).single()
assertNull(filed.signApprovedAt, "filed and asked, as the older build left it")
assertEquals(1, FrostSigningManager.resumeVouched(member.db, member.publicKey))
assertNotNull(member.db.frostSigningSessionDao().getSessionById(filed.id)?.signApprovedAt)
assertEquals(0, FrostSigningManager.resumeVouched(member.db, member.publicKey), "once")
}
@Test
fun `a withheld member ends with the new table and no share, and declines to sign`() = runBlocking<Unit> {
val group = Group(3, 2)
@@ -648,11 +766,15 @@ class ShareRefreshRitualJvmTest {
val all = devicesFor(group)
val refresh = propose(all[0])
pump(all)
approveAll(all, refresh.id)
// The key state is held on its way, so the rotation completes with nothing signed yet.
all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) }
pump(all, hold = { FrostSigningEvents.isProposal(it.kind) })
all.forEach { assertEquals(ShareRefreshStage.COMPLETE, it.refresh(refresh.id)?.stage) }
// Not yet: the old share stays until the new ones have signed something.
all.forEach { assertNotNull(it.key().secretShare, "device ${it.index} deleted before the group signed") }
pump(all)
approveSigning(all)
all.forEach { device ->