From a25ff2e25322581b048855ed170b804e35c9abcb Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:37:49 +0200 Subject: [PATCH 01/23] docs: a rotation waits for the last one to be signed A plan to hold Rotate shares while the key state the previous rotation produced is still waiting on the group's signature, and to stop asking the proposer to approve their own rotation. Co-Authored-By: Claude Opus 5.5 --- docs/rotation-waits-for-key-state.md | 349 +++++++++++++++++++++++++++ 1 file changed, 349 insertions(+) create mode 100644 docs/rotation-waits-for-key-state.md diff --git a/docs/rotation-waits-for-key-state.md b/docs/rotation-waits-for-key-state.md new file mode 100644 index 00000000..324ca10e --- /dev/null +++ b/docs/rotation-waits-for-key-state.md @@ -0,0 +1,349 @@ +# A rotation waits for the last one to be signed + +A plan to hold the **Rotate shares** button until the group has signed the key state +the previous rotation produced, and to stop asking the person who proposed a rotation +to approve it. + +Read [frost-share-refresh.md](./frost-share-refresh.md) first, especially Phase 7's +approval gates, Phase 8 (the cutover) and D6 (when the old share is wiped). Read +[automatic-key-ceremony.md](./automatic-key-ceremony.md) as well. Its rule, "the device +asks its owner only for decisions the device cannot make on its own", is the precedent +for Phase 4 here. + +**Not built.** Planned against `fc437d05`. + +--- + +## The bug + +A rotation does not end when its refresh session reaches `COMPLETE`. It ends when the +group has signed the new generation's key state (kind 30326). That signature is the +first one the new shares make, and every device waits for it before it wipes the old +shares (D6). Here is the sequence: + +``` + Rotate shares + └─ ShareRefreshSession PROPOSED … COMPLETE ← canRotate checks only this + └─ coordinator: GroupKeyStateManager.proposeGeneration + └─ FrostSigningSession over a 30326 at g+1 ← open, waiting on a quorum + └─ signed → record() → retireOlderShares → wipe g +``` + +`DatabaseChatRepository.sharesSummary` (`DatabaseChatRepository.kt:681-688`) works +out `canRotate` as: + +```kotlin +val running = refreshes.any { it.stage != COMPLETE && it.stage != FAILED } +canRotate = ExperimentalFeatures.shareRefresh && shares.secretShare != null && !running +``` + +So the button comes back once the refresh is `COMPLETE`, while the key-state +proposal for `g+1` is still collecting signatures. `ShareRefreshManager.proposeRefresh` +has no further check either. Its `running(...)` guard (`ShareRefreshManager.kt:207`) +looks only at refresh sessions. A second tap then does the following: + +1. It starts a refresh from base `g+1` before anyone has shown that `g+1` can sign. + That is the thing D6 exists to prevent. Two unproven generations are now stacked. +2. It turns the open `g+1` key-state proposal into a dead end. Once `g+2` is active + and its key state is signed, `retireOlderShares` calls `failRotated(g+2)`, and every + open session below `g+2` fails. That includes the `g+1` key-state session that + members may still be approving. They approve a proposal that can only fail. +3. A device that has not received the `g+1` certificate yet refuses the new proposal + on arrival ("it refreshes generation g+1, and this device is at generation g"), and + if it is a recipient it broadcasts a failure. + +The same gap reaches the room detail screen's "Rotate shares without them?" dialog +(`ChatRoomDetailScreen.kt:192-207`). `rotateSharesWithout` never reads `canRotate`. + +Two smaller problems sit next to the main one: + +- **The screen is not reactive.** `ChatRoomDetailViewModel.initiateChatRoomDetail` + reads `sharesSummary` once and reads it again only after one of the screen's own + actions. A key state signed in the background does not re-enable anything until the + screen is opened again. +- **Nothing guards a double tap.** `sharesAction` (`ChatRoomDetailViewModel.kt:146`) + does not disable the button while it runs. A second tap is caught by `running(...)`, + which hands back the first session, and the screen still says "Share rotation + proposed" a second time. `isActionPending` exists on the view model but nothing uses + it. + +## The question: should the proposer approve their own rotation? + +At the moment the proposer is asked like everyone else: + +> The proposer is auto-approved for nothing. Proposing a refresh is not agreeing to +> withhold whomever the form defaulted to. (frost-share-refresh.md, Phase 7) + +`nothing of a member's own goes out before they approve` in `ShareRefreshRitualJvmTest` +asserts it. So tapping **Rotate shares** puts a "Take part in rotating the shares" row +in front of the person who just tapped it, and later a "Store your new share" row. + +The reason given is real, but it describes the screen, not the protocol. The plain +button runs no confirmation step at all. It withholds every stale member automatically +and never says so. The way to fix that is to have the tap state what it agrees to, not +to ask a second time. The ceremony has already settled this: +`ChillDkgRitualManager` approves the coordinator's host key at proposal +(`ChillDkgRitualManager.kt:308`), and since automatic-key-ceremony.md both rounds are +automatic for everyone. + +**Recommendation: yes.** Once the tap goes through a confirmation that names who is +withheld and as what, approve the proposer's `DEAL` and `CONFIRM` at proposal. + +- `DEAL` is the decision about the withheld list. A proposer who has been shown the + list and confirmed it has made that decision. +- `CONFIRM` guards against "a coordinator substituting a table the recipients never + dealt". The proposer *is* the coordinator, so it cannot defend against itself. The + CertEq check its device runs is what does the work, and a tap adds nothing to that. + +Approval stays exactly as it is for every *other* recipient. Whether `CONFIRM` should +become automatic for everyone, as round 2 did in the ceremony, is a separate decision. +It is listed under [Not in this plan](#not-in-this-plan). + +The key-state proposal at the end of a rotation already approves its proposer: +`FrostSigningManager.proposeSigning` sets `signApprovedAt` (`FrostSigningManager.kt:364`). +Nothing changes there. + +--- + +## Phase 0: decisions + +| # | Question | Recommendation | Why | +|---|---|---|---| +| R1 | What counts as "a proposal for a group-signed key is pending"? | Any of: (a) a refresh for the key not yet `COMPLETE`/`FAILED`, which is today's check; (b) the key state the group has signed for the room names a generation **below** this device's active one; (c) an open `FrostSigningSession` for the key whose single item is a 30326, at any generation, rebinds included; (d) the signed state names a generation **above** this device's active one, so this device is behind | (b) covers the window before the coordinator's proposal arrives and the case where it failed. (c) covers a Phase 10b rebind and the ceremony's first state. (d) catches a device that missed a certificate, whose proposal every other device would refuse | +| R2 | Is the check made on the proposer's device only, or by recipients on arrival as well? | **On the proposer's device only.** Recipients keep today's refusals | A recipient that refuses on arrival broadcasts a failure. A device a few seconds behind on the key-state signature would then kill a valid rotation. The rule is "don't stack unproven generations from here", and the proposer is the device that can follow it | +| R3 | Does a running **repair** block rotation? | **No**, unless its rebind key state is open, which R1(c) already covers | `ShareRepairManager` has no abandon. A repair whose target never comes back would disable the button for good | +| R4 | What if the key state is never signed? | The Shares section offers **Ask the group to sign the new shares**, which calls `proposeGeneration` again ("anyone can propose it again", Phase 8), but only when R1(b) holds and no R1(c) session is open | Without this, a coordinator who disappears after `COMPLETE` disables the button for everyone, with nothing offered to fix it | +| R5 | Is the button hidden or disabled? | **Disabled, with a line saying why** | The user asked for it disabled. A missing button looks like a lost feature, and a disabled one with a reason tells people what they are waiting for | +| R6 | Does the proposer's confirmation name the withheld? | Yes. The plain button gets a dialog in the style of "Rotate shares without them?", listing every stale member who will be withheld again (or saying nobody is) | That is the condition the Phase 7 sentence was protecting, and Phase 4 depends on it | + +The question R1(c) has to answer before it is relied on: **does a 30326 signing session +that never reaches a quorum ever reach `FAILED` on this device?** If declining it +(`FrostSigningManager.decline`, `:2090`) only stops this device's own participation, +an open session would disable the button indefinitely. Phase 1 checks this first. If the +answer is no, R1(c) counts a session only while it is younger than the signing stall +window, or only while this device has not declined it. + +--- + +## Phase 1: the rule, in the manager + +One function that the summary and the propose paths both read, so the screen and the +protocol cannot drift apart. That is the same discipline `pendingApproval` follows with +`advance`. + +**`ShareRefreshManager`** + +```kotlin +/** Why this device must not propose a rotation of [key] now, or null when it may. */ +sealed interface RotationHold { + data class Running(val refreshId: String) : RotationHold + data class AwaitingKeyState(val generation: Int, val signingSessionId: String?) : RotationHold + data class Behind(val groupGeneration: Int, val localGeneration: Int) : RotationHold +} + +suspend fun rotationHold(database: GizaDatabase, localChatRoom: LocalChatRoom, key: DkgSession): RotationHold? +``` + +- `Running`: the current `running(database, key)`. +- `AwaitingKeyState(g, id)`: covers R1(b) and R1(c). `g` is the active generation, + read through `ShareGenerations.active`. `id` is the open 30326 session, if there is + one, found from `frostSigningSessionDao().getOpenSessionsForKey(key.id)` with the + item read by `getItems`. The signed generation is + `GroupKeyStateManager.keyStateFor(database, roomId)?.generation ?: 0`. +- `Behind`: R1(d). +- Generation 0 with no open 30326 session is never held. It needs no new key state + (`proposeGeneration` refuses it). + +**`proposeRefresh`** keeps handing back a running refresh. That is what +`a second proposal while one runs hands back the first` asserts. For `AwaitingKeyState` +and `Behind` it throws an `IllegalStateException` carrying the reason, which +`DatabaseChatRepository.failureOf` already turns into the snackbar text. +`proposeWithout` goes through `proposeRefresh`, so the removal dialog is covered too. + +**Tests**, in `ShareRefreshRitualJvmTest`: + +- `the next rotation waits until the group has signed the last one`: refresh to + generation 1, then check that `proposeRefresh` throws naming generation 1. Approve + the key-state signing on a quorum (`approveSigning`), and the next refresh proposes. +- `a rebind waiting on signatures holds a rotation`: uses the Phase 10b fixture. +- `a device that missed the certificate cannot propose from the old generation`. +- `rotating without a member waits as well`: `proposeWithout` while generation 1 is + unsigned. +- the R1(c) question above, answered by a test whichever way it goes. + +**Existing tests that will break, as intended:** +`the recovery walk rebuilds the live share three refreshes on` runs three refreshes +back to back with no key state signed in between, which is exactly what this phase +forbids. Add `approveSigning(all)` after each round. Before relying on it, check that +`ShareGenerations.wipeBefore` leaves the recovery data the walk reads, which should hold +because it nulls only `secretShare`. If it does not, that is a real bug for restoring +after a wipe, and it has to be fixed rather than worked around in the test. + +**Done when** the new tests pass and `jvmTest` is green. + +--- + +## Phase 2: the Shares section says why + +**`SharesSummary`.** `canRotate: Boolean` becomes something the screen can explain: + +```kotlin +/** Whether this device may propose a rotation, and if not, what it waits on. */ +val rotation: Rotation + +sealed interface Rotation { + data object Unavailable : Rotation // no live share, or the flag is off: no button + data object Available : Rotation + data class Held(val reason: Reason, val canAskForSignature: Boolean) : Rotation + enum class Reason { ROTATION_RUNNING, AWAITING_SIGNATURES, BEHIND } +} +``` + +`sharesSummary` maps `rotationHold` onto it. `canAskForSignature` is +`AwaitingKeyState` with `signingSessionId == null` (R4). + +**`ChatRoomDetailScreen`** (`:438-469`): + +- The caveat text and the button are shown for `Available` and `Held`. For `Held` the + button has `enabled = false`, and the line below it comes from the reason: + - `rotation_held_running`: "A rotation is in progress" + - `rotation_held_awaiting_signatures`: "Waiting for the group to sign the new shares + before another rotation" + - `rotation_held_behind`: "This device is catching up with the group's latest + rotation" + + These go in sentence case, through the catalogue, coloured `onSurfaceVariant` like + the caveat. +- When `canAskForSignature` is true, a `TextButton` **Ask the group to sign the new + shares** calls a new `ChatRepository.proposeKeyState(localChatRoom)`. That + calls `GroupKeyStateManager.proposeGeneration(..., refreshId = )` and reports through `notify`. +- With `AWAITING_SIGNATURES` and an open session, the line links to the room's + proposals, using the same `ProposalListRoute` the overflow already opens (`:622`). + The proposal waiting on the reader is one tap away. +- **The removal dialog.** `ChatRoomDetailViewModel.removeMember` raises + `rotationOffer` only when `holdsShare` is true *and* rotation is `Available`. When + it is `Held`, the snackbar says the member still holds a share and a rotation can be + started once the group has signed the current one. The offer is not shown and then + refused. + +**The double tap.** `sharesAction` sets `isActionPending` for its duration, and every +Shares section button reads it as `enabled = !isActionPending.value && …`. + +**Tests.** A `sharesSummary` test in `jvmTest` for each `Rotation` value, built on the +ritual harness. Plus the M3 audit: no literals, no `.dp`, sentence case. + +**Done when** `./gradlew :composeApp:m3Audit` and `:composeApp:jvmTest` pass, and the +section has been looked at on the desktop target in each of the three held states. + +--- + +## Phase 3: the button comes back on its own + +Re-read the shares summary whenever something it depends on changes, instead of only +after this screen's own actions. + +- In `ChatRoomDetailViewModel`, collect `combine(groupKeyStateDao().observeByChatRoomId(id), + frostSigningSessionDao().observeSessionsForChatRoom(id), + shareRefreshDao().observeSessionsForRoom(id))` through a new + `ChatRepository.observeSharesInputs(chatRoomId): Flow`. Debounce it, and + recompute **only** `shares` on the `Loaded` state with `copy(shares = …)`. A full + `initiateChatRoomDetail` would reload the subgroups and the profile as well. +- Repairs are left out on purpose (R3). Their pending approvals still refresh on the + existing paths. + +**Done when** a test drives the view model with a fake repository whose flow emits +after a key state is filed and sees `rotation` move from `Held` to `Available`. Also +check by hand on desktop that approving the key state from a second device re-enables +the button without leaving the screen. + +--- + +## Phase 4: the proposer is not asked about their own rotation + +Only after Phases 1–3, and only together with R6's dialog. + +**The confirmation.** The plain **Rotate shares** button opens an `AlertDialog`: + +- title: `rotate_shares_confirm_title`, "Rotate the group's shares?" +- body: the existing caveat, plus a line built from `SharesSummary.members` with + `standing == STALE`: "%1$s will be left out again until they are brought back", or + "Every member with a share takes part" when there are none. +- confirm: **Rotate shares**. Dismiss: **Not now**. + +The "Rotate shares without them?" dialog already names the person being retired, so it +counts as R6's confirmation as it stands. + +**The manager.** In `proposeRefresh`, the new `ShareRefreshSession` is created with +`dealApprovedAt = now` and `confirmApprovedAt = now`, and the KDoc at +`ShareRefreshManager.kt:111-116` is rewritten to state the rule and its reason: the +proposer confirmed the withheld list, and is the coordinator whose substitution +`CONFIRM` guards against. As a result: + +- `advance` publishes the proposer's round 1 straight after the proposal, so other + devices see "dealt" from the proposer at once. +- `pendingApproval` is null for the proposer throughout, so no "Take part" or + "Store your new share" row appears for them, and `announceApprovalNeeded` writes no + "approval needed" line for them. +- Other recipients are asked exactly as before. + +**Watch:** two members who propose from the same base before either hears of the +other. With both proposers auto-confirmed, each has confirmed its own refresh, and D3a +stops it confirming the other. Each refresh needs every recipient, so at most one can +certify, and possibly neither. That is the same outcome as two people who each tapped +**Approve** on their own, so no new failure mode appears. It just arrives faster. Add a +test that shows it ends in one completed refresh or in a state a recipient can +**Abandon**, and never in two certificates. + +**Tests.** + +- `nothing of a member's own goes out before they approve` is rewritten: the proposer's + outbox holds `PROPOSAL` and `ROUND_1`, every other device's holds nothing, and only + the others are asked. Its last assertion, that the proposer *is* asked, is inverted. + This test is the one that records the decision, so its name and comment change along + with it. +- `approveAll` still works unchanged, since it skips devices that have nothing pending. +- the concurrent-proposal test above. + +**Strings.** `share_rotation_requested` becomes "Share rotation proposed; every other +member is asked to take part". `StringCatalogueJvmTest` needs no change. + +--- + +## Phase 5: the record + +- In `frost-share-refresh.md`, add rows to "Where it stands" for this work. Rewrite the + Phase 7 sentence "The proposer is auto-approved for nothing" as the new rule and its + reason. Add "a rotation whose key state the group has not signed" to Phase 7's list of + refusals, marked as the proposer's own check only (R2). +- Mark this file **Built**, with the commits, in the manner of + automatic-key-ceremony.md's table of "what the plan said / what it turned out to be". +- `./gradlew check` runs the m3, brand and wallet audits. + +--- + +## Not in this plan + +- **`CONFIRM` automatic for every recipient**, the ceremony's round-2 decision applied + to refresh. It is defensible on the same argument, but it changes what every member + is asked, so it needs its own decision. +- **Recipients refusing a proposal whose base key state they have not seen signed** + (R2). Without D5's capability check there is no way to tell "behind" from "never + will". +- **An abandon for repairs**, which R3 would need before a repair could hold rotation. +- **The refresh screen** that Phase 11 of frost-share-refresh.md described and the + Shares section replaced. The held state's line is the only progress shown. + +## Files + +| file | phase | +|---|---| +| `managers/ShareRefreshManager.kt`: `rotationHold`, `proposeRefresh` | 1, 4 | +| `database/repository/DatabaseChatRepository.kt`: `sharesSummary`, `proposeKeyState`, `observeSharesInputs` | 2, 3 | +| `repository/ChatRepository.kt` | 2, 3 | +| `ui/view/state/SharesSummary.kt`: `Rotation` | 2 | +| `ui/view/model/ChatRoomDetailViewModel.kt`: `isActionPending`, the observer, the removal offer | 2, 3 | +| `ui/composable/ChatRoomDetailScreen.kt`: disabled button and reason, ask-to-sign, the confirmation dialog | 2, 4 | +| `composeResources/values/strings.xml` | 2, 4 | +| `jvmTest/.../ShareRefreshRitualJvmTest.kt` | 1, 4 | +| `docs/frost-share-refresh.md` | 5 | From 159ae402dbfadf0390aef3ab4890767d6d4619a0 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:42:59 +0200 Subject: [PATCH 02/23] 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) From d358a0db38d747dad10d9c8e7ae35aa9acaa0e0a Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:44:59 +0200 Subject: [PATCH 03/23] feat: the Shares section holds Rotate shares and says why (Phase 2) SharesSummary.canRotate becomes Rotation: Unavailable, Available, or Held with a reason -- a rotation in progress, the group's signature on the new shares still owed, or this device behind. The button stays, disabled, with the reason beneath it. While the key state is owed and nobody here is asking for it, the section offers to ask the group to sign it (ShareRefreshManager.proposeOwedKeyState), so a coordinator who is gone does not hold every later rotation; while somebody is asking, it links to the proposal. The offer to rotate without a removed member is made only when a rotation could start now, and says so otherwise. The section's actions run one at a time, through isActionPending. ShareRefreshRitualJvmTest 24/24, m3Audit, compileDebugKotlinAndroid. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 7 ++ .../repository/DatabaseChatRepository.kt | 22 +++++- .../compose/managers/ShareRefreshManager.kt | 20 ++++++ .../giza/compose/repository/ChatRepository.kt | 9 +++ .../ui/composable/ChatRoomDetailScreen.kt | 67 +++++++++++++++++-- .../ui/view/model/ChatRoomDetailViewModel.kt | 25 +++++-- .../compose/ui/view/state/SharesSummary.kt | 25 ++++++- .../managers/ShareRefreshRitualJvmTest.kt | 53 +++++++++++++++ 8 files changed, 215 insertions(+), 13 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 733a0b2c..307ca511 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -127,6 +127,13 @@ Store your new share Help bring a member back Sent to the group + A rotation is in progress + Waiting for the group to sign the new shares before another rotation + This device is catching up with the group's latest rotation + Removal sent. They still hold a share; rotate without them once the group has signed the current shares. + Ask the group to sign the new shares + Asked the group to sign the new shares + See the proposal Share rotation proposed; every remaining member is asked to take part Library Lightning invoice diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 1a119258..ec55d70b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -42,6 +42,7 @@ import mobi.giza.compose.database.model.types.MarmotReindexReport import mobi.giza.compose.identity.Identity import mobi.giza.compose.identity.toKeyPair import mobi.giza.compose.managers.ShareRefreshManager +import mobi.giza.compose.managers.RotationHold import mobi.giza.compose.ui.view.state.SharesSummary import mobi.giza.compose.database.model.types.ShareStanding import mobi.giza.compose.database.model.types.ShareRepairStage @@ -676,7 +677,6 @@ class DatabaseChatRepository( } } + repairs.filter { ShareRepairManager.isAwaitingApproval(database, it) } .map { SharesSummary.PendingApproval(it.id, SharesSummary.PendingApproval.Kind.REPAIR_HELP) } - val running = refreshes.any { it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED } val mine = shares.roster.firstOrNull { it.memberPublicKey == me } val repairing = repairs.any { it.targetPublicKey == me && it.stage != ShareRepairStage.FAILED && it.stage != ShareRepairStage.COMPLETE } SharesSummary( @@ -685,7 +685,19 @@ class DatabaseChatRepository( SharesSummary.Member(entry.memberPublicKey, names[entry.memberPublicKey] ?: entry.memberPublicKey.take(8), entry.standing, entry.memberPublicKey == me) }, pending = if (ExperimentalFeatures.shareRefresh) pending else emptyList(), - canRotate = ExperimentalFeatures.shareRefresh && shares.secretShare != null && !running, + rotation = if (!ExperimentalFeatures.shareRefresh || shares.secretShare == null) { + SharesSummary.Rotation.Unavailable + } else { + when (val hold = ShareRefreshManager.rotationHold(database, localChatRoom, key)) { + null -> SharesSummary.Rotation.Available + is RotationHold.Running -> SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.ROTATION_RUNNING) + is RotationHold.AwaitingKeyState -> SharesSummary.Rotation.Held( + SharesSummary.Rotation.Reason.AWAITING_SIGNATURES, + canAskForSignature = hold.signingSessionId == null, + ) + is RotationHold.Behind -> SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.BEHIND) + } + }, canAskToBeRepaired = ExperimentalFeatures.shareRefresh && mine?.standing == ShareStanding.STALE && !repairing, ) }.getOrNull() @@ -716,6 +728,12 @@ class DatabaseChatRepository( }.exceptionOrNull()) } + override suspend fun proposeKeyState(localChatRoom: LocalChatRoom): String? { + val (me, _) = privateKeyOrNull() ?: return "This identity cannot sign" + val key = shareKeyOf(localChatRoom) ?: return "This group has no shared key" + return failureOf(runCatching { ShareRefreshManager.proposeOwedKeyState(database, localChatRoom, me, key) }.exceptionOrNull()) + } + override suspend fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String): String? = failureOf(runCatching { ShareRefreshManager.abandon(database, localChatRoom, sessionId) }.exceptionOrNull()) 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 fcbe2900..68eaa193 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -235,6 +235,26 @@ object ShareRefreshManager { return null } + /** + * Asks the group to sign the key state it owes for the generation the last + * rotation produced, when nobody here is asking -- the coordinator's proposal + * failed, or its device is gone. Anyone may (docs/frost-share-refresh.md, + * Phase 8); without it a lost coordinator holds every later rotation for good + * (docs/rotation-waits-for-key-state.md, R4). + */ + suspend fun proposeOwedKeyState(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, key: DkgSession): FrostSigningSession { + val hold = rotationHold(database, localChatRoom, key) + check(hold is RotationHold.AwaitingKeyState && hold.signingSessionId == null) { + "The group is not waiting on anyone to ask for its key state" + } + // The refresh that produced the generation, named on the state as the + // coordinator would have named it. + val refreshId = database.shareRefreshDao().getSessionsForKey(key.id) + .firstOrNull { it.stage == ShareRefreshStage.COMPLETE && it.baseGeneration + 1 == hold.generation } + ?.id + return GroupKeyStateManager.proposeGeneration(database, localChatRoom, userPublicKey, key, refreshId) + } + /** * 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 diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index f8a61f1f..f7d7563f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -290,6 +290,13 @@ interface ChatRepository { /** Answers what [approval] asks. Null on success, or why not. */ suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? + /** + * Asks the group to sign the key state at the generation the last rotation + * produced, when nobody here is asking (docs/rotation-waits-for-key-state.md, R4). + * Null when the request went out, or why it did not. + */ + suspend fun proposeKeyState(localChatRoom: LocalChatRoom): String? + /** Ends the rotation [sessionId] for everyone. Null on success, or why not. */ suspend fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String): String? @@ -496,6 +503,8 @@ interface ChatRepository { override suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? = null + override suspend fun proposeKeyState(localChatRoom: LocalChatRoom): String? = null + override suspend fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String): String? = null override suspend fun askToBeRepaired(localChatRoom: LocalChatRoom): String? = null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 2b3ac801..272c0c54 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -122,6 +122,13 @@ import androidx.compose.foundation.layout.Row import mobi.giza.compose.resources.share_rotation_requested import mobi.giza.compose.resources.not_now import mobi.giza.compose.resources.rotate_shares +import mobi.giza.compose.resources.rotation_held_running +import mobi.giza.compose.resources.rotation_held_awaiting_signatures +import mobi.giza.compose.resources.rotation_held_behind +import mobi.giza.compose.resources.rotation_held_after_removal +import mobi.giza.compose.resources.ask_the_group_to_sign_the_new_shares +import mobi.giza.compose.resources.key_state_requested +import mobi.giza.compose.resources.see_the_proposal import mobi.giza.compose.resources.rotate_shares_without_body import mobi.giza.compose.resources.rotate_shares_without_title import androidx.compose.material3.AlertDialog @@ -185,6 +192,8 @@ fun ChatRoomDetailScreen( val removalRequested = stringResource(Res.string.member_removal_requested) val rotationRequested = stringResource(Res.string.share_rotation_requested) val sharesActionSent = stringResource(Res.string.shares_action_sent) + val keyStateRequested = stringResource(Res.string.key_state_requested) + val rotationHeldAfterRemoval = stringResource(Res.string.rotation_held_after_removal) // Offered after removing a member who still holds a share of the room's key: // the removal took them out of the room, not out of the key @@ -413,6 +422,7 @@ fun ChatRoomDetailScreen( Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { if (approval.kind != SharesSummary.PendingApproval.Kind.REPAIR_HELP) { TextButton( + enabled = !chatRoomDetailViewModel.isActionPending.value, onClick = { chatRoomDetailViewModel.abandonRotation(chatRoomDetailUIState.localChatRoom, approval.sessionId) { failure -> notify(failure ?: sharesActionSent) @@ -423,6 +433,7 @@ fun ChatRoomDetailScreen( } } FilledTonalButton( + enabled = !chatRoomDetailViewModel.isActionPending.value, onClick = { chatRoomDetailViewModel.approveShares(chatRoomDetailUIState.localChatRoom, approval) { failure -> notify(failure ?: sharesActionSent) @@ -435,7 +446,9 @@ fun ChatRoomDetailScreen( } ) } - if (shares.canRotate || shares.canAskToBeRepaired) { + val rotation = shares.rotation + val actionPending = chatRoomDetailViewModel.isActionPending.value + if (rotation != SharesSummary.Rotation.Unavailable || shares.canAskToBeRepaired) { item { Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { Text( @@ -443,8 +456,12 @@ fun ChatRoomDetailScreen( style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant ) - if (shares.canRotate) { + if (rotation != SharesSummary.Rotation.Unavailable) { + // Disabled rather than hidden while the last rotation is + // unfinished, with the reason beneath it + // (docs/rotation-waits-for-key-state.md, Phase 2). FilledTonalButton( + enabled = rotation == SharesSummary.Rotation.Available && !actionPending, onClick = { chatRoomDetailViewModel.rotateShares(chatRoomDetailUIState.localChatRoom) { failure -> notify(failure ?: rotationRequested) @@ -454,8 +471,50 @@ fun ChatRoomDetailScreen( Text(stringResource(Res.string.rotate_shares)) } } + if (rotation is SharesSummary.Rotation.Held) { + Text( + text = stringResource( + when (rotation.reason) { + SharesSummary.Rotation.Reason.ROTATION_RUNNING -> Res.string.rotation_held_running + SharesSummary.Rotation.Reason.AWAITING_SIGNATURES -> Res.string.rotation_held_awaiting_signatures + SharesSummary.Rotation.Reason.BEHIND -> Res.string.rotation_held_behind + } + ), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + if (rotation.canAskForSignature) { + // Nobody is asking for the key state the group owes: + // the coordinator's proposal failed, or its device is + // gone. Anyone may ask again (frost-share-refresh.md, Phase 8). + TextButton( + enabled = !actionPending, + onClick = { + chatRoomDetailViewModel.proposeKeyState(chatRoomDetailUIState.localChatRoom) { failure -> + notify(failure ?: keyStateRequested) + } + } + ) { + Text(stringResource(Res.string.ask_the_group_to_sign_the_new_shares)) + } + } else if (rotation.reason == SharesSummary.Rotation.Reason.AWAITING_SIGNATURES) { + TextButton( + onClick = { + onNavigateToRoute.invoke( + ProposalListRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId + ) + ) + } + ) { + Text(stringResource(Res.string.see_the_proposal)) + } + } + } if (shares.canAskToBeRepaired) { TextButton( + enabled = !actionPending, onClick = { chatRoomDetailViewModel.askToBeRepaired(chatRoomDetailUIState.localChatRoom) { failure -> notify(failure ?: sharesActionSent) @@ -706,8 +765,8 @@ fun ChatRoomDetailScreen( chatRoomDetailViewModel.removeMember( localChatRoom = chatRoomDetailUIState.localChatRoom, memberPublicKey = memberPublicKey, - ) { failure -> - notify(failure ?: removalRequested) + ) { failure, rotationHeld -> + notify(failure ?: if (rotationHeld) rotationHeldAfterRemoval else removalRequested) } } ) { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 3cb13a0e..a191551e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -118,20 +118,24 @@ class ChatRoomDetailViewModel( * applied when a relay accepts it, so the member's row stays until then; the * line saying they were removed is there at once. */ - fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey, onDone: (String?) -> Unit = {}) { + fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey, onDone: (failure: String?, rotationHeld: Boolean) -> Unit = { _, _ -> }) { viewModelScope.launch(Dispatchers.IO) { // Asked before the removal, while they are still in the room's roster. val heldShare = chatRepository.holdsShare(localChatRoom, memberPublicKey) val failure = runCatching { chatRepository.removeMember(localChatRoom, memberPublicKey) } .exceptionOrNull() + // Offered only when a rotation could start now; while the last one is + // unfinished the offer would only be refused + // (docs/rotation-waits-for-key-state.md, Phase 2). + val rotation = if (failure == null && heldShare) chatRepository.sharesSummary(localChatRoom)?.rotation else null initiateChatRoomDetail() viewModelScope.launch(Dispatchers.Main) { - onDone(failure?.message) + onDone(failure?.message, rotation is SharesSummary.Rotation.Held) // The removal takes them out of the room, not out of the key: they // can still help sign until the shares are rotated without them. // A second act, offered rather than folded in -- it needs every // remaining holder (docs/frost-share-refresh.md, Phase 9). - if (failure == null && heldShare) rotationOffer = RotationOffer(localChatRoom, memberPublicKey) + if (rotation == SharesSummary.Rotation.Available) rotationOffer = RotationOffer(localChatRoom, memberPublicKey) } } } @@ -142,9 +146,17 @@ class ChatRoomDetailViewModel( * goes on with in the background, so done means sent, not finished. */ private fun sharesAction(onDone: (String?) -> Unit, action: suspend () -> String?) { + // One at a time: the section's buttons read this, so a second tap while the + // first is on its way does nothing rather than reporting twice. + if (isActionPending.value) return + isActionPending.value = true viewModelScope.launch(Dispatchers.IO) { - val failure = action() - initiateChatRoomDetail() + val failure = try { + action() + } finally { + initiateChatRoomDetail() + viewModelScope.launch(Dispatchers.Main) { isActionPending.value = false } + } viewModelScope.launch(Dispatchers.Main) { onDone(failure) } } } @@ -155,6 +167,9 @@ class ChatRoomDetailViewModel( fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval, onDone: (String?) -> Unit) = sharesAction(onDone) { chatRepository.approveShares(localChatRoom, approval) } + fun proposeKeyState(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) = + sharesAction(onDone) { chatRepository.proposeKeyState(localChatRoom) } + fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String, onDone: (String?) -> Unit) = sharesAction(onDone) { chatRepository.abandonRotation(localChatRoom, sessionId) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt index 720377f0..01b35ce2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt @@ -12,13 +12,34 @@ data class SharesSummary( val generation: Int, val members: List, val pending: List, - /** This device holds a live share and no rotation is running: it may propose one. */ - val canRotate: Boolean, + /** Whether this device may propose a rotation, and if not, what it waits on. */ + val rotation: Rotation, /** This device's own id is stale and nothing is bringing it back yet. */ val canAskToBeRepaired: Boolean, ) { data class Member(val publicKey: HexKey, val name: String, val standing: ShareStanding, val isSelf: Boolean) + /** + * The rotate action, as the section shows it (docs/rotation-waits-for-key-state.md). + * [ShareRefreshManager.rotationHold][mobi.giza.compose.managers.ShareRefreshManager.rotationHold] + * decides it, the same function proposing asks, so the button and the protocol agree. + */ + sealed interface Rotation { + /** No live share here, or a build without the feature: no button. */ + data object Unavailable : Rotation + + data object Available : Rotation + + /** + * The button, disabled, and why. [canAskForSignature]: the group owes the + * key state at this generation and nobody here is asking for it, so this + * device can. + */ + data class Held(val reason: Reason, val canAskForSignature: Boolean = false) : Rotation + + enum class Reason { ROTATION_RUNNING, AWAITING_SIGNATURES, BEHIND } + } + /** Something this device's owner is being asked, and the session it is for. */ data class PendingApproval(val sessionId: String, val kind: Kind) { enum class Kind { REFRESH_DEAL, REFRESH_CONFIRM, REPAIR_HELP } 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 39694888..42513bc5 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -19,6 +19,8 @@ import kotlin.test.assertNotEquals import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job import kotlinx.coroutines.runBlocking import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase @@ -32,6 +34,7 @@ import mobi.giza.compose.database.model.NostrEvent import mobi.giza.compose.database.model.Profile import mobi.giza.compose.database.model.ShareRefreshConfirmation import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.repository.DatabaseChatRepository import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.database.model.types.FrostSigningStage import mobi.giza.compose.database.model.types.ShareGenerationState @@ -41,6 +44,7 @@ import mobi.giza.compose.extensions.toHex import mobi.giza.compose.nostr.dkg.DkgRitualEvents import mobi.giza.compose.nostr.frost.FrostSigningEvents import mobi.giza.compose.nostr.frost.ShareRefreshEvents +import mobi.giza.compose.ui.view.state.SharesSummary /** * A share refresh between devices (docs/frost-share-refresh.md, Phase 7). @@ -584,6 +588,55 @@ class ShareRefreshRitualJvmTest { assertFailsWith { propose(late) } } + /** The rotate action as the room's Shares section reads it. */ + private suspend fun rotation(device: Device): SharesSummary.Rotation? = + DatabaseChatRepository(device.db, CoroutineScope(Job())).sharesSummary(device.room)?.rotation + + @Test + fun `the Shares section holds the button while a rotation is unfinished, and says why`() = runBlocking { + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true + val group = Group(3, 2) + val all = devicesFor(group) + val (alice, bob) = all + assertEquals(SharesSummary.Rotation.Available, rotation(bob)) + + val refresh = propose(alice) + pump(all) + assertEquals(SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.ROTATION_RUNNING), rotation(bob)) + + approveAll(all, refresh.id) + val awaiting = SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.AWAITING_SIGNATURES, canAskForSignature = false) + assertEquals(awaiting, rotation(bob), "the coordinator is already asking") + + // The coordinator's proposal fails: nobody is asking, so Bob may. + all.forEach { device -> + device.db.frostSigningSessionDao().getSessionsForChatRoom(group.roomId).forEach { + device.db.frostSigningSessionDao().upsert(it.copy(stage = FrostSigningStage.FAILED)) + } + } + assertEquals(awaiting.copy(canAskForSignature = true), rotation(bob)) + val asked = ShareRefreshManager.proposeOwedKeyState(bob.db, bob.room, bob.publicKey, bob.key()) + pump(all) + assertEquals(awaiting, rotation(bob)) + assertFailsWith("one ask at a time") { + ShareRefreshManager.proposeOwedKeyState(alice.db, alice.room, alice.publicKey, alice.key()) + } + + approveSigning(all) + assertEquals(FrostSigningStage.COMPLETE, bob.db.frostSigningSessionDao().getSessionById(asked.id)?.stage) + all.forEach { assertEquals(SharesSummary.Rotation.Available, rotation(it), "device ${it.index}") } + val stated = Event.fromJson(bob.db.frostSigningSessionDao().getItems(asked.id).single().unsignedEventJson) + assertTrue(stated.tags.any { it.contains(refresh.id) }, "the refresh is named as the coordinator would have named it") + } + + @Test + fun `a member left out of a rotation is offered no rotate button`() = runBlocking { + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = true + val (_, all) = rotatedWithout(2) + assertEquals(SharesSummary.Rotation.Unavailable, rotation(all[2])) + assertEquals(SharesSummary.Rotation.Available, rotation(all[0])) + } + // ---- Phase 10: re-enrollment ----------------------------------------------------------------------------------- /** Every helper approves every repair waiting on them. */ From 98567629ba7dbb1c89931bdc7daa88fb6f28e184 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:47:00 +0200 Subject: [PATCH 04/23] feat: the Shares section follows the group while it is open (Phase 3) The room detail screen read the shares summary once, and again only after one of its own actions, so a key state signed in the background left Rotate shares disabled until the screen was reopened. ChatRepository.observeSharesInputs emits when the room's key state, signing sessions or refreshes change; the view model reads the section again once they settle, and nothing else on the screen. ChatRoomDetailSharesJvmTest 2/2, m3Audit, compileDebugKotlinAndroid. Co-Authored-By: Claude Opus 5.5 --- .../repository/DatabaseChatRepository.kt | 7 ++ .../giza/compose/repository/ChatRepository.kt | 11 ++ .../ui/view/model/ChatRoomDetailViewModel.kt | 30 +++++ .../view/model/ChatRoomDetailSharesJvmTest.kt | 105 ++++++++++++++++++ 4 files changed, 153 insertions(+) create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index ec55d70b..b72d682e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -25,6 +25,7 @@ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.combine import mobi.giza.compose.database.GENESIS_AT import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ChatMessage @@ -702,6 +703,12 @@ class DatabaseChatRepository( ) }.getOrNull() + override fun observeSharesInputs(chatRoomId: String): Flow = combine( + database.groupKeyStateDao().observeByChatRoomId(chatRoomId), + database.frostSigningSessionDao().observeSessionsForChatRoom(chatRoomId), + database.shareRefreshDao().observeSessionsForRoom(chatRoomId), + ) { _, _, _ -> } + private fun failureOf(t: Throwable?): String? = t?.let { it.message ?: it::class.simpleName ?: "Unknown error" } private fun privateKeyOrNull(): Pair? { diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index f7d7563f..c8829a43 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -7,6 +7,7 @@ import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync import com.vitorpamplona.quartz.nip17Dm.messages.ChatMessageEvent import com.vitorpamplona.quartz.nip17Dm.settings.DmRelayListEvent import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flow import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.GiftWrapPayload @@ -284,6 +285,14 @@ interface ChatRepository { /** The room's key as the Shares section shows it, or null when the room has none. */ suspend fun sharesSummary(localChatRoom: LocalChatRoom): SharesSummary? + /** + * Emits whenever something [sharesSummary] reads for [chatRoomId] may have + * changed -- the key state the group signed, a signing session, a refresh -- + * so the section follows the group without being reopened + * (docs/rotation-waits-for-key-state.md, Phase 3). + */ + fun observeSharesInputs(chatRoomId: String): Flow + /** Proposes rotating every share of the room's key. Null on success, or why not. */ suspend fun rotateShares(localChatRoom: LocalChatRoom): String? @@ -499,6 +508,8 @@ interface ChatRepository { override suspend fun sharesSummary(localChatRoom: LocalChatRoom): SharesSummary? = null + override fun observeSharesInputs(chatRoomId: String): Flow = emptyFlow() + override suspend fun rotateShares(localChatRoom: LocalChatRoom): String? = null override suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? = null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index a191551e..9112b03a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -16,7 +16,10 @@ import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.FlowPreview import kotlinx.coroutines.IO +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.launch import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.MarmotReindexReport @@ -110,6 +113,30 @@ class ChatRoomDetailViewModel( shares = chatRepository.sharesSummary(localChatRoom), ) } + localChatRoom?.let { observeShares(it.chatRoom.id) } + } + } + + private var sharesObserver: Job? = null + + /** + * Keeps the Shares section following the group: a key state signed, a + * proposal declined, a refresh moved on by another device, all while this + * screen is open (docs/rotation-waits-for-key-state.md, Phase 3). Only the + * section is read again -- the rest of the screen has its own paths. + */ + @OptIn(FlowPreview::class) + private fun observeShares(roomId: String) { + if (sharesObserver != null) return + sharesObserver = viewModelScope.launch(Dispatchers.IO) { + chatRepository.observeSharesInputs(roomId) + // A signing session writes a row per message; read once it settles. + .debounce(SHARES_SETTLE_MILLIS) + .collect { + val loaded = chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded ?: return@collect + val shares = chatRepository.sharesSummary(loaded.localChatRoom) + (chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded)?.let { chatRoomDetailUIState = it.copy(shares = shares) } + } } } @@ -286,6 +313,9 @@ class ChatRoomDetailViewModel( companion object { private const val TAG = "ChatRoomDetailViewModel" + /** How long the Shares section's inputs have to be still before it is read again. */ + internal const val SHARES_SETTLE_MILLIS = 250L + fun factory( activeUserPublicKey: HexKey, chatRoomId: String, diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt new file mode 100644 index 00000000..ad25eae1 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt @@ -0,0 +1,105 @@ +package mobi.giza.compose.ui.view.model + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.repository.ChatRepository +import mobi.giza.compose.repository.NostrRepository +import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState +import mobi.giza.compose.ui.view.state.SharesSummary +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * The room detail screen's Shares section follows the group while it is open + * (docs/rotation-waits-for-key-state.md, Phase 3): the rotate button the last + * rotation held comes back when the group signs, without the screen being left + * and opened again. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class ChatRoomDetailSharesJvmTest { + @BeforeTest + fun setUp() { + Dispatchers.setMain(UnconfinedTestDispatcher()) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + private val chatRoomId = "c0ffee00".repeat(8) + private val me = "a".repeat(64) + private val localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = chatRoomId, userPublicKey = me, subject = "Admins", description = null, mlsGroupState = null) + ) + + private fun summary(rotation: SharesSummary.Rotation) = + SharesSummary(generation = 1, members = emptyList(), pending = emptyList(), rotation = rotation, canAskToBeRepaired = false) + + private class Repository(val room: LocalChatRoom, var shares: SharesSummary) : + ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + val inputs = MutableSharedFlow(replay = 1) + var reads = 0 + override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = room.takeIf { id == room.chatRoom.id } + override suspend fun sharesSummary(localChatRoom: LocalChatRoom): SharesSummary { reads++; return shares } + override fun observeSharesInputs(chatRoomId: String): Flow = inputs + } + + private fun viewModel(repository: Repository) = ChatRoomDetailViewModel( + chatRoomId = chatRoomId, + activeUserPublicKey = me, + relayHint = null, + initialChatRoomDetailUIState = ChatRoomDetailUIState.Loading, + nostrRepository = NostrRepository.NO_OP_NOSTR_REPOSITORY, + chatRepository = repository, + ) + + private suspend fun ChatRoomDetailViewModel.awaitRotation(expected: SharesSummary.Rotation) = withTimeout(5_000) { + while ((chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded)?.shares?.rotation != expected) delay(10) + } + + @Test + fun `the rotate button comes back when the group signs, with the screen open`() = runBlocking { + val held = SharesSummary.Rotation.Held(SharesSummary.Rotation.Reason.AWAITING_SIGNATURES) + val repository = Repository(localChatRoom, summary(held)) + val viewModel = viewModel(repository) + viewModel.initiateChatRoomDetail() + viewModel.awaitRotation(held) + + // The group's signature lands in the database while the screen is open. + repository.shares = summary(SharesSummary.Rotation.Available) + repository.inputs.emit(Unit) + viewModel.awaitRotation(SharesSummary.Rotation.Available) + } + + @Test + fun `a burst of signing messages is read once it settles`() = runBlocking { + val repository = Repository(localChatRoom, summary(SharesSummary.Rotation.Available)) + val viewModel = viewModel(repository) + viewModel.initiateChatRoomDetail() + viewModel.awaitRotation(SharesSummary.Rotation.Available) + delay(ChatRoomDetailViewModel.SHARES_SETTLE_MILLIS * 2) + val before = repository.reads + + repeat(20) { repository.inputs.emit(Unit) } + delay(ChatRoomDetailViewModel.SHARES_SETTLE_MILLIS * 3) + + val reads = repository.reads - before + assertTrue(reads in 1..2, "20 changes in a burst read the section $reads times") + assertEquals(SharesSummary.Rotation.Available, (viewModel.chatRoomDetailUIState as ChatRoomDetailUIState.Loaded).shares?.rotation) + } +} From 951312489c4a5808b3a221547be11caa09ce4633 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:49:04 +0200 Subject: [PATCH 05/23] feat: the proposer is not asked about their own rotation (Phase 4) Tapping Rotate shares put "Take part in rotating the shares" in front of the person who had just tapped it, and "Store your new share" after. The button now asks first, in a dialog naming every member the rotation leaves out -- the stale, withheld again -- and proposeRefresh approves the proposer at both gates. DEAL is the decision about who is withheld, which the dialog just took; CONFIRM guards against a coordinator substituting a table, and the proposer is the coordinator. Every other recipient is asked as before. A test now shows two proposals crossing on the wire end with neither running and every device on one table. ShareRefreshRitualJvmTest 25/25, ChatRoomDetailSharesJvmTest 3/3, m3Audit, compileDebugKotlinAndroid. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 5 +- .../compose/managers/ShareRefreshManager.kt | 12 +++-- .../ui/composable/ChatRoomDetailScreen.kt | 38 ++++++++++++-- .../ui/view/model/ChatRoomDetailViewModel.kt | 29 +++++++++++ .../managers/ShareRefreshRitualJvmTest.kt | 51 ++++++++++++++++--- .../view/model/ChatRoomDetailSharesJvmTest.kt | 28 ++++++++++ 6 files changed, 150 insertions(+), 13 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 307ca511..4e9ab9c7 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -134,7 +134,10 @@ Ask the group to sign the new shares Asked the group to sign the new shares See the proposal - Share rotation proposed; every remaining member is asked to take part + Share rotation proposed; every other member is asked to take part + Rotate the group's shares? + Every member with a share takes part. + Left out again, until they are brought back: Library Lightning invoice Open in a wallet app 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 68eaa193..7202b594 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -113,9 +113,13 @@ object ShareRefreshManager { * Opens a refresh of [key], making this device the coordinator. Every live * participant not in [withheld] is a recipient. * - * The proposer is auto-approved for nothing: proposing a refresh is not - * agreeing to withhold whomever the form defaulted to, so it is asked at both - * gates like everyone else. + * The proposer is approved at both gates on proposal + * (docs/rotation-waits-for-key-state.md, Phase 4). `DEAL` is the decision about + * the withheld list, and the screen only proposes after its owner has confirmed + * a dialog naming everyone withheld -- so the tap was that decision. `CONFIRM` + * guards against a coordinator substituting a table nobody dealt, and the + * proposer is the coordinator: its own CertEq check does that work, and a tap + * adds nothing to it. Every other recipient is asked at both gates as before. */ suspend fun proposeRefresh( database: GizaDatabase, @@ -158,6 +162,8 @@ object ShareRefreshManager { withheld = ShareRefreshSession.formatWithheld(allWithheld), round1Random = RandomInstance.bytes(32).toHex(), auxRandom = RandomInstance.bytes(32).toHex(), + dealApprovedAt = Clock.System.now(), + confirmApprovedAt = Clock.System.now(), ) database.shareRefreshDao().upsert(session) announce(database, session, ChatMessage.TYPE_SHARE_REFRESH_STARTED, startedLine(session, shares), userPublicKey) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 272c0c54..79a5c50d 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -123,6 +123,9 @@ import mobi.giza.compose.resources.share_rotation_requested import mobi.giza.compose.resources.not_now import mobi.giza.compose.resources.rotate_shares import mobi.giza.compose.resources.rotation_held_running +import mobi.giza.compose.resources.rotate_shares_confirm_title +import mobi.giza.compose.resources.rotate_shares_confirm_everyone +import mobi.giza.compose.resources.rotate_shares_confirm_left_out import mobi.giza.compose.resources.rotation_held_awaiting_signatures import mobi.giza.compose.resources.rotation_held_behind import mobi.giza.compose.resources.rotation_held_after_removal @@ -216,6 +219,37 @@ fun ChatRoomDetailScreen( ) } + // The plain rotate button's confirmation. Proposing approves the proposer, so + // this names who the rotation leaves out (docs/rotation-waits-for-key-state.md, + // Phase 4). + chatRoomDetailViewModel.rotationConfirmation?.let { confirmation -> + AlertDialog( + onDismissRequest = { chatRoomDetailViewModel.dismissRotationConfirmation() }, + title = { Text(stringResource(Res.string.rotate_shares_confirm_title)) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text(stringResource(Res.string.shares_rotation_caveat)) + if (confirmation.leftOut.isEmpty()) { + Text(stringResource(Res.string.rotate_shares_confirm_everyone)) + } else { + Text(stringResource(Res.string.rotate_shares_confirm_left_out)) + confirmation.leftOut.forEach { name -> Text(name, style = MaterialTheme.typography.bodyMedium) } + } + } + }, + confirmButton = { + TextButton(onClick = { chatRoomDetailViewModel.confirmRotation(confirmation) { failure -> notify(failure ?: rotationRequested) } }) { + Text(stringResource(Res.string.rotate_shares)) + } + }, + dismissButton = { + TextButton(onClick = { chatRoomDetailViewModel.dismissRotationConfirmation() }) { + Text(stringResource(Res.string.not_now)) + } + }, + ) + } + ScreenStateTransition(chatRoomDetailViewModel.chatRoomDetailUIState) { uiState -> when (val chatRoomDetailUIState = uiState) { is ChatRoomDetailUIState.Error -> { @@ -463,9 +497,7 @@ fun ChatRoomDetailScreen( FilledTonalButton( enabled = rotation == SharesSummary.Rotation.Available && !actionPending, onClick = { - chatRoomDetailViewModel.rotateShares(chatRoomDetailUIState.localChatRoom) { failure -> - notify(failure ?: rotationRequested) - } + chatRoomDetailViewModel.askToRotate(chatRoomDetailUIState.localChatRoom, shares) } ) { Text(stringResource(Res.string.rotate_shares)) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 9112b03a..7b1080c1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -23,6 +23,7 @@ import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.launch import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.MarmotReindexReport +import mobi.giza.compose.database.model.types.ShareStanding import mobi.giza.compose.managers.WalletRefusal import mobi.giza.compose.nostr.MarmotProfile import mobi.giza.compose.repository.ChatRepository @@ -203,6 +204,34 @@ class ChatRoomDetailViewModel( fun askToBeRepaired(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) = sharesAction(onDone) { chatRepository.askToBeRepaired(localChatRoom) } + /** + * A rotation this device's owner is being asked to confirm, and who it leaves + * out: the members stale at this generation, withheld again as stale. The + * proposal approves the proposer, so this is where they decide who is withheld + * (docs/rotation-waits-for-key-state.md, Phase 4). + */ + data class RotationConfirmation(val localChatRoom: LocalChatRoom, val leftOut: List) + + var rotationConfirmation: RotationConfirmation? by mutableStateOf(null) + private set + + fun askToRotate(localChatRoom: LocalChatRoom, shares: SharesSummary) { + rotationConfirmation = RotationConfirmation( + localChatRoom, + shares.members.filter { it.standing == ShareStanding.STALE }.map { it.name }, + ) + } + + fun dismissRotationConfirmation() { + rotationConfirmation = null + } + + /** Proposes the rotation [rotationConfirmation] asked about. */ + fun confirmRotation(confirmation: RotationConfirmation, onDone: (String?) -> Unit) { + rotationConfirmation = null + rotateShares(confirmation.localChatRoom, onDone) + } + /** A removed member who still holds a share of the room's key, for the offer to rotate without them. */ data class RotationOffer(val localChatRoom: LocalChatRoom, val memberPublicKey: HexKey) 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 42513bc5..895392b5 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -38,6 +38,7 @@ import mobi.giza.compose.database.repository.DatabaseChatRepository import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.database.model.types.FrostSigningStage import mobi.giza.compose.database.model.types.ShareGenerationState +import mobi.giza.compose.database.model.types.ShareRefreshApprovalStep import mobi.giza.compose.database.model.types.ShareRefreshStage import mobi.giza.compose.database.model.types.ShareStanding import mobi.giza.compose.extensions.toHex @@ -217,18 +218,56 @@ class ShareRefreshRitualJvmTest { } @Test - fun `nothing of a member's own goes out before they approve`() = runBlocking { + fun `nothing of a member's own goes out before they approve, but the proposer is not asked`() = runBlocking { val group = Group(3, 2) val all = devicesFor(group) val refresh = propose(all[0]) pump(all) - all.forEach { device -> - assertEquals(listOf(ShareRefreshEvents.PROPOSAL).takeIf { device.index == 0 } ?: emptyList(), outbox(device).map { it.kind }, "device ${device.index}") - assertNotNull(ShareRefreshManager.pendingApproval(device.db, device.refresh(refresh.id)!!), "device ${device.index} must be asked") + // The proposer confirmed who is withheld before proposing, and is the + // coordinator CONFIRM guards against: it deals at once and is asked nothing + // (docs/rotation-waits-for-key-state.md, Phase 4). + assertEquals(listOf(ShareRefreshEvents.PROPOSAL, ShareRefreshEvents.ROUND_1), outbox(all[0]).map { it.kind }) + assertNull(ShareRefreshManager.pendingApproval(all[0].db, all[0].refresh(refresh.id)!!), "the proposer must not be asked") + assertTrue(all[0].db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).none { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED }) + + // Everyone else is asked, and has sent nothing. + all.drop(1).forEach { device -> + assertEquals(emptyList(), outbox(device).map { it.kind }, "device ${device.index}") + assertEquals(ShareRefreshApprovalStep.DEAL, ShareRefreshManager.pendingApproval(device.db, device.refresh(refresh.id)!!), "device ${device.index} must be asked") } - // The proposer is asked like anyone: proposing is not agreeing to withhold whoever the form defaulted to. - assertTrue(all[0].db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).any { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED }) + + // And once they have dealt, they are asked again before confirming; the proposer is not. + all.drop(1).forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) } + pump(all) + assertNull(ShareRefreshManager.pendingApproval(all[0].db, all[0].refresh(refresh.id)!!)) + all.drop(1).forEach { device -> + assertEquals(ShareRefreshApprovalStep.CONFIRM, ShareRefreshManager.pendingApproval(device.db, device.refresh(refresh.id)!!), "device ${device.index}") + } + } + + /** + * Two members propose from one base before either hears of the other. Each is + * approved for its own and refuses the other on arrival, as a recipient, + * out loud -- so neither stalls and nothing forks. + */ + @Test + fun `two proposals crossing on the wire end with neither stuck and at most one generation`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val first = propose(all[0]) + val second = propose(all[1]) + pump(all) + approveAll(all, first.id) + approveAll(all, second.id) + + all.forEach { device -> + val stages = listOf(first.id, second.id).map { device.refresh(it)?.stage } + assertTrue(stages.none { it != null && it != ShareRefreshStage.COMPLETE && it != ShareRefreshStage.FAILED }, "device ${device.index} left one running: $stages") + assertTrue(stages.count { it == ShareRefreshStage.COMPLETE } <= 1, "device ${device.index}: $stages") + assertTrue(ShareRefreshManager.rotationHold(device.db, device.room, device.key()) !is RotationHold.Running, "device ${device.index}") + } + assertEquals(1, all.map { it.active().publicShares }.toSet().size, "every device on one table") } @Test diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt index ad25eae1..a2f3e21b 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailSharesJvmTest.kt @@ -13,6 +13,7 @@ import kotlinx.coroutines.test.setMain import kotlinx.coroutines.withTimeout import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.ShareStanding import mobi.giza.compose.repository.ChatRepository import mobi.giza.compose.repository.NostrRepository import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState @@ -21,6 +22,7 @@ import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertNull import kotlin.test.assertTrue /** @@ -54,6 +56,8 @@ class ChatRoomDetailSharesJvmTest { ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { val inputs = MutableSharedFlow(replay = 1) var reads = 0 + var rotations = 0 + override suspend fun rotateShares(localChatRoom: LocalChatRoom): String? { rotations++; return null } override suspend fun getChatRoomByIdentifier(id: HexKey): LocalChatRoom? = room.takeIf { id == room.chatRoom.id } override suspend fun sharesSummary(localChatRoom: LocalChatRoom): SharesSummary { reads++; return shares } override fun observeSharesInputs(chatRoomId: String): Flow = inputs @@ -102,4 +106,28 @@ class ChatRoomDetailSharesJvmTest { assertTrue(reads in 1..2, "20 changes in a burst read the section $reads times") assertEquals(SharesSummary.Rotation.Available, (viewModel.chatRoomDetailUIState as ChatRoomDetailUIState.Loaded).shares?.rotation) } + + @Test + fun `rotating asks first, naming who it leaves out`() = runBlocking { + val shares = summary(SharesSummary.Rotation.Available).copy( + members = listOf( + SharesSummary.Member("b".repeat(64), "Bongani", ShareStanding.LIVE, isSelf = false), + SharesSummary.Member("c".repeat(64), "Carol", ShareStanding.STALE, isSelf = false), + SharesSummary.Member("d".repeat(64), "Dumi", ShareStanding.RETIRED, isSelf = false), + ) + ) + val repository = Repository(localChatRoom, shares) + val viewModel = viewModel(repository) + + viewModel.askToRotate(localChatRoom, shares) + val confirmation = viewModel.rotationConfirmation!! + assertEquals(listOf("Carol"), confirmation.leftOut, "the stale are withheld again; the retired are gone already") + assertEquals(0, repository.rotations, "nothing is proposed before the owner confirms") + + val done = kotlinx.coroutines.CompletableDeferred() + viewModel.confirmRotation(confirmation) { done.complete(it) } + assertNull(withTimeout(5_000) { done.await() }) + assertEquals(1, repository.rotations) + assertNull(viewModel.rotationConfirmation) + } } From 5820be9bc5a871be6a27ea7c83934e94ea7aeb10 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:50:04 +0200 Subject: [PATCH 06/23] docs: taking part is the only approval a share rotation needs, as a plan A recipient is asked three times today: to deal, to store the new share, and to sign the new generation's key state. Only the first is a decision. The plan removes the other two in seven phases, and names what removing them breaks: abandon lives only on an approval row, and nothing resumes a rotation without a message. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + docs/rotate-shares-single-approval.md | 550 ++++++++++++++++++++++++++ 2 files changed, 551 insertions(+) create mode 100644 docs/rotate-shares-single-approval.md diff --git a/docs/README.md b/docs/README.md index 5208a9ba..631ce39d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -20,6 +20,7 @@ the [retired](./retired/) notes now. | [frost-batch-signing.md](./frost-batch-signing.md) | signing several events in one ceremony — why one nonce can never cover two messages, and the phased schema, wire and UI work that follows from it | | [frost-session-resend.md](./frost-session-resend.md) | asking the members who never got a signing proposal to look again — why a proposer can repeat only what it wrote, why a member's availability signal needs no repeating, and the one half that has to come from the silent member's own device | | [frost-share-refresh.md](./frost-share-refresh.md) | giving every member a new share of the same group key, phased and not built — why enrollment cannot rotate a share, the zero-sum refresh that can, what a rotation protects against and the two things it never can, and re-enrollment as the repair that brings back the members a refresh left out | +| [rotate-shares-single-approval.md](./rotate-shares-single-approval.md) | taking part is the only approval: a phased plan, not built, that makes a share rotation run by itself after a member agrees to take part. Covers the three asks a recipient gets today, why storing the new share was never a decision, the one key state for a new generation a device can sign without asking, and the abandon a member loses once nothing is left to approve | | [marmot-membership.md](./marmot-membership.md) | how members join an MLS group, and the epoch race that makes a missing member look like a successful invite | | [member-chronicle.md](./member-chronicle.md) | handing a member added after the work was done the group's signed record — why the events are not on the wire at all, and why the room's id is enough to verify them | | [marmot-direct-messages.md](./marmot-direct-messages.md) | a one-to-one message inside a group as a stock NIP-59 gift wrap — what its MIP-03 carve-out costs, why the sender cannot read their own, and the one query that would broadcast it | diff --git a/docs/rotate-shares-single-approval.md b/docs/rotate-shares-single-approval.md new file mode 100644 index 00000000..22807395 --- /dev/null +++ b/docs/rotate-shares-single-approval.md @@ -0,0 +1,550 @@ +# Taking part is the only approval + +A plan to make a share rotation run by itself once a member has agreed to take +part. The member decides one thing: whether to take part in this rotation, with +these members withheld. Their device does everything after that. It deals its +part, checks the combined result, stores the new share, confirms it, signs the +group's new key state, and deletes the old share. **Abandon** stays, because the +one stall automation cannot fix is a member who agreed and then went quiet. + +This is the same change [automatic-key-ceremony.md](./automatic-key-ceremony.md) +made to the ceremony, applied to [frost-share-refresh.md](./frost-share-refresh.md). +Read both first. This plan follows the first one's shape, because the reasoning +is the same and so are most of the traps. + +**Not built.** Written against `fc437d05` on 2026-11-20. + +The headline: **a device asks its owner only for decisions it cannot make on +its own.** Taking part is one of those decisions, because it agrees to the +withheld list, and withholding someone takes their signing away. Storing the new +share is not a decision. The device has already checked the combined result +against the commitments and the table before it asks, and a person tapping +**Approve** under "Store your new share" adds nothing to that check. + +--- + +## What a member is asked today + +A rotation in a room whose key is `t`-of-`n`. Today every recipient is asked +**three** times, not two. The third ask is easy to miss because it looks like an +ordinary signing request rather than part of the rotation. + +| # | step | whose | today | after this plan | +|---|---|---|---|---| +| 1 | propose the rotation | proposer | **Rotate shares** button, no dialog, or the dialog after a removal | a dialog naming who takes part and who is withheld. Pressing it is the proposer's approval (R2) | +| 2 | deal round 1 (`DEAL`) | every recipient, proposer included | Shares section row, *Take part in rotating the shares* | **unchanged: the one approval**. The row now names who is withheld | +| 3 | sum round 1 (`cmsg1`) | coordinator | automatic | automatic | +| 4 | check, store the pending generation, send CertEq (`CONFIRM`) | every recipient | Shares section row, *Store your new share* | automatic. If the check fails, the rotation fails and says so, as it does today | +| 5 | certificate, activate `g+1` | coordinator, then every device | automatic | automatic | +| 6 | propose the `g+1` key state | coordinator | automatic (`proposeGeneration`) | automatic | +| 7 | sign the `g+1` key state | every recipient, `t` needed | signing approval, because `vouchesFor` rule 8 refuses any state with a generation (`fc437d05`) | automatic when the state is exactly the one this device's own completed rotation implies (Phase 5). Asked as today otherwise | +| 8 | wipe generation `g` | every device | automatic once 7 is signed | automatic | +| — | abandon | any recipient | only on a pending approval row | **kept**, and reachable for the whole run (Phase 6) | + +Today a recipient taps at rows 2, 4 and 7, and the proposer taps the button and +then rows 2, 4 and 7 as well. After this plan a recipient taps once, and the +proposer taps once. + +### Where the gates are + +| finding | where | +|---|---| +| G1. `advance` stops before round 1 until `dealApprovedAt` is set | `ShareRefreshManager.kt:391` | +| G2. `advance` stops before round 2 until `confirmApprovedAt` is set | `ShareRefreshManager.kt:415` | +| G3. `pendingApproval` mirrors G1 and G2, and must keep doing so | `ShareRefreshManager.kt:589-600` | +| G4. The proposer is approved for nothing on proposal, by design | `ShareRefreshManager.kt:111-116`, asserted by `ShareRefreshRitualJvmTest` "nothing of a member's own goes out before they approve" | +| G5. A rotation's key state is never vouched for: `vouchesFor` rule 8 | `GroupKeyStateManager.kt:659-660` | +| G6. Vouching is decided once, on the proposal's arrival. A device that receives the `g+1` key state before its own rotation has activated `g+1` cannot vouch for it then, and nothing asks again | `FrostSigningManager.kt:447`, `resumeAt` at `:1945` | +| G7. Nothing resumes a rotation except an arriving message. The sweep covers ceremonies only | `DatabaseNostrRepository.resumeRunningCeremonies` calls `ChillDkgRitualManager.resumeRunning` and nothing else | +| G8. The Shares section shows `REFRESH_CONFIRM` as its own row, with its own string | `SharesSummary.kt:24`, `DatabaseChatRepository.kt:674`, `ChatRoomDetailScreen.kt:406`, `pending_rotation_confirm` | +| G9. The only abandon button is on a pending approval row. Once a member has approved the last thing asked of them, they can no longer abandon a rotation stuck on somebody else | `ChatRoomDetailScreen.kt:413` | +| G10. The `DEAL` row does not say who is withheld, which is the whole of what that approval decides | `ChatRoomDetailScreen.kt:399-410` | + +G9 is a bug today only in a narrow case: a member who has confirmed and is +waiting on the certificate. Removing `CONFIRM` makes it the normal case. Every +member who has taken part would have no way out of a stalled rotation, and +`canRotate` stays false while one runs, so the group could not start another. +Phase 6 is not optional. + +G10 is the same kind of gap. Once `DEAL` is the only approval, it carries all +the weight of the decision, and today the row shows none of what is being +decided. + +--- + +## Why `CONFIRM` was never a decision + +`ShareRefreshApprovalStep.CONFIRM`'s KDoc gives two reasons for the gate. Neither +needs a person. + +- **"This is what stops a coordinator substituting a table the recipients never + dealt."** The check that stops it is `FrostRefresh.participantStep2`. It + decrypts and sums the dealt values, runs the Feldman check against the + commitments, recomputes every public share, and checks the new share against + its public share and the table against the threshold key. It runs before the + prompt appears, whatever the person does. A substituted table fails there and + the rotation fails out loud (`raiseIfFaulty`, `fail`, FAILURE). It never + reaches the prompt. The prompt shows nothing the person could check + themselves. +- **"The one confirmation per base generation this device will ever give."** The + write-once claim is `ShareRefreshConfirmation`, taken in the same transaction + as the `PENDING` row (`confirmAndStore`). It holds whether or not a person + tapped. A second refresh from the same base is refused by the database, not by + the owner. + +The only thing a person could do at `CONFIRM` that the device cannot is change +their mind. Abandon still covers that, from the whole run once Phase 6 lands. + +The same argument covers the key state at row 7. For a rotation this device +completed, the new generation's public-share table, the refresh id and the +retired ids are all facts the device holds and has checked against the +certificate. Exactly one key state can be true. If the proposal matches it, a +person has nothing to add. That is the rule automatic-key-ceremony.md Phase 0.5 +set for the ceremony's own key state. `fc437d05` kept rotation states out of it +because they say more than a ceremony does. Phase 5 adds the rule for what they +say. + +--- + +## Phase 0: decisions + +**An hour. Each has a recommendation.** + +**Decided 2026-11-20: all six as recommended.** Execution began the same day. + +| # | question | recommendation | if decided otherwise | +|---|---|---|---| +| R1 | What does taking part consent to? | **The whole rotation.** `dealApprovedAt` keeps its column and name and now means "agreed to take part, with these members withheld". The member is not asked about this rotation again, and neither is the signature on its key state when that state is exactly what the rotation implies | Keep row 7 asked. A rotation still needs `t` taps after the certificate before the old shares are wiped, and in the meantime the old shares stay on every device | +| R2 | Is proposing the proposer's approval? | **Yes, once the proposal is a dialog that names who takes part and who is withheld, stale members included.** The reason the proposer is asked today is that "proposing is not agreeing to withhold whomever the form defaulted to". The fix for that is a form that shows its defaults. Asking again afterwards does not fix it | The proposer taps twice: the button, then the row. Harmless, but it is the same decision twice | +| R3 | Anything new on the wire? | **No.** Kinds 30340-30345, the tags and the ordering stay. A Giza build from before this change keeps its gates, and a rotation that includes it finishes when that member taps, as today. Rotation is behind `ExperimentalFeatures.shareRefresh`, off in release, so no shipped build is affected | — | +| R4 | The schema | **No migration.** `confirmApprovedAt` stays, unread, with KDoc saying earlier builds wrote it. `ShareRefreshApprovalStep.CONFIRM` stays in the enum because `approvalRequestedThrough` stores it by name on rows already written. This matches automatic-key-ceremony.md Phase 0.3 | Drop both in a schema bump: a migration and a migration test for two nullable values nothing reads | +| R5 | Bindings (10b) | **Still asked.** A key state that adds a `frost_member` binding re-binds an id to a new identity. That is governance, not arithmetic, and `fc437d05` was right to keep it asked. Phase 5 vouches only for a state whose bindings are exactly the ones already signed for that generation, which right after a rotation means none | — | +| R6 | A timer that abandons by itself? | **No**, as in the ceremony. The Shares section says who the rotation is waiting on and since when. Whether that is too long is for the group to judge | — | + +--- + +## Phase 1: pin today's gates + +**Two hours. Do this before changing anything.** + +`ShareRefreshRitualJvmTest` already has the multi-device harness (`devicesFor`, +`pump`, `approveAll`, `approveSigning`). What it lacks is a test that says where +the gates are. `approveAll` approves "whatever they are asked, until nobody is +asked anything", which passes whatever the gates are. + +Add, against today's behaviour: + +- **today's gates, pinned:** propose in a 2-of-3. Every recipient approves + exactly once (`DEAL`), then `pump` until quiet. Every recipient is at + `pendingApproval == CONFIRM`, nobody has a `PENDING` generation, and the + outbox holds round 1 and `cmsg1` and nothing more. Phase 2 flips this + assertion, and that flip is the change. +- **the key state, pinned:** run a rotation to COMPLETE with `approveAll`, then + `pump`. The `g+1` key-state session is open and awaiting approval on every + recipient, and generation `g` is still `RETIRING`, not `WIPED`. Phase 5 flips + this one. +- **counted asks:** a helper `asksOf(device)` that counts the + `TYPE_SHARE_REFRESH_APPROVAL_NEEDED` lines plus signing approval lines a device + wrote for one rotation. Today it is 3 per recipient. Phases 2, 4 and 5 take it + to 1. + +--- + +## Phase 2: the manager stops at taking part and nowhere else + +**Half a day. Closes G1 to G3.** + +In `ShareRefreshManager`: + +- **`advance`** loses the `confirmApprovedAt` block (`:415-418`). The `DEAL` + gate at `:391` stays and gets a comment: it is now the only gate. The steps + after it are already idempotent. `ownMessage(ROUND_2)` guards the send, and + `confirmAndStore` is idempotent for the session that holds the claim. Removing + the gate adds no path. It only stops cutting the existing one short. +- **`pendingApproval`** becomes: + + ```kotlin + if (session.stage == COMPLETE || session.stage == FAILED) return null + // ...key, base, myId as now... + if (myId !in session.recipientIdList()) return null + return if (session.dealApprovedAt == null) ShareRefreshApprovalStep.DEAL else null + ``` + + It is still "a step is pending exactly when `advance` would stop at it", which + is now easy to see. +- **`approve`** acts on `DEAL` only. A `CONFIRM` approval from a screen left open + across the upgrade cannot arrive any more (`pendingApproval` never returns + it), but the `when` keeps the arm as a logged no-op so the enum stays + exhaustive. +- **`announceApprovalNeeded`** only ever receives `DEAL`. The `CONFIRM` arm of + its `when` stays with a one-line comment saying nothing reaches it, so nobody + takes it for live wording. +- **KDoc.** The object's KDoc (`:63-64`, "at two gates") and + `ShareRefreshApprovalStep`'s become the record of what a rotation has *ever* + asked: one step still asked, one kept so old rows decode. Move the reasoning in + [Why `CONFIRM` was never a decision](#why-confirm-was-never-a-decision) into + the `CONFIRM` KDoc, so the next reader does not put the gate back. + `ShareRefreshSession.confirmApprovedAt` gets "written by builds before + docs/rotate-shares-single-approval.md; read by nothing". + +A round-2 fault keeps the failure path it has today: `raiseIfFaulty`, `fail`, +broadcast FAILURE. The difference is that it can now happen with nobody looking. +The transcript's *ended* line already covers that, and Phase 6 puts it in the +Shares section too. + +**Tests**, in `ShareRefreshRitualJvmTest`: + +- Phase 1's pinned assertion, flipped: each recipient approves once and every + device reaches COMPLETE at generation `g+1`, with no other call; +- `pendingApproval` never returns `CONFIRM`, sampled after every `pump` pass; +- the last recipient to approve sends round 1, and on the next pass round 2 + goes out with no further call; +- a coordinator that substitutes `cmsg1` in transit (the harness tampers with it) + fails the rotation on every honest recipient, with no approval in between, and + nobody holds a `PENDING` generation. This was always the protection, and the + test shows it no longer depends on a person; +- **the fork rule still holds without a person:** two proposals from one base, + both approved at `DEAL` by an overlapping recipient. That recipient confirms + one and fails the other, and at most one certificate exists. This is the + existing "a device confirms one refresh per generation" test, run with the + confirm gate gone. If it needed the gate to pass, the gate was carrying D3a, + and that has to be found now; +- "nothing of a member's own goes out before they approve" passes unchanged + (until Phase 4 changes the proposer's half of it). + +--- + +## Phase 3: running rotations resume without a message + +**Half a day. Closes G7. Ships with Phase 2.** + +With the `CONFIRM` tap gone, a rotation paused at `CONFIRM` by the old build has +`cmsg1` stored, is waiting on its own round 2, and will receive no more messages. +Without a sweep it never moves. + +```kotlin +/** + * Moves every running rotation of this user's as far as its stored messages + * allow. What a tap on "Store your new share" used to do, for rotations that + * already have everything they need and will receive nothing more. + */ +suspend fun resumeRunning(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int +``` + +- **What it selects:** a new `ShareRefreshDao.getRunningSessionsFor(userPublicKey)`, + sessions not COMPLETE or FAILED, oldest first. It does **not** filter on + `dealApprovedAt`. A coordinator waiting on others' round 1 and a withheld + device waiting on the certificate also have work a sweep can finish, and + `advance` stops at the `DEAL` gate for anyone not yet approved. +- **What it calls:** for each, look up the room (skip a gone room with a warning) + and `advance`. `advance` already returns at its first missing input. +- **Where it is wired:** `DatabaseNostrRepository.resumeRunningCeremonies`, after + `ChillDkgRitualManager.resumeRunning`, under the same `storeNostrEventMutex`. + Rename it to `resumeRunningRituals` while there, or leave the name and widen + its KDoc. It runs from `SynchronizationViewModel` once the live subscription is + open, so anything it publishes goes into a pipeline that is already running. +- **Behind the flag.** With `ExperimentalFeatures.shareRefresh` off it resumes + nothing. A release build has no rotations to resume. If one somehow exists, it + was refused on arrival. + +The same sweep covers the second half of G6 for upgrades. A `g+1` key-state +session that an old build left awaiting approval is re-checked against +`vouchesFor` (Phase 5). That part lands with Phase 5, which owns the rule. + +**Tests:** + +- **the upgrade case:** a session with `cmsg1` stored, `dealApprovedAt` set, + `confirmApprovedAt` null, `approvalRequestedThrough = CONFIRM`, which is + exactly what the old build leaves. Run the sweep with no message arriving. It + publishes round 2, and on the harness the rotation completes; +- a session never approved at `DEAL` is advanced but sends nothing; +- a FAILED or COMPLETE session is not touched; +- two sweeps in a row publish nothing twice; +- with the flag off, the sweep does nothing. + +--- + +## Phase 4: proposing is the proposer's approval + +**Half a day. Closes G4. Only if R2 is decided as recommended.** + +The proposer is asked today because the button commits them to a withheld list +they were never shown. The fix is to show it. + +- **A dialog behind *Rotate shares*.** `AlertDialog` in `ChatRoomDetailScreen`, + in the style of the existing `rotate_shares_without_*` dialog. It shows: + - *Taking part*: every live member's name; + - *Left out until they are brought back*: every stale member, who + `proposeRefresh` withholds again automatically (`:139-143`). Today the + proposer never sees this list; + - the existing `shares_rotation_caveat` copy; + - confirm **Rotate shares**, dismiss **Not now**. + + It reads from a new `ChatRepository.rotationPreview(localChatRoom)` that runs + the same selection `proposeRefresh` does, and `refusal`, so a rotation that + would be refused says why before the tap rather than as a snackbar after it. + `proposeRefresh` and the preview share one private function for the + recipient/withheld split, so they cannot drift. +- **The removal dialog** (`rotate_shares_without_body`) gains the same stale list + when there is one. The removed member is already named. +- **`proposeRefresh`** sets `dealApprovedAt = now` on the session it creates. The + KDoc at `:111-116` becomes: proposing, from a dialog that named everyone + withheld, is agreeing to the rotation, and the proposer is not asked again. + `proposeWithout` inherits it. +- **The repository API** keeps `rotateShares(localChatRoom)`. The dialog is where + the decision is shown, and the manager does not need to know a dialog exists. + +Strings go in `strings.xml`, sentence case: `rotation_taking_part`, +`rotation_left_out_until_brought_back`, `not_now` if not already there. + +**Tests:** + +- the proposer's half of "nothing of a member's own goes out before they + approve" flips. The proposer publishes the proposal and its round 1 in the one + `proposeRefresh` call, and writes no approval-needed line. The other + recipients' half is unchanged; +- `rotationPreview` and `proposeRefresh` agree on recipients and withheld for + every fixture: 0, 1 and 2 stale, and a retired member; +- a preview of a rotation that `refusal` rejects carries the reason and no + recipients. + +--- + +## Phase 5: a rotation's key state signs itself + +**A day. Closes G5 and G6.** + +`GroupKeyStateManager.vouchesFor` signs exactly one statement per room: the key +state of a ceremony this device finished. Rule 8 (`fc437d05`) keeps every +generation state out. This phase replaces rule 8 with the rule for the one +generation state that can be true. + +**The rule.** For a claim with `generation = h ≥ 1`, rules 1 to 6 stand as they +are. Rules 7 and 8 become: + +7. **No state for this room is signed here at generation `h` or later.** This + replaces "no state at all", which would refuse every rotation, since a room + that rotates already has a generation-0 state. +8. **This device completed the rotation that made `h`:** + - `KeyShareGeneration(key, h)` exists here, is `ACTIVE`, and holds a secret + share. A device withheld from `h` cannot sign at `h` anyway, and should not + vouch for a table it did not help make; + - its `refreshSessionId` equals the claim's `frost_refresh`, and that + `ShareRefreshSession` is COMPLETE here; + - the claim's `frost_pubshares` equals + `ShareGenerations.publicSharesHash(` that row's `publicShares` `)`; + - the claim's `frost_retired` ids equal the ids `RETIRED` in this device's + roster at `h`; + - the claim's bindings equal the bindings already in a group-signed state at + `h` on this device. Right after a rotation that is none. A state that adds + a binding is a 10b re-bind and stays asked (R5); + - the signing session's `generation` is `h`. +9. **Path and parent match the room's signed state**, not only the admin path. + `proposeGeneration` copies them from `keyStateFor`, so a claim whose path or + birth certificate differs from what the room already signed is not the one + true statement. + +Each condition calls what already exists (`claimFrom`, `stateAmong`, +`ShareGenerations.publicSharesHash`, the key-share DAO). None of it is copied, +for the reason automatic-key-ceremony.md Phase 7 gives: the rule for signing and +the rule for keeping must be one function. + +**Asking again when the answer can change (G6).** Vouching is decided once, when +the proposal arrives (`FrostSigningManager.kt:447`). For a rotation that is +often too early. The coordinator proposes the `g+1` state the moment its own +certificate verifies, and a recipient can receive the proposal before the +certificate, while `h` is still `PENDING` here. Two changes: + +- `FrostSigningManager.resumeAt(database, room, dkgSessionId, generation)`, + which `ShareRefreshManager.advance` already calls after `activate`, runs + `signsAsItsOwnKeyState` on each open session at that generation before + advancing it, and approves the ones it vouches for; +- Phase 3's sweep does the same for open key-state sessions, for the upgrade + case: a session an old build left asking. + +`signsAsItsOwnKeyState` already refuses a session that has been approved or +declined, so a person who answered first keeps their answer. + +**What stays asked.** Anything that fails a check takes the normal path: the +approval line, the proposal, the member's decision. Failing a check is not a +reason to decline. It means the device cannot vouch for the statement, so a +person has to. That includes a key state proposed by a member whose rotation +this device never saw. That should not happen, and if it does, a person should +look. + +**Tests**, in `ShareRefreshRitualJvmTest` and `KeyStateSignsItselfJvmTest`: + +- Phase 1's key-state assertion, flipped: each recipient approves `DEAL` once. + With no other call, the group signs the `g+1` key state, every device wipes + generation `g`, and the group signs at `g+1` as the same room. `asksOf` is 1 + per recipient (0 for the proposer after Phase 4); +- **the race:** the proposal for the `g+1` state is delivered before the + certificate. It is not vouched for on arrival, and is vouched for when the + certificate activates `h`; +- each check broken on its own leaves the session at `isAwaitingApproval`: + - a different `frost_pubshares`; + - a `frost_refresh` naming a rotation this device did not complete; + - a retired id added or missing; + - a new binding (the 10b test's re-bind state stays asked, so its + `approveSigning(listOf(alice, bob))` call is still needed); + - a session at generation `h−1`; + - a device withheld from `h`; + - a room already holding a signed state at `h`; + - a path or parent that differs from the room's signed state; +- `fc437d05`'s regression stays covered: a generation-1 state on devices that + hold no first state still needs every rule to pass, and is asked when one + fails; +- every existing `KeyStateSignsItselfJvmTest` case passes unedited for + generation-0 states. + +--- + +## Phase 6: the Shares section, with one approval + +**A day. Closes G8 to G10.** + +Under CLAUDE.md's rules: strings in the catalogue in sentence case, spacing and +colour from the theme, outcomes through `rememberNotifier`, `Decorative` on any +icon whose label sits beside it. + +**The approval row says what it decides (G10).** + +- `SharesSummary.PendingApproval` gains `withheld: List`, each with a + display name and `STALE` or `RETIRED`, filled in by + `DatabaseChatRepository.sharesSummary` from the session's `withheldStandings()`. +- The `REFRESH_DEAL` row's headline becomes *Take part in rotating the shares*, + as now. Its `supportingContent` becomes one of: + - *Every member takes part.* + - *Without Alice until they are brought back, and without Bob for good.* Built + from format arguments, not concatenation, with a plural-safe form for one + name or several. + - A line on what taking part now commits to: *Your device sends its part, + stores your new share and signs the group's new key state without asking + again.* +- The row keeps **Abandon** and **Approve**. + +**`REFRESH_CONFIRM` goes (G8).** The enum value in `SharesSummary.PendingApproval.Kind` +is UI state only, so it is removed outright, along with its arm in +`sharesSummary` and `approveShares` and the `pending_rotation_confirm` string. +Run `m3-extract-strings.py --list` afterwards to catch any other orphans. + +**A running rotation is visible, and can be abandoned, for its whole run (G9).** + +- `SharesSummary` gains `running: Running?`, with the session id, the stage in + words (*dealing*, *storing the new shares*, *signing the new key state*), the + members it is waiting on, the time of the newest `ShareRefreshMessage` for the + session, and `canAbandon` (this device is a recipient). The rotation counts as + running until the `g+1` key state is signed, not only until the certificate, + because that signature is what the old shares wait on. +- "Waiting on" comes from stored rows: recipients with no round 1, then no round + 2, then the coordinator's sum or certificate, then the key-state session's + missing signers. The stall clock is dated from the newest message, not the + newest transcript line, for the reason automatic-key-ceremony.md's build table + gives: `ShareRefreshManager.record` must store a message once, on first + arrival. Check that it does (`:343-344` upserts on every redelivery, which + rewrites the row) and fix it the way `ChillDkgRitualManager.record` was fixed. +- The Shares section shows it as a card above the members: *Rotating the + shares*, the stage, *Waiting on Carol since yesterday*, and **Abandon** when + `canAbandon`, behind the existing confirmation. It sits above the member list + because a stall is the most important thing in the section when there is one. +- A rotation that ended shows its reason from `failureReason` until the next one + starts, so a fault found with nobody looking is not lost in the transcript. + +**The transcript** needs no code change. Check it rather than assume it. +`CONFIRM` approval-needed lines already written by the old build still render, +and the automatic round 2 writes the same `TYPE_SHARE_REFRESH_CONFIRMED` line a +tapped one did. Each device now writes one approval-needed line per rotation +instead of two. + +**Tests:** + +- a `SharesSummary` test that the `DEAL` row carries the withheld list, and that + no `REFRESH_CONFIRM` kind exists; +- `running` names the right members at each stage, including the key-state + stage after the certificate; +- `canAbandon` is true for a recipient who has already approved, and false for a + withheld member; +- a redelivered round 1 does not move the stall clock; +- `./gradlew :composeApp:m3Audit` at its budgets, floors not moved. + +--- + +## Phase 7: the record, and three emulators + +**Half a day of docs, then a device session.** + +- **frost-share-refresh.md**: Phase 7's *Approval gates* table shrinks to one + row, with a short history of `CONFIRM` (why it existed, why it went, why the + enum value and column remain). Phase 8's step 2 says the key state signs itself + under the rule in this plan's Phase 5. Phase 11's bullet *the two approvals* + becomes one. The build table gains a row pointing here. +- **automatic-key-ceremony.md**, *What this does not do*: "It does not automate + signatures other than the key state" gains "a rotation's key state is + automated too, by rotate-shares-single-approval.md". +- **README.md**: this note's row, and frost-share-refresh.md's row, which still + says "not built" although it is. +- **This note**: a *Built* header and a table of where the build chose + differently. + +**On three emulators** (Bob, Charlie, Medium), a debug build so the flag is on: + +1. A 2-of-3 room. Bob presses **Rotate shares** and confirms the dialog. Charlie + and Medium each tap **Approve** once. Nobody touches anything else. All three + show generation 1, and the transcript shows the key state signed and no + second approval line. +2. Remove Medium. Bob rotates without them from the dialog. Charlie taps once. + Medium's standing is *retired*. +3. **The upgrade:** on the current build, stop a rotation at *Store your new + share* on all three, install this build over it, and open the app. It should + finish from the sweep alone. +4. Charlie approves and then force-stops the app. Bob's and Medium's Shares + section name Charlie and how long they have been waiting, and **Abandon** + ends the rotation on all three. + +`./gradlew check` must pass: `m3-audit`, `brand-audit`, `wallet-audit`. + +--- + +## What this does not do + +- **It does not run while the app is closed.** The live subscription is + foreground-only ([long-running-sync.md](./long-running-sync.md)). After + approving, each member's device still has to be opened once the others have + dealt, again once the coordinator has summed, and again for the key state. + What changes is that opening the app is enough. +- **It does not change the protocol.** Every recipient still has to take part + (D2), the majority and write-once rules (D3) still hold, and the old share is + still wiped only after the group signs the new generation (D6). This plan only + changes who presses what. +- **It does not change older peers.** A build from before this change still asks + at both gates, and a rotation that includes one waits for that member's taps. + D5's capability check is still unbuilt, so nothing tells the proposer in + advance. +- **It does not automate repair.** A helper's approval in a repair (10a) spends + its share's secrecy on the target's behalf. That is a decision about someone + else, and stays asked. +- **It does not automate re-binding an id to a new identity** (10b, R5). +- **It does not add a way to decline.** A member who does not want to take part + abandons, which ends the rotation for everyone. A rotation cannot finish + without every recipient, so a quiet "no" and a loud one end the same way. The + loud one is just faster. + +## Order and size + +| phase | size | depends on | +|---|---|---| +| 0 decisions | an hour | — | +| 1 pin today's gates | two hours | — | +| 2 manager: one gate | half a day | 1 | +| 3 resume sweep | half a day | 2 | +| 4 proposing is approving | half a day | 2, R2 | +| 5 the key state signs itself | a day | 2 | +| 6 Shares section | a day | 2, 5 (for the key-state stage) | +| 7 docs, emulators | half a day plus a session | all | + +**Phases 2 and 3 ship together.** With 2 and without 3, a rotation paused by the +old build at *Store your new share* sits still until a message happens to +arrive. **Phase 6's abandon card ships with Phase 2 or before it.** Without it, a +member who has approved has no way to end a stalled rotation (G9). Phases 4 and 5 +are independent of each other and can land in either order. Everything is behind +`ExperimentalFeatures.shareRefresh`, so no phase changes a release build. From f2b0aa91d476b8924cc34f29b4decdd2bcb0bcc6 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:50:34 +0200 Subject: [PATCH 07/23] docs: every founding member of a robust group is its admin, phased Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + docs/robust-group-admins.md | 269 ++++++++++++++++++++++++++++++++++++ 2 files changed, 270 insertions(+) create mode 100644 docs/robust-group-admins.md diff --git a/docs/README.md b/docs/README.md index 5208a9ba..a3f287de 100644 --- a/docs/README.md +++ b/docs/README.md @@ -36,6 +36,7 @@ the [retired](./retired/) notes now. | [marmot-kmp.md](./marmot-kmp.md) | moving the group layer off quartz's engine and onto marmot-kmp, mls-kmp and crypto-kmp — why staying on quartz 1.15.2 is staying on an engine that left, the 228 import lines and the one rule that places all but two of them, the group state on a device that must still open afterwards, nine phases that put the swap in one commit and the evidence around it, how often this app persists a group once a sent message no longer rewrites it, and the schema change that followed, opened from the version the app ships | | [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and built but for moving off the wallet library (7b). Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase | | [giza-rebrand.md](./giza-rebrand.md) | forking Bennu as Giza under `mobi.giza` — what carries the name, what must not be renamed and why, why the desktop data directory changes first, and how the fork keeps merging from Bennu | +| [robust-group-admins.md](./robust-group-admins.md) | making every founding member of a robust group an admin of its room, on every device -- phased and not built. Covers why the ceremony's participants are the founding set, the Welcome that flags no admins, the joiner's check against the ceremony it took part in, and finishing an invite that partly failed | Start with the ceremony if you are new to this area; the Marmot notes all assume it. Read the skipped-keys note before debugging any "the other device never got it" diff --git a/docs/robust-group-admins.md b/docs/robust-group-admins.md new file mode 100644 index 00000000..3abb6483 --- /dev/null +++ b/docs/robust-group-admins.md @@ -0,0 +1,269 @@ +# Every founding member of a robust group is its admin + +A robust group promises, on the screen that makes it, that "everyone administers the +group together". This note is the plan that makes the promise true on every device from +the moment the group exists: what "founding member" means, the four places the promise +breaks today, and seven phases that close them. + +**Planned, not built.** Written against `fc437d05`. + +Read [shared-key-ceremony.md](./shared-key-ceremony.md) and +[ceremony-creation.md](./ceremony-creation.md) first. + +## What a robust group is, in the code + +A robust group is two rooms and a key. + +``` +SelectChatRoomTypeViewModel.createNip17ChatRoom + │ + ├─ the NIP-17 room members = picked + creator; no admins, no MLS + │ └─ proposeRitual ceremony participants = room members + creator + │ + ├─ the ChillDKG key t-of-n over those participants + │ + └─ the admin room (Marmot) id = marmotGroupId(threshold key) + created by CeremonyFollowThrough (step 3) or DkgRitualViewModel, + both through MarmotGroupCreation.create(adminPublicKeys = participantsOf(session)) +``` + +The NIP-17 room has no admin concept, and that is correct: membership is the p-tag set +and nothing in it can be governed. **Admin means admin of the Marmot room**, whose +epoch-0 admin policy (`AdminPolicyV1` on the current profile, `MarmotGroupData.admin_pubkeys` +on the legacy one) is what the library enforces and what `isLocalAdmin()` reads. +`Participant.adminAt` is a local cache of it. + +A subgroup is the same shape with a different participant set, and everything below +applies to it unchanged. + +`ChatRoomType` is not persisted. Nothing on a device records that a room was made robust; +what marks one is a `GroupKeyState` -- a room whose id is derived from a threshold key. + +## What "founding member" means + +**D1. The founding members of a key-backed room are the participants of the ceremony that +made its key** -- `DkgSession.participantPublicKeySet()` on the row +`GroupKeyState.dkgSessionId` names. For a top-level robust group that is the picked members +plus the creator; for a subgroup, the picked admins plus the coordinator. + +Not the NIP-17 room's rows, which `ChillDkgRitualManager.memberPublicKeys` already warns +can drift. Not the admin list a Welcome arrives with, which is one device's claim. The +session row is the one record every founding member's device built independently from the +proposal it agreed to, and the ceremony would not have completed if they disagreed about `n`. + +A member added to the admin room later is not a founding member and is not made an admin by +anything here. + +## Where the promise breaks today + +| | gap | effect | phase | +|---|---|---|---| +| G1 | The founding set is computed at three call sites -- `SelectChatRoomTypeViewModel.adminCount`, `CeremonyFollowThrough.takeNextStep` step 3, `DkgRitualViewModel` -- and passed into `MarmotGroupCreation.create` as a free parameter. `participantsOf` falls back to the room's rows when the session carries no set | nothing stops a caller passing a different set; a room's admin list is fixed at a derived address forever, so one wrong call is permanent | 1 | +| G2 | The Welcome path in `NostrDao` writes `Participant.fromMlsGroup(...)` rows with no `adminAt`. Only the creator (`stampAdmins`) and a later commit (`processGroupMembershipChanges`) ever set it | on every device but the creator's, the admin room shows no admins until some other commit arrives -- which may be never | 2 | +| G3 | A joiner never checks the admin list it was welcomed into against the ceremony it took part in | a device that created the room with a different list (a bug, an older build, a Bennu peer) goes unnoticed | 3 | +| G4 | `MarmotGroupCreation.create` returns `notAdded` when `addMembers` partly fails. Those founding members are listed as admins but hold no leaf, so the policy treats them as inactive, and nothing invites them again | a founding admin who is not in the room | 4 | + +G2 has a smaller blast radius than it sounds: `canGovern` reads `isLocalAdmin()`, and +`SubgroupManager` reads `currentAdminIdentities()`, so permissions are right. What is wrong +is every reader of `adminAt` -- today the subgroup picker's "Admin of this group" line -- +and the fact that two devices disagree about the same room. + +## Decisions + +**D2. The admin policy is the truth; `adminAt` is derived from it on every path.** One +function writes the flags, from `mlsGroup.currentAdminIdentities()`, and the creation, +Welcome and commit paths all call it. `stampAdmins` stops taking a list of its own. + +**D3. No wire change.** Putting the founding set on the signed `GroupKeyStateEvent` (so a +quorum signs it) was considered and left out: every founding member already holds the set +on its own session row, a later joiner is by definition not one of them, and the 30326 event +is shared with Bennu. Revisit if a device ever needs to check the founding set without +having taken part. + +**D4. No schema change.** Every check below is derived on demand from rows that already +exist -- the session, the key state, the stored MLS group, the participant rows -- so no +Room migration and no new column. + +## Phases + +One commit per phase. Each phase ends with: + +```bash +./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest +``` + +and phases that touch UI also with: + +```bash +./gradlew :composeApp:m3Audit +``` + +### Phase 0: pin the invariant in a failing test + +Before changing anything, a test that states the promise and shows where it fails. + +**Add** `composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt`, +on the `CeremonyNetwork` harness `RobustRoomKeyCeremonyTest` uses, with three devices: + +- `every founding member is an admin of the room the key makes, on every device` -- run the + ceremony and follow-through, deliver the Welcomes, then on each device assert + `currentAdminIdentities() == participants`, `isLocalAdmin()` and `adminAt != null` on + exactly the founding rows. **Expected to fail on `adminAt` for the two joiners (G2).** +- `the founding set is the same set at every step` -- picked + creator, the NIP-17 room's + members, the session's participants and the admin policy are one set. +- `a member added after the founding is not an admin` -- the boundary D1 draws. +- The same three for a subgroup, on the `SubgroupCeremonyInParentRoomTest` fixtures. + +Mark the failing assertions `@Ignore("Phase 2")` and the like, so the build stays green and +each phase un-ignores what it fixes. + +**Done when** the test exists, the passing parts pass, and each ignored part names its phase. + +### Phase 1: one derivation of the founding set (G1) + +**Change** `ChatRepository.createMarmotGroup` / `MarmotGroupCreation.create` to take the +`DkgSession` instead of `adminPublicKeys`, and derive the set inside, through a new +`ChillDkgRitualManager.foundingMembersOf(session, room)`: + +- returns `session.participantPublicKeySet()` when present; +- falls back to the room's members only for a row that predates the column (logged), as + `participantsOf` does today; +- requires the creating device to be in the set -- a device outside the ceremony holds no + key state for the room and should never get here, so reaching it is a bug, not an outcome. + +The two call sites (`CeremonyFollowThrough.takeNextStep` step 3 and +`DkgRitualViewModel`'s admin-room action) stop computing a set. `SelectChatRoomTypeViewModel` +keeps `adminCount` -- the session does not exist yet on that screen -- but computes it with +the same `(members + creator).distinct()` rule `proposeRitual` uses, and a comment points at +the other. + +**Tests.** `MarmotGroupCreationJvmTest`: `the room's admins are the ceremony's participants, +whoever creates it` -- the coordinator's path and a non-coordinator's manual path produce +the same admin policy. `CeremonyFollowThroughJvmTest` keeps passing unchanged. + +**Done when** no caller can name a room's admins. + +### Phase 2: the Welcome writes admin flags (G2) + +**Add** `AdminFlags.reconcile(database, localChatRoom, mlsGroup)` in `managers/` -- flags +only, never membership: sets `adminAt` on rows the policy names and clears it on rows it +does not. It is `processGroupMembershipChanges`'s `graduatedAdmins` / `removedAdmins` / +new-participant logic, lifted out. + +**Call it** from: + +- the Welcome path in `NostrDao` (after the participant upsert, before + `GroupKeyStateManager.adopt`); +- `MarmotGroupCreation`, replacing `stampAdmins`. Its reasoning -- flags are safe, a + membership reconciliation on a best-effort step is not -- moves to the new function's KDoc; +- `processGroupMembershipChanges`, replacing its three inline admin computations. + +Having `Participant.fromMlsGroup` set `adminAt` itself would fix the Welcome alone, but it +only ever builds new rows: it cannot clear a flag on a stored one, so half the logic would +still live somewhere else. One function that does both is the point of D2. + +**Tests.** Un-ignore Phase 0's joiner assertions. Add to `WelcomeBundleMatchJvmTest`: +`a member welcomed into a room sees its admins at once`. + +**Done when** every device shows the same admins the moment it holds the room. + +### Phase 3: a joiner checks what it was welcomed into (G3) + +**Add** `FoundingAdmins.check(database, localChatRoom): Check` in `managers/`, returning one +of: + +- `NotKeyBacked` -- no key state; a convenient room, nothing to check; +- `CannotCheck` -- key state, but this device holds no session for it (a later joiner); +- `Matches` -- every founding member is in the admin policy; +- `Missing(publicKeys: Set)` -- founding members the policy does not name, against + `foundingMembersOf`. For a subgroup, also against the birth certificate's + `SubgroupBirthCertificateEvent.parseAdminPublicKeys`, which the parent's quorum signed. + +**Call it** once at the Welcome, after `adopt`, and write a transcript line on `Missing` +(a new `ChatMessage.TYPE_FOUNDING_ADMINS_MISSING`, derived like the membership captions). +And on every load of `ChatRoomDetailViewModel`, into a new +`ChatRoomDetailUIState.Loaded.foundingAdmins` field. + +The room is not left or refused. Its address is the key, and there is no second room to go +to; a warning that names who is missing is what can be acted on. + +**Repair**, where this device is an active admin: an "Make founding members admins" action +adds the missing ones to the policy in one admin-policy update commit. Additions only -- the +commit is built from the current policy plus `Missing`, never as a replacement list. + +**Tests.** `FoundingAdminsJvmTest`: one case per `Check`, including a Welcome built by a +device that listed only itself, and the repair commit leaving every existing admin in place. + +**Done when** a founding member left out of the admin policy is said, on the device that +can see it, and can be put back by any admin. + +### Phase 4: every founding admin is invited (G4) + +**Add step 4 to `CeremonyFollowThrough.takeNextStep`**, after the room exists: founding +members who have never had a row in the room -- not even a soft-deleted one -- are invited +with `addMembers`, one commit for all of them. "Never had a row" keeps this step to +finishing the founding invite: it never re-invites anybody who was in the room and left it. +Read-then-act like the other steps, so a repeat does nothing. + +Who acts: the coordinator, as for step 3, so two devices do not race the same epoch. Any +other active admin gets an "Invite again" action on the detail screen for the same set, for +the case the coordinator's phone is in a drawer. + +A founding member with no key package is reported as `BlockedOn`, exactly as creation does, +and the step is retried the next time the follow-through runs. + +**Tests.** `CeremonyFollowThroughJvmTest`: `a founding member the first invite missed is +invited again`, `a founding member who was in the room is not`, and `a second run invites +nobody`. + +**Done when** `Outcome.Created.notAdded` is something the follow-through finishes, not +something a screen reports and forgets. + +### Phase 5: show it + +- The admin room's member list shows "Admin" as supporting text on rows with `adminAt`. +- Phase 3's warning card and repair action, and Phase 4's "Invite again", on the detail + screen. +- The NIP-17 room's detail says its members administer the group through the admin room, + with a link to it, rather than showing no admins. + +Strings in `strings.xml`, sentence case; every new button a 48dp target; the card's states +through `ScreenStateTransition`. The m3 audit is the check. + +**Done when** a person can tell who administers the group, and whether that is everybody who +made it, without reading a transcript. + +### Phase 6: rooms that already exist + +No migration is needed (D4), but the rooms made before Phase 2 still carry unflagged +joiner rows and possibly uninvited founding admins. + +- `AdminFlags.reconcile` runs once per Marmot room at startup, behind a stored + "reconciled" preference, so G2 is repaired without waiting for a commit. +- Phase 4's step already runs over every completed session; it covers G4 for old rooms. +- Phase 3's check runs on every detail load; it covers G3 for old rooms. + +**Tests.** A fixture room with joiner rows missing `adminAt` is reconciled on start, once. + +### Phase 7: docs + +- This note: mark it built, with a table of where the build chose differently. +- [ceremony-creation.md](./ceremony-creation.md) and [subgroups.md](./subgroups.md): link + here from the admin-room creation sections. +- [README.md](./README.md): the table row is added with this note. + +## Out of scope + +- **Removing or demoting an admin**, founding or not. This plan makes the founding members + admins; what happens to them afterwards is left as it is. +- **Making a later member an admin.** A separate feature, being planned separately. +- **Convenient groups.** Their only admin is the creator, by design. +- **The NIP-17 room.** It has no state to govern; see *What a robust group is*. + +## Risks + +- **Bennu peers.** One can create the admin room with a different list; Phase 3 can say so + and repair it, but not prevent it. +- **Racing invites.** Phase 4 is coordinator-first to avoid two commits on one epoch; the + manual "Invite again" can still race, and convergence already resolves that fork + (`ConvergenceForkJvmTest`). From 2664f6ca47f63d9a792515e3a5e4dca282570831 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:51:51 +0200 Subject: [PATCH 08/23] docs: a rotation waits for the last one to be signed, built (Phase 5) frost-share-refresh.md records the new refusal (the proposer's own check only), strikes "the proposer is auto-approved for nothing" for the rule that replaced it, and gives the work a row. The plan is marked built, with where the build chose differently. ./gradlew check: jvmTest 1240/1240, testDebugUnitTest 496/496, lint, audits. Co-Authored-By: Claude Opus 5.5 --- docs/frost-share-refresh.md | 19 +++++++++++++++---- docs/rotation-waits-for-key-state.md | 19 ++++++++++++++++++- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index 2ba0b94a..4fb4a277 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -26,6 +26,7 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | 11 | `99229090` | `compileDebugKotlinAndroid`; the M3 audit at its budgets. **Not seen on a device or a desktop window** | | 12 | `4949f0fe` | `ShareRefreshRitualJvmTest`: three refreshes in a row, then the recovery walk from the generation-0 share lands on every device's live share, each generation checked against its table. `jvmTest` 1200/1200 | | 13 | `99229090` | `ShareRefreshRitualJvmTest`: with the flag off, the recipients decline a rotation out loud and it fails; proposing one throws. Android, desktop and iOS device checks not done | +| after 13 | `159ae402`, `d358a0db`, `98567629`, `95131248` | [rotation-waits-for-key-state.md](./rotation-waits-for-key-state.md): a rotation waits for the group to sign the last one's key state, the Shares section says why, follows the group while open, and the proposer is not asked about their own rotation. `ShareRefreshRitualJvmTest` 25/25, `ChatRoomDetailSharesJvmTest` 3/3; `./gradlew check` (`jvmTest` 1240/1240, `testDebugUnitTest` 496/496, lint, audits). **Not seen on a device or a desktop window** | | 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | | 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | @@ -48,7 +49,7 @@ Where the build chose differently from the plan: | Phase 7: the refusals | one more: every participant not retired has to be a recipient or withheld, so a proposal cannot leave someone in neither list. A participant stale at the base generation is withheld again, as stale, automatically: a refresh brings nobody back, a repair does. A recipient that refuses a proposal on arrival broadcasts a failure, since the certificate needs it; anyone else refuses silently. D5's capability check waits for Phase 13 | | Phase 7: a kill between storing the pending generation and sending the confirmation | handled the way the plan said -- `confirmAndStore` is idempotent for the refresh that holds the claim, so the next pass stores it again and sends -- but not tested on its own | | Phase 7: the transcript | system lines through `RitualNotice`, settled. The request line opens nothing until the refresh screen exists (Phase 11) | -| Phase 8: any recipient proposes the new key state | the coordinator does, automatically, the moment its refresh completes; anyone can again. That races the certificate to the other devices, and lost in the first test run: a device still holding the generation as pending declined. A proposal at a generation this device has confirmed and is waiting on the certificate for now waits instead, and the refresh resumes it on activation (`FrostSigningManager.resumeAt`) | +| Phase 8: any recipient proposes the new key state | the coordinator does, automatically, the moment its refresh completes; anyone can again. That races the certificate to the other devices, and lost in the first test run: a device still holding the generation as pending declined. A proposal at a generation this device has confirmed and is waiting on the certificate for now waits instead, and the refresh resumes it on activation (`FrostSigningManager.resumeAt`). "Anyone can again" had no button until [rotation-waits-for-key-state.md](./rotation-waits-for-key-state.md): the Shares section offers it when the key state is owed and nobody is asking | | Phase 8: `ShareRefreshCutoverJvmTest` | the cutover tests live in `ShareRefreshRitualJvmTest`, which has the multi-device harness. The bytes-on-disk check is `SecureDeleteJvmTest`'s, against a file; these devices are in memory. A device that disagrees with the group's table keeps its share and logs it, untested | | Phase 8: gen-0's randomness nulled | emptied: `round1Random` and `round2AuxRandom` are not nullable, and a complete ceremony never reads them again | | Phase 9: an action on the members screen | a dialog the room detail screen raises after a removal succeeds, when the member held a live share (asked before the removal, while they are still in the roster). "Not now" leaves it; nothing offers it again yet -- Phase 11's Shares section is where a rotation can be started at any time. `MemberRemovalRefreshJvmTest` is two tests in the ritual harness | @@ -477,7 +478,12 @@ host keys, so a room-wide message is fine here, which it is **not** for repair ( enforced with a write-once column on `KeyShareGeneration`, set in the same transaction that stores the `PENDING` row. **It is as important as the nonce rules, and for the same reason: it is the one way the group splits.** -- an open ChillDKG or refresh for the same key. +- an open ChillDKG or refresh for the same key; +- **on the proposer's device only**, a rotation whose key state the group has not signed yet, a + key-state proposal still open there, or a device behind the group + ([rotation-waits-for-key-state.md](./rotation-waits-for-key-state.md), + `ShareRefreshManager.rotationHold`). Not on arrival: a recipient a few seconds behind on the + signature would end a rotation that was fine. **Approval gates.** Two, mirroring the ceremony's, with `pendingApproval` mirroring `advance` exactly: @@ -487,8 +493,13 @@ exactly: | `DEAL` | round 1 | joins the refresh and agrees to the withheld list. Withholding someone is a decision about them, so every recipient makes it, not only the proposer | | `CONFIRM` | CertEq | commits to the new generation. This is what stops a coordinator substituting a table the recipients never dealt | -The proposer is auto-approved for nothing. Proposing a refresh is not agreeing to withhold -whomever the form defaulted to. +~~The proposer is auto-approved for nothing. Proposing a refresh is not agreeing to withhold +whomever the form defaulted to.~~ The proposer is approved at both gates on proposal +([rotation-waits-for-key-state.md](./rotation-waits-for-key-state.md), Phase 4). The form no +longer defaults silently: the Shares section's button asks first in a dialog naming everyone +the rotation leaves out, so the tap is the `DEAL` decision; and the proposer is the coordinator +`CONFIRM` guards against, whose own CertEq check does that work. Every other recipient is asked +at both gates. **Transcript.** System lines in the room, as the ceremony writes them, idempotent by reading the row before writing: diff --git a/docs/rotation-waits-for-key-state.md b/docs/rotation-waits-for-key-state.md index 324ca10e..d8c6a2ac 100644 --- a/docs/rotation-waits-for-key-state.md +++ b/docs/rotation-waits-for-key-state.md @@ -10,7 +10,24 @@ approval gates, Phase 8 (the cutover) and D6 (when the old share is wiped). Read asks its owner only for decisions the device cannot make on its own", is the precedent for Phase 4 here. -**Not built.** Planned against `fc437d05`. +**Built**, one commit per phase on `claude/rotate-shares-pending-proposal-9d72d7` +(`159ae402`, `d358a0db`, `98567629`, `95131248`), against the code as it stood at +`fc437d05`. The phases are kept as written because they are the reasoning. Where the +build chose differently: + +| what the plan said | what it turned out to be | +|---|---| +| R1(c)'s open question: does a key-state session nobody finishes ever fail here? | Only once `participantCount - threshold + 1` members have declined (`FrostSigningSession.declinesThatAbandon`), so one refusal does not end it. An open session counts **unless this device declined it**. The coordinator who proposed it cannot decline its own, and stays held until others do or it completes | +| Phase 2's `ChatRepository.proposeKeyState` does the work | the work is `ShareRefreshManager.proposeOwedKeyState`, which the repository wraps, so it is tested in the ritual harness without building an `Identity` | +| Phase 2's held line links to the proposals | a **See the proposal** button under the line, to `ProposalListRoute` | +| Phase 2's summary tests are their own file | two tests in `ShareRefreshRitualJvmTest`, reading `DatabaseChatRepository.sharesSummary` on the harness's devices through every `Rotation` value, the re-ask included | +| Phase 3 recomputes on repairs too, or leaves them out | left out: `ShareRepairDao` has no observable query | +| Phase 4's dialog says "%1$s will be left out again…" | a line, then one name per line. Joining names into one string needs a separator the catalogue cannot hold | +| Phase 4's crossing proposals end in one completed refresh or one a recipient can abandon | each proposer is a recipient of the other's proposal and refuses it on arrival ("another refresh of this key is still running here"), out loud, so neither is left running. The test asserts the property, not which one survives: nothing running, at most one complete, every device on one table | + +**Not done:** none of it has been seen on a device or a desktop window: the disabled +button and its line, the re-ask, the confirmation dialog, or the section updating while +open. --- From 18f426ca46304d294ab10209a56626ba90f1cb5d Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:51:54 +0200 Subject: [PATCH 09/23] test: a rotation's approvals, counted as they are today (rotate-shares-single-approval, Phase 1) Three tests pin where a rotation stops for its owners, so the phases that remove those stops flip an assertion rather than pass by accident: taking part alone leaves every recipient asked to store the new share; a recipient is asked to take part, to store, and to sign the new key state (the proposer the first two); and a completed rotation keeps the old shares until the owners sign. answerEverything records each ask. ShareRefreshRitualJvmTest 20/20. Co-Authored-By: Claude Opus 5.5 --- .../managers/ShareRefreshRitualJvmTest.kt | 116 ++++++++++++++++++ 1 file changed, 116 insertions(+) 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..2d78f976 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -176,6 +176,47 @@ class ShareRefreshRitualJvmTest { private suspend fun propose(by: Device, withheld: Map = emptyMap()) = ShareRefreshManager.proposeRefresh(by.db, by.room, by.publicKey, by.privateKey, by.key(), withheld) + /** One thing a device's owner was asked during a rotation. */ + private sealed interface Ask { + data class Rotation(val step: mobi.giza.compose.database.model.types.ShareRefreshApprovalStep) : Ask + data object KeyState : Ask + data class Signature(val kind: Int) : Ask + } + + /** + * Every owner says yes to whatever they are asked, about the rotation or any + * signature, until nobody is asked anything -- and the list of what each was + * asked, in order. The count is what docs/rotate-shares-single-approval.md + * takes from three to one. + */ + private suspend fun answerEverything(between: List, refreshId: String): Map> { + val asks = between.associate { it.index to mutableListOf() } + var asked = true + while (asked) { + asked = false + for (device in between) { + device.refresh(refreshId)?.let { session -> + ShareRefreshManager.pendingApproval(device.db, session)?.let { step -> + asks.getValue(device.index) += Ask.Rotation(step) + ShareRefreshManager.approve(device.db, device.room, refreshId, device.privateKey) + asked = true + } + } + val signing = device.db.frostSigningSessionDao() + signing.getSessionsForChatRoom(device.group.roomId) + .filter { FrostSigningManager.isAwaitingApproval(it, signing.getItems(it.id)) } + .forEach { session -> + val kind = Event.fromJsonOrNull(signing.getItems(session.id).single().unsignedEventJson)!!.kind + asks.getValue(device.index) += if (kind == mobi.giza.compose.nostr.frost.GroupKeyStateEvent.KIND) Ask.KeyState else Ask.Signature(kind) + FrostSigningManager.approve(device.db, device.room, session.id) + asked = true + } + } + pump(between) + } + return asks + } + // ---- the tests --------------------------------------------------------------------------------------------- @Test @@ -227,6 +268,81 @@ class ShareRefreshRitualJvmTest { assertTrue(all[0].db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).any { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED }) } + // ---- the approvals, counted (docs/rotate-shares-single-approval.md) --------------------------------------------- + + /** + * Today's gates, pinned: taking part is not enough. With every recipient's + * owner agreeing to take part and nothing more, the rotation goes quiet with + * every recipient asked to store their new share, and nobody has stored one. + */ + @Test + fun `after taking part, every recipient is asked again before storing the new share`() = runBlocking { + 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) + + all.forEach { device -> + val session = device.refresh(refresh.id)!! + assertEquals(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.CONFIRM, ShareRefreshManager.pendingApproval(device.db, session), "device ${device.index}") + assertNull(device.db.keyShareDao().getGeneration(ceremonyId, 1), "device ${device.index} stored a share it was not told to") + assertTrue(outbox(device).none { it.kind == ShareRefreshEvents.ROUND_2 }, "device ${device.index} confirmed") + assertTrue(outbox(device).any { it.kind == ShareRefreshEvents.ROUND_1 }, "device ${device.index} did not deal") + } + } + + /** + * Today's asks, pinned: three per recipient -- take part, store the new + * share, sign the new generation's key state -- before the old shares are + * deleted. The proposer is asked the first two; its device proposes the key + * state, and a proposer's signature is its proposal. + */ + @Test + fun `a recipient is asked three times before the old shares go`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + val asks = answerEverything(all, refresh.id) + + val rotation = listOf( + Ask.Rotation(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.DEAL), + Ask.Rotation(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.CONFIRM), + ) + assertEquals(rotation, asks[0], "the proposer") + all.drop(1).forEach { device -> assertEquals(rotation + Ask.KeyState, 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") + } + } + + /** + * 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. + */ + @Test + fun `a completed rotation waits on its owners to sign the new key state`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + approveAll(all, refresh.id) + pump(all) + + all.forEach { assertEquals(ShareRefreshStage.COMPLETE, it.refresh(refresh.id)?.stage) } + all.drop(1).forEach { device -> + 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") + } + } + @Test fun `a withheld member ends with the new table and no share, and declines to sign`() = runBlocking { val group = Group(3, 2) From b4103bcb404b7057324db57c8982b0bfcd290d7c Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:53:49 +0200 Subject: [PATCH 10/23] feat: taking part is a rotation's only approval (rotate-shares-single-approval, Phase 2) ShareRefreshManager.advance no longer stops before round 2 for its owner. The gate's two reasons never needed a person: participantStep2 is the check that stops a substituted table, and it fails the rotation out loud before any prompt could appear; ShareRefreshConfirmation is the one confirmation per generation, claimed with the pending share in one transaction. pendingApproval now only answers DEAL. No migration: confirmApprovedAt and ShareRefreshApprovalStep.CONFIRM stay so rows written before still decode, documented as read by nothing. Tests: the pinned gate flips (taking part alone completes the rotation, asked once); the last to take part deals and confirms with nothing more asked; a tampered sum fails the rotation on every device with nobody asked; two rotations opened at once never split the group. ShareRefreshRitualJvmTest 23/23. Must ship with Phase 3: a rotation paused at the old second approval has nothing left to arrive and needs the sweep to move. Co-Authored-By: Claude Opus 5.5 --- .../database/model/ShareRefreshSession.kt | 7 ++ .../model/types/ShareRefreshApprovalStep.kt | 23 ++-- .../compose/managers/ShareRefreshManager.kt | 34 +++--- .../managers/ShareRefreshRitualJvmTest.kt | 110 ++++++++++++++---- 4 files changed, 133 insertions(+), 41 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt index a7478251..846724ce 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ShareRefreshSession.kt @@ -74,7 +74,14 @@ data class ShareRefreshSession( /** Secret-adjacent. Round 2's auxiliary randomness for the confirmation's signature. */ val auxRandom: HexKey, + /** When this device's owner agreed to take part: the refresh's one approval. */ val dealApprovedAt: Instant? = null, + + /** + * Written by builds before docs/rotate-shares-single-approval.md, when storing + * the new share was its own approval. Read by nothing; kept rather than + * migrated away. + */ val confirmApprovedAt: Instant? = null, /** The furthest step this device has asked its owner about, so the request line is written once. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt index e871ce94..347551fe 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/types/ShareRefreshApprovalStep.kt @@ -1,21 +1,30 @@ package mobi.giza.compose.database.model.types /** - * The two decisions a recipient makes in a share refresh. Each publishes - * something different and commits the member to something different. + * Everything a share refresh has ever asked a recipient. One step is still + * asked; the other is kept so rows that stored it by name still decode + * (`ShareRefreshSession.approvalRequestedThrough`). */ enum class ShareRefreshApprovalStep { /** - * Deal round 1: join the refresh, and agree to the withheld list. Withholding + * Take part: deal round 1, and agree to the withheld list. Withholding * someone takes their signing away, so every recipient decides it, not only - * the proposer. + * the proposer. **The only approval a refresh asks for**: the device does + * everything after it on its own (docs/rotate-shares-single-approval.md). */ DEAL, /** - * Confirm round 2: store the new generation and say so. This is what stops a - * coordinator substituting a table the recipients never dealt, and the one - * confirmation per base generation this device will ever give. + * Was: confirm round 2, storing the new generation and saying so. **No + * longer asked**, and nothing produces it. + * + * Its two reasons never needed a person. Stopping a coordinator substituting + * a table nobody dealt is `FrostRefresh.participantStep2`'s check, which runs + * before any prompt could appear and fails the refresh out loud. The one + * confirmation per base generation is `ShareRefreshConfirmation`, claimed in + * the same transaction as the pending share. Neither depended on the tap. + * Don't put the gate back: a person shown "store your new share" has nothing + * to check that the device has not already checked. */ CONFIRM, } 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..2faa60b5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -60,8 +60,12 @@ import mobi.giza.compose.nostr.frost.ShareRefreshEvents * - **Every recipient takes part** (D2). A certificate needs them all; anyone * who cannot is withheld, and repaired later. * - * Nothing of this device's own goes out without its owner's approval, at two - * gates ([ShareRefreshApprovalStep]). [pendingApproval] mirrors them. + * Nothing of this device's own goes out until its owner agrees to take part, + * with the withheld list the proposal names ([ShareRefreshApprovalStep.DEAL]). + * That is the only gate, and [pendingApproval] mirrors it. Everything after it + * -- dealing, checking the combined result, storing the new share, confirming -- + * the device does itself: the check is the device's, and a person tapping + * "store" added nothing to it (docs/rotate-shares-single-approval.md). */ object ShareRefreshManager { private val logger = Logger.withTag("ShareRefreshManager") @@ -388,6 +392,8 @@ object ShareRefreshManager { val hostSecretKey = ChillDkgRitualManager.deriveHostSecretKey(nostrPrivateKey) if (isRecipient) { + // The one gate: taking part, with these members withheld. Every + // step after it follows from that decision and asks nothing more. if (session.dealApprovedAt == null) { announceApprovalNeeded(database, session, ShareRefreshApprovalStep.DEAL) return @@ -412,10 +418,10 @@ object ShareRefreshManager { session = moveTo(database, session, ShareRefreshStage.COLLECTING_ROUND_2) if (isRecipient && ownMessage(database, session, ShareRefreshEvents.ROUND_2) == null) { - if (session.confirmApprovedAt == null) { - announceApprovalNeeded(database, session, ShareRefreshApprovalStep.CONFIRM) - return - } + // No gate here. participantStep2 is the check that stops a + // coordinator substituting a table nobody dealt, and it runs + // whoever is looking; confirmAndStore is the one-confirmation + // rule, and it holds whoever is looking. val secretShare = base.secretShare ?: throw IllegalStateException("this device holds no share of generation ${base.generation}") val step2 = FrostRefresh.participantStep2(hostSecretKey, secretShare, params, myId.toUInt(), ByteVector(cmsg1.hexToByteArray()), ByteVector32(session.auxRandom)) step2.fault.raiseIfFaulty("round 2", base) @@ -583,8 +589,11 @@ object ShareRefreshManager { /** * What this device's owner is being asked for, or null. **Must mirror the - * gates in [advance] exactly**: drift makes the screen offer an approval that + * gate in [advance] exactly**: drift makes the screen offer an approval that * does nothing, or none while the refresh sits still. + * + * Only ever [ShareRefreshApprovalStep.DEAL]. [ShareRefreshApprovalStep.CONFIRM] + * was a second gate until docs/rotate-shares-single-approval.md. */ suspend fun pendingApproval(database: GizaDatabase, session: ShareRefreshSession): ShareRefreshApprovalStep? { if (session.stage == ShareRefreshStage.COMPLETE || session.stage == ShareRefreshStage.FAILED) return null @@ -592,11 +601,7 @@ object ShareRefreshManager { val base = ShareGenerations.at(database, key, session.baseGeneration) ?: return null val myId = base.roster.firstOrNull { it.memberPublicKey == session.userPublicKey }?.participantId ?: return null if (myId !in session.recipientIdList()) return null - if (session.dealApprovedAt == null) return ShareRefreshApprovalStep.DEAL - if (session.coordinatorRound1 != null && session.confirmApprovedAt == null && - ownMessage(database, session, ShareRefreshEvents.ROUND_2) == null - ) return ShareRefreshApprovalStep.CONFIRM - return null + return if (session.dealApprovedAt == null) ShareRefreshApprovalStep.DEAL else null } /** Approves the step this device's owner is being asked for, and moves on. */ @@ -605,8 +610,8 @@ object ShareRefreshManager { val now = Clock.System.now() when (pendingApproval(database, session)) { ShareRefreshApprovalStep.DEAL -> update(database, session) { it.copy(dealApprovedAt = now) } - ShareRefreshApprovalStep.CONFIRM -> update(database, session) { it.copy(confirmApprovedAt = now) } - null -> return + // Never pending any more; kept so the `when` stays over the whole enum. + ShareRefreshApprovalStep.CONFIRM, null -> return } advance(database, localChatRoom, sessionId, nostrPrivateKey) } @@ -707,6 +712,7 @@ object ShareRefreshManager { update(database, session) { it.copy(approvalRequestedThrough = step) } val line = when (step) { ShareRefreshApprovalStep.DEAL -> "Your approval is needed to take part in rotating the group's shares." + // Unreachable: CONFIRM is no longer asked. Kept because the enum keeps the value. ShareRefreshApprovalStep.CONFIRM -> "Your approval is needed to store your new share." } announce(database, session, ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED, line, session.userPublicKey) 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 2d78f976..5d07aeee 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -134,7 +134,7 @@ class ShareRefreshRitualJvmTest { .filter { it.publicKey == device.publicKey } .sortedWith(compareBy({ it.createdAt }, { it.kind })) - private suspend fun pump(between: List) { + private suspend fun pump(between: List, tamper: (MarmotInnerEvent) -> MarmotInnerEvent = { it }) { var moved = true while (moved) { moved = false @@ -143,8 +143,9 @@ class ShareRefreshRitualJvmTest { outbox(from).forEach { queued -> if (!to.received.add(queued.id)) return@forEach moved = true - to.db.marmotInnerEventDao().upsert(queued.copy(chatRoomId = to.group.roomId)) - val event = Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, queued.content, "") + val delivered = tamper(queued) + to.db.marmotInnerEventDao().upsert(delivered.copy(chatRoomId = to.group.roomId)) + val event = Event(queued.id, queued.publicKey, queued.createdAt.epochSeconds, queued.kind, queued.tags, delivered.content, "") if (ShareRefreshEvents.isShareRefreshKind(event.kind)) { ShareRefreshManager.processRefreshPayload(to.db, to.room, event, to.publicKey, to.privateKey) } else if (mobi.giza.compose.nostr.frost.ShareRepairEvents.isShareRepairKind(event.kind)) { @@ -271,12 +272,12 @@ class ShareRefreshRitualJvmTest { // ---- the approvals, counted (docs/rotate-shares-single-approval.md) --------------------------------------------- /** - * Today's gates, pinned: taking part is not enough. With every recipient's - * owner agreeing to take part and nothing more, the rotation goes quiet with - * every recipient asked to store their new share, and nobody has stored one. + * Taking part is the only approval. With every recipient's owner agreeing to + * take part and nothing more, every device stores its new share, confirms it, + * and arrives at the new generation; and nothing ever asks to store it. */ @Test - fun `after taking part, every recipient is asked again before storing the new share`() = runBlocking { + fun `after taking part, every device stores its new share without being asked again`() = runBlocking { val group = Group(3, 2) val all = devicesFor(group) val refresh = propose(all[0]) @@ -286,31 +287,100 @@ class ShareRefreshRitualJvmTest { all.forEach { device -> val session = device.refresh(refresh.id)!! - assertEquals(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.CONFIRM, ShareRefreshManager.pendingApproval(device.db, session), "device ${device.index}") - assertNull(device.db.keyShareDao().getGeneration(ceremonyId, 1), "device ${device.index} stored a share it was not told to") - assertTrue(outbox(device).none { it.kind == ShareRefreshEvents.ROUND_2 }, "device ${device.index} confirmed") - assertTrue(outbox(device).any { it.kind == ShareRefreshEvents.ROUND_1 }, "device ${device.index} did not deal") + assertEquals(ShareRefreshStage.COMPLETE, session.stage, "device ${device.index}") + assertNull(ShareRefreshManager.pendingApproval(device.db, session), "device ${device.index}") + assertNull(session.confirmApprovedAt, "nothing writes the old second approval") + assertEquals(ShareGenerationState.ACTIVE, device.db.keyShareDao().getGeneration(ceremonyId, 1)?.state, "device ${device.index}") + assertTrue(outbox(device).any { it.kind == ShareRefreshEvents.ROUND_2 }, "device ${device.index} did not confirm") + val lines = device.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId) + .filter { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED } + assertEquals(1, lines.size, "device ${device.index} must be asked once") } } /** - * Today's asks, pinned: three per recipient -- take part, store the new - * share, sign the new generation's key state -- before the old shares are - * deleted. The proposer is asked the first two; its device proposes the key - * state, and a proposer's signature is its proposal. + * The last recipient to take part deals at once, and confirms on the next + * pass that brings the coordinator's sum, with no call in between. */ @Test - fun `a recipient is asked three times before the old shares go`() = runBlocking { + fun `the last to take part deals and then confirms with nothing more asked`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + all.dropLast(1).forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) } + pump(all) + val last = all.last() + assertTrue(outbox(last).none { it.kind == ShareRefreshEvents.ROUND_1 }) + + ShareRefreshManager.approve(last.db, last.room, refresh.id, last.privateKey) + assertTrue(outbox(last).any { it.kind == ShareRefreshEvents.ROUND_1 }, "it deals in the approve call") + pump(all) + assertTrue(outbox(last).any { it.kind == ShareRefreshEvents.ROUND_2 }, "and confirms when the sum arrives") + all.forEach { assertEquals(ShareRefreshStage.COMPLETE, it.refresh(refresh.id)?.stage) } + } + + /** + * What the second approval was said to protect, protected without it: a + * coordinator's sum altered on its way fails the rotation on every device, + * and nobody arrives at a new generation. + */ + @Test + fun `a tampered sum fails the rotation with nobody asked`() = runBlocking { + 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) { event -> + if (event.kind != ShareRefreshEvents.COORDINATOR_ROUND_1) event + else event.copy(content = event.content.dropLast(2) + if (event.content.endsWith("00")) "01" else "00") + } + + all.forEach { device -> + val session = device.refresh(refresh.id)!! + assertEquals(ShareRefreshStage.FAILED, session.stage, "device ${device.index}") + assertEquals(0, device.active().generation, "device ${device.index} moved to a generation") + } + assertTrue(all.drop(1).any { it.refresh(refresh.id)!!.failureReason!!.contains("Share refresh") }, "an honest recipient has to say what it found") + } + + /** + * Two members open a rotation from the same generation at once. With every + * owner saying yes to everything, the group never splits: at most one + * completes, and every device that moved holds the same table. + */ + @Test + fun `two rotations opened at once never split the group`() = runBlocking { + val group = Group(4, 2) + val all = devicesFor(group) + val first = propose(all[0]) + val second = propose(all[1]) + pump(all) + answerEverything(all, first.id) + answerEverything(all, second.id) + + val completed = listOf(first.id, second.id).filter { id -> all.any { it.refresh(id)?.stage == ShareRefreshStage.COMPLETE } } + assertTrue(completed.size <= 1, "two rotations from one generation both completed") + val tables = all.map { it.active().generation to it.active().publicShares }.toSet() + assertEquals(1, tables.size, "devices disagree about the group's table: $tables") + } + + /** + * 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 only to take part; its device proposes the key state, and + * a proposer's signature is its proposal. + */ + @Test + fun `a recipient is asked to take part and to sign the new key state`() = runBlocking { val group = Group(3, 2) val all = devicesFor(group) val refresh = propose(all[0]) pump(all) val asks = answerEverything(all, refresh.id) - val rotation = listOf( - Ask.Rotation(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.DEAL), - Ask.Rotation(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.CONFIRM), - ) + val rotation = listOf(Ask.Rotation(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.DEAL)) assertEquals(rotation, asks[0], "the proposer") all.drop(1).forEach { device -> assertEquals(rotation + Ask.KeyState, asks[device.index], "device ${device.index}") } all.forEach { device -> From 959c120d5251758f70c2750a3a9e393d640c166a Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:55:34 +0200 Subject: [PATCH 11/23] feat: running rotations resume without a message (rotate-shares-single-approval, Phase 3) ShareRefreshManager.resumeRunning advances every rotation this user is in that has not finished, through a new ShareRefreshDao.getRunningSessionsFor. resumeRunningCeremonies runs it after the ceremony sweep, under the same lock as the inbound path, once the live subscription is open. Behind the rotation flag. Without it, Phase 2 strands a rotation an older build paused at 'store your new share': the sum is on file and nothing more will arrive. Tests: that upgrade case resumes from the sweep alone and completes, and two more sweeps send nothing; a member who has not taken part is looked at and sends nothing, asked once; a build without rotation resumes nothing. ShareRefreshRitualJvmTest 26/26. Co-Authored-By: Claude Opus 5.5 --- .../compose/database/dao/ShareRefreshDao.kt | 7 ++ .../repository/DatabaseNostrRepository.kt | 8 +- .../compose/managers/ShareRefreshManager.kt | 30 +++++++ .../compose/repository/NostrRepository.kt | 10 ++- .../ui/view/model/SynchronizationViewModel.kt | 2 + .../managers/ShareRefreshRitualJvmTest.kt | 80 ++++++++++++++++++- 6 files changed, 128 insertions(+), 9 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt index eefbf601..d699c000 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt @@ -28,6 +28,13 @@ abstract class ShareRefreshDao { @Query("SELECT * FROM ShareRefreshSession WHERE dkgSessionId = :dkgSessionId ORDER BY createdAt DESC") abstract suspend fun getSessionsForKey(dkgSessionId: String): List + /** + * Every refresh [userPublicKey] is in that has not finished, oldest first: + * what `ShareRefreshManager.resumeRunning` moves on. + */ + @Query("SELECT * FROM ShareRefreshSession WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED') ORDER BY createdAt ASC") + abstract suspend fun getRunningSessionsFor(userPublicKey: HexKey): List + @Query("SELECT * FROM ShareRefreshSession WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") abstract fun observeSessionsForRoom(chatRoomId: String): Flow> diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt index 611cb87d..414a37cf 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt @@ -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.ShareRefreshManager import com.vitorpamplona.quartz.nip01Core.core.toHexKey import mobi.giza.compose.identity.Identity @@ -144,9 +145,14 @@ class DatabaseNostrRepository( // Under the same lock as the inbound path that otherwise drives a ritual, so // a message arriving mid-sweep is not acted on twice at once. return storeNostrEventMutex.withLock { + val userPublicKey = activeKeyPair.pubKey.toHexKey() ChillDkgRitualManager.resumeRunning( database = database, - userPublicKey = activeKeyPair.pubKey.toHexKey(), + userPublicKey = userPublicKey, + nostrPrivateKey = privateKey + ) + ShareRefreshManager.resumeRunning( + database = database, + userPublicKey = userPublicKey, nostrPrivateKey = privateKey ) } 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 2faa60b5..99fea167 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -213,6 +213,36 @@ object ShareRefreshManager { it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED } + // ---- resuming ------------------------------------------------------------------------------------------------ + + /** + * Moves every running refresh of this user's as far as its stored messages + * allow. What a tap on "Store your new share" used to do, for refreshes that + * already have everything they need and will receive nothing more -- one an + * older build left waiting on that tap, or one the app died in between + * storing a message and acting on it (docs/rotate-shares-single-approval.md, + * Phase 3). + * + * Not only the approved ones: a coordinator waiting on everyone's round 1 and + * a withheld device waiting on the certificate may also hold what they need, + * and [advance] stops at the one gate for anyone who has not taken part. + * Safe to run as often as the caller likes: [advance] repeats no work. + */ + suspend fun resumeRunning(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): Int { + if (!ExperimentalFeatures.shareRefresh) return 0 + val running = database.shareRefreshDao().getRunningSessionsFor(userPublicKey) + running.forEach { session -> + val localChatRoom = database.chatRoomDao().findChatRoomById(session.chatRoomId) + if (localChatRoom == null) { + logger.w("Refresh ${session.id} is in ${session.chatRoomId}, which is gone; not resuming it") + return@forEach + } + advance(database, localChatRoom, session.id, nostrPrivateKey) + } + if (running.isNotEmpty()) logger.i("Resumed ${running.size} running refresh(es)") + return running.size + } + // ---- inbound --------------------------------------------------------------------------------------------------- /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/NostrRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/NostrRepository.kt index c46b7309..2b235e02 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/NostrRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/NostrRepository.kt @@ -58,10 +58,12 @@ interface NostrRepository { suspend fun reopenInbox(activeKeyPair: KeyPair): Int /** - * Moves every key ceremony [activeKeyPair] has joined as far as the messages - * already stored allow. Run once per activation, after [reopenInbox], since what - * that opens may be what a ceremony was waiting for. Returns how many it looked - * at. See docs/automatic-key-ceremony.md, Phase 3. + * Moves every key ceremony [activeKeyPair] has joined, and every share rotation + * it is in, as far as the messages already stored allow. Run once per + * activation, after [reopenInbox], since what that opens may be what one was + * waiting for. Returns how many it looked at. See + * docs/automatic-key-ceremony.md and docs/rotate-shares-single-approval.md, + * Phase 3 of each. */ suspend fun resumeRunningCeremonies(activeKeyPair: KeyPair): Int diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt index c292ec61..9985c278 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt @@ -244,6 +244,8 @@ class SynchronizationViewModel( // a message and acting on it -- would sit still for good. // After the reopen, since what that opened may be what it // was waiting for. docs/automatic-key-ceremony.md, Phase 3. + // A share rotation is the same, past its one approval + // (docs/rotate-shares-single-approval.md, Phase 3). runCatching { nostrRepository.resumeRunningCeremonies(keyPair) } .onFailure { logger.e("Could not resume running key ceremonies", it) } launch(Dispatchers.IO) { observePendingBroadcastNostrEventRequests(keyPair) } 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 5d07aeee..1e45a63a 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -134,14 +134,19 @@ class ShareRefreshRitualJvmTest { .filter { it.publicKey == device.publicKey } .sortedWith(compareBy({ it.createdAt }, { it.kind })) - private suspend fun pump(between: List, tamper: (MarmotInnerEvent) -> MarmotInnerEvent = { it }) { + private suspend fun pump( + between: List, + hold: (MarmotInnerEvent) -> Boolean = { false }, + tamper: (MarmotInnerEvent) -> MarmotInnerEvent = { it }, + ) { var moved = true while (moved) { moved = false for (from in between) for (to in between) { if (from === to) continue outbox(from).forEach { queued -> - if (!to.received.add(queued.id)) return@forEach + if (queued.id in to.received || hold(queued)) return@forEach + to.received += queued.id moved = true val delivered = tamper(queued) to.db.marmotInnerEventDao().upsert(delivered.copy(chatRoomId = to.group.roomId)) @@ -332,10 +337,10 @@ class ShareRefreshRitualJvmTest { val refresh = propose(all[0]) pump(all) all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) } - pump(all) { event -> + pump(all, tamper = { event -> if (event.kind != ShareRefreshEvents.COORDINATOR_ROUND_1) event else event.copy(content = event.content.dropLast(2) + if (event.content.endsWith("00")) "01" else "00") - } + }) all.forEach { device -> val session = device.refresh(refresh.id)!! @@ -366,6 +371,73 @@ class ShareRefreshRitualJvmTest { assertEquals(1, tables.size, "devices disagree about the group's table: $tables") } + /** + * The upgrade: an older build stored the coordinator's sum and stopped, asking + * its owner to store the new share. Nothing more will arrive, so only the + * sweep can move it -- and it does, once, and the rotation completes. + */ + @Test + fun `a rotation left waiting on the old second approval resumes from the sweep`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val (coordinator, others) = all.first() to all.drop(1) + val refresh = propose(coordinator) + pump(all) + all.forEach { ShareRefreshManager.approve(it.db, it.room, refresh.id, it.privateKey) } + // The sum goes out, but the others' build files it and stops. + pump(all, hold = { it.kind == ShareRefreshEvents.COORDINATOR_ROUND_1 }) + val sum = outbox(coordinator).single { it.kind == ShareRefreshEvents.COORDINATOR_ROUND_1 } + others.forEach { device -> + device.received += sum.id + device.db.marmotInnerEventDao().upsert(sum.copy(chatRoomId = group.roomId)) + device.db.shareRefreshDao().upsert( + device.refresh(refresh.id)!!.copy( + coordinatorRound1 = sum.content, + stage = ShareRefreshStage.COLLECTING_ROUND_2, + approvalRequestedThrough = mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.CONFIRM, + ) + ) + assertTrue(outbox(device).none { it.kind == ShareRefreshEvents.ROUND_2 }, "device ${device.index}") + } + pump(all) + others.forEach { assertTrue(outbox(it).none { e -> e.kind == ShareRefreshEvents.ROUND_2 }, "nothing arrives to move device ${it.index}") } + + others.forEach { assertEquals(1, ShareRefreshManager.resumeRunning(it.db, it.publicKey, it.privateKey)) } + others.forEach { assertEquals(1, outbox(it).count { e -> e.kind == ShareRefreshEvents.ROUND_2 }, "device ${it.index} confirmed from the sweep") } + pump(all) + all.forEach { assertEquals(ShareRefreshStage.COMPLETE, it.refresh(refresh.id)?.stage, "device ${it.index}") } + + // Twice more: nothing runs, nothing goes out. + val sent = all.map { outbox(it).size } + repeat(2) { all.forEach { device -> assertEquals(0, ShareRefreshManager.resumeRunning(device.db, device.publicKey, device.privateKey)) } } + assertEquals(sent, all.map { outbox(it).size }) + } + + /** A rotation nobody has taken part in yet is looked at by the sweep and sends nothing. */ + @Test + fun `the sweep sends nothing for a member who has not taken part`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + val member = all[1] + assertEquals(1, ShareRefreshManager.resumeRunning(member.db, member.publicKey, member.privateKey)) + assertTrue(outbox(member).isEmpty()) + assertEquals(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.DEAL, ShareRefreshManager.pendingApproval(member.db, member.refresh(refresh.id)!!)) + val asked = member.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).count { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED } + assertEquals(1, asked, "asked once, however often the sweep looks") + } + + @Test + fun `a build without rotation resumes nothing`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + propose(all[0]) + pump(all) + mobi.giza.compose.ExperimentalFeatures.shareRefreshOverride = false + assertEquals(0, ShareRefreshManager.resumeRunning(all[1].db, all[1].publicKey, all[1].privateKey)) + } + /** * 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 From 3efa1af554af8a6d13e527512567407e153501eb Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 00:57:18 +0200 Subject: [PATCH 12/23] test: every founding member of a robust group is its admin (robust-group-admins, Phase 0) RobustGroupAdminsJvmTest states the promise and shows where it breaks. Three app phones: one creates the admin room through MarmotGroupCreation with all three as admins, the others join by a real Welcome, gift wrapped and stored through the sync funnel. On every device the admin policy names the founders and isLocalAdmin is true, on both profiles. The rows do not: a joiner's Welcome writes no adminAt, so its own rows flag nobody -- ignored until Phase 2. A member invited later is not an admin. The ceremony half checks that every device that took part agrees on the founding set, for a group and a subgroup. The later-member case runs on the legacy profile only: on the current profile MarmotGroupCreation invites the founders through a room read before its routing id is recorded, so a later invite skips its commit. Phase 4 fixes that. Co-Authored-By: Claude Opus 5.5 --- .../managers/RobustGroupAdminsJvmTest.kt | 262 ++++++++++++++++++ 1 file changed, 262 insertions(+) create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt new file mode 100644 index 00000000..91283b7a --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt @@ -0,0 +1,262 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.marmot.groups.isLocalAdmin +import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent +import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent +import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent +import kotlin.test.Ignore +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlin.time.Instant +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.MarmotKeyPackage +import mobi.giza.compose.database.model.types.DkgApprovalStep +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.database.repository.DatabaseMarmotRepository +import mobi.giza.compose.database.repository.DatabaseNostrRepository +import mobi.giza.compose.nostr.MarmotProfile + +/** + * The promise a robust group makes -- "everyone administers the group together" -- + * held on every device of every founding member. docs/robust-group-admins.md. + * + * Two halves. The ceremony half runs real ChillDKG on [CeremonyNetwork] and checks + * that every device agrees who the founding members are. The room half has one app + * device create the admin room and the others join it by a real Welcome, gift + * wrapped and stored through the same funnel a relay's copy goes through, because + * the Welcome is where a joiner first learns -- or fails to learn -- who its + * admins are. + */ +class RobustGroupAdminsJvmTest { + + /** One phone: its own database, as in the app, and nothing shared with the others. */ + private class Phone(profile: MarmotProfile) : AutoCloseable { + val keyPair = KeyPair() + val publicKey: HexKey = keyPair.pubKey.toHexKey() + val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + val chatRepository = DatabaseChatRepository(db, CoroutineScope(Dispatchers.Default)) + private val nostrRepository = DatabaseNostrRepository(db, CoroutineScope(Dispatchers.Default)) + private val marmotRepository = DatabaseMarmotRepository(db, CoroutineScope(Dispatchers.Default)) + + /** This phone's key package, as another phone would have synced it. */ + lateinit var keyPackage: MarmotKeyPackage + + val ready: suspend () -> Unit = { + marmotRepository.publishMarmotKeyPackageBundle(keyPair, setOf(profile)) + val bundle = db.marmotKeyPackageBundleDao().getAllMarmotKeyPackageBundles(publicKey).single() + keyPackage = MarmotKeyPackage( + id = bundle.id, + publicKey = publicKey, + tlsEncodedMarmotKeyPackage = bundle.tlsEncodedMarmotKeyPackage, + profile = profile.wireName, + ) + } + + /** + * A relay's OK on the newest commit this phone put on the wire. An invite + * into a room that already has members holds its Welcome back until then. + */ + suspend fun okTheLatestCommit() { + val event = db.nostrEventDao().getMLSGroupEvents(since = Instant.fromEpochSeconds(0), limit = 20) + .filter { it.kind == GroupEvent.KIND } + .last { db.marmotCommitResultDao().getMarmotCommitRequestById(it.id) != null } + val request = assertNotNull(db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(event.id)) + nostrRepository.broadcastProcessed(request, "published") + } + + override fun close() = db.close() + override fun toString() = publicKey.take(8) + } + + private val roomId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey()) + + /** + * Three phones; the first creates the admin room with all three as its admins, + * as `CeremonyFollowThrough` does after a ceremony, and the other two join it. + */ + private suspend fun foundedRoom(profile: MarmotProfile, size: Int = 3): List { + val phones = List(size) { Phone(profile) } + phones.forEach { it.ready() } + phones.forEach { phone -> phones.forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } } + + val creator = phones.first() + phones.drop(1).forEach { creator.db.marmotKeyPackageDao().upsert(it.keyPackage) } + + val outcome = MarmotGroupCreation.create( + database = creator.db, + chatRepository = creator.chatRepository, + groupId = roomId, + name = "Ekklesia", + purpose = "Admins of Ekklesia.", + adminPublicKeys = phones.map { it.publicKey }.toSet(), + userPublicKey = creator.publicKey, + keyPair = creator.keyPair, + keyPackageLookupTimeout = 2_000L, + profile = profile, + ) + val created = assertIs(outcome) + assertTrue(created.notAdded.isEmpty(), "the creator could not invite ${created.notAdded}") + + phones.drop(1).forEach { welcome(from = creator, to = it) } + return phones + } + + /** Hands [to] the Welcome [from] queued for it, wrapped as a relay would carry it. */ + private suspend fun welcome(from: Phone, to: Phone) { + val payload = from.db.giftWrapPayloadDao().getAllGiftWrapUnsigned() + .filter { it.kind == WelcomeEvent.KIND } + .single { payload -> payload.tags.any { it.size > 1 && it[1] == to.keyPackage.id } } + + val rumor = RumorAssembler.assembleRumor( + pubKey = from.publicKey, + ev = EventTemplate(payload.createdAt.epochSeconds, payload.kind, payload.tags, payload.content), + ) + val signer = NostrSignerSync(from.keyPair) + val seal = signer.signNormal( + createdAt = rumor.createdAt, kind = SealEvent.KIND, tags = emptyArray(), + content = signer.nip44Encrypt(rumor.toJson(), to.publicKey), + ) + val wrap = GiftWrapEvent.create(event = seal, recipientPubKey = to.publicKey, createdAt = rumor.createdAt) + + MarmotStandIn.storeInApp(to.db, to.keyPair, wrap) + assertNotNull(to.db.chatRoomDao().findChatRoomById(roomId), "$to did not join from the Welcome") + } + + // ---- The room ---------------------------------------------------------------- + + /** [block] on a freshly founded room, once on each profile a room can be made on. */ + private fun onEveryProfile( + profiles: List = listOf(MarmotProfile.LEGACY, MarmotProfile.CURRENT), + block: suspend (MarmotProfile, List) -> Unit, + ) = runBlocking { + profiles.forEach { profile -> + val phones = foundedRoom(profile) + try { + block(profile, phones) + } finally { + phones.forEach { it.close() } + } + } + } + + private suspend fun Phone.room() = assertNotNull(db.chatRoomDao().findChatRoomById(roomId), "$this has no room") + + /** Whom this phone's own rows call an admin. */ + private suspend fun Phone.flaggedAdmins(): Set = room().localParticipants + .map { it.participant } + .filter { it.deletedAt == null && it.adminAt != null } + .map { it.participantPublicKey } + .toSet() + + @Test + fun `every founding member is in the room's admin policy, on every device`() = onEveryProfile { profile, phones -> + val founders = phones.map { it.publicKey }.toSet() + + phones.forEach { phone -> + val group = assertNotNull(phone.room().chatRoom.toMlsGroup(), "$phone holds no group ($profile)") + assertEquals(founders, group.currentAdminIdentities(), "$phone's admin policy ($profile)") + assertTrue(group.isLocalAdmin(), "$phone is not an admin of its own room ($profile)") + } + } + + /** + * The rows, which are what the screens label members with. The creator's are + * caught up by `MarmotGroupCreation`; a joiner's come from the Welcome, which + * writes none of them. + */ + @Ignore("Phase 2: the Welcome writes no admin flags") + @Test + fun `every device flags every founding member as an admin`() = onEveryProfile { profile, phones -> + val founders = phones.map { it.publicKey }.toSet() + + phones.forEach { phone -> + assertEquals(founders, phone.flaggedAdmins(), "$phone's rows say a different set are admins ($profile)") + } + } + + /** + * The boundary docs/robust-group-admins.md, D1 draws: founding, not present. + * + * Legacy only until Phase 4. On the current profile `MarmotGroupCreation` invites + * the founders through a room read before its routing id was recorded, so the + * engine's group at the real address still holds only the creator, and a later + * invite takes the founding path -- no commit, and nobody else told. + */ + @Test + fun `a member added after the founding is not an admin`() = onEveryProfile(listOf(MarmotProfile.LEGACY)) { profile, phones -> + val founders = phones.map { it.publicKey }.toSet() + val creator = phones.first() + + Phone(profile).use { later -> + later.ready() + (phones + later).forEach { phone -> (phones + later).forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } } + + creator.chatRepository.inviteMember(creator.room(), later.publicKey, later.keyPackage) + creator.okTheLatestCommit() + welcome(from = creator, to = later) + + listOf(creator, later).forEach { phone -> + val group = assertNotNull(phone.room().chatRoom.toMlsGroup(), "$phone holds no group ($profile)") + assertEquals(founders, group.currentAdminIdentities(), "$phone's admin policy ($profile)") + assertTrue(later.publicKey !in phone.flaggedAdmins(), "$phone flags the later member ($profile)") + } + assertFalse(assertNotNull(later.room().chatRoom.toMlsGroup()).isLocalAdmin(), "the later member governs ($profile)") + } + } + + // ---- The ceremony ------------------------------------------------------------ + + @Test + fun `the founding set is the same set on every device that took part`(): Unit = runBlocking { + CeremonyNetwork.nip17(size = 3).use { network -> + val everyone = network.devices.map { it.publicKey }.toSet() + val session = network.propose(threshold = 2) + network.deliverUntilQuiet() + network.devices.drop(1).forEach { network.approve(it, session.id, DkgApprovalStep.HOST_KEY) } + network.deliverUntilQuiet() + + network.devices.forEach { device -> + val theirs = assertNotNull(network.session(device, session.id), "$device has no ceremony") + assertEquals(everyone, ChillDkgRitualManager.memberPublicKeys(network.room(device)), "$device's room") + assertEquals(everyone, theirs.participantPublicKeySet(), "$device's ceremony") + assertEquals( + everyone, + ChillDkgRitualManager.participantsOf(theirs, network.room(device)), + "$device's founding set", + ) + } + } + } + + @Test + fun `a subgroup's founding set is its ceremony's participants on every device in it`(): Unit = runBlocking { + val parentId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey()) + CeremonyNetwork.marmot(size = 4, roomId = parentId).use { network -> + val picked = network.devices.take(3).map { it.publicKey }.toSet() + val session = network.propose(threshold = 2, participants = picked, parentChatRoomId = parentId, subject = "Translation") + network.deliverUntilQuiet() + + network.devices.take(3).forEach { device -> + val theirs = assertNotNull(network.session(device, session.id), "$device has no ceremony") + assertEquals(picked, ChillDkgRitualManager.participantsOf(theirs, network.room(device)), "$device") + } + } + } +} From 69871c68a56f573fb1aa0ab14607e63f88c5d8e0 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:00:56 +0200 Subject: [PATCH 13/23] feat: proposing a rotation is the proposer's approval (rotate-shares-single-approval, Phase 4) The proposer was asked like anyone because the button committed them to a withheld list they were never shown. Now Rotate shares opens a dialog naming who takes part and who is left out -- the stale members proposing withholds again automatically included -- and why it would be refused, before anything is sent. Pressing it is the proposer's agreement: the session is created with dealApprovedAt set, and the proposer deals at once. ShareRefreshManager.plan is the one recipient/withheld split behind both proposeRefresh and the new preview, so the dialog shows what the proposal will say. The removal dialog names the stale members too. Tests: the proposer's half of 'nothing goes out before they approve' flips; the preview equals the proposal with nobody stale and with one; a removal's preview names the removed for good and the stale until they are back; a refused preview says why and sends nothing. jvmTest 1241/1241, m3Audit, brand and wallet audits. Not seen on a device. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 7 ++ .../repository/DatabaseChatRepository.kt | 15 ++++ .../compose/managers/ShareRefreshManager.kt | 86 +++++++++++++++---- .../giza/compose/repository/ChatRepository.kt | 10 +++ .../ui/composable/ChatRoomDetailScreen.kt | 74 ++++++++++++++-- .../ui/view/model/ChatRoomDetailViewModel.kt | 43 ++++++++-- .../compose/ui/view/state/RotationPreview.kt | 17 ++++ .../managers/ShareRefreshRitualJvmTest.kt | 70 +++++++++++++-- 8 files changed, 287 insertions(+), 35 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/RotationPreview.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 733a0b2c..d1cf168a 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -114,6 +114,13 @@ Rotate shares without them? They are out of the room, but their share of the group key still helps sign until the shares are rotated without them. Rotating asks every remaining member to take part. Shares held before the rotation stop working once every device has deleted them. Rotate shares + Rotate the shares? + Taking part: %1$s + Left out until they are brought back: %1$s + Left out for good: %1$s + Each member taking part is asked once. Rotating counts as your own agreement, so you are not asked again. + This group has no key this device can rotate + This rotation cannot start: %1$s Shares Generation %1$d Holds a share diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 1a119258..0c99990f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -43,6 +43,7 @@ import mobi.giza.compose.identity.Identity import mobi.giza.compose.identity.toKeyPair import mobi.giza.compose.managers.ShareRefreshManager import mobi.giza.compose.ui.view.state.SharesSummary +import mobi.giza.compose.ui.view.state.RotationPreview import mobi.giza.compose.database.model.types.ShareStanding import mobi.giza.compose.database.model.types.ShareRepairStage import mobi.giza.compose.database.model.types.ShareRefreshStage @@ -704,6 +705,20 @@ class DatabaseChatRepository( return failureOf(runCatching { ShareRefreshManager.proposeRefresh(database, localChatRoom, me, privateKey, key) }.exceptionOrNull()) } + override suspend fun rotationPreview(localChatRoom: LocalChatRoom, without: HexKey?): RotationPreview? = runCatching { + if (!ExperimentalFeatures.shareRefresh) return null + val me = localChatRoom.chatRoom.userPublicKey + val preview = ShareRefreshManager.preview(database, localChatRoom, me, without) ?: return null + val names = localChatRoom.localParticipants.associate { it.participant.participantPublicKey to it.profile?.humanReadableNameOrPubkey() } + fun nameOf(member: HexKey) = names[member] ?: member.take(8) + RotationPreview( + takingPart = preview.takingPart.map(::nameOf), + untilBroughtBack = preview.withheld.filterValues { it == ShareStanding.STALE }.keys.map(::nameOf), + forGood = preview.withheld.filterValues { it == ShareStanding.RETIRED }.keys.map(::nameOf), + refusal = preview.refusal, + ) + }.getOrNull() + override suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? { val (_, privateKey) = privateKeyOrNull() ?: return "This identity cannot sign" return failureOf(runCatching { 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 99fea167..61b551e2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -111,13 +111,75 @@ object ShareRefreshManager { // ---- proposing ------------------------------------------------------------------------------------------------ + /** + * Who a refresh of [key] from [shares] would deal to and who it would leave + * out, with [withheld] asked for: every live participant not in it is a + * recipient, and every stale participant is withheld again, as what they + * were -- a refresh does not bring anybody back, a repair does. [refusal] is + * why it cannot run, or null. One function for [proposeRefresh] and + * [preview], so the dialog shows exactly what the proposal will say. + */ + private fun plan(key: DkgSession, shares: ShareGenerations.Shares, userPublicKey: HexKey, withheld: Map): Plan { + val recipients = shares.roster + .filter { it.standing == ShareStanding.LIVE && it.participantId !in withheld } + .map { it.participantId } + val allWithheld = withheld + shares.roster + .filter { it.standing == ShareStanding.STALE && it.participantId !in withheld } + .associate { it.participantId to ShareStanding.STALE } + val myId = shares.signerIds[userPublicKey] + val refusal = when { + shares.secretShare == null -> "this device holds no share of generation ${shares.generation}" + myId == null -> "this device is not a signer of generation ${shares.generation}" + else -> refusal(key, shares, recipients, allWithheld) + ?: "the proposer has to be a recipient".takeIf { myId !in recipients } + } + return Plan(recipients, allWithheld, refusal) + } + + private data class Plan(val recipients: List, val withheld: Map, val refusal: String?) + + /** A refresh as it would be proposed, by member rather than by id. */ + data class Preview( + val takingPart: List, + val withheld: Map, + /** Why it cannot be proposed, or null. */ + val refusal: String?, + ) + + /** + * What [proposeRefresh] would open from this device, without opening it: who + * takes part and who is left out, stale members included, and whether it + * would be refused. The proposer's dialog shows this, and pressing it is the + * proposer's agreement to take part (docs/rotate-shares-single-approval.md, + * Phase 4). [without] is a member to withhold for good, as after a removal. + */ + suspend fun preview(database: GizaDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, without: HexKey? = null): Preview? { + val key = FrostSigningManager.completedKey(database, localChatRoom.chatRoom.id) ?: return null + if (!isKeysRoom(database, localChatRoom, key)) return null + val shares = ShareGenerations.active(database, key) + val withheld = without?.let { member -> + val id = shares.signerIds[member] ?: return Preview(emptyList(), emptyMap(), "they hold no share of the group's key") + mapOf(id to ShareStanding.RETIRED) + } ?: emptyMap() + val plan = plan(key, shares, userPublicKey, withheld) + val memberOf = shares.roster.associate { it.participantId to it.memberPublicKey } + return Preview( + takingPart = plan.recipients.mapNotNull { memberOf[it] }, + withheld = plan.withheld.mapNotNull { (id, standing) -> memberOf[id]?.let { it to standing } }.toMap(), + refusal = plan.refusal ?: running(database, key)?.let { "a rotation of this key is already running" }, + ) + } + /** * Opens a refresh of [key], making this device the coordinator. Every live - * participant not in [withheld] is a recipient. + * participant not in [withheld] is a recipient, and every stale one is + * withheld again ([plan]). * - * The proposer is auto-approved for nothing: proposing a refresh is not - * agreeing to withhold whomever the form defaulted to, so it is asked at both - * gates like everyone else. + * **Proposing is the proposer's agreement to take part**: the proposer's + * device deals at once, and its owner is not asked again. That is safe only + * because the proposal is made from a dialog that named everyone it leaves + * out ([preview]) -- proposing is agreeing to withhold whoever the form + * showed, never whoever it defaulted to unseen. */ suspend fun proposeRefresh( database: GizaDatabase, @@ -134,19 +196,8 @@ object ShareRefreshManager { running(database, key)?.let { return it } val shares = ShareGenerations.active(database, key) - requireNotNull(shares.secretShare) { "This device holds no share of generation ${shares.generation}" } - val myId = requireNotNull(shares.signerIds[userPublicKey]) { "This device is not a signer of generation ${shares.generation}" } - - val recipients = shares.roster - .filter { it.standing == ShareStanding.LIVE && it.participantId !in withheld } - .map { it.participantId } - // Stale participants are withheld again, as what they were: a refresh does - // not bring anybody back. That is a repair. - val allWithheld = withheld + shares.roster - .filter { it.standing == ShareStanding.STALE && it.participantId !in withheld } - .associate { it.participantId to ShareStanding.STALE } - refusal(key, shares, recipients, allWithheld)?.let { throw IllegalStateException("Cannot refresh: $it") } - require(myId in recipients) { "The proposer has to be a recipient" } + val (recipients, allWithheld, refused) = plan(key, shares, userPublicKey, withheld) + refused?.let { throw IllegalStateException("Cannot refresh: $it") } val session = ShareRefreshSession( id = RandomInstance.bytes(32).toHex(), @@ -159,6 +210,7 @@ object ShareRefreshManager { withheld = ShareRefreshSession.formatWithheld(allWithheld), round1Random = RandomInstance.bytes(32).toHex(), auxRandom = RandomInstance.bytes(32).toHex(), + dealApprovedAt = Clock.System.now(), ) database.shareRefreshDao().upsert(session) announce(database, session, ChatMessage.TYPE_SHARE_REFRESH_STARTED, startedLine(session, shares), userPublicKey) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index f8a61f1f..57eac81f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -22,6 +22,7 @@ import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.SubgroupManager import mobi.giza.compose.nostr.MarmotProfile import mobi.giza.compose.ui.view.state.SharesSummary +import mobi.giza.compose.ui.view.state.RotationPreview interface ChatRepository { suspend fun observeChatRoomListByPublicKey(publicKey: String): Flow> @@ -287,6 +288,13 @@ interface ChatRepository { /** Proposes rotating every share of the room's key. Null on success, or why not. */ suspend fun rotateShares(localChatRoom: LocalChatRoom): String? + /** + * Who a rotation proposed from this device would take part and who it would + * leave out -- [without] for good, as after a removal -- or null when the room + * has no key this device can rotate. Nothing is sent. + */ + suspend fun rotationPreview(localChatRoom: LocalChatRoom, without: HexKey? = null): RotationPreview? + /** Answers what [approval] asks. Null on success, or why not. */ suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? @@ -494,6 +502,8 @@ interface ChatRepository { override suspend fun rotateShares(localChatRoom: LocalChatRoom): String? = null + override suspend fun rotationPreview(localChatRoom: LocalChatRoom, without: HexKey?): RotationPreview? = null + override suspend fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval): String? = null override suspend fun abandonRotation(localChatRoom: LocalChatRoom, sessionId: String): String? = null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 2b3ac801..abbc23f5 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -124,6 +124,14 @@ import mobi.giza.compose.resources.not_now import mobi.giza.compose.resources.rotate_shares import mobi.giza.compose.resources.rotate_shares_without_body import mobi.giza.compose.resources.rotate_shares_without_title +import mobi.giza.compose.resources.rotate_shares_title +import mobi.giza.compose.resources.rotation_cannot_start +import mobi.giza.compose.resources.rotation_left_out_for_good +import mobi.giza.compose.resources.rotation_left_out_until_brought_back +import mobi.giza.compose.resources.rotation_proposing_is_taking_part +import mobi.giza.compose.resources.rotation_taking_part +import mobi.giza.compose.resources.rotation_no_key +import mobi.giza.compose.ui.view.state.RotationPreview import androidx.compose.material3.AlertDialog import mobi.giza.compose.resources.disband_group import mobi.giza.compose.resources.disband_group_explainer @@ -185,6 +193,7 @@ fun ChatRoomDetailScreen( val removalRequested = stringResource(Res.string.member_removal_requested) val rotationRequested = stringResource(Res.string.share_rotation_requested) val sharesActionSent = stringResource(Res.string.shares_action_sent) + val noKeyToRotate = stringResource(Res.string.rotation_no_key) // Offered after removing a member who still holds a share of the room's key: // the removal took them out of the room, not out of the key @@ -193,9 +202,19 @@ fun ChatRoomDetailScreen( AlertDialog( onDismissRequest = { chatRoomDetailViewModel.dismissRotationOffer() }, title = { Text(stringResource(Res.string.rotate_shares_without_title)) }, - text = { Text(stringResource(Res.string.rotate_shares_without_body)) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text(stringResource(Res.string.rotate_shares_without_body)) + // The removed member is named by the title; the others it would leave out are not. + offer.preview?.let { RotationLeftOut(it.copy(forGood = emptyList())) } + offer.preview?.refusal?.let { Text(stringResource(Res.string.rotation_cannot_start, it), color = MaterialTheme.colorScheme.error) } + } + }, confirmButton = { - TextButton(onClick = { chatRoomDetailViewModel.rotateSharesWithout(offer) { failure -> notify(failure ?: rotationRequested) } }) { + TextButton( + enabled = offer.preview?.refusal == null, + onClick = { chatRoomDetailViewModel.rotateSharesWithout(offer) { failure -> notify(failure ?: rotationRequested) } } + ) { Text(stringResource(Res.string.rotate_shares)) } }, @@ -207,6 +226,40 @@ fun ChatRoomDetailScreen( ) } + // The proposer's one approval: the rotation as it will be proposed, with + // everyone it leaves out named (docs/rotate-shares-single-approval.md, Phase 4). + chatRoomDetailViewModel.rotationProposal?.let { proposal -> + AlertDialog( + onDismissRequest = { chatRoomDetailViewModel.dismissRotationProposal() }, + title = { Text(stringResource(Res.string.rotate_shares_title)) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text(stringResource(Res.string.rotation_taking_part, proposal.preview.takingPart.joinToString(", "))) + RotationLeftOut(proposal.preview) + val refusal = proposal.preview.refusal + if (refusal != null) { + Text(stringResource(Res.string.rotation_cannot_start, refusal), color = MaterialTheme.colorScheme.error) + } else { + Text(stringResource(Res.string.rotation_proposing_is_taking_part)) + } + } + }, + confirmButton = { + TextButton( + enabled = proposal.preview.refusal == null, + onClick = { chatRoomDetailViewModel.rotateShares(proposal) { failure -> notify(failure ?: rotationRequested) } } + ) { + Text(stringResource(Res.string.rotate_shares)) + } + }, + dismissButton = { + TextButton(onClick = { chatRoomDetailViewModel.dismissRotationProposal() }) { + Text(stringResource(Res.string.not_now)) + } + }, + ) + } + ScreenStateTransition(chatRoomDetailViewModel.chatRoomDetailUIState) { uiState -> when (val chatRoomDetailUIState = uiState) { is ChatRoomDetailUIState.Error -> { @@ -446,8 +499,8 @@ fun ChatRoomDetailScreen( if (shares.canRotate) { FilledTonalButton( onClick = { - chatRoomDetailViewModel.rotateShares(chatRoomDetailUIState.localChatRoom) { failure -> - notify(failure ?: rotationRequested) + chatRoomDetailViewModel.previewRotation(chatRoomDetailUIState.localChatRoom) { + notify(noKeyToRotate) } } ) { @@ -1329,4 +1382,15 @@ private fun ChatRoomMessagingScreenPreview() { ) } } -} \ No newline at end of file +} + +/** Who a rotation leaves out, a line per standing, nothing when it leaves out nobody. */ +@Composable +private fun RotationLeftOut(preview: RotationPreview) { + if (preview.untilBroughtBack.isNotEmpty()) { + Text(stringResource(Res.string.rotation_left_out_until_brought_back, preview.untilBroughtBack.joinToString(", "))) + } + if (preview.forGood.isNotEmpty()) { + Text(stringResource(Res.string.rotation_left_out_for_good, preview.forGood.joinToString(", "))) + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 3cb13a0e..c2d7f2b1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -28,6 +28,7 @@ import mobi.giza.compose.ui.composable.navigation.routes.HomeRoute import mobi.giza.compose.ui.composable.navigation.routes.Route import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState import mobi.giza.compose.ui.view.state.SharesSummary +import mobi.giza.compose.ui.view.state.RotationPreview class ChatRoomDetailViewModel( val chatRoomId: String, @@ -124,6 +125,8 @@ class ChatRoomDetailViewModel( val heldShare = chatRepository.holdsShare(localChatRoom, memberPublicKey) val failure = runCatching { chatRepository.removeMember(localChatRoom, memberPublicKey) } .exceptionOrNull() + // Who else the rotation would leave out, for the offer to name. + val preview = if (failure == null && heldShare) chatRepository.rotationPreview(localChatRoom, memberPublicKey) else null initiateChatRoomDetail() viewModelScope.launch(Dispatchers.Main) { onDone(failure?.message) @@ -131,7 +134,7 @@ class ChatRoomDetailViewModel( // can still help sign until the shares are rotated without them. // A second act, offered rather than folded in -- it needs every // remaining holder (docs/frost-share-refresh.md, Phase 9). - if (failure == null && heldShare) rotationOffer = RotationOffer(localChatRoom, memberPublicKey) + if (failure == null && heldShare) rotationOffer = RotationOffer(localChatRoom, memberPublicKey, preview) } } } @@ -149,8 +152,35 @@ class ChatRoomDetailViewModel( } } - fun rotateShares(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) = - sharesAction(onDone) { chatRepository.rotateShares(localChatRoom) } + /** A rotation this device could propose, shown before it is: pressing it is the proposer's agreement to take part. */ + data class RotationProposal(val localChatRoom: LocalChatRoom, val preview: RotationPreview) + + var rotationProposal: RotationProposal? by mutableStateOf(null) + private set + + /** + * Asks who a rotation would take part and leave out, and shows it. Nothing is + * sent until [rotateShares]. [onUnavailable] is told when there is nothing to + * show -- the room has no key this device can rotate. + */ + fun previewRotation(localChatRoom: LocalChatRoom, onUnavailable: () -> Unit) { + viewModelScope.launch(Dispatchers.IO) { + val preview = chatRepository.rotationPreview(localChatRoom) + viewModelScope.launch(Dispatchers.Main) { + if (preview == null) onUnavailable() else rotationProposal = RotationProposal(localChatRoom, preview) + } + } + } + + fun dismissRotationProposal() { + rotationProposal = null + } + + /** Proposes the rotation [rotationProposal] showed. */ + fun rotateShares(proposal: RotationProposal, onDone: (String?) -> Unit) { + rotationProposal = null + sharesAction(onDone) { chatRepository.rotateShares(proposal.localChatRoom) } + } fun approveShares(localChatRoom: LocalChatRoom, approval: SharesSummary.PendingApproval, onDone: (String?) -> Unit) = sharesAction(onDone) { chatRepository.approveShares(localChatRoom, approval) } @@ -161,8 +191,11 @@ class ChatRoomDetailViewModel( fun askToBeRepaired(localChatRoom: LocalChatRoom, onDone: (String?) -> Unit) = sharesAction(onDone) { chatRepository.askToBeRepaired(localChatRoom) } - /** A removed member who still holds a share of the room's key, for the offer to rotate without them. */ - data class RotationOffer(val localChatRoom: LocalChatRoom, val memberPublicKey: HexKey) + /** + * A removed member who still holds a share of the room's key, for the offer to + * rotate without them, with who else it would leave out. + */ + data class RotationOffer(val localChatRoom: LocalChatRoom, val memberPublicKey: HexKey, val preview: RotationPreview? = null) var rotationOffer: RotationOffer? by mutableStateOf(null) private set diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/RotationPreview.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/RotationPreview.kt new file mode 100644 index 00000000..0d7d997d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/RotationPreview.kt @@ -0,0 +1,17 @@ +package mobi.giza.compose.ui.view.state + +/** + * A share rotation as the proposer's dialog shows it before anything is sent + * (docs/rotate-shares-single-approval.md, Phase 4): who takes part and who is + * left out, by name. Pressing the dialog's button is the proposer's agreement + * to take part, so it shows everything that agreement covers. + */ +data class RotationPreview( + val takingPart: List, + /** Withheld as stale: left out until a repair brings them back. */ + val untilBroughtBack: List, + /** Withheld as retired: left out for good. */ + val forGood: List, + /** Why the rotation cannot be proposed, or null when it can. */ + val refusal: String?, +) 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 1e45a63a..03f6d9d2 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -266,12 +266,66 @@ class ShareRefreshRitualJvmTest { val refresh = propose(all[0]) pump(all) - all.forEach { device -> - assertEquals(listOf(ShareRefreshEvents.PROPOSAL).takeIf { device.index == 0 } ?: emptyList(), outbox(device).map { it.kind }, "device ${device.index}") + all.drop(1).forEach { device -> + assertEquals(emptyList(), outbox(device).map { it.kind }, "device ${device.index}") assertNotNull(ShareRefreshManager.pendingApproval(device.db, device.refresh(refresh.id)!!), "device ${device.index} must be asked") } - // The proposer is asked like anyone: proposing is not agreeing to withhold whoever the form defaulted to. - assertTrue(all[0].db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).any { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED }) + // Proposing is the proposer's agreement, made from a dialog that named + // everyone left out: its device deals at once, and its owner is not asked. + val proposer = all[0] + assertEquals(listOf(ShareRefreshEvents.PROPOSAL, ShareRefreshEvents.ROUND_1), outbox(proposer).map { it.kind }) + assertNull(ShareRefreshManager.pendingApproval(proposer.db, proposer.refresh(refresh.id)!!)) + assertTrue(proposer.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId).none { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED }) + } + + // ---- Phase 4 of rotate-shares-single-approval: what the proposer is shown ---------------------------------------- + + /** The dialog shows what the proposal will say: the same recipients, the same members left out, as the same standing. */ + @Test + fun `the preview is the proposal`() = runBlocking { + suspend fun agrees(by: Device, without: HexKey? = null) { + val preview = assertNotNull(ShareRefreshManager.preview(by.db, by.room, by.publicKey, without)) + assertNull(preview.refusal, preview.refusal) + val refresh = if (without == null) propose(by) else ShareRefreshManager.proposeWithout(by.db, by.room, by.publicKey, by.privateKey, without) + val roster = by.active().roster.associate { it.participantId to it.memberPublicKey } + assertEquals(preview.takingPart, refresh.recipientIdList().map { roster.getValue(it) }) + assertEquals(preview.withheld, refresh.withheldStandings().mapKeys { roster.getValue(it.key) }) + } + + // Nobody stale, nobody removed. + val fresh = devicesFor(Group(3, 2)) + agrees(fresh[0]) + + // One stale, withheld again without being asked for. + val (_, rotated) = rotatedWithout(2) + val stale = ShareRefreshManager.preview(rotated[0].db, rotated[0].room, rotated[0].publicKey)!! + assertEquals(mapOf(rotated[2].publicKey to ShareStanding.STALE), stale.withheld) + agrees(rotated[0]) + } + + @Test + fun `the preview of a removal names the removed for good and the stale until they are back`() = runBlocking { + val group = Group(5, 2) + val all = devicesFor(group) + val first = propose(all[0], mapOf(group.idOf[4] to ShareStanding.STALE)) + pump(all) + approveAll(all, first.id) + approveSigning(all) + + val preview = assertNotNull(ShareRefreshManager.preview(all[0].db, all[0].room, all[0].publicKey, without = all[3].publicKey)) + assertNull(preview.refusal, preview.refusal) + assertEquals(mapOf(all[3].publicKey to ShareStanding.RETIRED, all[4].publicKey to ShareStanding.STALE), preview.withheld) + assertEquals(setOf(all[0], all[1], all[2]).map { it.publicKey }.toSet(), preview.takingPart.toSet()) + } + + @Test + fun `the preview of a rotation that would be refused says why and sends nothing`() = runBlocking { + val group = Group(2, 2) + val (alice, bob) = devicesFor(group) + val preview = assertNotNull(ShareRefreshManager.preview(alice.db, alice.room, alice.publicKey, without = bob.publicKey)) + assertTrue(preview.refusal!!.contains("fewer than the 2 it takes to sign"), preview.refusal) + assertTrue(outbox(alice).isEmpty()) + assertNull(alice.db.shareRefreshDao().getSessionsForKey(ceremonyId).firstOrNull()) } // ---- the approvals, counted (docs/rotate-shares-single-approval.md) --------------------------------------------- @@ -299,7 +353,7 @@ class ShareRefreshRitualJvmTest { assertTrue(outbox(device).any { it.kind == ShareRefreshEvents.ROUND_2 }, "device ${device.index} did not confirm") val lines = device.db.chatMessageDao().getChatMessagesByChatRoomId(group.roomId) .filter { it.chatMessage.messageType == ChatMessage.TYPE_SHARE_REFRESH_APPROVAL_NEEDED } - assertEquals(1, lines.size, "device ${device.index} must be asked once") + assertEquals(if (device.index == 0) 0 else 1, lines.size, "device ${device.index} must be asked once, the proposer never") } } @@ -441,8 +495,8 @@ 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 only to take part; its device proposes the key state, and - * a proposer's signature is its proposal. + * proposer is asked nothing: proposing was taking part, its device proposes + * the key state, and a proposer's signature is its proposal. */ @Test fun `a recipient is asked to take part and to sign the new key state`() = runBlocking { @@ -453,7 +507,7 @@ class ShareRefreshRitualJvmTest { val asks = answerEverything(all, refresh.id) val rotation = listOf(Ask.Rotation(mobi.giza.compose.database.model.types.ShareRefreshApprovalStep.DEAL)) - assertEquals(rotation, asks[0], "the proposer") + 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.forEach { device -> assertEquals(1, device.db.groupKeyStateDao().getByChatRoomId(group.roomId)?.generation, "device ${device.index}") From d7fb71036f5eec39f2504ae9b2693a871e96f1e0 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:02:08 +0200 Subject: [PATCH 14/23] feat: a robust group's admin room takes its admins from the ceremony (robust-group-admins, Phase 1) ChatRepository.createMarmotGroup now takes the ceremony and the room it ran in instead of a list of admins, and MarmotGroupCreation.createFor derives the room's id, name, description and admins from it. The two callers -- CeremonyFollowThrough's step 3 and the ritual screen's button -- stop computing a set of their own. A room's epoch-0 admin list is fixed for good at an address the key derives, so the one place the founding set is read is now the one place a room is made. A device that was not in the ceremony is refused rather than listed as the room's creator. MarmotGroupCreationJvmTest: the coordinator's device and a member's make a room with the same admins, the ceremony's participants; an outsider makes none. jvmTest 1236/1236 (1 skipped, Phase 2's), compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../repository/DatabaseChatRepository.kt | 22 ++-- .../compose/managers/CeremonyFollowThrough.kt | 11 +- .../compose/managers/MarmotGroupCreation.kt | 63 ++++++++++ .../giza/compose/repository/ChatRepository.kt | 30 ++--- .../ui/view/model/DkgRitualViewModel.kt | 38 ++---- .../view/model/SelectChatRoomTypeViewModel.kt | 6 + .../managers/CeremonyFollowThroughJvmTest.kt | 11 +- .../managers/KeyStateSignsItselfJvmTest.kt | 12 +- .../managers/MarmotGroupCreationJvmTest.kt | 108 +++++++++++++++++- 9 files changed, 221 insertions(+), 80 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 1a119258..f76a9b99 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -29,6 +29,7 @@ import mobi.giza.compose.database.GENESIS_AT import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.ChatMessage import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.GiftWrapPayload import mobi.giza.compose.database.model.GroupKeyState import mobi.giza.compose.database.model.GroupSignedEvent @@ -48,7 +49,6 @@ import mobi.giza.compose.database.model.types.ShareRepairStage import mobi.giza.compose.database.model.types.ShareRefreshStage import mobi.giza.compose.database.model.types.ShareRefreshApprovalStep import mobi.giza.compose.database.model.types.DkgRitualStage -import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.managers.ShareGenerations import mobi.giza.compose.managers.ShareRepairManager import mobi.giza.compose.ExperimentalFeatures @@ -73,24 +73,16 @@ class DatabaseChatRepository( val logger = Logger.withTag(TAG) override suspend fun createMarmotGroup( - groupId: String, - name: String, - purpose: String, - adminPublicKeys: Set, - userPublicKey: HexKey, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, keyPair: KeyPair, - path: List, parentChatRoomId: HexKey?, - ): MarmotGroupCreation.Outcome = MarmotGroupCreation.create( + ): MarmotGroupCreation.Outcome = MarmotGroupCreation.createFor( database = database, chatRepository = this, - groupId = groupId, - name = name, - purpose = purpose, - adminPublicKeys = adminPublicKeys, - userPublicKey = userPublicKey, + ceremony = ceremony, + ceremonyRoom = ceremonyRoom, keyPair = keyPair, - path = path, parentChatRoomId = parentChatRoomId, ) @@ -778,4 +770,4 @@ class DatabaseChatRepository( companion object { const val TAG = "DatabaseChatRepository" } -} \ No newline at end of file +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt index 85846d44..0f0fb013 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt @@ -240,14 +240,13 @@ object CeremonyFollowThrough { } } - // 3. The room, with everyone the ceremony was run with as its admins. + // 3. The room, with everyone the ceremony was run with as its admins -- + // which `MarmotGroupCreation.createFor` reads off the ceremony itself, so + // there is no list here to get wrong (docs/robust-group-admins.md, Phase 1). when ( val outcome = chatRepository.createMarmotGroup( - groupId = roomId, - name = roomName(current), - purpose = roomPurpose(current), - adminPublicKeys = participants, - userPublicKey = current.userPublicKey, + ceremony = current, + ceremonyRoom = ceremonyRoom, keyPair = keyPair, // Verified by the time it is written: the key state this room was // gated on carries the certificate, and `stateFrom` refused it diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt index 0875dc3c..66ced0bf 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.flow.first import kotlin.time.Clock import kotlinx.coroutines.withTimeoutOrNull import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.MarmotKeyPackage import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.extensions.toHex @@ -195,6 +196,68 @@ object MarmotGroupCreation { ) } + /** + * Creates the room [ceremony]'s key derives, with the ceremony's participants + * as its admins. + * + * The only way the app makes such a room, and the reason [create] takes a list + * of admins nobody outside this file supplies. The founding members of a + * robust group are the participants of the ceremony that made its key -- + * every one of their devices built that set from the proposal it agreed to -- + * and a room's epoch-0 admin list is fixed for good at an address derived from + * the key. Two callers computing it was two chances to compute it differently. + * See docs/robust-group-admins.md, D1 and Phase 1. + * + * The room's id, name and description come off the ceremony too, so the + * coordinator's device creating it on its own and a member pressing the + * button make the same room. + * + * [ceremonyRoom] is the room the ceremony ran in: the participant set falls + * back to its members for a ceremony that predates its own participant list, + * as [ChillDkgRitualManager.participantsOf] does everywhere. + * + * A device that was not in the ceremony is refused. It holds no key state for + * the room and no share of the key, and listing itself as the room's + * creator would put an admin into the room the group never chose. + */ + suspend fun createFor( + database: GizaDatabase, + chatRepository: ChatRepository, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + keyPair: KeyPair, + parentChatRoomId: HexKey? = null, + keyPackageLookupTimeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT, + profile: MarmotProfile = MarmotProfile.DEFAULT_FOR_NEW_ROOMS, + ): Outcome { + val thresholdPublicKey = ceremony.thresholdPublicKey + ?: return Outcome.Failed("This ceremony has no key yet.") + + val founders = ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) + if (ceremony.participantPublicKeySet() == null) { + logger.w("Ceremony ${ceremony.id} predates its participant list; its room's members are its founders") + } + + if (ceremony.userPublicKey !in founders) { + logger.e("Not creating the room for ${ceremony.id}: ${ceremony.userPublicKey} was not in it") + return Outcome.Failed("Only someone who took part in the key ceremony can create its room.") + } + + return create( + database = database, + chatRepository = chatRepository, + groupId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey), + name = CeremonyFollowThrough.roomName(ceremony), + purpose = CeremonyFollowThrough.roomPurpose(ceremony), + adminPublicKeys = founders, + userPublicKey = ceremony.userPublicKey, + keyPair = keyPair, + parentChatRoomId = parentChatRoomId, + keyPackageLookupTimeout = keyPackageLookupTimeout, + profile = profile, + ) + } + /** * Writes `adminAt` on the rows of the members this room was created with as * admins. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index f8a61f1f..8284ded8 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -9,6 +9,7 @@ import com.vitorpamplona.quartz.nip17Dm.settings.DmRelayListEvent import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.GiftWrapPayload import mobi.giza.compose.database.model.GroupKeyState import mobi.giza.compose.database.model.GroupSignedEvent @@ -18,7 +19,6 @@ import mobi.giza.compose.database.model.intermdiate.LocalChatMessage import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.MarmotReindexReport import mobi.giza.compose.managers.MarmotGroupCreation -import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.SubgroupManager import mobi.giza.compose.nostr.MarmotProfile import mobi.giza.compose.ui.view.state.SharesSummary @@ -196,26 +196,30 @@ interface ChatRepository { ): List /** - * Creates a Marmot room at an id the group's key derives, with - * [adminPublicKeys] as its admins, and welcomes them into it. + * Creates the Marmot room [ceremony]'s key derives, with everyone the ceremony + * was run with as its admins, and welcomes them into it. * * Two flows want exactly this: the admin room a group opens after its * ceremony, and a subgroup. See `MarmotGroupCreation`, which holds the rules * -- every key package before anything exists, the admins baked into epoch 0, * and the key state filed before the members are added. * + * Takes the ceremony rather than a list of admins on purpose. The room's id + * is derived, so its epoch-0 admin list is fixed at that address for good, and + * the founding members of a robust group are exactly the ceremony's + * participants -- so the one place that set is read is the one place a room is + * made. [ceremonyRoom] is the room the ceremony ran in, read only for a + * ceremony that predates its own participant list. See + * docs/robust-group-admins.md, Phase 1. + * * Refuses rather than half-creates: the id is derived, so a partly created * room occupies that address permanently and there is no second id to retry * with. */ suspend fun createMarmotGroup( - groupId: String, - name: String, - purpose: String, - adminPublicKeys: Set, - userPublicKey: HexKey, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, keyPair: KeyPair, - path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH, parentChatRoomId: HexKey? = null, ): MarmotGroupCreation.Outcome @@ -439,13 +443,9 @@ interface ChatRepository { ): List = peers.map { it.first } override suspend fun createMarmotGroup( - groupId: String, - name: String, - purpose: String, - adminPublicKeys: Set, - userPublicKey: HexKey, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, keyPair: KeyPair, - path: List, parentChatRoomId: HexKey?, ): MarmotGroupCreation.Outcome = MarmotGroupCreation.Outcome.Failed("No database") diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt index 4bca2b1a..115dd582 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/DkgRitualViewModel.kt @@ -53,7 +53,6 @@ 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. @@ -522,7 +521,7 @@ class DkgRitualViewModel( val loaded = dkgRitualUIState as? DkgRitualUIState.Loaded ?: return val session = loaded.session - val thresholdPublicKey = session.thresholdPublicKey ?: return + if (session.thresholdPublicKey == null) return // The screen offers nothing until the group has signed, so this is a // guard rather than a path anybody takes. @@ -535,43 +534,24 @@ class DkgRitualViewModel( } val keyPair = KeyPair(privKey = nostrPrivateKey.value.toByteArray()) - val groupId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) - - // Everyone the ceremony was run with, this device included. These are the - // admins: the whole point of the room is that the members who hold shares of - // the key can all act in it. - // - // Off the ceremony rather than off the room, because for a subgroup the - // room is the parent's and its roster is the wrong set entirely. - val members = ChillDkgRitualManager.participantsOf(session, loaded.localChatRoom) - - // A subgroup is called what the coordinator called it; an admin room is - // called after the group it administers, because it has no name of its - // 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 = CeremonyFollowThrough.roomName(session) isActionPending.value = true adminGroupBlockedOn.value = emptyList() viewModelScope.launch(Dispatchers.IO) { + // The room, its name and its admins all come off the ceremony, inside + // `MarmotGroupCreation.createFor` -- the same call the coordinator's + // device makes on its own in `CeremonyFollowThrough`, so the two ways of + // making it cannot make two different rooms. Nothing here names an + // admin: docs/robust-group-admins.md, Phase 1. val outcome = chatRepository.createMarmotGroup( - groupId = groupId, - name = name, - purpose = CeremonyFollowThrough.roomPurpose(session), - adminPublicKeys = members, - userPublicKey = activeUserPublicKey, + ceremony = session, + ceremonyRoom = loaded.localChatRoom, 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 = subgroupParent + parentChatRoomId = loaded.parentChatRoomId ) isActionPending.value = false diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt index 0d4c290f..3a884bed 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SelectChatRoomTypeViewModel.kt @@ -94,6 +94,12 @@ class SelectChatRoomTypeViewModel( /** * Everyone who administers the group under [ChatRoomType.ROBUST]: the picked * members plus the creator. + * + * Counted here only to offer a quorum. The admins themselves are read off + * the ceremony this screen opens -- `ChillDkgRitualManager.proposeRitual` + * builds its participants by the same rule, the room's members plus the + * creator -- and `MarmotGroupCreation.createFor` makes the admin room from + * those. See docs/robust-group-admins.md, Phase 1. */ val adminCount: Int = (memberPublicKeys + activeUserPublicKey).distinct().size diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt index 5ff9d1fc..19003418 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt @@ -15,6 +15,7 @@ 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.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.GroupSignedEvent import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.database.model.types.DkgRitualStage @@ -52,15 +53,13 @@ class CeremonyFollowThroughJvmTest { private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { override suspend fun createMarmotGroup( - groupId: String, - name: String, - purpose: String, - adminPublicKeys: Set, - userPublicKey: HexKey, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, keyPair: KeyPair, - path: List, parentChatRoomId: HexKey?, ): MarmotGroupCreation.Outcome { + val groupId = SharedKeyDerivation.marmotGroupId(ceremony.thresholdPublicKey!!) + val adminPublicKeys = ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) created += groupId to adminPublicKeys return outcome(groupId) } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt index ce886ee3..c5c15336 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/KeyStateSignsItselfJvmTest.kt @@ -9,8 +9,10 @@ import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.FrostSigningItem import mobi.giza.compose.database.model.FrostSigningSession +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.nostr.frost.GroupKeyStateEvent @@ -32,15 +34,13 @@ class KeyStateSignsItselfJvmTest { private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { override suspend fun createMarmotGroup( - groupId: String, - name: String, - purpose: String, - adminPublicKeys: Set, - userPublicKey: HexKey, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, keyPair: KeyPair, - path: List, parentChatRoomId: HexKey?, ): MarmotGroupCreation.Outcome { + val groupId = SharedKeyDerivation.marmotGroupId(ceremony.thresholdPublicKey!!) + val adminPublicKeys = ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) created += groupId to adminPublicKeys return MarmotGroupCreation.Outcome.Failed("the room is MarmotGroupCreation's to test") } diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt index 3b7f1528..d66d4ced 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt @@ -22,6 +22,13 @@ import kotlinx.coroutines.IO import kotlinx.coroutines.runBlocking import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase +import com.vitorpamplona.marmot.appComponents.CurrentProfileGroupFactory +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.MarmotKeyPackage +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.database.model.NostrEvent import mobi.giza.compose.database.model.Profile import mobi.giza.compose.database.repository.DatabaseChatRepository @@ -153,9 +160,104 @@ class MarmotGroupCreationJvmTest { assertEquals("#Ekklesia", data.name) } - private suspend fun seedProfile(publicKey: String) { + // ---- From a ceremony: docs/robust-group-admins.md, Phase 1 ---------------- + + private val alice = KeyPair() + private val bob = KeyPair() + private val ceremonyRoomId = "ce1e".repeat(16) + + /** A finished ceremony over [user], alice and bob, as [owner]'s device holds it. */ + private suspend fun ceremonyOn(database: GizaDatabase, owner: KeyPair): Pair { + val everyone = listOf(keyPair, alice, bob) + everyone.forEach { seedProfile(it.pubKey.toHexKey(), database) } + + // Everybody but the device's own owner, as that device would have synced them. + everyone.filter { it !== owner }.forEach { peer -> + val bundle = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(peer)) + database.marmotKeyPackageDao().upsert( + MarmotKeyPackage( + id = peer.pubKey.toHexKey().take(60) + "0000", + publicKey = peer.pubKey.toHexKey(), + tlsEncodedMarmotKeyPackage = bundle.keyPackage.toTlsBytes(), + profile = MarmotProfile.CURRENT.wireName, + ) + ) + } + + database.chatRoomDao().upsert( + ChatRoom(id = ceremonyRoomId, userPublicKey = owner.pubKey.toHexKey(), subject = "Ekklesia", description = null, mlsGroupState = null) + ) + val session = DkgSession( + id = "the-ceremony", + chatRoomId = ceremonyRoomId, + coordinatorPublicKey = user, + userPublicKey = owner.pubKey.toHexKey(), + threshold = 2, + participantCount = 3, + participantPublicKeys = DkgSession.formatParticipants(everyone.map { it.pubKey.toHexKey() }.toSet()), + subject = "Ekklesia", + stage = DkgRitualStage.COMPLETE, + hostPublicKey = owner.pubKey.toHexKey(), + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + thresholdPublicKey = "02" + "ab".repeat(32), + secretShare = "cc".repeat(32), + ) + database.dkgSessionDao().upsert(session) + return session to assertNotNull(database.chatRoomDao().findChatRoomById(ceremonyRoomId)) + } + + @Test + fun `the room's admins are the ceremony's participants, whoever creates it`(): Unit = runBlocking { + val founders = setOf(user, alice.pubKey.toHexKey(), bob.pubKey.toHexKey()) + val alicesDb = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + try { + // The coordinator's device, and a member's -- the two ways the room gets made. + listOf(db to keyPair, alicesDb to alice).forEach { (database, owner) -> + val (session, ceremonyRoom) = ceremonyOn(database, owner) + + val outcome = MarmotGroupCreation.createFor( + database = database, + chatRepository = DatabaseChatRepository(database, CoroutineScope(Dispatchers.IO)), + ceremony = session, + ceremonyRoom = ceremonyRoom, + keyPair = owner, + keyPackageLookupTimeout = 2_000L, + ) + val created = assertIs(outcome) + assertEquals(groupId, created.room.chatRoom.id, "the room is not the one the key derives") + assertEquals("#Ekklesia", created.room.chatRoom.subject) + + val group = assertNotNull(created.room.chatRoom.toMlsGroup()) + assertEquals(founders, group.currentAdminIdentities(), "${owner.pubKey.toHexKey().take(8)}'s room") + } + } finally { + alicesDb.close() + } + } + + @Test + fun `a device that was not in the ceremony cannot create its room`(): Unit = runBlocking { + val (session, ceremonyRoom) = ceremonyOn(db, keyPair) + val outsider = session.copy(userPublicKey = KeyPair().pubKey.toHexKey()) + + val outcome = MarmotGroupCreation.createFor( + database = db, + chatRepository = repository, + ceremony = outsider, + ceremonyRoom = ceremonyRoom, + keyPair = KeyPair(), + ) + + assertIs(outcome) + assertNull(db.chatRoomDao().findChatRoomById(groupId), "a room was made anyway") + } + + private suspend fun seedProfile(publicKey: String, database: GizaDatabase = db) { + if (database.profileDao().getProfileByPublicKey(publicKey) != null) return val nostrEventId = publicKey.take(63) + "f" - db.nostrEventDao().upsert( + database.nostrEventDao().upsert( NostrEvent( id = nostrEventId, pubKey = publicKey, @@ -165,7 +267,7 @@ class MarmotGroupCreationJvmTest { sig = "0".repeat(128), ) ) - db.profileDao().upsert( + database.profileDao().upsert( Profile(publicKey = publicKey, userName = "member", nostrEventId = nostrEventId) ) } From 83711419ef0d299b40ceda45ea5ec32250131de0 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:05:42 +0200 Subject: [PATCH 15/23] fix: a member welcomed into a room sees its admins at once (robust-group-admins, Phase 2) Participant.adminAt had three writers and the Welcome was not one of them: a joiner's rows came from Participant.fromMlsGroup with no flag, so on every device but the creator's a robust group's admin room showed no admins until some later commit happened to arrive. AdminFlags.reconcile is now the one writer. It reads the room's rows fresh and flags them from the group's own admin policy, both ways, and writes nothing about membership. The Welcome path calls it after the participant upsert; MarmotGroupCreation calls it in place of stampAdmins, off the group it just made rather than its own list; and processGroupMembershipChanges calls it in place of its three inline computations. Phase 0's ignored test passes. MarmotGroupCreationJvmTest: flags follow the policy both ways, and a second pass changes nothing. jvmTest 1237/1237, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../giza/compose/database/dao/NostrDao.kt | 12 ++++ .../mobi/giza/compose/managers/AdminFlags.kt | 59 +++++++++++++++++++ .../compose/managers/MarmotGroupCreation.kt | 49 +++++---------- .../compose/managers/MarmotInboundManager.kt | 33 ++--------- .../managers/MarmotGroupCreationJvmTest.kt | 42 +++++++++++++ .../managers/RobustGroupAdminsJvmTest.kt | 4 +- 6 files changed, 132 insertions(+), 67 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index 80a643f1..d8054d99 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -60,6 +60,7 @@ import mobi.giza.compose.exceptions.MarmotMissingKeyPackageBundleException import mobi.giza.compose.exceptions.MarmotMissingNostrGroupDataExtension import mobi.giza.compose.exceptions.MarmotNotMemberOfChatGroupException import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.managers.AdminFlags import mobi.giza.compose.managers.ChillDkgRitualManager import mobi.giza.compose.managers.ShareRefreshManager import mobi.giza.compose.managers.ShareRepairManager @@ -899,6 +900,17 @@ abstract class NostrDao( participants ) + // The admins, from the group context this device + // was welcomed into. Without it a joiner's rows + // flagged nobody until some later commit arrived, + // which in a robust group's admin room may be + // never -- docs/robust-group-admins.md, Phase 2. + AdminFlags.reconcile( + database = database, + chatRoomId = nostrGroupId, + mlsGroup = group, + ) + // Save ChatRoom Relays... participants.filter { it.participantPublicKey != userPublicKey }.forEach { participant -> val publicKey = participant.participantPublicKey diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt new file mode 100644 index 00000000..cb121030 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt @@ -0,0 +1,59 @@ +package mobi.giza.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.mls.group.MlsGroup +import kotlin.time.Clock +import mobi.giza.compose.database.GizaDatabase + +/** + * `Participant.adminAt`, kept in line with the group's own admin policy. + * + * The policy is the truth -- `AdminPolicyV1` on the current profile, + * `MarmotGroupData.admin_pubkeys` on the legacy one -- and it is what the library + * enforces and what `isLocalAdmin()` reads. The column is this device's cache of + * it, for the screens that label members. A cache with three writers drifted: + * the creator caught its rows up by hand, a commit reconciled them, and the + * Welcome wrote none at all, so on every device but the creator's a robust + * group's admin room showed no admins until some later commit happened to + * arrive. docs/robust-group-admins.md, G2 and D2. + * + * So there is one writer, and every path that changes what the policy says or + * which rows exist calls it: the room's creation, the Welcome, and every commit. + * + * Flags only, never membership. Removing the rows of members the tree no longer + * holds is `MarmotInboundManager.processGroupMembershipChanges`'s job, on a + * commit; doing it here would turn a best-effort step -- a partly failed invite + * at creation, say -- into a partial membership. + */ +object AdminFlags { + private val logger = Logger.withTag("AdminFlags") + + /** + * Flags the rows of [chatRoomId] that [mlsGroup]'s admin policy names and + * clears the rest. Reads the rows fresh, so it can run straight after an + * upsert that added some. + * + * @return how many rows changed. + */ + suspend fun reconcile(database: GizaDatabase, chatRoomId: String, mlsGroup: MlsGroup): Int { + val admins = mlsGroup.currentAdminIdentities() + val room = database.chatRoomDao().findChatRoomById(chatRoomId) ?: return 0 + val now = Clock.System.now() + + val changed = room.localParticipants.map { it.participant }.mapNotNull { participant -> + val named = participant.participantPublicKey in admins + when { + named && participant.adminAt == null -> participant.copy(adminAt = now) + !named && participant.adminAt != null -> participant.copy(adminAt = null) + else -> null + } + } + + if (changed.isNotEmpty()) { + logger.d("$chatRoomId: ${changed.size} admin flag(s) brought in line with the group") + database.participantDao().upsert(changed) + } + return changed.size + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt index 66ced0bf..e3623067 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt @@ -9,7 +9,6 @@ import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first -import kotlin.time.Clock import kotlinx.coroutines.withTimeoutOrNull import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.model.DkgSession @@ -188,7 +187,7 @@ object MarmotGroupCreation { logger.w("$groupId created without ${notAdded.size} member(s): $notAdded") } - stampAdmins(database, groupId, adminPublicKeys) + flagAdmins(database, groupId) return Outcome.Created( room = chatRepository.getChatRoomByIdentifier(groupId) ?: localChatRoom, @@ -262,45 +261,25 @@ object MarmotGroupCreation { * Writes `adminAt` on the rows of the members this room was created with as * admins. * - * The creating device never learns this any other way, which is a bug older - * than subgroups and easy to miss. `Participant.adminAt` is written in exactly - * one place -- `MarmotInboundManager.processGroupMembershipChanges`, on an - * arriving commit -- while the rows a creator makes come from - * `getOrCreateChatRoom` and `addMembers`, neither of which sets it. So on the - * device that made the room, every participant reads as a non-admin until some - * *other* member sends a commit it processes: a room whose epoch-0 context - * names three admins had none of them flagged, on the one device certain to be - * one. + * The creating device never learns this any other way: its rows come from + * `getOrCreateChatRoom` and `addMembers`, neither of which sets the flag, and + * no commit arrives to reconcile them -- a room whose epoch-0 context named + * three admins had none of them flagged on the one device certain to be one. * - * This is the same list already baked into `MarmotGroupData` a few lines - * above, so nothing new is being asserted -- the row is being caught up with - * the group context it was created from. `processGroupMembershipChanges` - * reconciles it against the MLS tree from then on and will agree. - * - * Only flags are written. That function also *removes* participants missing - * from the tree, and running the whole reconciliation here would soft-delete + * Through [AdminFlags.reconcile], off the group this device just made, rather + * than off [create]'s own list: the policy is what every other device reads, + * and one writer is how the two cannot disagree (docs/robust-group-admins.md, + * D2). Only flags are written. A membership reconciliation here would remove * the rows of anyone `addMembers` could not reach -- turning a partial invite - * into a partial membership. Widening a flag is safe; narrowing membership on - * a best-effort step is not. + * into a partial membership. * * Swallowed on failure, like `adopt` above it: the room is made and usable, - * and what a missing flag costs is a button not being offered rather than - * anything being wrong. + * and what a missing flag costs is a label rather than anything being wrong. */ - private suspend fun stampAdmins( - database: GizaDatabase, - groupId: String, - adminPublicKeys: Set - ) { + private suspend fun flagAdmins(database: GizaDatabase, groupId: String) { runCatching { - val room = database.chatRoomDao().findChatRoomById(groupId) ?: return - - val stamped = room.localParticipants - .map { it.participant } - .filter { it.participantPublicKey in adminPublicKeys && it.adminAt == null } - .map { it.copy(adminAt = Clock.System.now()) } - - if (stamped.isNotEmpty()) database.participantDao().upsert(stamped) + val group = database.chatRoomDao().findChatRoomById(groupId)?.chatRoom?.toMlsGroup() ?: return + AdminFlags.reconcile(database, groupId, group) }.onFailure { logger.e("Created $groupId but could not flag its admins", it) } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt index af9fac92..e10d30d6 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotInboundManager.kt @@ -3,7 +3,6 @@ package mobi.giza.compose.managers import co.touchlab.kermit.Logger import com.vitorpamplona.marmot.GroupEventResult import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent -import com.vitorpamplona.marmot.groups.currentAdminIdentities import com.vitorpamplona.marmot.groups.currentGroupState import com.vitorpamplona.marmot.mip03GroupMessages.GroupEventEncryption import com.vitorpamplona.mls.codec.TlsReader @@ -136,7 +135,6 @@ object MarmotInboundManager { announceAdditions: Boolean = true, ) { logger.d("processGroupMembershipChanges") - val adminPublicKeys = mlsGroup.currentAdminIdentities() val commitedGroupMembers = Participant.fromMlsGroup( mlsGroup = mlsGroup, @@ -153,35 +151,13 @@ object MarmotInboundManager { } logger.d("excludedParticipants: $excludedParticipants") val existingParticipantPublicKeys = localChatRoom.localParticipants.map { it.participant.participantPublicKey } + // Admin flags are not written here: `AdminFlags.reconcile` below reads the + // rows this function leaves and flags them from the group's policy, the + // same call the Welcome and the room's creation make. val newParticipants = commitedGroupMembers.filter { committedGroupMember -> existingParticipantPublicKeys.contains(committedGroupMember.participantPublicKey).not() - }.map { newParticipant -> - newParticipant.copy( - adminAt = if (adminPublicKeys.contains(newParticipant.participantPublicKey)) { - Clock.System.now() - } else { - null - } - ) } logger.d("newParticipants: $newParticipants") - val removedAdmins = localChatRoom.localParticipants.filter { localParticipant -> - localParticipant.participant.adminAt != null && !adminPublicKeys.contains(localParticipant.participant.participantPublicKey) - }.map { localParticipant -> - localParticipant.participant.copy( - adminAt = null - ) - } - logger.d("removedAdmins: $removedAdmins") - - val graduatedAdmins = localChatRoom.localParticipants.filter { localParticipant -> - localParticipant.participant.adminAt == null && adminPublicKeys.contains(localParticipant.participant.participantPublicKey) - }.map { localParticipant -> - localParticipant.participant.copy( - adminAt = Clock.System.now() - ) - } - logger.d("graduatedAdmins: $graduatedAdmins") // Placeholder profiles for new participants... newParticipants.forEach { newParticipant -> @@ -246,10 +222,9 @@ object MarmotInboundManager { ) } // Handle membership changes... - database.participantDao().upsert(removedAdmins) database.participantDao().delete(excludedParticipants) database.participantDao().upsert(newParticipants) - database.participantDao().upsert(graduatedAdmins) + AdminFlags.reconcile(database, localChatRoom.chatRoom.id, mlsGroup) val userPublicKey = localChatRoom.chatRoom.userPublicKey val disbanded = mlsGroup.currentGroupState().isDisbanded diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt index d66d4ced..1285b919 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/MarmotGroupCreationJvmTest.kt @@ -30,6 +30,7 @@ import mobi.giza.compose.database.model.MarmotKeyPackage import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.DkgRitualStage import mobi.giza.compose.database.model.NostrEvent +import mobi.giza.compose.database.model.Participant import mobi.giza.compose.database.model.Profile import mobi.giza.compose.database.repository.DatabaseChatRepository import mobi.giza.compose.extensions.toHex @@ -160,6 +161,47 @@ class MarmotGroupCreationJvmTest { assertEquals("#Ekklesia", data.name) } + /** + * One writer for the flags, from the group's policy, both ways: a row the + * policy names is flagged, and a row it does not name loses a flag it had. + * docs/robust-group-admins.md, Phase 2. + */ + @Test + fun `admin flags follow the group's policy, both ways`(): Unit = runBlocking { + seedProfile(user) + MarmotGroupCreation.create( + database = db, + chatRepository = repository, + groupId = groupId, + name = "#Ekklesia", + purpose = "Admins of Ekklesia.", + adminPublicKeys = setOf(user), + userPublicKey = user, + keyPair = keyPair, + ) + + val stranger = KeyPair().pubKey.toHexKey() + seedProfile(stranger) + val creatorRow = db.chatRoomDao().findChatRoomById(groupId)!!.localParticipants + .single { it.participant.participantPublicKey == user }.participant + db.participantDao().upsert( + listOf( + creatorRow.copy(adminAt = null), + Participant(participantPublicKey = stranger, chatRoomId = groupId, relayHint = null, adminAt = Clock.System.now()), + ) + ) + + val group = assertNotNull(db.chatRoomDao().findChatRoomById(groupId)!!.chatRoom.toMlsGroup()) + assertEquals(2, AdminFlags.reconcile(db, groupId, group)) + + val rows = db.chatRoomDao().findChatRoomById(groupId)!!.localParticipants.associate { + it.participant.participantPublicKey to it.participant.adminAt + } + assertNotNull(rows[user], "the policy names the creator") + assertNull(rows[stranger], "the policy does not name the stranger") + assertEquals(0, AdminFlags.reconcile(db, groupId, group), "and a second pass changes nothing") + } + // ---- From a ceremony: docs/robust-group-admins.md, Phase 1 ---------------- private val alice = KeyPair() diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt index 91283b7a..7d7e1774 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt @@ -13,7 +13,6 @@ import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealEvent import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent -import kotlin.test.Ignore import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertEquals @@ -179,9 +178,8 @@ class RobustGroupAdminsJvmTest { /** * The rows, which are what the screens label members with. The creator's are * caught up by `MarmotGroupCreation`; a joiner's come from the Welcome, which - * writes none of them. + * wrote none of them until Phase 2 put `AdminFlags.reconcile` on that path. */ - @Ignore("Phase 2: the Welcome writes no admin flags") @Test fun `every device flags every founding member as an admin`() = onEveryProfile { profile, phones -> val founders = phones.map { it.publicKey }.toSet() From 46eb23b7776c8be9b0cb7ae2e011cb677cc92aa3 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:06:39 +0200 Subject: [PATCH 16/23] 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 --- .../database/dao/FrostSigningSessionDao.kt | 7 + .../repository/DatabaseNostrRepository.kt | 4 + .../compose/managers/FrostSigningManager.kt | 52 +++++- .../compose/managers/GroupKeyStateManager.kt | 78 ++++++++- .../managers/ShareRefreshRitualJvmTest.kt | 158 ++++++++++++++++-- 5 files changed, 264 insertions(+), 35 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt index b1f23073..0f30919c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/FrostSigningSessionDao.kt @@ -83,6 +83,13 @@ interface FrostSigningSessionDao { suspend fun getSessionsForChatRoom(chatRoomId: String): List /** 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 + @Query("SELECT * FROM FrostSigningSession WHERE dkgSessionId = :dkgSessionId AND stage NOT IN ('COMPLETE', 'FAILED')") suspend fun getOpenSessionsForKey(dkgSessionId: String): List diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt index 414a37cf..7d105ec7 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseNostrRepository.kt @@ -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, ) } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt index 8fcca9db..a3a9095e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FrostSigningManager.kt @@ -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 } /** diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt index 0b1dcab3..60c82131 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/GroupKeyStateManager.kt @@ -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 } 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 03f6d9d2..fbe26bbd 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -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 { + fun `a recipient is asked only to take part`() = runBlocking { 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 { + fun `a completed rotation signs its new key state and the old shares go, with nobody asked`() = runBlocking { 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 { + 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 { + 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>) = 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 = 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 { + 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 { + 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 { 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 -> From 4671a86a6de121497871ae6b9279dfc7b942df30 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:10:01 +0200 Subject: [PATCH 17/23] feat: a device checks its admin room against the ceremony it took part in (robust-group-admins, Phase 3) FoundingAdmins.check compares a key-backed room's admin policy with the participants of the ceremony that made its key, as this device's own DkgSession row has them -- and, for a subgroup, with the admins its parent's birth certificate names. NotKeyBacked, CannotCheck (a later joiner, who holds no ceremony), Matches, or Missing with who. At the Welcome, after the key state is adopted, a room missing founders gets one transcript line naming them (TYPE_FOUNDING_ADMINS_MISSING, a membership line). The detail screen reads the check on every load into ChatRoomDetailUIState.missingFoundingAdmins. The repair is MarmotOutboundDao.addAdmins: one gated commit on the current profile that writes the policy the group holds now plus the missing founders -- additions only, never a list built elsewhere. The legacy profile has no governance commits in this app, so a legacy room gets the warning without the repair. FoundingAdminsJvmTest: each Check, the pre-column fallback, the line written once and only when someone is missing, and the repair on the current profile through a relay's OK. jvmTest 1245/1245, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../compose/database/dao/MarmotOutboundDao.kt | 26 +++ .../giza/compose/database/dao/NostrDao.kt | 12 + .../compose/database/model/ChatMessage.kt | 9 + .../repository/DatabaseChatRepository.kt | 14 ++ .../giza/compose/managers/FoundingAdmins.kt | 115 +++++++++ .../giza/compose/repository/ChatRepository.kt | 21 ++ .../ui/view/model/ChatRoomDetailViewModel.kt | 17 ++ .../ui/view/state/ChatRoomDetailUIState.kt | 7 + .../compose/managers/FoundingAdminsJvmTest.kt | 221 ++++++++++++++++++ 9 files changed, 442 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt create mode 100644 composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt index e0d28947..9f98ea80 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/MarmotOutboundDao.kt @@ -7,6 +7,7 @@ import com.vitorpamplona.crypto.random.RandomInstance import com.vitorpamplona.marmot.appComponents.AppComponentIds import com.vitorpamplona.marmot.foundation.appEvents.MarmotAppEvent import com.vitorpamplona.marmot.groups.MlsGroupManager +import com.vitorpamplona.marmot.appComponents.AdminPolicyV1 import com.vitorpamplona.marmot.groups.currentAdminIdentities import com.vitorpamplona.marmot.groups.currentGroupState import com.vitorpamplona.marmot.groups.isLocalAdmin @@ -862,6 +863,31 @@ abstract class MarmotOutboundDao( publishGatedCommit(localChatRoom) { manager, id -> manager.stageRemoveMember(id, leafIndex) } } + /** + * Adds [publicKeys] to a current-profile room's admin policy, as an admin. + * + * Additions only. The policy committed is the one the group holds now plus + * these -- never a list built somewhere else -- so an admin already there is + * never dropped by it. One commit for all of them, through the publish gate + * like every other governance change. Nothing to do when every one is already + * listed. docs/robust-group-admins.md, Phase 3. + */ + @Transaction + open suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) { + require(localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT) { "Only a current-profile room can change its admins" } + val group = database.marmotEngine.groupFor(localChatRoom.routingId) + ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}") + + val current = group.currentAdminIdentities() + val added = publicKeys - current + if (added.isEmpty()) return + + val policy = AdminPolicyV1.ofHex(current + added).encode() + publishGatedCommit(localChatRoom) { manager, id -> + manager.stageAppDataUpdate(id, AdminPolicyV1.COMPONENT_ID, policy) + } + } + /** * Disbands a current-profile room, as an admin. * diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt index d8054d99..7facdce2 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/NostrDao.kt @@ -61,6 +61,7 @@ import mobi.giza.compose.exceptions.MarmotMissingNostrGroupDataExtension import mobi.giza.compose.exceptions.MarmotNotMemberOfChatGroupException import mobi.giza.compose.extensions.toHex import mobi.giza.compose.managers.AdminFlags +import mobi.giza.compose.managers.FoundingAdmins import mobi.giza.compose.managers.ChillDkgRitualManager import mobi.giza.compose.managers.ShareRefreshManager import mobi.giza.compose.managers.ShareRepairManager @@ -972,6 +973,17 @@ abstract class NostrDao( chatRoomId = nostrGroupId ) + // And with the state on file, whether the room + // names every member of that ceremony as an + // admin -- this device's own record against the + // creator's list. docs/robust-group-admins.md, + // Phase 3. + FoundingAdmins.announceIfMissing( + database = database, + chatRoomId = nostrGroupId, + userPublicKey = userPublicKey, + ) + // Where is the decoded welcome message... // TODO: Sync GroupEvents/Messages... // database.chatMessageDao().upsert( diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt index a0907524..ef1c736b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/model/ChatMessage.kt @@ -577,6 +577,14 @@ data class ChatMessage( */ const val TYPE_CHANGE_REJECTED = "changeRejected" + /** + * The admin room this device was welcomed into does not name every member + * of the ceremony that made its key as an admin. Derived at the Welcome + * from this device's own record of the ceremony, never received, and + * written once. docs/robust-group-admins.md, Phase 3. + */ + const val TYPE_FOUNDING_ADMINS_MISSING = "foundingAdminsMissing" + /** * Every membership line, for the one check the transcript dispatches on. * @@ -591,6 +599,7 @@ data class ChatMessage( TYPE_MEMBER_LEFT, TYPE_GROUP_DISBANDED, TYPE_CHANGE_REJECTED, + TYPE_FOUNDING_ADMINS_MISSING, ) const val TYPE_UNDECRYPTABLE_OUTER_LAYER = "undecryptableOuterLayer" diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index f76a9b99..e713b2bb 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -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.FoundingAdmins import mobi.giza.compose.managers.CeremonyFollowThrough import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate @@ -639,6 +640,19 @@ class DatabaseChatRepository( database.marmotOutboundDao().removeMember(localChatRoom, memberPublicKey) } + override suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) { + database.marmotOutboundDao().addAdmins(localChatRoom, publicKeys) + } + + override suspend fun foundingAdmins(chatRoomId: String): FoundingAdmins.Check = try { + FoundingAdmins.check(database, chatRoomId) + } catch (e: Throwable) { + // A room whose check threw is shown without the warning rather than not + // at all; the check is a label on the room, not a gate in front of it. + logger.e("Error checking the founding admins of $chatRoomId", e) + FoundingAdmins.Check.CannotCheck + } + override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = ExperimentalFeatures.shareRefresh && runCatching { ShareRefreshManager.liveIdOf(database, localChatRoom, memberPublicKey) != null }.getOrDefault(false) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt new file mode 100644 index 00000000..bd5b78b6 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt @@ -0,0 +1,115 @@ +package mobi.giza.compose.managers + +import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent + +/** + * Whether a key-backed room's admin policy names every one of its founding + * members. docs/robust-group-admins.md, Phase 3. + * + * The founding members are the participants of the ceremony that made the room's + * key (D1). Every one of their devices built that set from the proposal it agreed + * to, so each can check the room it was welcomed into against its own record + * rather than trusting the device that happened to create it -- a bug, an older + * build, or a Bennu peer could all have listed fewer. A subgroup has a second + * record of the same set: the birth certificate its parent's quorum signed, which + * names its admins. + * + * Nothing is refused on a mismatch. The room's address is the key, and there is + * no second room to go to; a warning that names who is missing is what can be + * acted on, by any admin, with [missingFrom]'s answer. + */ +object FoundingAdmins { + + /** Enough of a key to tell two members apart when no profile is stored. */ + private const val SHORTENED_PUBLIC_KEY_LENGTH = 12 + + sealed interface Check { + /** No key behind the room -- a convenient group, run by its creator. */ + data object NotKeyBacked : Check + + /** + * A key-backed room this device holds no ceremony for: a member added + * after the founding, or a reinstall. It is not one of the founders, and + * has nothing of its own to check the room against. + */ + data object CannotCheck : Check + + data object Matches : Check + + /** Founding members the room's admin policy does not name. */ + data class Missing(val publicKeys: Set) : Check + } + + suspend fun check(database: GizaDatabase, chatRoomId: String): Check { + val state = database.groupKeyStateDao().getByChatRoomId(chatRoomId) ?: return Check.NotKeyBacked + val group = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.toMlsGroup() + ?: return Check.CannotCheck + val ceremony = database.dkgSessionDao().getSessionById(state.dkgSessionId) + + val founders = foundersOf(database, ceremony).orEmpty() + certifiedAdmins(state.birthCertificateJson) + if (founders.isEmpty()) return Check.CannotCheck + + val missing = founders - group.currentAdminIdentities() + return if (missing.isEmpty()) Check.Matches else Check.Missing(missing) + } + + /** + * Checks the room this device was just welcomed into, and says so in its + * transcript when founding members are missing from its admins. Once, at the + * Welcome: the detail screen repeats the check on every visit, and a line per + * visit would be the same news told again. + * + * A whole sentence naming who is missing, like the membership lines it sits + * among, so nothing prefixes a sender's name to it. + */ + suspend fun announceIfMissing(database: GizaDatabase, chatRoomId: String, userPublicKey: HexKey): Check { + val check = check(database, chatRoomId) + if (check !is Check.Missing) return check + + val names = check.publicKeys.map { publicKey -> + database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey() + ?: publicKey.take(SHORTENED_PUBLIC_KEY_LENGTH) + }.sorted() + + database.chatMessageDao().upsert( + ChatMessage( + content = "This room was created without ${names.joinToString(", ")} as " + + (if (names.size == 1) "an admin" else "admins") + + ", though they took part in the key ceremony. An admin can add them back from the room's details.", + messageType = ChatMessage.TYPE_FOUNDING_ADMINS_MISSING, + chatRoomId = chatRoomId, + senderPublicKey = userPublicKey, + isUserMessage = true, + giftWrapPayloadId = null, + marmotGroupEventId = null, + marmotInnerEventId = null, + ) + ) + return check + } + + /** The ceremony's participants, or null when this device holds no record of them. */ + private suspend fun foundersOf(database: GizaDatabase, ceremony: DkgSession?): Set? { + ceremony ?: return null + ceremony.participantPublicKeySet()?.let { return it } + val ceremonyRoom = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return null + return ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) + } + + /** + * The admins a subgroup's parent certified it with, or nothing for a group + * with no parent. Only read off a state that `GroupKeyStateManager.stateFrom` + * kept, which it does only for a certificate that checked out. + */ + private fun certifiedAdmins(birthCertificateJson: String?): Set = + birthCertificateJson + ?.let { Event.fromJsonOrNull(it) } + ?.let { SubgroupBirthCertificateEvent.parseAdminPublicKeys(it.tags).toSet() } + .orEmpty() +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index 8284ded8..bdb80a06 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -18,6 +18,7 @@ import mobi.giza.compose.database.model.Participant import mobi.giza.compose.database.model.intermdiate.LocalChatMessage import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.MarmotReindexReport +import mobi.giza.compose.managers.FoundingAdmins import mobi.giza.compose.managers.MarmotGroupCreation import mobi.giza.compose.managers.SubgroupManager import mobi.giza.compose.nostr.MarmotProfile @@ -272,6 +273,21 @@ interface ChatRepository { */ suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) + /** + * Adds [publicKeys] to a current-profile room's admin policy, as an admin of + * it: one commit through the publish gate, additions only. The repair for a + * room missing founding members from its admins -- see [foundingAdmins] and + * docs/robust-group-admins.md, Phase 3. + */ + suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) + + /** + * Whether [chatRoomId]'s admin policy names every member of the ceremony that + * made its key, as this device's own record of that ceremony has them. See + * `FoundingAdmins`. + */ + suspend fun foundingAdmins(chatRoomId: String): FoundingAdmins.Check + /** * Whether [memberPublicKey] holds a live share of the room's key, and so * whether a removal leaves them able to help sign until the shares are @@ -486,6 +502,11 @@ interface ChatRepository { override suspend fun removeMember(localChatRoom: LocalChatRoom, memberPublicKey: HexKey) = Unit + override suspend fun addAdmins(localChatRoom: LocalChatRoom, publicKeys: Set) = Unit + + override suspend fun foundingAdmins(chatRoomId: String): FoundingAdmins.Check = + FoundingAdmins.Check.NotKeyBacked + override suspend fun holdsShare(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): Boolean = false override suspend fun rotateSharesWithout(localChatRoom: LocalChatRoom, memberPublicKey: HexKey): String? = null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 3cb13a0e..83a7739b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -18,6 +18,7 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch +import mobi.giza.compose.managers.FoundingAdmins import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.MarmotReindexReport import mobi.giza.compose.managers.WalletRefusal @@ -108,6 +109,9 @@ class ChatRoomDetailViewModel( canGovern = canGovern, isDisbanded = isDisbanded, shares = chatRepository.sharesSummary(localChatRoom), + missingFoundingAdmins = (chatRepository.foundingAdmins(chatRoomId) as? FoundingAdmins.Check.Missing) + ?.publicKeys + .orEmpty(), ) } } @@ -136,6 +140,19 @@ class ChatRoomDetailViewModel( } } + /** + * Adds the founding members the room's admin policy is missing, as an admin, + * and reloads the screen. One commit, applied when a relay accepts it, so the + * warning stays until then. docs/robust-group-admins.md, Phase 3. + */ + fun addMissingFoundingAdmins(localChatRoom: LocalChatRoom, missing: Set, onDone: (String?) -> Unit = {}) { + viewModelScope.launch(Dispatchers.IO) { + val failure = runCatching { chatRepository.addAdmins(localChatRoom, missing) }.exceptionOrNull() + initiateChatRoomDetail() + viewModelScope.launch(Dispatchers.Main) { onDone(failure?.message) } + } + } + /** * Runs one Shares section action, reloads the screen, and reports: null for * done, or why not. Every one of them is a proposal or an answer the group diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 5b7b8511..20b85009 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -84,6 +84,13 @@ sealed interface ChatRoomDetailUIState { * room has no key (docs/frost-share-refresh.md, Phase 11). */ val shares: SharesSummary? = null, + /** + * Members of the ceremony that made this room's key whom its admin policy + * does not name -- empty when it names them all, and when this device has + * no record of the ceremony to check against. Read through + * `FoundingAdmins.check`; docs/robust-group-admins.md, Phase 3. + */ + val missingFoundingAdmins: Set = emptySet(), ): ChatRoomDetailUIState data class Error( diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt new file mode 100644 index 00000000..adb93818 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/FoundingAdminsJvmTest.kt @@ -0,0 +1,221 @@ +package mobi.giza.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.marmot.groups.currentAdminIdentities +import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent +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 kotlin.time.Clock +import kotlin.time.Instant +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.builder.getRoomDatabase +import mobi.giza.compose.database.model.ChatMessage +import mobi.giza.compose.database.model.ChatRoom +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.GroupKeyState +import mobi.giza.compose.database.model.Participant +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.repository.DatabaseChatRepository +import mobi.giza.compose.database.repository.DatabaseNostrRepository +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.MarmotProfile +import mobi.giza.compose.nostr.Relays + +/** + * A device checking the room it holds against the ceremony it took part in. + * docs/robust-group-admins.md, Phase 3. + * + * The rooms here are made with [MarmotGroupCreation.create] and a list of admins + * on purpose: that is the one way to stand in for a room some other device made + * with fewer admins than the ceremony had, which is what the check is for. + */ +class FoundingAdminsJvmTest { + + private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val scope = CoroutineScope(Dispatchers.Default) + private val chatRepository = DatabaseChatRepository(db, scope) + private val nostrRepository = DatabaseNostrRepository(db, scope) + + @AfterTest + fun closeDb() = db.close() + + private val keyPair = KeyPair() + private val user = keyPair.pubKey.toHexKey() + private val alice = KeyPair().pubKey.toHexKey() + private val bob = KeyPair().pubKey.toHexKey() + private val founders = setOf(user, alice, bob) + + private val thresholdPublicKey = "02" + KeyPair().pubKey.toHexKey() + private val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + private val ceremonyRoomId = "ce1e".repeat(16) + private val sessionId = "the-ceremony" + + /** + * A room at [roomId] whose epoch-0 admins are [admins] -- whatever the ceremony + * said -- holding only its creator. Built from the steps `MarmotGroupCreation` + * takes, minus the invites: the check is about the policy, and listing an admin + * needs no key package of theirs. + */ + private suspend fun roomWithAdmins(admins: Set, profile: MarmotProfile = MarmotProfile.LEGACY) { + (founders + admins).forEach { MarmotStandIn.seedProfile(db, it) } + val created = MarmotGroupFactory.create( + creator = keyPair, + roomId = roomId, + name = "#Ekklesia", + description = SharedKeyDerivation.describe("Admins of Ekklesia."), + adminPublicKeys = admins, + relays = Relays.DefaultDMRelayList.map { it.url }, + profile = profile, + ) + assertNotNull( + chatRepository.getOrCreateChatRoom( + chatRoomId = roomId, + activeUserPublicKey = user, + relayHint = null, + defaultSubject = "#Ekklesia", + description = null, + mlsGroupState = created.group.saveState().encodeTls().toHex(), + ) + ) + chatRepository.recordMarmotRouting(chatRoomId = roomId, routingId = created.routingId) + } + + private suspend fun ceremony(participants: Set? = founders) { + db.chatRoomDao().upsert(ChatRoom(id = ceremonyRoomId, userPublicKey = user, subject = "Ekklesia", description = null, mlsGroupState = null)) + db.dkgSessionDao().upsert( + DkgSession( + id = sessionId, + chatRoomId = ceremonyRoomId, + coordinatorPublicKey = user, + userPublicKey = user, + threshold = 2, + participantCount = 3, + participantPublicKeys = participants?.let { DkgSession.formatParticipants(it) }, + subject = "Ekklesia", + stage = DkgRitualStage.COMPLETE, + hostPublicKey = user, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + thresholdPublicKey = thresholdPublicKey, + secretShare = "cc".repeat(32), + ) + ) + } + + private suspend fun keyState() { + db.groupKeyStateDao().replace( + GroupKeyState( + chatRoomId = roomId, + dkgSessionId = sessionId, + thresholdPublicKey = thresholdPublicKey, + derivationPath = SharedKeyDerivation.formatPath(SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH), + announcedBy = roomId, + announcedAt = Clock.System.now(), + ) + ) + } + + @Test + fun `a room with no key behind it has no founders to check`(): Unit = runBlocking { + roomWithAdmins(setOf(user)) + assertEquals(FoundingAdmins.Check.NotKeyBacked, FoundingAdmins.check(db, roomId)) + } + + @Test + fun `a device that holds no ceremony for the room cannot check it`(): Unit = runBlocking { + roomWithAdmins(setOf(user)) + keyState() + assertEquals(FoundingAdmins.Check.CannotCheck, FoundingAdmins.check(db, roomId)) + } + + @Test + fun `a room made with every founder as an admin matches`(): Unit = runBlocking { + roomWithAdmins(founders) + ceremony() + keyState() + assertEquals(FoundingAdmins.Check.Matches, FoundingAdmins.check(db, roomId)) + } + + @Test + fun `a room made by a device that listed only itself is missing the others`(): Unit = runBlocking { + roomWithAdmins(setOf(user)) + ceremony() + keyState() + assertEquals(FoundingAdmins.Check.Missing(setOf(alice, bob)), FoundingAdmins.check(db, roomId)) + } + + @Test + fun `a ceremony from before its participant list falls back to its room's members`(): Unit = runBlocking { + roomWithAdmins(setOf(user)) + ceremony(participants = null) + db.participantDao().upsert(founders.map { Participant(participantPublicKey = it, chatRoomId = ceremonyRoomId, relayHint = null) }) + keyState() + assertEquals(FoundingAdmins.Check.Missing(setOf(alice, bob)), FoundingAdmins.check(db, roomId)) + } + + /** What the Welcome path writes: one line naming who is missing, and none when nobody is. */ + @Test + fun `the room says who it is missing, once, and only when someone is`(): Unit = runBlocking { + roomWithAdmins(setOf(user)) + ceremony() + keyState() + + FoundingAdmins.announceIfMissing(db, roomId, user) + val lines = db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage } + .filter { it.messageType == ChatMessage.TYPE_FOUNDING_ADMINS_MISSING } + val line = lines.single() + assertTrue(alice.take(8) in line.content && bob.take(8) in line.content, line.content) + assertTrue(ChatMessage.TYPE_FOUNDING_ADMINS_MISSING in ChatMessage.MEMBERSHIP_TYPES, "it would render as a chat bubble") + } + + @Test + fun `a room that names every founder says nothing`(): Unit = runBlocking { + roomWithAdmins(founders) + ceremony() + keyState() + + assertEquals(FoundingAdmins.Check.Matches, FoundingAdmins.announceIfMissing(db, roomId, user)) + assertTrue(db.chatMessageDao().getChatMessagesByChatRoomId(roomId).none { + it.chatMessage.messageType == ChatMessage.TYPE_FOUNDING_ADMINS_MISSING + }) + } + + /** + * The repair: one commit that adds the missing founders to the policy and + * leaves every admin already there in place. On the current profile, where + * the app governs a room; the relay's OK is played by hand. + */ + @Test + fun `an admin puts the missing founders back into the policy`(): Unit = runBlocking { + roomWithAdmins(setOf(user), MarmotProfile.CURRENT) + ceremony() + keyState() + val missing = assertIs(FoundingAdmins.check(db, roomId)).publicKeys + + chatRepository.addAdmins(db.chatRoomDao().findChatRoomById(roomId)!!, missing) + okTheLatestCommit() + + val room = db.chatRoomDao().findChatRoomById(roomId)!! + val group = assertNotNull(db.marmotEngine.groupFor(room.routingId)) + assertEquals(founders, group.currentAdminIdentities()) + assertEquals(FoundingAdmins.Check.Matches, FoundingAdmins.check(db, roomId)) + } + + private suspend fun okTheLatestCommit() { + val event = db.nostrEventDao().getMLSGroupEvents(since = Instant.fromEpochSeconds(0), limit = 20) + .filter { it.kind == GroupEvent.KIND } + .last { db.marmotCommitResultDao().getMarmotCommitRequestById(it.id) != null } + val request = assertNotNull(db.broadcastNostrEventRequestDao().getFirstBroadcastNostrEventRequestByNostrEventId(event.id)) + nostrRepository.broadcastProcessed(request, "published") + } +} From 11f2cb2babe110f3ff0182ad721c43e1d5bd5965 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:12:23 +0200 Subject: [PATCH 18/23] feat: the Shares section, with one approval (rotate-shares-single-approval, Phase 6) Removing the second approval took away the only abandon button a member who had taken part could reach: it lived on the approval row. A running rotation is now a card above the members -- the step it is on (dealing, storing, the group signing the new key state), who it waits on and since when, and Abandon, behind a confirmation, for any member taking part. It counts as running until the new generation's key state is signed, while that signature is open, because the old shares wait on it. A rotation that ended without completing says why until the next one. The taking-part row now says what it decides: who is left out and as what, and that nothing more will be asked. REFRESH_CONFIRM and its string are gone from the UI state. ShareRefreshManager.progress reads the step and who is missing from stored messages. Those are now stored once, on first arrival, in record and publishOwn: a redelivery rewrote the row and reset the stall clock. Tests: the row names the withheld; the withheld member sees the rotation run and cannot abandon it; the waiting-on names at dealing and storing; the signing step, which nobody abandons; an abandoned rotation says why. The stall-clock test backdates the messages first, and fails with the old store-every-time behaviour put back. jvmTest 1250/1250; m3Audit at its budgets; brand and wallet audits. Not seen on a device. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 15 +- .../compose/database/dao/ShareRefreshDao.kt | 3 + .../repository/DatabaseChatRepository.kt | 76 +++++++++- .../compose/managers/ShareRefreshManager.kt | 51 ++++++- .../ui/composable/ChatRoomDetailScreen.kt | 142 +++++++++++++++++- .../compose/ui/view/state/SharesSummary.kt | 36 ++++- .../managers/ShareRefreshRitualJvmTest.kt | 117 +++++++++++++++ 7 files changed, 421 insertions(+), 19 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index d1cf168a..b6c68bbc 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -131,7 +131,20 @@ Ask to be brought back Approve Take part in rotating the shares - Store your new share + Every member takes part. + Without %1$s. + %1$s until they are brought back + %1$s for good + Your device then sends its part, stores your new share and signs the group\'s new key state without asking again. + Rotating the shares + Members are sending their parts of the new shares. + Members are storing their new shares. + The group is signing its new key state. The old shares are deleted once it has. + If someone has stopped answering, any member taking part can abandon the rotation. Every share stays as it was, and the group can start again. + Abandon rotation + Abandon this rotation? + It ends for every member. Nobody gets a new share, and the group keeps signing with the shares it has. + The last rotation ended: %1$s Help bring a member back Sent to the group Share rotation proposed; every remaining member is asked to take part diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt index d699c000..bb4d1fee 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ShareRefreshDao.kt @@ -44,6 +44,9 @@ abstract class ShareRefreshDao { @Upsert abstract suspend fun upsert(message: ShareRefreshMessage) + @Query("SELECT * FROM ShareRefreshMessage WHERE sessionId = :sessionId") + abstract suspend fun getMessagesForSession(sessionId: String): List + @Query("SELECT * FROM ShareRefreshMessage WHERE sessionId = :sessionId AND kind = :kind") abstract suspend fun getMessagesByKind(sessionId: String, kind: Kind): List diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 0c99990f..cf1e27a4 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -1,5 +1,8 @@ package mobi.giza.compose.database.repository +import mobi.giza.compose.database.model.ShareRefreshSession +import mobi.giza.compose.nostr.frost.GroupKeyStateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event import co.touchlab.kermit.Logger import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -667,30 +670,89 @@ class DatabaseChatRepository( val shares = ShareGenerations.active(database, key) if (shares.roster.isEmpty()) return null val names = localChatRoom.localParticipants.associate { it.participant.participantPublicKey to it.profile?.humanReadableNameOrPubkey() } + fun nameOf(member: HexKey) = names[member] ?: member.take(8) val refreshes = database.shareRefreshDao().getSessionsForKey(key.id) val repairs = database.shareRepairDao().getSessionsForKey(key.id) val pending = refreshes.mapNotNull { session -> when (ShareRefreshManager.pendingApproval(database, session)) { - ShareRefreshApprovalStep.DEAL -> SharesSummary.PendingApproval(session.id, SharesSummary.PendingApproval.Kind.REFRESH_DEAL) - ShareRefreshApprovalStep.CONFIRM -> SharesSummary.PendingApproval(session.id, SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM) - null -> null + ShareRefreshApprovalStep.DEAL -> { + val roster = ShareGenerations.at(database, key, session.baseGeneration)?.roster.orEmpty() + .associate { it.participantId to it.memberPublicKey } + SharesSummary.PendingApproval( + sessionId = session.id, + kind = SharesSummary.PendingApproval.Kind.REFRESH_DEAL, + withheld = session.withheldStandings().map { (id, standing) -> + SharesSummary.Withheld(roster[id]?.let(::nameOf) ?: id.toString(), standing) + }, + ) + } + // Never pending since docs/rotate-shares-single-approval.md. + ShareRefreshApprovalStep.CONFIRM, null -> null } } + repairs.filter { ShareRepairManager.isAwaitingApproval(database, it) } .map { SharesSummary.PendingApproval(it.id, SharesSummary.PendingApproval.Kind.REPAIR_HELP) } - val running = refreshes.any { it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED } + val runningRefresh = refreshes.firstOrNull { it.stage != ShareRefreshStage.COMPLETE && it.stage != ShareRefreshStage.FAILED } + val running = runningRefresh?.let { session -> + // The approval row covers a member not yet asked; this is everything after it. + if (ShareRefreshManager.pendingApproval(database, session) != null) return@let null + ShareRefreshManager.progress(database, session)?.let { progress -> + SharesSummary.Running( + sessionId = session.id, + step = when (progress.step) { + ShareRefreshManager.Progress.Step.DEALING -> SharesSummary.Running.Step.DEALING + ShareRefreshManager.Progress.Step.STORING -> SharesSummary.Running.Step.STORING + }, + waitingOn = progress.waitingOn.map(::nameOf), + since = progress.since, + canAbandon = progress.canAbandon, + ) + } + } ?: signingNewGeneration(localChatRoom, key, shares.generation, refreshes) val mine = shares.roster.firstOrNull { it.memberPublicKey == me } val repairing = repairs.any { it.targetPublicKey == me && it.stage != ShareRepairStage.FAILED && it.stage != ShareRepairStage.COMPLETE } SharesSummary( generation = shares.generation, members = shares.roster.map { entry -> - SharesSummary.Member(entry.memberPublicKey, names[entry.memberPublicKey] ?: entry.memberPublicKey.take(8), entry.standing, entry.memberPublicKey == me) + SharesSummary.Member(entry.memberPublicKey, nameOf(entry.memberPublicKey), entry.standing, entry.memberPublicKey == me) }, pending = if (ExperimentalFeatures.shareRefresh) pending else emptyList(), - canRotate = ExperimentalFeatures.shareRefresh && shares.secretShare != null && !running, + canRotate = ExperimentalFeatures.shareRefresh && shares.secretShare != null && runningRefresh == null, canAskToBeRepaired = ExperimentalFeatures.shareRefresh && mine?.standing == ShareStanding.STALE && !repairing, + running = running.takeIf { ExperimentalFeatures.shareRefresh }, + lastFailure = refreshes.firstOrNull()?.takeIf { it.stage == ShareRefreshStage.FAILED }?.failureReason + ?.takeIf { ExperimentalFeatures.shareRefresh }, ) }.getOrNull() + /** + * The last step of a rotation: complete, and the group signing the new + * generation's key state, which the old shares wait on before they are + * deleted. Shown only while that signature is actually open, so a key state + * nobody is asking for does not read as one under way. + */ + private suspend fun signingNewGeneration( + localChatRoom: LocalChatRoom, + key: DkgSession, + generation: Int, + refreshes: List, + ): SharesSummary.Running? { + val refresh = refreshes.firstOrNull { it.stage == ShareRefreshStage.COMPLETE && it.baseGeneration + 1 == generation } ?: return null + val signed = GroupKeyStateManager.signedStateFor(database, localChatRoom.chatRoom.id) + if ((signed?.generation ?: 0) >= generation) return null + val signing = database.frostSigningSessionDao() + val open = signing.getOpenSessionsForKey(key.id).firstOrNull { session -> + (session.generation ?: 0) == generation && signing.getItems(session.id).singleOrNull() + ?.let { Event.fromJsonOrNull(it.unsignedEventJson)?.kind } == GroupKeyStateEvent.KIND + } ?: return null + return SharesSummary.Running( + sessionId = refresh.id, + step = SharesSummary.Running.Step.SIGNING, + waitingOn = emptyList(), + since = open.createdAt, + canAbandon = false, + ) + } + private fun failureOf(t: Throwable?): String? = t?.let { it.message ?: it::class.simpleName ?: "Unknown error" } private fun privateKeyOrNull(): Pair? { @@ -723,7 +785,7 @@ class DatabaseChatRepository( val (_, privateKey) = privateKeyOrNull() ?: return "This identity cannot sign" return failureOf(runCatching { when (approval.kind) { - SharesSummary.PendingApproval.Kind.REFRESH_DEAL, SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM -> + SharesSummary.PendingApproval.Kind.REFRESH_DEAL -> ShareRefreshManager.approve(database, localChatRoom, approval.sessionId, privateKey) SharesSummary.PendingApproval.Kind.REPAIR_HELP -> ShareRepairManager.approve(database, localChatRoom, approval.sessionId, privateKey) 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 61b551e2..84e1370a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ShareRefreshManager.kt @@ -426,10 +426,14 @@ object ShareRefreshManager { logger.w("Refresh ${session.id}: kind ${innerEvent.kind} from ${innerEvent.pubKey.take(8)}, who is not a recipient; ignoring") return true } + // Stored once, on first arrival: its time is when the rotation last + // moved, and a relay repeating itself is not progress ([progress]). val known = database.shareRefreshDao().getMessage(session.id, innerEvent.kind, innerEvent.pubKey) != null - database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, innerEvent.pubKey, innerEvent.kind, innerEvent.content)) - if (!known && innerEvent.pubKey != session.userPublicKey) { - announce(database, session, stepType(innerEvent.kind), stepLine(innerEvent.kind), innerEvent.pubKey) + if (!known) { + database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, innerEvent.pubKey, innerEvent.kind, innerEvent.content)) + if (innerEvent.pubKey != session.userPublicKey) { + announce(database, session, stepType(innerEvent.kind), stepLine(innerEvent.kind), innerEvent.pubKey) + } } } @@ -686,6 +690,43 @@ object ShareRefreshManager { return if (session.dealApprovedAt == null) ShareRefreshApprovalStep.DEAL else null } + /** + * Where a running refresh stands, as the Shares section shows it once its one + * approval is given: which step, who it waits on, since when, and whether + * this device may abandon it (docs/rotate-shares-single-approval.md, Phase 6). + * Null once it has finished. + * + * With nothing left to approve, this is the only place a member who took part + * can see a rotation stall, and the only way they can end it. + */ + suspend fun progress(database: GizaDatabase, session: ShareRefreshSession): Progress? { + if (session.stage == ShareRefreshStage.COMPLETE || session.stage == ShareRefreshStage.FAILED) return null + val key = database.dkgSessionDao().getSessionById(session.dkgSessionId) ?: return null + val base = ShareGenerations.at(database, key, session.baseGeneration) ?: return null + val memberOf = base.roster.associate { it.participantId to it.memberPublicKey } + val recipients = session.recipientIdList() + val messages = database.shareRefreshDao().getMessagesForSession(session.id) + fun missing(kind: Kind) = recipients + .filter { id -> messages.none { it.kind == kind && it.participantPublicKey == memberOf[id] } } + .mapNotNull { memberOf[it] } + val (step, waitingOn) = when { + session.coordinatorRound1 == null -> Progress.Step.DEALING to missing(ShareRefreshEvents.ROUND_1).ifEmpty { listOf(session.coordinatorPublicKey) } + else -> Progress.Step.STORING to missing(ShareRefreshEvents.ROUND_2).ifEmpty { listOf(session.coordinatorPublicKey) } + } + val myId = memberOf.entries.firstOrNull { it.value == session.userPublicKey }?.key + return Progress( + step = step, + waitingOn = waitingOn, + since = messages.maxOfOrNull { it.createdAt } ?: session.createdAt, + canAbandon = myId != null && myId in recipients, + ) + } + + /** See [progress]. */ + data class Progress(val step: Step, val waitingOn: List, val since: Instant, val canAbandon: Boolean) { + enum class Step { DEALING, STORING } + } + /** Approves the step this device's owner is being asked for, and moves on. */ suspend fun approve(database: GizaDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) { val session = database.shareRefreshDao().getSessionById(sessionId) ?: return @@ -736,9 +777,9 @@ object ShareRefreshManager { /** Queues this device's own message and records it, so the coordinator's own is in its sums. */ private suspend fun publishOwn(database: GizaDatabase, localChatRoom: LocalChatRoom, session: ShareRefreshSession, kind: Kind, content: String) { broadcast(database, localChatRoom, session, kind, content, ShareRefreshEvents.assembleTags(session.id)) - val known = ownMessage(database, session, kind) != null + if (ownMessage(database, session, kind) != null) return database.shareRefreshDao().upsert(ShareRefreshMessage(session.id, session.userPublicKey, kind, content)) - if (!known) announce(database, session, stepType(kind), stepLine(kind), session.userPublicKey) + announce(database, session, stepType(kind), stepLine(kind), session.userPublicKey) } /** One of this device's messages, as an inner event of the key's Marmot room. */ diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index abbc23f5..10b8e07b 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -104,7 +104,6 @@ import mobi.giza.compose.resources.leave_group import mobi.giza.compose.resources.remove_from_group import mobi.giza.compose.resources.shares_action_sent import mobi.giza.compose.resources.pending_repair_help -import mobi.giza.compose.resources.pending_rotation_confirm import mobi.giza.compose.resources.pending_rotation_deal import mobi.giza.compose.resources.abandon import mobi.giza.compose.resources.approve @@ -132,6 +131,23 @@ import mobi.giza.compose.resources.rotation_proposing_is_taking_part import mobi.giza.compose.resources.rotation_taking_part import mobi.giza.compose.resources.rotation_no_key import mobi.giza.compose.ui.view.state.RotationPreview +import androidx.compose.runtime.remember +import androidx.compose.material3.CardDefaults +import mobi.giza.compose.resources.waiting_on_s_since_s +import mobi.giza.compose.resources.rotation_ended +import mobi.giza.compose.resources.abandon_rotation_body +import mobi.giza.compose.resources.abandon_rotation_question +import mobi.giza.compose.resources.abandon_rotation +import mobi.giza.compose.resources.rotation_abandon_explainer +import mobi.giza.compose.resources.rotation_step_signing +import mobi.giza.compose.resources.rotation_step_storing +import mobi.giza.compose.resources.rotation_step_dealing +import mobi.giza.compose.resources.rotation_running +import mobi.giza.compose.resources.pending_rotation_commits +import mobi.giza.compose.resources.rotation_withheld_for_good +import mobi.giza.compose.resources.rotation_withheld_until_back +import mobi.giza.compose.resources.pending_rotation_without +import mobi.giza.compose.resources.pending_rotation_everyone import androidx.compose.material3.AlertDialog import mobi.giza.compose.resources.disband_group import mobi.giza.compose.resources.disband_group_explainer @@ -226,6 +242,33 @@ fun ChatRoomDetailScreen( ) } + var abandoningRotation by remember { mutableStateOf(null) } + abandoningRotation?.let { sessionId -> + AlertDialog( + onDismissRequest = { abandoningRotation = null }, + title = { Text(stringResource(Res.string.abandon_rotation_question)) }, + text = { Text(stringResource(Res.string.abandon_rotation_body)) }, + confirmButton = { + TextButton( + onClick = { + abandoningRotation = null + (chatRoomDetailViewModel.chatRoomDetailUIState as? ChatRoomDetailUIState.Loaded)?.let { loaded -> + chatRoomDetailViewModel.abandonRotation(loaded.localChatRoom, sessionId) { failure -> notify(failure ?: sharesActionSent) } + } + }, + colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error) + ) { + Text(stringResource(Res.string.abandon_rotation)) + } + }, + dismissButton = { + TextButton(onClick = { abandoningRotation = null }) { + Text(stringResource(Res.string.not_now)) + } + }, + ) + } + // The proposer's one approval: the rotation as it will be proposed, with // everyone it leaves out named (docs/rotate-shares-single-approval.md, Phase 4). chatRoomDetailViewModel.rotationProposal?.let { proposal -> @@ -431,6 +474,28 @@ fun ChatRoomDetailScreen( style = MaterialTheme.typography.bodyMedium ) } + // Above the members: with nothing left to approve, this is + // where a member who took part sees a rotation stall, and the + // only way out of one (docs/rotate-shares-single-approval.md). + shares.running?.let { running -> + item(key = "rotation-running") { + RotationRunningCard( + running = running, + onAbandon = { abandoningRotation = running.sessionId }, + ) + } + } + if (shares.running == null) { + shares.lastFailure?.let { reason -> + item(key = "rotation-ended") { + Text( + text = stringResource(Res.string.rotation_ended, reason), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } items(items = shares.members, key = { member -> "share-${member.publicKey}" }) { member -> ListItem( headlineContent = { @@ -456,12 +521,18 @@ fun ChatRoomDetailScreen( stringResource( when (approval.kind) { SharesSummary.PendingApproval.Kind.REFRESH_DEAL -> Res.string.pending_rotation_deal - SharesSummary.PendingApproval.Kind.REFRESH_CONFIRM -> Res.string.pending_rotation_confirm SharesSummary.PendingApproval.Kind.REPAIR_HELP -> Res.string.pending_repair_help } ) ) }, + // Taking part is agreeing to who is left out, and it is the + // only thing this rotation will ask: so the row says both. + supportingContent = if (approval.kind == SharesSummary.PendingApproval.Kind.REFRESH_DEAL) { + { RotationTakingPart(approval.withheld) } + } else { + null + }, trailingContent = { Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { if (approval.kind != SharesSummary.PendingApproval.Kind.REPAIR_HELP) { @@ -1394,3 +1465,70 @@ private fun RotationLeftOut(preview: RotationPreview) { Text(stringResource(Res.string.rotation_left_out_for_good, preview.forGood.joinToString(", "))) } } + +/** What taking part in a rotation agrees to: who it leaves out, and that nothing more will be asked. */ +@Composable +private fun RotationTakingPart(withheld: List) { + val leftOut = withheld.map { entry -> + stringResource( + if (entry.standing == ShareStanding.RETIRED) Res.string.rotation_withheld_for_good else Res.string.rotation_withheld_until_back, + entry.name + ) + } + Column { + Text( + if (leftOut.isEmpty()) stringResource(Res.string.pending_rotation_everyone) + else stringResource(Res.string.pending_rotation_without, leftOut.joinToString(", ")) + ) + Text(stringResource(Res.string.pending_rotation_commits)) + } +} + +/** + * A rotation past its one approval: the step it is on, who it waits on and since + * when, and abandon for a member taking part. Shown whether or not it has + * stalled -- unlike a ceremony, a rotation has no screen of its own to show it. + */ +@Composable +private fun RotationRunningCard(running: SharesSummary.Running, onAbandon: () -> Unit) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.secondaryContainer, + contentColor = MaterialTheme.colorScheme.onSecondaryContainer + ) + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + Text(stringResource(Res.string.rotation_running), style = MaterialTheme.typography.titleSmall) + Text( + stringResource( + when (running.step) { + SharesSummary.Running.Step.DEALING -> Res.string.rotation_step_dealing + SharesSummary.Running.Step.STORING -> Res.string.rotation_step_storing + SharesSummary.Running.Step.SIGNING -> Res.string.rotation_step_signing + } + ), + style = MaterialTheme.typography.bodyMedium + ) + if (running.waitingOn.isNotEmpty()) { + Text( + stringResource(Res.string.waiting_on_s_since_s, running.waitingOn.joinToString(", "), running.since.toFormattedTimeAndDateString()), + style = MaterialTheme.typography.bodyMedium + ) + } + if (running.canAbandon) { + Text(stringResource(Res.string.rotation_abandon_explainer), style = MaterialTheme.typography.bodyMedium) + TextButton( + onClick = onAbandon, + modifier = Modifier.align(Alignment.End), + colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error) + ) { + Text(stringResource(Res.string.abandon_rotation)) + } + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt index 720377f0..af7dbc63 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/SharesSummary.kt @@ -1,12 +1,13 @@ package mobi.giza.compose.ui.view.state import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlin.time.Instant import mobi.giza.compose.database.model.types.ShareStanding /** * A room's key, as the Shares section shows it (docs/frost-share-refresh.md, * Phase 11): the generation the group signs with, who holds what, what this - * device is being asked, and what it may start. + * device is being asked, what is running, and what it may start. */ data class SharesSummary( val generation: Int, @@ -16,11 +17,38 @@ data class SharesSummary( val canRotate: Boolean, /** This device's own id is stale and nothing is bringing it back yet. */ val canAskToBeRepaired: Boolean, + /** A rotation under way, from its one approval until the group signs the new generation. */ + val running: Running? = null, + /** Why the newest rotation ended, when it ended without completing and nothing has run since. */ + val lastFailure: String? = null, ) { data class Member(val publicKey: HexKey, val name: String, val standing: ShareStanding, val isSelf: Boolean) - /** Something this device's owner is being asked, and the session it is for. */ - data class PendingApproval(val sessionId: String, val kind: Kind) { - enum class Kind { REFRESH_DEAL, REFRESH_CONFIRM, REPAIR_HELP } + /** + * Something this device's owner is being asked, and the session it is for. + * A rotation's carries who it leaves out, because agreeing to that is what + * taking part is (docs/rotate-shares-single-approval.md, Phase 6). + */ + data class PendingApproval(val sessionId: String, val kind: Kind, val withheld: List = emptyList()) { + /** A rotation asks one thing, to take part; storing the new share stopped being a question. */ + enum class Kind { REFRESH_DEAL, REPAIR_HELP } + } + + data class Withheld(val name: String, val standing: ShareStanding) + + /** + * A rotation running past its one approval. With nothing left to approve, + * this is the only place a member who took part sees it stall, and the only + * way out of one. + */ + data class Running( + val sessionId: String, + val step: Step, + val waitingOn: List, + val since: Instant, + /** This device is a recipient of a rotation not yet certified, so it may end it for everyone. */ + val canAbandon: Boolean, + ) { + enum class Step { DEALING, STORING, SIGNING } } } 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 fbe26bbd..9f504526 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ShareRefreshRitualJvmTest.kt @@ -657,6 +657,123 @@ class ShareRefreshRitualJvmTest { assertEquals(0, FrostSigningManager.resumeVouched(member.db, member.publicKey), "once") } + // ---- Phase 6 of rotate-shares-single-approval: the Shares section ------------------------------------------------ + + private suspend fun summaryOn(device: Device): mobi.giza.compose.ui.view.state.SharesSummary { + val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined + kotlinx.coroutines.Job()) + return try { + assertNotNull(mobi.giza.compose.database.repository.DatabaseChatRepository(device.db, scope).sharesSummary(device.room), "device ${device.index}") + } finally { + scope.coroutineContext[kotlinx.coroutines.Job]?.cancel() + } + } + + private fun nameOf(device: Device) = device.publicKey.take(8) + + @Test + fun `a rotation asks one thing, to take part`() { + assertEquals( + listOf(mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.REFRESH_DEAL, mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.REPAIR_HELP), + mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.entries.toList(), + ) + } + + /** Taking part is agreeing to who is left out, so the row that asks it names them. */ + @Test + fun `the taking-part row names who is left out, and the withheld member sees the rotation run`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + propose(all[0], mapOf(group.idOf[2] to ShareStanding.STALE)) + pump(all) + + val asked = summaryOn(all[1]) + val row = asked.pending.single() + assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.PendingApproval.Kind.REFRESH_DEAL, row.kind) + assertEquals(listOf(mobi.giza.compose.ui.view.state.SharesSummary.Withheld(nameOf(all[2]), ShareStanding.STALE)), row.withheld) + assertNull(asked.running, "the row covers a member not yet asked") + + val withheld = summaryOn(all[2]) + assertTrue(withheld.pending.isEmpty()) + val running = assertNotNull(withheld.running) + assertEquals(listOf(nameOf(all[1])), running.waitingOn) + assertTrue(!running.canAbandon, "only a member taking part may end it") + } + + /** + * Once a member has taken part there is nothing left to approve, so the + * running rotation is what they see: the step, who it waits on, and abandon. + */ + @Test + fun `a running rotation names who it waits on at each step`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val (alice, bob, carol) = all + val refresh = propose(alice) + pump(all) + ShareRefreshManager.approve(bob.db, bob.room, refresh.id, bob.privateKey) + pump(all) + + val dealing = assertNotNull(summaryOn(bob).running) + assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.Running.Step.DEALING, dealing.step) + assertEquals(listOf(nameOf(carol)), dealing.waitingOn) + assertTrue(dealing.canAbandon, "a member who took part can still end it") + assertTrue(summaryOn(bob).pending.isEmpty()) + assertTrue(!summaryOn(bob).canRotate) + + // Carol takes part; her confirmation is slow to arrive. + ShareRefreshManager.approve(carol.db, carol.room, refresh.id, carol.privateKey) + pump(all, hold = { it.kind == ShareRefreshEvents.ROUND_2 && it.publicKey == carol.publicKey }) + val storing = assertNotNull(summaryOn(bob).running) + assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.Running.Step.STORING, storing.step) + assertEquals(listOf(nameOf(carol)), storing.waitingOn) + + // A relay repeating itself is not progress. Dated a day back first, so a + // redelivery that rewrote a row would show, whatever the clock's precision. + val dao = bob.db.shareRefreshDao() + val dayAgo = kotlin.time.Clock.System.now() - kotlin.time.Duration.parse("1d") + dao.getMessagesForSession(refresh.id).forEach { dao.upsert(it.copy(createdAt = dayAgo, updatedAt = dayAgo, savedAt = dayAgo)) } + val since = assertNotNull(summaryOn(bob).running).since + assertTrue(kotlin.time.Clock.System.now() - since > kotlin.time.Duration.parse("23h")) + bob.received.clear() + pump(all, hold = { it.kind == ShareRefreshEvents.ROUND_2 && it.publicKey == carol.publicKey }) + assertEquals(since, summaryOn(bob).running?.since, "a redelivered message moved the stall clock") + } + + @Test + fun `the last step is the group signing the new key state, which nobody abandons`() = runBlocking { + 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) }) + + val signing = assertNotNull(summaryOn(all[0]).running, "the coordinator's own key state is open") + assertEquals(mobi.giza.compose.ui.view.state.SharesSummary.Running.Step.SIGNING, signing.step) + assertTrue(!signing.canAbandon) + + pump(all) + all.forEach { assertNull(summaryOn(it).running, "device ${it.index}: nothing is running once it is signed") } + } + + @Test + fun `an abandoned rotation says why until the next one`() = runBlocking { + val group = Group(3, 2) + val all = devicesFor(group) + val refresh = propose(all[0]) + pump(all) + ShareRefreshManager.approve(all[1].db, all[1].room, refresh.id, all[1].privateKey) + ShareRefreshManager.abandon(all[1].db, all[1].room, refresh.id) + pump(all) + + all.forEach { device -> + val summary = summaryOn(device) + assertNull(summary.running) + assertTrue(summary.lastFailure!!.contains("Abandoned"), summary.lastFailure) + assertTrue(summary.canRotate) + } + } + @Test fun `a withheld member ends with the new table and no share, and declines to sign`() = runBlocking { val group = Group(3, 2) From 99261876bffdbe7f11ace9dce6ff6b938c5451dc Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:13:55 +0200 Subject: [PATCH 19/23] docs: taking part is the only approval, as built (rotate-shares-single-approval, Phase 7) The plan gets a Built header and a table of where the build chose differently: the proposer was asked twice not three times; two rotations opened at once never reach the write-once rule; the stall-clock test had to backdate its messages to catch anything; one full run died on a SQLite SIGSEGV unrelated to this change. frost-share-refresh.md's gate table shrinks to one row with the history of CONFIRM, its key-state step names the rule that now signs it, and README says both notes are built. automatic-key-ceremony.md points here for the second automated key state. Not done: the emulator session. Nothing here has run on a device. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 4 ++-- docs/automatic-key-ceremony.md | 4 +++- docs/frost-share-refresh.md | 22 +++++++++++++++------- docs/rotate-shares-single-approval.md | 25 ++++++++++++++++++++++++- 4 files changed, 44 insertions(+), 11 deletions(-) diff --git a/docs/README.md b/docs/README.md index 631ce39d..b80c1f3c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -19,8 +19,8 @@ the [retired](./retired/) notes now. | [ceremony-creation.md](./ceremony-creation.md) | one place to start a key ceremony — how joining a subgroup's ceremony opened a second one for the parent room, the screen that showed a ceremony and offered to start one in the same button, and the removal of the nip30303 documents, whose kinds collided with the ceremony's, leaving the member chronicle with nothing to carry and nothing to say | | [frost-batch-signing.md](./frost-batch-signing.md) | signing several events in one ceremony — why one nonce can never cover two messages, and the phased schema, wire and UI work that follows from it | | [frost-session-resend.md](./frost-session-resend.md) | asking the members who never got a signing proposal to look again — why a proposer can repeat only what it wrote, why a member's availability signal needs no repeating, and the one half that has to come from the silent member's own device | -| [frost-share-refresh.md](./frost-share-refresh.md) | giving every member a new share of the same group key, phased and not built — why enrollment cannot rotate a share, the zero-sum refresh that can, what a rotation protects against and the two things it never can, and re-enrollment as the repair that brings back the members a refresh left out | -| [rotate-shares-single-approval.md](./rotate-shares-single-approval.md) | taking part is the only approval: a phased plan, not built, that makes a share rotation run by itself after a member agrees to take part. Covers the three asks a recipient gets today, why storing the new share was never a decision, the one key state for a new generation a device can sign without asking, and the abandon a member loses once nothing is left to approve | +| [frost-share-refresh.md](./frost-share-refresh.md) | giving every member a new share of the same group key, phased and built behind a flag that is off in release — why enrollment cannot rotate a share, the zero-sum refresh that can, what a rotation protects against and the two things it never can, and re-enrollment as the repair that brings back the members a refresh left out | +| [rotate-shares-single-approval.md](./rotate-shares-single-approval.md) | taking part is the only approval: a phased plan, built but for its device session, that makes a share rotation run by itself after a member agrees to take part. Covers the three asks a recipient gets today, why storing the new share was never a decision, the one key state for a new generation a device can sign without asking, and the abandon a member loses once nothing is left to approve | | [marmot-membership.md](./marmot-membership.md) | how members join an MLS group, and the epoch race that makes a missing member look like a successful invite | | [member-chronicle.md](./member-chronicle.md) | handing a member added after the work was done the group's signed record — why the events are not on the wire at all, and why the room's id is enough to verify them | | [marmot-direct-messages.md](./marmot-direct-messages.md) | a one-to-one message inside a group as a stock NIP-59 gift wrap — what its MIP-03 carve-out costs, why the sender cannot read their own, and the one query that would broadcast it | diff --git a/docs/automatic-key-ceremony.md b/docs/automatic-key-ceremony.md index de05aa02..337c884a 100644 --- a/docs/automatic-key-ceremony.md +++ b/docs/automatic-key-ceremony.md @@ -514,7 +514,9 @@ decline. It means the device cannot vouch for the statement, so a person has to. waits for that member's taps. - **It does not automate signatures other than the key state.** A post, a profile, a certificate for some other group, or anything in a batch is still - asked about, exactly as today. + asked about, exactly as today. A share rotation's key state for its new + generation was automated later, by the same rule, in + [rotate-shares-single-approval.md](./rotate-shares-single-approval.md). ## Order and size diff --git a/docs/frost-share-refresh.md b/docs/frost-share-refresh.md index 2ba0b94a..b86389fb 100644 --- a/docs/frost-share-refresh.md +++ b/docs/frost-share-refresh.md @@ -26,6 +26,7 @@ ceremony they describe and the rule that a room's id *is* the key it signs with. | 11 | `99229090` | `compileDebugKotlinAndroid`; the M3 audit at its budgets. **Not seen on a device or a desktop window** | | 12 | `4949f0fe` | `ShareRefreshRitualJvmTest`: three refreshes in a row, then the recovery walk from the generation-0 share lands on every device's live share, each generation checked against its table. `jvmTest` 1200/1200 | | 13 | `99229090` | `ShareRefreshRitualJvmTest`: with the flag off, the recipients decline a rotation out loud and it fails; proposing one throws. Android, desktop and iOS device checks not done | +| after | rotate-shares-single-approval.md | taking part is a rotation's only approval: `CONFIRM` is gone, the proposer's dialog is its approval, the new generation's key state signs itself, and a running rotation can be abandoned from the Shares section. See that note | | 5 | `4040ae74` | `SecureDeleteJvmTest` (5, two of them controls that fail without the fix); `jvmTest` 1176/1176; `compileDebugKotlinAndroid`, `processDebugResources` | | 6 | `fce51e20` | `ShareGenerationsJvmTest` (7: a real 2-of-3 signature with hand-refreshed shares verifying as the unchanged room, a decline from a device without the generation, a withheld member who is not a signer); every existing signing test unedited; `jvmTest` 1183/1183; `compileDebugKotlinAndroid`; the M3, brand and wallet audits | @@ -479,16 +480,21 @@ host keys, so a room-wide message is fine here, which it is **not** for repair ( is the one way the group splits.** - an open ChillDKG or refresh for the same key. -**Approval gates.** Two, mirroring the ceremony's, with `pendingApproval` mirroring `advance` -exactly: +**Approval gates.** One, with `pendingApproval` mirroring `advance` exactly: | step | publishes | why it is its own decision | |---|---|---| | `DEAL` | round 1 | joins the refresh and agrees to the withheld list. Withholding someone is a decision about them, so every recipient makes it, not only the proposer | -| `CONFIRM` | CertEq | commits to the new generation. This is what stops a coordinator substituting a table the recipients never dealt | -The proposer is auto-approved for nothing. Proposing a refresh is not agreeing to withhold -whomever the form defaulted to. +The proposer makes it by proposing, from a dialog that names everyone the proposal leaves out. + +*As first built there were two gates.* `CONFIRM` stood before CertEq, on the reasoning that it +"stops a coordinator substituting a table the recipients never dealt". It never did: that is +`participantStep2`'s check, which runs before any prompt could appear and fails the refresh out +loud, and the one confirmation per generation is the write-once `ShareRefreshConfirmation`. Both +hold whoever is looking. [rotate-shares-single-approval.md](./rotate-shares-single-approval.md) +removed the gate; `ShareRefreshApprovalStep.CONFIRM` and `confirmApprovedAt` remain, unread, so +rows written before still decode. The proposer, also asked at first, is not asked either. **Transcript.** System lines in the room, as the ceremony writes them, idempotent by reading the row before writing: @@ -524,7 +530,9 @@ What a device does with a certificate, and when the old share goes. - `frost_retired` per retired id. It is signed under `g+1`, which makes it the first signature the new shares make: the proof - D6 waits for. + D6 waits for. A recipient's device signs it without asking when it is exactly the state the + rotation it completed implies (`GroupKeyStateManager.vouchesForGeneration`, + [rotate-shares-single-approval.md](./rotate-shares-single-approval.md), Phase 5). 3. **`GroupKeyStateManager` changes, and the comment in `GroupKeyStateEvent.kt` (L84–87) gets answered.** - The comment expects that rotation would break `verifies()`. It does not: the *key* is @@ -649,7 +657,7 @@ Under CLAUDE.md's rules: Standing gets a text label, not only an icon, so the icon gets `Decorative`. - **The refresh screen.** A progress ladder that names who it waits on, like the ceremony's, - with the two approvals. + with its one approval (two as first built; see [rotate-shares-single-approval.md](./rotate-shares-single-approval.md)). - The `DEAL` prompt lists who is withheld, and as what. - The `CONFIRM` prompt is the ceremony's CertEq prompt in different words. - **The copy has to tell the truth from [what it protects against](#what-a-refresh-protects-against-and-what-it-cannot).** diff --git a/docs/rotate-shares-single-approval.md b/docs/rotate-shares-single-approval.md index 22807395..19244aa2 100644 --- a/docs/rotate-shares-single-approval.md +++ b/docs/rotate-shares-single-approval.md @@ -12,7 +12,30 @@ made to the ceremony, applied to [frost-share-refresh.md](./frost-share-refresh. Read both first. This plan follows the first one's shape, because the reasoning is the same and so are most of the traps. -**Not built.** Written against `fc437d05` on 2026-11-20. +**Built**, one commit per phase on `claude/rotate-shares-single-approval-338a7d` +(`18f426ca` to the commit that adds this header), against `fc437d05`, on +2026-11-20. Each recipient is now asked once and the proposer not at all: +`ShareRefreshRitualJvmTest`'s `answerEverything` counts the asks, and they went +from three per recipient to one. jvmTest 1250/1250, `compileDebugKotlinAndroid`, `m3Audit` at its budgets, +the brand and wallet audits. The phases are kept as written because they are +the reasoning. Where the build chose differently: + +| what the plan said | what it turned out to be | +|---|---| +| Phase 1: three asks per recipient, the proposer included | two for the proposer. Its device proposes the key state, and a proposer's signature is its proposal. The pinned test said so, and Phase 4 took the proposer to none | +| Phase 2: the fork test, two proposals with an overlapping recipient who confirms one | two proposals opened at once never reach the write-once rule. Each device refuses the second on arrival ("another refresh of this key is still running here"), and the refusals end both. The test asserts what matters, that the group never splits. The write-once rule keeps its own test, against the DAO, which never involved the gate | +| Phase 2: a tampered sum fails on every honest recipient | it fails on every device, the coordinator included, through the FAILURE an honest recipient broadcasts. The coordinator used its own untampered sum and had confirmed | +| Phase 3: rename `resumeRunningCeremonies` or widen its KDoc | widened. It now also runs `ShareRefreshManager.resumeRunning` and, from Phase 5, `FrostSigningManager.resumeVouched` | +| Phase 4: `rotationPreview` runs the same selection as `proposeRefresh` | both call one private `ShareRefreshManager.plan`, which also carries the refusals that were `require`s. Those now throw `IllegalStateException` rather than `IllegalArgumentException`. The removal dialog names only the stale members, since its title already names the removed one | +| Phase 5: re-check vouching in `resumeAt` and the sweep | one `approveIfVouched` behind all three: arrival, `resumeAt`, and `resumeVouched`. The sweep answers any key state the device can vouch for, a ceremony's included, through a new `getOpenUnansweredSessionsFor` | +| Phase 5: path and parent match the room's signed state | the birth certificate is compared by event id, not JSON. No test has a signed generation-0 state to differ from, since the ritual harness's devices hold none, so the test breaks the path against rule 4 instead | +| Phase 6: the running card shows who it waits on and since when, with an inline abandon past a day | always shown, with no threshold. Unlike a ceremony, a rotation has no screen of its own, so the card is the only place it can be seen at all. Abandon got a confirmation dialog, since the Shares section had none | +| Phase 6: running until the key state is signed | while that signature is *open*. A key state nobody is asking for would otherwise read as one under way, forever | +| Phase 6: fix `record` the way the ceremony's was | `record` and `publishOwn` both. The first version of the test passed without the fix: timestamps are kept to the second, and a redelivery in the same second looks identical. The test now backdates the messages a day first, and fails with the old behaviour put back | +| (not in the plan) | one full `jvmTest` run died on a SIGSEGV in SQLite's native code (`sqlite3DbMallocRawNN`), inside a background `MarmotKeyPackageDao.upsert`. That looks like an existing test leaving a write running against an in-memory database it has closed. The rerun was clean. Not investigated | + +**Not done:** the emulator session in Phase 7. Nothing here has run on a device: +not the dialog, not the card, not the upgrade in place. The headline: **a device asks its owner only for decisions it cannot make on its own.** Taking part is one of those decisions, because it agrees to the From 1dc94ad423692da8d3f8d3d8d1ba2f9bc1e1d04a Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:14:19 +0200 Subject: [PATCH 20/23] feat: a founding invite that never went out is finished (robust-group-admins, Phase 4) MarmotGroupCreation.finishFoundingInvite invites the founders a room's founding invite never reached, in one commit, every key package first as at creation. It acts only on a room still at epoch 0: the founding invite is the commit that ends epoch 0, and leaving is a commit too, so a founder without a leaf there is one nobody ever invited -- never one who left. CeremonyFollowThrough takes it as step 4 once the room exists, on the coordinator's device; the repository exposes it by room for the detail screen, with the set it would invite. Also fixes what Phase 0 found. MarmotGroupCreation invited the founders through a room read before its routing id was recorded, so on the current profile the engine adopted a second copy of the group under the room id, and the copy at the real address still held only its creator: every later invite took the founding path, with no commit and nobody already in the room told. It now reads the room again first. RobustGroupAdminsJvmTest: a room left without its invite is finished and every founder joins as an admin, on both profiles; a room past its founding invites nobody; a later member on the current profile now gets a real commit. CeremonyFollowThroughJvmTest: step 4's outcomes. jvmTest 1249/1249, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../repository/DatabaseChatRepository.kt | 27 ++++ .../compose/managers/CeremonyFollowThrough.kt | 29 +++- .../giza/compose/managers/FoundingAdmins.kt | 13 ++ .../compose/managers/MarmotGroupCreation.kt | 102 ++++++++++++- .../giza/compose/repository/ChatRepository.kt | 21 +++ .../managers/CeremonyFollowThroughJvmTest.kt | 25 ++++ .../managers/RobustGroupAdminsJvmTest.kt | 135 +++++++++++++++++- 7 files changed, 340 insertions(+), 12 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index e713b2bb..75987d93 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -87,6 +87,33 @@ class DatabaseChatRepository( parentChatRoomId = parentChatRoomId, ) + override suspend fun finishFoundingInvite( + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + ): MarmotGroupCreation.FoundingInvite = MarmotGroupCreation.finishFoundingInvite( + database = database, + chatRepository = this, + ceremony = ceremony, + ceremonyRoom = ceremonyRoom, + ) + + override suspend fun finishFoundingInvite(chatRoomId: String): MarmotGroupCreation.FoundingInvite { + val (ceremony, ceremonyRoom) = FoundingAdmins.ceremonyOf(database, chatRoomId) + ?: return MarmotGroupCreation.FoundingInvite.NothingToDo + return finishFoundingInvite(ceremony, ceremonyRoom) + } + + override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = try { + FoundingAdmins.ceremonyOf(database, localChatRoom.chatRoom.id) + ?.let { (ceremony, ceremonyRoom) -> + MarmotGroupCreation.uninvitedFounders(database, localChatRoom, ceremony, ceremonyRoom) + } + .orEmpty() + } catch (e: Throwable) { + logger.e("Error reading who ${localChatRoom.chatRoom.id}'s founding invite missed", e) + emptySet() + } + override suspend fun followThroughCeremonies(keyPair: KeyPair) = CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt index 0f0fb013..430c9e06 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/CeremonyFollowThrough.kt @@ -30,7 +30,9 @@ import mobi.giza.compose.repository.ChatRepository * 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. + * 3. the room is created and the members welcomed into it; + * 4. a room whose founding invite never went out has it finished + * (docs/robust-group-admins.md, Phase 4). * * 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 @@ -62,7 +64,7 @@ object CeremonyFollowThrough { /** 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. */ + /** Not this device's to do, or nothing left: not the coordinator, not finished, or the room exists with its founders. */ data object NothingToDo : Step /** Waiting on signatures somebody else gives. */ @@ -74,6 +76,12 @@ object CeremonyFollowThrough { /** The room exists now. */ data class Created(val chatRoomId: String) : Step + /** + * The room existed without its founders, whose invite never went out, and + * now they have been invited; [notAdded] could not be. + */ + data class Invited(val chatRoomId: String, val notAdded: List) : Step + /** The room cannot be created until these members' devices publish a key package. */ data class BlockedOn(val missing: List) : Step @@ -166,11 +174,24 @@ object CeremonyFollowThrough { 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") + // 4. The room exists: finish its founding invite if it never went out. + // Only a room still at epoch 0 has anything to finish, so nobody who + // left is ever invited back -- see `MarmotGroupCreation.uninvitedFounders`. + if (database.chatRoomDao().findChatRoomById(roomId) != null) { + return@withLock when (val invite = chatRepository.finishFoundingInvite(current, ceremonyRoom)) { + MarmotGroupCreation.FoundingInvite.NothingToDo -> Step.NothingToDo + is MarmotGroupCreation.FoundingInvite.Sent -> { + logger.i("Ceremony ${current.id}: invited ${invite.invited.size} founder(s) to $roomId") + Step.Invited(roomId, invite.notAdded) + } + is MarmotGroupCreation.FoundingInvite.BlockedOn -> Step.BlockedOn(invite.missing) + is MarmotGroupCreation.FoundingInvite.Failed -> Step.Stuck(invite.reason) + } + } + val participants = ChillDkgRitualManager.participantsOf(current, ceremonyRoom) val parent = current.parentChatRoomId diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt index bd5b78b6..b0b5c836 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/FoundingAdmins.kt @@ -6,6 +6,7 @@ import com.vitorpamplona.quartz.nip01Core.core.HexKey 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.intermdiate.LocalChatRoom import mobi.giza.compose.nostr.subgroup.SubgroupBirthCertificateEvent /** @@ -94,6 +95,18 @@ object FoundingAdmins { return check } + /** + * The ceremony that made [chatRoomId]'s key, as this device holds it, and the + * room it ran in -- or null where this device holds no key state for the room, + * no record of that ceremony, or no longer the room it ran in. + */ + suspend fun ceremonyOf(database: GizaDatabase, chatRoomId: String): Pair? { + val state = database.groupKeyStateDao().getByChatRoomId(chatRoomId) ?: return null + val ceremony = database.dkgSessionDao().getSessionById(state.dkgSessionId) ?: return null + val ceremonyRoom = database.chatRoomDao().findChatRoomById(ceremony.chatRoomId) ?: return null + return ceremony to ceremonyRoom + } + /** The ceremony's participants, or null when this device holds no record of them. */ private suspend fun foundersOf(database: GizaDatabase, ceremony: DkgSession?): Set? { ceremony ?: return null diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt index e3623067..2f8c4570 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/MarmotGroupCreation.kt @@ -4,6 +4,7 @@ import co.touchlab.kermit.Logger import mobi.giza.compose.nostr.MarmotProfile import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.mls.group.MlsGroup import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope @@ -11,6 +12,7 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import kotlinx.coroutines.withTimeoutOrNull import mobi.giza.compose.database.GizaDatabase +import mobi.giza.compose.database.model.Participant import mobi.giza.compose.database.model.DkgSession import mobi.giza.compose.database.model.MarmotKeyPackage import mobi.giza.compose.database.model.intermdiate.LocalChatRoom @@ -177,8 +179,16 @@ object MarmotGroupCreation { // there is a row to file it against. GroupKeyStateManager.adopt(database, groupId) + // Read again now the routing is on file. The row above predates it, and a + // room with no routing row is addressed by its own id -- so on the current + // profile the invite went to a second copy of the group the engine adopted + // under the room id, and the copy at the real address still held only its + // creator. Every later invite then took the founding path: no commit, and + // nobody already in the room told. docs/robust-group-admins.md, Phase 4. + val routedRoom = chatRepository.getChatRoomByIdentifier(groupId) ?: localChatRoom + val notAdded = runCatching { - chatRepository.addMembers(localChatRoom = localChatRoom, peers = addable) + chatRepository.addMembers(localChatRoom = routedRoom, peers = addable) }.onFailure { logger.e("Failed to add members to $groupId", it) }.getOrElse { addable.map { (publicKey, _) -> publicKey } } @@ -257,6 +267,96 @@ object MarmotGroupCreation { ) } + /** What [finishFoundingInvite] did. */ + sealed interface FoundingInvite { + /** Every founding member holds a leaf, or the room is past its founding. */ + data object NothingToDo : FoundingInvite + + /** The founders who were missing were invited; [notAdded] could not be. */ + data class Sent(val chatRoomId: String, val invited: List, val notAdded: List) : FoundingInvite + + /** Some founders have no published key package, so nobody was invited. */ + data class BlockedOn(val missing: List) : FoundingInvite + + data class Failed(val reason: String) : FoundingInvite + } + + /** + * The founding members of [room] its founding invite never reached: listed as + * admins, holding no leaf, in a room nothing has been committed to since it was + * made. + * + * Only at epoch 0. A room is created at epoch 0 and its founding invite is the + * commit that leaves it -- so a room still there is one whose invite failed + * outright, and nobody in it has left or been removed, because either would + * have been a commit. Past epoch 0 a founder without a leaf might be one who + * left, and inviting them back is not this function's to decide + * (docs/robust-group-admins.md, Out of scope). + * + * A device holds a room at epoch 0 only if it made it: everybody else's copy + * comes from a Welcome, which is already past the founding commit. + */ + suspend fun uninvitedFounders( + database: GizaDatabase, + room: LocalChatRoom, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + ): Set { + val group = liveGroupOf(database, room) ?: return emptySet() + if (group.epoch != 0L) return emptySet() + + val holdingLeaves = Participant.fromMlsGroup(group, room.chatRoom.id, null).map { it.participantPublicKey }.toSet() + return ChillDkgRitualManager.participantsOf(ceremony, ceremonyRoom) - holdingLeaves + } + + /** + * Invites the founding members [room]'s founding invite never reached -- see + * [uninvitedFounders] -- in one commit, as [create] would have. + * + * Every key package first, as at creation: a founder who cannot be invited yet + * holds the rest back rather than leaving the room to a second, partial + * founding. docs/robust-group-admins.md, Phase 4. + */ + suspend fun finishFoundingInvite( + database: GizaDatabase, + chatRepository: ChatRepository, + ceremony: DkgSession, + ceremonyRoom: LocalChatRoom, + keyPackageLookupTimeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT, + ): FoundingInvite { + val thresholdPublicKey = ceremony.thresholdPublicKey ?: return FoundingInvite.NothingToDo + val groupId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + val room = chatRepository.getChatRoomByIdentifier(groupId) ?: return FoundingInvite.NothingToDo + + val uninvited = uninvitedFounders(database, room, ceremony, ceremonyRoom) + if (uninvited.isEmpty()) return FoundingInvite.NothingToDo + + val keyPackages = keyPackagesFor(chatRepository, uninvited.toList(), keyPackageLookupTimeout, room.chatRoom.marmotProfile()) + val missing = keyPackages.filter { it.second == null }.map { it.first } + if (missing.isNotEmpty()) { + logger.w("Not finishing $groupId's founding invite: no key package for $missing") + return FoundingInvite.BlockedOn(missing) + } + val addable = keyPackages.mapNotNull { (publicKey, keyPackage) -> keyPackage?.let { publicKey to it } } + + val notAdded = runCatching { + chatRepository.addMembers(localChatRoom = room, peers = addable) + }.onFailure { + logger.e("Failed to finish $groupId's founding invite", it) + }.getOrElse { return FoundingInvite.Failed(it.message ?: "Couldn't invite them. Please try again.") } + + flagAdmins(database, groupId) + logger.i("Finished $groupId's founding invite: ${addable.size - notAdded.size} invited, ${notAdded.size} not") + return FoundingInvite.Sent(groupId, addable.map { it.first }, notAdded) + } + + /** The room's live group: the row's on the legacy profile, the engine's on the current one. */ + private suspend fun liveGroupOf(database: GizaDatabase, room: LocalChatRoom): MlsGroup? = + when (room.chatRoom.marmotProfile()) { + MarmotProfile.LEGACY -> room.chatRoom.toMlsGroup() + MarmotProfile.CURRENT -> database.marmotEngine.groupFor(room.routingId) + } + /** * Writes `adminAt` on the rows of the members this room was created with as * admins. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index bdb80a06..20d1eee1 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -224,6 +224,19 @@ interface ChatRepository { parentChatRoomId: HexKey? = null, ): MarmotGroupCreation.Outcome + /** + * Invites the founding members [ceremony]'s room never reached, when its + * founding invite never went out. See `MarmotGroupCreation.finishFoundingInvite` + * and docs/robust-group-admins.md, Phase 4. + */ + suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom): MarmotGroupCreation.FoundingInvite + + /** [finishFoundingInvite] for the room [chatRoomId], through the ceremony its key state names. */ + suspend fun finishFoundingInvite(chatRoomId: String): MarmotGroupCreation.FoundingInvite + + /** The founders [localChatRoom]'s founding invite never reached; empty when there are none to reach. */ + suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set + /** * 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 @@ -468,6 +481,14 @@ interface ChatRepository { override suspend fun followThroughCeremonies(keyPair: KeyPair) = Unit + override suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom) = + MarmotGroupCreation.FoundingInvite.NothingToDo + + override suspend fun finishFoundingInvite(chatRoomId: String) = + MarmotGroupCreation.FoundingInvite.NothingToDo + + override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = emptySet() + override suspend fun sendChatMessage( text: String, diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt index 19003418..25e9ad7c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyFollowThroughJvmTest.kt @@ -50,6 +50,7 @@ class CeremonyFollowThroughJvmTest { /** The room creations asked for, and what the next one answers. */ private val created = mutableListOf>>() private var outcome: (String) -> MarmotGroupCreation.Outcome = { MarmotGroupCreation.Outcome.Failed("unset") } + private var foundingInvite: MarmotGroupCreation.FoundingInvite = MarmotGroupCreation.FoundingInvite.NothingToDo private val chatRepository = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { override suspend fun createMarmotGroup( @@ -63,6 +64,8 @@ class CeremonyFollowThroughJvmTest { created += groupId to adminPublicKeys return outcome(groupId) } + + override suspend fun finishFoundingInvite(ceremony: DkgSession, ceremonyRoom: LocalChatRoom) = foundingInvite } private val material = keyMaterial("5eed0000000000000000000000000000000000000000000000000000000000e5") @@ -203,6 +206,28 @@ class CeremonyFollowThroughJvmTest { assertTrue(created.isEmpty()) } + /** docs/robust-group-admins.md, Phase 4: a room that exists is asked whether its founding invite went out. */ + @Test + fun `a room whose founding invite never went out has it finished`(): Unit = runBlocking { + val session = finishedCeremony() + signKeyState(session) + GroupFixtures.seedRoom(db, roomOf(material)) + foundingInvite = MarmotGroupCreation.FoundingInvite.Sent(roomOf(material), invited = listOf(alice, bob), notAdded = listOf(bob)) + + assertEquals(CeremonyFollowThrough.Step.Invited(roomOf(material), listOf(bob)), next(session)) + assertTrue(created.isEmpty(), "and no second room") + } + + @Test + fun `a founding invite waiting on key packages says on whom`(): Unit = runBlocking { + val session = finishedCeremony() + signKeyState(session) + GroupFixtures.seedRoom(db, roomOf(material)) + foundingInvite = MarmotGroupCreation.FoundingInvite.BlockedOn(listOf(alice)) + + assertEquals(CeremonyFollowThrough.Step.BlockedOn(listOf(alice)), next(session)) + } + /** * 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 diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt index 7d7e1774..cd660d8c 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt @@ -26,6 +26,12 @@ import kotlinx.coroutines.runBlocking import mobi.giza.compose.database.GizaDatabase import mobi.giza.compose.database.builder.getRoomDatabase import mobi.giza.compose.database.model.MarmotKeyPackage +import mobi.giza.compose.nostr.Relays +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.database.model.intermdiate.LocalChatRoom +import mobi.giza.compose.database.model.DkgSession +import mobi.giza.compose.database.model.ChatRoom import mobi.giza.compose.database.model.types.DkgApprovalStep import mobi.giza.compose.database.repository.DatabaseChatRepository import mobi.giza.compose.database.repository.DatabaseMarmotRepository @@ -84,7 +90,8 @@ class RobustGroupAdminsJvmTest { override fun toString() = publicKey.take(8) } - private val roomId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey()) + private val foundingThresholdPublicKey = "02" + KeyPair().pubKey.toHexKey() + private val roomId = SharedKeyDerivation.marmotGroupId(foundingThresholdPublicKey) /** * Three phones; the first creates the admin room with all three as its admins, @@ -118,7 +125,7 @@ class RobustGroupAdminsJvmTest { } /** Hands [to] the Welcome [from] queued for it, wrapped as a relay would carry it. */ - private suspend fun welcome(from: Phone, to: Phone) { + private suspend fun welcome(from: Phone, to: Phone, roomId: String = this.roomId) { val payload = from.db.giftWrapPayloadDao().getAllGiftWrapUnsigned() .filter { it.kind == WelcomeEvent.KIND } .single { payload -> payload.tags.any { it.size > 1 && it[1] == to.keyPackage.id } } @@ -192,13 +199,14 @@ class RobustGroupAdminsJvmTest { /** * The boundary docs/robust-group-admins.md, D1 draws: founding, not present. * - * Legacy only until Phase 4. On the current profile `MarmotGroupCreation` invites - * the founders through a room read before its routing id was recorded, so the - * engine's group at the real address still holds only the creator, and a later - * invite takes the founding path -- no commit, and nobody else told. + * On both profiles since Phase 4. Before it, `MarmotGroupCreation` invited the + * founders on the current profile through a room read before its routing id was + * recorded, so the engine's group at the real address still held only the + * creator, and this later invite took the founding path -- no commit, and + * nobody else told. */ @Test - fun `a member added after the founding is not an admin`() = onEveryProfile(listOf(MarmotProfile.LEGACY)) { profile, phones -> + fun `a member added after the founding is not an admin`() = onEveryProfile { profile, phones -> val founders = phones.map { it.publicKey }.toSet() val creator = phones.first() @@ -219,6 +227,119 @@ class RobustGroupAdminsJvmTest { } } + // ---- The founding invite: docs/robust-group-admins.md, Phase 4 ------------- + + private val ceremonyRoomId = "ce1e".repeat(16) + + /** The ceremony [phones] ran, as [owner]'s device holds it: everyone in it, and its key [roomId]'s. */ + private suspend fun ceremonyOn(owner: Phone, phones: List, thresholdPublicKey: HexKey): Pair { + owner.db.chatRoomDao().upsert( + ChatRoom(id = ceremonyRoomId, userPublicKey = owner.publicKey, subject = "Ekklesia", description = null, mlsGroupState = null) + ) + val session = DkgSession( + id = "the-ceremony", + chatRoomId = ceremonyRoomId, + coordinatorPublicKey = owner.publicKey, + userPublicKey = owner.publicKey, + threshold = 2, + participantCount = phones.size, + participantPublicKeys = DkgSession.formatParticipants(phones.map { it.publicKey }.toSet()), + subject = "Ekklesia", + stage = DkgRitualStage.COMPLETE, + hostPublicKey = owner.publicKey, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + thresholdPublicKey = thresholdPublicKey, + secretShare = "cc".repeat(32), + ) + owner.db.dkgSessionDao().upsert(session) + return session to assertNotNull(owner.db.chatRoomDao().findChatRoomById(ceremonyRoomId)) + } + + /** + * A room whose founding invite never went out: made, with every founder in + * its policy, and nobody but its creator in its tree -- what `create` leaves + * when `addMembers` throws. + */ + private suspend fun roomWithoutItsInvite(profile: MarmotProfile, phones: List, roomId: String) { + val creator = phones.first() + val created = MarmotGroupFactory.create( + creator = creator.keyPair, + roomId = roomId, + name = "#Ekklesia", + description = SharedKeyDerivation.describe("Admins of Ekklesia."), + adminPublicKeys = phones.map { it.publicKey }, + relays = Relays.DefaultDMRelayList.map { it.url }, + profile = profile, + ) + assertNotNull( + creator.chatRepository.getOrCreateChatRoom( + chatRoomId = roomId, + activeUserPublicKey = creator.publicKey, + relayHint = null, + defaultSubject = "#Ekklesia", + description = null, + mlsGroupState = created.group.saveState().encodeTls().toHex(), + ) + ) + creator.chatRepository.recordMarmotRouting(chatRoomId = roomId, routingId = created.routingId) + } + + @Test + fun `a founding invite that never went out is finished, and every founder is an admin`(): Unit = runBlocking { + listOf(MarmotProfile.LEGACY, MarmotProfile.CURRENT).forEach { profile -> + val phones = List(3) { Phone(profile) } + try { + phones.forEach { it.ready() } + phones.forEach { phone -> phones.forEach { MarmotStandIn.seedProfile(phone.db, it.publicKey) } } + val creator = phones.first() + phones.drop(1).forEach { creator.db.marmotKeyPackageDao().upsert(it.keyPackage) } + + val thresholdPublicKey = "02" + KeyPair().pubKey.toHexKey() + val roomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + roomWithoutItsInvite(profile, phones, roomId) + val (session, ceremonyRoom) = ceremonyOn(creator, phones, thresholdPublicKey) + + val invite = MarmotGroupCreation.finishFoundingInvite( + creator.db, creator.chatRepository, session, ceremonyRoom, keyPackageLookupTimeout = 2_000L, + ) + val sent = assertIs(invite, "($profile)") + assertEquals(phones.drop(1).map { it.publicKey }.toSet(), sent.invited.toSet(), "($profile)") + assertTrue(sent.notAdded.isEmpty(), "($profile)") + + assertEquals( + MarmotGroupCreation.FoundingInvite.NothingToDo, + MarmotGroupCreation.finishFoundingInvite(creator.db, creator.chatRepository, session, ceremonyRoom, 2_000L), + "and a second run invites nobody ($profile)", + ) + + phones.drop(1).forEach { welcome(from = creator, to = it, roomId = roomId) } + val founders = phones.map { it.publicKey }.toSet() + phones.forEach { phone -> + val room = assertNotNull(phone.db.chatRoomDao().findChatRoomById(roomId), "$phone has no room ($profile)") + val group = assertNotNull(room.chatRoom.toMlsGroup(), "$phone holds no group ($profile)") + assertEquals(founders, group.currentAdminIdentities(), "$phone's admin policy ($profile)") + assertTrue(group.isLocalAdmin(), "$phone is not an admin ($profile)") + } + } finally { + phones.forEach { it.close() } + } + } + } + + /** Past epoch 0 a founder without a leaf may be one who left; that is not this step's to undo. */ + @Test + fun `a room past its founding invites nobody`() = onEveryProfile { profile, phones -> + val creator = phones.first() + val (session, ceremonyRoom) = ceremonyOn(creator, phones, foundingThresholdPublicKey) + + assertEquals( + MarmotGroupCreation.FoundingInvite.NothingToDo, + MarmotGroupCreation.finishFoundingInvite(creator.db, creator.chatRepository, session, ceremonyRoom, 2_000L), + "($profile)", + ) + } + // ---- The ceremony ------------------------------------------------------------ @Test From baf63b8d7aaa1ee075905ae13d74841e0a2ae096 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:18:00 +0200 Subject: [PATCH 21/23] feat: the room's details say who administers it, and whether the founders do (robust-group-admins, Phase 5) The member list labels admins, from the flags AdminFlags keeps. Two cards on the error container, under the signing key and the parent: founding members the room's policy does not list as admins, with "Make them admins" for an admin of a current-profile room; and founding members the founding invite never reached, with "Invite them" on the device that holds the room at epoch 0. Founders are named through their profiles, since an uninvited one is not in the room to read a row off. A robust group's NIP-17 room has no admins of its own, so its details link to the admin room its ceremony made (ChatRepository.adminRoomOf), saying every member is an admin there. Strings in the catalogue, sentence case; colours from the error container roles; spacing from the scale; the actions guard a second tap. m3Audit: all budgets met. jvmTest 1249/1249, compileDebugKotlinAndroid. Not looked at in a running app. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 12 ++ .../repository/DatabaseChatRepository.kt | 14 ++ .../giza/compose/repository/ChatRepository.kt | 10 + .../ui/composable/ChatRoomDetailScreen.kt | 184 +++++++++++++++++- .../ui/view/model/ChatRoomDetailViewModel.kt | 50 ++++- .../ui/view/state/ChatRoomDetailUIState.kt | 20 ++ 6 files changed, 281 insertions(+), 9 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 733a0b2c..79276c4a 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -479,4 +479,16 @@ Waiting on %1$s since %2$s. If they have stopped answering, any member can abandon the ceremony. No key is made, and the group can start again. Open the room + Admin + Founding members aren't admins + %1$s took part in the key ceremony that made this group, but this room doesn't list them as admins. + Make them admins + Asked the group to make them admins + Not every founding member was invited + %1$s took part in the key ceremony that made this group, but the invitation to this room never went out. + Invite them + Invited them to the room + Some of them haven't published a key package yet + Admin room + Every member of this group is an admin there. diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 75987d93..0b28ef4f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -8,6 +8,7 @@ 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.FoundingAdmins +import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.CeremonyFollowThrough import com.vitorpamplona.quartz.nip01Core.relay.normalizer.NormalizedRelayUrl import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate @@ -114,6 +115,19 @@ class DatabaseChatRepository( emptySet() } + override suspend fun adminRoomOf(chatRoomId: String): String? = try { + // The room's own ceremony, not a subgroup's it hosted: a subgroup's key + // makes the subgroup's room, which is not this group's admin room. + database.dkgSessionDao().getLatestSessionFor(chatRoomId, parentChatRoomId = null) + ?.takeIf { it.stage == DkgRitualStage.COMPLETE } + ?.thresholdPublicKey + ?.let { SharedKeyDerivation.marmotGroupId(it) } + ?.takeIf { it != chatRoomId && database.chatRoomDao().findChatRoomById(it) != null } + } catch (e: Throwable) { + logger.e("Error finding the admin room of $chatRoomId", e) + null + } + override suspend fun followThroughCeremonies(keyPair: KeyPair) = CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index 20d1eee1..894c444e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -237,6 +237,14 @@ interface ChatRepository { /** The founders [localChatRoom]'s founding invite never reached; empty when there are none to reach. */ suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set + /** + * The admin room [chatRoomId]'s own key ceremony made, if this device holds + * it: where the members of a robust group's NIP-17 room are admins. Null for + * a room with no finished ceremony of its own, and for one whose admin room + * this device does not hold. + */ + suspend fun adminRoomOf(chatRoomId: String): String? + /** * 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 @@ -489,6 +497,8 @@ interface ChatRepository { override suspend fun uninvitedFounders(localChatRoom: LocalChatRoom): Set = emptySet() + override suspend fun adminRoomOf(chatRoomId: String): String? = null + override suspend fun sendChatMessage( text: String, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt index 2b3ac801..6e7340ad 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/composable/ChatRoomDetailScreen.kt @@ -14,6 +14,9 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons +import mobi.giza.compose.managers.MarmotGroupCreation +import androidx.compose.material3.CardDefaults +import androidx.compose.material.icons.filled.AdminPanelSettings import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.AccountTree import androidx.compose.material.icons.filled.Autorenew @@ -81,6 +84,18 @@ import mobi.giza.compose.ui.view.model.ChatRoomDetailViewModel import mobi.giza.compose.ui.view.state.ChatRoomDetailUIState import com.vitorpamplona.quartz.nip01Core.core.HexKey import mobi.giza.compose.ui.theme.spacing +import mobi.giza.compose.resources.every_member_of_this_group_administers_it_there +import mobi.giza.compose.resources.admin_room +import mobi.giza.compose.resources.founding_members_have_no_key_package +import mobi.giza.compose.resources.founding_members_invited +import mobi.giza.compose.resources.invite_them +import mobi.giza.compose.resources.s_took_part_in_the_key_ceremony_but_were_not_invited +import mobi.giza.compose.resources.not_every_founding_member_was_invited +import mobi.giza.compose.resources.founding_members_made_admins_requested +import mobi.giza.compose.resources.make_them_admins +import mobi.giza.compose.resources.s_took_part_in_the_key_ceremony_but_are_not_admins +import mobi.giza.compose.resources.founding_members_are_not_admins +import mobi.giza.compose.resources.admin import mobi.giza.compose.resources.run_by_members import mobi.giza.compose.resources.parent_group import mobi.giza.compose.resources.a_subgroup @@ -185,6 +200,9 @@ fun ChatRoomDetailScreen( val removalRequested = stringResource(Res.string.member_removal_requested) val rotationRequested = stringResource(Res.string.share_rotation_requested) val sharesActionSent = stringResource(Res.string.shares_action_sent) + val madeAdminsRequested = stringResource(Res.string.founding_members_made_admins_requested) + val foundersInvited = stringResource(Res.string.founding_members_invited) + val foundersHaveNoKeyPackage = stringResource(Res.string.founding_members_have_no_key_package) // Offered after removing a member who still holds a share of the room's key: // the removal took them out of the room, not out of the key @@ -347,6 +365,94 @@ fun ChatRoomDetailScreen( } } + // The founding members, where the room is not as the + // ceremony that made its key left it: founders its + // policy does not list as admins, or founders its + // founding invite never reached. Under the key and the + // parent, because it is about the same thing -- who the + // group that made this room is. docs/robust-group-admins.md, + // Phase 5. + if (chatRoomDetailUIState.missingFoundingAdmins.isNotEmpty()) { + item { + FoundingMembersCard( + title = stringResource(Res.string.founding_members_are_not_admins), + body = stringResource( + Res.string.s_took_part_in_the_key_ceremony_but_are_not_admins, + chatRoomDetailUIState.founderNamesFor(chatRoomDetailUIState.missingFoundingAdmins), + ), + // An admin of a room the app governs: the + // repair is a commit only they can make. + actionLabel = stringResource(Res.string.make_them_admins) + .takeIf { chatRoomDetailUIState.canGovern }, + isActionPending = chatRoomDetailViewModel.isActionPending.value, + onAction = { + chatRoomDetailViewModel.addMissingFoundingAdmins( + localChatRoom = chatRoomDetailUIState.localChatRoom, + missing = chatRoomDetailUIState.missingFoundingAdmins, + ) { failure -> notify(failure ?: madeAdminsRequested) } + }, + ) + } + } + + if (chatRoomDetailUIState.uninvitedFounders.isNotEmpty()) { + item { + FoundingMembersCard( + title = stringResource(Res.string.not_every_founding_member_was_invited), + body = stringResource( + Res.string.s_took_part_in_the_key_ceremony_but_were_not_invited, + chatRoomDetailUIState.founderNamesFor(chatRoomDetailUIState.uninvitedFounders), + ), + actionLabel = stringResource(Res.string.invite_them), + isActionPending = chatRoomDetailViewModel.isActionPending.value, + onAction = { + chatRoomDetailViewModel.inviteFounders(chatRoomId) { invite -> + notify( + when (invite) { + is MarmotGroupCreation.FoundingInvite.BlockedOn -> foundersHaveNoKeyPackage + is MarmotGroupCreation.FoundingInvite.Failed -> invite.reason + else -> foundersInvited + } + ) + } + }, + ) + } + } + + // A robust group's NIP-17 room has no admins of its own; + // its members are admins of the room its key made. + chatRoomDetailUIState.adminRoomId?.let { adminRoomId -> + item { + Card( + modifier = Modifier.fillMaxWidth(), + onClick = { + onNavigateToRoute.invoke( + ChatRoomDetailRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = adminRoomId, + relayHint = relayHint + ) + ) + } + ) { + ListItem( + leadingContent = { + Icon(Icons.Default.AdminPanelSettings, contentDescription = Decorative) + }, + trailingContent = { + Icon(Icons.Default.ChevronRight, contentDescription = Decorative) + }, + headlineContent = { + Text(text = stringResource(Res.string.admin_room)) + }, + supportingContent = { + Text(text = stringResource(Res.string.every_member_of_this_group_administers_it_there)) + } + ) + } + } + } item { chatRoomDetailUIState.localChatRoom.chatRoom.description?.let { Text( @@ -729,10 +835,21 @@ fun ChatRoomDetailScreen( ) }, supportingContent = { - localParticipant.profile?.about?.let { - Text( - text = it - ) + Column { + // From the group's admin policy, through + // `AdminFlags` -- docs/robust-group-admins.md. + if (localParticipant.participant.adminAt != null) { + Text( + text = stringResource(Res.string.admin), + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + localParticipant.profile?.about?.let { + Text( + text = it + ) + } } } @@ -1329,4 +1446,61 @@ private fun ChatRoomMessagingScreenPreview() { ) } } -} \ No newline at end of file +} + +/** + * Something about this room's founding members that is not as the ceremony + * left it -- founders it does not list as admins, or founders its invite never + * reached -- and, where this device can, the one action that repairs it. + * + * On the error container: the room works, but not as the group that made it + * agreed, and that is worth more than a supporting line. docs/robust-group-admins.md, + * Phase 5. + */ +@Composable +private fun FoundingMembersCard( + title: String, + body: String, + actionLabel: String?, + isActionPending: Boolean, + onAction: () -> Unit, +) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer, + contentColor = MaterialTheme.colorScheme.onErrorContainer, + ) + ) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Icon(Icons.Default.AdminPanelSettings, contentDescription = Decorative) + Text(text = title, style = MaterialTheme.typography.titleSmall) + } + + Text(text = body, style = MaterialTheme.typography.bodyMedium) + + actionLabel?.let { label -> + TextButton( + onClick = onAction, + enabled = !isActionPending, + colors = ButtonDefaults.textButtonColors( + contentColor = MaterialTheme.colorScheme.onErrorContainer + ), + ) { + Text(label) + } + } + } + } +} + +/** The founders [publicKeys] names, as the screen calls them, in a stable order. */ +private fun ChatRoomDetailUIState.Loaded.founderNamesFor(publicKeys: Set): String = + publicKeys.map { founderNames[it] ?: it }.sorted().joinToString(", ") diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt index 83a7739b..a857793a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/ChatRoomDetailViewModel.kt @@ -19,6 +19,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.IO import kotlinx.coroutines.launch import mobi.giza.compose.managers.FoundingAdmins +import mobi.giza.compose.managers.MarmotGroupCreation import mobi.giza.compose.database.model.intermdiate.LocalChatRoom import mobi.giza.compose.database.model.types.MarmotReindexReport import mobi.giza.compose.managers.WalletRefusal @@ -98,6 +99,14 @@ class ChatRoomDetailViewModel( ?.let { Event.fromJsonOrNull(it) } ?.let(WalletRefusal::isGuarded) == true + // The founding members, against what the ceremony that made the + // room's key said: who the policy leaves out, and who the founding + // invite never reached. docs/robust-group-admins.md, Phases 3 and 4. + val missingFoundingAdmins = (chatRepository.foundingAdmins(chatRoomId) as? FoundingAdmins.Check.Missing) + ?.publicKeys + .orEmpty() + val uninvitedFounders = chatRepository.uninvitedFounders(localChatRoom) + ChatRoomDetailUIState.Loaded( localChatRoom = localChatRoom, groupKeyState = groupKeyState, @@ -109,9 +118,13 @@ class ChatRoomDetailViewModel( canGovern = canGovern, isDisbanded = isDisbanded, shares = chatRepository.sharesSummary(localChatRoom), - missingFoundingAdmins = (chatRepository.foundingAdmins(chatRoomId) as? FoundingAdmins.Check.Missing) - ?.publicKeys - .orEmpty(), + missingFoundingAdmins = missingFoundingAdmins, + uninvitedFounders = uninvitedFounders, + founderNames = (missingFoundingAdmins + uninvitedFounders).associateWith { publicKey -> + nostrRepository.getProfileWithPublicKey(publicKey)?.humanReadableNameOrPubkey() + ?: publicKey.take(SHORTENED_PUBLIC_KEY_LENGTH) + }, + adminRoomId = if (localChatRoom.chatRoom.mlsGroupState == null) chatRepository.adminRoomOf(chatRoomId) else null, ) } } @@ -146,10 +159,36 @@ class ChatRoomDetailViewModel( * warning stays until then. docs/robust-group-admins.md, Phase 3. */ fun addMissingFoundingAdmins(localChatRoom: LocalChatRoom, missing: Set, onDone: (String?) -> Unit = {}) { + if (isActionPending.value) return + isActionPending.value = true viewModelScope.launch(Dispatchers.IO) { val failure = runCatching { chatRepository.addAdmins(localChatRoom, missing) }.exceptionOrNull() initiateChatRoomDetail() - viewModelScope.launch(Dispatchers.Main) { onDone(failure?.message) } + viewModelScope.launch(Dispatchers.Main) { + isActionPending.value = false + onDone(failure?.message) + } + } + } + + /** + * Finishes the room's founding invite, and reloads the screen. Reports null + * when it went out, or why not -- naming the founders still without a key + * package, since only they can publish one. docs/robust-group-admins.md, + * Phase 4. + */ + fun inviteFounders(chatRoomId: String, onDone: (MarmotGroupCreation.FoundingInvite) -> Unit = {}) { + // Waits on relays for key packages, so a second tap would ask twice. + if (isActionPending.value) return + isActionPending.value = true + viewModelScope.launch(Dispatchers.IO) { + val invite = runCatching { chatRepository.finishFoundingInvite(chatRoomId) } + .getOrElse { MarmotGroupCreation.FoundingInvite.Failed(it.message ?: "Couldn't invite them. Please try again.") } + initiateChatRoomDetail() + viewModelScope.launch(Dispatchers.Main) { + isActionPending.value = false + onDone(invite) + } } } @@ -288,6 +327,9 @@ class ChatRoomDetailViewModel( companion object { private const val TAG = "ChatRoomDetailViewModel" + /** Enough of a key to tell two founders apart when no profile is stored. */ + private const val SHORTENED_PUBLIC_KEY_LENGTH = 12 + fun factory( activeUserPublicKey: HexKey, chatRoomId: String, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt index 20b85009..a7fe3b32 100755 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/state/ChatRoomDetailUIState.kt @@ -91,6 +91,26 @@ sealed interface ChatRoomDetailUIState { * `FoundingAdmins.check`; docs/robust-group-admins.md, Phase 3. */ val missingFoundingAdmins: Set = emptySet(), + /** + * Founding members this room's founding invite never reached -- only ever + * non-empty on the device that made the room, while it is still at epoch 0. + * See `MarmotGroupCreation.uninvitedFounders`; docs/robust-group-admins.md, + * Phase 4. + */ + val uninvitedFounders: Set = emptySet(), + /** + * What to call the founders the two sets above name. They need not be in + * this room -- an uninvited one is not, by definition -- so the room's own + * rows cannot be asked. + */ + val founderNames: Map = emptyMap(), + /** + * The admin room this group's ceremony made, when this is the group's + * NIP-17 room and this device holds it. A NIP-17 room has no admins of its + * own; this is where its members are admins. docs/robust-group-admins.md, + * Phase 5. + */ + val adminRoomId: String? = null, ): ChatRoomDetailUIState data class Error( From 01e33f5a6f25f523e2b128bdc1cd42488c498069 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:21:12 +0200 Subject: [PATCH 22/23] fix: rooms joined before the Welcome wrote flags are caught up at start (robust-group-admins, Phase 6) AdminFlags.reconcileAll runs AdminFlags.reconcile over every room this device holds MLS state for, and the sync start calls it once, through ChatRepository.reconcileAdminFlags, beside the ceremony resume. A room joined before Phase 2 flags nobody on the joiner's device until some commit arrives, and a robust group's admin room may never get one. No stored "done" flag: a room whose rows already agree is a read and no write, so a second start costs one decode per room. A room that will not decode is logged and passed over. RobustGroupAdminsJvmTest: a joiner's cleared flags are restored on both profiles, and a second pass changes nothing. jvmTest 1250/1250, compileDebugKotlinAndroid, audits. Co-Authored-By: Claude Opus 5.5 --- .../repository/DatabaseChatRepository.kt | 3 +++ .../mobi/giza/compose/managers/AdminFlags.kt | 27 +++++++++++++++++++ .../giza/compose/repository/ChatRepository.kt | 9 +++++++ .../ui/view/model/SynchronizationViewModel.kt | 7 +++++ .../managers/RobustGroupAdminsJvmTest.kt | 16 +++++++++++ 5 files changed, 62 insertions(+) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt index 0b28ef4f..55c42504 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/repository/DatabaseChatRepository.kt @@ -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.AdminFlags import mobi.giza.compose.managers.FoundingAdmins import mobi.giza.compose.managers.SharedKeyDerivation import mobi.giza.compose.managers.CeremonyFollowThrough @@ -128,6 +129,8 @@ class DatabaseChatRepository( null } + override suspend fun reconcileAdminFlags(): Int = AdminFlags.reconcileAll(database) + override suspend fun followThroughCeremonies(keyPair: KeyPair) = CeremonyFollowThrough.observe(database = database, chatRepository = this, keyPair = keyPair) diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt index cb121030..85a9156c 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/AdminFlags.kt @@ -56,4 +56,31 @@ object AdminFlags { } return changed.size } + + /** + * [reconcile] for every room this device holds MLS state for and is still in. + * + * Run once per start, for the rooms made before the Welcome wrote any flags: + * a joiner's rows there flag nobody until some commit arrives, and in a + * robust group's admin room one may never arrive. No stored "done" flag -- a + * room whose rows already agree is a read and no write, so a second run costs + * one decode per room and a preference would only be one more thing to keep + * right. docs/robust-group-admins.md, Phase 6. + * + * One room that will not decode is logged and passed over, not fatal to the + * rest. + * + * @return how many rows changed, across every room. + */ + suspend fun reconcileAll(database: GizaDatabase): Int = + database.chatRoomDao().getChatRoomIdsWithMlsState().sumOf { chatRoomId -> + runCatching { + val group = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom?.toMlsGroup() + ?: return@runCatching 0 + reconcile(database, chatRoomId, group) + }.getOrElse { + logger.e("Could not bring $chatRoomId's admin flags in line", it) + 0 + } + } } diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt index 894c444e..df13f39f 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/ChatRepository.kt @@ -245,6 +245,13 @@ interface ChatRepository { */ suspend fun adminRoomOf(chatRoomId: String): String? + /** + * Brings every Marmot room's admin flags in line with its group's policy, for + * the rooms joined before the Welcome wrote any. Once per start. See + * `AdminFlags.reconcileAll` and docs/robust-group-admins.md, Phase 6. + */ + suspend fun reconcileAdminFlags(): Int + /** * 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 @@ -499,6 +506,8 @@ interface ChatRepository { override suspend fun adminRoomOf(chatRoomId: String): String? = null + override suspend fun reconcileAdminFlags(): Int = 0 + override suspend fun sendChatMessage( text: String, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt index c292ec61..8b4c5ac3 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/ui/view/model/SynchronizationViewModel.kt @@ -246,6 +246,13 @@ class SynchronizationViewModel( // was waiting for. docs/automatic-key-ceremony.md, Phase 3. runCatching { nostrRepository.resumeRunningCeremonies(keyPair) } .onFailure { logger.e("Could not resume running key ceremonies", it) } + // The rooms joined before the Welcome wrote admin flags + // flag nobody until some commit arrives, and a robust + // group's admin room may never get one. Caught up here, + // once a start; a room already right is read, not + // written. docs/robust-group-admins.md, Phase 6. + runCatching { chatRepository.reconcileAdminFlags() } + .onFailure { logger.e("Could not bring admin flags in line", it) } launch(Dispatchers.IO) { observePendingBroadcastNostrEventRequests(keyPair) } // Runs until cancelled rather than draining a queue, but it // belongs here for the same reason the pumps do: it needs the diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt index cd660d8c..99d6a32b 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/RobustGroupAdminsJvmTest.kt @@ -227,6 +227,22 @@ class RobustGroupAdminsJvmTest { } } + /** + * A room joined before Phase 2, whose joiner's rows flag nobody, is caught up + * at the next start, once. docs/robust-group-admins.md, Phase 6. + */ + @Test + fun `a room joined before the Welcome wrote flags is caught up at start`() = onEveryProfile { profile, phones -> + val founders = phones.map { it.publicKey }.toSet() + val joiner = phones.last() + joiner.db.participantDao().upsert(joiner.room().localParticipants.map { it.participant.copy(adminAt = null) }) + assertTrue(joiner.flaggedAdmins().isEmpty(), "the fixture did not clear the flags ($profile)") + + assertEquals(founders.size, AdminFlags.reconcileAll(joiner.db), "($profile)") + assertEquals(founders, joiner.flaggedAdmins(), "($profile)") + assertEquals(0, AdminFlags.reconcileAll(joiner.db), "and a second start changes nothing ($profile)") + } + // ---- The founding invite: docs/robust-group-admins.md, Phase 4 ------------- private val ceremonyRoomId = "ce1e".repeat(16) From a95d6db118e5563ac9f8c87972647c06ecc492ad Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 20 Nov 2026 01:21:12 +0200 Subject: [PATCH 23/23] docs: every founding member of a robust group is its admin, built (robust-group-admins, Phase 7) The plan is marked built, with a table of the nine places the build chose differently -- among them that Phase 4 acts on a room at epoch 0 rather than on rows that were never written, since rows are hard-deleted, and that it also fixed the current-profile routing bug Phase 0 found. The README row says built; automatic-key-ceremony.md gains step 4 and subgroups.md the repository taking the ceremony instead of a list. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 2 +- docs/automatic-key-ceremony.md | 5 +++++ docs/robust-group-admins.md | 22 +++++++++++++++++++--- docs/subgroups.md | 6 ++++++ 4 files changed, 31 insertions(+), 4 deletions(-) diff --git a/docs/README.md b/docs/README.md index a3f287de..b4e38d65 100644 --- a/docs/README.md +++ b/docs/README.md @@ -36,7 +36,7 @@ the [retired](./retired/) notes now. | [marmot-kmp.md](./marmot-kmp.md) | moving the group layer off quartz's engine and onto marmot-kmp, mls-kmp and crypto-kmp — why staying on quartz 1.15.2 is staying on an engine that left, the 228 import lines and the one rule that places all but two of them, the group state on a device that must still open afterwards, nine phases that put the swap in one commit and the evidence around it, how often this app persists a group once a sent message no longer rewrites it, and the schema change that followed, opened from the version the app ships | | [giza-wallet-removal.md](./giza-wallet-removal.md) | taking every wallet out of Giza, phased and built but for moving off the wallet library (7b). Covers why a Giza member declines a Bennu peer's wallet proposal instead of ignoring or signing it, why the wallet's kinds are retired rather than freed, why a recovery phrase stays as a key backup that has to derive the same npub and id byte for byte, and why the threshold crypto keeps the build tied to the wallet library until the last phase | | [giza-rebrand.md](./giza-rebrand.md) | forking Bennu as Giza under `mobi.giza` — what carries the name, what must not be renamed and why, why the desktop data directory changes first, and how the fork keeps merging from Bennu | -| [robust-group-admins.md](./robust-group-admins.md) | making every founding member of a robust group an admin of its room, on every device -- phased and not built. Covers why the ceremony's participants are the founding set, the Welcome that flags no admins, the joiner's check against the ceremony it took part in, and finishing an invite that partly failed | +| [robust-group-admins.md](./robust-group-admins.md) | making every founding member of a robust group an admin of its room, on every device -- phased and built. Covers why the ceremony's participants are the founding set, the Welcome that flags no admins, the joiner's check against the ceremony it took part in, and finishing an invite that partly failed | Start with the ceremony if you are new to this area; the Marmot notes all assume it. Read the skipped-keys note before debugging any "the other device never got it" diff --git a/docs/automatic-key-ceremony.md b/docs/automatic-key-ceremony.md index de05aa02..6a86e310 100644 --- a/docs/automatic-key-ceremony.md +++ b/docs/automatic-key-ceremony.md @@ -388,6 +388,11 @@ on a COMPLETE ceremony this device coordinated: room does not exist -> create it ``` +> **Since [robust-group-admins.md](./robust-group-admins.md), Phase 4:** a fifth line, after +> the room exists -- a room still at epoch 0 without its founders, whose founding invite never +> went out, has it finished. And the room's admins are no longer the caller's to pass: the +> repository takes the ceremony and reads them off it. + - **What it calls:** the code behind `DkgRitualViewModel.proposeBirthCertificate`, `proposeKeyState` and `createAdminGroup`. That code moves from the view model into the manager (and `DkgRepository`), along with each one's "already asked" diff --git a/docs/robust-group-admins.md b/docs/robust-group-admins.md index 3abb6483..0ba663cd 100644 --- a/docs/robust-group-admins.md +++ b/docs/robust-group-admins.md @@ -1,11 +1,27 @@ # Every founding member of a robust group is its admin A robust group promises, on the screen that makes it, that "everyone administers the -group together". This note is the plan that makes the promise true on every device from +group together". This note is the plan that made the promise true on every device from the moment the group exists: what "founding member" means, the four places the promise -breaks today, and seven phases that close them. +broke before, and the eight phases that closed them. -**Planned, not built.** Written against `fc437d05`. +**Built**, phases 0-7, one commit each. The phases below are kept as written, +because they are the reasoning; where the build chose differently the table says +so, and it did nine times worth reading: + +| what the plan said | what it turned out to be | +|---|---| +| a new `ChillDkgRitualManager.foundingMembersOf` | never built. `participantsOf` already was that function, fallback and all; Phase 1 made `MarmotGroupCreation.createFor` its one caller on the way to a room, and took the list off `ChatRepository.createMarmotGroup` altogether | +| Phase 2's `stampAdmins` replaced by `AdminFlags.reconcile` with the creation's list | with the group's policy instead. Reading the list back would have kept two sources for one flag, which is the drift D2 is about | +| Phase 2's Welcome test in `WelcomeBundleMatchJvmTest` | in `RobustGroupAdminsJvmTest`, where Phase 0 already delivers real gift-wrapped Welcomes between three app devices. The bundle test is about which key package a Welcome names, not what it leaves behind | +| Phase 3 reports `Differs(missing, unexpected)` and offers removing unexpected admins | `Missing` only. Removing an admin is out of scope, so an admin the ceremony did not have is not this plan's to act on | +| Phase 3's repair on every room | on the current profile only. The app makes no governance commit on a legacy room -- no removal, no disband -- so a legacy room gets the warning and the transcript line and not the button | +| Phase 4 invites founders "who have never had a row in the room, not even a soft-deleted one" | founders without a leaf in a room still at **epoch 0**. Rows are hard-deleted when a member leaves, so "never had a row" cannot be told from "left"; epoch 0 can, because leaving is a commit and the founding invite is the commit that ends epoch 0 | +| Phase 4 is about `notAdded` | it also fixed what Phase 0 found: on the current profile `MarmotGroupCreation` invited the founders through a room read before its routing id was recorded, so the engine adopted a second copy of the group under the room id, and every later invite into that room took the founding path -- no commit, and nobody already in the room told | +| Phase 4's "Invite again" for any other active admin | only on the device holding the room at epoch 0, which is its creator's: nobody else holds the room until the invite reaches them. The coordinator's device does it on its own as step 4 | +| Phase 6 reconciles behind a stored "reconciled" preference | on every start, with no flag. `AdminFlags.reconcile` writes nothing when the rows already agree, so running it again costs one decode per room and a preference would only be a second thing to keep right | + +Written against `fc437d05`. Read [shared-key-ceremony.md](./shared-key-ceremony.md) and [ceremony-creation.md](./ceremony-creation.md) first. diff --git a/docs/subgroups.md b/docs/subgroups.md index 88f129d8..6055b00c 100644 --- a/docs/subgroups.md +++ b/docs/subgroups.md @@ -671,6 +671,12 @@ re-deriving: - **`adopt` before the members are added**, because filing the key state is local and certain and adding members is neither. +> **Since [robust-group-admins.md](./robust-group-admins.md):** the repository's +> `createMarmotGroup` takes the ceremony and the room it ran in instead of +> `adminPublicKeys`, and `MarmotGroupCreation.createFor` reads the admins, the id and the name +> off the ceremony. A subgroup's founding admins are its ceremony's participants, as a +> group's are, so the same rule makes both. + `parentChatRoomId` is the one genuinely new parameter, written onto the `ChatRoom` row. The subgroup's description carries the path through `SharedKeyDerivation.describe`, exactly as the admin room's does — MIP-01 has no