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
}