diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index fc65c639..ad5fe7d9 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -579,7 +579,9 @@
Join the ceremony
Send your contributions
Confirm what you saw
- Joining publishes commitments to your contributions. Nothing secret leaves this device.
+ Joining publishes commitments to your contributions. Your device then takes the other two steps by itself, checking each one, and sends your contributions only encrypted to the members who will hold them.
+ If it hasn't finished %1$s hours after it was proposed, it is abandoned and the group can start another.
+ Couldn't abandon the ceremony.
Each contribution is encrypted to the members who will hold it. Your randomness starts shaping the key here.
Confirming publishes your public share and a hash of every commitment you saw, so the group can check it agrees.
%1$s of 3 steps
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/IcebergKeySessionDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/IcebergKeySessionDao.kt
index 91ff55ee..601c65c9 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/IcebergKeySessionDao.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/IcebergKeySessionDao.kt
@@ -25,6 +25,10 @@ interface IcebergKeySessionDao {
@Query("SELECT * FROM IcebergKeySession WHERE stage = 'COMPLETE'")
suspend fun getCompletedSessions(): List
+ /** Every ceremony still under way, on any identity's account: neither finished nor failed. */
+ @Query("SELECT * FROM IcebergKeySession WHERE stage NOT IN ('COMPLETE', 'FAILED')")
+ suspend fun getRunningSessions(): List
+
@Upsert
suspend fun upsert(session: IcebergKeySession)
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/IcebergKeySession.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/IcebergKeySession.kt
index 6d7a71ca..425719c7 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/IcebergKeySession.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/IcebergKeySession.kt
@@ -61,11 +61,14 @@ data class IcebergKeySession(
/** Every participant's public share, in participant order, comma-separated hex. */
val publicShares: String? = null,
val joinApprovedAt: Instant? = null,
+ /** Written by builds that asked before revealing; nothing reads it now. */
val revealApprovedAt: Instant? = null,
+ /** Written by builds that asked before confirming; nothing reads it now. */
val confirmApprovedAt: Instant? = null,
/** The furthest step this device has asked its owner about, so each request is written once. */
val approvalRequestedThrough: IcebergApprovalStep? = null,
val failureReason: String? = null,
+ /** When the ceremony was proposed, by its proposal's timestamp: its deadline runs from here. */
val createdAt: Instant = Clock.System.now(),
val updatedAt: Instant = createdAt,
) {
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/types/IcebergApprovalStep.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/types/IcebergApprovalStep.kt
index d66f3dff..262c775a 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/types/IcebergApprovalStep.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/types/IcebergApprovalStep.kt
@@ -1,8 +1,11 @@
package com.machankura.bennu.compose.database.model.types
/**
- * The three things an Iceberg ceremony asks a member before their device publishes anything of
- * theirs, in order. The same three gates the ChillDKG ceremony has, for the same reasons.
+ * What an Iceberg ceremony asks a member before their device publishes anything of theirs.
+ *
+ * Only [JOIN] is asked now. The ceremony used to stop at all three, as the ChillDKG ceremony does, but
+ * the checks behind [REVEAL] and [CONFIRM] are made by the device, not the person, so after joining it
+ * takes them by itself. The two stay because rows and transcript lines written before name them.
*/
enum class IcebergApprovalStep {
/**
@@ -13,14 +16,14 @@ enum class IcebergApprovalStep {
/**
* Send this device's contributions to the seeds it holds, each encrypted to the other holders.
- * From here the member's own randomness is shaping a key they will help sign with.
+ * No longer asked: the device sends them once it has every commitment.
*/
REVEAL,
/**
- * Publish this device's public share and the hash of the transcript it saw. A real check: two
+ * Publish this device's public share and the hash of the transcript it saw. A real check -- two
* members shown different commitments sign different transcripts, and the ceremony refuses to
- * finish on transcripts that disagree.
+ * finish on transcripts that disagree -- but the device's, so no longer asked.
*/
CONFIRM,
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt
index 9c8ee7da..d792c3df 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt
@@ -115,4 +115,10 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr
override suspend fun approveCeremony(localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray) =
IcebergRitualManager.approve(database, localChatRoom, sessionId, step, nostrPrivateKey)
+
+ override suspend fun resumeCeremony(localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) =
+ IcebergRitualManager.resume(database, localChatRoom, sessionId, nostrPrivateKey)
+
+ override suspend fun abandonCeremony(localChatRoom: LocalChatRoom, sessionId: String): Boolean =
+ IcebergRitualManager.abandon(database, localChatRoom, sessionId)
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergRitualManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergRitualManager.kt
index ad52d401..15f5fcb9 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergRitualManager.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergRitualManager.kt
@@ -33,6 +33,8 @@ import fr.acinq.bitcoin.utils.Either
import kotlinx.coroutines.CancellationException
import kotlinx.serialization.Serializable
import kotlin.time.Clock
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.hours
import kotlin.time.Instant
/**
@@ -40,9 +42,21 @@ import kotlin.time.Instant
* wallet signs its channels with (`docs/group-lightning-wallet.md`, Phase 5).
*
* Built like [ChillDkgRitualManager], and following its rules: every step is a pure function of what
- * this device has stored, so a ceremony survives the app being killed; nothing of this device's own is
- * published until its owner approves, at three gates; faults are values with one failure path; and each
- * device writes the ceremony's transcript lines from what it has received.
+ * this device has stored, so a ceremony survives the app being killed; faults are values with one
+ * failure path; and each device writes the ceremony's transcript lines from what it has received.
+ *
+ * ### One approval, then the device
+ *
+ * Nothing of this device's own is published until its owner agrees to join. After that the device takes
+ * the other two rounds by itself, because every check in them is one the code makes and the person
+ * could not: whether a contribution matches its commitment, whether everyone saw the same commitments,
+ * whether the public shares make one key. Asking a person to tap through them added nothing but the
+ * chance that a member who joined would not come back, holding the ceremony open for everybody.
+ *
+ * A ceremony ends without anyone deciding to end it in two ways. A fault any device detects stops it on
+ * that device, and the failure it broadcasts stops it on every other. A ceremony that has not finished
+ * [DEADLINE] after its proposal is abandoned by the device of whichever participant notices first
+ * ([abandonOverdue]), naming who had not taken their part. Any participant can also [abandon] it.
*
* ### Two things it does not need, that ChillDKG does
*
@@ -71,6 +85,16 @@ object IcebergRitualManager {
private const val THRESHOLD_TAG = "threshold"
private const val ONCHAIN_TAG = "onchain_dkg"
+ /**
+ * How long a ceremony has, from its proposal, before any participant's device abandons it. Long
+ * enough for a member to see the request and open the app once; short enough that a member who
+ * never does stops blocking the room, which can only run one ceremony at a time.
+ */
+ val DEADLINE: Duration = 24.hours
+
+ /** When [session] is abandoned if it has not finished: [DEADLINE] after it was proposed. */
+ fun deadlineOf(session: IcebergKeySession): Instant = session.createdAt + DEADLINE
+
@Serializable
private data class Round1(val commitments: Map)
@@ -209,6 +233,15 @@ object IcebergRitualManager {
val threshold = innerEvent.tags.firstOrNull { it.size >= 2 && it[0] == THRESHOLD_TAG }?.get(1)?.toIntOrNull()
val onchainId = innerEvent.tags.firstOrNull { it.size >= 2 && it[0] == ONCHAIN_TAG }?.get(1)
if (userPublicKey.lowercase() !in members) return null
+ // A proposal read after its deadline is over on every device that took part in it, finished or
+ // not: one that could still be running would need this device, which has not joined. Filing it
+ // would ask its owner to join a ceremony that is about to be abandoned -- or, on a device
+ // reading the room again after a restore, abandon one the group finished long ago.
+ val proposedAt = Instant.fromEpochSeconds(innerEvent.createdAt)
+ if (Clock.System.now() >= proposedAt + DEADLINE) {
+ logger.i("Iceberg proposal $sessionId is past its deadline; not filing it")
+ return null
+ }
if (threshold == null || !IcebergDkg.isDeployable(members.size, threshold)) {
logger.w("Iceberg proposal $sessionId asks for $threshold-of-${members.size}, which is not deployable; dropping")
return null
@@ -236,6 +269,9 @@ object IcebergRitualManager {
participantPublicKeys = IcebergKeySession.formatParticipants(members),
onchainDkgSessionId = onchainKey.id,
root = RandomInstance.bytes(32).toHex(),
+ // When it was proposed, not when this device heard of it: the deadline runs from here,
+ // and every device has to agree on it.
+ createdAt = proposedAt,
)
database.icebergKeySessionDao().upsert(session)
announce(
@@ -308,10 +344,6 @@ object IcebergRitualManager {
val commitments = commitmentsOf(database, session, params) ?: return
session = moveTo(database, session, IcebergRitualStage.COLLECTING_REVEALS)
- if (session.revealApprovedAt == null) {
- announceApprovalNeeded(database, session, IcebergApprovalStep.REVEAL)
- return
- }
if (own(database, session, GroupLightningEvents.DKG_ROUND_2) == null) {
val to = (1..params.n).filter { it != me }.associate { k ->
val recipient = session.participants()[k - 1]
@@ -327,10 +359,6 @@ object IcebergRitualManager {
}
session = moveTo(database, session, IcebergRitualStage.COLLECTING_CONFIRMATIONS)
- if (session.confirmApprovedAt == null) {
- announceApprovalNeeded(database, session, IcebergApprovalStep.CONFIRM)
- return
- }
val transcript = IcebergDkg.transcriptHash(params, commitments)
val myPublicShare = Iceberg.publicShare(share, null)
if (own(database, session, GroupLightningEvents.DKG_ROUND_3) == null) {
@@ -436,19 +464,13 @@ object IcebergRitualManager {
}
}
- /** What this ceremony is waiting on its owner for, or null. Mirrors the gates in [advance]. */
+ /**
+ * What this ceremony is waiting on its owner for, or null. Only ever [IcebergApprovalStep.JOIN]: it
+ * is the one gate in [advance].
+ */
suspend fun pendingApproval(database: BennuDatabase, session: IcebergKeySession): IcebergApprovalStep? {
if (session.stage == IcebergRitualStage.COMPLETE || session.stage == IcebergRitualStage.FAILED) return null
- if (session.joinApprovedAt == null) return IcebergApprovalStep.JOIN
- val dao = database.icebergKeySessionDao()
- if (session.revealApprovedAt == null) {
- return if (dao.countMessagesByKind(session.id, GroupLightningEvents.DKG_ROUND_1) >= session.participantCount) IcebergApprovalStep.REVEAL else null
- }
- if (session.confirmApprovedAt == null) {
- val reveals = dao.getMessagesByKind(session.id, GroupLightningEvents.DKG_ROUND_2).count { it.participantPublicKey != session.userPublicKey.lowercase() }
- return if (reveals >= session.participantCount - 1) IcebergApprovalStep.CONFIRM else null
- }
- return null
+ return if (session.joinApprovedAt == null) IcebergApprovalStep.JOIN else null
}
/** Records that this device's owner agreed to [step] and runs on. A step it is not waiting on is a no-op. */
@@ -469,6 +491,62 @@ object IcebergRitualManager {
advance(database, localChatRoom, sessionId, nostrPrivateKey)
}
+ /**
+ * Takes whatever steps [sessionId] can take now. Messages arriving and approvals already do this;
+ * this is for a ceremony that stopped at a gate a build before this one had, and that nothing will
+ * arrive to move, since the others are waiting on this device.
+ */
+ suspend fun resume(database: BennuDatabase, localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) =
+ advance(database, localChatRoom, sessionId, nostrPrivateKey)
+
+ /**
+ * Ends [sessionId] for everyone in it, at its owner's word. Open to any participant, as the shared
+ * key's is (`docs/ceremony-creation.md`, decision 3): any of them could already end it by going
+ * quiet, and saying so lets the others stop waiting. False when it is already over.
+ */
+ suspend fun abandon(database: BennuDatabase, localChatRoom: LocalChatRoom, sessionId: String): Boolean {
+ val session = database.icebergKeySessionDao().getSessionById(sessionId) ?: return false
+ if (session.stage == IcebergRitualStage.COMPLETE || session.stage == IcebergRitualStage.FAILED) return false
+ val reason = "@${ChatMessage.memberName(database, session.userPublicKey)} abandoned it."
+ fail(database, session, reason)
+ broadcast(database, localChatRoom, session, GroupLightningEvents.CEREMONY_FAILURE, reason)
+ return true
+ }
+
+ /**
+ * Abandons every ceremony [userPublicKey] is in that has passed its [deadlineOf] without finishing,
+ * telling the group who had not taken their part. Every participant's device does this, so several
+ * may say it; the first failure each device files is the one it keeps.
+ */
+ suspend fun abandonOverdue(database: BennuDatabase, userPublicKey: HexKey, now: Instant = Clock.System.now()) {
+ for (session in database.icebergKeySessionDao().getRunningSessions()) {
+ if (session.userPublicKey != userPublicKey || now < deadlineOf(session)) continue
+ val localChatRoom = database.chatRoomDao().findChatRoomById(session.chatRoomId) ?: continue
+ val reason = overdueReason(database, session)
+ logger.i("Iceberg ceremony ${session.id} is past its deadline; abandoning it")
+ fail(database, session, reason)
+ broadcast(database, localChatRoom, session, GroupLightningEvents.CEREMONY_FAILURE, reason)
+ }
+ }
+
+ /**
+ * Why an overdue ceremony stopped: the members missing from the first round this device does not
+ * have from everyone, which is who the ceremony was waiting on.
+ */
+ internal suspend fun overdueReason(database: BennuDatabase, session: IcebergKeySession): String {
+ val dao = database.icebergKeySessionDao()
+ val missing = listOf(GroupLightningEvents.DKG_ROUND_1, GroupLightningEvents.DKG_ROUND_2, GroupLightningEvents.DKG_ROUND_3)
+ .firstNotNullOfOrNull { kind ->
+ val sent = dao.getMessagesByKind(session.id, kind).map { it.participantPublicKey.lowercase() }.toSet()
+ session.participants().filter { it !in sent }.takeIf { it.isNotEmpty() }
+ }
+ .orEmpty()
+ val hours = DEADLINE.inWholeHours
+ if (missing.isEmpty()) return "It didn't finish within $hours hours of being proposed."
+ val names = missing.map { "@" + ChatMessage.memberName(database, it) }
+ return "${names.joinToString(", ")} didn't take their part within $hours hours of it being proposed."
+ }
+
/** The share this device holds for the room's newest completed ceremony, with what it is a share of. */
suspend fun completedKey(database: BennuDatabase, chatRoomId: String): IcebergKeySession? =
database.icebergKeySessionDao().getSessionsForChatRoom(chatRoomId).firstOrNull { it.stage == IcebergRitualStage.COMPLETE && it.share != null }
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt
index ee7b55b4..93ea9832 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt
@@ -44,6 +44,12 @@ interface GroupLightningRepository {
suspend fun approveCeremony(localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray)
+ /** Takes whatever steps the ceremony can take now, for one a gate of an earlier build left waiting. */
+ suspend fun resumeCeremony(localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray)
+
+ /** Ends the ceremony for everyone in it; false when it is already over. */
+ suspend fun abandonCeremony(localChatRoom: LocalChatRoom, sessionId: String): Boolean
+
/** The newest completed Lightning wallet key this device holds a share of, or null. */
suspend fun completedCeremony(chatRoomId: String): IcebergKeySession?
@@ -115,6 +121,8 @@ interface GroupLightningRepository {
override suspend fun hasOnchainWallet(chatRoomId: String, chain: Chain): Boolean = false
override suspend fun proposeCeremony(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, threshold: Int, chain: Chain): IcebergKeySession = error("No room to propose in")
override suspend fun approveCeremony(localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray) = Unit
+ override suspend fun resumeCeremony(localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) = Unit
+ override suspend fun abandonCeremony(localChatRoom: LocalChatRoom, sessionId: String): Boolean = false
override suspend fun completedCeremony(chatRoomId: String): IcebergKeySession? = null
override suspend fun lightningWallet(chatRoomId: String, chain: Chain): GroupLightningWalletManager.Wallet? = null
override suspend fun earlierWallets(chatRoomId: String, chain: Chain): List = emptyList()
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/IcebergCeremonyScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/IcebergCeremonyScreen.kt
index a87bc6db..c9276597 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/IcebergCeremonyScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/IcebergCeremonyScreen.kt
@@ -15,7 +15,9 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.Key
+import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
@@ -25,9 +27,14 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -35,6 +42,13 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.viewmodel.compose.viewModel
import bennu.composeapp.generated.resources.Res
import bennu.composeapp.generated.resources.a_lightning_wallet_needs_four_signers
+import bennu.composeapp.generated.resources.abandon
+import bennu.composeapp.generated.resources.abandon_ceremony
+import bennu.composeapp.generated.resources.abandon_this_key_ceremony_question
+import bennu.composeapp.generated.resources.cancel
+import bennu.composeapp.generated.resources.couldn_t_abandon_the_ceremony
+import bennu.composeapp.generated.resources.if_it_hasn_t_finished_s_hours_after
+import bennu.composeapp.generated.resources.it_ends_for_everyone_in_it_no_key_is_created
import bennu.composeapp.generated.resources.the_ceremony_was_abandoned
import bennu.composeapp.generated.resources.nothing_was_created_and_no_key_exists_it_is
import bennu.composeapp.generated.resources.confirm_what_you_saw
@@ -61,6 +75,7 @@ import bennu.composeapp.generated.resources.your_share_of_this_key_is_stored_une
import com.machankura.bennu.compose.database.model.types.IcebergApprovalStep
import com.machankura.bennu.compose.database.model.types.IcebergRitualStage
import com.machankura.bennu.compose.identity.Identity
+import com.machankura.bennu.compose.managers.IcebergRitualManager
import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
import com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.repository.GroupLightningRepository
@@ -82,8 +97,8 @@ import kotlinx.coroutines.flow.StateFlow
import org.jetbrains.compose.resources.stringResource
/**
- * A group's Lightning wallet key ceremony: who has done which of its three rounds, what this device is
- * being asked, and -- for a group without one -- the way to start it.
+ * A group's Lightning wallet key ceremony: who has done which of its three rounds, whether this device
+ * has been asked to join, the way to abandon it, and -- for a group without one -- the way to start it.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -112,6 +127,7 @@ fun IcebergCeremonyScreen(
val notify = rememberNotifier(rememberCoroutineScope())
val couldNotStart = stringResource(Res.string.couldn_t_start_the_key_ceremony)
val couldNotApprove = stringResource(Res.string.couldn_t_approve_this_step)
+ val couldNotAbandon = stringResource(Res.string.couldn_t_abandon_the_ceremony)
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
@@ -156,6 +172,8 @@ fun IcebergCeremonyScreen(
state = state,
isPending = viewModel.isActionPending.value,
onApprove = { viewModel.approve(onFailure = { notify(couldNotApprove) }) },
+ canAbandon = viewModel.canAbandon(),
+ onAbandon = { viewModel.abandon(onFailure = { notify(couldNotAbandon) }) },
)
}
}
@@ -186,9 +204,17 @@ private fun StartCeremony(thresholds: List, participants: Int, chosen: Int?
}
@Composable
-private fun Ceremony(modifier: Modifier, state: IcebergCeremonyUIState.Loaded, isPending: Boolean, onApprove: () -> Unit) {
+private fun Ceremony(
+ modifier: Modifier,
+ state: IcebergCeremonyUIState.Loaded,
+ isPending: Boolean,
+ onApprove: () -> Unit,
+ canAbandon: Boolean,
+ onAbandon: () -> Unit,
+) {
val session = state.session ?: return
val members = state.localChatRoom.localParticipants.associate { it.participant.participantPublicKey.lowercase() to it }
+ var isConfirmingAbandon by remember { mutableStateOf(false) }
LazyColumn(
modifier = modifier.readableContent().fillMaxSize().padding(MaterialTheme.spacing.screenMargin),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
@@ -209,6 +235,14 @@ private fun Ceremony(modifier: Modifier, state: IcebergCeremonyUIState.Loaded, i
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
+ // Said while it runs, so a member who has not joined knows the room is not held forever.
+ if (canAbandon) {
+ Text(
+ text = stringResource(Res.string.if_it_hasn_t_finished_s_hours_after, IcebergRitualManager.DEADLINE.inWholeHours.toString()),
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant,
+ )
+ }
}
// As the shared key's ceremony says it: why, in the sentence the device that
// stopped it wrote, and that nothing was made.
@@ -275,5 +309,41 @@ private fun Ceremony(modifier: Modifier, state: IcebergCeremonyUIState.Loaded, i
},
)
}
+ // Below the members rather than beside the join button: the consequence is the whole
+ // ceremony's, and reads against who is in it.
+ if (canAbandon) {
+ item {
+ TextButton(
+ onClick = { isConfirmingAbandon = true },
+ enabled = !isPending,
+ colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error),
+ ) {
+ Text(stringResource(Res.string.abandon_ceremony))
+ }
+ }
+ }
+ }
+
+ if (isConfirmingAbandon) {
+ AlertDialog(
+ onDismissRequest = { isConfirmingAbandon = false },
+ title = { Text(stringResource(Res.string.abandon_this_key_ceremony_question)) },
+ text = { Text(stringResource(Res.string.it_ends_for_everyone_in_it_no_key_is_created)) },
+ confirmButton = {
+ TextButton(
+ onClick = {
+ isConfirmingAbandon = false
+ onAbandon()
+ }
+ ) {
+ Text(stringResource(Res.string.abandon))
+ }
+ },
+ dismissButton = {
+ TextButton(onClick = { isConfirmingAbandon = false }) {
+ Text(stringResource(Res.string.cancel))
+ }
+ },
+ )
}
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/IcebergCeremonyViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/IcebergCeremonyViewModel.kt
index d5788862..cd8840a6 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/IcebergCeremonyViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/IcebergCeremonyViewModel.kt
@@ -10,6 +10,8 @@ import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import co.touchlab.kermit.Logger
+import com.machankura.bennu.compose.database.model.IcebergKeySession
+import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.database.model.types.IcebergRitualStage
import com.machankura.bennu.compose.identity.Identity
import com.machankura.bennu.compose.repository.ChatRepository
@@ -26,10 +28,10 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
- * Watches a group's Lightning wallet key ceremony, opens one, and approves its steps.
+ * Watches a group's Lightning wallet key ceremony, opens one, joins it, and abandons it.
*
* Nothing here drives the protocol: [com.machankura.bennu.compose.managers.IcebergRitualManager]
- * advances as messages arrive, and this only reads the session and asks its owner what it is waiting on.
+ * advances as messages arrive, and this only reads the session and asks its owner whether to join.
*/
class IcebergCeremonyViewModel(
val activeUserPublicKey: HexKey,
@@ -54,6 +56,9 @@ class IcebergCeremonyViewModel(
private var watching: Job? = null
+ /** The ceremonies this screen has nudged once, so a re-read does not nudge them again. */
+ private val resumed = mutableSetOf()
+
fun initiate() {
watching?.cancel()
watching = viewModelScope.launch(Dispatchers.IO) {
@@ -73,6 +78,7 @@ class IcebergCeremonyViewModel(
lightningRepository.observeCeremonies(chatRoomId).map { it.firstOrNull() }
}
sessions.collect { session ->
+ if (session != null) resume(localChatRoom, session)
val messages = session?.let { lightningRepository.ceremonyMessages(it.id) }.orEmpty()
uiState = IcebergCeremonyUIState.Loaded(
localChatRoom = localChatRoom,
@@ -87,6 +93,18 @@ class IcebergCeremonyViewModel(
}
}
+ /**
+ * A joined ceremony this device has not moved since an earlier build stopped it at a gate that no
+ * longer exists: the others are waiting on it, so nothing will arrive to move it. Once per ceremony.
+ */
+ private suspend fun resume(localChatRoom: LocalChatRoom, session: IcebergKeySession) {
+ val running = session.stage != IcebergRitualStage.FAILED && session.stage != IcebergRitualStage.COMPLETE
+ if (!running || session.joinApprovedAt == null || !resumed.add(session.id)) return
+ val privateKey = activeIdentityStateFlow.value?.nostrPrivateKey?.value?.toByteArray() ?: return
+ runCatching { lightningRepository.resumeCeremony(localChatRoom, session.id, privateKey) }
+ .onFailure { logger.e("Could not resume ${session.id}", it) }
+ }
+
/** Whether this device can open a ceremony: none running, a deployable size, an onchain wallet, a key to sign with. */
fun canPropose(): Boolean {
val loaded = uiState as? IcebergCeremonyUIState.Loaded ?: return false
@@ -128,6 +146,26 @@ class IcebergCeremonyViewModel(
}
}
+ /** Whether the shown ceremony is still running, which is when a participant may end it. */
+ fun canAbandon(): Boolean {
+ val loaded = uiState as? IcebergCeremonyUIState.Loaded ?: return false
+ return loaded.session?.stage?.let { it != IcebergRitualStage.FAILED && it != IcebergRitualStage.COMPLETE } == true
+ }
+
+ fun abandon(onFailure: () -> Unit) {
+ val loaded = uiState as? IcebergCeremonyUIState.Loaded ?: return
+ val session = loaded.session ?: return
+ if (isActionPending.value) return
+ isActionPending.value = true
+ viewModelScope.launch(Dispatchers.IO) {
+ val abandoned = runCatching { lightningRepository.abandonCeremony(loaded.localChatRoom, session.id) }
+ .onFailure { logger.e("Could not abandon ${session.id}", it) }
+ .getOrDefault(false)
+ isActionPending.value = false
+ if (!abandoned) withContext(Dispatchers.Main) { onFailure() }
+ }
+ }
+
companion object {
private const val TAG = "IcebergCeremonyViewModel"
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupLightningNodes.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupLightningNodes.kt
index c95052c9..1a45d763 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupLightningNodes.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupLightningNodes.kt
@@ -5,6 +5,7 @@ import com.machankura.bennu.compose.database.BennuDatabase
import com.machankura.bennu.compose.managers.GroupLightningNode
import com.machankura.bennu.compose.managers.GroupLightningOperatorManager
import com.machankura.bennu.compose.managers.GroupLightningWalletManager
+import com.machankura.bennu.compose.managers.IcebergRitualManager
import com.machankura.bennu.compose.wallet.GroupLightningRollout
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.Chain
@@ -26,6 +27,10 @@ import kotlin.time.Duration.Companion.minutes
* again at every Lightning wallet this device holds a share of: a node starts once this device is elected
* and has heard from the room recently, and each running node stops itself when a later term begins.
*
+ * The same check abandons any of this identity's Lightning key ceremonies that has passed its deadline
+ * ([IcebergRitualManager.abandonOverdue]): it is the one loop an identity runs for its Lightning wallets,
+ * and a ceremony nobody is looking at is exactly the one that needs it.
+ *
* On Android the node runs while the app does. A foreground service that keeps it running with the app
* in the background is the next piece of work, and the nomination screen says so meanwhile.
*/
@@ -78,6 +83,7 @@ class GroupLightningNodes(
job?.cancel()
job = scope.launch {
while (isActive) {
+ runCatching { IcebergRitualManager.abandonOverdue(database, userPublicKey) }.onFailure { logger.e("Could not abandon overdue key ceremonies", it) }
runCatching { refresh() }.onFailure { logger.e("Could not refresh the group nodes", it) }
delay(CHECK)
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/IcebergCeremonyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/IcebergCeremonyJvmTest.kt
index 42f7d30f..acca5bad 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/IcebergCeremonyJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/IcebergCeremonyJvmTest.kt
@@ -48,6 +48,8 @@ import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
+import kotlin.time.Clock
+import kotlin.time.Duration.Companion.seconds
import kotlin.time.Instant
/**
@@ -155,7 +157,7 @@ class IcebergCeremonyJvmTest {
private suspend fun group(): List = (0 until n).map { device(it) }.also { openOnchainWallet(it) }
- /** Runs the ceremony from [proposer], each other device approving every step when it is asked. */
+ /** Runs the ceremony from [proposer], each other device approving when it is asked: joining, only. */
private suspend fun runCeremony(all: List, proposer: Device = all[0], threshold: Int = 2): IcebergKeySession {
val proposed = IcebergRitualManager.proposeCeremony(proposer.db, proposer.room, proposer.publicKey, proposer.privateKey, threshold, chain)
repeat(6) {
@@ -210,7 +212,7 @@ class IcebergCeremonyJvmTest {
}
@Test
- fun `nothing of a member's goes out before they approve it`() = runBlocking {
+ fun `nothing of a member's goes out before they join, and joining is the only approval`() = runBlocking {
val all = group()
val proposed = IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 2, chain)
pump(all, GroupLightningEvents.CEREMONY)
@@ -218,10 +220,82 @@ class IcebergCeremonyJvmTest {
assertEquals(IcebergApprovalStep.JOIN, IcebergRitualManager.pendingApproval(other.db, other.ceremony(proposed.id)!!))
assertTrue(outbox(other, GroupLightningEvents.CEREMONY).isEmpty(), "a member who has not joined has published nothing")
- all.drop(1).forEach { IcebergRitualManager.approve(it.db, it.room, proposed.id, IcebergApprovalStep.JOIN, it.privateKey) }
+ // Three of four join: commitments go out, and nothing more, while one is missing.
+ all.drop(1).dropLast(1).forEach { IcebergRitualManager.approve(it.db, it.room, proposed.id, IcebergApprovalStep.JOIN, it.privateKey) }
pump(all, GroupLightningEvents.CEREMONY)
assertEquals(setOf(GroupLightningEvents.DKG_ROUND_1), outbox(other, GroupLightningEvents.CEREMONY).map { it.kind }.toSet(), "joining publishes commitments and nothing more")
- assertEquals(IcebergApprovalStep.REVEAL, IcebergRitualManager.pendingApproval(other.db, other.ceremony(proposed.id)!!))
+
+ // The last joins, and the ceremony runs to its key with nobody asked anything else.
+ IcebergRitualManager.approve(all[3].db, all[3].room, proposed.id, IcebergApprovalStep.JOIN, all[3].privateKey)
+ pump(all, GroupLightningEvents.CEREMONY)
+ all.forEach { d ->
+ val session = d.ceremony(proposed.id)!!
+ assertEquals(IcebergRitualStage.COMPLETE, session.stage, "device ${d.index}: ${session.failureReason}")
+ val asked = d.db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage.messageType }
+ assertTrue(ChatMessage.TYPE_ICEBERG_APPROVAL_NEEDED_REVEAL !in asked && ChatMessage.TYPE_ICEBERG_APPROVAL_NEEDED_CONFIRM !in asked)
+ }
+ }
+
+ /**
+ * A ceremony a member never joins is abandoned by the first device past its deadline, naming them,
+ * and the failure that device sends ends it on every other. Then the room can open another.
+ */
+ @Test
+ fun `a ceremony past its deadline is abandoned, naming who had not taken part`() = runBlocking {
+ val all = group()
+ val proposed = IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 2, chain)
+ pump(all, GroupLightningEvents.CEREMONY)
+ all.drop(1).dropLast(1).forEach { IcebergRitualManager.approve(it.db, it.room, proposed.id, IcebergApprovalStep.JOIN, it.privateKey) }
+ pump(all, GroupLightningEvents.CEREMONY)
+
+ val deadline = IcebergRitualManager.deadlineOf(all[1].ceremony(proposed.id)!!)
+ IcebergRitualManager.abandonOverdue(all[1].db, all[1].publicKey, now = deadline - 1.seconds)
+ assertEquals(IcebergRitualStage.COLLECTING_COMMITMENTS, all[1].ceremony(proposed.id)!!.stage, "not before its deadline")
+
+ IcebergRitualManager.abandonOverdue(all[1].db, all[1].publicKey, now = deadline)
+ val name = ChatMessage.memberName(all[1].db, all[3].publicKey)
+ val expected = "@$name didn't take their part within 24 hours of it being proposed."
+ assertEquals(expected, all[1].ceremony(proposed.id)!!.failureReason)
+
+ pump(all, GroupLightningEvents.CEREMONY)
+ all.forEach { d ->
+ val session = d.ceremony(proposed.id)!!
+ assertEquals(IcebergRitualStage.FAILED, session.stage, "device ${d.index}")
+ assertEquals(expected, session.failureReason, "device ${d.index} keeps the sentence it was sent")
+ }
+ val again = IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 2, chain)
+ assertTrue(again.id != proposed.id, "the room is free for a new ceremony")
+ }
+
+ @Test
+ fun `any participant can abandon a ceremony, and it ends for everyone`() = runBlocking {
+ val all = group()
+ val proposed = IcebergRitualManager.proposeCeremony(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, 2, chain)
+ pump(all, GroupLightningEvents.CEREMONY)
+
+ assertTrue(IcebergRitualManager.abandon(all[2].db, all[2].room, proposed.id))
+ assertTrue(!IcebergRitualManager.abandon(all[2].db, all[2].room, proposed.id), "a ceremony is abandoned once")
+ pump(all, GroupLightningEvents.CEREMONY)
+ val expected = "@${ChatMessage.memberName(all[2].db, all[2].publicKey)} abandoned it."
+ all.forEach { d ->
+ val session = d.ceremony(proposed.id)!!
+ assertEquals(IcebergRitualStage.FAILED, session.stage, "device ${d.index}")
+ assertEquals(expected, session.failureReason)
+ assertNull(session.root, "the random root goes with it")
+ }
+ }
+
+ /** A proposal read after its deadline -- by a device reading the room again, say -- is not filed. */
+ @Test
+ fun `a proposal past its deadline is not filed`() = runBlocking {
+ val all = group()
+ val tags = members.drop(1).map { arrayOf("p", it) } + listOf(
+ arrayOf("iceberg_session", Random.nextBytes(32).toHex()), arrayOf("threshold", "2"), arrayOf("onchain_dkg", onchainCeremonyId),
+ )
+ val createdAt = (Clock.System.now() - IcebergRitualManager.DEADLINE - 1.seconds).epochSeconds
+ val event = Event(EventHasher.hashId(pubKey = members[0], createdAt = createdAt, kind = GroupLightningEvents.CEREMONY_PROPOSAL, tags = tags.toTypedArray(), content = ""), members[0], createdAt, GroupLightningEvents.CEREMONY_PROPOSAL, tags.toTypedArray(), "", "")
+ IcebergRitualManager.processCeremonyPayload(all[1].db, all[1].room, event, all[1].publicKey, all[1].privateKey)
+ assertTrue(all[1].db.icebergKeySessionDao().getSessionsForChatRoom(roomId).isEmpty())
}
@Test
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt
index 154fe0aa..81f707a5 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSignedWorkRowsJvmTest.kt
@@ -11,6 +11,9 @@ import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.runDesktopComposeUiTest
+import com.machankura.bennu.compose.database.model.GroupSignedEvent
+import com.machankura.bennu.compose.managers.GroupWalletDerivation
+import com.machankura.bennu.compose.nostr.wallet.GroupWallet
import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
import com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.repository.NostrRepository
@@ -24,9 +27,14 @@ import com.machankura.bennu.compose.ui.theme.BennuTheme
import com.machankura.bennu.compose.ui.view.state.ChatRoomDetailUIState
import com.machankura.bennu.compose.wallet.GroupLightningRollout
import com.machankura.bennu.compose.wallet.GroupWalletRollout
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.secp256k1.Hex
import kotlin.test.Test
import kotlin.test.assertEquals
+import kotlin.test.assertNull
import kotlin.test.assertTrue
+import kotlin.time.Instant
/**
* The row on the group's screen that stands for its signed work, and what it
@@ -69,7 +77,7 @@ class GroupSignedWorkRowsJvmTest {
if (!GroupWalletRollout.ENABLED || !GroupLightningRollout.ENABLED) return
var opened: Route? = null
- render(state(), onNavigateToRoute = { opened = it }) {
+ render(state(groupWallet = onchainWallet), onNavigateToRoute = { opened = it }) {
onNode(hasText("Lightning wallet") and hasText(GroupWalletStatementEvent.chainName(GroupLightningRollout.NETWORK))).assertIsDisplayed()
onNodeWithText("Group onchain wallet on", substring = true).assertDoesNotExist()
onNodeWithText("Lightning wallet").performClick()
@@ -78,6 +86,20 @@ class GroupSignedWorkRowsJvmTest {
assertEquals(GroupLightningWalletRoute(activeUserPublicKey, chatRoomId), opened)
}
+ /** It closes to the onchain wallet, so until there is one it says so and opens nothing. */
+ @Test
+ fun `the Lightning wallet's row waits for an onchain wallet`() {
+ if (!GroupWalletRollout.ENABLED || !GroupLightningRollout.ENABLED) return
+ var opened: Route? = null
+
+ render(state(), onNavigateToRoute = { opened = it }) {
+ onNode(hasText("Lightning wallet") and hasText("Lightning is only available once the group has an onchain wallet.")).assertIsDisplayed()
+ onNodeWithText("Lightning wallet").performClick()
+ }
+
+ assertNull(opened)
+ }
+
@Test
fun `the group's screen has no nostr profile, relays, posts or paste`() = render(state()) {
onNodeWithText("Nostr profile").assertDoesNotExist()
@@ -101,11 +123,33 @@ class GroupSignedWorkRowsJvmTest {
/** The wallet row is named for its room: the fixture's subject. */
private val WALLET_ROW = "Translation room onchain wallet"
- private fun state(mlsGroupState: String? = "state") = ChatRoomDetailUIState.Loaded(
+ private fun state(mlsGroupState: String? = "state", groupWallet: GroupWallet? = null) = ChatRoomDetailUIState.Loaded(
localChatRoom = GroupSignedWorkFixtures.localChatRoom(mlsGroupState),
groupKeyState = GroupSignedWorkFixtures.groupKeyState,
+ groupWallet = groupWallet,
)
+ /** An onchain wallet on the Lightning wallet's network; only its presence matters to these rows. */
+ private val onchainWallet: GroupWallet by lazy {
+ val account = GroupWalletDerivation.account(
+ PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(),
+ GroupLightningRollout.NETWORK,
+ )
+ GroupWallet(
+ signedEvent = GroupSignedEvent(
+ id = "e".repeat(64),
+ chatRoomId = chatRoomId,
+ publicKey = chatRoomId,
+ kind = GroupWalletStatementEvent.KIND,
+ tags = GroupWalletStatementEvent.template(account).tags,
+ content = account.xpub,
+ signature = "f".repeat(128),
+ createdAt = Instant.fromEpochSeconds(1_700_000_000),
+ ),
+ account = account,
+ )
+ }
+
/**
* The screen at a phone's width and a window tall enough to compose the whole
* of it, since a `LazyColumn` does not lay out what it would not show.
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt
index 89dd4a8c..5d7c3390 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt
@@ -113,6 +113,8 @@ class GroupLightningWalletViewModelJvmTest {
override suspend fun hasOnchainWallet(chatRoomId: String, chain: Chain): Boolean = onchain
override suspend fun proposeCeremony(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, threshold: Int, chain: Chain): IcebergKeySession = error("unused")
override suspend fun approveCeremony(localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray) = Unit
+ override suspend fun resumeCeremony(localChatRoom: LocalChatRoom, sessionId: String, nostrPrivateKey: ByteArray) = Unit
+ override suspend fun abandonCeremony(localChatRoom: LocalChatRoom, sessionId: String): Boolean = false
override suspend fun completedCeremony(chatRoomId: String): IcebergKeySession? = completed
override suspend fun lightningWallet(chatRoomId: String, chain: Chain): GroupLightningWalletManager.Wallet? = wallet
override suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator? = operator
diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md
index 3e934254..f0b660c9 100644
--- a/docs/group-lightning-wallet.md
+++ b/docs/group-lightning-wallet.md
@@ -68,6 +68,7 @@ build chose differently, this table says so.
| a transcript *signature* in round 3 | a transcript *hash*, beside the public share. The MLS frame already says who sent it. The hash covers the parameters and every commitment but not the public shares, which are published in the same message. `groupPublicKey`'s consistency check holds those together, and Phase 6's statement is where a member whose device computed a different key refuses to sign |
| round-2 values are NIP-44 encrypted to each recipient's ceremony host key | to each recipient's nostr key, from the sender's, for the same reason as the row above |
| an `IcebergKeySession` holds the share, and the protocol state | it holds the share and the *inputs*, as `DkgSession` does: a random root that every contribution is derived from, and every message in `IcebergParticipantMessage`. The root is dropped once the share exists, or when the ceremony fails |
+| three approval gates, as in the ChillDKG ceremony | one, joining. After it the device sends its contributions and confirms by itself, because every check in those rounds is the code's: a contribution against its commitment, everyone's transcript hash, the public shares making one key. The person had nothing to judge, and a member who joined and never came back held the ceremony open for everybody. A ceremony also ends on its own: any participant's device abandons one that has not finished 24 hours after its proposal (`IcebergRitualManager.DEADLINE`, checked each minute beside the group nodes), naming who had not taken their part, and any participant can abandon it from the ceremony screen. Before this a ceremony nobody finished blocked the room for good, since a room runs one at a time. A device that finishes just as another passes the deadline keeps its key while the others fail. The split is possible but contained: a device whose record of the ceremony is not COMPLETE refuses any wallet statement under its key (`GroupLightningWalletManager.verify`), so those members' devices never co-sign for it |
| the ceremony's transcript lines get their own session column | they reuse `ChatMessage.dkgSessionId` for the Iceberg session's id. The line's type says which ceremony screen it opens |
| entry from the Lightning wallet screen | the Lightning wallet screen arrives in Phase 6. Until then the ceremony screen is reached from its own transcript lines, and `IcebergCeremonyRoute` with no session shows the room's newest, with the way to start one |
| the seed is sent once the statement completes | with the proposal. Every co-signer then holds the seed the statement names before they are asked to sign it, and a device files a seed only after recomputing the node id it produces. A seed whose statement never completes is never used |
@@ -629,6 +630,7 @@ order. Faults are values, and their single failure path names the culprit.
contributions is another. The transcript signature is a third, with the same
reason: it is the check that stops a coordinator from swapping in a key nobody
contributed to.
+ *(Built with joining as the only gate; see the table at the top.)*
- **Storage:** an `IcebergKeySession` table holds `t`, `n`, the participants, the
group key, the public shares, the serialised **share** and the stored round
inputs. The schema goes from 26 to 27 with an `AutoMigration`. The transcript