diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index c80f5639..4eecb11f 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -714,7 +714,7 @@
Open for %1$d days
Shorter
Longer
- Proposing shows this group's admins to the admins of every group named here, and each group that accepts shows its own. Once every group has accepted, every admin of every group can join the key ceremony.
+ Proposing shows this group's admins to the admins of every group named here, and each group that accepts shows its own. Once every group has accepted, every admin's device joins the key ceremony on its own.
Has announced no inbox, so the proposal could not reach it
Set up this group's inbox first: a confederation's proposal and every answer are sent from it.
A confederation can name at most %1$d groups
@@ -735,7 +735,7 @@
Reason (optional)
Waiting for the group to sign its answer
Open the signing session
- Accepting shows this group's admins and threshold to the admins of every group the proposal names.
+ Accepting shows this group's admins and threshold to the admins of every group the proposal names. Once every group has accepted, each of this group's admins joins the key ceremony and holds a share of the confederation's key.
This device does not hold that proposal
Couldn't ask the group to answer
Every group accepted. %1$d admins across %2$d groups would hold the confederation's key.
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt
index ec47cf44..daf1ba4c 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/ConfederationCeremonyDao.kt
@@ -123,6 +123,16 @@ interface ConfederationCeremonyDao {
@Query("SELECT * FROM ConfederationCeremonyHeard WHERE sessionId = :sessionId ORDER BY heardAt ASC, kind ASC")
suspend fun getCeremonyHeardForSession(sessionId: String): List
+ /**
+ * Changes whenever a ceremony message is heard or a ceremony ends: what the device's own join
+ * looks again on, for a retry somebody else started (docs/confederation-auto-join.md).
+ */
+ @Query(
+ "SELECT (SELECT COUNT(*) FROM ConfederationCeremonyHeard) + " +
+ "(SELECT COUNT(*) FROM ConfederationCeremony WHERE stage IN ('COMPLETE', 'FAILED'))"
+ )
+ fun observeCeremonyActivity(): Flow
+
@Query("SELECT * FROM ConfederationCeremonyHeard WHERE proposalId = :proposalId ORDER BY heardAt ASC, kind ASC")
suspend fun getCeremonyHeardForProposal(proposalId: HexKey): 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 93b9c623..5d7ce47f 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
@@ -211,6 +211,12 @@ class DatabaseChatRepository(
// the other groups' inboxes. docs/confederation-room-removal.md, D4.
launch { mobi.giza.compose.managers.ConfederationBridge.observe(database = database, keyPair = keyPair) }
keyPair.privKey?.let { secret ->
+ // The key ceremony of a proposal every group accepted, joined with nobody asked:
+ // each group's signed acceptance already named its admins.
+ // docs/confederation-auto-join.md.
+ if (ExperimentalFeatures.groupInbox) {
+ launch { ConfederationRitualManager.observeAndJoin(database, keyPair.pubKey.toHex(), secret) }
+ }
launch {
runCatching { ConfederationRitualManager.resumeRunning(database, keyPair.pubKey.toHex(), secret) }
.onFailure { logger.e("Could not resume confederation ceremonies", it) }
diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt
index 2c0fd65f..b34830cc 100644
--- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt
+++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ConfederationRitualManager.kt
@@ -26,8 +26,18 @@ import fr.acinq.bitcoin.crypto.confederation.ConfederationRoleId
import fr.acinq.bitcoin.crypto.confederation.ConfederationRoster
import fr.acinq.bitcoin.crypto.confederation.ConfederationTransition
import fr.acinq.bitcoin.utils.Either
+import kotlin.coroutines.cancellation.CancellationException
import kotlin.time.Clock
import kotlin.time.Instant
+import kotlin.time.Duration.Companion.minutes
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.conflate
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.merge
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
import mobi.giza.compose.database.GENESIS_AT
import mobi.giza.compose.database.GizaDatabase
import mobi.giza.compose.database.model.ChatMessage
@@ -61,8 +71,10 @@ import mobi.giza.compose.nostr.confederation.ConfederationStatus
* The shape is `ChillDkgRitualManager`'s and for its reasons. Every step is a pure function of what
* this device has stored, so [advance] decides what to do next from which messages exist, never
* from the stage, and a device that dies between rounds picks up on the next message or the next
- * [resumeRunning]. Joining is the only thing a member is asked; the rounds after it run by
- * themselves (docs/automatic-key-ceremony.md).
+ * [resumeRunning]. Nobody is asked anything: a member's device joins on its own once every group has
+ * accepted, since their group's signed acceptance already named them ([joinOnItsOwn],
+ * docs/confederation-auto-join.md), and the rounds after it run by themselves
+ * (docs/automatic-key-ceremony.md).
*
* What a coordinator did is done on every device:
*
@@ -87,6 +99,13 @@ object ConfederationRitualManager {
const val ABANDONED = "Abandoned by a participant"
+ /**
+ * One join at a time on a device, whoever asked: the device on its own or a person's tap. Two at
+ * once would each make the ceremony with its own random seed and send a 30381 for it, and two
+ * different signed host-key messages from one person fail the ceremony as an equivocation.
+ */
+ private val joining = Mutex()
+
// ---- what a ceremony is built from ------------------------------------------------------
/**
@@ -229,7 +248,10 @@ object ConfederationRitualManager {
* running or finished ceremony is returned as it is. Throws, with a reason a person can read,
* when this device cannot take part.
*/
- suspend fun join(database: GizaDatabase, proposalId: HexKey, userPublicKey: HexKey, nostrPrivateKey: ByteArray): ConfederationCeremony {
+ suspend fun join(database: GizaDatabase, proposalId: HexKey, userPublicKey: HexKey, nostrPrivateKey: ByteArray): ConfederationCeremony =
+ joining.withLock { joinLocked(database, proposalId, userPublicKey, nostrPrivateKey) }
+
+ private suspend fun joinLocked(database: GizaDatabase, proposalId: HexKey, userPublicKey: HexKey, nostrPrivateKey: ByteArray): ConfederationCeremony {
val latest = database.confederationCeremonyDao().getLatestForProposal(proposalId)?.takeIf { it.userPublicKey == userPublicKey }
if (latest != null && latest.stage == ConfederationCeremonyStage.COMPLETE) return latest
if (latest != null && latest.isRunning) {
@@ -262,6 +284,81 @@ object ConfederationRitualManager {
return database.confederationCeremonyDao().getCeremony(ceremony.id)!!
}
+ /** How often [observeAndJoin] looks again with nothing new: what lets a device join once it can, such as when its inbox key is announced. */
+ private val LOOK_AGAIN = 1.minutes
+
+ /**
+ * Joins on its own for as long as it runs (docs/confederation-auto-join.md): whenever a statement
+ * is filed, a ceremony message is heard or a ceremony ends, and every [LOOK_AGAIN] besides.
+ */
+ suspend fun observeAndJoin(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray) {
+ val ticks: Flow = flow { while (true) { emit(Unit); delay(LOOK_AGAIN) } }
+ merge(
+ ticks,
+ database.confederationDao().observeProposals().map { },
+ database.confederationCeremonyDao().observeCeremonyActivity().map { },
+ ).conflate().collect {
+ try {
+ joinOnItsOwn(database, userPublicKey, nostrPrivateKey)
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Throwable) {
+ logger.e("Could not look for key ceremonies to join", e)
+ }
+ }
+ }
+
+ /**
+ * Joins, as [userPublicKey], every ceremony this device should join without asking anyone
+ * (docs/confederation-auto-join.md), and returns the ceremonies it joined. See [shouldJoinOnItsOwn]
+ * for which. A join that fails is logged and left for the next pass or the button.
+ */
+ suspend fun joinOnItsOwn(database: GizaDatabase, userPublicKey: HexKey, nostrPrivateKey: ByteArray): List =
+ database.confederationDao().getProposals().mapNotNull { row ->
+ try {
+ if (!shouldJoinOnItsOwn(database, row.id, userPublicKey)) return@mapNotNull null
+ join(database, row.id, userPublicKey, nostrPrivateKey).also {
+ logger.i { "Joined the key ceremony for ${row.id.take(8)} on its own, as attempt ${it.attempt}" }
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Throwable) {
+ logger.e("Could not join the key ceremony for ${row.id.take(8)} on its own", e)
+ null
+ }
+ }
+
+ /**
+ * Whether [userPublicKey]'s device joins [proposalId]'s ceremony now, with nobody asked:
+ *
+ * - **the first attempt**, once every group has accepted and [joinable] passes. Their group's
+ * quorum signed an acceptance that names them as one of its admins, and every admin must
+ * join for the ceremony to finish, so a tap could only ever say yes or stall everybody. The
+ * way to say no is the group's answer, or **Abandon** once it runs;
+ * - **a ceremony made by an older build** that is still waiting on its member's tap;
+ * - **a retry somebody else started**: after this device's attempt `k` failed or was abandoned,
+ * once it holds a message for attempt `k + 1` signed by another person in the roster.
+ * It never starts `k + 1` itself. A failure that repeats -- a group that told two groups
+ * different things -- would otherwise go round on every device for good; a person pressing
+ * **Try again** is the decision, and everybody else follows it.
+ */
+ suspend fun shouldJoinOnItsOwn(database: GizaDatabase, proposalId: HexKey, userPublicKey: HexKey): Boolean {
+ if (ConfederationManager.status(database, proposalId)?.state != ConfederationProposalState.ACCEPTED) return false
+ val latest = database.confederationCeremonyDao().getLatestForProposal(proposalId)?.takeIf { it.userPublicKey == userPublicKey }
+ return when {
+ latest == null -> joinable(database, proposalId, userPublicKey) is Either.Right
+ latest.stage == ConfederationCeremonyStage.COMPLETE -> false
+ latest.isRunning -> latest.approvedAt == null
+ else -> {
+ val people = planOf(latest)?.people ?: return false
+ val next = ConfederationAttestation.ceremonyId(proposalId, latest.attempt + 1)
+ val started = database.confederationCeremonyDao().getCeremonyHeardForSession(next)
+ .any { it.pubKey != userPublicKey && it.pubKey in people }
+ started && joinable(database, proposalId, userPublicKey) is Either.Right
+ }
+ }
+ }
+
private fun newCeremony(user: HexKey, basis: Basis, plan: Plan, attempt: Int): ConfederationCeremony {
val groups = plan.seatsOf(user).map { it.group }
return ConfederationCeremony(
diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt
index 6fe3192c..f52bc295 100644
--- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/ConfederationCeremonyJvmTest.kt
@@ -1,5 +1,7 @@
package mobi.giza.compose.managers
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.async
import androidx.room3.Room
import mobi.giza.compose.nostr.MarmotProfile
import mobi.giza.compose.database.repository.DatabaseChatRepository
@@ -700,4 +702,83 @@ class ConfederationCeremonyJvmTest {
assertTrue(runBlocking { ConfederationFormation.isConfederation(host.db, confederation.id) }, "by its record: what a welcome to it is refused on")
assertFalse(runBlocking { ConfederationFormation.isConfederation(host.db, groups[0]) }, "a member group is no confederation")
}
+ // ---- joining on its own (docs/confederation-auto-join.md) ------------------------------
+
+ /** What [ConfederationRitualManager.observeAndJoin] does on each pass, on [device]: the proposals it joined. */
+ private fun joinOnItsOwn(device: ConfederationPeople.Device): List = runBlocking {
+ ConfederationRitualManager.joinOnItsOwn(device.db, device.person, device.nsec).map { it.proposalId }
+ }
+
+ @Test
+ fun `every admin's device joins on its own once every group has accepted, and the key forms`() {
+ setUp()
+ devices.values.forEach { assertEquals(listOf(network.proposalId), joinOnItsOwn(it), "on ${it.person.take(6)}") }
+ pump()
+ ceremonies().values.forEach {
+ assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason)
+ assertEquals(1, it?.attempt)
+ }
+ devices.values.forEach { assertEquals(emptyList(), joinOnItsOwn(it), "a finished ceremony is not joined again") }
+ }
+
+ @Test
+ fun `a device joins on its own only once it holds every acceptance`() {
+ val late = 32
+ setUp(statementsFor = { device -> if (device.person == network.npub(late)) network.everyStatement().take(2) else network.everyStatement() })
+ assertEquals(emptyList(), joinOnItsOwn(network.device(late)))
+ assertNull(ceremonies()[npub(late)], "nothing is made")
+ }
+
+ @Test
+ fun `a device does not join on its own where it cannot join at all`() {
+ setUp()
+ val polisMember = network.device(22)
+ RoomAdmins.override = { id ->
+ if (id == groups[1]) RoomAdmins(setOf(21, 22, 23, 24).map { npub(it) }.toSet(), governed = false) else null
+ }
+ assertEquals(emptyList(), joinOnItsOwn(polisMember))
+ assertNull(ceremonies()[polisMember.person])
+ }
+
+ @Test
+ fun `a failed attempt is never tried again on its own, but a retry somebody starts is followed`() {
+ setUp()
+ devices.values.forEach { joinOnItsOwn(it) }
+ runBlocking { ConfederationRitualManager.abandon(network.device(11).db, ceremonies().getValue(npub(11))!!.id, network.device(11).nsec) }
+ pump()
+ ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.FAILED, it?.stage) }
+
+ devices.values.forEach { assertEquals(emptyList(), joinOnItsOwn(it), "nobody pressed Try again, so nothing starts on ${it.person.take(6)}") }
+
+ // One person presses Try again; everybody else's device follows once their 30381 arrives.
+ val retrier = network.device(21)
+ runBlocking { network.join(retrier) }
+ pump()
+ devices.values.filter { it != retrier }.forEach { assertEquals(listOf(network.proposalId), joinOnItsOwn(it), "on ${it.person.take(6)}") }
+ pump()
+ ceremonies().values.forEach {
+ assertEquals(2, it?.attempt)
+ assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason)
+ }
+ }
+
+ @Test
+ fun `a tap and the device's own join at the same moment send one host-key message, and the key forms`() {
+ setUp()
+ val both = network.device(11)
+ runBlocking {
+ listOf(
+ async(Dispatchers.Default) { network.join(both) },
+ async(Dispatchers.Default) { ConfederationRitualManager.joinOnItsOwn(both.db, both.person, both.nsec) },
+ ).awaitAll()
+ }
+ assertEquals(
+ 1,
+ runBlocking { both.db.confederationCeremonyDao().getCeremonyHeardForProposal(network.proposalId) }
+ .count { it.pubKey == both.person && it.kind == ConfederationRitualEvents.HOST_KEYS },
+ )
+ devices.values.filter { it != both }.forEach { joinOnItsOwn(it) }
+ pump()
+ ceremonies().values.forEach { assertEquals(ConfederationCeremonyStage.COMPLETE, it?.stage, it?.failureReason) }
+ }
}
diff --git a/docs/confederation-auto-join.md b/docs/confederation-auto-join.md
new file mode 100644
index 00000000..6b0cd827
--- /dev/null
+++ b/docs/confederation-auto-join.md
@@ -0,0 +1,77 @@
+# The confederation's key ceremony joins itself
+
+Until this change every admin of every group was shown **Join the key ceremony** once every group
+had accepted, and the ceremony could not start its rounds until each of them had pressed it
+([confederation-without-coordinator.md](./confederation-without-coordinator.md) D8, "Joining is still
+the only approval"). Now each admin's device joins on its own. The button stays, for the cases the
+device leaves alone.
+
+## Why the tap was not a decision
+
+[automatic-key-ceremony.md](./automatic-key-ceremony.md) kept the join as the one approval in a
+group's own ceremony because "nothing on the device can decide that for them": joining puts a
+member in a signing quorum, and nobody else agreed to that on their behalf.
+
+A confederation is different in two ways:
+
+- **Someone has already agreed, by signature.** Each group's acceptance (9431) is signed by the
+ group's own quorum and names the admins it puts forward. The admin is in the roster because their
+ group said so, and the proposer's own admin list is in the 9430 its quorum signed.
+- **Every admin must join** ([confederation.md](./confederation.md) D11). An admin who does not tap
+ does not leave the roster. They stall the ceremony for every group until somebody abandons it.
+ So the tap had two outcomes: yes, or everyone waits.
+
+So the tap added a stall and nothing else. Saying no happens elsewhere: in the group's answer to the
+proposal, and in **Abandon** once the ceremony is running. Both are still there.
+
+What the person used to see at the join is now said when the decision is made. The accept and
+propose screens say that, once every group accepts, each admin joins the key ceremony and holds a
+share (`accepting_discloses_admins`, `proposing_shows_admins_to_the_groups`).
+
+## What the device joins
+
+`ConfederationRitualManager.shouldJoinOnItsOwn`, for this device's owner:
+
+| the device holds | joins on its own |
+|---|---|
+| no ceremony for an `ACCEPTED` proposal, and `joinable` passes | **yes**: attempt 1 |
+| a running ceremony made by an older build, still waiting on its member (`approvedAt == null`) | **yes** |
+| a running or complete ceremony | no |
+| a failed or abandoned attempt `k` | **only once it holds a message for attempt `k + 1` signed by somebody else in the roster** |
+| anything `joinable` refuses (admins changed, no inbox key yet, a roster too large) | no; the screen still says why, and the button still offers it |
+
+**It never starts a retry itself.** Some failures repeat, such as a group that told two groups
+different things. If devices started `k + 1` on their own, a failure like that would go round on
+every device forever. When a person presses **Try again**, that is the decision (D10), and every
+other device follows it.
+
+## When it runs
+
+`ConfederationRitualManager.observeAndJoin`, launched by `ChatRepository.followThroughCeremonies`
+next to the confederation's other drivers, behind both `ExperimentalFeatures.confederation` and
+`ExperimentalFeatures.groupInbox` (D13). It runs a pass when a statement is filed, when a ceremony
+message is heard, when a ceremony ends, and once a minute. The minute pass catches a device that
+becomes able to join, for example when its inbox key is announced.
+
+**One join at a time.** `join` holds a mutex now, so the device's own join and a person's tap
+cannot both make the ceremony. Each would pick its own random seed and send a 30381, and two
+different signed host-key messages from one person fail the ceremony as an equivocation. The
+second caller finds the ceremony running and returns it.
+
+## Tests
+
+`ConfederationCeremonyJvmTest`, under "joining on its own":
+
+- every device joins on its own and the key forms; a second pass joins nothing;
+- a device that does not hold every acceptance joins nothing;
+- a device whose group's admins changed since it accepted joins nothing;
+- a failed attempt is not retried on its own, but once one person retries, every other device
+ follows and attempt 2 forms;
+- a tap and the device's own join at the same moment send one 30381, and the key forms.
+
+## Not done
+
+- No device run.
+- A person who abandoned attempt `k` themselves is still brought into `k + 1` when somebody else
+ retries. Abandon means "this attempt stalled" (automatic-key-ceremony.md), not "I am out". They
+ can abandon again.
diff --git a/docs/confederation-without-coordinator.md b/docs/confederation-without-coordinator.md
index 5f7b1367..0e4f3653 100644
--- a/docs/confederation-without-coordinator.md
+++ b/docs/confederation-without-coordinator.md
@@ -368,6 +368,8 @@ the room = createNip17ChatRoom over the roster's people: id deriveChatR
attestation tag moves to `v2` because its inputs are rumor ids now. The `mantra/…` spelling is the
house rule for protocol tags (CLAUDE.md).
+> **Since [confederation-auto-join.md](./confederation-auto-join.md):** nobody is asked to join. Each admin's device joins once every group has accepted, since the group's signed acceptance already named its admins, and a tap could only say yes or stall everyone.
+
**Joining is still the only approval.** Each admin is asked once, on the proposal's screen. Joining
sends this person's 30381. A message that arrives before this device has every statement, or before
its owner joins, is stored and replayed, as `replayStoredMessages` does today for messages that beat
@@ -464,8 +466,8 @@ build declines a peer's confederation seal batch out loud rather than signing it
| A signs | A's quorum | that A proposes this, with these admins | wrapping and sending to every group's 10050 (proposer's device) |
| invitation arrives | nobody | — | every admin's device in every invited group files it and writes a line |
| B answers | one admin of B, then B's quorum | accept or reject | wrapping and sending |
-| all accepted | nobody | — | every admin's device shows **Join** |
-| ceremony | each admin of each group | **to join** | every round after the join; the seed; the broadcast |
+| all accepted | nobody | — | every admin's device joins on its own ([confederation-auto-join.md](./confederation-auto-join.md)) |
+| ceremony | nobody | — | the join; every round after it; the seed; the broadcast |
| a retry | any person in the roster | **to try again**, which is their join | as above |
| room | nobody | — | made by the first person in the order who can, with the fallback |