feat: storage for a group's direct messages, schema 45 (group-threshold-ecdh, Phase 4)

GroupEcdhRound, GroupEcdhPartial, GroupConversationKey, GroupDmWrap,
GroupDmMessage and GroupDmOutbound, by AutoMigration(44, 45). Redelivery of a
partial, wrap or rumor is a no-op; wiping a room takes its kept keys with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-22 11:23:56 +02:00
1 parent fcdc2db78e
commit 42ebfc4568
6 files changed
+6824 -4

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -23,6 +23,7 @@ import mobi.giza.compose.database.dao.FrostSigningSessionDao
import mobi.giza.compose.database.dao.GiftWrapMessageDao
import mobi.giza.compose.database.dao.GiftWrapPayloadDao
import mobi.giza.compose.database.dao.GiftWrapSealDao
import mobi.giza.compose.database.dao.GroupDmDao
import mobi.giza.compose.database.dao.GroupKeyStateDao
import mobi.giza.compose.database.dao.GroupSignedEventDao
import mobi.giza.compose.database.dao.InReplyToRelationDao
@@ -67,6 +68,12 @@ import mobi.giza.compose.database.model.ChatMessageBroadcastNostrEventRequestRel
import mobi.giza.compose.database.model.ChatMessageNostrEventRelation
import mobi.giza.compose.database.model.ChatRoom
import mobi.giza.compose.database.model.Confederation
import mobi.giza.compose.database.model.GroupConversationKey
import mobi.giza.compose.database.model.GroupDmMessage
import mobi.giza.compose.database.model.GroupDmOutbound
import mobi.giza.compose.database.model.GroupDmWrap
import mobi.giza.compose.database.model.GroupEcdhPartial
import mobi.giza.compose.database.model.GroupEcdhRound
import mobi.giza.compose.database.model.ConfederationCeremony
import mobi.giza.compose.database.model.ConfederationMember
import mobi.giza.compose.database.model.ConfederationCeremonyMessage
@@ -150,6 +157,12 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
GiftWrapMessage::class,
GiftWrapSeal::class,
GiftWrapPayload::class,
GroupConversationKey::class,
GroupDmMessage::class,
GroupDmOutbound::class,
GroupDmWrap::class,
GroupEcdhPartial::class,
GroupEcdhRound::class,
GroupKeyState::class,
GroupSignedEvent::class,
KeyShareGeneration::class,
@@ -189,7 +202,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
UnsignedNostrEvent::class,
Zap::class
],
version = 44,
version = 45,
autoMigrations = [
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
// generate the migration itself — nothing existing changes shape.
@@ -461,6 +474,10 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
// Phases 11 and 12): ConfederationCeremony, ConfederationCeremonyMessage, Confederation
// and ConfederationMember. New tables only, so Room generates it.
AutoMigration(from = 43, to = 44),
// v45 adds a group's direct messages (docs/group-threshold-ecdh.md, Phase 4):
// GroupEcdhRound, GroupEcdhPartial, GroupConversationKey, GroupDmWrap, GroupDmMessage
// and GroupDmOutbound. New tables only, so Room generates it.
AutoMigration(from = 44, to = 45),
]
)
@ConstructedBy(GizaDatabaseConstructor::class)
@@ -495,6 +512,8 @@ abstract class GizaDatabase: RoomDatabase() {
abstract fun frostSigningSessionDao(): FrostSigningSessionDao
abstract fun groupDmDao(): GroupDmDao
abstract fun groupKeyStateDao(): GroupKeyStateDao
abstract fun keyShareDao(): KeyShareDao
@@ -0,0 +1,162 @@
package mobi.giza.compose.database.dao
import androidx.room3.Dao
import androidx.room3.Insert
import androidx.room3.OnConflictStrategy
import androidx.room3.Query
import androidx.room3.Transaction
import androidx.room3.Upsert
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlin.time.Instant
import kotlinx.coroutines.flow.Flow
import mobi.giza.compose.database.model.GroupConversationKey
import mobi.giza.compose.database.model.GroupDmMessage
import mobi.giza.compose.database.model.GroupDmOutbound
import mobi.giza.compose.database.model.GroupDmWrap
import mobi.giza.compose.database.model.GroupEcdhPartial
import mobi.giza.compose.database.model.GroupEcdhRound
/** A group's direct messages and the rounds that open them (docs/group-threshold-ecdh.md, Phase 4). */
@Dao
abstract class GroupDmDao {
// --- rounds
@Query("SELECT * FROM GroupEcdhRound WHERE id = :id")
abstract suspend fun getRound(id: HexKey): GroupEcdhRound?
@Query("SELECT * FROM GroupEcdhRound WHERE chatRoomId = :chatRoomId AND state = 'OPEN'")
abstract suspend fun getOpenRounds(chatRoomId: HexKey): List<GroupEcdhRound>
@Query("SELECT * FROM GroupEcdhRound WHERE chatRoomId = :chatRoomId AND state = 'OPEN'")
abstract fun observeOpenRounds(chatRoomId: HexKey): Flow<List<GroupEcdhRound>>
@Query("SELECT * FROM GroupEcdhRound WHERE state = 'OPEN'")
abstract suspend fun getAllOpenRounds(): List<GroupEcdhRound>
@Query("SELECT COUNT(*) FROM GroupEcdhRound WHERE chatRoomId = :chatRoomId AND purpose = 'WRAP' AND openedAt >= :since")
abstract suspend fun countWrapRoundsSince(chatRoomId: HexKey, since: Instant): Int
/** Once per round: two devices opening the same wrap open the same round. */
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract suspend fun insertRound(round: GroupEcdhRound): Long
@Upsert
abstract suspend fun upsertRound(round: GroupEcdhRound)
// --- partials
@Query("SELECT * FROM GroupEcdhPartial WHERE roundId = :roundId")
abstract suspend fun getPartials(roundId: HexKey): List<GroupEcdhPartial>
@Query("SELECT * FROM GroupEcdhPartial WHERE roundId IN (SELECT id FROM GroupEcdhRound WHERE chatRoomId = :chatRoomId AND state = 'OPEN')")
abstract fun observeOpenPartials(chatRoomId: HexKey): Flow<List<GroupEcdhPartial>>
/** Once per round and participant: redelivery is a no-op, as `DkgParticipantMessage` absorbs it. */
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract suspend fun insertPartial(partial: GroupEcdhPartial): Long
@Upsert
abstract suspend fun upsertPartial(partial: GroupEcdhPartial)
// --- kept conversation keys
@Query("SELECT * FROM GroupConversationKey WHERE chatRoomId = :chatRoomId AND peer = :peer")
abstract suspend fun getConversationKey(chatRoomId: HexKey, peer: HexKey): GroupConversationKey?
@Query("SELECT * FROM GroupConversationKey WHERE chatRoomId = :chatRoomId")
abstract suspend fun getConversationKeys(chatRoomId: HexKey): List<GroupConversationKey>
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract suspend fun insertConversationKey(key: GroupConversationKey): Long
// --- the wrap ledger
@Query("SELECT * FROM GroupDmWrap WHERE id = :id")
abstract suspend fun getWrap(id: HexKey): GroupDmWrap?
@Query("SELECT * FROM GroupDmWrap WHERE chatRoomId = :chatRoomId AND state = :state ORDER BY createdAt DESC")
abstract suspend fun getWrapsInState(chatRoomId: HexKey, state: String): List<GroupDmWrap>
@Query("SELECT * FROM GroupDmWrap WHERE chatRoomId = :chatRoomId AND state IN ('WAITING', 'QUEUED') ORDER BY createdAt DESC")
abstract fun observePendingWraps(chatRoomId: HexKey): Flow<List<GroupDmWrap>>
@Query("SELECT MAX(createdAt) FROM GroupDmWrap WHERE chatRoomId = :chatRoomId")
abstract suspend fun newestWrapCreatedAt(chatRoomId: HexKey): Instant?
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract suspend fun insertWrap(wrap: GroupDmWrap): Long
@Upsert
abstract suspend fun upsertWrap(wrap: GroupDmWrap)
// --- messages
@Query("SELECT * FROM GroupDmMessage WHERE rumorId = :rumorId")
abstract suspend fun getMessage(rumorId: HexKey): GroupDmMessage?
@Query("SELECT * FROM GroupDmMessage WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC")
abstract fun observeMessages(chatRoomId: HexKey): Flow<List<GroupDmMessage>>
@Query("SELECT * FROM GroupDmMessage WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId ORDER BY createdAt ASC")
abstract fun observeConversation(chatRoomId: HexKey, conversationId: HexKey): Flow<List<GroupDmMessage>>
@Query("SELECT * FROM GroupDmMessage WHERE chatRoomId = :chatRoomId")
abstract suspend fun getMessages(chatRoomId: HexKey): List<GroupDmMessage>
@Query("SELECT COUNT(*) FROM GroupDmMessage WHERE chatRoomId = :chatRoomId AND outgoing = 0 AND readAt IS NULL")
abstract fun observeUnreadCount(chatRoomId: HexKey): Flow<Int>
@Query("UPDATE GroupDmMessage SET readAt = :at WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId AND readAt IS NULL")
abstract suspend fun markRead(chatRoomId: HexKey, conversationId: HexKey, at: Instant)
/** Once per rumor: the same rumor in two wraps is one message. */
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract suspend fun insertMessage(message: GroupDmMessage): Long
// --- what the group owes recipients
@Query("SELECT * FROM GroupDmOutbound WHERE publishedAt IS NULL")
abstract suspend fun getOwed(): List<GroupDmOutbound>
@Query("SELECT * FROM GroupDmOutbound WHERE signingSessionId = :signingSessionId")
abstract suspend fun getOutbound(signingSessionId: String): List<GroupDmOutbound>
@Query("SELECT * FROM GroupDmOutbound WHERE chatRoomId = :chatRoomId")
abstract fun observeOutbound(chatRoomId: HexKey): Flow<List<GroupDmOutbound>>
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract suspend fun insertOutbound(outbound: GroupDmOutbound): Long
@Upsert
abstract suspend fun upsertOutbound(outbound: GroupDmOutbound)
// --- wiping
@Query("DELETE FROM GroupConversationKey WHERE chatRoomId = :chatRoomId")
abstract suspend fun deleteConversationKeys(chatRoomId: HexKey)
@Query("DELETE FROM GroupDmMessage WHERE chatRoomId = :chatRoomId")
abstract suspend fun deleteMessages(chatRoomId: HexKey)
@Query("DELETE FROM GroupDmWrap WHERE chatRoomId = :chatRoomId")
abstract suspend fun deleteWraps(chatRoomId: HexKey)
@Query("DELETE FROM GroupEcdhRound WHERE chatRoomId = :chatRoomId")
abstract suspend fun deleteRounds(chatRoomId: HexKey)
@Query("DELETE FROM GroupDmOutbound WHERE chatRoomId = :chatRoomId")
abstract suspend fun deleteOutbound(chatRoomId: HexKey)
/**
* Everything this device holds of a room's mail: its kept keys, what it opened, and the
* rounds in flight (D14). Cooperation, not enforcement: what was read stays read.
*/
@Transaction
open suspend fun wipeRoom(chatRoomId: HexKey) {
deleteConversationKeys(chatRoomId)
deleteMessages(chatRoomId)
deleteWraps(chatRoomId)
deleteRounds(chatRoomId)
deleteOutbound(chatRoomId)
}
}
@@ -0,0 +1,170 @@
package mobi.giza.compose.database.model
import androidx.room3.Entity
import androidx.room3.ForeignKey
import androidx.room3.Index
import androidx.room3.PrimaryKey
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import kotlin.time.Clock
import kotlin.time.Instant
import mobi.giza.compose.nostr.groupdm.EcdhPurpose
/*
* A group's direct messages, by threshold ECDH (docs/group-threshold-ecdh.md, Phase 4).
*
* None of this writes a GiftWrapMessage, GiftWrapPayload or NostrEvent row: the group's mail
* is its own pipeline (D9), and the personal one is built around one identity.
*/
/** Where a round has got to. */
enum class GroupEcdhRoundState { OPEN, COMBINED, FAILED }
/**
* One point the admins are multiplying their shares by: `(room, generation, P)`, its id a hash
* of the three, so two devices that open a round for the same wrap open the same round (D11).
*/
@Entity(
foreignKeys = [
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
],
indices = [Index("chatRoomId"), Index("point")],
)
data class GroupEcdhRound(
@PrimaryKey
val id: HexKey,
val chatRoomId: HexKey,
val generation: Int,
/** The x-only key multiplied. */
val point: HexKey,
val purpose: EcdhPurpose,
/** A wrap or a seal is named by the wrap's id. */
val ref: HexKey? = null,
/** A recipient's evidence, as JSON: the only evidence that travels whole. */
val evidenceJson: String? = null,
val state: GroupEcdhRoundState = GroupEcdhRoundState.OPEN,
/** When this device's own partial went out; null while it is owed or not yet answerable. */
val partialSentAt: Instant? = null,
val openedAt: Instant = Clock.System.now(),
val combinedAt: Instant? = null,
)
/** One holder's partial for a round, once per participant id: redelivery is a no-op. */
@Entity(
primaryKeys = ["roundId", "participantId"],
foreignKeys = [
ForeignKey(entity = GroupEcdhRound::class, parentColumns = ["id"], childColumns = ["roundId"], onDelete = ForeignKey.CASCADE)
],
)
data class GroupEcdhPartial(
val roundId: HexKey,
val participantId: Int,
val senderPublicKey: HexKey,
/** `Dᵢ`, compressed. */
val partial: String,
val proof: String,
/** False for a partial whose proof failed: kept so its sender is named once. */
val verified: Boolean,
/** When this device published the round's failure naming this participant. */
val blamedAt: Instant? = null,
val receivedAt: Instant = Clock.System.now(),
)
/**
* The conversation key between the group and one correspondent, kept so their next message
* costs one round instead of two, and writing to them costs none (D6). A secret: wiped with the
* room's shares, and on this device's member being removed as an admin (D14).
*/
@Entity(
primaryKeys = ["chatRoomId", "peer"],
foreignKeys = [
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
],
)
data class GroupConversationKey(
val chatRoomId: HexKey,
val peer: HexKey,
val conversationKey: String,
val roundId: HexKey,
val computedAt: Instant = Clock.System.now(),
) {
override fun toString(): String = "GroupConversationKey(chatRoomId=$chatRoomId, peer=$peer, conversationKey=<secret>)"
}
/** Where a wrap to the group has got to. */
enum class GroupDmWrapState {
/** Waiting on the admins: its wrap round, or its seal's. */
WAITING,
/** Beyond this hour's rate cap; opened newest first when there is room (Phase 7). */
QUEUED,
OPENED,
/** The combined key did not open it, or what was inside was not a seal with a rumor. */
UNREADABLE,
}
/** The ledger of wraps addressed to the group's npub, keyed by id: redelivery is a no-op. */
@Entity(
foreignKeys = [
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
],
indices = [Index("chatRoomId"), Index("state")],
)
data class GroupDmWrap(
@PrimaryKey
val id: HexKey,
val chatRoomId: HexKey,
val wrapJson: String,
/** The wrap's own created_at, back-dated by up to two days as NIP-59 does. */
val createdAt: Instant,
val state: GroupDmWrapState = GroupDmWrapState.WAITING,
/** The seal, once the wrap round combined: it is the seal round's evidence. */
val sealJson: String? = null,
val receivedAt: Instant = Clock.System.now(),
)
/** A message in one of the group's conversations, in or out, keyed by rumor id. */
@Entity(
foreignKeys = [
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
],
indices = [Index("chatRoomId"), Index("conversationId")],
)
data class GroupDmMessage(
@PrimaryKey
val rumorId: HexKey,
val chatRoomId: HexKey,
val conversationId: HexKey,
val senderPublicKey: HexKey,
val rumorJson: String,
val createdAt: Instant,
val outgoing: Boolean,
/** The wrap it came in, for a message the group was sent. */
val wrapId: HexKey? = null,
/** The signing session it went out in, for a message the group sent. */
val signingSessionId: String? = null,
val readAt: Instant? = null,
val filedAt: Instant = Clock.System.now(),
)
/** One recipient's copy of a message the group signed, owed until a relay takes it (D10). */
@Entity(
primaryKeys = ["signingSessionId", "sealId"],
foreignKeys = [
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
],
indices = [Index("chatRoomId")],
)
data class GroupDmOutbound(
val signingSessionId: String,
val sealId: HexKey,
val chatRoomId: HexKey,
val recipient: HexKey,
/** Comma-separated: the recipient's 10050, or the publish set when there is none. */
val relays: String,
/** The wrap, built once so every retry sends the same event. */
val wrapJson: String? = null,
val publishedAt: Instant? = null,
val attempts: Int = 0,
val nextAttemptAt: Instant? = null,
)
@@ -0,0 +1,74 @@
package mobi.giza.compose.database.dao
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.time.Instant
import kotlinx.coroutines.runBlocking
import mobi.giza.compose.database.model.GroupConversationKey
import mobi.giza.compose.database.model.GroupDmMessage
import mobi.giza.compose.database.model.GroupDmWrap
import mobi.giza.compose.database.model.GroupEcdhPartial
import mobi.giza.compose.database.model.GroupEcdhRound
import mobi.giza.compose.managers.SigningProposalHarness
import mobi.giza.compose.nostr.groupdm.EcdhPurpose
/**
* Phase 4 of docs/group-threshold-ecdh.md: redelivery of a partial, a wrap or a rumor changes
* nothing, and wiping a room takes its kept keys and its mail with it.
*/
class GroupDmStorageJvmTest {
private val harness = SigningProposalHarness()
@AfterTest
fun close() = harness.close()
private val roundId = "r".repeat(64).replace('r', '1')
@Test
fun `redelivery is a no-op`() = runBlocking {
val db = harness.openDevice(harness.members[0])
val dao = db.groupDmDao()
val round = GroupEcdhRound(id = roundId, chatRoomId = harness.roomId, generation = 0, point = "a".repeat(64), purpose = EcdhPurpose.WRAP, ref = "b".repeat(64))
assertEquals(true, dao.insertRound(round) > 0)
assertEquals(-1L, dao.insertRound(round.copy(point = "c".repeat(64))), "the same round, not a second")
assertEquals("a".repeat(64), dao.getRound(roundId)?.point)
val partial = GroupEcdhPartial(roundId, 1, harness.members[1], "02" + "d".repeat(64), "e".repeat(128), verified = true)
assertEquals(true, dao.insertPartial(partial) > 0)
assertEquals(-1L, dao.insertPartial(partial.copy(partial = "03" + "f".repeat(64))))
assertEquals(listOf("02" + "d".repeat(64)), dao.getPartials(roundId).map { it.partial })
val wrap = GroupDmWrap(id = "b".repeat(64), chatRoomId = harness.roomId, wrapJson = "{}", createdAt = Instant.fromEpochSeconds(1))
assertEquals(true, dao.insertWrap(wrap) > 0)
assertEquals(-1L, dao.insertWrap(wrap))
val message = GroupDmMessage("9".repeat(64), harness.roomId, "c".repeat(64), "a".repeat(64), "{}", Instant.fromEpochSeconds(2), outgoing = false, wrapId = wrap.id)
assertEquals(true, dao.insertMessage(message) > 0)
assertEquals(-1L, dao.insertMessage(message.copy(wrapId = "8".repeat(64))), "the same rumor in another wrap")
assertEquals(wrap.id, dao.getMessage(message.rumorId)?.wrapId)
}
@Test
fun `wiping a room removes its keys, its mail and its rounds`() = runBlocking {
val db = harness.openDevice(harness.members[0])
val dao = db.groupDmDao()
dao.insertRound(GroupEcdhRound(id = roundId, chatRoomId = harness.roomId, generation = 0, point = "a".repeat(64), purpose = EcdhPurpose.SEAL, ref = "b".repeat(64)))
dao.insertPartial(GroupEcdhPartial(roundId, 1, harness.members[1], "02" + "d".repeat(64), "e".repeat(128), verified = true))
dao.insertConversationKey(GroupConversationKey(harness.roomId, "a".repeat(64), "5".repeat(64), roundId))
dao.insertWrap(GroupDmWrap(id = "b".repeat(64), chatRoomId = harness.roomId, wrapJson = "{}", createdAt = Instant.fromEpochSeconds(1)))
dao.insertMessage(GroupDmMessage("9".repeat(64), harness.roomId, "c".repeat(64), "a".repeat(64), "{}", Instant.fromEpochSeconds(2), outgoing = false))
assertNotNull(dao.getConversationKey(harness.roomId, "a".repeat(64)))
assertEquals(false, dao.getConversationKey(harness.roomId, "a".repeat(64)).toString().contains("5555"), "a kept key never prints")
dao.wipeRoom(harness.roomId)
assertNull(dao.getConversationKey(harness.roomId, "a".repeat(64)))
assertEquals(emptyList(), dao.getMessages(harness.roomId))
assertNull(dao.getWrap("b".repeat(64)))
assertNull(dao.getRound(roundId))
assertEquals(emptyList(), dao.getPartials(roundId))
}
}
@@ -66,10 +66,11 @@ class ShippedProfileUpgradeJvmTest {
* refresh and 40 for share repair (docs/frost-share-refresh.md, Phases 6, 7 and
* 10), 41 for governance proposals and 42 for what follows them
* (docs/member-admin-promotion.md, Phases 5, 8 and 9), 43 for the confederation
* (docs/confederation.md, Phase 4) and 44 for its key ceremony (Phase 11), so the upgrade
* crosses eight generated migrations and the file has to come out at the last.
* (docs/confederation.md, Phase 4), 44 for its key ceremony (Phase 11) and 45 for a
* group's direct messages (docs/group-threshold-ecdh.md, Phase 4), so the upgrade crosses
* nine generated migrations and the file has to come out at the last.
*/
private val current = 44
private val current = 45
private val directory: File = Files.createTempDirectory("giza-shipped-profile").toFile()
private val file: File = File(directory, "aux.db")