feat: where a group's inbox is kept, schema 44 to 45 (group-inbox, Phase 3)
InboxKeyCeremony, InboxKeyCeremonyMessage and InboxKey, apart from DkgSession so no signing path can find a threshold-1 key; and GroupInboxWrap (the ledger, opened or not), GroupInboxMessage (one row per rumor) and GroupInboxPublication (what this device owes relays). New tables only, so an AutoMigration. InboxStorageJvmTest pins redelivery, the wipe and that the signing lookups see none of it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e215cff843
commit
1f66c39f2f
8 files changed
+7042
-4
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -25,6 +25,8 @@ import mobi.giza.compose.database.dao.GiftWrapPayloadDao
|
||||
import mobi.giza.compose.database.dao.GiftWrapSealDao
|
||||
import mobi.giza.compose.database.dao.GroupKeyStateDao
|
||||
import mobi.giza.compose.database.dao.GroupSignedEventDao
|
||||
import mobi.giza.compose.database.dao.GroupInboxDao
|
||||
import mobi.giza.compose.database.dao.InboxKeyDao
|
||||
import mobi.giza.compose.database.dao.InReplyToRelationDao
|
||||
import mobi.giza.compose.database.dao.KeyShareDao
|
||||
import mobi.giza.compose.database.dao.ShareRefreshDao
|
||||
@@ -112,6 +114,12 @@ import mobi.giza.compose.database.model.Reaction
|
||||
import mobi.giza.compose.database.model.RecentSearch
|
||||
import mobi.giza.compose.database.model.DkgParticipantMessage
|
||||
import mobi.giza.compose.database.model.DkgSession
|
||||
import mobi.giza.compose.database.model.GroupInboxMessage
|
||||
import mobi.giza.compose.database.model.GroupInboxPublication
|
||||
import mobi.giza.compose.database.model.GroupInboxWrap
|
||||
import mobi.giza.compose.database.model.InboxKey
|
||||
import mobi.giza.compose.database.model.InboxKeyCeremony
|
||||
import mobi.giza.compose.database.model.InboxKeyCeremonyMessage
|
||||
import mobi.giza.compose.database.model.FrostSignerMessage
|
||||
import mobi.giza.compose.database.model.FrostSigningItem
|
||||
import mobi.giza.compose.database.model.FrostSigningSession
|
||||
@@ -150,8 +158,14 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
GiftWrapMessage::class,
|
||||
GiftWrapSeal::class,
|
||||
GiftWrapPayload::class,
|
||||
GroupInboxMessage::class,
|
||||
GroupInboxPublication::class,
|
||||
GroupInboxWrap::class,
|
||||
GroupKeyState::class,
|
||||
GroupSignedEvent::class,
|
||||
InboxKey::class,
|
||||
InboxKeyCeremony::class,
|
||||
InboxKeyCeremonyMessage::class,
|
||||
KeyShareGeneration::class,
|
||||
KeyShareMember::class,
|
||||
ShareRefreshConfirmation::class,
|
||||
@@ -189,7 +203,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 +475,11 @@ 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 the group's inbox (docs/group-inbox.md, Phase 3): InboxKeyCeremony,
|
||||
// InboxKeyCeremonyMessage and InboxKey, kept apart from DkgSession so no signing path
|
||||
// can find a threshold-1 key, and GroupInboxWrap, GroupInboxMessage and
|
||||
// GroupInboxPublication. New tables only, so Room generates it.
|
||||
AutoMigration(from = 44, to = 45),
|
||||
]
|
||||
)
|
||||
@ConstructedBy(GizaDatabaseConstructor::class)
|
||||
@@ -506,6 +525,10 @@ abstract class GizaDatabase: RoomDatabase() {
|
||||
|
||||
abstract fun groupSignedEventDao(): GroupSignedEventDao
|
||||
|
||||
abstract fun inboxKeyDao(): InboxKeyDao
|
||||
|
||||
abstract fun groupInboxDao(): GroupInboxDao
|
||||
|
||||
|
||||
|
||||
abstract fun connectionDao(): ConnectionDao
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
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.Upsert
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import mobi.giza.compose.database.model.GroupInboxMessage
|
||||
import mobi.giza.compose.database.model.GroupInboxPublication
|
||||
import mobi.giza.compose.database.model.GroupInboxWrap
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** What a group's inbox has received, filed and owes relays (docs/group-inbox.md, Phase 3). */
|
||||
@Dao
|
||||
interface GroupInboxDao {
|
||||
/** The ledger is keyed by the wrap's id: a second copy of one changes nothing. */
|
||||
@Insert(onConflict = OnConflictStrategy.IGNORE)
|
||||
suspend fun insertWrap(wrap: GroupInboxWrap): Long
|
||||
|
||||
@Query("SELECT * FROM GroupInboxWrap WHERE id = :id")
|
||||
suspend fun getWrap(id: HexKey): GroupInboxWrap?
|
||||
|
||||
@Query("SELECT * FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId AND openedGeneration IS NULL ORDER BY receivedAt")
|
||||
suspend fun getUnopenedWraps(chatRoomId: String): List<GroupInboxWrap>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId AND openedGeneration IS NULL")
|
||||
fun observeUnopenedCount(chatRoomId: String): Flow<Int>
|
||||
|
||||
/** The newest wrap's own time in a room: where a catch-up starts, less NIP-59's two days. */
|
||||
@Query("SELECT MAX(wrapCreatedAt) FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId")
|
||||
suspend fun newestWrapCreatedAt(chatRoomId: String): Long?
|
||||
|
||||
@Query("UPDATE GroupInboxWrap SET openedGeneration = :generation WHERE id = :id")
|
||||
suspend fun markOpened(id: HexKey, generation: Int)
|
||||
|
||||
/** Keyed by room and rumor: two wraps of one rumor are one message, and the first is kept. */
|
||||
@Insert(onConflict = OnConflictStrategy.IGNORE)
|
||||
suspend fun insertMessage(message: GroupInboxMessage): Long
|
||||
|
||||
@Query("SELECT * FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId AND rumorId = :rumorId")
|
||||
suspend fun getMessage(chatRoomId: String, rumorId: HexKey): GroupInboxMessage?
|
||||
|
||||
@Query("SELECT * FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC")
|
||||
fun observeMessages(chatRoomId: String): Flow<List<GroupInboxMessage>>
|
||||
|
||||
@Query("SELECT * FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC")
|
||||
suspend fun getMessages(chatRoomId: String): List<GroupInboxMessage>
|
||||
|
||||
@Query("SELECT * FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId ORDER BY createdAt ASC")
|
||||
fun observeConversation(chatRoomId: String, conversationId: String): Flow<List<GroupInboxMessage>>
|
||||
|
||||
@Query("SELECT * FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId ORDER BY createdAt ASC")
|
||||
suspend fun getConversation(chatRoomId: String, conversationId: String): List<GroupInboxMessage>
|
||||
|
||||
@Query("SELECT COUNT(*) FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId AND outgoing = 0 AND readAt IS NULL")
|
||||
fun observeUnreadCount(chatRoomId: String): Flow<Int>
|
||||
|
||||
@Query("UPDATE GroupInboxMessage SET readAt = :at WHERE chatRoomId = :chatRoomId AND conversationId = :conversationId AND readAt IS NULL")
|
||||
suspend fun markConversationRead(chatRoomId: String, conversationId: String, at: Instant)
|
||||
|
||||
@Query("DELETE FROM GroupInboxMessage WHERE chatRoomId = :chatRoomId")
|
||||
suspend fun deleteMessages(chatRoomId: String)
|
||||
|
||||
@Query("DELETE FROM GroupInboxWrap WHERE chatRoomId = :chatRoomId")
|
||||
suspend fun deleteWraps(chatRoomId: String)
|
||||
|
||||
@Upsert
|
||||
suspend fun upsertPublication(publication: GroupInboxPublication)
|
||||
|
||||
@Query("SELECT * FROM GroupInboxPublication WHERE eventId = :eventId")
|
||||
suspend fun getPublication(eventId: HexKey): GroupInboxPublication?
|
||||
|
||||
/** What is still owed and due by [now], oldest first. */
|
||||
@Query("SELECT * FROM GroupInboxPublication WHERE publishedAt IS NULL AND (nextAttemptAt IS NULL OR nextAttemptAt <= :now) ORDER BY createdAt")
|
||||
suspend fun getDuePublications(now: Instant): List<GroupInboxPublication>
|
||||
|
||||
@Query("SELECT * FROM GroupInboxPublication WHERE signingSessionId = :signingSessionId")
|
||||
suspend fun getPublicationsFor(signingSessionId: String): List<GroupInboxPublication>
|
||||
|
||||
@Query("SELECT * FROM GroupInboxPublication WHERE signingSessionId = :signingSessionId")
|
||||
fun observePublicationsFor(signingSessionId: String): Flow<List<GroupInboxPublication>>
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
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.Upsert
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Kind
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import mobi.giza.compose.database.model.InboxKey
|
||||
import mobi.giza.compose.database.model.InboxKeyCeremony
|
||||
import mobi.giza.compose.database.model.InboxKeyCeremonyMessage
|
||||
import kotlin.time.Instant
|
||||
|
||||
/** The group inbox's key ceremonies and the keys they leave (docs/group-inbox.md, Phase 3). */
|
||||
@Dao
|
||||
interface InboxKeyDao {
|
||||
@Query("SELECT * FROM InboxKeyCeremony WHERE id = :id")
|
||||
suspend fun getCeremony(id: String): InboxKeyCeremony?
|
||||
|
||||
@Query("SELECT * FROM InboxKeyCeremony WHERE id = :id")
|
||||
fun observeCeremony(id: String): Flow<InboxKeyCeremony?>
|
||||
|
||||
@Query("SELECT * FROM InboxKeyCeremony WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey ORDER BY createdAt DESC LIMIT 1")
|
||||
suspend fun getLatestCeremony(chatRoomId: String, userPublicKey: HexKey): InboxKeyCeremony?
|
||||
|
||||
@Query("SELECT * FROM InboxKeyCeremony WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey ORDER BY createdAt DESC LIMIT 1")
|
||||
fun observeLatestCeremony(chatRoomId: String, userPublicKey: HexKey): Flow<InboxKeyCeremony?>
|
||||
|
||||
@Query("SELECT * FROM InboxKeyCeremony WHERE userPublicKey = :userPublicKey AND stage NOT IN ('COMPLETE', 'FAILED')")
|
||||
suspend fun getRunningCeremonies(userPublicKey: HexKey): List<InboxKeyCeremony>
|
||||
|
||||
@Query("SELECT * FROM InboxKeyCeremony WHERE chatRoomId = :chatRoomId AND stage NOT IN ('COMPLETE', 'FAILED')")
|
||||
suspend fun getRunningCeremoniesIn(chatRoomId: String): List<InboxKeyCeremony>
|
||||
|
||||
@Upsert
|
||||
suspend fun upsertCeremony(ceremony: InboxKeyCeremony)
|
||||
|
||||
@Query("SELECT * FROM InboxKeyCeremonyMessage WHERE sessionId = :sessionId")
|
||||
suspend fun getMessages(sessionId: String): List<InboxKeyCeremonyMessage>
|
||||
|
||||
@Query("SELECT * FROM InboxKeyCeremonyMessage WHERE sessionId = :sessionId")
|
||||
fun observeMessages(sessionId: String): Flow<List<InboxKeyCeremonyMessage>>
|
||||
|
||||
@Query("SELECT * FROM InboxKeyCeremonyMessage WHERE sessionId = :sessionId AND senderPublicKey = :sender AND kind = :kind")
|
||||
suspend fun getMessage(sessionId: String, sender: HexKey, kind: Kind): InboxKeyCeremonyMessage?
|
||||
|
||||
/** Ignores a second copy: relays redeliver, and the first one a ceremony read is the one it used. */
|
||||
@Insert(onConflict = OnConflictStrategy.IGNORE)
|
||||
suspend fun insertMessage(message: InboxKeyCeremonyMessage): Long
|
||||
|
||||
@Query("SELECT * FROM InboxKey WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey ORDER BY generation DESC")
|
||||
suspend fun getKeys(chatRoomId: String, userPublicKey: HexKey): List<InboxKey>
|
||||
|
||||
@Query("SELECT * FROM InboxKey WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey ORDER BY generation DESC")
|
||||
fun observeKeys(chatRoomId: String, userPublicKey: HexKey): Flow<List<InboxKey>>
|
||||
|
||||
@Query("SELECT * FROM InboxKey WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey AND generation = :generation")
|
||||
suspend fun getKey(chatRoomId: String, userPublicKey: HexKey, generation: Int): InboxKey?
|
||||
|
||||
/** Every key this identity can still open mail with, in every room, newest generation first. */
|
||||
@Query("SELECT * FROM InboxKey WHERE userPublicKey = :userPublicKey AND secretKey IS NOT NULL ORDER BY chatRoomId, generation DESC")
|
||||
suspend fun getHeldKeys(userPublicKey: HexKey): List<InboxKey>
|
||||
|
||||
@Query("SELECT * FROM InboxKey WHERE userPublicKey = :userPublicKey AND secretKey IS NOT NULL ORDER BY chatRoomId, generation DESC")
|
||||
fun observeHeldKeys(userPublicKey: HexKey): Flow<List<InboxKey>>
|
||||
|
||||
/** Any key a 10044 could name in this room, held here or not: [publicKey] is public. */
|
||||
@Query("SELECT * FROM InboxKey WHERE chatRoomId = :chatRoomId AND publicKey = :publicKey LIMIT 1")
|
||||
suspend fun findByPublicKey(chatRoomId: String, publicKey: HexKey): InboxKey?
|
||||
|
||||
@Upsert
|
||||
suspend fun upsertKey(key: InboxKey)
|
||||
|
||||
@Query("UPDATE InboxKey SET secretKey = NULL, recoveryData = NULL, state = 'WIPED', wipedAt = :at WHERE chatRoomId = :chatRoomId AND userPublicKey = :userPublicKey")
|
||||
suspend fun wipeKeys(chatRoomId: String, userPublicKey: HexKey, at: Instant)
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
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 com.vitorpamplona.quartz.nip01Core.core.Kind
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* Every gift wrap addressed to a group this device keeps an inbox for, opened or not
|
||||
* (docs/group-inbox.md, D8).
|
||||
*
|
||||
* The ledger is what makes redelivery a no-op, and what lets a key that arrives later -- a
|
||||
* restore, a ceremony that finished after the mail did -- reopen what is already here. A wrap
|
||||
* no held key opens stays with [openedGeneration] null, and is counted on the inbox screen
|
||||
* rather than hidden.
|
||||
*
|
||||
* Never a `GiftWrapMessage`: those belong to the personal inbox, which would file the group's
|
||||
* correspondents into the admin's own direct messages.
|
||||
*/
|
||||
@Entity(
|
||||
foreignKeys = [
|
||||
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
|
||||
],
|
||||
indices = [Index("chatRoomId")],
|
||||
)
|
||||
data class GroupInboxWrap(
|
||||
@PrimaryKey
|
||||
val id: HexKey,
|
||||
val chatRoomId: String,
|
||||
/** The wrap as it arrived, so it can be tried again with a key this device gets later. */
|
||||
val wrapJson: String,
|
||||
/** The wrap's own `created_at`: back-dated by up to two days, as NIP-59 has it. */
|
||||
val wrapCreatedAt: Long,
|
||||
/** The inbox key generation that opened it, or null while none has. */
|
||||
val openedGeneration: Int? = null,
|
||||
val receivedAt: Instant = Clock.System.now(),
|
||||
)
|
||||
|
||||
/**
|
||||
* A message in a group's inbox, incoming or outgoing (docs/group-inbox.md, D8 and D10): one row
|
||||
* per rumor, however many wraps carried it.
|
||||
*/
|
||||
@Entity(
|
||||
primaryKeys = ["chatRoomId", "rumorId"],
|
||||
foreignKeys = [
|
||||
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
|
||||
],
|
||||
indices = [Index("chatRoomId"), Index("conversationId")],
|
||||
)
|
||||
data class GroupInboxMessage(
|
||||
val chatRoomId: String,
|
||||
/** Computed from the rumor, never taken from it. */
|
||||
val rumorId: HexKey,
|
||||
/** The first wrap it arrived in; null for an outgoing message filed before its copy came back. */
|
||||
val wrapId: HexKey?,
|
||||
/** [mobi.giza.compose.nostr.inbox.InboxConversation.idOf] over [participants]. */
|
||||
val conversationId: String,
|
||||
/** Everyone in the conversation but the group, sorted, comma-separated. */
|
||||
val participants: String,
|
||||
val senderPublicKey: HexKey,
|
||||
val kind: Kind,
|
||||
/** The rumor as NIP-59 carries it: its id and no signature. */
|
||||
val rumorJson: String,
|
||||
/** The rumor's own `created_at`, unfuzzed: when the sender says they wrote it. */
|
||||
val createdAt: Long,
|
||||
/** The inbox key generation that opened it, or sealed it if outgoing. */
|
||||
val generation: Int,
|
||||
/** Written by the group: a reply. */
|
||||
val outgoing: Boolean,
|
||||
/** The signing session a reply came from, when this device knows it. */
|
||||
val signingSessionId: String? = null,
|
||||
val readAt: Instant? = null,
|
||||
val receivedAt: Instant = Clock.System.now(),
|
||||
) {
|
||||
fun participantList(): List<HexKey> = participants.split(",").map { it.trim() }.filter { it.isNotEmpty() }
|
||||
}
|
||||
|
||||
/**
|
||||
* An event this device owes relays on the group's behalf (docs/group-inbox.md, D7 and D10): a
|
||||
* signed 10044 or 10050 the group agreed to, or a gift wrap carrying a reply it signed. Sent with
|
||||
* backoff until a relay takes it, as `ConfederationPublisher` sends confederation events.
|
||||
*
|
||||
* Never a `NostrEvent` row, for the reasons group-nostr-profile-and-posts.md D7 gives: the group's
|
||||
* events are not the feed's, and a kind 0 or 10050 there would make a profile of the group.
|
||||
*/
|
||||
@Entity(
|
||||
foreignKeys = [
|
||||
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
|
||||
],
|
||||
indices = [Index("chatRoomId"), Index("signingSessionId")],
|
||||
)
|
||||
data class GroupInboxPublication(
|
||||
@PrimaryKey
|
||||
val eventId: HexKey,
|
||||
val chatRoomId: String,
|
||||
val kind: Kind,
|
||||
val eventJson: String,
|
||||
/** Where it goes, comma-separated; the app's publish set is added to these. */
|
||||
val relays: String,
|
||||
/** The signing session it came from. */
|
||||
val signingSessionId: String?,
|
||||
/** For a wrap: who it is to. Null for the group's own announcements. */
|
||||
val recipientPublicKey: HexKey?,
|
||||
val attempts: Int = 0,
|
||||
val nextAttemptAt: Instant? = null,
|
||||
val publishedAt: Instant? = null,
|
||||
val createdAt: Instant = Clock.System.now(),
|
||||
) {
|
||||
fun relayList(): List<String> = relays.split(",").map { it.trim() }.filter { it.isNotEmpty() }
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
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 com.vitorpamplona.quartz.nip01Core.core.Kind
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* One device's part in a group's inbox key ceremony (docs/group-inbox.md, D2 and D3): ChillDKG
|
||||
* at threshold 1 over the room's admins.
|
||||
*
|
||||
* Kept apart from [DkgSession] on purpose. Every completed `DkgSession` is a key the signing
|
||||
* path may find, and a threshold-1 key there would be a key any one admin could sign as the
|
||||
* group with. Nothing that looks for a signing key reads this table.
|
||||
*
|
||||
* Inputs, never protocol state, as `DkgSession` keeps them: every step is a pure function of
|
||||
* the randomness here and the messages in [InboxKeyCeremonyMessage], so a device that dies
|
||||
* between rounds recomputes the step on the next message. The secret it produces is not kept
|
||||
* here but in [InboxKey], once, when the ceremony completes.
|
||||
*/
|
||||
@Entity(
|
||||
foreignKeys = [
|
||||
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
|
||||
],
|
||||
indices = [Index("chatRoomId")],
|
||||
)
|
||||
data class InboxKeyCeremony(
|
||||
@PrimaryKey
|
||||
val id: String,
|
||||
/** The group's Marmot room: the ceremony runs in it, and its admins are the participants. */
|
||||
val chatRoomId: String,
|
||||
/** Which generation of the room's inbox key this ceremony makes. */
|
||||
val generation: Int,
|
||||
val coordinatorPublicKey: HexKey,
|
||||
/** The identity on this device taking part, or watching. */
|
||||
val userPublicKey: HexKey,
|
||||
/** The admins the proposal named, sorted, comma-separated. */
|
||||
val participantPublicKeys: String,
|
||||
val stage: InboxKeyCeremonyStage = InboxKeyCeremonyStage.COLLECTING_HOST_KEYS,
|
||||
/** Null on the device of a member who is not a participant: it only watches. */
|
||||
val hostPublicKey: HexKey? = null,
|
||||
val round1Random: HexKey? = null,
|
||||
val round2AuxRandom: HexKey? = null,
|
||||
/** The ceremony's public key `E`, x-only, once it is certified. */
|
||||
val inboxPublicKey: HexKey? = null,
|
||||
val failureReason: String? = null,
|
||||
/** Whose fault a failure was, when ChillDKG could say. */
|
||||
val culprit: HexKey? = null,
|
||||
/** When the last message arrived: what "waiting since" is measured from. */
|
||||
val lastMessageAt: Instant = Clock.System.now(),
|
||||
val createdAt: Instant = Clock.System.now(),
|
||||
val updatedAt: Instant = createdAt,
|
||||
) {
|
||||
val isRunning: Boolean
|
||||
get() = stage != InboxKeyCeremonyStage.COMPLETE && stage != InboxKeyCeremonyStage.FAILED
|
||||
|
||||
fun isCoordinator(): Boolean = coordinatorPublicKey == userPublicKey
|
||||
|
||||
fun participants(): List<HexKey> = participantPublicKeys.split(",").map { it.trim() }.filter { it.isNotEmpty() }
|
||||
|
||||
fun isParticipant(): Boolean = userPublicKey in participants()
|
||||
|
||||
companion object {
|
||||
fun formatParticipants(publicKeys: Collection<HexKey>): String = publicKeys.distinct().sorted().joinToString(",")
|
||||
}
|
||||
}
|
||||
|
||||
/** Where an inbox key ceremony has got to, as a label for screens. */
|
||||
enum class InboxKeyCeremonyStage {
|
||||
COLLECTING_HOST_KEYS,
|
||||
ROUND_1,
|
||||
ROUND_2,
|
||||
COMPLETE,
|
||||
FAILED,
|
||||
}
|
||||
|
||||
/** One message an inbox key ceremony has received or sent, written once per sender and kind. */
|
||||
@Entity(
|
||||
primaryKeys = ["sessionId", "senderPublicKey", "kind"],
|
||||
foreignKeys = [
|
||||
ForeignKey(entity = InboxKeyCeremony::class, parentColumns = ["id"], childColumns = ["sessionId"], onDelete = ForeignKey.CASCADE)
|
||||
],
|
||||
)
|
||||
data class InboxKeyCeremonyMessage(
|
||||
val sessionId: String,
|
||||
val senderPublicKey: HexKey,
|
||||
val kind: Kind,
|
||||
val payload: String,
|
||||
val receivedAt: Instant = Clock.System.now(),
|
||||
)
|
||||
|
||||
/**
|
||||
* One generation of a group's inbox key, as this device holds it (docs/group-inbox.md, D14).
|
||||
*
|
||||
* [secretKey] is the whole secret `e`: every admin holds it, which is the point of it. It is
|
||||
* kept as a share is kept, and wiped as a share is wiped -- [state] goes to [InboxKeyState.WIPED]
|
||||
* and the secret to null, while [publicKey] stays so the device can still say which key it was.
|
||||
*/
|
||||
@Entity(
|
||||
primaryKeys = ["chatRoomId", "userPublicKey", "generation"],
|
||||
foreignKeys = [
|
||||
ForeignKey(entity = ChatRoom::class, parentColumns = ["id"], childColumns = ["chatRoomId"], onDelete = ForeignKey.CASCADE)
|
||||
],
|
||||
indices = [Index("chatRoomId")],
|
||||
)
|
||||
data class InboxKey(
|
||||
val chatRoomId: String,
|
||||
val userPublicKey: HexKey,
|
||||
val generation: Int,
|
||||
/** `E`, x-only hex: what the group's 10044 names. */
|
||||
val publicKey: HexKey,
|
||||
/** `e`, hex; null once wiped. */
|
||||
val secretKey: HexKey?,
|
||||
/** ChillDKG's recovery data: with the host secret from the nsec, it restores [secretKey]. */
|
||||
val recoveryData: HexKey?,
|
||||
val ceremonyId: String,
|
||||
val state: InboxKeyState = InboxKeyState.HELD,
|
||||
/** The signed 10044 that announced this generation, once there is one. */
|
||||
val announcementEventId: HexKey? = null,
|
||||
val createdAt: Instant = Clock.System.now(),
|
||||
val announcedAt: Instant? = null,
|
||||
val wipedAt: Instant? = null,
|
||||
)
|
||||
|
||||
enum class InboxKeyState {
|
||||
/** Made, not yet announced: nobody has been told to write to it. */
|
||||
HELD,
|
||||
/** The key the group's newest signed 10044 names: replies are sealed from it. */
|
||||
ANNOUNCED,
|
||||
/** Replaced by a later generation: used to open, never to seal. */
|
||||
RETIRED,
|
||||
/** Gone from this device: the admin was removed, or the device asked to forget. */
|
||||
WIPED,
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package mobi.giza.compose.database
|
||||
|
||||
import androidx.room3.Room
|
||||
import kotlin.test.AfterTest
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.time.Clock
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import mobi.giza.compose.database.builder.getRoomDatabase
|
||||
import mobi.giza.compose.database.model.ChatRoom
|
||||
import mobi.giza.compose.database.model.GroupInboxMessage
|
||||
import mobi.giza.compose.database.model.GroupInboxWrap
|
||||
import mobi.giza.compose.database.model.InboxKey
|
||||
import mobi.giza.compose.database.model.InboxKeyCeremony
|
||||
import mobi.giza.compose.database.model.InboxKeyCeremonyMessage
|
||||
import mobi.giza.compose.database.model.InboxKeyCeremonyStage
|
||||
import mobi.giza.compose.database.model.InboxKeyState
|
||||
import mobi.giza.compose.database.model.NostrEvent
|
||||
import mobi.giza.compose.database.model.Profile
|
||||
import mobi.giza.compose.managers.FrostSigningManager
|
||||
import mobi.giza.compose.nostr.inbox.InboxKeyRitualEvents
|
||||
|
||||
/**
|
||||
* Where a group's inbox is kept (docs/group-inbox.md, Phase 3): redelivery changes nothing,
|
||||
* a wipe keeps the key's name and loses its secret, and nothing a signing path reads can find a
|
||||
* threshold-1 key.
|
||||
*/
|
||||
class InboxStorageJvmTest {
|
||||
private val db: GizaDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder<GizaDatabase>())
|
||||
private val room = "f".repeat(64)
|
||||
private val admin = "a".repeat(64)
|
||||
|
||||
@AfterTest
|
||||
fun close() = db.close()
|
||||
|
||||
private fun seedRoom() = runBlocking {
|
||||
// A room belongs to a profile, which belongs to the event that made it.
|
||||
val profileEvent = "9".repeat(64)
|
||||
db.nostrEventDao().upsert(NostrEvent(id = profileEvent, pubKey = admin, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)))
|
||||
db.profileDao().upsert(Profile(publicKey = admin, nostrEventId = profileEvent))
|
||||
db.chatRoomDao().upsert(ChatRoom(id = room, userPublicKey = admin, subject = "#Ekklesia", description = "", mlsGroupState = null))
|
||||
}
|
||||
|
||||
private fun completedCeremonyAndKey() = runBlocking {
|
||||
seedRoom()
|
||||
db.inboxKeyDao().upsertCeremony(
|
||||
InboxKeyCeremony(
|
||||
id = "c".repeat(64),
|
||||
chatRoomId = room,
|
||||
generation = 0,
|
||||
coordinatorPublicKey = admin,
|
||||
userPublicKey = admin,
|
||||
participantPublicKeys = InboxKeyCeremony.formatParticipants(listOf(admin, "b".repeat(64))),
|
||||
stage = InboxKeyCeremonyStage.COMPLETE,
|
||||
hostPublicKey = "02" + "1".repeat(64),
|
||||
round1Random = "2".repeat(64),
|
||||
round2AuxRandom = "3".repeat(64),
|
||||
inboxPublicKey = "e".repeat(64),
|
||||
)
|
||||
)
|
||||
db.inboxKeyDao().upsertKey(
|
||||
InboxKey(
|
||||
chatRoomId = room,
|
||||
userPublicKey = admin,
|
||||
generation = 0,
|
||||
publicKey = "e".repeat(64),
|
||||
secretKey = "5".repeat(64),
|
||||
recoveryData = "66",
|
||||
ceremonyId = "c".repeat(64),
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a ceremony message delivered twice is kept once, as first received`() = runBlocking {
|
||||
completedCeremonyAndKey()
|
||||
val first = InboxKeyCeremonyMessage("c".repeat(64), admin, InboxKeyRitualEvents.HOST_KEY, "first")
|
||||
assertTrue(db.inboxKeyDao().insertMessage(first) > 0)
|
||||
assertEquals(-1L, db.inboxKeyDao().insertMessage(first.copy(payload = "second")))
|
||||
assertEquals("first", db.inboxKeyDao().getMessage("c".repeat(64), admin, InboxKeyRitualEvents.HOST_KEY)?.payload)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a wrap or a rumor delivered twice is one row`() = runBlocking {
|
||||
seedRoom()
|
||||
val wrap = GroupInboxWrap(id = "1".repeat(64), chatRoomId = room, wrapJson = "{}", wrapCreatedAt = 10)
|
||||
db.groupInboxDao().insertWrap(wrap)
|
||||
db.groupInboxDao().insertWrap(wrap.copy(wrapJson = "{\"again\":true}"))
|
||||
assertEquals(listOf(wrap.id to wrap.wrapJson), db.groupInboxDao().getUnopenedWraps(room).map { it.id to it.wrapJson })
|
||||
|
||||
val message = GroupInboxMessage(
|
||||
chatRoomId = room, rumorId = "2".repeat(64), wrapId = wrap.id, conversationId = "x",
|
||||
participants = "b".repeat(64), senderPublicKey = "b".repeat(64), kind = 14,
|
||||
rumorJson = "{}", createdAt = 5, generation = 0, outgoing = false,
|
||||
)
|
||||
db.groupInboxDao().insertMessage(message)
|
||||
db.groupInboxDao().insertMessage(message.copy(wrapId = "3".repeat(64)))
|
||||
assertEquals(listOf(message.wrapId), db.groupInboxDao().getMessages(room).map { it.wrapId })
|
||||
assertEquals(1, db.groupInboxDao().observeUnreadCount(room).first())
|
||||
|
||||
db.groupInboxDao().markOpened(wrap.id, 0)
|
||||
assertEquals(0, db.groupInboxDao().observeUnopenedCount(room).first())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a wipe loses the secret and keeps the key's name`() = runBlocking {
|
||||
completedCeremonyAndKey()
|
||||
db.inboxKeyDao().wipeKeys(room, admin, Clock.System.now())
|
||||
|
||||
val key = assertNotNull(db.inboxKeyDao().getKey(room, admin, 0))
|
||||
assertNull(key.secretKey)
|
||||
assertNull(key.recoveryData)
|
||||
assertEquals(InboxKeyState.WIPED, key.state)
|
||||
assertEquals("e".repeat(64), key.publicKey)
|
||||
assertEquals(emptyList(), db.inboxKeyDao().getHeldKeys(admin))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `no signing path can find an inbox key`() = runBlocking {
|
||||
// D3: a threshold-1 key any one admin holds, found by the signing path, would let one
|
||||
// admin sign as the group. It lives where nothing that signs looks.
|
||||
completedCeremonyAndKey()
|
||||
assertEquals(emptyList(), db.dkgSessionDao().getKeyHoldingSessions())
|
||||
assertNull(FrostSigningManager.completedKey(db, room))
|
||||
assertEquals(false, FrostSigningManager.canSign(db, room))
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -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 the group's
|
||||
* inbox (docs/group-inbox.md, Phase 3), 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")
|
||||
|
||||
Reference in new issue
Block a user