diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt index 129fe10c..bbbdf40b 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt @@ -12,6 +12,8 @@ import com.machankura.bennu.compose.database.model.traits.TimestampedEntity import com.machankura.bennu.compose.database.model.traits.UserViewableEntity import com.machankura.bennu.compose.exceptions.MarmotUnprocessableInnerEventException import com.machankura.bennu.compose.managers.ChronicleManager +import com.machankura.bennu.compose.managers.MemberWalletManager +import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent import com.machankura.bennu.compose.managers.GroupKeyStateManager import com.machankura.bennu.compose.managers.GroupWalletManager import com.machankura.bennu.compose.managers.GuardianManager @@ -980,6 +982,24 @@ data class ChatMessage( return null } + // A member asking what the group signs with, so their device + // can work out a guarded wallet's leaves, or a member + // answering. Plumbing, so no line either way: the row above + // is the record, and an answer is checked each time it is + // read. Answered like the chronicle's request -- by any + // member holding the key state, none elected. + // docs/member-guarded-wallets.md, Phase 2. + if (event.kind == GroupKeyNoticeEvent.KIND) { + MemberWalletManager.answerKeyRequest( + database = database, + chatRoomId = groupEventResult.groupId, + request = event, + userPublicKey = activeKeyPair.pubKey.toHex(), + ) + + return null + } + applyInnerEvent( database = database, groupId = groupEventResult.groupId, diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt new file mode 100644 index 00000000..12b1c90f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt @@ -0,0 +1,134 @@ +package com.machankura.bennu.compose.managers + +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import kotlin.time.Clock +import kotlin.time.Instant + +/** + * A member's guarded wallet, from the asking to the guarding: + * `docs/member-guarded-wallets.md`. + * + * The member's device makes a random key, works out every ancestor leaf, stores + * the key and only then asks the group. A signer puts the request to the group, + * the group's quorum signs a certificate saying it guards that key for that + * person, and the certificate is what every device opens the wallet on. + */ +object MemberWalletManager { + private const val TAG = "MemberWalletManager" + + private val logger = Logger.withTag(TAG) + + /** + * The key [chatRoomId] signs with and the certificate it was born with -- + * what a member's grant is worked out from -- or null when this device knows + * neither. + * + * This device's own verified key state first. Behind it, the newest answer to + * a key notice in the room that checks out: a member welcomed after the + * founding holds no key state, and asks (`askForGroupKey`). Never filed as + * key state -- see [GroupKeyNoticeEvent]. + */ + suspend fun groupKeyFor(database: BennuDatabase, chatRoomId: String): GroupKeyNoticeEvent.GroupKey? { + GroupKeyStateManager.keyStateFor(database, chatRoomId)?.takeIf { it.verifies() }?.let { state -> + return GroupKeyNoticeEvent.GroupKey( + chatRoomId = state.chatRoomId, + thresholdPublicKey = state.thresholdPublicKey, + certificate = state.birthCertificateJson?.let { Event.fromJsonOrNull(it) }, + ) + } + + return noticesIn(database, chatRoomId) + .sortedByDescending { it.createdAt } + .firstNotNullOfOrNull { GroupKeyNoticeEvent.read(it, chatRoomId) } + } + + /** + * Asks [chatRoomId] for its key, as [userPublicKey]. Returns false, asking + * nothing, when this device already knows it or has asked and not been + * answered: a second question would get the same answer. + */ + suspend fun askForGroupKey(database: BennuDatabase, chatRoomId: String, userPublicKey: HexKey): Boolean { + if (groupKeyFor(database, chatRoomId) != null) return false + + val notices = noticesIn(database, chatRoomId) + val answered = notices.mapNotNull { GroupKeyNoticeEvent.answers(it) }.toSet() + if (notices.any { GroupKeyNoticeEvent.isAsking(it) && it.pubKey == userPublicKey && it.id !in answered }) return false + + queue(database, chatRoomId, userPublicKey, GroupKeyNoticeEvent.askingTags(chatRoomId), content = "") + logger.i("Asked $chatRoomId for its key") + return true + } + + /** + * Answers [request], an asking notice that arrived in [chatRoomId], as + * [userPublicKey] -- when this device holds the room's verified key state and + * nobody has answered it yet. Returns whether it answered. + * + * Any member holding the state may answer, and none is elected to: a + * duplicate answer costs bandwidth and nothing else, since every answer is + * checked on its own and they all say the same thing. The chronicle's + * request is answered the same way. + */ + suspend fun answerKeyRequest(database: BennuDatabase, chatRoomId: String, request: Event, userPublicKey: HexKey): Boolean { + if (!GroupKeyNoticeEvent.isAsking(request) || request.pubKey == userPublicKey) return false + val state = GroupKeyStateManager.keyStateFor(database, chatRoomId)?.takeIf { it.verifies() } ?: return false + val path = state.pathIndices() ?: return false + if (noticesIn(database, chatRoomId).any { GroupKeyNoticeEvent.answers(it) == request.id }) return false + + val groupKey = GroupKeyNoticeEvent.GroupKey( + chatRoomId = state.chatRoomId, + thresholdPublicKey = state.thresholdPublicKey, + certificate = state.birthCertificateJson?.let { Event.fromJsonOrNull(it) }, + ) + queue(database, chatRoomId, userPublicKey, GroupKeyNoticeEvent.answeringTags(request.id, groupKey, path), content = state.thresholdPublicKey) + logger.i("Answered ${request.pubKey.take(8)}'s request for $chatRoomId's key") + return true + } + + private suspend fun noticesIn(database: BennuDatabase, chatRoomId: String): List = + database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId, listOf(GroupKeyNoticeEvent.KIND)) + .map { it.asEvent() } + + /** + * A stored inner event as the event it was, unsigned: an inner event's + * authority is the MLS frame it arrived in, not a signature, so `sig` is + * empty here as it is everywhere inner events are read back. + */ + internal fun MarmotInnerEvent.asEvent(): Event = + Event(id = id, pubKey = publicKey, createdAt = createdAt.epochSeconds, kind = kind, tags = tags, content = content, sig = "") + + /** + * Queues one inner event in [chatRoomId] for the outbound pipeline, the way + * every inner event is: a row, which `encryptAndSendMarmotInnerEvent` sends. + */ + internal suspend fun queue( + database: BennuDatabase, + chatRoomId: String, + userPublicKey: HexKey, + tags: Array>, + content: String, + kind: Int = GroupKeyNoticeEvent.KIND, + createdAt: Instant = Clock.System.now(), + ): HexKey { + val id = EventHasher.hashId(userPublicKey, createdAt.epochSeconds, kind, tags, content) + database.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = id, + publicKey = userPublicKey, + kind = kind, + createdAt = createdAt, + tags = tags, + content = content, + chatRoomId = chatRoomId, + ) + ) + return id + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupKeyNoticeEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupKeyNoticeEvent.kt new file mode 100644 index 00000000..e35f563f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupKeyNoticeEvent.kt @@ -0,0 +1,125 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.SubgroupBirthCertificateTag +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind + +/** + * A member asking the group for its key, and a member answering -- the two + * things a guarded wallet's grant is worked out from. + * + * A member's guarded wallet carries the group's leaf and its ancestors' leaves, + * and the member's own device works them out before it asks the group to guard + * anything: `GuardianDerivation.grant` over the group's threshold key and the + * guardian keys in the group's own birth certificate. Both are read off the + * group's verified key state, which only ceremony participants hold. A member + * welcomed later has neither. See `docs/member-guarded-wallets.md`, D4. + * + * ``` + * member without a key state --[ 30336, no content ]-> the room "what does this group sign with?" + * member holding one --[ 30336, the key + its cert ]-> the room + * the asking device checks the answer on its own + * ``` + * + * ### Nothing the answerer says is taken on its word + * + * The answer carries the threshold key, the path, and the certificate if the + * group has one, and every one of them checks itself: the key at the path + * rederives the room's id, and the certificate certifies that room and names + * that key. A forged answer cannot name another key, and one that leaves out or + * swaps the certificate gives a grant every signer refuses, because each signer + * works the grant out again from its own key state. + * + * The signed key state itself is not carried: its row keeps what it said and not + * the event, and nothing in it is needed beyond what checks itself. + * + * ### Never filed as key state + * + * An answer is read in one place, for one purpose, every time it is used. Filing + * it into `GroupKeyState` would give every late member a key state and quietly + * change what `GroupWalletManager.thresholdKeyFor` answers for them across the + * app. + * + * ### Why 30336 + * + * After the member wallet's certificate (30334) and request (30335). + */ +object GroupKeyNoticeEvent { + val KIND: Kind = 30336 + + private const val ROOM_TAG = "h" + private const val REQUEST_TAG = "e" + private const val PATH_TAG = "frost_path" + + /** What a group signs with, as a member's device has checked it. */ + data class GroupKey( + val chatRoomId: String, + val thresholdPublicKey: HexKey, + /** The group's own birth certificate, or null for a group nobody's subgroup. */ + val certificate: Event?, + ) { + /** The guardian keys the group's certificate grants it, nearest first: what it passes down. */ + val guardians: List + get() = certificate?.let { SubgroupBirthCertificateEvent.parseGuardians(it.tags) }.orEmpty() + } + + /** The asking shape's tags. */ + fun askingTags(chatRoomId: String): Array> = arrayOf(arrayOf(ROOM_TAG, chatRoomId)) + + /** The answering shape's tags, answering [requestId]. The content is [GroupKey.thresholdPublicKey]. */ + fun answeringTags(requestId: HexKey, groupKey: GroupKey, path: List): Array> = + listOfNotNull( + arrayOf(ROOM_TAG, groupKey.chatRoomId), + arrayOf(REQUEST_TAG, requestId), + arrayOf(PATH_TAG, SharedKeyDerivation.formatPath(path)), + groupKey.certificate?.let { SubgroupBirthCertificateTag.assemble(it) }, + ).toTypedArray() + + /** Whether [event] asks rather than answers. */ + fun isAsking(event: Event): Boolean = event.kind == KIND && event.content.isBlank() + + /** The asking notice [event] answers, or null when it answers none. */ + fun answers(event: Event): HexKey? = + event.takeIf { it.kind == KIND && it.content.isNotBlank() }?.tags + ?.firstOrNull { it.size >= 2 && it[0] == REQUEST_TAG }?.get(1) + + /** + * The key [event] says [chatRoomId] signs with, or null when it is not an + * answer or does not check out: + * + * 1. it is an answer, and names [chatRoomId]; + * 2. the key at the path it names rederives [chatRoomId]; + * 3. a certificate it carries certifies [chatRoomId], names that key, and + * reads -- its guardian keys and its wallet policy both. One present and + * unreadable is refused rather than read as none, for the reason + * `GroupKeyStateManager.stateFrom` refuses it. + */ + fun read(event: Event, chatRoomId: String): GroupKey? = runCatching { + if (event.kind != KIND || event.content.isBlank()) return null + fun value(name: String): String? = event.tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) + if (!value(ROOM_TAG).equals(chatRoomId, ignoreCase = true)) return null + + val thresholdPublicKey = event.content.trim().lowercase() + val path = value(PATH_TAG)?.let { SharedKeyDerivation.parsePathString(it) } ?: return null + if (!SharedKeyDerivation.marmotGroupId(thresholdPublicKey, path).equals(chatRoomId, ignoreCase = true)) return null + + val certificateTags = event.tags.filter { it.isNotEmpty() && it[0] == SubgroupBirthCertificateTag.TAG_NAME } + if (certificateTags.size > 1) return null + val certificate = certificateTags.singleOrNull()?.let { tag -> + SubgroupBirthCertificateTag.parse(tag)?.certificate ?: return null + } + if (certificate != null) { + val parentChatRoomId = SubgroupBirthCertificateEvent.parseParentChatRoomId(certificate.tags) ?: return null + if (!SubgroupBirthCertificateEvent.certifies(certificate, chatRoomId, parentChatRoomId)) return null + if (!SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags).equals(thresholdPublicKey, ignoreCase = true)) return null + SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) ?: return null + SubgroupBirthCertificateEvent.parseWalletPolicy(certificate.tags) ?: return null + } + + GroupKey(chatRoomId = chatRoomId.lowercase(), thresholdPublicKey = thresholdPublicKey, certificate = certificate) + }.getOrNull() +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt new file mode 100644 index 00000000..766c88fb --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt @@ -0,0 +1,150 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.GroupKeyState +import com.machankura.bennu.compose.database.model.NostrEvent +import com.machankura.bennu.compose.database.model.Profile +import com.machankura.bennu.compose.extensions.toHex +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.Frost +import fr.acinq.bitcoin.crypto.frost.IndividualNonce +import fr.acinq.bitcoin.crypto.frost.KeyMaterial +import fr.acinq.bitcoin.crypto.frost.SecretNonce +import fr.acinq.bitcoin.crypto.frost.Session +import kotlin.time.Instant + +/** + * Groups with real keys, for the tests that need a group's signature on + * something: a trusted-dealer key per group, its room id, and a 2-of-3 FROST + * signature as the room. The shape `SubgroupManagerJvmTest` builds inline, kept + * in one place for the member-wallet tests, which need a parent, a group and a + * certificate between them in nearly every case. + */ +internal object GroupFixtures { + private const val PARTICIPANTS = 3 + private const val THRESHOLD = 2 + + val path: List = SharedKeyDerivation.MARMOT_ADMIN_GROUP_PATH + + fun keyMaterial(secret: String): KeyMaterial = Frost.trustedDealerKeygen( + thresholdSecretKey = PrivateKey(ByteVector32(secret.padStart(64, '0'))), + nParticipants = PARTICIPANTS, + threshold = THRESHOLD, + ) + + fun thresholdKeyOf(material: KeyMaterial): HexKey = material.thresholdPublicKey.value.toHex() + + fun roomOf(material: KeyMaterial): String = SharedKeyDerivation.marmotGroupId(thresholdKeyOf(material), path) + + /** [kind] over [tags] and [content], signed by [material]'s quorum as its room. */ + fun signedAsRoom(material: KeyMaterial, kind: Int, tags: Array>, content: String, createdAt: Long = 1_700_000_000): Event { + val pubKey = roomOf(material) + val id = EventHasher.hashId(pubKey = pubKey, createdAt = createdAt, kind = kind, tags = tags, content = content) + return Event(id = id, pubKey = pubKey, createdAt = createdAt, kind = kind, tags = tags, content = content, sig = signature(material, id)) + } + + /** + * [parent]'s certificate for [child], granting [guardians] under [policy] -- + * the grant is the caller's, so a test can hand over a wrong one. + */ + fun birthCertificate( + parent: KeyMaterial, + child: KeyMaterial, + guardians: List, + policy: SubgroupWalletPolicy? = if (guardians.isEmpty()) SubgroupWalletPolicy.UNGUARDED else SubgroupWalletPolicy.GUARDED, + admins: List = listOf("a".repeat(64)), + ): Event = signedAsRoom( + material = parent, + kind = SubgroupBirthCertificateEvent.KIND, + tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = roomOf(child), + parentChatRoomId = roomOf(parent), + thresholdPublicKey = thresholdKeyOf(child), + adminPublicKeys = admins, + name = "#Child", + path = path, + guardians = guardians, + walletPolicy = policy, + ), + content = roomOf(child), + ) + + /** [parent]'s guarded certificate for [child], with exactly the grant a parent with no parent makes. */ + fun guardedCertificate(parent: KeyMaterial, child: KeyMaterial): Event = + birthCertificate(parent, child, GuardianDerivation.grant(thresholdKeyOf(parent), roomOf(parent), emptyList(), roomOf(child))) + + /** [material]'s verified key state on this device, carrying [certificate] when it is somebody's subgroup. */ + suspend fun fileKeyState(db: BennuDatabase, material: KeyMaterial, certificate: Event? = null) { + seedRoom(db, roomOf(material)) + db.groupKeyStateDao().upsert( + GroupKeyState( + chatRoomId = roomOf(material), + dkgSessionId = "ceremony-" + roomOf(material).take(8), + thresholdPublicKey = thresholdKeyOf(material), + derivationPath = SharedKeyDerivation.formatPath(path), + announcedBy = roomOf(material), + announcedAt = Instant.fromEpochSeconds(1_700_000_000), + parentChatRoomId = certificate?.let { SubgroupBirthCertificateEvent.parseParentChatRoomId(it.tags) }, + birthCertificateJson = certificate?.toJson(), + ) + ) + } + + /** The device's own profile, which every room row names. */ + val owner: HexKey = "0e".repeat(32) + + suspend fun seedProfile(db: BennuDatabase, publicKey: HexKey, name: String = "member") { + if (db.profileDao().getProfileByPublicKey(publicKey) != null) return + val nostrEventId = publicKey.take(63) + "f" + db.nostrEventDao().upsert( + NostrEvent(id = nostrEventId, pubKey = publicKey, kind = 0, tags = emptyArray(), content = "{}", sig = "0".repeat(128)) + ) + db.profileDao().upsert(Profile(publicKey = publicKey, userName = name, nostrEventId = nostrEventId)) + } + + /** A room row for [chatRoomId], if there is none: what a key state, a signed event or a session hangs off. */ + suspend fun seedRoom(db: BennuDatabase, chatRoomId: String, subject: String? = null) { + seedProfile(db, owner) + if (db.chatRoomDao().findChatRoomById(chatRoomId) != null) return + db.chatRoomDao().upsert(ChatRoom(id = chatRoomId, userPublicKey = owner, subject = subject, description = null, mlsGroupState = null)) + } + + private fun signature(material: KeyMaterial, eventId: String): String { + val cache = SharedKeyDerivation.derive(thresholdKeyOf(material), path).cache + val message = ByteVector(eventId.hexToByteArray()) + val signerIds = listOf(0, 1) + + val nonces = signerIds.map { signerId -> + SecretNonce.generate( + sessionRandom = ByteVector32("a".repeat(63) + "${signerId + 1}"), + secretShare = material.secretShares[signerId], + publicShare = material.publicShares[signerId], + tweakedThresholdPublicKey = cache.tweakedPublicKey, + message = message, + extraInput = null, + ) + } + val session = Session.create( + aggregatedNonce = IndividualNonce.aggregate(nonces.map { it.second }).right!!, + signerIds = signerIds.map { it.toUInt() }, + signerPublicShares = signerIds.map { material.publicShares[it] }, + nParticipants = PARTICIPANTS, + threshold = THRESHOLD, + tweakCache = cache, + message = message, + ) + val partials = signerIds.mapIndexed { position, signerId -> + session.sign(nonces[position].first, material.secretShares[signerId], signerId.toUInt()).right!! + } + return session.aggregateSigs(partials).right!!.toByteArray().toHex() + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyNoticeJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyNoticeJvmTest.kt new file mode 100644 index 00000000..f3e4961f --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupKeyNoticeJvmTest.kt @@ -0,0 +1,139 @@ +package com.machankura.bennu.compose.managers + +import androidx.room3.Room +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.builder.getRoomDatabase +import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.managers.GroupFixtures.fileKeyState +import com.machankura.bennu.compose.managers.GroupFixtures.guardedCertificate +import com.machankura.bennu.compose.managers.GroupFixtures.keyMaterial +import com.machankura.bennu.compose.managers.GroupFixtures.roomOf +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.managers.MemberWalletManager.asEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * A member who holds no key state asking what the group signs with, and a member + * who holds one answering -- two devices, two databases, the inner-event rows + * carried from one to the other as the MLS room would carry them. + * + * The negative cases carry the weight: an answer is believed only for what it + * can prove about itself, and never filed as the room's key state. + */ +class GroupKeyNoticeJvmTest { + private val asking: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + private val answering: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDbs() { + asking.close() + answering.close() + } + + private val parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val stranger = keyMaterial("57a9") + private val groupRoom = roomOf(group) + private val certificate = guardedCertificate(parent, group) + + private val member = KeyPair().pubKey.toHexKey() + private val signer = KeyPair().pubKey.toHexKey() + + /** Carries every row of [kind] in the group's room from [from] to [to], as the room would. */ + private suspend fun deliver(from: BennuDatabase, to: BennuDatabase) = + from.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).forEach { to.marmotInnerEventDao().upsert(it) } + + @Test + fun `a member with no key state asks, is answered, and learns the key and the certificate`(): Unit = runBlocking { + fileKeyState(answering, group, certificate) + + assertNull(MemberWalletManager.groupKeyFor(asking, groupRoom)) + assertTrue(MemberWalletManager.askForGroupKey(asking, groupRoom, member)) + assertFalse(MemberWalletManager.askForGroupKey(asking, groupRoom, member), "asked and not yet answered") + + deliver(asking, answering) + val request = answering.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).single().asEvent() + assertTrue(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer)) + assertFalse(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer), "answered once") + + deliver(answering, asking) + val groupKey = assertNotNull(MemberWalletManager.groupKeyFor(asking, groupRoom)) + assertEquals(thresholdKeyOf(group), groupKey.thresholdPublicKey) + assertEquals(certificate.id, groupKey.certificate?.id) + assertEquals(SubgroupBirthCertificateEvent.parseGuardians(certificate.tags), groupKey.guardians) + + assertNull(asking.groupKeyStateDao().getByChatRoomId(groupRoom), "an answer is never filed as key state") + assertFalse(MemberWalletManager.askForGroupKey(asking, groupRoom, member), "nothing left to ask") + } + + @Test + fun `a device that holds no key state answers nothing`(): Unit = runBlocking { + MemberWalletManager.askForGroupKey(asking, groupRoom, member) + deliver(asking, answering) + val request = answering.marmotInnerEventDao().getByChatRoomAndKinds(groupRoom, listOf(GroupKeyNoticeEvent.KIND)).single().asEvent() + + assertFalse(MemberWalletManager.answerKeyRequest(answering, groupRoom, request, signer)) + } + + private fun answer(content: String, tags: Array>): Event { + val pubKey = signer + val id = EventHasher.hashId(pubKey, 1_700_000_000, GroupKeyNoticeEvent.KIND, tags, content) + return Event(id, pubKey, 1_700_000_000, GroupKeyNoticeEvent.KIND, tags, content, "") + } + + private fun answerFor(groupKey: GroupKeyNoticeEvent.GroupKey): Event = + answer(groupKey.thresholdPublicKey, GroupKeyNoticeEvent.answeringTags("e".repeat(64), groupKey, GroupFixtures.path)) + + @Test + fun `an answer is believed only for what it proves`() { + val honest = GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(group), certificate) + assertNotNull(GroupKeyNoticeEvent.read(answerFor(honest), groupRoom)) + + // Another group's key does not derive this room. + assertNull(GroupKeyNoticeEvent.read(answerFor(honest.copy(thresholdPublicKey = thresholdKeyOf(stranger))), groupRoom)) + // An answer about another room is not one about this room. + assertNull(GroupKeyNoticeEvent.read(answerFor(honest), roomOf(stranger))) + // A certificate for another child does not certify this one. + val elsewhere = guardedCertificate(parent, stranger) + assertNull(GroupKeyNoticeEvent.read(answerFor(honest.copy(certificate = elsewhere)), groupRoom)) + // A certificate whose signature is not the parent's. + val forged = Event(certificate.id, certificate.pubKey, certificate.createdAt, certificate.kind, certificate.tags, certificate.content, "0".repeat(128)) + assertNull(GroupKeyNoticeEvent.read(answerFor(honest.copy(certificate = forged)), groupRoom)) + // The asking shape is not an answer. + assertNull(GroupKeyNoticeEvent.read(answer("", GroupKeyNoticeEvent.askingTags(groupRoom)), groupRoom)) + // A root group's answer, with no certificate, reads with no guardians. + val root = GroupKeyNoticeEvent.read(answerFor(GroupKeyNoticeEvent.GroupKey(roomOf(parent), thresholdKeyOf(parent), null)), roomOf(parent)) + assertEquals(emptyList(), assertNotNull(root).guardians) + } + + @Test + fun `an answer that does not check out leaves the member asking`(): Unit = runBlocking { + val forged = answerFor(GroupKeyNoticeEvent.GroupKey(groupRoom, thresholdKeyOf(stranger), null)) + asking.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = forged.id, + publicKey = forged.pubKey, + kind = forged.kind, + createdAt = Instant.fromEpochSeconds(forged.createdAt), + tags = forged.tags, + content = forged.content, + chatRoomId = groupRoom, + ) + ) + assertNull(MemberWalletManager.groupKeyFor(asking, groupRoom)) + } +}