diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt index 3cffa2c8..abc3152e 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/database/dao/DkgSessionDao.kt @@ -156,6 +156,20 @@ interface DkgSessionDao { @Query("SELECT * FROM DkgSession WHERE parentChatRoomId = :parentChatRoomId ORDER BY createdAt DESC") suspend fun getByParentChatRoomId(parentChatRoomId: String): List + /** + * Every ceremony [userPublicKey] has joined that has not finished either way, + * oldest first: what `ChillDkgRitualManager.resumeRunning` moves on. + * + * Joined, because a ceremony nobody here agreed to has nothing of this + * device's to send. Stage by name, which is how Room stores an enum. + */ + @Query( + "SELECT * FROM DkgSession WHERE userPublicKey = :userPublicKey AND " + + "hostKeyApprovedAt IS NOT NULL AND stage NOT IN ('COMPLETE', 'FAILED') " + + "ORDER BY createdAt ASC" + ) + suspend fun getRunningSessionsFor(userPublicKey: HexKey): List + @Upsert suspend fun upsert(dkgSession: DkgSession) 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 686c551c..611cb87d 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 @@ -58,6 +58,8 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import mobi.giza.compose.managers.ChillDkgRitualManager +import com.vitorpamplona.quartz.nip01Core.core.toHexKey import mobi.giza.compose.identity.Identity /** @@ -136,6 +138,20 @@ class DatabaseNostrRepository( } } + override suspend fun resumeRunningCeremonies(activeKeyPair: KeyPair): Int { + val privateKey = activeKeyPair.privKey ?: return 0 + + // 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 { + ChillDkgRitualManager.resumeRunning( + database = database, + userPublicKey = activeKeyPair.pubKey.toHexKey(), + nostrPrivateKey = privateKey + ) + } + } + override suspend fun createNewProfile( publicKey: HexKey, name: String?, diff --git a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt index 26823acd..134cf43a 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/managers/ChillDkgRitualManager.kt @@ -408,6 +408,48 @@ object ChillDkgRitualManager { ) } + /** + * Moves every ceremony [userPublicKey] has joined as far as its stored messages + * allow. Returns how many it looked at. + * + * What a tap on "Contribute" used to do. [advance] runs when a message arrives, + * and until rounds 1 and 2 stopped being asked about, a member's approval was + * the other thing that ran it. Without one, a ceremony that already holds + * every message it needs and will be sent no more never moves -- which is + * exactly where an older build leaves a ceremony it was waiting to be told to + * contribute to, and where a crash between storing a message and acting on it + * leaves any ceremony. + * + * Safe to run as often as the caller likes: [advance] repeats no work, and a + * ceremony with nothing to do returns at its first missing input. + */ + suspend fun resumeRunning( + database: GizaDatabase, + userPublicKey: HexKey, + nostrPrivateKey: ByteArray + ): Int { + val running = database.dkgSessionDao().getRunningSessionsFor(userPublicKey) + + running.forEach { session -> + val localChatRoom = database.chatRoomDao().findChatRoomById(session.chatRoomId) + if (localChatRoom == null) { + logger.w("Ritual ${session.id} is in ${session.chatRoomId}, which is gone; not resuming it") + return@forEach + } + + advance( + database = database, + localChatRoom = localChatRoom, + sessionId = session.id, + nostrPrivateKey = nostrPrivateKey + ) + } + + if (running.isNotEmpty()) logger.i("Resumed ${running.size} running ritual(s)") + + return running.size + } + /** * Records a proposal and answers it with this device's host key. Returns the * session, whether it was just created or already known. 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 07408aa5..c46b7309 100644 --- a/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/NostrRepository.kt +++ b/composeApp/src/commonMain/kotlin/mobi/giza/compose/repository/NostrRepository.kt @@ -57,6 +57,14 @@ 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. + */ + suspend fun resumeRunningCeremonies(activeKeyPair: KeyPair): Int + suspend fun createNewProfile( publicKey: HexKey, name: String?, @@ -265,6 +273,8 @@ interface NostrRepository { override suspend fun reopenInbox(activeKeyPair: KeyPair): Int = 0 + override suspend fun resumeRunningCeremonies(activeKeyPair: KeyPair): Int = 0 + override suspend fun observePendingSynchronizeNostrEventRequests(ownerPublicKey: HexKey): Flow { TODO("Not yet implemented") } 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 21fd8b89..499bce82 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 @@ -237,6 +237,15 @@ class SynchronizationViewModel( runCatching { nostrRepository.reopenInbox(keyPair) } .onSuccess { if (it > 0) logger.i { "Reopened $it gift wrap(s) that arrived while this profile was not open" } } .onFailure { logger.e("Could not reopen the inbox", it) } + // A key ceremony moves when a message arrives, and nothing + // else moves it now that its members are not asked to. + // One that already holds what it needs -- an older build + // left it waiting on a tap, or the app died between storing + // 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. + runCatching { nostrRepository.resumeRunningCeremonies(keyPair) } + .onFailure { logger.e("Could not resume running key ceremonies", 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/CeremonyNetwork.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyNetwork.kt index 9790809d..f576e6c2 100644 --- a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyNetwork.kt +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyNetwork.kt @@ -111,6 +111,10 @@ class CeremonyNetwork private constructor( nostrPrivateKey = device.privateKey, ) + /** What the app does once per activation; see `ChillDkgRitualManager.resumeRunning`. */ + suspend fun resume(device: Device): Int = + ChillDkgRitualManager.resumeRunning(device.db, device.publicKey, device.privateKey) + /** * Hands every message queued so far to every device that has not had it. * Returns how many handings there were, so a caller can tell a quiet network. diff --git a/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyResumeJvmTest.kt b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyResumeJvmTest.kt new file mode 100644 index 00000000..6a2a9ead --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/mobi/giza/compose/managers/CeremonyResumeJvmTest.kt @@ -0,0 +1,137 @@ +package mobi.giza.compose.managers + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlinx.coroutines.runBlocking +import mobi.giza.compose.database.model.DkgParticipantMessage +import mobi.giza.compose.database.model.types.DkgApprovalStep +import mobi.giza.compose.database.model.types.DkgRitualStage +import mobi.giza.compose.extensions.toHex +import mobi.giza.compose.nostr.dkg.DkgRitualEvents + +/** + * A ceremony that holds everything it needs and will be sent nothing more moves + * when the app starts, not never. + * + * Until rounds 1 and 2 stopped being asked about, a member's tap was the other + * thing besides an arriving message that ran a ritual. The sweep is what replaces + * it -- docs/automatic-key-ceremony.md, Phase 3. + */ +class CeremonyResumeJvmTest { + + /** + * Where a build that still asked leaves a ceremony: every member joined, every + * host key on every device, everybody waiting to be asked to contribute. No + * message is outstanding, so nothing arriving will ever move it. + */ + private suspend fun pausedByAnOlderBuild(network: CeremonyNetwork): String { + val session = network.propose(threshold = 2) + network.deliverUntilQuiet() + + val hostKeys = network.devices.associate { device -> + device.publicKey to ChillDkgRitualManager.deriveHostPublicKey(device.privateKey).value.toHex() + } + + network.devices.forEach { device -> + val theirs = assertNotNull(network.session(device, session.id)) + device.db.dkgSessionDao().upsert( + theirs.copy( + hostKeyApprovedAt = theirs.hostKeyApprovedAt ?: Clock.System.now(), + approvalRequestedThrough = DkgApprovalStep.ROUND_1, + ) + ) + hostKeys.forEach { (participant, hostKey) -> + device.db.dkgSessionDao().upsert( + DkgParticipantMessage( + sessionId = session.id, + participantPublicKey = participant, + kind = DkgRitualEvents.HOST_KEY, + payload = hostKey, + ) + ) + } + } + + return session.id + } + + @Test + fun `a ceremony an older build left waiting finishes from the sweep alone`(): Unit = runBlocking { + CeremonyNetwork.nip17(size = 3).use { network -> + val sessionId = pausedByAnOlderBuild(network) + + assertEquals(0, network.deliver(), "nothing is on its way to anybody") + network.devices.forEach { device -> + assertEquals(DkgRitualStage.COLLECTING_HOST_KEYS, network.session(device, sessionId)!!.stage) + } + + network.devices.forEach { device -> + assertEquals(1, network.resume(device), "$device has one ceremony to resume") + } + network.deliverUntilQuiet() + + val keys = network.devices.map { device -> + val theirs = assertNotNull(network.session(device, sessionId)) + assertEquals(DkgRitualStage.COMPLETE, theirs.stage, "$device: ${theirs.failureReason}") + assertNotNull(theirs.thresholdPublicKey) + } + assertEquals(1, keys.toSet().size) + + network.devices.forEach { device -> + assertEquals(0, network.resume(device), "a finished ceremony is not resumed") + } + } + } + + @Test + fun `sweeping twice publishes nothing twice`(): Unit = runBlocking { + CeremonyNetwork.nip17(size = 3).use { network -> + val sessionId = pausedByAnOlderBuild(network) + + network.devices.forEach { network.resume(it) } + network.devices.forEach { network.resume(it) } + + network.devices.forEach { device -> + assertEquals( + 1, + network.sent(device, DkgRitualEvents.ROUND_1).size, + "$device contributed once", + ) + } + assertTrue(network.session(network.coordinator, sessionId) != null) + } + } + + /** Nothing goes out for a member who has not agreed to take part. */ + @Test + fun `a ceremony nobody here joined is left alone`(): Unit = runBlocking { + CeremonyNetwork.nip17(size = 3).use { network -> + val member = network.devices[1] + val session = network.propose(threshold = 2) + network.deliverUntilQuiet() + + assertEquals(0, network.resume(member)) + assertTrue(network.sent(member, DkgRitualEvents.HOST_KEY).isEmpty()) + assertEquals(DkgApprovalStep.HOST_KEY, network.pendingApproval(member, session.id)) + } + } + + @Test + fun `an abandoned ceremony is not resumed`(): Unit = runBlocking { + CeremonyNetwork.nip17(size = 3).use { network -> + val session = network.propose(threshold = 2) + network.deliverUntilQuiet() + + ChillDkgRitualManager.abandon( + database = network.coordinator.db, + localChatRoom = network.room(network.coordinator), + sessionId = session.id, + ) + + assertEquals(0, network.resume(network.coordinator)) + } + } +}