From 52390e27cfb06f80714674049fff9cf85fd63307 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sat, 24 Oct 2026 07:25:51 +0200 Subject: [PATCH] feat(wallet): the certificate a group signs to guard a member's wallet (Phase 4) MemberWalletCertificateEvent (30334) is the group's signature over a member's request, which it embeds whole so an ancestor never in the room can check that the member asked. template(request) is the only way one is built and verify() checks a certificate is exactly that template, so a sponsor chooses nothing and two sponsors propose one event id. Its own kind rather than a 30329: every reader of birth certificates assumes a room, and a test fails the day subgroupsOf reads both. Co-Authored-By: Claude Opus 5.5 --- .../wallet/MemberWalletCertificateEvent.kt | 153 ++++++++++++++++++ .../MemberWalletCertificateEventJvmTest.kt | 134 +++++++++++++++ 2 files changed, 287 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEvent.kt create mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEventJvmTest.kt 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 new file mode 100644 index 00000000..ddfc1e94 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEvent.kt @@ -0,0 +1,153 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate + +/** + * A group saying it guards a wallet for one of its members: the group's + * signature over the member's request, and what every device opens the wallet + * on. + * + * ``` + * member --[ 30335 request, signed by them ]-> the group's room + * any signer --[ 30320 proposal over a 30334 ]-> the group's room + * ...a signing session... + * everyone holds the signed 30334 "this group guards W for this person" + * ``` + * + * ``` + * kind: 30334 + * pubkey: G set by the signing session + * created_at: the request's created_at so every sponsor proposes one event id + * content: W + * tags: + * ["d", W] + * ["p", ] + * ["wallet_key", ] + * ["chain", …] + * ["guardian", …] as in the request + * ["descriptor", …, "receive"] + * ["descriptor", …, "change"] + * ["label", …] if the request had one + * ["request", ] + * ``` + * + * ### Not a birth certificate + * + * A `SubgroupBirthCertificateEvent` says *this room is my child*, and every + * reader of 30329 assumes a room -- its `certifies` rederives one from the key, + * `SubgroupManager.subgroupsOf` lists one, the transcript announces one being + * born. A member's wallet is not a room, so it has its own kind and none of the + * lineage meaning. `docs/member-guarded-wallets.md`, "Should it be a birth + * certificate?". + * + * ### Built from the request and nothing else + * + * [template] is the only way a certificate is made, and [verify] checks one is + * exactly [template] of the request it carries. So the sponsor who puts a + * request to the group chooses nothing, two sponsors propose one event id, and + * no tag can say one thing in the request and another in the certificate. + * + * The request is embedded rather than looked up, as a guarded statement embeds + * its birth certificate: an ancestor who was never in the group's room can + * check that the member asked, from the group's signature alone. + * + * ### Never on a relay + * + * It carries an xpub. + * + * ### Why 30334 + * + * The first free number past the guarded-wallet notice (30333), which carries + * it upward to the groups above. + */ +object MemberWalletCertificateEvent { + val KIND: Kind = 30334 + + private const val D_TAG = "d" + private const val MEMBER_TAG = "p" + private const val REQUEST_TAG = "request" + + /** A certificate believed: who it guards a wallet for, and the wallet it opens. */ + data class Verified( + val certificate: Event, + val request: Event, + val groupChatRoomId: String, + val memberPublicKey: HexKey, + val walletId: String, + val label: String?, + /** The account the request rederived to, guardians and all. */ + val account: GroupWalletDerivation.Account, + ) + + /** + * The certificate [request] asks for: the request's own tags, minus the + * possession signature it already carries whole, under the wallet id. + */ + fun template(request: Event): EventTemplate<*> { + val reading = requireNotNull(MemberWalletRequestEvent.read(request)) { "not a request" } + val carried = request.tags.filterNot { it.isNotEmpty() && it[0] in setOf("h", "wallet", "possession") } + + return EventTemplate( + createdAt = request.createdAt, + kind = KIND, + tags = ( + listOf( + arrayOf(D_TAG, reading.walletId), + arrayOf(MEMBER_TAG, reading.memberPublicKey), + ) + carried + listOf(arrayOf(REQUEST_TAG, request.toJson())) + ).toTypedArray(), + content = reading.walletId, + ) + } + + /** The request [certificate] carries, or null. Nothing is verified here. */ + fun requestOf(certificate: Event): Event? = + certificate.tags.filter { it.size >= 2 && it[0] == REQUEST_TAG }.singleOrNull()?.let { Event.fromJsonOrNull(it[1]) } + + /** The member [certificate] names, or null. Nothing is verified here. */ + fun memberOf(certificate: Event): HexKey? = + certificate.tags.firstOrNull { it.size >= 2 && it[0] == MEMBER_TAG }?.get(1) + + /** + * [certificate] believed as [groupChatRoomId]'s, with no database: + * + * 1. it is a 30334, and the room signed it; + * 2. the request it carries is believed (`MemberWalletRequestEvent.verified`) + * and asked this room; + * 3. it is exactly [template] of that request -- every tag, the content and + * the time; + * 4. so its `p` is the member who asked. + * + * 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. + */ + fun verify(certificate: Event, groupChatRoomId: String): Verified? = runCatching { + if (certificate.kind != KIND) return null + if (!GroupKeyStateEvent.isSignedByRoom(certificate, groupChatRoomId)) return null + + val request = requestOf(certificate) ?: return null + val verified = MemberWalletRequestEvent.verified(request) ?: return null + if (!verified.reading.groupChatRoomId.equals(groupChatRoomId, ignoreCase = true)) return null + + val expected = template(request) + if (certificate.createdAt != expected.createdAt) return null + if (certificate.content != expected.content) return null + if (certificate.tags.map { it.toList() } != expected.tags.map { it.toList() }) return null + + Verified( + certificate = certificate, + request = request, + groupChatRoomId = groupChatRoomId.lowercase(), + memberPublicKey = verified.reading.memberPublicKey, + walletId = verified.reading.walletId, + label = verified.reading.label, + account = verified.account, + ) + }.getOrNull() +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEventJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEventJvmTest.kt new file mode 100644 index 00000000..27e0b859 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletCertificateEventJvmTest.kt @@ -0,0 +1,134 @@ +package com.machankura.bennu.compose.nostr.wallet + +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.managers.GroupFixtures +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.thresholdKeyOf +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.MemberWalletDerivation +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.machankura.bennu.compose.managers.SubgroupManager +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag +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.bitcoin.crypto.frost.KeyMaterial +import fr.acinq.secp256k1.Hex +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 + +/** + * A group's certificate that it guards a member's wallet: believed when it is + * exactly the group's signature over the request it carries, and never mistaken + * for a birth certificate by anything that reads those. + */ +class MemberWalletCertificateEventJvmTest { + 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 group = keyMaterial("6a0b") + private val stranger = keyMaterial("57a9") + private val groupRoom = roomOf(group) + + private val member = privateKey(0x3e3be7) + private val walletPrivateKey = privateKey(0xa11ce) + private val walletKey = walletPrivateKey.publicKey() + private val walletId = MemberWalletDerivation.walletId(walletKey) + + private fun request(guardians: List = GuardianDerivation.grant(thresholdKeyOf(group), groupRoom, emptyList(), walletId)) = + MemberWalletRequestEvent.build( + memberPrivateKey = member, + groupChatRoomId = groupRoom, + walletPrivateKey = walletPrivateKey, + account = MemberWalletDerivation.account(walletKey, chain, guardians), + label = "Savings", + createdAt = 1_700_000_000, + ) + + private fun certified(request: Event = request(), signer: KeyMaterial = group): Event { + val template = MemberWalletCertificateEvent.template(request) + return signedAsRoom(signer, MemberWalletCertificateEvent.KIND, template.tags, template.content, createdAt = template.createdAt) + } + + private fun Event.withTags(tags: Array>, signer: KeyMaterial = group): Event = + signedAsRoom(signer, kind, tags, content, createdAt) + + @Test + fun `a certificate the group signed over the request is believed`() { + val verified = assertNotNull(MemberWalletCertificateEvent.verify(certified(), groupRoom)) + assertEquals(member.xOnlyPublicKey().value.toHex(), verified.memberPublicKey) + assertEquals(walletId, verified.walletId) + assertEquals("Savings", verified.label) + assertEquals(groupRoom, verified.groupChatRoomId) + assertTrue(verified.account.isGuarded) + } + + @Test + fun `two sponsors propose one event`() { + assertEquals(certified().id, certified().id) + } + + @Test + fun `a certificate another room signed is refused`() { + assertNull(MemberWalletCertificateEvent.verify(certified(signer = stranger), groupRoom)) + } + + @Test + fun `a certificate over a request to another group is refused`() { + // The stranger signs a request that asked the group: the request is real, the group is not the one asked. + val strangerRoom = roomOf(stranger) + assertNull(MemberWalletCertificateEvent.verify(certified(signer = stranger), strangerRoom)) + } + + @Test + fun `a certificate naming another member is refused`() { + val certificate = certified() + val other = privateKey(0xb0b).xOnlyPublicKey().value.toHex() + val tags = certificate.tags.map { if (it[0] == "p") arrayOf("p", other) else it }.toTypedArray() + assertNull(MemberWalletCertificateEvent.verify(certificate.withTags(tags), groupRoom)) + } + + @Test + fun `a guardian swapped against its request is refused`() { + val certificate = certified() + val swapped = GuardianDerivation.grant(thresholdKeyOf(stranger), groupRoom, emptyList(), walletId).single() + val tags = certificate.tags.map { if (it[0] == "guardian") GuardianTag.assemble(swapped) else it }.toTypedArray() + assertNull(MemberWalletCertificateEvent.verify(certificate.withTags(tags), groupRoom)) + } + + @Test + fun `a member wallet certificate is never a subgroup`(): Unit = runBlocking { + val certificate = certified() + assertFalse(SubgroupBirthCertificateEvent.certifies(certificate, walletId, groupRoom)) + + GroupFixtures.seedRoom(db, groupRoom) + db.groupSignedEventDao().upsert( + GroupSignedEvent.fromEvent( + event = certificate, + chatRoomId = groupRoom, + derivationPath = SharedKeyDerivation.formatPath(GroupFixtures.path), + frostSigningSessionId = null, + ) + ) + assertEquals(emptyList(), SubgroupManager.subgroupsOf(db, groupRoom), "a reader of 30329 never sees a 30334") + } +}