feat(marmot): current-profile rooms, and a routing address apart from the room id (v2 Phase 4)
After this the app can create rooms on the current profile -- behind MarmotProfile.DEFAULT_FOR_NEW_ROOMS, which stays legacy until the rollout flips it -- and every path keyed on the `h` tag reads the room through its address. docs/marmot-v2.md, Phase 4. The room's id is a key. A room built around a threshold key is keyed on the id derived from that key -- the one it signs as and every chronicle is verified against -- and every member can compute it unaided. v2's routing component says of `nostr_group_id` the opposite: random, never derived from any public key, because a derivable address lets a relay link a group's traffic to the identity behind it, which here is the key that authors the group's published entries. Both are right about their own value, so they are two values now. A new MarmotRouting table (schema 21 -> 22) maps an address to its room; a current-profile room this app creates mints a random one, and every other room -- legacy, or made by another client -- has a row whose address is its own id, or no row at all and is addressed by its own id, which every reader falls back to. The inbound ingest, the reindex, the negentropy answer for a `#h` filter, the chat list's sync request and the live subscriptions all resolve or emit addresses; LocalChatRoom carries its routings as a relation so the subscription planner needs no query; the outbound commit, application and Welcome templates are stamped with the room's address rather than its id. A joiner keys a room on the group's `nostr_group_id`, which for a current-profile room would be the address, and the creator, the joiner's own DKG session and every chronicle know the room by its derived id. The components carry no field for it, so it rides in the group profile's description as one line -- `Room id: <hex>` -- the way the derivation path already does, and MlsGroup.roomId() reads it back first. It is a claim by the creator, exactly as the legacy `nostr_group_id` was, and is trusted no further. MarmotGroupFactory is now the one place a group is minted. The three sites -- a direct message, the convenient room, and the derived room MarmotGroupCreation builds -- say what the room is, and the factory decides the profile: a legacy group is the 0xF2EE extension as before; a current-profile group is quartz's own CurrentProfileGroupFactory with the admin policy, routing, profile and the creator's proof-bearing leaf, and no 0xF2EE at all, because RFC 9420 requires every member to support every GroupContext extension and an MDK leaf does not advertise it. Creating a direct-message room reads the identity from the chat repository, which now takes it, so the creator's leaf can carry its proof. A peer's KeyPackage is picked by the room's profile rather than by age: a current-profile room takes the newest current-profile package or none, since the legacy package is deliberately the newest a peer publishes. A leaf on the wrong profile is refused a step before the library refuses it, with a reason the member can act on -- their package is from an older profile -- shown on the confirmation screen and in the room's line rather than as "try again". Tests: MarmotGroupFactoryJvmTest pins both profiles' shapes, the address minted apart from the room id, the room id riding in the description, the read-only creator refused on the current profile, and which leaves fit which groups; MarmotGroupCreationJvmTest adds a current-profile room keeping its derived id with a routing row, a legacy room unchanged, and a kind:445 under the address filed in the room; MarmotRoomIdentityTest the description line; LiveSubscriptionPlanTest the addresses watched. Full JVM suite: 1,166 pass. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
99dba546d8
commit
9b5e4c95fc
31 files changed
+6669
-132
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -41,6 +41,7 @@ import to.curare.compose.database.dao.MarmotOutboundDao
|
||||
import to.curare.compose.database.dao.MarmotGroupEventDao
|
||||
import to.curare.compose.database.dao.MarmotInnerEventDao
|
||||
import to.curare.compose.database.dao.MarmotKeyPackageBundleDao
|
||||
import to.curare.compose.database.dao.MarmotRoutingDao
|
||||
import to.curare.compose.database.dao.MarmotKeyPackageDao
|
||||
import to.curare.compose.database.dao.MarmotRetainedEpochSecretDao
|
||||
import to.curare.compose.database.dao.MentionDao
|
||||
@@ -93,6 +94,7 @@ import to.curare.compose.database.model.MarmotGroupEvent
|
||||
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.database.model.MarmotRetainedEpochSecret
|
||||
import to.curare.compose.database.model.Mention
|
||||
import to.curare.compose.database.model.NegentropySynchronizeRequest
|
||||
@@ -158,6 +160,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
MarmotInnerEvent::class,
|
||||
MarmotKeyPackage::class,
|
||||
MarmotKeyPackageBundle::class,
|
||||
MarmotRouting::class,
|
||||
MarmotRetainedEpochSecret::class,
|
||||
Mention::class,
|
||||
NegentropySynchronizeRequest::class,
|
||||
@@ -177,7 +180,7 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
UnsignedNostrEvent::class,
|
||||
Zap::class
|
||||
],
|
||||
version = 21,
|
||||
version = 22,
|
||||
autoMigrations = [
|
||||
// v2 only adds the DkgSession/DkgParticipantMessage tables, so Room can
|
||||
// generate the migration itself — nothing existing changes shape.
|
||||
@@ -329,6 +332,14 @@ val GENESIS_AT = Instant.fromEpochMilliseconds(1231006505000L)
|
||||
// is what a room picks by. Rows from before read back null, which every
|
||||
// reader takes as legacy -- what they were.
|
||||
AutoMigration(from = 20, to = 21),
|
||||
// v22 adds MarmotRouting: the address a room's kind:445 traffic is carried
|
||||
// under, separate from the room's id (docs/marmot-v2.md, Phase 4). A
|
||||
// current-profile room this app creates mints a random routing id -- the
|
||||
// room's own id is a derived key, which v2's routing component says must
|
||||
// never be the address -- and every reader keyed on the `h` tag resolves it
|
||||
// through this table. No rows are backfilled: a room with none is addressed
|
||||
// by its own id, which is what every room before the table was.
|
||||
AutoMigration(from = 21, to = 22),
|
||||
]
|
||||
)
|
||||
@ColumnTypeConverters(CurareConverters::class)
|
||||
@@ -397,6 +408,7 @@ abstract class CurareDatabase: RoomDatabase() {
|
||||
abstract fun marmotInnerEventDao(): MarmotInnerEventDao
|
||||
|
||||
abstract fun marmotKeyPackageBundleDao(): MarmotKeyPackageBundleDao
|
||||
abstract fun marmotRoutingDao(): MarmotRoutingDao
|
||||
|
||||
abstract fun marmotKeyPackageDao(): MarmotKeyPackageDao
|
||||
|
||||
|
||||
+6
-1
@@ -1,7 +1,9 @@
|
||||
package to.curare.compose.database.dao
|
||||
|
||||
import androidx.room3.Dao
|
||||
import androidx.room3.Query
|
||||
import androidx.room3.Upsert
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import to.curare.compose.database.model.MarmotGroupEvent
|
||||
|
||||
@Dao
|
||||
@@ -9,4 +11,7 @@ interface MarmotGroupEventDao {
|
||||
|
||||
@Upsert
|
||||
suspend fun upsert(marmotGroupEvent: MarmotGroupEvent)
|
||||
}
|
||||
|
||||
@Query("SELECT * FROM MarmotGroupEvent WHERE id = :id")
|
||||
suspend fun getMarmotGroupEventById(id: HexKey): MarmotGroupEvent?
|
||||
}
|
||||
+13
@@ -21,6 +21,19 @@ interface MarmotKeyPackageDao {
|
||||
@Query("SELECT * FROM MarmotKeyPackage WHERE publicKey = :publicKey ORDER BY createdAt DESC LIMIT 1")
|
||||
fun observeMarmotKeyPackageForPublicKey(publicKey: HexKey): Flow<MarmotKeyPackage?>
|
||||
|
||||
/**
|
||||
* The newest package of one profile. A current-profile room can only add a
|
||||
* current-profile leaf, so it asks for that rather than for the newest of any --
|
||||
* which, while a peer publishes both, is deliberately the legacy one. Rows from
|
||||
* before the column have a null profile and are legacy, so they never answer for
|
||||
* "current". See docs/marmot-v2.md, Phase 3.
|
||||
*/
|
||||
@Query("SELECT * FROM MarmotKeyPackage WHERE publicKey = :publicKey AND profile = :profile ORDER BY createdAt DESC")
|
||||
suspend fun getMarmotKeyPackageForPublicKeyAndProfile(publicKey: HexKey, profile: String): MarmotKeyPackage?
|
||||
|
||||
@Query("SELECT * FROM MarmotKeyPackage WHERE publicKey = :publicKey AND profile = :profile ORDER BY createdAt DESC LIMIT 1")
|
||||
fun observeMarmotKeyPackageForPublicKeyAndProfile(publicKey: HexKey, profile: String): Flow<MarmotKeyPackage?>
|
||||
|
||||
@Query("SELECT * FROM MarmotKeyPackage WHERE id = :id ORDER BY createdAt DESC")
|
||||
suspend fun getMarmotKeyPackageById(id: HexKey): MarmotKeyPackage?
|
||||
|
||||
|
||||
+58
-28
@@ -15,9 +15,13 @@ import to.curare.compose.database.model.MarmotGroupEvent
|
||||
import to.curare.compose.database.model.MarmotInnerEvent
|
||||
import to.curare.compose.database.model.MarmotInnerEvent.Companion.disappearingExpiration
|
||||
import to.curare.compose.database.model.MarmotKeyPackage
|
||||
import to.curare.compose.database.model.MarmotRouting
|
||||
import to.curare.compose.managers.MarmotGroupFactory
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import to.curare.compose.database.model.MarmotRetainedEpochSecret
|
||||
import to.curare.compose.database.model.NostrEvent
|
||||
import to.curare.compose.database.model.Participant
|
||||
import to.curare.compose.exceptions.MarmotKeyPackageProfileException
|
||||
import to.curare.compose.exceptions.MarmotMissingChatGroupException
|
||||
import to.curare.compose.database.model.intermdiate.LocalChatRoom
|
||||
import to.curare.compose.extensions.exporterSecret
|
||||
@@ -59,26 +63,33 @@ abstract class MarmotOutboundDao(
|
||||
) {
|
||||
val logger = Logger.withTag(TAG)
|
||||
|
||||
/**
|
||||
* @param creator the room's creator. Its private key is needed when new rooms are
|
||||
* on the current profile -- see [MarmotGroupFactory]; a legacy room needs only
|
||||
* the public half, which is all a read-only identity has.
|
||||
*/
|
||||
@Transaction
|
||||
open suspend fun createMlsDirectMessageChatRoom(
|
||||
name: String? = null,
|
||||
description: String? = null,
|
||||
userPublicKey: HexKey,
|
||||
creator: KeyPair,
|
||||
peerPublicKey: HexKey,
|
||||
peerKeyPackage: MarmotKeyPackage,
|
||||
relays: List<String> = Relays.DefaultDMRelayList.map { it.url }
|
||||
relays: List<String> = Relays.DefaultDMRelayList.map { it.url },
|
||||
profile: MarmotProfile = MarmotProfile.DEFAULT_FOR_NEW_ROOMS,
|
||||
): String {
|
||||
val userPublicKey = creator.pubKey.toHexKey()
|
||||
val nostrGroupId = RandomInstance.bytes(32).toHexKey()
|
||||
val mlsGroup = MlsGroup.create(
|
||||
identity = userPublicKey.hexToByteArray(),
|
||||
initialExtensions = listOf(
|
||||
MarmotGroupData.bootstrap(
|
||||
nostrGroupId = nostrGroupId,
|
||||
creatorPubKey = userPublicKey,
|
||||
outboxRelays = relays,
|
||||
).toExtension()
|
||||
)
|
||||
val created = MarmotGroupFactory.create(
|
||||
creator = creator,
|
||||
roomId = nostrGroupId,
|
||||
name = name,
|
||||
description = description,
|
||||
adminPublicKeys = listOf(userPublicKey),
|
||||
relays = relays,
|
||||
profile = profile,
|
||||
)
|
||||
val mlsGroup = created.group
|
||||
|
||||
// Save Chat Room
|
||||
//
|
||||
@@ -98,6 +109,10 @@ abstract class MarmotOutboundDao(
|
||||
database.chatRoomDao().upsert(
|
||||
chatRoom
|
||||
)
|
||||
// The address the room's traffic travels under, which on the current
|
||||
// profile is not its id. Recorded before the invite, whose commit is the
|
||||
// first thing stamped with it.
|
||||
database.marmotRoutingDao().upsert(MarmotRouting(routingId = created.routingId, chatRoomId = chatRoom.id))
|
||||
|
||||
// Save Participants...
|
||||
database.participantDao().upsert(
|
||||
@@ -117,7 +132,7 @@ abstract class MarmotOutboundDao(
|
||||
|
||||
// Invite peer...
|
||||
inviteMember(
|
||||
nostrGroupId = nostrGroupId,
|
||||
chatRoomId = nostrGroupId,
|
||||
mlsGroup = mlsGroup,
|
||||
userPublicKey = userPublicKey,
|
||||
peerPublicKey = peerPublicKey,
|
||||
@@ -165,7 +180,7 @@ abstract class MarmotOutboundDao(
|
||||
)
|
||||
|
||||
inviteMember(
|
||||
nostrGroupId = localChatRoom.chatRoom.id,
|
||||
chatRoomId = localChatRoom.chatRoom.id,
|
||||
mlsGroup = mlsGroup,
|
||||
userPublicKey = localChatRoom.chatRoom.userPublicKey,
|
||||
peerPublicKey = peerPublicKey,
|
||||
@@ -338,7 +353,7 @@ abstract class MarmotOutboundDao(
|
||||
// transcript line instead, so its answer is what says whether this peer
|
||||
// was reached -- a runCatching here would see nothing to catch.
|
||||
val delivered = deliveryWelcome(
|
||||
nostrGroupId = localChatRoom.chatRoom.id,
|
||||
chatRoomId = localChatRoom.chatRoom.id,
|
||||
userPublicKey = localChatRoom.chatRoom.userPublicKey,
|
||||
welcomeBytes = welcomeBytes,
|
||||
peerKeyPackageEventId = peerKeyPackage.id,
|
||||
@@ -450,7 +465,7 @@ abstract class MarmotOutboundDao(
|
||||
}
|
||||
|
||||
private suspend fun inviteMember(
|
||||
nostrGroupId: HexKey,
|
||||
chatRoomId: HexKey,
|
||||
mlsGroup: MlsGroup,
|
||||
userPublicKey: HexKey,
|
||||
peerPublicKey: HexKey,
|
||||
@@ -458,6 +473,9 @@ abstract class MarmotOutboundDao(
|
||||
relays: List<String> = Relays.DefaultDMRelayList.map { it.url },
|
||||
) {
|
||||
logger.d("inviteMember: $peerPublicKey")
|
||||
// What the commit's kind:445 is stamped with: the room's address, which on
|
||||
// the current profile is not its id. See MarmotRouting.
|
||||
val routingId = database.marmotRoutingDao().activeRoutingIdFor(chatRoomId)
|
||||
|
||||
// Read before `addMember` advances the tree. A group holding only its
|
||||
// creator has nobody to tell about the commit -- no other member exists, and
|
||||
@@ -492,6 +510,16 @@ abstract class MarmotOutboundDao(
|
||||
"KeyPackage credential identity does not match memberPubKey"
|
||||
}
|
||||
|
||||
// The library refuses this too, at addMember, naming extension and proposal
|
||||
// numbers. Refused here first with a reason the member can act on: in a
|
||||
// current-profile room a leaf from an older build is the one failure that
|
||||
// is theirs to fix.
|
||||
if (!MarmotGroupFactory.leafFits(mlsGroup, keyPackage)) {
|
||||
throw MarmotKeyPackageProfileException(
|
||||
"${memberName(peerPublicKey)}'s key package is from an older Marmot profile; ask them to update"
|
||||
)
|
||||
}
|
||||
|
||||
// Say so now, not when the Welcome eventually goes out. On the deferred path
|
||||
// that is a relay round trip away and may never happen at all, and until this
|
||||
// line existed the room showed nothing whatsoever in the meantime -- an invite
|
||||
@@ -500,7 +528,7 @@ abstract class MarmotOutboundDao(
|
||||
// transaction, so an invite that does not survive `addMember` leaves no claim
|
||||
// that it did.
|
||||
announceMembership(
|
||||
chatRoomId = nostrGroupId,
|
||||
chatRoomId = chatRoomId,
|
||||
userPublicKey = userPublicKey,
|
||||
messageType = ChatMessage.TYPE_MEMBER_INVITED,
|
||||
content = "Invited ${memberName(peerPublicKey)} to the group",
|
||||
@@ -513,7 +541,7 @@ abstract class MarmotOutboundDao(
|
||||
|
||||
database.marmotRetainedEpochSecretDao().insert(
|
||||
MarmotRetainedEpochSecret(
|
||||
chatRoomId = nostrGroupId,
|
||||
chatRoomId = chatRoomId,
|
||||
epoch = retainedBefore.epoch,
|
||||
senderDataSecret = retainedBefore.senderDataSecret,
|
||||
encryptionSecret = retainedBefore.encryptionSecret,
|
||||
@@ -525,7 +553,7 @@ abstract class MarmotOutboundDao(
|
||||
// Trim retained epochs out of the retention window...
|
||||
val defenestratableMarmotRetainedEpochSecrets = database.marmotRetainedEpochSecretDao()
|
||||
.getDefenestratableMarmotRetainedEpochSecretForChatRoomId(
|
||||
chatRoomId = nostrGroupId,
|
||||
chatRoomId = chatRoomId,
|
||||
epochCutOffPoint = retainedBefore.epoch - EPOCH_RETENTION_WINDOW.toLong()
|
||||
)
|
||||
logger.d("Defenestratable Retained Epochs: ${defenestratableMarmotRetainedEpochSecrets.map { it.epoch }}")
|
||||
@@ -537,7 +565,7 @@ abstract class MarmotOutboundDao(
|
||||
// Send welcome event to participant
|
||||
commitResult.welcomeBytes?.let { welcomeBytes ->
|
||||
deliveryWelcome(
|
||||
nostrGroupId = nostrGroupId,
|
||||
chatRoomId = chatRoomId,
|
||||
userPublicKey = userPublicKey,
|
||||
welcomeBytes = welcomeBytes,
|
||||
peerKeyPackageEventId = peerKeyPackage.id,
|
||||
@@ -555,7 +583,7 @@ abstract class MarmotOutboundDao(
|
||||
|
||||
val template = GroupEvent.build(
|
||||
encryptedContentBase64 = encryptedContent,
|
||||
nostrGroupId = nostrGroupId
|
||||
nostrGroupId = routingId
|
||||
)
|
||||
|
||||
val ephemeralSigner = NostrSignerInternal(KeyPair())
|
||||
@@ -581,7 +609,7 @@ abstract class MarmotOutboundDao(
|
||||
publicKey = commitEvent.pubKey,
|
||||
userPublicKey = userPublicKey,
|
||||
expiresAt = commitEvent.expiration()?.let { Instant.fromEpochSeconds(it) },
|
||||
chatRoomId = nostrGroupId,
|
||||
chatRoomId = chatRoomId,
|
||||
signature = commitEvent.sig
|
||||
)
|
||||
)
|
||||
@@ -591,7 +619,7 @@ abstract class MarmotOutboundDao(
|
||||
MarmotCommitResult.from(
|
||||
commitEventId = commitEvent.id,
|
||||
commitResult = commitResult,
|
||||
chatRoomId = nostrGroupId,
|
||||
chatRoomId = chatRoomId,
|
||||
userPublicKey = userPublicKey,
|
||||
peerKeyPackageEventId = peerKeyPackage.id,
|
||||
isOneMemberInitialGroupCreation = isOneMemberInitialGroupCreation,
|
||||
@@ -622,7 +650,7 @@ abstract class MarmotOutboundDao(
|
||||
* Welcome that never went out.
|
||||
*/
|
||||
suspend fun deliveryWelcome(
|
||||
nostrGroupId: HexKey,
|
||||
chatRoomId: HexKey,
|
||||
userPublicKey: HexKey,
|
||||
welcomeBytes: ByteArray,
|
||||
peerKeyPackageEventId: HexKey,
|
||||
@@ -640,7 +668,9 @@ abstract class MarmotOutboundDao(
|
||||
createdAt = createdAt.epochSeconds,
|
||||
keyPackageEventId = peerKeyPackageEventId,
|
||||
relays = relays.map { NormalizedRelayUrl(it) },
|
||||
nostrGroupId = nostrGroupId,
|
||||
// The hint a joiner checks against the group's own routing component:
|
||||
// the room's address, not its id.
|
||||
nostrGroupId = database.marmotRoutingDao().activeRoutingIdFor(chatRoomId),
|
||||
)
|
||||
// Compute welcomeEventId
|
||||
val welcomeEventId = EventHasher.hashId(
|
||||
@@ -658,7 +688,7 @@ abstract class MarmotOutboundDao(
|
||||
GiftWrapPayload(
|
||||
id = welcomeEventId,
|
||||
publicKey = userPublicKey,
|
||||
chatRoomId = nostrGroupId,
|
||||
chatRoomId = chatRoomId,
|
||||
kind = welcomeEvent.kind,
|
||||
tags = welcomeEvent.tags,
|
||||
content = welcomeEvent.content,
|
||||
@@ -696,7 +726,7 @@ abstract class MarmotOutboundDao(
|
||||
// Welcome it rides behind.
|
||||
ChronicleManager.sendTo(
|
||||
database = database,
|
||||
chatRoomId = nostrGroupId,
|
||||
chatRoomId = chatRoomId,
|
||||
userPublicKey = userPublicKey,
|
||||
recipient = marmotKeyPackage.publicKey,
|
||||
)
|
||||
@@ -712,7 +742,7 @@ abstract class MarmotOutboundDao(
|
||||
// taking the invite's transaction down over a line about it.
|
||||
runCatching {
|
||||
announceInviteFailed(
|
||||
chatRoomId = nostrGroupId,
|
||||
chatRoomId = chatRoomId,
|
||||
userPublicKey = userPublicKey,
|
||||
peerPublicKey = database.marmotKeyPackageDao()
|
||||
.getMarmotKeyPackageById(peerKeyPackageEventId)?.publicKey,
|
||||
@@ -826,7 +856,7 @@ abstract class MarmotOutboundDao(
|
||||
// never carried one either.
|
||||
val template = GroupEvent.build(
|
||||
encryptedContentBase64 = encryptedContent,
|
||||
nostrGroupId = localChatRoom.chatRoom.id,
|
||||
nostrGroupId = localChatRoom.routingId,
|
||||
createdAt = createdAt,
|
||||
) {
|
||||
if (expirationTime != null) expiration(expirationTime)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package to.curare.compose.database.dao
|
||||
|
||||
import androidx.room3.Dao
|
||||
import androidx.room3.Query
|
||||
import androidx.room3.Upsert
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import to.curare.compose.database.model.MarmotRouting
|
||||
|
||||
@Dao
|
||||
interface MarmotRoutingDao {
|
||||
@Upsert
|
||||
suspend fun upsert(routing: MarmotRouting)
|
||||
|
||||
@Query("SELECT * FROM MarmotRouting WHERE routingId = :routingId")
|
||||
suspend fun findByRoutingId(routingId: HexKey): MarmotRouting?
|
||||
|
||||
@Query("SELECT * FROM MarmotRouting WHERE chatRoomId = :chatRoomId ORDER BY activeFromEpoch DESC")
|
||||
suspend fun findByChatRoomId(chatRoomId: HexKey): List<MarmotRouting>
|
||||
|
||||
/**
|
||||
* The room addressed by [routingId], or [routingId] itself when no row says
|
||||
* otherwise -- the fallback every room from before the table relies on, and the
|
||||
* truth for every room whose routing id is its own id.
|
||||
*/
|
||||
suspend fun chatRoomIdFor(routingId: HexKey): HexKey = findByRoutingId(routingId)?.chatRoomId ?: routingId
|
||||
|
||||
/** The address [chatRoomId]'s outbound traffic is stamped with right now. */
|
||||
suspend fun activeRoutingIdFor(chatRoomId: HexKey): HexKey =
|
||||
findByChatRoomId(chatRoomId).firstOrNull { it.isActive }?.routingId ?: chatRoomId
|
||||
}
|
||||
@@ -42,6 +42,9 @@ import to.curare.compose.managers.MarmotReindexSweep
|
||||
import to.curare.compose.managers.WelcomeBundleMatch
|
||||
import to.curare.compose.managers.roomDescription
|
||||
import to.curare.compose.managers.roomName
|
||||
import to.curare.compose.managers.roomId
|
||||
import to.curare.compose.managers.routingId
|
||||
import to.curare.compose.database.model.MarmotRouting
|
||||
import co.touchlab.kermit.Logger
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import com.vitorpamplona.quartz.marmot.GroupEventResult
|
||||
@@ -466,10 +469,13 @@ abstract class NostrDao(
|
||||
)?.let { groupEvent ->
|
||||
logger.d("groupEvent: ${groupEvent.toJson()}")
|
||||
|
||||
groupEvent.groupId()?.let { chatRoomId ->
|
||||
// The `h` tag is the room's address, which on the current profile is not
|
||||
// its id; the routing table says which room, and a room with no row is
|
||||
// addressed by its own id. See MarmotRouting.
|
||||
groupEvent.groupId()?.let { routingId ->
|
||||
indexMarmotGroupEvent(
|
||||
groupEvent = groupEvent,
|
||||
chatRoomId = chatRoomId,
|
||||
chatRoomId = database.marmotRoutingDao().chatRoomIdFor(routingId),
|
||||
activeKeyPair = activeKeyPair,
|
||||
)
|
||||
}
|
||||
@@ -775,11 +781,17 @@ abstract class NostrDao(
|
||||
)
|
||||
logger.d("Group: $group")
|
||||
|
||||
// From whichever profile the group is on: the routing
|
||||
// component for a current-profile group, the 0xF2EE
|
||||
// extension for a legacy one. A group with neither is
|
||||
// not a Marmot group and there is no room to make of it.
|
||||
val nostrGroupId = group.currentNostrGroupId() ?: throw MarmotMissingNostrGroupDataExtension("Didn't find group data for $group")
|
||||
// The room's address, from whichever profile the group
|
||||
// is on: the routing component for a current-profile
|
||||
// group, the 0xF2EE extension for a legacy one. A group
|
||||
// with neither is not a Marmot group and there is no
|
||||
// room to make of it. The room's *id* is what the group
|
||||
// says it is -- the address, unless its description names
|
||||
// the room, as a current-profile room this app created
|
||||
// does. See MarmotRoomIdentity and MarmotRouting.
|
||||
val routingId = group.routingId().takeIf { group.currentNostrGroupId() != null }
|
||||
?: throw MarmotMissingNostrGroupDataExtension("Didn't find group data for $group")
|
||||
val nostrGroupId = group.roomId()
|
||||
|
||||
logger.d("nostrGroupId: $nostrGroupId")
|
||||
|
||||
@@ -814,6 +826,10 @@ abstract class NostrDao(
|
||||
)
|
||||
)
|
||||
|
||||
database.marmotRoutingDao().upsert(
|
||||
MarmotRouting(routingId = routingId, chatRoomId = nostrGroupId)
|
||||
)
|
||||
|
||||
database.marmotKeyPackageBundleDao().upsert(
|
||||
marmotKeyPackageBundle.copy(
|
||||
consumed = true
|
||||
@@ -1548,16 +1564,19 @@ abstract class NostrDao(
|
||||
val userPublicKey = activeKeyPair.pubKey.toHex()
|
||||
val chatRoom = database.chatRoomDao().findChatRoomById(chatRoomId)?.chatRoom
|
||||
|
||||
// The query's LIKE only narrows; the h tag is what decides the room. Sorted
|
||||
// by CommitOrdering's own comparator rather than left in createdAt order, so
|
||||
// that where two commits compete for an epoch the first one replayed is the
|
||||
// one every other member also picked.
|
||||
val groupEvents = database.nostrEventDao()
|
||||
.getMarmotGroupNostrEventsByChatRoomId(chatRoomId)
|
||||
// The query's LIKE only narrows; the h tag is what decides the room, and the
|
||||
// h tag is one of the room's routing addresses -- its own id, or the ones the
|
||||
// routing table records. Sorted by CommitOrdering's own comparator rather
|
||||
// than left in createdAt order, so that where two commits compete for an
|
||||
// epoch the first one replayed is the one every other member also picked.
|
||||
val routingIds = database.marmotRoutingDao().findByChatRoomId(chatRoomId).map { it.routingId }.ifEmpty { listOf(chatRoomId) }
|
||||
val groupEvents = routingIds
|
||||
.flatMap { database.nostrEventDao().getMarmotGroupNostrEventsByChatRoomId(it) }
|
||||
.distinctBy { it.id }
|
||||
.mapNotNull { storedNostrEvent ->
|
||||
storedNostrEvent
|
||||
.toGroupEvent(userPublicKey = userPublicKey)
|
||||
?.takeIf { it.groupId() == chatRoomId }
|
||||
?.takeIf { it.groupId() in routingIds }
|
||||
}
|
||||
.sortedWith(CommitOrdering.comparator)
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
package to.curare.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
|
||||
|
||||
/**
|
||||
* The address a room's kind:445 traffic is carried under, and the room it belongs to.
|
||||
*
|
||||
* A room's id and its routing id are two values, and were one until the current
|
||||
* profile. `ChatRoom.id` is the room's identity: for a room this app makes with a
|
||||
* threshold key it is the key derived from that key, the one the room signs as and
|
||||
* every chronicle is verified against (docs/shared-key-derivation.md). The routing
|
||||
* id is the `nostr_group_id` in the group's `0x8004` component, the `h` tag on every
|
||||
* kind:445, and v2 says of it: random, and never derived from any public key,
|
||||
* because a derivable address lets a relay link a group's traffic to the identity
|
||||
* behind it -- which here would be the key that authors the group's published
|
||||
* entries. So a current-profile room this app creates mints one at random.
|
||||
*
|
||||
* Every other room has a row whose routing id *is* its room id: legacy rooms, where
|
||||
* the `0xF2EE` extension's `nostr_group_id` is what the room was keyed on, and rooms
|
||||
* created by other clients, whose routing id is the only id they have. A room with
|
||||
* no row at all -- one from before this table -- is addressed by its own id, which
|
||||
* is what every reader falls back to. See docs/marmot-v2.md, Phase 4.
|
||||
*
|
||||
* [retiredAtEpoch] is for routing rotation, which v2 describes and nothing here
|
||||
* writes yet: a member "has to be able to map several routing ids to one group"
|
||||
* while the epochs that used a prior one are still inside the retention window.
|
||||
*/
|
||||
@Entity(
|
||||
foreignKeys = [
|
||||
ForeignKey(
|
||||
entity = ChatRoom::class,
|
||||
parentColumns = ["id"],
|
||||
childColumns = ["chatRoomId"],
|
||||
onDelete = ForeignKey.CASCADE,
|
||||
),
|
||||
],
|
||||
indices = [
|
||||
Index("chatRoomId"),
|
||||
],
|
||||
)
|
||||
data class MarmotRouting(
|
||||
@PrimaryKey
|
||||
val routingId: HexKey,
|
||||
val chatRoomId: HexKey,
|
||||
/** The MLS epoch this address came into use at; 0 for one a room was created with. */
|
||||
val activeFromEpoch: Long = 0,
|
||||
/** The MLS epoch this address stopped being current at, or null while it is. */
|
||||
val retiredAtEpoch: Long? = null,
|
||||
) {
|
||||
val isActive: Boolean get() = retiredAtEpoch == null
|
||||
}
|
||||
+25
@@ -11,6 +11,7 @@ import androidx.room3.Embedded
|
||||
import androidx.room3.Relation
|
||||
import to.curare.compose.database.model.ChatMessage
|
||||
import to.curare.compose.database.model.ChatRoom
|
||||
import to.curare.compose.database.model.MarmotRouting
|
||||
import to.curare.compose.database.model.Participant
|
||||
import to.curare.compose.extensions.memberName
|
||||
import to.curare.compose.ui.composable.widgets.profile.ProfileColor
|
||||
@@ -36,7 +37,31 @@ data class LocalChatRoom(
|
||||
*/
|
||||
@Embedded(prefix = "lastMessage_")
|
||||
val lastChatMessage: ChatRoomLastMessage? = null,
|
||||
/**
|
||||
* The addresses this room's kind:445 traffic travels under. Empty for a room from
|
||||
* before the table, which is addressed by its own id -- see [routingId].
|
||||
*/
|
||||
@Relation(
|
||||
entity = MarmotRouting::class,
|
||||
parentColumns = ["id"],
|
||||
entityColumns = ["chatRoomId"],
|
||||
)
|
||||
val routings: List<MarmotRouting> = emptyList(),
|
||||
) {
|
||||
/**
|
||||
* The `h` tag to stamp on what this room sends now: its current routing id, or its
|
||||
* own id when it has none recorded. See [MarmotRouting].
|
||||
*/
|
||||
val routingId: HexKey
|
||||
get() = routings.filter { it.isActive }.maxByOrNull { it.activeFromEpoch }?.routingId ?: chatRoom.id
|
||||
|
||||
/**
|
||||
* Every address this room has ever been reachable at, current first, for the
|
||||
* filters that fetch its history. A room with no row is its own one address.
|
||||
*/
|
||||
val routingIds: List<HexKey>
|
||||
get() = routings.sortedByDescending { it.activeFromEpoch }.map { it.routingId }.ifEmpty { listOf(chatRoom.id) }
|
||||
|
||||
@Composable
|
||||
fun RenderChatRoomTitleText() {
|
||||
if (chatRoom.subject != null) {
|
||||
|
||||
+39
-8
@@ -2,6 +2,12 @@ package to.curare.compose.database.repository
|
||||
|
||||
import to.curare.compose.database.GENESIS_AT
|
||||
import to.curare.compose.database.CurareDatabase
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import to.curare.compose.database.model.MarmotRouting
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import to.curare.compose.identity.Identity
|
||||
import to.curare.compose.identity.toKeyPair
|
||||
import to.curare.compose.database.model.GroupKeyState
|
||||
import to.curare.compose.database.model.GroupSignedEvent
|
||||
import to.curare.compose.managers.ChronicleManager
|
||||
@@ -51,9 +57,16 @@ import kotlinx.coroutines.flow.Flow
|
||||
import kotlin.time.Clock
|
||||
import kotlin.time.Instant
|
||||
|
||||
/**
|
||||
* @param activeIdentity the identity the app runs as. Read by the one write here that
|
||||
* has to sign as it -- creating a direct-message room on the current profile puts
|
||||
* an account identity proof in the creator's leaf -- and by nothing else; a caller
|
||||
* that has only the public key still gets a legacy room without it.
|
||||
*/
|
||||
class DatabaseChatRepository(
|
||||
private val database: CurareDatabase,
|
||||
private val scope: CoroutineScope
|
||||
private val scope: CoroutineScope,
|
||||
private val activeIdentity: StateFlow<Identity?> = MutableStateFlow(null),
|
||||
): to.curare.compose.repository.ChatRepository {
|
||||
val logger = Logger.withTag(TAG)
|
||||
|
||||
@@ -306,13 +319,19 @@ class DatabaseChatRepository(
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun getMarmotKeyPackageForPublicKey(publicKey: HexKey): MarmotKeyPackage? {
|
||||
return database.marmotKeyPackageDao().getMarmotKeyPackageForPublicKey(publicKey)
|
||||
}
|
||||
override suspend fun getMarmotKeyPackageForPublicKey(publicKey: HexKey, roomProfile: MarmotProfile): MarmotKeyPackage? =
|
||||
when (roomProfile) {
|
||||
MarmotProfile.LEGACY -> database.marmotKeyPackageDao().getMarmotKeyPackageForPublicKey(publicKey)
|
||||
MarmotProfile.CURRENT -> database.marmotKeyPackageDao()
|
||||
.getMarmotKeyPackageForPublicKeyAndProfile(publicKey, MarmotProfile.CURRENT.wireName)
|
||||
}
|
||||
|
||||
override suspend fun observeMarmotKeyPackageForPublicKey(publicKey: HexKey): Flow<MarmotKeyPackage?> {
|
||||
return database.marmotKeyPackageDao().observeMarmotKeyPackageForPublicKey(publicKey)
|
||||
}
|
||||
override suspend fun observeMarmotKeyPackageForPublicKey(publicKey: HexKey, roomProfile: MarmotProfile): Flow<MarmotKeyPackage?> =
|
||||
when (roomProfile) {
|
||||
MarmotProfile.LEGACY -> database.marmotKeyPackageDao().observeMarmotKeyPackageForPublicKey(publicKey)
|
||||
MarmotProfile.CURRENT -> database.marmotKeyPackageDao()
|
||||
.observeMarmotKeyPackageForPublicKeyAndProfile(publicKey, MarmotProfile.CURRENT.wireName)
|
||||
}
|
||||
|
||||
override suspend fun createNip17ChatRoom(
|
||||
userPublicKey: HexKey,
|
||||
@@ -338,15 +357,27 @@ class DatabaseChatRepository(
|
||||
peerPublicKey: HexKey,
|
||||
peerKeyPackage: MarmotKeyPackage
|
||||
): String {
|
||||
// The active identity's key pair when it is the creator; otherwise a read-only
|
||||
// pair, which is enough for a legacy room and refused by the factory for a
|
||||
// current-profile one.
|
||||
val creator = activeIdentity.value
|
||||
?.takeIf { it.nostrPublicKey.equals(userPublicKey, ignoreCase = true) }
|
||||
?.toKeyPair()
|
||||
?: KeyPair(privKey = null, pubKey = userPublicKey.hexToByteArray())
|
||||
|
||||
return database.marmotOutboundDao().createMlsDirectMessageChatRoom(
|
||||
name = name,
|
||||
description = description,
|
||||
userPublicKey = userPublicKey,
|
||||
creator = creator,
|
||||
peerPublicKey = peerPublicKey,
|
||||
peerKeyPackage = peerKeyPackage
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun recordMarmotRouting(chatRoomId: HexKey, routingId: HexKey) {
|
||||
database.marmotRoutingDao().upsert(MarmotRouting(routingId = routingId, chatRoomId = chatRoomId))
|
||||
}
|
||||
|
||||
override suspend fun inviteMember(
|
||||
localChatRoom: LocalChatRoom,
|
||||
peerPublicKey: HexKey,
|
||||
|
||||
+6
-4
@@ -531,7 +531,7 @@ class DatabaseNostrRepository(
|
||||
|
||||
logger.d("welcomeBytes: ${welcomeBytes.toHex()}")
|
||||
val delivered = database.marmotOutboundDao().deliveryWelcome(
|
||||
nostrGroupId = marmotCommitResult.chatRoomId,
|
||||
chatRoomId = marmotCommitResult.chatRoomId,
|
||||
userPublicKey = marmotCommitResult.userPublicKey,
|
||||
welcomeBytes = welcomeBytes,
|
||||
peerKeyPackageEventId = marmotCommitResult.peerKeyPackageEventId,
|
||||
@@ -806,12 +806,14 @@ class DatabaseNostrRepository(
|
||||
NostrEventFilterQuery.NO_LIMIT
|
||||
}
|
||||
|
||||
val chatRoomIds = synchronizationFilter.marmotGroupChatRoomIds()
|
||||
if (chatRoomIds != null) {
|
||||
val routingIds = synchronizationFilter.marmotGroupChatRoomIds()
|
||||
if (routingIds != null) {
|
||||
// Group messages live in their own table, which carries the NIP-40 expiry a relay
|
||||
// uses to decide whether it still serves the event, and an indexed chatRoomId
|
||||
// rather than a scan of the tags JSON.
|
||||
// rather than a scan of the tags JSON. The filter names routing addresses, as a
|
||||
// relay indexes them; the table is keyed by room, so each is resolved first.
|
||||
logger.d("getMarmotGroupEvents($applyLimits): $synchronizationFilter")
|
||||
val chatRoomIds = routingIds.map { database.marmotRoutingDao().chatRoomIdFor(it) }.distinct().toTypedArray()
|
||||
return database.nostrEventDao().getMarmotGroupEvents(
|
||||
chatRoomIds = chatRoomIds,
|
||||
since = synchronizationFilter.since ?: GENESIS_AT,
|
||||
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package to.curare.compose.exceptions
|
||||
|
||||
/**
|
||||
* A peer's KeyPackage cannot join this room because its leaf is on the wrong Marmot
|
||||
* profile: a current-profile room requires a leaf that advertises the
|
||||
* `app_data_dictionary` extension and the `app_data_update` proposal, and a package
|
||||
* from an older build advertises neither. The member can fix that -- by updating --
|
||||
* and cannot fix a generic failure, which is why this is its own exception with a
|
||||
* message meant to be shown. See docs/marmot-v2.md, Phase 4.
|
||||
*/
|
||||
class MarmotKeyPackageProfileException(message: String? = null, cause: Throwable? = null) : Exception(message, cause)
|
||||
+6
-1
@@ -160,7 +160,12 @@ class LiveSubscriptionManager(
|
||||
rooms
|
||||
.filter { it.chatRoom.mlsGroupState != null }
|
||||
.filter { it.chatRoom.leftGroupAt == null && it.chatRoom.deletedAt == null }
|
||||
.map { it.chatRoom.id }
|
||||
// The addresses, not the ids: a relay indexes the `h` tag, and on the
|
||||
// current profile that is a routing id apart from the room's own. Every
|
||||
// address a room has had, so a message published to a prior one while
|
||||
// it is still inside the retention window is not missed.
|
||||
.flatMap { it.routingIds }
|
||||
.distinct()
|
||||
.sorted()
|
||||
|
||||
internal fun groupChunks(groupIds: List<HexKey>): List<List<HexKey>> =
|
||||
|
||||
+23
-23
@@ -1,9 +1,7 @@
|
||||
package to.curare.compose.managers
|
||||
|
||||
import co.touchlab.kermit.Logger
|
||||
import com.vitorpamplona.quartz.marmot.mip01Groups.MarmotGroupData
|
||||
import com.vitorpamplona.quartz.marmot.mls.crypto.Ed25519
|
||||
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroup
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
|
||||
import kotlinx.coroutines.async
|
||||
@@ -113,14 +111,15 @@ object MarmotGroupCreation {
|
||||
keyPair: KeyPair,
|
||||
path: List<Long> = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH,
|
||||
parentChatRoomId: HexKey? = null,
|
||||
keyPackageLookupTimeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT
|
||||
keyPackageLookupTimeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT,
|
||||
profile: MarmotProfile = MarmotProfile.DEFAULT_FOR_NEW_ROOMS,
|
||||
): Outcome {
|
||||
chatRepository.getChatRoomByIdentifier(groupId)?.let { return Outcome.Existing(it) }
|
||||
|
||||
val groupName = MarmotGroupName.of(name)
|
||||
|
||||
val peers = adminPublicKeys.filterNot { it == userPublicKey }
|
||||
val keyPackages = keyPackagesFor(chatRepository, peers, keyPackageLookupTimeout)
|
||||
val keyPackages = keyPackagesFor(chatRepository, peers, keyPackageLookupTimeout, profile)
|
||||
|
||||
val missing = keyPackages.filter { it.second == null }.map { it.first }
|
||||
if (missing.isNotEmpty()) {
|
||||
@@ -134,26 +133,24 @@ object MarmotGroupCreation {
|
||||
|
||||
val description = SharedKeyDerivation.describe(purpose = purpose, path = path)
|
||||
|
||||
// Built directly rather than through MarmotGroupData.bootstrap, which
|
||||
// hardcodes a single admin.
|
||||
val metadata = MarmotGroupData(
|
||||
nostrGroupId = groupId,
|
||||
// On whichever profile new rooms are on. The room id is the derived key
|
||||
// either way; on the current profile the group's routing address is minted
|
||||
// apart from it and the id rides in the description, so a joiner keys the
|
||||
// room as this device does. See MarmotGroupFactory and MarmotRoomIdentity.
|
||||
val created = MarmotGroupFactory.create(
|
||||
creator = keyPair,
|
||||
roomId = groupId,
|
||||
name = groupName,
|
||||
description = description,
|
||||
adminPubkeys = adminPublicKeys.toList(),
|
||||
relays = Relays.DefaultDMRelayList.map { it.url }
|
||||
adminPublicKeys = adminPublicKeys,
|
||||
relays = Relays.DefaultDMRelayList.map { it.url },
|
||||
profile = profile,
|
||||
)
|
||||
val group = created.group
|
||||
|
||||
val signingKeyPair = Ed25519.generateKeyPair()
|
||||
val group = MlsGroup.create(
|
||||
keyPair.pubKey,
|
||||
signingKeyPair.privateKey,
|
||||
listOf(metadata.toExtension())
|
||||
)
|
||||
|
||||
// Keyed on the Marmot nostrGroupId, not MlsGroup's own groupId: they are
|
||||
// unrelated 32-byte values, and every inbound path resolves rooms by the
|
||||
// former.
|
||||
// Keyed on the room id, not MlsGroup's own groupId and not the routing
|
||||
// address: they are unrelated 32-byte values, and every inbound path resolves
|
||||
// rooms to this one.
|
||||
val localChatRoom = chatRepository.getOrCreateChatRoom(
|
||||
chatRoomId = groupId,
|
||||
activeUserPublicKey = userPublicKey,
|
||||
@@ -163,6 +160,8 @@ object MarmotGroupCreation {
|
||||
mlsGroupState = group.saveState().encodeTls().toHex()
|
||||
) ?: return Outcome.Failed("Couldn't create the group. Please try again.")
|
||||
|
||||
chatRepository.recordMarmotRouting(chatRoomId = groupId, routingId = created.routingId)
|
||||
|
||||
if (parentChatRoomId != null) {
|
||||
// Written after the room exists rather than passed into its creation,
|
||||
// because `getOrCreateChatRoom` is shared with every other way a room
|
||||
@@ -254,12 +253,13 @@ object MarmotGroupCreation {
|
||||
suspend fun keyPackagesFor(
|
||||
chatRepository: ChatRepository,
|
||||
publicKeys: List<HexKey>,
|
||||
timeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT
|
||||
timeout: Long = KEY_PACKAGE_LOOKUP_TIMEOUT,
|
||||
profile: MarmotProfile = MarmotProfile.DEFAULT_FOR_NEW_ROOMS,
|
||||
): List<Pair<HexKey, MarmotKeyPackage?>> = coroutineScope {
|
||||
publicKeys.map { publicKey ->
|
||||
async {
|
||||
publicKey to withTimeoutOrNull(timeout) {
|
||||
chatRepository.observeMarmotKeyPackageForPublicKey(publicKey)
|
||||
chatRepository.observeMarmotKeyPackageForPublicKey(publicKey, profile)
|
||||
.filterNotNull()
|
||||
.first()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
package to.curare.compose.managers
|
||||
|
||||
import com.vitorpamplona.quartz.marmot.appComponents.CurrentProfileGroupFactory
|
||||
import com.vitorpamplona.quartz.marmot.appComponents.GroupProfileV1
|
||||
import com.vitorpamplona.quartz.marmot.mip01Groups.MarmotGroupData
|
||||
import com.vitorpamplona.quartz.marmot.mls.crypto.Ed25519
|
||||
import com.vitorpamplona.quartz.marmot.mls.components.AppDataDictionary
|
||||
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroup
|
||||
import com.vitorpamplona.quartz.marmot.mls.messages.MlsKeyPackage
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
|
||||
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.utils.RandomInstance
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
|
||||
/**
|
||||
* The one place a Marmot group is minted, on whichever profile new rooms are on.
|
||||
*
|
||||
* Three sites make rooms -- a direct message, the "convenient" room, and the derived
|
||||
* room `MarmotGroupCreation` builds around a threshold key -- and each used to hand
|
||||
* `MlsGroup.create` a `0xF2EE` extension of its own. The current profile is not one
|
||||
* more extension: epoch 0 carries `required_capabilities` naming extension `0x0006`
|
||||
* and proposal `0x0008`, a GroupContext dictionary with the required-component list,
|
||||
* the admin policy, the routing and the profile, and the creator's leaf with its
|
||||
* account identity proof -- and no `0xF2EE` at all, because RFC 9420 requires every
|
||||
* member to support every GroupContext extension and an MDK leaf does not advertise
|
||||
* it. So the profile is decided here, once, from [MarmotProfile.DEFAULT_FOR_NEW_ROOMS]
|
||||
* unless a caller says otherwise, and the three sites only say what the room is.
|
||||
*
|
||||
* **The routing id.** A legacy room's `nostr_group_id` is its room id; that is how
|
||||
* every room was keyed and how every other client keys the rooms it makes. A
|
||||
* current-profile room's is minted here at random, whatever its room id, because the
|
||||
* routing component says it must never be derived from a public key and the derived
|
||||
* room id is exactly that. The caller records the pair in `MarmotRouting`; the room
|
||||
* id stays the identity everything else is keyed on. See docs/marmot-v2.md, Phase 4.
|
||||
*/
|
||||
object MarmotGroupFactory {
|
||||
class Created(
|
||||
val group: MlsGroup,
|
||||
/** The `h` tag the room's kind:445 traffic carries. Equal to the room id on the legacy profile. */
|
||||
val routingId: HexKey,
|
||||
val profile: MarmotProfile,
|
||||
)
|
||||
|
||||
/**
|
||||
* @param creator the room's creator. Its private key is needed on the current
|
||||
* profile, where the creator's leaf carries a proof only the account key can
|
||||
* sign; a legacy room needs only the public half.
|
||||
* @param roomId what `ChatRoom.id` will be: derived for a room with a threshold key
|
||||
* behind it, random otherwise.
|
||||
* @param adminPublicKeys the founding admins. The creator is one whether or not it
|
||||
* is listed.
|
||||
*/
|
||||
suspend fun create(
|
||||
creator: KeyPair,
|
||||
roomId: HexKey,
|
||||
name: String?,
|
||||
description: String?,
|
||||
adminPublicKeys: Collection<HexKey>,
|
||||
relays: List<String>,
|
||||
profile: MarmotProfile = MarmotProfile.DEFAULT_FOR_NEW_ROOMS,
|
||||
): Created {
|
||||
val creatorHex = creator.pubKey.toHexKey()
|
||||
val admins = (listOf(creatorHex) + adminPublicKeys.filterNot { it == creatorHex }).distinct()
|
||||
|
||||
return when (profile) {
|
||||
MarmotProfile.LEGACY -> {
|
||||
val metadata = MarmotGroupData(
|
||||
nostrGroupId = roomId,
|
||||
name = name.orEmpty(),
|
||||
description = description.orEmpty(),
|
||||
adminPubkeys = admins,
|
||||
relays = relays,
|
||||
)
|
||||
val group = MlsGroup.create(
|
||||
identity = creatorHex.hexToByteArray(),
|
||||
signingKey = Ed25519.generateKeyPair().privateKey,
|
||||
initialExtensions = listOf(metadata.toExtension()),
|
||||
)
|
||||
Created(group = group, routingId = roomId, profile = profile)
|
||||
}
|
||||
|
||||
MarmotProfile.CURRENT -> {
|
||||
requireNotNull(creator.privKey) {
|
||||
"A current-profile room needs an identity that can sign: its leaf carries an account identity proof"
|
||||
}
|
||||
val routingId = RandomInstance.bytes(32)
|
||||
// The routing id is an address; the room id is what every member keys
|
||||
// the room on and what a joiner has to be told. It rides in the
|
||||
// description, as the derivation path does -- see MarmotRoomIdentity.
|
||||
val describedRoom = MarmotRoomIdentity.describe(description, roomId)
|
||||
val group = CurrentProfileGroupFactory.createGroup(
|
||||
signer = NostrSignerInternal(creator),
|
||||
nostrGroupId = routingId,
|
||||
relays = relays,
|
||||
// Byte-capped by the component (256 and 4096); a name is a `#name`
|
||||
// and a description is a sentence, a path and a room id, so the
|
||||
// caps only ever bind on input nobody meant, and cutting the
|
||||
// front of the description beats refusing the room over it. The
|
||||
// room-id line is last and is what must survive the cut.
|
||||
profile = GroupProfileV1(
|
||||
name = name.orEmpty().truncatedToBytes(GroupProfileV1.NAME_MAX_BYTES),
|
||||
description = describedRoom.truncatedToBytesKeepingTail(GroupProfileV1.DESCRIPTION_MAX_BYTES),
|
||||
),
|
||||
additionalAdmins = admins.filterNot { it == creatorHex }.map { it.hexToByteArray() },
|
||||
)
|
||||
Created(group = group, routingId = routingId.toHexKey(), profile = profile)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether [keyPackage]'s leaf can be added to [group]: it advertises what the
|
||||
* group's `required_capabilities` names.
|
||||
*
|
||||
* A current-profile group requires the `app_data_dictionary` extension and the
|
||||
* `app_data_update` proposal; a legacy group the `0xF2EE` extension and the
|
||||
* `self_remove` proposal. A current-profile leaf advertises all four, so it fits
|
||||
* either; a legacy leaf fits only a legacy group. The library checks the same
|
||||
* thing at `addMember` and refuses with the missing numbers; this is the same
|
||||
* answer a step earlier, so the refusal can name the profile instead.
|
||||
*/
|
||||
fun leafFits(group: MlsGroup, keyPackage: MlsKeyPackage): Boolean {
|
||||
val capabilities = keyPackage.leafNode.capabilities
|
||||
return if (group.currentGroupState().isCurrentProfile) {
|
||||
capabilities.extensions.contains(AppDataDictionary.EXTENSION_TYPE) &&
|
||||
capabilities.proposals.contains(APP_DATA_UPDATE_PROPOSAL_TYPE)
|
||||
} else {
|
||||
capabilities.extensions.contains(MarmotGroupData.EXTENSION_ID_INT) &&
|
||||
capabilities.proposals.contains(SELF_REMOVE_PROPOSAL_TYPE)
|
||||
}
|
||||
}
|
||||
|
||||
/** MLS proposal type `app_data_update` (draft-ietf-mls-extensions). */
|
||||
private const val APP_DATA_UPDATE_PROPOSAL_TYPE = 0x0008
|
||||
|
||||
/** MLS proposal type `self_remove` (draft-ietf-mls-extensions). */
|
||||
private const val SELF_REMOVE_PROPOSAL_TYPE = 0x000A
|
||||
|
||||
/** [this] cut to at most [maxBytes] of UTF-8, on a character boundary. */
|
||||
private fun String.truncatedToBytes(maxBytes: Int): String {
|
||||
if (encodeToByteArray().size <= maxBytes) return this
|
||||
var end = length
|
||||
while (end > 0 && substring(0, end).encodeToByteArray().size > maxBytes) end--
|
||||
return substring(0, end)
|
||||
}
|
||||
|
||||
/** [this] cut from the front to at most [maxBytes] of UTF-8, keeping its last line whole. */
|
||||
private fun String.truncatedToBytesKeepingTail(maxBytes: Int): String {
|
||||
if (encodeToByteArray().size <= maxBytes) return this
|
||||
val tail = substringAfterLast('\n')
|
||||
val head = substringBeforeLast('\n', missingDelimiterValue = "")
|
||||
val room = maxBytes - tail.encodeToByteArray().size - 1
|
||||
return if (room <= 0) tail else head.truncatedToBytes(room) + "\n" + tail
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package to.curare.compose.managers
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
|
||||
/**
|
||||
* How a current-profile room tells its joiners which room it is.
|
||||
*
|
||||
* A legacy room's id travels in its `0xF2EE` extension as the `nostr_group_id`, and
|
||||
* a joiner keys the room on it -- which for a room built around a threshold key is
|
||||
* the derived key every member can compute and the room signs as. A current-profile
|
||||
* room's `nostr_group_id` is a routing address minted at random (see `MarmotRouting`),
|
||||
* so a joiner reading only that would key the room on the address and disagree with
|
||||
* the creator, with its own DKG session and with every chronicle, all of which know
|
||||
* the room by its derived id.
|
||||
*
|
||||
* The components carry no field for it, so it rides in the group profile's
|
||||
* description, the way [SharedKeyDerivation.describe] already carries the path there:
|
||||
* one line, `Room id: <64 hex>`, which [parse] reads back. It is a claim by the
|
||||
* creator, exactly as the legacy `nostr_group_id` was; nothing here trusts it further
|
||||
* than the tables it keys, and a room with key state behind it checks the derivation
|
||||
* for itself in `GroupKeyStateManager.adopt`. See docs/marmot-v2.md, Phase 4.
|
||||
*/
|
||||
object MarmotRoomIdentity {
|
||||
private const val MARKER = "Room id: "
|
||||
private val HEX_64 = Regex("^[0-9a-f]{64}$")
|
||||
|
||||
/** [description] with the room-id line added, unless it already names [roomId]. */
|
||||
fun describe(description: String?, roomId: HexKey): String {
|
||||
val base = description.orEmpty()
|
||||
if (parse(base) == roomId) return base
|
||||
return if (base.isBlank()) "$MARKER$roomId" else "$base\n\n$MARKER$roomId"
|
||||
}
|
||||
|
||||
/** The room id a description names, or null when it names none or one that is not hex. */
|
||||
fun parse(description: String?): HexKey? {
|
||||
val line = description
|
||||
?.lineSequence()
|
||||
?.firstOrNull { it.trimStart().startsWith(MARKER) }
|
||||
?: return null
|
||||
return line.trimStart().removePrefix(MARKER).trim().lowercase().takeIf { HEX_64.matches(it) }
|
||||
}
|
||||
}
|
||||
@@ -24,11 +24,26 @@ import to.curare.compose.extensions.toHex
|
||||
*/
|
||||
|
||||
/**
|
||||
* The id this group's rooms are keyed on: the Marmot `nostr_group_id` from either
|
||||
* profile, or -- for a group that has no Marmot state, which only a test builds --
|
||||
* the MLS group id, which is what every caller fell back to before.
|
||||
* The id this group's room is keyed on.
|
||||
*
|
||||
* A current-profile room this app created names its room id in its profile
|
||||
* description -- see [MarmotRoomIdentity] -- because its `nostr_group_id` is a
|
||||
* routing address, not an identity. Every other group is keyed on its
|
||||
* `nostr_group_id`, from whichever profile carries it: a legacy room's derived or
|
||||
* random id, or the only id a room made by another client has. A group with neither,
|
||||
* which only a test builds, falls back to the MLS group id as every caller did before.
|
||||
*/
|
||||
fun MlsGroup.roomId(): HexKey = currentNostrGroupId() ?: groupId.toHex()
|
||||
fun MlsGroup.roomId(): HexKey =
|
||||
MarmotRoomIdentity.parse(currentGroupState().profile?.description)
|
||||
?: currentNostrGroupId()
|
||||
?: groupId.toHex()
|
||||
|
||||
/**
|
||||
* The `h` tag this group's kind:445 traffic carries: its `nostr_group_id` from either
|
||||
* profile, which for a current-profile room is a random address and for a legacy one
|
||||
* is the room id itself. Same fallback as [roomId] for a group with no Marmot state.
|
||||
*/
|
||||
fun MlsGroup.routingId(): HexKey = currentNostrGroupId() ?: groupId.toHex()
|
||||
|
||||
/** The group's display name, or null when it has none or it is blank. */
|
||||
fun MlsGroup.roomName(): String? =
|
||||
|
||||
@@ -6,6 +6,7 @@ import to.curare.compose.database.model.GroupKeyState
|
||||
import to.curare.compose.database.model.GroupSignedEvent
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
|
||||
import to.curare.compose.database.model.MarmotKeyPackage
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import to.curare.compose.managers.SharedKeyDerivation
|
||||
import to.curare.compose.managers.MarmotGroupCreation
|
||||
import to.curare.compose.managers.SubgroupManager
|
||||
@@ -201,9 +202,23 @@ interface ChatRepository {
|
||||
|
||||
suspend fun getChatMessageRelayForPublicKey(publicKey: HexKey): ChatMessageRelayListEvent?
|
||||
|
||||
suspend fun getMarmotKeyPackageForPublicKey(publicKey: HexKey): MarmotKeyPackage?
|
||||
/**
|
||||
* A peer's usable KeyPackage for a room on [roomProfile].
|
||||
*
|
||||
* A legacy room takes the newest of any profile -- both shapes fit it. A
|
||||
* current-profile room takes the newest current-profile package or none: the
|
||||
* legacy one is deliberately the newest a peer publishes while they publish both,
|
||||
* and cannot join a current-profile room. See docs/marmot-v2.md, Phase 3.
|
||||
*/
|
||||
suspend fun getMarmotKeyPackageForPublicKey(
|
||||
publicKey: HexKey,
|
||||
roomProfile: MarmotProfile = MarmotProfile.LEGACY,
|
||||
): MarmotKeyPackage?
|
||||
|
||||
suspend fun observeMarmotKeyPackageForPublicKey(publicKey: HexKey): Flow<MarmotKeyPackage?>
|
||||
suspend fun observeMarmotKeyPackageForPublicKey(
|
||||
publicKey: HexKey,
|
||||
roomProfile: MarmotProfile = MarmotProfile.LEGACY,
|
||||
): Flow<MarmotKeyPackage?>
|
||||
|
||||
/**
|
||||
* Creates a NIP-17 group: participants and a room, no MLS group. Membership is
|
||||
@@ -224,6 +239,13 @@ interface ChatRepository {
|
||||
peerKeyPackage: MarmotKeyPackage
|
||||
): String
|
||||
|
||||
/**
|
||||
* Record that [chatRoomId]'s kind:445 traffic travels under [routingId]. On the
|
||||
* legacy profile the two are one value; on the current profile the address is
|
||||
* minted at random and this is what ties it back. See `MarmotRouting`.
|
||||
*/
|
||||
suspend fun recordMarmotRouting(chatRoomId: HexKey, routingId: HexKey)
|
||||
|
||||
suspend fun inviteMember(
|
||||
localChatRoom: LocalChatRoom,
|
||||
peerPublicKey: HexKey,
|
||||
@@ -413,11 +435,11 @@ interface ChatRepository {
|
||||
return null
|
||||
}
|
||||
|
||||
override suspend fun getMarmotKeyPackageForPublicKey(publicKey: HexKey): MarmotKeyPackage? {
|
||||
override suspend fun getMarmotKeyPackageForPublicKey(publicKey: HexKey, roomProfile: MarmotProfile): MarmotKeyPackage? {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
override suspend fun observeMarmotKeyPackageForPublicKey(publicKey: HexKey): Flow<MarmotKeyPackage?> {
|
||||
override suspend fun observeMarmotKeyPackageForPublicKey(publicKey: HexKey, roomProfile: MarmotProfile): Flow<MarmotKeyPackage?> {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
@@ -440,6 +462,8 @@ interface ChatRepository {
|
||||
TODO("Not yet implemented")
|
||||
}
|
||||
|
||||
override suspend fun recordMarmotRouting(chatRoomId: HexKey, routingId: HexKey) = Unit
|
||||
|
||||
override suspend fun inviteMember(
|
||||
localChatRoom: LocalChatRoom,
|
||||
peerPublicKey: HexKey,
|
||||
|
||||
+2
-1
@@ -223,7 +223,8 @@ fun CurareNavHost(
|
||||
val databaseChatRepository = remember {
|
||||
DatabaseChatRepository(
|
||||
database = auxDatabaseManager.auxDatabase,
|
||||
applicationIOScope
|
||||
applicationIOScope,
|
||||
activeIdentity = sovereignWalletViewModel.activeIdentity,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+15
-3
@@ -10,6 +10,8 @@ import androidx.lifecycle.viewModelScope
|
||||
import androidx.lifecycle.viewmodel.initializer
|
||||
import androidx.lifecycle.viewmodel.viewModelFactory
|
||||
import to.curare.compose.database.model.MarmotKeyPackage
|
||||
import to.curare.compose.exceptions.MarmotKeyPackageProfileException
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import to.curare.compose.database.model.NegentropySynchronizeRequest
|
||||
import to.curare.compose.database.model.intermdiate.LocalChatRoom
|
||||
import to.curare.compose.database.model.types.SynchronizationFilter
|
||||
@@ -80,7 +82,13 @@ class AddMemberToChatRoomConfirmationViewModel(
|
||||
// Observe rather than read once: the key package usually lands a moment after
|
||||
// this screen opens, and the old one-shot read latched a terminal error that no
|
||||
// amount of waiting could clear.
|
||||
chatRepository.observeMarmotKeyPackageForPublicKey(profilePublicKey)
|
||||
// The package has to fit the room: a current-profile room can add only a
|
||||
// current-profile leaf, and the newest package of any profile is, while a
|
||||
// peer publishes both, deliberately the legacy one.
|
||||
val roomProfile = localChatRoom.chatRoom.toMlsGroup()
|
||||
?.let { if (it.currentGroupState().isCurrentProfile) MarmotProfile.CURRENT else MarmotProfile.LEGACY }
|
||||
?: MarmotProfile.LEGACY
|
||||
chatRepository.observeMarmotKeyPackageForPublicKey(profilePublicKey, roomProfile)
|
||||
.distinctUntilChanged()
|
||||
.collect { marmotKeyPackage ->
|
||||
if (marmotKeyPackage != null) {
|
||||
@@ -138,8 +146,12 @@ class AddMemberToChatRoomConfirmationViewModel(
|
||||
outcome.exceptionOrNull()?.let { e ->
|
||||
logger.e("Failed to invite $peerPublicKey to ${localChatRoom.chatRoom.id}", e)
|
||||
isActionPending.value = false
|
||||
addMemberToChatRoomConfirmationUIState =
|
||||
AddMemberToChatRoomConfirmationUIState.Error("Couldn't send the invite. Please try again.")
|
||||
// A key package on the wrong profile is the one failure the member can
|
||||
// fix, so it is shown as itself rather than as "try again".
|
||||
addMemberToChatRoomConfirmationUIState = AddMemberToChatRoomConfirmationUIState.Error(
|
||||
(e as? MarmotKeyPackageProfileException)?.message
|
||||
?: "Couldn't send the invite. Please try again."
|
||||
)
|
||||
return@launch
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -109,9 +109,11 @@ class ChatRoomListViewModel(
|
||||
|
||||
// Get/observe groupIds for publicKey
|
||||
val chatRooms = chatRepository.getChatRoomListByPublicKey(publicKey)
|
||||
// The addresses the rooms' traffic travels under, not their ids: a relay
|
||||
// indexes the `h` tag, and on the current profile that is the routing id.
|
||||
val relayChatRoomMaps = Relays.DefaultDMRelayList.map { dmRelay ->
|
||||
dmRelay.url to chatRooms.map { localChatRoom ->
|
||||
localChatRoom.chatRoom.id
|
||||
dmRelay.url to chatRooms.flatMap { localChatRoom ->
|
||||
localChatRoom.routingIds
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package to.curare.compose.ui.view.model
|
||||
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import androidx.compose.runtime.MutableState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
@@ -102,7 +103,7 @@ class ChatRoomMessagingViewModel(
|
||||
|
||||
combine(
|
||||
nostrRepository.observeProfileWithPublicKey(chatRoomId),
|
||||
chatRepository.observeMarmotKeyPackageForPublicKey(chatRoomId)
|
||||
chatRepository.observeMarmotKeyPackageForPublicKey(chatRoomId, MarmotProfile.DEFAULT_FOR_NEW_ROOMS)
|
||||
) { profile, keyPackage -> profile to keyPackage }
|
||||
.distinctUntilChanged()
|
||||
.collect { (profile, keyPackageEvent) ->
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package to.curare.compose.ui.view.model
|
||||
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
@@ -116,7 +117,7 @@ class ProfilePreviewViewModel(
|
||||
|
||||
combine(
|
||||
nostrRepository.observeProfileWithPublicKey(profilePublicKey),
|
||||
chatRepository.observeMarmotKeyPackageForPublicKey(profilePublicKey),
|
||||
chatRepository.observeMarmotKeyPackageForPublicKey(profilePublicKey, MarmotProfile.DEFAULT_FOR_NEW_ROOMS),
|
||||
) { profile, keyPackage ->
|
||||
// A placeholder is not a person. Mapping it to null here is what keeps
|
||||
// "LOADING..." off a screen whose one job is to say who this is.
|
||||
|
||||
+25
-32
@@ -1,5 +1,6 @@
|
||||
package to.curare.compose.ui.view.model
|
||||
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import androidx.compose.runtime.MutableState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateListOf
|
||||
@@ -13,6 +14,7 @@ import androidx.lifecycle.viewmodel.viewModelFactory
|
||||
import to.curare.compose.database.model.Profile
|
||||
import to.curare.compose.database.model.types.ChatRoomType
|
||||
import to.curare.compose.extensions.toHex
|
||||
import to.curare.compose.managers.MarmotGroupFactory
|
||||
import to.curare.compose.managers.MarmotGroupName
|
||||
import to.curare.compose.nostr.Relays
|
||||
import to.curare.compose.repository.ChatRepository
|
||||
@@ -23,9 +25,6 @@ import to.curare.compose.ui.composable.navigation.routes.ImplementationPendingRo
|
||||
import to.curare.compose.ui.composable.navigation.routes.Route
|
||||
import to.curare.compose.ui.view.state.SelectChatRoomTypeUIState
|
||||
import co.touchlab.kermit.Logger
|
||||
import com.vitorpamplona.quartz.marmot.mip01Groups.MarmotGroupData
|
||||
import com.vitorpamplona.quartz.marmot.mls.crypto.Ed25519
|
||||
import com.vitorpamplona.quartz.marmot.mls.group.MlsGroup
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
|
||||
@@ -228,36 +227,27 @@ class SelectChatRoomTypeViewModel(
|
||||
// convention is applied here as well as there.
|
||||
val groupName = MarmotGroupName.of(name)
|
||||
|
||||
// Stamp initial metadata via the shared factory so UI + CLI stay
|
||||
// byte-identical. Bake the MarmotGroupData extension into the
|
||||
// epoch-0 GroupContext directly (see `MarmotManager.createGroup`)
|
||||
// so later invitees receive a pre-populated group from the
|
||||
// welcome and never have to chase an undecryptable bootstrap
|
||||
// commit that predates their membership.
|
||||
val metadata = MarmotGroupData.bootstrap(
|
||||
nostrGroupId = gid,
|
||||
creatorPubKey = keyPair.pubKey.toHexKey(),
|
||||
outboxRelays = Relays.DefaultDMRelayList.map { it.url },
|
||||
name = groupName,
|
||||
description = description.orEmpty()
|
||||
)
|
||||
|
||||
val extras = listOf(metadata.toExtension())
|
||||
|
||||
val signingKeyPair = Ed25519.generateKeyPair()
|
||||
// TODO: Use nostrPrivateKey Ed25519.publicFromPrivate(privateKey).let { ed25519pubKey ->
|
||||
// Ed25519KeyPair(privateKey, ed25519pubKey)
|
||||
// }
|
||||
val group = MlsGroup.create(keyPair.pubKey, signingKeyPair.privateKey, extras)
|
||||
|
||||
viewModelScope.launch(Dispatchers.IO) {
|
||||
// The group's initial state is baked into the epoch-0 GroupContext so later
|
||||
// invitees receive a pre-populated group from the Welcome and never have to
|
||||
// chase an undecryptable bootstrap commit that predates their membership.
|
||||
// Which profile that state is on is the factory's decision, not this
|
||||
// screen's -- see MarmotGroupFactory.
|
||||
val created = MarmotGroupFactory.create(
|
||||
creator = keyPair,
|
||||
roomId = gid,
|
||||
name = groupName,
|
||||
description = description,
|
||||
adminPublicKeys = listOf(keyPair.pubKey.toHexKey()),
|
||||
relays = Relays.DefaultDMRelayList.map { it.url },
|
||||
)
|
||||
val group = created.group
|
||||
|
||||
val localChatRoom = chatRepository.getOrCreateChatRoom(
|
||||
// Key the room on the Marmot `nostr_group_id` baked into the group's
|
||||
// 0xF2EE extension, NOT on `MlsGroup`'s own randomly generated groupId —
|
||||
// they are unrelated 32-byte values. GroupEvents are h-tagged with the
|
||||
// room id, while every inbound path (and the invitee's own join) resolves
|
||||
// rooms by nostrGroupId, so using the MLS id meant the two sides could
|
||||
// never see each other's events.
|
||||
// Key the room on its Marmot id, NOT on `MlsGroup`'s own randomly
|
||||
// generated groupId — they are unrelated 32-byte values. Every inbound
|
||||
// path (and the invitee's own join) resolves rooms to this id, through
|
||||
// the routing address recorded below.
|
||||
chatRoomId = gid,
|
||||
activeUserPublicKey = keyPair.pubKey.toHexKey(),
|
||||
relayHint = null,
|
||||
@@ -265,6 +255,9 @@ class SelectChatRoomTypeViewModel(
|
||||
description = description,
|
||||
mlsGroupState = group.saveState().encodeTls().toHex()
|
||||
)
|
||||
if (localChatRoom != null) {
|
||||
chatRepository.recordMarmotRouting(chatRoomId = gid, routingId = created.routingId)
|
||||
}
|
||||
|
||||
if (localChatRoom == null) {
|
||||
withContext(Dispatchers.Main) {
|
||||
@@ -395,7 +388,7 @@ class SelectChatRoomTypeViewModel(
|
||||
memberPublicKeys.map { publicKey ->
|
||||
async {
|
||||
publicKey to withTimeoutOrNull(KEY_PACKAGE_LOOKUP_TIMEOUT) {
|
||||
chatRepository.observeMarmotKeyPackageForPublicKey(publicKey)
|
||||
chatRepository.observeMarmotKeyPackageForPublicKey(publicKey, MarmotProfile.DEFAULT_FOR_NEW_ROOMS)
|
||||
.filterNotNull()
|
||||
.first()
|
||||
}
|
||||
|
||||
+23
@@ -3,6 +3,7 @@ package to.curare.compose.managers
|
||||
import com.vitorpamplona.quartz.marmot.mip03GroupMessages.GroupEvent
|
||||
import com.vitorpamplona.quartz.nip59Giftwrap.wraps.GiftWrapEvent
|
||||
import to.curare.compose.database.model.ChatRoom
|
||||
import to.curare.compose.database.model.MarmotRouting
|
||||
import to.curare.compose.database.model.intermdiate.LocalChatRoom
|
||||
import to.curare.compose.managers.LiveSubscriptionManager.Companion.GIFT_WRAP_SUB_ID
|
||||
import to.curare.compose.managers.LiveSubscriptionManager.Companion.GROUP_SUB_ID_PREFIX
|
||||
@@ -108,6 +109,28 @@ class LiveSubscriptionPlanTest {
|
||||
assertEquals(listOf("a", "b", "c"), groupIdsFrom(rooms))
|
||||
}
|
||||
|
||||
/**
|
||||
* The filter names addresses, not rooms. A current-profile room is addressed by a
|
||||
* routing id apart from its own, and every address it has had is watched, so a
|
||||
* message published to a prior one inside the retention window is not missed. A
|
||||
* room with no routing recorded is its own one address. See docs/marmot-v2.md,
|
||||
* Phase 4.
|
||||
*/
|
||||
@Test
|
||||
fun `rooms are watched by their routing addresses`() {
|
||||
val routed = room(id = "room", mlsGroupState = "state").copy(
|
||||
routings = listOf(
|
||||
MarmotRouting(routingId = "addr-old", chatRoomId = "room", activeFromEpoch = 0, retiredAtEpoch = 3),
|
||||
MarmotRouting(routingId = "addr-new", chatRoomId = "room", activeFromEpoch = 3),
|
||||
),
|
||||
)
|
||||
val unrouted = room(id = "legacy", mlsGroupState = "state")
|
||||
|
||||
assertEquals(listOf("addr-new", "addr-old", "legacy"), groupIdsFrom(listOf(routed, unrouted)))
|
||||
assertEquals("addr-new", routed.routingId)
|
||||
assertEquals("legacy", unrouted.routingId)
|
||||
}
|
||||
|
||||
// --- chunking and subscription ids -------------------------------------------------
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package to.curare.compose.managers
|
||||
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNull
|
||||
|
||||
class MarmotRoomIdentityTest {
|
||||
private val roomId = "a1".repeat(32)
|
||||
|
||||
@Test
|
||||
fun `the room id rides at the end of the description and reads back`() {
|
||||
val described = MarmotRoomIdentity.describe("Admins of X.\n\nShared key path: m/9420/0/0", roomId)
|
||||
|
||||
assertEquals("Admins of X.\n\nShared key path: m/9420/0/0\n\nRoom id: $roomId", described)
|
||||
assertEquals(roomId, MarmotRoomIdentity.parse(described))
|
||||
// The path line beside it is untouched.
|
||||
assertEquals(listOf(9420L, 0L, 0L), SharedKeyDerivation.parsePath(described))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `an empty description is just the line`() {
|
||||
assertEquals("Room id: $roomId", MarmotRoomIdentity.describe(null, roomId))
|
||||
assertEquals("Room id: $roomId", MarmotRoomIdentity.describe(" ", roomId))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `describing twice does not repeat the line`() {
|
||||
val once = MarmotRoomIdentity.describe("d", roomId)
|
||||
assertEquals(once, MarmotRoomIdentity.describe(once, roomId))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a description that names no room, or names it badly, yields none`() {
|
||||
assertNull(MarmotRoomIdentity.parse(null))
|
||||
assertNull(MarmotRoomIdentity.parse("Admins of X."))
|
||||
assertNull(MarmotRoomIdentity.parse("Room id: not-hex"))
|
||||
assertNull(MarmotRoomIdentity.parse("Room id: " + "a".repeat(63)))
|
||||
assertEquals(roomId, MarmotRoomIdentity.parse(" Room id: ${roomId.uppercase()} "))
|
||||
}
|
||||
}
|
||||
@@ -890,7 +890,7 @@ class ChronicleApplyJvmTest {
|
||||
seedSenderWork()
|
||||
|
||||
sender.marmotOutboundDao().deliveryWelcome(
|
||||
nostrGroupId = chatRoomId,
|
||||
chatRoomId = chatRoomId,
|
||||
userPublicKey = oldMember,
|
||||
welcomeBytes = ByteArray(8),
|
||||
peerKeyPackageEventId = seedInviteeKeyPackage(),
|
||||
@@ -918,7 +918,7 @@ class ChronicleApplyJvmTest {
|
||||
seedRoom(sender, oldMember)
|
||||
|
||||
sender.marmotOutboundDao().deliveryWelcome(
|
||||
nostrGroupId = chatRoomId,
|
||||
chatRoomId = chatRoomId,
|
||||
userPublicKey = oldMember,
|
||||
welcomeBytes = ByteArray(8),
|
||||
peerKeyPackageEventId = seedInviteeKeyPackage(),
|
||||
|
||||
+113
@@ -19,6 +19,10 @@ import to.curare.compose.database.model.NostrEvent
|
||||
import to.curare.compose.database.model.Profile
|
||||
import to.curare.compose.database.repository.DatabaseChatRepository
|
||||
import to.curare.compose.extensions.toHex
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import kotlin.test.assertNotEquals
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.time.Clock
|
||||
|
||||
/**
|
||||
* What the device that *creates* a room knows about it afterwards.
|
||||
@@ -161,4 +165,113 @@ class MarmotGroupCreationJvmTest {
|
||||
Profile(publicKey = publicKey, userName = "member", nostrEventId = nostrEventId)
|
||||
)
|
||||
}
|
||||
|
||||
// ---- The current profile ---------------------------------------------------
|
||||
|
||||
/**
|
||||
* docs/marmot-v2.md, Phase 4. The room's id is still the derived key; the group's
|
||||
* routing address is minted apart from it and recorded; and the group's own
|
||||
* description names the room, so a joiner keys it as this device does.
|
||||
*/
|
||||
@Test
|
||||
fun `a current-profile room keeps its derived id and gets a routing address of its own`(): Unit = runBlocking {
|
||||
seedProfile(user)
|
||||
|
||||
val outcome = MarmotGroupCreation.create(
|
||||
database = db,
|
||||
chatRepository = repository,
|
||||
groupId = groupId,
|
||||
name = "#Ekklesia",
|
||||
purpose = "Admins of Ekklesia.",
|
||||
adminPublicKeys = setOf(user),
|
||||
userPublicKey = user,
|
||||
keyPair = keyPair,
|
||||
profile = MarmotProfile.CURRENT,
|
||||
)
|
||||
assertIs<MarmotGroupCreation.Outcome.Created>(outcome)
|
||||
|
||||
val room = assertNotNull(db.chatRoomDao().findChatRoomById(groupId), "the room is not keyed on the derived id")
|
||||
val group = assertNotNull(room.chatRoom.toMlsGroup())
|
||||
assertTrue(group.currentGroupState().isCurrentProfile, "the group is not on the current profile")
|
||||
assertNull(group.currentMarmotData(), "a current-profile group must carry no 0xF2EE")
|
||||
|
||||
// The address is not the identity.
|
||||
val routing = assertNotNull(db.marmotRoutingDao().findByChatRoomId(groupId).singleOrNull(), "no routing row")
|
||||
assertEquals(groupId, routing.chatRoomId)
|
||||
assertNotEquals(groupId, routing.routingId)
|
||||
assertEquals(routing.routingId, group.routingId())
|
||||
assertEquals(routing.routingId, group.currentNostrGroupId())
|
||||
assertEquals(listOf(routing.routingId), room.routingIds)
|
||||
|
||||
// And the group says which room it is, so a joiner agrees with us.
|
||||
assertEquals(groupId, group.roomId())
|
||||
assertEquals(setOf(user), group.currentAdminIdentities())
|
||||
assertNotNull(room.localParticipants.firstOrNull { it.participant.participantPublicKey == user }?.participant?.adminAt)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a legacy room is addressed by its own id, unchanged`(): Unit = runBlocking {
|
||||
seedProfile(user)
|
||||
|
||||
MarmotGroupCreation.create(
|
||||
database = db,
|
||||
chatRepository = repository,
|
||||
groupId = groupId,
|
||||
name = "#Ekklesia",
|
||||
purpose = "Admins of Ekklesia.",
|
||||
adminPublicKeys = setOf(user),
|
||||
userPublicKey = user,
|
||||
keyPair = keyPair,
|
||||
profile = MarmotProfile.LEGACY,
|
||||
)
|
||||
|
||||
val room = assertNotNull(db.chatRoomDao().findChatRoomById(groupId))
|
||||
val group = assertNotNull(room.chatRoom.toMlsGroup())
|
||||
assertEquals(groupId, group.routingId())
|
||||
assertEquals(groupId, group.roomId())
|
||||
assertEquals(listOf(groupId), room.routingIds)
|
||||
assertEquals(groupId, room.routingId)
|
||||
}
|
||||
|
||||
/**
|
||||
* The inbound side of the split: a kind:445 arrives under the routing address and
|
||||
* has to land in the room the address belongs to. Its content is nothing the
|
||||
* group can read, which files it as undecryptable -- what matters is which room.
|
||||
*/
|
||||
@Test
|
||||
fun `a group event under the routing address is filed in the room`(): Unit = runBlocking {
|
||||
seedProfile(user)
|
||||
MarmotGroupCreation.create(
|
||||
database = db,
|
||||
chatRepository = repository,
|
||||
groupId = groupId,
|
||||
name = "#Ekklesia",
|
||||
purpose = "Admins of Ekklesia.",
|
||||
adminPublicKeys = setOf(user),
|
||||
userPublicKey = user,
|
||||
keyPair = keyPair,
|
||||
profile = MarmotProfile.CURRENT,
|
||||
)
|
||||
val routingId = db.marmotRoutingDao().activeRoutingIdFor(groupId)
|
||||
|
||||
val eventId = "5".repeat(64)
|
||||
db.nostrDao().storeNostrEvent(
|
||||
nostrEvent = NostrEvent(
|
||||
id = eventId,
|
||||
pubKey = "6".repeat(64),
|
||||
kind = 445,
|
||||
tags = arrayOf(arrayOf("h", routingId)),
|
||||
content = "bm90IGEgZ3JvdXAgZXZlbnQ=",
|
||||
sig = "0".repeat(128),
|
||||
createdAt = Clock.System.now(),
|
||||
),
|
||||
relayURL = "wss://relay.example",
|
||||
synchronizationRelayURLs = listOf("wss://relay.example"),
|
||||
level = 0,
|
||||
activeKeyPair = keyPair,
|
||||
)
|
||||
|
||||
val filed = assertNotNull(db.marmotGroupEventDao().getMarmotGroupEventById(eventId), "the event was not filed")
|
||||
assertEquals(groupId, filed.chatRoomId, "filed under the address rather than the room")
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package to.curare.compose.managers
|
||||
|
||||
import com.vitorpamplona.quartz.marmot.appComponents.CurrentProfileGroupFactory
|
||||
import com.vitorpamplona.quartz.marmot.mip00KeyPackages.KeyPackageUtils
|
||||
import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray
|
||||
import com.vitorpamplona.quartz.nip01Core.core.toHexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
|
||||
import com.vitorpamplona.quartz.nip01Core.signers.NostrSignerInternal
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import to.curare.compose.database.dao.marmotKeyPackageFor
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import to.curare.compose.nostr.Relays
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertFailsWith
|
||||
import kotlin.test.assertFalse
|
||||
import kotlin.test.assertNotEquals
|
||||
import kotlin.test.assertNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/**
|
||||
* The one place a Marmot group is minted, on either profile. docs/marmot-v2.md, Phase 4.
|
||||
*/
|
||||
class MarmotGroupFactoryJvmTest {
|
||||
private val creator = KeyPair()
|
||||
private val creatorHex = creator.pubKey.toHexKey()
|
||||
private val admin = KeyPair().pubKey.toHexKey()
|
||||
// A real point, as a threshold key is; the derivation refuses anything else.
|
||||
private val roomId = SharedKeyDerivation.marmotGroupId("02" + KeyPair().pubKey.toHexKey())
|
||||
private val relays = Relays.DefaultDMRelayList.map { it.url }
|
||||
|
||||
@Test
|
||||
fun `a legacy group is addressed by the room id and names its admins in 0xF2EE`() = runBlocking {
|
||||
val created = MarmotGroupFactory.create(
|
||||
creator = creator, roomId = roomId, name = "#room", description = "d",
|
||||
adminPublicKeys = listOf(admin), relays = relays, profile = MarmotProfile.LEGACY,
|
||||
)
|
||||
|
||||
assertEquals(MarmotProfile.LEGACY, created.profile)
|
||||
assertEquals(roomId, created.routingId)
|
||||
assertEquals(roomId, created.group.roomId())
|
||||
assertEquals(roomId, created.group.routingId())
|
||||
assertFalse(created.group.currentGroupState().isCurrentProfile)
|
||||
assertEquals(setOf(creatorHex, admin), created.group.currentAdminIdentities())
|
||||
assertEquals("#room", created.group.roomName())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a current-profile group mints an address apart from the room id and names the room`() = runBlocking {
|
||||
val created = MarmotGroupFactory.create(
|
||||
creator = creator, roomId = roomId, name = "#room", description = "Admins of room.",
|
||||
adminPublicKeys = listOf(admin), relays = relays, profile = MarmotProfile.CURRENT,
|
||||
)
|
||||
|
||||
assertEquals(MarmotProfile.CURRENT, created.profile)
|
||||
assertNotEquals(roomId, created.routingId)
|
||||
assertEquals(64, created.routingId.length)
|
||||
assertTrue(created.group.currentGroupState().isCurrentProfile)
|
||||
assertNull(created.group.currentMarmotData(), "a current-profile group carries no 0xF2EE")
|
||||
|
||||
assertEquals(created.routingId, created.group.routingId())
|
||||
assertEquals(roomId, created.group.roomId(), "the room id does not ride in the group's description")
|
||||
assertEquals(setOf(creatorHex, admin), created.group.currentAdminIdentities())
|
||||
assertEquals("#room", created.group.roomName())
|
||||
assertTrue(created.group.roomDescription()!!.startsWith("Admins of room."))
|
||||
assertEquals(relays.sorted(), created.group.roomRelays().sorted())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `two current-profile groups never share an address`() = runBlocking {
|
||||
val first = MarmotGroupFactory.create(creator, roomId, "#a", null, emptyList(), relays, MarmotProfile.CURRENT)
|
||||
val second = MarmotGroupFactory.create(creator, roomId, "#a", null, emptyList(), relays, MarmotProfile.CURRENT)
|
||||
|
||||
assertNotEquals(first.routingId, second.routingId)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a current-profile group needs a creator that can sign`() = runBlocking<Unit> {
|
||||
val readOnly = KeyPair(privKey = null, pubKey = creator.pubKey)
|
||||
|
||||
assertFailsWith<IllegalArgumentException> {
|
||||
MarmotGroupFactory.create(readOnly, roomId, "#a", null, emptyList(), relays, MarmotProfile.CURRENT)
|
||||
}
|
||||
// And a legacy one does not.
|
||||
MarmotGroupFactory.create(readOnly, roomId, "#a", null, emptyList(), relays, MarmotProfile.LEGACY)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `a current-profile leaf fits either group and a legacy leaf fits only a legacy one`() = runBlocking {
|
||||
val legacyGroup = MarmotGroupFactory.create(creator, roomId, "#a", null, emptyList(), relays, MarmotProfile.LEGACY).group
|
||||
val currentGroup = MarmotGroupFactory.create(creator, roomId, "#a", null, emptyList(), relays, MarmotProfile.CURRENT).group
|
||||
val legacyLeaf = KeyPackageUtils.decodeKeyPackage(marmotKeyPackageFor(admin).tlsEncodedMarmotKeyPackage)
|
||||
val currentLeaf = CurrentProfileGroupFactory.createKeyPackage(NostrSignerInternal(KeyPair())).keyPackage
|
||||
|
||||
assertTrue(MarmotGroupFactory.leafFits(legacyGroup, legacyLeaf))
|
||||
assertTrue(MarmotGroupFactory.leafFits(legacyGroup, currentLeaf))
|
||||
assertTrue(MarmotGroupFactory.leafFits(currentGroup, currentLeaf))
|
||||
assertFalse(MarmotGroupFactory.leafFits(currentGroup, legacyLeaf))
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package to.curare.compose.ui.composable
|
||||
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
@@ -180,7 +181,7 @@ class ProfilePreviewScreenJvmTest {
|
||||
|
||||
/** No room with the person, and no key package for them. */
|
||||
private val NoRooms = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY {
|
||||
override suspend fun observeMarmotKeyPackageForPublicKey(publicKey: String): Flow<MarmotKeyPackage?> = flowOf(null)
|
||||
override suspend fun observeMarmotKeyPackageForPublicKey(publicKey: String, roomProfile: MarmotProfile): Flow<MarmotKeyPackage?> = flowOf(null)
|
||||
override suspend fun findDirectMessageRoom(userPublicKey: String, peerPublicKey: String): LocalChatRoom? = null
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -1,5 +1,6 @@
|
||||
package to.curare.compose.ui.view.model
|
||||
|
||||
import to.curare.compose.nostr.MarmotProfile
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
@@ -74,7 +75,7 @@ class ProfilePreviewViewModelJvmTest {
|
||||
val keyPackage: MutableStateFlow<MarmotKeyPackage?> = MutableStateFlow(null),
|
||||
private val existingRoom: LocalChatRoom? = null,
|
||||
) : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY {
|
||||
override suspend fun observeMarmotKeyPackageForPublicKey(publicKey: HexKey): Flow<MarmotKeyPackage?> = keyPackage
|
||||
override suspend fun observeMarmotKeyPackageForPublicKey(publicKey: HexKey, roomProfile: MarmotProfile): Flow<MarmotKeyPackage?> = keyPackage
|
||||
override suspend fun findDirectMessageRoom(userPublicKey: HexKey, peerPublicKey: HexKey): LocalChatRoom? = existingRoom
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user