diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/database/CurareDatabase.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/database/CurareDatabase.kt index 9deb0d76..65e2a9f7 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/database/CurareDatabase.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/database/CurareDatabase.kt @@ -95,6 +95,7 @@ import to.curare.compose.database.model.MarmotInnerEvent import to.curare.compose.database.model.MarmotKeyPackage import to.curare.compose.database.model.MarmotKeyPackageBundle import to.curare.compose.database.model.MarmotRouting +import to.curare.compose.managers.MarmotEngine import to.curare.compose.database.model.MarmotRetainedEpochSecret import to.curare.compose.database.model.Mention import to.curare.compose.database.model.NegentropySynchronizeRequest @@ -344,6 +345,14 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L) ) @ColumnTypeConverters(CurareConverters::class) abstract class CurareDatabase: RoomDatabase() { + /** + * The Marmot engine for this database's current-profile rooms, made on first use + * and living as long as the database does. Owned here rather than registered + * elsewhere because the DAOs that need it are made by Room from this instance and + * can be handed nothing else. See [MarmotEngine]. + */ + val marmotEngine: MarmotEngine by lazy { MarmotEngine(this) } + abstract fun broadcastNostrEventReceiptDao(): BroadcastNostrEventReceiptDao abstract fun broadcastNostrEventRequestDao(): BroadcastNostrEventRequestDao diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/ChatRoomDao.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/ChatRoomDao.kt index d2258507..d193203d 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/ChatRoomDao.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/ChatRoomDao.kt @@ -86,6 +86,23 @@ interface ChatRoomDao { ) fun observeByParentChatRoomId(parentChatRoomId: String): Flow> + /** + * The ids of every room holding MLS state that this device is still in. What the + * Marmot engine restores at startup -- ids only, because it loads each state on + * its own and the relations the room queries above carry would be wasted here. + */ + @Query("SELECT id FROM ChatRoom WHERE mlsGroupState IS NOT NULL AND deletedAt IS NULL AND leftGroupAt IS NULL") + suspend fun getChatRoomIdsWithMlsState(): List + + @Query("SELECT mlsGroupState FROM ChatRoom WHERE id = :id") + suspend fun getMlsGroupState(id: String): String? + + @Query("SELECT COUNT(*) > 0 FROM ChatRoom WHERE id = :id") + suspend fun exists(id: String): Boolean + + @Query("UPDATE ChatRoom SET mlsGroupState = :mlsGroupState WHERE id = :id") + suspend fun updateMlsGroupState(id: String, mlsGroupState: String?) + @Upsert suspend fun upsert(chatRoom: ChatRoom) diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/MarmotOutboundDao.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/MarmotOutboundDao.kt index 6b01519e..e3ff4814 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/MarmotOutboundDao.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/MarmotOutboundDao.kt @@ -130,26 +130,48 @@ abstract class MarmotOutboundDao( ) ) - // Invite peer... + // Invite peer. On the current profile the manager owns the group from the row + // just written, and the invite moves that instance rather than the one the + // factory handed back. + val liveGroup = liveGroupFor(LocalChatRoom(chatRoom = chatRoom, routings = listOf(MarmotRouting(created.routingId, chatRoom.id)))) + ?: throw MarmotMissingChatGroupException("The room just made holds no MLS state") inviteMember( chatRoomId = nostrGroupId, - mlsGroup = mlsGroup, + mlsGroup = liveGroup, userPublicKey = userPublicKey, peerPublicKey = peerPublicKey, peerKeyPackage = peerKeyPackage, relays = relays ) - // Update chatRoom - database.chatRoomDao().upsert( - chatRoom.copy( - mlsGroupState = mlsGroup.saveState().encodeTls().toHex(), + // Update chatRoom -- a legacy room's state from the instance the invite moved; + // a current-profile room's was persisted by the manager. + if (created.profile == MarmotProfile.LEGACY) { + database.chatRoomDao().upsert( + chatRoom.copy( + mlsGroupState = liveGroup.saveState().encodeTls().toHex(), + ) ) - ) + } return nostrGroupId } + /** + * The room's live group, by the room's profile. + * + * A legacy room's is rebuilt from its row, as it always was, and written back by + * the caller. A current-profile room's is the one the engine's manager holds -- + * the single writer of that room's state -- and the caller must not write it + * back: every manager operation persists itself, and a state saved from a + * second instance would be a stale one. See MarmotEngine. + */ + private suspend fun liveGroupFor(localChatRoom: LocalChatRoom): MlsGroup? = + when (localChatRoom.chatRoom.marmotProfile()) { + MarmotProfile.LEGACY -> localChatRoom.chatRoom.toMlsGroup() + MarmotProfile.CURRENT -> database.marmotEngine.groupFor(localChatRoom.routingId) + } + @Transaction open suspend fun inviteMemberToChatRoom( localChatRoom: LocalChatRoom, @@ -159,7 +181,7 @@ abstract class MarmotOutboundDao( // A room restored from an inbound gift wrap has no persisted MLS state, so there is // nothing to add a member to. Say so instead of silently doing nothing and letting the // caller report success. - val mlsGroup = localChatRoom.chatRoom.toMlsGroup() + val mlsGroup = liveGroupFor(localChatRoom) ?: throw MarmotMissingChatGroupException( "No MLS group state for chat room ${localChatRoom.chatRoom.id}; cannot invite $peerPublicKey" ) @@ -191,11 +213,15 @@ abstract class MarmotOutboundDao( // `addMember` advanced the in-memory group to the next epoch. Without persisting it the // creator kept encrypting under the old epoch — which the new member cannot decrypt — // and the next invite would re-derive from stale state and produce a conflicting commit. - database.chatRoomDao().upsert( - localChatRoom.chatRoom.copy( - mlsGroupState = mlsGroup.saveState().encodeTls().toHex() + // A current-profile room's state was persisted by the manager that moved it, and a + // write from here would be of a stale instance. + if (localChatRoom.chatRoom.marmotProfile() == MarmotProfile.LEGACY) { + database.chatRoomDao().upsert( + localChatRoom.chatRoom.copy( + mlsGroupState = mlsGroup.saveState().encodeTls().toHex() + ) ) - ) + } } /** @@ -229,7 +255,7 @@ abstract class MarmotOutboundDao( ): List { if (peers.isEmpty()) return emptyList() - val mlsGroup = localChatRoom.chatRoom.toMlsGroup() + val mlsGroup = liveGroupFor(localChatRoom) ?: throw MarmotMissingChatGroupException( "No MLS state for chat room ${localChatRoom.chatRoom.id}; cannot add members" ) @@ -288,32 +314,59 @@ abstract class MarmotOutboundDao( require(credential.identity.toHexKey() == peerPublicKey) { "KeyPackage credential identity does not match memberPubKey" } - - mlsGroup.proposeAdd(peerKeyPackage.tlsEncodedMarmotKeyPackage) + if (!MarmotGroupFactory.leafFits(mlsGroup, keyPackage)) { + throw MarmotKeyPackageProfileException( + "${memberName(peerPublicKey)}'s key package is from an older Marmot profile; ask them to update" + ) + } } - val retainedBefore = mlsGroup.retainedSecrets() - val commitResult = mlsGroup.commit() + val commitResult = when (localChatRoom.chatRoom.marmotProfile()) { + MarmotProfile.CURRENT -> { + // Staged on a clone and installed at once: the manager retains the + // epoch it is leaving and persists, so nothing below writes the state + // for this room. Installing here rather than on a relay's OK is what + // docs/marmot-v2.md Phase 6 changes. + val manager = database.marmotEngine.groupManager + val staged = manager.stageAddMembers( + nostrGroupId = localChatRoom.routingId, + keyPackagesBytes = peers.map { (_, peerKeyPackage) -> peerKeyPackage.tlsEncodedMarmotKeyPackage }, + ) + manager.installState(localChatRoom.routingId, staged.pendingState) + staged.result + } - database.marmotRetainedEpochSecretDao().insert( - MarmotRetainedEpochSecret( - chatRoomId = localChatRoom.chatRoom.id, - epoch = retainedBefore.epoch, - senderDataSecret = retainedBefore.senderDataSecret, - encryptionSecret = retainedBefore.encryptionSecret, - leafCount = retainedBefore.leafCount, - exporterSecret = retainedBefore.exporterSecret, - ) - ) + MarmotProfile.LEGACY -> { + peers.forEach { (_, peerKeyPackage) -> + mlsGroup.proposeAdd(peerKeyPackage.tlsEncodedMarmotKeyPackage) + } - // `commit` advanced the in-memory group. Persist before delivering, so a - // crash between the two leaves the group at the epoch the Welcomes describe - // rather than one behind it. - database.chatRoomDao().upsert( - localChatRoom.chatRoom.copy( - mlsGroupState = mlsGroup.saveState().encodeTls().toHex() - ) - ) + val retainedBefore = mlsGroup.retainedSecrets() + val commitResult = mlsGroup.commit() + + database.marmotRetainedEpochSecretDao().insert( + MarmotRetainedEpochSecret( + chatRoomId = localChatRoom.chatRoom.id, + epoch = retainedBefore.epoch, + senderDataSecret = retainedBefore.senderDataSecret, + encryptionSecret = retainedBefore.encryptionSecret, + leafCount = retainedBefore.leafCount, + exporterSecret = retainedBefore.exporterSecret, + ) + ) + + // `commit` advanced the in-memory group. Persist before delivering, so a + // crash between the two leaves the group at the epoch the Welcomes describe + // rather than one behind it. + database.chatRoomDao().upsert( + localChatRoom.chatRoom.copy( + mlsGroupState = mlsGroup.saveState().encodeTls().toHex() + ) + ) + + commitResult + } + } // One line each, as `inviteMember` writes for the invites it makes -- this // path does its own commit and never goes through it. Written before the @@ -534,32 +587,45 @@ abstract class MarmotOutboundDao( content = "Invited ${memberName(peerPublicKey)} to the group", ) - val retainedBefore = mlsGroup.retainedSecrets() - val commitResult = mlsGroup.addMember( - peerKeyPackage.tlsEncodedMarmotKeyPackage - ) - - database.marmotRetainedEpochSecretDao().insert( - MarmotRetainedEpochSecret( - chatRoomId = chatRoomId, - epoch = retainedBefore.epoch, - senderDataSecret = retainedBefore.senderDataSecret, - encryptionSecret = retainedBefore.encryptionSecret, - leafCount = retainedBefore.leafCount, - exporterSecret = retainedBefore.exporterSecret, + val commitResult = if (mlsGroup.currentGroupState().isCurrentProfile) { + // Staged on a clone and installed at once by the manager, which retains + // the epoch it is leaving and persists the state itself; the caller + // must not write it back. Installing here rather than on a relay's OK + // is what docs/marmot-v2.md Phase 6 changes. + val manager = database.marmotEngine.groupManager + val staged = manager.stageAddMember(routingId, peerKeyPackage.tlsEncodedMarmotKeyPackage) + manager.installState(routingId, staged.pendingState) + staged.result + } else { + val retainedBefore = mlsGroup.retainedSecrets() + val commitResult = mlsGroup.addMember( + peerKeyPackage.tlsEncodedMarmotKeyPackage ) - ) - // Trim retained epochs out of the retention window... - val defenestratableMarmotRetainedEpochSecrets = database.marmotRetainedEpochSecretDao() - .getDefenestratableMarmotRetainedEpochSecretForChatRoomId( - chatRoomId = chatRoomId, - epochCutOffPoint = retainedBefore.epoch - EPOCH_RETENTION_WINDOW.toLong() + database.marmotRetainedEpochSecretDao().insert( + MarmotRetainedEpochSecret( + chatRoomId = chatRoomId, + epoch = retainedBefore.epoch, + senderDataSecret = retainedBefore.senderDataSecret, + encryptionSecret = retainedBefore.encryptionSecret, + leafCount = retainedBefore.leafCount, + exporterSecret = retainedBefore.exporterSecret, + ) ) - logger.d("Defenestratable Retained Epochs: ${defenestratableMarmotRetainedEpochSecrets.map { it.epoch }}") - database.marmotRetainedEpochSecretDao().defenestrate( - defenestratableMarmotRetainedEpochSecrets - ) + + // Trim retained epochs out of the retention window... + val defenestratableMarmotRetainedEpochSecrets = database.marmotRetainedEpochSecretDao() + .getDefenestratableMarmotRetainedEpochSecretForChatRoomId( + chatRoomId = chatRoomId, + epochCutOffPoint = retainedBefore.epoch - EPOCH_RETENTION_WINDOW.toLong() + ) + logger.d("Defenestratable Retained Epochs: ${defenestratableMarmotRetainedEpochSecrets.map { it.epoch }}") + database.marmotRetainedEpochSecretDao().defenestrate( + defenestratableMarmotRetainedEpochSecrets + ) + + commitResult + } if (isOneMemberInitialGroupCreation) { // Send welcome event to participant @@ -771,12 +837,13 @@ abstract class MarmotOutboundDao( marmotInnerEvent: MarmotInnerEvent, nostrSignerSync: NostrSignerSync ): GroupEvent { - // The room's profile decides the shape of what goes into MLS. See - // docs/marmot-v2.md, Phase 2: it is the feature flag for every wire change - // an old build cannot read, because a current-profile room admits only - // leaves that carry an identity proof, and only a build past Phase 3 can - // make one. - val isCurrentProfileRoom = mlsGroup.currentGroupState().isCurrentProfile + // The room's profile decides the shape of what goes into MLS and which + // pipeline encrypts it. See docs/marmot-v2.md, Phase 2: it is the feature + // flag for every wire change an old build cannot read, because a + // current-profile room admits only leaves that carry an identity proof, and + // only a build past Phase 3 can make one; and Phase 5: a current-profile + // room's group is the engine's, not this function's argument. + val isCurrentProfileRoom = localChatRoom.chatRoom.marmotProfile() == MarmotProfile.CURRENT val plainTextBytes: ByteArray = marmotInnerEvent.directMessageRecipientPublicKey?.let { recipient -> // A direct message is gift wrapped for one member before it goes into @@ -832,47 +899,63 @@ abstract class MarmotOutboundDao( logger.d("plainTextBytes: ${plainTextBytes.toHex()}") - // Step 1: MLS encrypt - val mlsCipherText = mlsGroup.encrypt(plainTextBytes) - logger.d("mlsCipherText: ${mlsCipherText.toHex()}") + val groupEvent: GroupEvent = if (isCurrentProfileRoom) { + // The library's outbound processor over the engine's live group: MLS + // encrypt, the outer layer, the template with its expiration, the + // ephemeral signer -- and the manager persists the ratchet it advanced, + // so nothing here writes the room's state. The `mlsGroup` this function + // was handed is another instance of the same group and is not used to + // encrypt: two instances of one ratchet is how a message gets a key the + // other side has already moved past. + val engine = database.marmotEngine + engine.groupFor(localChatRoom.routingId) + ?: throw MarmotMissingChatGroupException("No live group for ${localChatRoom.chatRoom.id}") + engine.outbound.buildGroupEventFromBytes(localChatRoom.routingId, plainTextBytes).signedEvent + } else { + // Step 1: MLS encrypt + val mlsCipherText = mlsGroup.encrypt(plainTextBytes) + logger.d("mlsCipherText: ${mlsCipherText.toHex()}") - // Step 2: Outer ChaCha20-Poly1305 encryption - val exportKey = mlsGroup.exporterSecret() - logger.d("exporterKey: ${exportKey.toHex()}") - val encryptedContent = GroupEventEncryption.encrypt( - mlsMessageBytes = mlsCipherText, - groupKey = exportKey - ) - logger.d("encryptedContent: $encryptedContent") - - // Step 3: Build the GroupEvent template (auto-apply NIP-40 expiration - // if the group has disappearing_message_secs configured per MIP-01/03). - val createdAt = TimeUtils.now() - val expirationTime = disappearingExpiration(mlsGroup, createdAt) - - // No `encoding` tag. `transports/nostr.md`: a sender MUST NOT add one to any - // event shape -- a receiver that switched decoders on it could be steered - // into a different parse of the same bytes -- and the commit template below - // never carried one either. - val template = GroupEvent.build( - encryptedContentBase64 = encryptedContent, - nostrGroupId = localChatRoom.routingId, - createdAt = createdAt, - ) { - if (expirationTime != null) expiration(expirationTime) - } - - // Step 4: Sign with a fresh ephemeral keypair - val ephemeralSigner = NostrSignerInternal(KeyPair()) - val groupEvent: GroupEvent = ephemeralSigner.sign(template) - logger.d("groupEvent: ${groupEvent.toJson()}") - - // May need to update chatRoom mlsGroupState... or last sent message - database.chatRoomDao().upsert( - localChatRoom.chatRoom.copy( - mlsGroupState = mlsGroup.saveState().encodeTls().toHex() + // Step 2: Outer ChaCha20-Poly1305 encryption + val exportKey = mlsGroup.exporterSecret() + logger.d("exporterKey: ${exportKey.toHex()}") + val encryptedContent = GroupEventEncryption.encrypt( + mlsMessageBytes = mlsCipherText, + groupKey = exportKey ) - ) + logger.d("encryptedContent: $encryptedContent") + + // Step 3: Build the GroupEvent template (auto-apply NIP-40 expiration + // if the group has disappearing_message_secs configured per MIP-01/03). + val createdAt = TimeUtils.now() + val expirationTime = disappearingExpiration(mlsGroup, createdAt) + + // No `encoding` tag. `transports/nostr.md`: a sender MUST NOT add one to any + // event shape -- a receiver that switched decoders on it could be steered + // into a different parse of the same bytes -- and the commit template below + // never carried one either. + val template = GroupEvent.build( + encryptedContentBase64 = encryptedContent, + nostrGroupId = localChatRoom.routingId, + createdAt = createdAt, + ) { + if (expirationTime != null) expiration(expirationTime) + } + + // Step 4: Sign with a fresh ephemeral keypair + val ephemeralSigner = NostrSignerInternal(KeyPair()) + val signed: GroupEvent = ephemeralSigner.sign(template) + + // The ratchet advanced; persist it, or the next message reuses a key. + database.chatRoomDao().upsert( + localChatRoom.chatRoom.copy( + mlsGroupState = mlsGroup.saveState().encodeTls().toHex() + ) + ) + + signed + } + logger.d("groupEvent: ${groupEvent.toJson()}") database.nostrEventDao().upsert( NostrEvent( diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/MarmotRetainedEpochSecretDao.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/MarmotRetainedEpochSecretDao.kt index 9a0af5cd..482398a1 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/MarmotRetainedEpochSecretDao.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/MarmotRetainedEpochSecretDao.kt @@ -25,4 +25,7 @@ interface MarmotRetainedEpochSecretDao { @Delete suspend fun defenestrate(marmotRetainedEpochSecrets: List) + @Query("DELETE FROM MarmotRetainedEpochSecret WHERE chatRoomId = :chatRoomId") + suspend fun deleteForChatRoomId(chatRoomId: HexKey) + } \ No newline at end of file diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt index 3000b15c..c24655fc 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/database/dao/NostrDao.kt @@ -39,6 +39,7 @@ import to.curare.compose.managers.GroupKeyStateManager import to.curare.compose.managers.MlsGroupCache import to.curare.compose.managers.MarmotInboundManager import to.curare.compose.managers.MarmotReindexSweep +import to.curare.compose.managers.MarmotEngine.Companion.inRoom import to.curare.compose.managers.WelcomeBundleMatch import to.curare.compose.managers.roomDescription import to.curare.compose.managers.roomName @@ -1368,6 +1369,62 @@ abstract class NostrDao( return } + // The room's profile picks its pipeline -- see MarmotEngine. A legacy room + // is read by the app's own manager over the cache, as it always was; a + // current-profile room by the library's processor over its manager, which + // is where convergence and message-id dedup live. + when (localChatRoom.chatRoom.marmotProfile()) { + MarmotProfile.LEGACY -> indexLegacyMarmotGroupEvent(groupEvent, localChatRoom, activeKeyPair) + MarmotProfile.CURRENT -> indexCurrentProfileGroupEvent(groupEvent, localChatRoom, activeKeyPair) + } + } + + private suspend fun indexCurrentProfileGroupEvent( + groupEvent: GroupEvent, + localChatRoom: LocalChatRoom, + activeKeyPair: KeyPair, + ) { + val chatRoomId = localChatRoom.chatRoom.id + val routingId = groupEvent.groupId() + ?: throw MarmotMissingNostrGroupDataExtension("${groupEvent.id} carries no h tag") + val engine = database.marmotEngine + val mlsGroup = engine.groupFor(routingId) + ?: throw MarmotMissingNostrGroupDataExtension("Couldn't restore the group for ${groupEvent.id}") + + if (!mlsGroup.currentMemberIdentities().contains(activeKeyPair.pubKey.toHex())) { + throw MarmotNotMemberOfChatGroupException("We are not a member of the chat room $chatRoomId") + } + + upsertMarmotGroupEvent(groupEvent, chatRoomId, activeKeyPair) + + // The processor names the group by its address; every row below is keyed by + // the room, so the result is re-addressed once. + val groupEventResult = engine.inbound.processGroupEvent(groupEvent).inRoom(chatRoomId) + logger.d("groupEventResult: $groupEventResult") + + fileGroupEventResult( + localChatRoom = localChatRoom, + groupEvent = groupEvent, + groupEventResult = groupEventResult, + activeKeyPair = activeKeyPair, + // The live group the manager holds, which the commit just moved. + mlsGroup = engine.groupManager.getGroup(routingId) ?: mlsGroup, + ) + + // A commit that forked the group opened a pass, and a quiet group has + // nothing else to drive it to its cutoff. + if (engine.inbound.openConvergencePasses().isNotEmpty()) { + engine.settleLater() + } + } + + private suspend fun indexLegacyMarmotGroupEvent( + groupEvent: GroupEvent, + localChatRoom: LocalChatRoom, + activeKeyPair: KeyPair, + ) { + val chatRoomId = localChatRoom.chatRoom.id + // Through the cache rather than rebuilt here, so the secret // tree's skipped-generation keys survive from one message to // the next. Two events published in the same instant arrive in @@ -1395,18 +1452,7 @@ abstract class NostrDao( } if (memberPubkeys.contains(activeKeyPair.pubKey.toHex())) { - database.marmotGroupEventDao().upsert( - MarmotGroupEvent( - id = groupEvent.id, - userPublicKey = activeKeyPair.pubKey.toHex(), - publicKey = groupEvent.pubKey, - encryptedContent = groupEvent.encryptedContent(), - chatRoomId = chatRoomId, - createdAt = Instant.fromEpochSeconds(groupEvent.createdAt), - expiresAt = groupEvent.expiration()?.let { Instant.fromEpochSeconds(it) }, - signature = groupEvent.sig - ) - ) + upsertMarmotGroupEvent(groupEvent, chatRoomId, activeKeyPair) MarmotInboundManager.processGroupEvent( database = database, activeKeyPair = activeKeyPair, @@ -1416,79 +1462,13 @@ abstract class NostrDao( )?.let { groupEventResult -> logger.d("groupEventResult: $groupEventResult") - when(groupEventResult) { - is GroupEventResult.CommitProcessed -> { - MarmotInboundManager.processGroupMembershipChanges( - database = database, - mlsGroup = mlsGroup, - localChatRoom = localChatRoom - ) - } - else -> { - logger.i("No app logic to handle: $groupEventResult") - } - } - - ChatMessage.fromGroupEventResult( - database = database, - activeKeyPair = activeKeyPair, + fileGroupEventResult( + localChatRoom = localChatRoom, groupEvent = groupEvent, groupEventResult = groupEventResult, - // Who sent it comes from the MLS frame, not the - // payload. Resolved here because this is where the - // group is; the leaf index is on the result, and the - // tree has not moved -- an application message - // advances no epoch. - senderIdentity = (groupEventResult as? GroupEventResult.ApplicationMessage) - ?.let { mlsGroup.memberIdentityHex(it.senderLeafIndex) }, - )?.let { chatMessage -> - logger.d("chatMessage: $chatMessage") - persistMarmotChatMessage(chatMessage) - } - - // A signing or ceremony message for this group. Driven - // from here rather than from ChatMessage because each - // manager needs the room to publish its own replies - // into, and because both write their transcript lines - // themselves. Both are idempotent, so a redelivered - // message re-runs a step already taken. - // - // A ceremony arrives here when the group is standing up - // a subgroup: the child's ChillDKG runs in this room, - // over the admins the proposal p-tags, because the - // child has no room of its own until the ceremony has - // produced the key its id is derived from. A member of - // this room who was not picked drops the proposal in - // `acceptProposal` and never opens a session. - // - // A GroupKeyStateEvent is deliberately not dispatched - // here. It is no longer something a member says -- - // it is what a session like this one produces -- and - // `ChatMessage.applyInnerEvent` files it alongside - // every other event the group has signed. - if (groupEventResult is GroupEventResult.ApplicationMessage) { - Event.fromJsonOrNull(groupEventResult.innerEventJson) - ?.let { innerEvent -> - when { - FrostSigningEvents.isFrostSigningKind(innerEvent.kind) -> - FrostSigningManager.processSigningPayload( - database = database, - localChatRoom = localChatRoom, - innerEvent = innerEvent, - userPublicKey = activeKeyPair.pubKey.toHex() - ) - - DkgRitualEvents.isDkgRitualKind(innerEvent.kind) -> - ChillDkgRitualManager.processRitualPayload( - database = database, - localChatRoom = localChatRoom, - innerEvent = innerEvent, - userPublicKey = activeKeyPair.pubKey.toHex(), - nostrPrivateKey = activeKeyPair.privKey!! - ) - } - } - } + activeKeyPair = activeKeyPair, + mlsGroup = mlsGroup, + ) } } else { throw MarmotNotMemberOfChatGroupException("We are not a member of the chat room ${localChatRoom.chatRoom.id}") @@ -1502,6 +1482,116 @@ abstract class NostrDao( } } + private suspend fun upsertMarmotGroupEvent( + groupEvent: GroupEvent, + chatRoomId: String, + activeKeyPair: KeyPair, + ) { + database.marmotGroupEventDao().upsert( + MarmotGroupEvent( + id = groupEvent.id, + userPublicKey = activeKeyPair.pubKey.toHex(), + publicKey = groupEvent.pubKey, + encryptedContent = groupEvent.encryptedContent(), + chatRoomId = chatRoomId, + createdAt = Instant.fromEpochSeconds(groupEvent.createdAt), + expiresAt = groupEvent.expiration()?.let { Instant.fromEpochSeconds(it) }, + signature = groupEvent.sig + ) + ) + } + + /** + * Turns what a kind:445 turned out to be into rows: the membership changes a + * commit made, the chat line, and the signing or ceremony step a payload drives. + * The same for either pipeline, which is why it is one function. + * + * [mlsGroup] is the room's live group after the event was applied: the tree + * the sender's leaf index is resolved against, and the membership a commit is + * diffed against. + */ + private suspend fun fileGroupEventResult( + localChatRoom: LocalChatRoom, + groupEvent: GroupEvent, + groupEventResult: GroupEventResult, + activeKeyPair: KeyPair, + mlsGroup: MlsGroup, + ) { + when(groupEventResult) { + is GroupEventResult.CommitProcessed -> { + MarmotInboundManager.processGroupMembershipChanges( + database = database, + mlsGroup = mlsGroup, + localChatRoom = localChatRoom + ) + } + else -> { + logger.i("No app logic to handle: $groupEventResult") + } + } + + ChatMessage.fromGroupEventResult( + database = database, + activeKeyPair = activeKeyPair, + groupEvent = groupEvent, + groupEventResult = groupEventResult, + // Who sent it comes from the MLS frame, not the + // payload. Resolved here because this is where the + // group is; the leaf index is on the result, and the + // tree has not moved -- an application message + // advances no epoch. + senderIdentity = (groupEventResult as? GroupEventResult.ApplicationMessage) + ?.let { mlsGroup.memberIdentityHex(it.senderLeafIndex) }, + )?.let { chatMessage -> + logger.d("chatMessage: $chatMessage") + persistMarmotChatMessage(chatMessage) + } + + // A signing or ceremony message for this group. Driven + // from here rather than from ChatMessage because each + // manager needs the room to publish its own replies + // into, and because both write their transcript lines + // themselves. Both are idempotent, so a redelivered + // message re-runs a step already taken. + // + // A ceremony arrives here when the group is standing up + // a subgroup: the child's ChillDKG runs in this room, + // over the admins the proposal p-tags, because the + // child has no room of its own until the ceremony has + // produced the key its id is derived from. A member of + // this room who was not picked drops the proposal in + // `acceptProposal` and never opens a session. + // + // A GroupKeyStateEvent is deliberately not dispatched + // here. It is no longer something a member says -- + // it is what a session like this one produces -- and + // `ChatMessage.applyInnerEvent` files it alongside + // every other event the group has signed. + if (groupEventResult is GroupEventResult.ApplicationMessage) { + Event.fromJsonOrNull(groupEventResult.innerEventJson) + ?.let { innerEvent -> + when { + FrostSigningEvents.isFrostSigningKind(innerEvent.kind) -> + FrostSigningManager.processSigningPayload( + database = database, + localChatRoom = localChatRoom, + innerEvent = innerEvent, + userPublicKey = activeKeyPair.pubKey.toHex() + ) + + DkgRitualEvents.isDkgRitualKind(innerEvent.kind) -> + ChillDkgRitualManager.processRitualPayload( + database = database, + localChatRoom = localChatRoom, + innerEvent = innerEvent, + userPublicKey = activeKeyPair.pubKey.toHex(), + nostrPrivateKey = activeKeyPair.privKey!! + ) + } + } + } + } + /** * Files the chat line a kind:445 produced, replacing the line that event * already has rather than adding a second one. The rule for which of the two @@ -1597,7 +1687,19 @@ abstract class NostrDao( // Held commits are what a replay is most often for, and they are only ever // cleared by one applying -- see MarmotInboundManager.forgetPendingCommits. - MarmotInboundManager.forgetPendingCommits(chatRoomId) + // A current-profile room holds nothing of the kind: its competing commits + // are candidates in a convergence pass, which is closed here so the replay + // runs against settled state rather than a branch a pass is about to drop. + when (chatRoom?.marmotProfile()) { + MarmotProfile.CURRENT -> { + val engine = database.marmotEngine + routingIds.forEach { routingId -> + engine.groupFor(routingId) + engine.inbound.resolveConvergence(routingId) + } + } + else -> MarmotInboundManager.forgetPendingCommits(chatRoomId) + } val resolved = database.chatMessageDao().getResolvedMarmotGroupEventIds( chatRoomId = chatRoomId, diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/database/model/ChatRoom.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/database/model/ChatRoom.kt index 948441b1..0f78765b 100644 --- a/composeApp/src/commonMain/kotlin/to/curare/compose/database/model/ChatRoom.kt +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/database/model/ChatRoom.kt @@ -9,7 +9,9 @@ import to.curare.compose.database.model.traits.SoftDeletableEntity import to.curare.compose.database.model.traits.TimestampedEntity import to.curare.compose.database.model.traits.UserViewableEntity import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.marmot.appComponents.MarmotGroupState import com.vitorpamplona.quartz.marmot.mls.group.MlsGroup +import to.curare.compose.nostr.MarmotProfile import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupState import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray @@ -231,4 +233,21 @@ data class ChatRoom( ) } } + + /** + * Which Marmot profile this room's group is on, read off the stored state's group + * context without rebuilding the group -- no key schedule, no secret tree, just + * the extensions. A room with no state, or state this build cannot read, answers + * legacy: that is the profile every room was on before there were two, and it is + * the pipeline that already copes with a room it cannot process. + * + * The profile picks the room's pipeline -- see `MarmotEngine`. + */ + fun marmotProfile(): MarmotProfile { + val state = mlsGroupState ?: return MarmotProfile.LEGACY + return runCatching { + val extensions = MlsGroupState.decodeTls(state.hexToByteArray()).groupContext.extensions + if (MarmotGroupState.fromExtensions(extensions).isCurrentProfile) MarmotProfile.CURRENT else MarmotProfile.LEGACY + }.getOrDefault(MarmotProfile.LEGACY) + } } diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/managers/MarmotEngine.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/managers/MarmotEngine.kt new file mode 100644 index 00000000..231b4591 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/managers/MarmotEngine.kt @@ -0,0 +1,143 @@ +package to.curare.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.marmot.GroupEventResult +import com.vitorpamplona.quartz.marmot.MarmotInboundProcessor +import com.vitorpamplona.quartz.marmot.MarmotOutboundProcessor +import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageRotationManager +import com.vitorpamplona.quartz.marmot.mls.group.MlsGroup +import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupManager +import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import to.curare.compose.database.CurareDatabase + +/** + * quartz's Marmot engine, over this database, for the rooms on the current profile. + * + * `MlsGroupManager` holds the live `MlsGroup` of every group and persists through + * [RoomMlsGroupStateStore]; `MarmotInboundProcessor` reads kind:445s against them, + * settling same-epoch commits through its convergence engine and recognising + * redelivery by the Marmot message id; `MarmotOutboundProcessor` builds the kind:445s + * this device sends. Everything in docs/marmot-v2.md's "v2 says" column that is not a + * wire shape lives in these three, and they are built around the store rather than + * the app's own copy of their logic. + * + * **A room's profile picks its pipeline.** Legacy rooms keep the app's own path -- + * `MarmotInboundManager` over `MlsGroupCache`, unchanged -- and retire with it; + * current-profile rooms go through here. A room is on one profile for its whole + * life, so the two never hold the same group, which is what keeps the manager's live + * instance the single writer of a current-profile room's state. The library's + * processor also has no carve-out for the bare gift wrap a legacy room carries a + * direct message in, which is the other reason legacy rooms stay where they are. + * + * One engine per database, owned by it ([CurareDatabase.marmotEngine]): the manager + * keys groups by routing address, which is unique across identities, and a room row + * belongs to one identity anyway. + * + * The library's KeyPackage rotation manager is constructed but not fed: Welcomes are + * matched to this device's bundles by the app's own table, which is profile-aware + * and matched by reference since Phase 1, and the processor reads the rotation + * manager only on its own Welcome path, which the app does not use. + */ +class MarmotEngine( + private val database: CurareDatabase, + private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default), +) { + private val logger = Logger.withTag("MarmotEngine") + + val store = RoomMlsGroupStateStore(database) + val groupManager = MlsGroupManager(store) + val inbound = MarmotInboundProcessor(groupManager, KeyPackageRotationManager()) + val outbound = MarmotOutboundProcessor(groupManager) + + private val restoreMutex = Mutex() + private var restored = false + + /** + * Load every group from the store, once, and seed convergence with each. + * + * Convergence cannot see a fork in a group whose current state it never + * retained, so a restored group is tracked before its first inbound commit. + */ + suspend fun ensureRestored() { + restoreMutex.withLock { + if (restored) return + groupManager.restoreAll() + groupManager.activeGroupIds().forEach { inbound.trackGroup(it) } + restored = true + logger.d("Restored ${groupManager.activeGroupIds().size} group(s)") + } + } + + /** + * The live group addressed by [routingId], or null when this device holds no + * state for it. + * + * A room made or joined after the restore is loaded from its row the first time + * it is asked for and handed to the manager, which owns it from then on. + */ + suspend fun groupFor(routingId: HexKey): MlsGroup? { + ensureRestored() + groupManager.getGroup(routingId)?.let { return it } + val bytes = store.load(routingId) ?: return null + val group = MlsGroup.restore(MlsGroupState.decodeTls(bytes)) + groupManager.adoptGroup(routingId, group) + inbound.trackGroup(routingId) + return group + } + + /** + * Tick convergence, and keep ticking while any pass is open. + * + * Inbound traffic is only an opportunistic tick: a group that goes quiet + * mid-pass has nothing else to drive it to its cutoff, so this loop runs at the + * quiescence window until the processor reports no open pass. A resolution that + * rewound canonical state is logged and nothing more for now -- see + * docs/marmot-v2.md, Phase 5, on why the transcript is not yet corrected. + */ + fun settleLater(): Job = scope.launch { + while (true) { + delay(SETTLE_TICK_MS) + val resolutions = runCatching { inbound.settleDueConvergence() } + .onFailure { logger.e("Convergence tick failed", it) } + .getOrDefault(emptyList()) + resolutions.forEach { resolution -> + logger.i( + "Convergence for ${resolution.groupId.take(8)}…: ${resolution.status}, epoch ${resolution.canonicalEpoch}" + + if (resolution.rewound) " -- REWOUND, the state that was canonical lost" else "" + ) + } + if (inbound.openConvergencePasses().isEmpty()) return@launch + } + } + + companion object { + /** The convergence policy's quiescence window: a pass may settle after one quiet second. */ + const val SETTLE_TICK_MS = 1_000L + + /** + * [result] as filed under [chatRoomId]. The processor names a group by its + * routing address; every row the app writes is keyed by the room, so the + * result is re-addressed once, here, rather than at each consumer. + */ + fun GroupEventResult.inRoom(chatRoomId: HexKey): GroupEventResult = when (this) { + is GroupEventResult.ApplicationMessage -> copy(groupId = chatRoomId) + is GroupEventResult.CommitProcessed -> copy(groupId = chatRoomId) + is GroupEventResult.CommitPending -> copy(groupId = chatRoomId) + is GroupEventResult.Duplicate -> copy(groupId = chatRoomId) + is GroupEventResult.UndecryptableOuterLayer -> copy(groupId = chatRoomId) + is GroupEventResult.ProposalStaged -> copy(groupId = chatRoomId) + is GroupEventResult.AppMessageOnCandidateBranch -> copy(groupId = chatRoomId) + is GroupEventResult.RefusedByLifecycle -> copy(groupId = chatRoomId) + is GroupEventResult.Error -> copy(groupId = chatRoomId) + } + } +} diff --git a/composeApp/src/commonMain/kotlin/to/curare/compose/managers/RoomMlsGroupStateStore.kt b/composeApp/src/commonMain/kotlin/to/curare/compose/managers/RoomMlsGroupStateStore.kt new file mode 100644 index 00000000..2d86afc4 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/to/curare/compose/managers/RoomMlsGroupStateStore.kt @@ -0,0 +1,101 @@ +package to.curare.compose.managers + +import co.touchlab.kermit.Logger +import com.vitorpamplona.quartz.marmot.mls.codec.TlsReader +import com.vitorpamplona.quartz.marmot.mls.codec.TlsWriter +import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupStateStore +import com.vitorpamplona.quartz.marmot.mls.group.RetainedEpochSecrets +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import to.curare.compose.database.CurareDatabase +import to.curare.compose.database.model.MarmotRetainedEpochSecret +import to.curare.compose.extensions.toHex + +/** + * quartz's group state store over the app's own tables. + * + * The library keys a group by its `nostr_group_id` -- the routing address -- and the + * app keys a room by its id, so every call here resolves the address through + * `MarmotRouting` first (a room with no row is its own address). The state itself is + * `ChatRoom.mlsGroupState`, the same hex the app has always written there; the + * retained epochs are `MarmotRetainedEpochSecret` rows, one per epoch, which until + * this store were written by the outbound path and read back by nothing -- every + * epoch the inbound path retained was a map in an `object`, gone at the next launch. + * + * A save for a room that does not exist yet is dropped with a log rather than + * creating one: the room row is what carries the state when a room is made, and + * the manager takes the group over once the row is there. + * + * Encryption at rest is what it was: the library's interface says MUST, the app's + * `TODO(security)` says the same, and moving the bytes behind an interface neither + * fixes nor worsens it. It does make the eventual fix one class. + * + * See docs/marmot-v2.md, Phase 5. + */ +class RoomMlsGroupStateStore( + private val database: CurareDatabase, +) : MlsGroupStateStore { + private val logger = Logger.withTag("RoomMlsGroupStateStore") + + private suspend fun chatRoomIdFor(nostrGroupId: String): String = + database.marmotRoutingDao().chatRoomIdFor(nostrGroupId) + + override suspend fun save(nostrGroupId: String, state: ByteArray) { + val chatRoomId = chatRoomIdFor(nostrGroupId) + if (!database.chatRoomDao().exists(chatRoomId)) { + logger.w("No room for $nostrGroupId; its state is not saved") + return + } + database.chatRoomDao().updateMlsGroupState(chatRoomId, state.toHex()) + } + + override suspend fun load(nostrGroupId: String): ByteArray? = + database.chatRoomDao().getMlsGroupState(chatRoomIdFor(nostrGroupId))?.hexToByteArray() + + override suspend fun delete(nostrGroupId: String) { + val chatRoomId = chatRoomIdFor(nostrGroupId) + database.chatRoomDao().updateMlsGroupState(chatRoomId, null) + database.marmotRetainedEpochSecretDao().deleteForChatRoomId(chatRoomId) + } + + override suspend fun listGroups(): List = + database.chatRoomDao().getChatRoomIdsWithMlsState().map { chatRoomId -> + database.marmotRoutingDao().activeRoutingIdFor(chatRoomId) + } + + override suspend fun saveRetainedEpochs(nostrGroupId: String, retainedSecrets: List) { + val chatRoomId = chatRoomIdFor(nostrGroupId) + val dao = database.marmotRetainedEpochSecretDao() + // Replaced whole rather than merged: the manager's window is the truth and it + // trims from the front, so a row it no longer lists has fallen out of it. + dao.deleteForChatRoomId(chatRoomId) + retainedSecrets.forEach { bytes -> + val retained = RetainedEpochSecrets.decodeTls(TlsReader(bytes)) + dao.insert( + MarmotRetainedEpochSecret( + chatRoomId = chatRoomId, + epoch = retained.epoch, + senderDataSecret = retained.senderDataSecret, + encryptionSecret = retained.encryptionSecret, + leafCount = retained.leafCount, + exporterSecret = retained.exporterSecret, + ) + ) + } + } + + override suspend fun loadRetainedEpochs(nostrGroupId: String): List = + database.marmotRetainedEpochSecretDao() + .getMarmotRetainedEpochSecretForChatRoomId(chatRoomIdFor(nostrGroupId)) + .sortedBy { it.epoch } + .map { row -> + val writer = TlsWriter() + RetainedEpochSecrets( + epoch = row.epoch, + senderDataSecret = row.senderDataSecret, + encryptionSecret = row.encryptionSecret, + leafCount = row.leafCount, + exporterSecret = row.exporterSecret, + ).encodeTls(writer) + writer.toByteArray() + } +} diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/managers/CurrentProfileInteropJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/managers/CurrentProfileInteropJvmTest.kt new file mode 100644 index 00000000..5b311656 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/managers/CurrentProfileInteropJvmTest.kt @@ -0,0 +1,247 @@ +package to.curare.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.marmot.GroupEventResult +import com.vitorpamplona.quartz.marmot.MarmotInboundProcessor +import com.vitorpamplona.quartz.marmot.MarmotOutboundProcessor +import com.vitorpamplona.quartz.marmot.appComponents.CurrentProfileGroupFactory +import com.vitorpamplona.quartz.marmot.appComponents.GroupProfileV1 +import com.vitorpamplona.quartz.marmot.foundation.appEvents.MarmotAppEvent +import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageEvent +import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageRotationManager +import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageUtils +import com.vitorpamplona.quartz.marmot.mip02Welcome.WelcomeEvent +import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent +import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupManager +import com.vitorpamplona.quartz.marmot.mls.group.MlsGroupStateStore +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal +import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerSync +import com.vitorpamplona.quartz.nip59Giftwrap.rumors.RumorAssembler +import com.vitorpamplona.quartz.nip59Giftwrap.seals.SealedRumorEvent +import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent +import com.vitorpamplona.quartz.nipC7Chats.ChatEvent +import com.vitorpamplona.quartz.utils.RandomInstance +import com.vitorpamplona.quartz.utils.TimeUtils +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import to.curare.compose.database.CurareDatabase +import to.curare.compose.database.builder.getRoomDatabase +import to.curare.compose.database.model.MarmotInnerEvent +import to.curare.compose.database.model.NostrEvent +import to.curare.compose.database.model.Profile +import to.curare.compose.database.repository.DatabaseMarmotRepository +import to.curare.compose.nostr.MarmotProfile +import to.curare.compose.nostr.Relays +import kotlin.io.encoding.Base64 +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * Two implementations in one current-profile group: the app's engine over a + * `CurareDatabase`, and a bare library stand-in -- `MlsGroupManager` and the two + * processors over an in-memory store -- playing Amethyst. docs/marmot-v2.md, + * Phases 5 and 8. + * + * The stand-in makes the group and invites the app; the Welcome arrives as a NIP-59 + * gift wrap through the sync funnel; then messages cross in both directions, a + * commit from the other side moves the app's room, and a second engine over the + * same database -- a restart -- reads a message from the epoch before it. + */ +class CurrentProfileInteropJvmTest { + + private val db: CurareDatabase = getRoomDatabase( + Room.inMemoryDatabaseBuilder() + ) + private val marmotRepository = DatabaseMarmotRepository(db, CoroutineScope(Dispatchers.Default)) + + @AfterTest + fun closeDb() = db.close() + + private val user = KeyPair() + private val userHex = user.pubKey.toHexKey() + private val relay = "wss://relay.example" + + /** Amethyst: quartz's own managers over a store that forgets nothing while the test runs. */ + private class StandIn(val keyPair: KeyPair) { + val hex = keyPair.pubKey.toHexKey() + val signer = NostrSignerInternal(keyPair) + private val store = object : MlsGroupStateStore { + private val states = mutableMapOf() + private val retained = mutableMapOf>() + override suspend fun save(nostrGroupId: String, state: ByteArray) { states[nostrGroupId] = state } + override suspend fun load(nostrGroupId: String): ByteArray? = states[nostrGroupId] + override suspend fun delete(nostrGroupId: String) { states.remove(nostrGroupId); retained.remove(nostrGroupId) } + override suspend fun listGroups(): List = states.keys.toList() + override suspend fun saveRetainedEpochs(nostrGroupId: String, retainedSecrets: List) { retained[nostrGroupId] = retainedSecrets } + override suspend fun loadRetainedEpochs(nostrGroupId: String): List = retained[nostrGroupId].orEmpty() + } + val manager = MlsGroupManager(store) + val inbound = MarmotInboundProcessor(manager, KeyPackageRotationManager()) + val outbound = MarmotOutboundProcessor(manager) + } + + private val amethyst = StandIn(KeyPair()) + + private suspend fun seedProfile(publicKey: String, name: String) { + val eventId = publicKey.take(32).padEnd(64, 'e') + db.nostrEventDao().upsert(NostrEvent(id = eventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = eventId)) + } + + private suspend fun store(event: Event) = db.nostrDao().storeNostrEvent( + nostrEvent = NostrEvent( + id = event.id, pubKey = event.pubKey, kind = event.kind, tags = event.tags, + content = event.content, sig = event.sig, createdAt = Instant.fromEpochSeconds(event.createdAt), + ), + relayURL = relay, + synchronizationRelayURLs = listOf(relay), + level = 0, + activeKeyPair = user, + ) + + /** The app's own published current-profile package, signed as the notary would. */ + private suspend fun ourKeyPackageEvent(): KeyPackageEvent { + marmotRepository.publishMarmotKeyPackageBundle(user, setOf(MarmotProfile.CURRENT)) + val unsigned = db.unsignedNostrEventDao().getAllUnprocessedUnsignedNostrEvents() + .single { it.kind == KeyPackageEvent.KIND && it.pubKey == userHex } + return NostrSignerSync(user).signNormal( + createdAt = unsigned.createdAt.epochSeconds, kind = unsigned.kind, tags = unsigned.tags, content = unsigned.content, + ) + } + + /** The stand-in makes its group, adds us, and we join from the gift-wrapped Welcome. */ + private suspend fun joinedRoom(): String { + seedProfile(userHex, "us") + val ourEvent = ourKeyPackageEvent() + val ourKeyPackage = KeyPackageUtils.decodeKeyPackage(Base64.decode(ourEvent.content)) + + val routingId = RandomInstance.bytes(32) + val routingHex = routingId.toHexKey() + val group = CurrentProfileGroupFactory.createGroup( + signer = amethyst.signer, + nostrGroupId = routingId, + relays = Relays.DefaultDMRelayList.map { it.url }, + profile = GroupProfileV1(name = "interop", description = ""), + ) + amethyst.manager.adoptGroup(routingHex, group) + amethyst.inbound.trackGroup(routingHex) + + val commit = amethyst.manager.addMember(routingHex, ourKeyPackage.toTlsBytes()) + val welcomeTemplate = WelcomeEvent.build( + welcomeBase64 = Base64.encode(assertNotNull(commit.welcomeBytes)), + keyPackageEventId = ourEvent.id, + relays = Relays.DefaultDMRelayList, + nostrGroupId = routingHex, + ) + val inviterSigner = NostrSignerSync(amethyst.keyPair) + val rumor = RumorAssembler.assembleRumor(pubKey = amethyst.hex, ev = welcomeTemplate) + val seal = inviterSigner.signNormal( + createdAt = rumor.createdAt, kind = SealedRumorEvent.KIND, tags = emptyArray(), + content = inviterSigner.nip44Encrypt(rumor.toJson(), userHex), + ) + store(GiftWrapEvent.create(event = seal, recipientPubKey = userHex, createdAt = rumor.createdAt)) + + assertNotNull(db.chatRoomDao().findChatRoomById(routingHex), "the app did not join") + return routingHex + } + + private suspend fun theirMessage(routingHex: String, text: String): GroupEvent = + amethyst.outbound.buildAppEvent( + routingHex, + MarmotAppEvent.build(pubKey = amethyst.hex, kind = ChatEvent.KIND, content = text, createdAt = TimeUtils.now()), + ).signedEvent + + private suspend fun transcript(roomId: String) = + db.chatMessageDao().getChatMessagesByChatRoomId(roomId).map { it.chatMessage } + + @Test + fun `a message from the other implementation is read and attributed to its sender`() = runBlocking { + val roomId = joinedRoom() + + store(theirMessage(roomId, "hello from the other side")) + + val line = assertNotNull(transcript(roomId).firstOrNull { it.content == "hello from the other side" }, "the message was not filed") + assertEquals(amethyst.hex, line.senderPublicKey) + assertFalse(line.isUserMessage) + } + + @Test + fun `a message the app sends is read by the other implementation, as a canonical payload`() = runBlocking { + val roomId = joinedRoom() + val room = assertNotNull(db.chatRoomDao().findChatRoomById(roomId)) + val inner = MarmotInnerEvent( + id = "7".repeat(64), publicKey = userHex, chatRoomId = roomId, kind = ChatEvent.KIND, + tags = emptyArray(), content = "hi back", + ) + + db.marmotOutboundDao().encryptAndSendMarmotInnerEvent( + localChatRoom = room, + mlsGroup = assertNotNull(room.chatRoom.toMlsGroup()), + marmotInnerEvent = inner, + nostrSignerSync = NostrSignerSync(user), + ) + + val sent = db.nostrEventDao().getMLSGroupEvents(since = Instant.fromEpochSeconds(0), limit = 10) + .mapNotNull { it.toGroupEvent(userHex) } + .single() + val result = assertIs(amethyst.inbound.processGroupEvent(sent)) + val payload = assertNotNull(MarmotAppEvent.decodeOrNull(result.innerEventJson.replace(",\"sig\":\"\"}", "}")), "not a canonical payload") + assertEquals("hi back", payload.content) + assertEquals(userHex, payload.pubKey) + } + + /** + * A commit from the other side moves the app's room to the same epoch, adds the + * member it added, and is persisted by the engine's manager -- the state on the + * row is the manager's, not a stale instance's. + */ + @Test + fun `a commit from the other implementation moves the room and its membership`() = runBlocking { + val roomId = joinedRoom() + val third = KeyPair() + seedProfile(third.pubKey.toHexKey(), "third") + val thirdPackage = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(third)).keyPackage + + val commit = amethyst.manager.addMember(roomId, thirdPackage.toTlsBytes()) + val commitEvent = amethyst.outbound.buildCommitEvent(roomId, commit.framedCommitBytes, commit.preCommitExporterSecret).signedEvent + store(commitEvent) + + val room = assertNotNull(db.chatRoomDao().findChatRoomById(roomId)) + val restored = assertNotNull(room.chatRoom.toMlsGroup()) + assertEquals(amethyst.manager.getGroup(roomId)!!.epoch, restored.epoch, "the app's persisted epoch lags the group's") + assertTrue(restored.currentMemberIdentities().contains(third.pubKey.toHexKey())) + assertTrue(room.localParticipants.any { it.participant.participantPublicKey == third.pubKey.toHexKey() }, "the new member has no row") + // And the epoch left behind is on disk, not in a map. + assertTrue(db.marmotRetainedEpochSecretDao().getMarmotRetainedEpochSecretForChatRoomId(roomId).isNotEmpty()) + } + + /** + * The case the old pipeline could not pass: a message from the epoch before a + * commit, read by an engine rebuilt over the same database -- the retained epochs + * come back from the store rather than from a map that died with the process. + */ + @Test + fun `a message from the prior epoch decrypts after the engine is rebuilt`() = runBlocking { + val roomId = joinedRoom() + val late = theirMessage(roomId, "sent before the commit") + + val third = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(KeyPair())).keyPackage + val commit = amethyst.manager.addMember(roomId, third.toTlsBytes()) + store(amethyst.outbound.buildCommitEvent(roomId, commit.framedCommitBytes, commit.preCommitExporterSecret).signedEvent) + + val rebuilt = MarmotEngine(db) + assertNotNull(rebuilt.groupFor(roomId), "the rebuilt engine does not restore the room") + val result = assertIs(rebuilt.inbound.processGroupEvent(late)) + assertTrue(result.innerEventJson.contains("sent before the commit")) + } +} diff --git a/composeApp/src/jvmTest/kotlin/to/curare/compose/managers/RoomMlsGroupStateStoreJvmTest.kt b/composeApp/src/jvmTest/kotlin/to/curare/compose/managers/RoomMlsGroupStateStoreJvmTest.kt new file mode 100644 index 00000000..37a4d95a --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/to/curare/compose/managers/RoomMlsGroupStateStoreJvmTest.kt @@ -0,0 +1,103 @@ +package to.curare.compose.managers + +import androidx.room3.Room +import com.vitorpamplona.quartz.marmot.mls.codec.TlsWriter +import com.vitorpamplona.quartz.marmot.mls.group.RetainedEpochSecrets +import kotlinx.coroutines.runBlocking +import to.curare.compose.database.CurareDatabase +import to.curare.compose.database.builder.getRoomDatabase +import to.curare.compose.database.model.ChatRoom +import to.curare.compose.database.model.MarmotRouting +import to.curare.compose.database.model.NostrEvent +import to.curare.compose.database.model.Profile +import to.curare.compose.extensions.toHex +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** + * The library's store contract over the app's tables: keyed by routing address, + * resolved to the room, and the retained epochs as rows rather than a map. + */ +class RoomMlsGroupStateStoreJvmTest { + private val db: CurareDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val store = RoomMlsGroupStateStore(db) + + @AfterTest + fun closeDb() = db.close() + + private val roomId = "a".repeat(64) + private val address = "b".repeat(64) + private val user = "c".repeat(64) + + private suspend fun seedRoom(routed: Boolean) { + // A room's user is a Profile, and a Profile hangs off its kind 0. + db.nostrEventDao().upsert(NostrEvent(id = "e".repeat(64), pubKey = user, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128))) + db.profileDao().upsert(Profile(publicKey = user, userName = "user", nostrEventId = "e".repeat(64))) + db.chatRoomDao().upsert(ChatRoom(id = roomId, userPublicKey = user, subject = null, description = null, mlsGroupState = "00")) + if (routed) db.marmotRoutingDao().upsert(MarmotRouting(routingId = address, chatRoomId = roomId)) + } + + private fun retained(epoch: Long) = TlsWriter().also { writer -> + RetainedEpochSecrets( + epoch = epoch, + senderDataSecret = ByteArray(32) { epoch.toByte() }, + encryptionSecret = ByteArray(32) { (epoch + 1).toByte() }, + leafCount = 3, + exporterSecret = ByteArray(32) { (epoch + 2).toByte() }, + ).encodeTls(writer) + }.toByteArray() + + @Test + fun `a routed room is listed, saved and loaded by its address`() = runBlocking { + seedRoom(routed = true) + + assertEquals(listOf(address), store.listGroups()) + store.save(address, byteArrayOf(1, 2, 3)) + assertContentEquals(byteArrayOf(1, 2, 3), store.load(address)) + assertEquals("010203", db.chatRoomDao().getMlsGroupState(roomId)) + } + + @Test + fun `a room with no routing row is its own address`() = runBlocking { + seedRoom(routed = false) + + assertEquals(listOf(roomId), store.listGroups()) + store.save(roomId, byteArrayOf(9)) + assertEquals("09", db.chatRoomDao().getMlsGroupState(roomId)) + } + + @Test + fun `a save for a room that does not exist is dropped`() = runBlocking { + store.save("d".repeat(64), byteArrayOf(1)) + + assertNull(store.load("d".repeat(64))) + assertEquals(emptyList(), store.listGroups()) + } + + @Test + fun `retained epochs round-trip as rows and are replaced whole`() = runBlocking { + seedRoom(routed = true) + + store.saveRetainedEpochs(address, listOf(retained(1), retained(2))) + assertEquals(listOf(1L, 2L), db.marmotRetainedEpochSecretDao().getMarmotRetainedEpochSecretForChatRoomId(roomId).map { it.epoch }.sorted()) + assertEquals(listOf(retained(1).toHex(), retained(2).toHex()), store.loadRetainedEpochs(address).map { it.toHex() }) + + // The manager's window trims from the front; the rows follow it. + store.saveRetainedEpochs(address, listOf(retained(2), retained(3))) + assertEquals(listOf(2L, 3L), db.marmotRetainedEpochSecretDao().getMarmotRetainedEpochSecretForChatRoomId(roomId).map { it.epoch }.sorted()) + } + + @Test + fun `deleting a group clears its state and its epochs`() = runBlocking { + seedRoom(routed = true) + store.saveRetainedEpochs(address, listOf(retained(1))) + + store.delete(address) + + assertNull(store.load(address)) + assertEquals(emptyList(), store.loadRetainedEpochs(address)) + } +}