feat: running key ceremonies resume when the app starts (automatic ceremony, Phase 3)
A ritual moved on an arriving message or a member's tap. Without the tap, a ceremony holding every message it needs -- one an older build left waiting to be told to contribute, or one interrupted between storing a message and acting on it -- would never move. resumeRunning advances every ceremony this user has joined. Sync runs it once per activation, after reopening the inbox. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ca5cda81db
commit
9278ccd54e
7 files changed
+232
No files matched your search
@@ -156,6 +156,20 @@ interface DkgSessionDao {
|
||||
@Query("SELECT * FROM DkgSession WHERE parentChatRoomId = :parentChatRoomId ORDER BY createdAt DESC")
|
||||
suspend fun getByParentChatRoomId(parentChatRoomId: String): List<DkgSession>
|
||||
|
||||
/**
|
||||
* 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<DkgSession>
|
||||
|
||||
@Upsert
|
||||
suspend fun upsert(dkgSession: DkgSession)
|
||||
|
||||
|
||||
+16
@@ -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?,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<SynchronizeNostrEventRequest?> {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
+9
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user