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 bbbdf40b..f1394197 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 @@ -14,6 +14,8 @@ import com.machankura.bennu.compose.exceptions.MarmotUnprocessableInnerEventExce 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.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent import com.machankura.bennu.compose.managers.GroupKeyStateManager import com.machankura.bennu.compose.managers.GroupWalletManager import com.machankura.bennu.compose.managers.GuardianManager @@ -467,6 +469,17 @@ data class ChatMessage( */ const val TYPE_GUARDIAN_SPEND = "guardianSpend" + /** + * A member asked this group to guard a wallet only they can spend from -- + * a `MemberWalletRequestEvent` this device checked. A request, not a + * decision: the group decides when a signer puts it to the quorum. See + * `docs/member-guarded-wallets.md`. + */ + const val TYPE_MEMBER_WALLET_REQUESTED = "memberWalletRequested" + + /** The group signed a member wallet certificate: it now guards that member's wallet. */ + const val TYPE_MEMBER_WALLET_GUARDED = "memberWalletGuarded" + /** * Every line the group signed, for the one check the transcript * dispatches on. A type missing from here renders as a chat bubble, @@ -482,6 +495,8 @@ data class ChatMessage( TYPE_GROUP_TRANSACTION_CONFIRMED, TYPE_GUARDED_WALLET_SHARED, TYPE_GUARDIAN_SPEND, + TYPE_MEMBER_WALLET_REQUESTED, + TYPE_MEMBER_WALLET_GUARDED, ) /** @@ -1118,6 +1133,10 @@ data class ChatMessage( * which is why they need an id of their own, and why every row this * writes carries it. */ + /** A member as a transcript line names them: their profile's name, or the start of their key. */ + private suspend fun memberName(database: BennuDatabase, publicKey: HexKey): String = + database.profileDao().getProfileByPublicKey(publicKey)?.humanReadableNameOrPubkey() ?: publicKey.take(8) + internal suspend fun applyInnerEvent( database: BennuDatabase, groupId: String, @@ -1252,6 +1271,50 @@ data class ChatMessage( ) } + // A member asking the group to guard a wallet of theirs. The + // inner event carries the signed request whole; only a request + // that checks out and asks this room gets a line, and it is a + // line and nothing more -- the group decides when a signer puts + // it to the quorum. docs/member-guarded-wallets.md. + MemberWalletRequestEvent.KIND -> { + val request = MemberWalletRequestEvent.carried(event) ?: return null + val reading = MemberWalletRequestEvent.verified(request)?.reading ?: return null + if (!reading.groupChatRoomId.equals(groupId, ignoreCase = true)) return null + + ChatMessage( + giftWrapPayloadId = null, + messageType = TYPE_MEMBER_WALLET_REQUESTED, + marmotGroupEventId = marmotGroupEventId, + marmotInnerEventId = marmotInnerEventId, + senderPublicKey = senderPublicKey, + isUserMessage = isUserMessage, + chatRoomId = groupId, + createdAt = createdAt, + content = "@${memberName(database, reading.memberPublicKey)} asked this group to guard a wallet", + ) + } + + // The group agreeing to guard a member's wallet. Checked whole -- + // the room's signature and the request inside -- because the line + // says the group made a promise about somebody's money. It is + // filed as a `GroupSignedEvent` either way, and every reader + // checks it there again. + MemberWalletCertificateEvent.KIND -> { + val verified = MemberWalletCertificateEvent.verify(event, groupId) ?: return null + + ChatMessage( + giftWrapPayloadId = null, + messageType = TYPE_MEMBER_WALLET_GUARDED, + marmotGroupEventId = marmotGroupEventId, + marmotInnerEventId = marmotInnerEventId, + senderPublicKey = senderPublicKey, + isUserMessage = isUserMessage, + chatRoomId = groupId, + createdAt = createdAt, + content = "This group now guards a wallet for @${memberName(database, verified.memberPublicKey)}", + ) + } + // The group opening a wallet. Checked the whole way -- the room's // signature, and the statement rederiving from the room's own key -- // because a line saying "the group opened a wallet" is a line people diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt index ed490ee8..6b9b8be7 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt @@ -6,6 +6,7 @@ import fr.acinq.bitcoin.OutPoint import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.database.model.types.FrostSigningSubject import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent import com.machankura.bennu.compose.wallet.GroupSpend import fr.acinq.bitcoin.ByteVector64 import fr.acinq.bitcoin.Chain @@ -573,6 +574,23 @@ object FrostSigningManager { } } + // A member wallet's certificate is this group agreeing to guard one + // member's key, so it has to be exactly what that member asked for, asked + // by a member, with exactly the guardian keys this group grants -- the + // list a guarded subgroup of it would get. Recomputed from this device's + // own key state, never taken from the sponsor who proposed it. + // docs/member-guarded-wallets.md, Phase 7. + unsignedEvents.forEach { rebuilt -> + if (rebuilt.kind != MemberWalletCertificateEvent.KIND) return@forEach + val reason = thresholdPublicKey + ?.let { MemberWalletManager.refuseCertificate(database, rebuilt.pubKey, it, rebuilt) } + ?: if (thresholdPublicKey == null) "cannot be checked without the group's key" else null + reason?.let { + logger.w("Signing proposal $sessionId carries a member wallet certificate that $it; dropping") + return null + } + } + // A subgroup's key state carries its birth certificate, and the // certificate's wallet policy has to be the one this group was made // under: every admin was shown it at the join gate, so joining was 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 index 12b1c90f..e4e637c4 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt @@ -2,8 +2,13 @@ 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.FrostSigningSession import com.machankura.bennu.compose.database.model.MarmotInnerEvent +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.types.FrostSigningStage import com.machankura.bennu.compose.nostr.wallet.GroupKeyNoticeEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher @@ -91,6 +96,144 @@ object MemberWalletManager { return true } + // ---- The group's side ------------------------------------------------ + + /** + * Every certificate [chatRoomId] holds that verifies as its own: the member + * wallets this group guards, newest first. One per wallet -- the `d` tag makes + * two certificates for one wallet replacements, and they say the same thing. + */ + suspend fun certificatesOf(database: BennuDatabase, chatRoomId: String): List = + database.groupSignedEventDao() + .getByChatRoomIdAndKind(chatRoomId, MemberWalletCertificateEvent.KIND) + .mapNotNull { MemberWalletCertificateEvent.verify(it.toEvent(), chatRoomId) } + .sortedByDescending { it.certificate.createdAt } + .distinctBy { it.walletId } + + /** + * Every request a member has put into [chatRoomId] that checks out and asks + * this room, newest first, one per wallet. + */ + suspend fun requestsIn(database: BennuDatabase, chatRoomId: String): List = + database.marmotInnerEventDao() + .getByChatRoomAndKinds(chatRoomId, listOf(MemberWalletRequestEvent.KIND)) + .mapNotNull { MemberWalletRequestEvent.carried(it.asEvent()) } + .mapNotNull { MemberWalletRequestEvent.verified(it) } + .filter { it.reading.groupChatRoomId.equals(chatRoomId, ignoreCase = true) } + .sortedByDescending { it.request.createdAt } + .distinctBy { it.reading.walletId } + + /** + * The event id a certificate for [request] signed in [chatRoomId] will have. + * The room's id is the author, and the request fixes everything else -- which + * is what lets two sponsors find each other's session. + */ + fun certificateIdFor(chatRoomId: String, request: Event): HexKey { + val template = MemberWalletCertificateEvent.template(request) + return EventHasher.hashId(chatRoomId.lowercase(), template.createdAt, template.kind, template.tags, template.content) + } + + /** The session open in [chatRoomId] over [request]'s certificate, if one is still running. */ + suspend fun openSessionFor(database: BennuDatabase, chatRoomId: String, request: Event): FrostSigningSession? { + val certificateId = certificateIdFor(chatRoomId, request) + return database.frostSigningSessionDao().getSessionsForChatRoom(chatRoomId) + .filter { it.stage != FrostSigningStage.FAILED && it.stage != FrostSigningStage.COMPLETE } + .firstOrNull { session -> database.frostSigningSessionDao().getItems(session.id).any { it.eventId == certificateId } } + } + + /** Whether the latest session over [request]'s certificate in [chatRoomId] failed -- declined, or abandoned. */ + suspend fun wasNotSigned(database: BennuDatabase, chatRoomId: String, request: Event): Boolean { + val certificateId = certificateIdFor(chatRoomId, request) + val sessions = database.frostSigningSessionDao().getSessionsForChatRoom(chatRoomId) + .filter { session -> database.frostSigningSessionDao().getItems(session.id).any { it.eventId == certificateId } } + return sessions.isNotEmpty() && sessions.all { it.stage == FrostSigningStage.FAILED } + } + + /** + * The requests in [chatRoomId] still waiting for somebody to put them to the + * group: no certificate for the wallet, and no session running over one. + */ + suspend fun awaitingSponsor(database: BennuDatabase, chatRoomId: String): List { + val certified = certificatesOf(database, chatRoomId).map { it.walletId }.toSet() + return requestsIn(database, chatRoomId) + .filter { it.reading.walletId !in certified } + .filter { openSessionFor(database, chatRoomId, it.request) == null } + } + + /** + * Why [chatRoomId], signing as [thresholdPublicKey], should not sign a + * proposed member wallet [certificate] -- or null when it may. + * + * The check every signer makes before agreeing to guard a member's wallet, + * refused before anything is shown, for the reason a mismatched id is: + * + * - it is not exactly the certificate the request it carries asks for, or + * the request does not check out, or it asked another group; + * - the person asking is not a member of this room; + * - its guardians are not the ones this group grants: `SubgroupManager.grantFor` + * with the wallet's id in a child room's place -- the same list a guarded + * subgroup of this group would get. A coordinator who slipped a key in, + * dropped an ancestor or reordered the leaves is refused here. + * + * The group's own wallet policy decides only which keys the grant carries. + * It never refuses a member's wallet: an unguarded group guards its members + * with its own key alone. `docs/member-guarded-wallets.md`, Phase 7. + */ + suspend fun refuseCertificate( + database: BennuDatabase, + chatRoomId: String, + thresholdPublicKey: HexKey, + certificate: Event, + ): String? { + val verified = MemberWalletCertificateEvent.verify(certificate, chatRoomId, signed = false) + ?: return "is not a certificate this group could have been asked for" + + val member = database.participantDao().findParticipantsByChatRoomId(chatRoomId) + .any { it.participantPublicKey.equals(verified.memberPublicKey, ignoreCase = true) } + if (!member) return "was asked by somebody who is not a member" + + val expected = runCatching { SubgroupManager.grantFor(database, chatRoomId, thresholdPublicKey, verified.walletId) }.getOrNull() + ?: return "grants keys this device cannot check" + return if (verified.account.guardians == expected) null else "grants guardian keys this group does not" + } + + /** + * Puts [request] to [groupRoom]'s quorum, as [userPublicKey]: a signing + * session over the certificate the request determines, which this device's + * proposing counts as approving. Returns the session already running over it + * instead, when another signer got there first. + * + * @throws IllegalStateException when the wallet is already certified, or this + * device would refuse the certificate itself -- a quorum should never be asked + * for what the proposer's own device knows is wrong. + */ + suspend fun putToGroup(database: BennuDatabase, groupRoom: LocalChatRoom, userPublicKey: HexKey, request: Event): FrostSigningSession { + val chatRoomId = groupRoom.chatRoom.id + val reading = MemberWalletRequestEvent.verified(request)?.reading + ?: throw IllegalStateException("This request does not check out") + check(certificatesOf(database, chatRoomId).none { it.walletId == reading.walletId }) { "This group already guards that wallet" } + openSessionFor(database, chatRoomId, request)?.let { return it } + + val thresholdPublicKey = GroupWalletManager.thresholdKeyFor(database, chatRoomId) + ?: throw IllegalStateException("This group has no shared key to sign with") + val template = MemberWalletCertificateEvent.template(request) + val unsigned = Event(certificateIdFor(chatRoomId, request), chatRoomId.lowercase(), template.createdAt, template.kind, template.tags, template.content, "") + refuseCertificate(database, chatRoomId, thresholdPublicKey, unsigned)?.let { reason -> + throw IllegalStateException("This group would refuse it: it $reason") + } + + logger.i("Putting ${reading.memberPublicKey.take(8)}'s wallet ${reading.walletId.take(8)} to $chatRoomId") + return FrostSigningManager.proposeSigning( + database = database, + localChatRoom = groupRoom, + userPublicKey = userPublicKey, + kind = template.kind, + tags = template.tags, + content = template.content, + createdAt = template.createdAt, + ) + } + private suspend fun noticesIn(database: BennuDatabase, chatRoomId: String): List = database.marmotInnerEventDao() .getByChatRoomAndKinds(chatRoomId, listOf(GroupKeyNoticeEvent.KIND)) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEvent.kt index ddfc1e94..20c64a0a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEvent.kt @@ -126,10 +126,15 @@ object MemberWalletCertificateEvent { * Whether the guardians are the ones the group grants is what the group's * signers checked before signing. A reader trusts the group's quorum for * that, and it is no new trust: that quorum can already take every coin. + * + * [signed] false is for a certificate still being proposed, which has no + * signature yet: everything else is checked, and its author has to be the + * room the session will sign as. */ - fun verify(certificate: Event, groupChatRoomId: String): Verified? = runCatching { + fun verify(certificate: Event, groupChatRoomId: String, signed: Boolean = true): Verified? = runCatching { if (certificate.kind != KIND) return null - if (!GroupKeyStateEvent.isSignedByRoom(certificate, groupChatRoomId)) return null + if (signed && !GroupKeyStateEvent.isSignedByRoom(certificate, groupChatRoomId)) return null + if (!signed && !certificate.pubKey.equals(groupChatRoomId, ignoreCase = true)) return null val request = requestOf(certificate) ?: return null val verified = MemberWalletRequestEvent.verified(request) ?: return null diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt index 3dafdf6a..d5ca25ab 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt @@ -3,6 +3,10 @@ package com.machankura.bennu.compose.text import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent import com.machankura.bennu.compose.managers.SharedKeyDerivation import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent @@ -27,7 +31,12 @@ object ProposedEvent { */ data class Summary(val label: String, val detail: String) - fun summarize(event: Event): Summary = when (event.kind) { + /** + * [nameOf] names a member by public key, for the one summary that is about a + * person: a caller with profiles to hand passes them, and one without gets + * the summary without a name rather than a wrong one. + */ + fun summarize(event: Event, nameOf: (HexKey) -> String? = { null }): Summary = when (event.kind) { // The one thing a group signs that is about the group rather than about // its work, and the only one a member sees before the room has done // anything. Shown as the path and the ceremony rather than as the key: @@ -92,6 +101,32 @@ object ProposedEvent { } ?: "A wallet statement this device cannot read" ) + // The group agreeing to guard one member's wallet. What a signer weighs + // is whose wallet, and what the group can do with it: take any coin that + // has sat for 12 blocks, alongside every group above it, while only the + // member can spend before then. The keys are their device's to check. + MemberWalletCertificateEvent.KIND -> Summary( + label = "Guard a member's wallet", + detail = MemberWalletCertificateEvent.requestOf(event) + ?.let { MemberWalletRequestEvent.read(it) } + ?.let { reading -> + val delay = GuardianDerivation.ANCESTOR_DELAY + val reach = when (val count = reading.guardians.size) { + 1 -> "this group can take its coins once they are $delay blocks old" + 2 -> "this group and the one above it can take its coins once they are $delay blocks old" + else -> "this group and the ${count - 1} above it can take its coins once they are $delay blocks old" + } + listOfNotNull( + nameOf(reading.memberPublicKey)?.let { "For @$it" }, + reading.label, + "on ${GroupWalletStatementEvent.chainName(reading.chain)}", + reach, + "only the member can spend from it before then", + ).joinToString(" · ") + } + ?: "A member wallet this device cannot read" + ) + else -> Summary(label = "Event of kind ${event.kind}", detail = event.content) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt index 7fa3d7ec..7b61abca 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/widgets/chat/ChatTranscript.kt @@ -16,6 +16,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountBalanceWallet import androidx.compose.material.icons.filled.AccountTree import bennu.composeapp.generated.resources.open import bennu.composeapp.generated.resources.the_group_has_its_key_finish_setting_it_up @@ -841,6 +842,7 @@ private fun RitualNotice( // path, so they get separate icons -- the whole reason both lines exist is // to be able to see that the first happened and the second did not. ChatMessage.TYPE_SUBGROUP_CERTIFIED -> Icons.Default.AccountTree + ChatMessage.TYPE_MEMBER_WALLET_REQUESTED, ChatMessage.TYPE_MEMBER_WALLET_GUARDED -> Icons.Default.AccountBalanceWallet ChatMessage.TYPE_MEMBER_INVITED -> Icons.Default.PersonAdd ChatMessage.TYPE_MEMBER_INVITE_SENT -> Icons.Default.Upload ChatMessage.TYPE_MEMBER_INVITE_FAILED -> Icons.Default.ErrorOutline 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 index 766c88fb..bd23cc63 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupFixtures.kt @@ -2,6 +2,17 @@ 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.DkgParticipantMessage +import com.machankura.bennu.compose.database.model.DkgSession +import com.machankura.bennu.compose.database.model.Participant +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.types.DkgRitualStage +import com.machankura.bennu.compose.nostr.Relays +import com.machankura.bennu.compose.nostr.dkg.DkgRitualEvents +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.crypto.KeyPair import com.machankura.bennu.compose.database.model.GroupKeyState import com.machankura.bennu.compose.database.model.NostrEvent import com.machankura.bennu.compose.database.model.Profile @@ -118,6 +129,54 @@ internal object GroupFixtures { db.chatRoomDao().upsert(ChatRoom(id = chatRoomId, userPublicKey = owner, subject = subject, description = null, mlsGroupState = null)) } + /** + * [material]'s Marmot room on this device, with [owner] holding a share of its + * key and every one of [members] a participant: a room this device can open + * a signing session in. Built as a real room is -- the id derived from the + * group's own key -- for the reason `SubgroupManagerJvmTest.parentWith` gives. + */ + suspend fun signingRoom(db: BennuDatabase, material: KeyMaterial, members: List, subject: String = "#Ekklesia"): LocalChatRoom { + val roomId = roomOf(material) + (members + owner).forEach { seedProfile(db, it) } + + val metadata = MarmotGroupData( + nostrGroupId = roomId, + name = subject, + description = SharedKeyDerivation.describe("Admins of $subject."), + adminPubkeys = members + owner, + relays = Relays.DefaultDMRelayList.map { it.url }, + ) + val mlsGroup = MlsGroup.create(KeyPair().pubKey, Ed25519.generateKeyPair().privateKey, listOf(metadata.toExtension())) + db.chatRoomDao().upsert( + ChatRoom(id = roomId, userPublicKey = owner, subject = subject, description = metadata.description, mlsGroupState = mlsGroup.saveState().encodeTls().toHex()) + ) + db.participantDao().upsert((members + owner).map { Participant(participantPublicKey = it, chatRoomId = roomId, relayHint = null) }) + + val ceremonyId = "signing-" + roomId.take(8) + db.dkgSessionDao().upsert( + DkgSession( + id = ceremonyId, + chatRoomId = roomId, + coordinatorPublicKey = owner, + userPublicKey = owner, + threshold = THRESHOLD, + participantCount = members.size + 1, + stage = DkgRitualStage.COMPLETE, + hostPublicKey = owner, + round1Random = "aa".repeat(32), + round2AuxRandom = "bb".repeat(32), + thresholdPublicKey = thresholdKeyOf(material), + secretShare = "cc".repeat(32), + ) + ) + (members + owner).forEachIndexed { index, member -> + db.dkgSessionDao().upsert( + DkgParticipantMessage(sessionId = ceremonyId, participantPublicKey = member, kind = DkgRitualEvents.HOST_KEY, payload = "0${index + 1}".repeat(33)) + ) + } + return requireNotNull(db.chatRoomDao().findChatRoomById(roomId)) + } + private fun signature(material: KeyMaterial, eventId: String): String { val cache = SharedKeyDerivation.derive(thresholdKeyOf(material), path).cache val message = ByteVector(eventId.hexToByteArray()) diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt new file mode 100644 index 00000000..a851825b --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletSigningJvmTest.kt @@ -0,0 +1,197 @@ +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.GroupSignedEvent +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.signedAsRoom +import com.machankura.bennu.compose.managers.GroupFixtures.signingRoom +import com.machankura.bennu.compose.managers.GroupFixtures.thresholdKeyOf +import com.machankura.bennu.compose.nostr.wallet.MemberWalletCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.MemberWalletRequestEvent +import com.machankura.bennu.compose.text.ProposedEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Instant + +/** + * A group's signers checking a member wallet certificate before they are asked + * to approve it, and a signer putting a member's request to the group. + * + * The group is itself a guarded subgroup, so a member's wallet under it carries + * two leaves -- the group's and its parent's, one step further -- and every + * refusal below is one way of getting that list wrong. + */ +class MemberWalletSigningJvmTest { + private val db: BennuDatabase = getRoomDatabase(Room.inMemoryDatabaseBuilder()) + + @AfterTest + fun closeDb() = db.close() + + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val parent = keyMaterial("9a9e") + private val group = keyMaterial("6a0b") + private val stranger = keyMaterial("57a9") + private val groupRoom = roomOf(group) + + private val member = privateKey(0x3e3be7) + private val memberPublicKey = member.xOnlyPublicKey().value.toHex() + private val outsider = privateKey(0x07575) + private val walletPrivateKey = privateKey(0xa11ce) + private val walletId = MemberWalletDerivation.walletId(walletPrivateKey.publicKey()) + + /** What the group grants the member's wallet: its own key, then its parent's, one step further. */ + private val grant: List = GuardianDerivation.grant( + thresholdKeyOf(group), groupRoom, + GuardianDerivation.grant(thresholdKeyOf(parent), roomOf(parent), emptyList(), groupRoom), + walletId, + ) + + private suspend fun groupRoomHere() = signingRoom(db, group, members = listOf(memberPublicKey)).also { + fileKeyState(db, group, guardedCertificate(parent, group)) + } + + private fun request(guardians: List = grant, by: PrivateKey = member, asking: String = groupRoom) = + MemberWalletRequestEvent.build( + memberPrivateKey = by, + groupChatRoomId = asking, + walletPrivateKey = walletPrivateKey, + account = MemberWalletDerivation.account(walletPrivateKey.publicKey(), chain, guardians), + label = "Savings", + createdAt = 1_700_000_000, + ) + + /** The certificate [request] asks for, as a session would carry it -- unsigned, authored by the room. */ + private fun proposed(request: Event, room: String = groupRoom): Event { + val template = MemberWalletCertificateEvent.template(request) + return Event(MemberWalletManager.certificateIdFor(room, request), room, template.createdAt, template.kind, template.tags, template.content, "") + } + + private suspend fun refusal(request: Event): String? = + MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), proposed(request)) + + @Test + fun `the honest certificate is signable`(): Unit = runBlocking { + groupRoomHere() + assertNull(refusal(request())) + } + + @Test + fun `a certificate that drops the group above is refused`(): Unit = runBlocking { + groupRoomHere() + assertEquals("grants guardian keys this group does not", refusal(request(guardians = grant.take(1)))) + } + + @Test + fun `a certificate whose leaves are reordered is refused`(): Unit = runBlocking { + groupRoomHere() + // Reordered, the group is no longer the nearest guardian, so the request itself is refused. + assertNotNull(refusal(request(guardians = grant.reversed()))) + } + + @Test + fun `a certificate naming another group's key is refused`(): Unit = runBlocking { + groupRoomHere() + val swapped = listOf(grant[0], GuardianDerivation.grant(thresholdKeyOf(stranger), roomOf(stranger), emptyList(), walletId).single()) + assertEquals("grants guardian keys this group does not", refusal(request(guardians = swapped))) + } + + @Test + fun `a certificate asked by somebody who is not a member is refused`(): Unit = runBlocking { + groupRoomHere() + assertEquals("was asked by somebody who is not a member", refusal(request(by = outsider))) + } + + @Test + fun `a request made of another group is refused here`(): Unit = runBlocking { + groupRoomHere() + val elsewhere = request(asking = roomOf(stranger), guardians = GuardianDerivation.grant(thresholdKeyOf(stranger), roomOf(stranger), emptyList(), walletId)) + assertNotNull(MemberWalletManager.refuseCertificate(db, groupRoom, thresholdKeyOf(group), proposed(elsewhere))) + } + + @Test + fun `an unguarded group guards its members with its own key alone`(): Unit = runBlocking { + // A root group: no certificate, so nothing to pass down. + signingRoom(db, group, members = listOf(memberPublicKey)) + fileKeyState(db, group, certificate = null) + assertNull(refusal(request(guardians = grant.take(1)))) + assertEquals("grants guardian keys this group does not", refusal(request())) + } + + private suspend fun deliverRequest(request: Event) { + db.marmotInnerEventDao().upsert( + MarmotInnerEvent( + id = "1".repeat(63) + "0", + publicKey = request.pubKey, + kind = MemberWalletRequestEvent.KIND, + createdAt = Instant.fromEpochSeconds(request.createdAt), + tags = arrayOf(arrayOf("h", groupRoom)), + content = request.toJson(), + chatRoomId = groupRoom, + ) + ) + } + + @Test + fun `a signer puts a request to the group, and a second sponsor finds the same session`(): Unit = runBlocking { + val room = groupRoomHere() + val request = request() + deliverRequest(request) + assertEquals(listOf(walletId), MemberWalletManager.awaitingSponsor(db, groupRoom).map { it.reading.walletId }) + + val session = MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request) + val items = db.frostSigningSessionDao().getItems(session.id) + assertEquals(listOf(MemberWalletManager.certificateIdFor(groupRoom, request)), items.map { it.eventId }) + assertTrue(MemberWalletManager.awaitingSponsor(db, groupRoom).isEmpty(), "no longer waiting for a sponsor") + + assertEquals(session.id, MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request).id) + } + + @Test + fun `a sponsor refuses to put what the group would refuse`(): Unit = runBlocking { + val room = groupRoomHere() + assertFailsWith { + MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request(guardians = grant.take(1))) + } + assertTrue(db.frostSigningSessionDao().getSessionsForChatRoom(groupRoom).isEmpty()) + } + + @Test + fun `a wallet the group already guards is not put to it again`(): Unit = runBlocking { + val room = groupRoomHere() + val request = request() + val template = MemberWalletCertificateEvent.template(request) + val signed = signedAsRoom(group, template.kind, template.tags, template.content, template.createdAt) + db.groupSignedEventDao().upsert(GroupSignedEvent.fromEvent(signed, chatRoomId = groupRoom, derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), frostSigningSessionId = null)) + + assertEquals(listOf(walletId), MemberWalletManager.certificatesOf(db, groupRoom).map { it.walletId }) + assertFailsWith { MemberWalletManager.putToGroup(db, room, GroupFixtures.owner, request) } + } + + @Test + fun `the signers read who it is for and what the group can do`() { + val summary = ProposedEvent.summarize(proposed(request())) { if (it == memberPublicKey) "alice" else null } + assertEquals("Guard a member's wallet", summary.label) + assertTrue(summary.detail.startsWith("For @alice · Savings · on regtest"), summary.detail) + assertTrue(summary.detail.contains("this group and the one above it can take its coins once they are 12 blocks old"), summary.detail) + } +}