diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEvent.kt new file mode 100644 index 00000000..912edf7f --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEvent.kt @@ -0,0 +1,232 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.MemberWalletDerivation +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag +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.core.hexToByteArray +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import kotlin.time.Clock + +/** + * A member asking their group to guard a wallet only they can spend from. + * + * The member's device has already made the wallet's key, worked out every + * ancestor's leaf and both descriptors, and stored the key. This is the first + * thing that leaves the device, and it carries all of it, so the group signs off + * on a wallet the member has already built rather than one it builds for them. + * See `docs/member-guarded-wallets.md`, Phase 3. + * + * ``` + * kind: 30335 + * pubkey: + * content: + * tags: + * ["h", G] the group asked + * ["wallet", W] + * ["wallet_key", ] + * ["chain", "mainnet" | "signet" | …] + * ["guardian", , , , "12"] one per guardian, nearest first + * ["descriptor", tr(…,{…}), "receive"] + * ["descriptor", tr(…,{…}), "change"] + * ["label", "Savings"] optional + * ["possession", ] + * ``` + * + * ### Signed twice + * + * By the member's nostr key, so it is bound to who asked, and -- in the + * `possession` tag -- by the wallet key itself, over [possessionMessage], so the + * member is shown to hold the key they are asking about. Without the second, Bob + * could ask for a certificate on Alice's wallet key under his own name. + * + * `k` signs exactly that one message, under its own tagged hash. It is never an + * output key: the account step always tweaks it first. + * + * ### Carried whole + * + * An inner event is an unsigned rumor -- its authority is the MLS frame -- and the + * row it travels in keeps no signature. This one's signature has to survive the + * room, because the group's certificate embeds it for ancestors who were never + * in the room. So the room carries an inner event of this kind whose content is + * the signed request, whole, as a 30333 notice carries a statement: [carried]. + * + * ### Never on a relay + * + * It carries an xpub, which is every address and the whole balance. + * + * ### Why 30335 + * + * After the certificate it asks for, at 30334. + */ +object MemberWalletRequestEvent { + val KIND: Kind = 30335 + + private const val ROOM_TAG = "h" + private const val WALLET_TAG = "wallet" + private const val WALLET_KEY_TAG = "wallet_key" + private const val CHAIN_TAG = "chain" + private const val DESCRIPTOR_TAG = "descriptor" + private const val RECEIVE_MARKER = "receive" + private const val CHANGE_MARKER = "change" + private const val LABEL_TAG = "label" + private const val POSSESSION_TAG = "possession" + + /** The tag of the possession signature's message. Frozen once a request carries one. */ + private const val POSSESSION_HASH_TAG = "bennu/member-wallet/possession/v1" + + /** The longest label a request carries: a name for a wallet, not a note. */ + const val MAX_LABEL_LENGTH = 64 + + /** What a request says, read but not yet believed. [verified] is what believes it. */ + data class Reading( + val memberPublicKey: HexKey, + val groupChatRoomId: String, + val walletId: String, + val walletKey: PublicKey, + val chain: Chain, + val xpub: String, + val receiveDescriptor: String, + val changeDescriptor: String, + val guardians: List, + val label: String?, + val possession: ByteVector64, + ) + + /** A request that checks out on everything a reader can check without the group's key. */ + data class Verified( + val request: Event, + val reading: Reading, + /** The account the request opens, rederived from the wallet key -- never what it said. */ + val account: GroupWalletDerivation.Account, + ) + + /** + * What `k` signs: the member, the group, the wallet key and the network -- + * everything that has to bind one key to one person in one group on one chain. + */ + fun possessionMessage(memberPublicKey: HexKey, groupChatRoomId: String, walletKey: PublicKey, chain: Chain): ByteVector32 = + Crypto.taggedHash( + memberPublicKey.lowercase().hexToByteArray() + + groupChatRoomId.lowercase().hexToByteArray() + + walletKey.value.toByteArray() + + chain.chainHash.value.toByteArray(), + POSSESSION_HASH_TAG, + ) + + /** + * The request for [account] -- opened under the wallet key [walletPrivateKey] + * holds -- of [groupChatRoomId], signed as the member [memberPrivateKey] holds. + */ + fun build( + memberPrivateKey: PrivateKey, + groupChatRoomId: String, + walletPrivateKey: PrivateKey, + account: GroupWalletDerivation.Account, + label: String?, + createdAt: Long = Clock.System.now().epochSeconds, + ): Event { + val memberPublicKey = memberPrivateKey.xOnlyPublicKey().value.toHex() + val walletKey = walletPrivateKey.publicKey() + require(account.extendedPublicKey == MemberWalletDerivation.account(walletKey, account.chain, account.guardians).extendedPublicKey) { + "the account is not the wallet key's" + } + val possession = Crypto.signSchnorr(possessionMessage(memberPublicKey, groupChatRoomId, walletKey, account.chain), walletPrivateKey, null) + + val tags = listOfNotNull( + arrayOf(ROOM_TAG, groupChatRoomId.lowercase()), + arrayOf(WALLET_TAG, MemberWalletDerivation.walletId(walletKey)), + arrayOf(WALLET_KEY_TAG, walletKey.toString()), + arrayOf(CHAIN_TAG, GroupWalletStatementEvent.chainName(account.chain)), + *account.guardians.map(GuardianTag::assemble).toTypedArray(), + arrayOf(DESCRIPTOR_TAG, account.receiveDescriptor, RECEIVE_MARKER), + arrayOf(DESCRIPTOR_TAG, account.changeDescriptor, CHANGE_MARKER), + label?.trim()?.takeIf { it.isNotEmpty() }?.let { arrayOf(LABEL_TAG, it.take(MAX_LABEL_LENGTH)) }, + arrayOf(POSSESSION_TAG, possession.toHex()), + ).toTypedArray() + + val id = EventHasher.hashId(memberPublicKey, createdAt, KIND, tags, account.xpub) + val sig = Crypto.signSchnorr(ByteVector32(id), memberPrivateKey, null) + return Event(id = id, pubKey = memberPublicKey, createdAt = createdAt, kind = KIND, tags = tags, content = account.xpub, sig = sig.toHex()) + } + + /** The request's fields, or null when any is missing, doubled or the wrong shape. Nothing is verified here. */ + fun read(event: Event): Reading? = runCatching { + if (event.kind != KIND) return null + fun single(name: String): String? = + event.tags.filter { it.isNotEmpty() && it[0] == name }.takeIf { it.size == 1 }?.single()?.takeIf { it.size >= 2 }?.get(1) + fun descriptor(marker: String): String? = + event.tags.filter { it.size >= 3 && it[0] == DESCRIPTOR_TAG && it[2] == marker }.singleOrNull()?.get(1) + + val labels = event.tags.filter { it.isNotEmpty() && it[0] == LABEL_TAG } + if (labels.size > 1) return null + val label = labels.singleOrNull()?.getOrNull(1)?.takeIf { it.isNotBlank() && it.length <= MAX_LABEL_LENGTH } + if (labels.isNotEmpty() && label == null) return null + + Reading( + memberPublicKey = event.pubKey.lowercase(), + groupChatRoomId = single(ROOM_TAG)?.lowercase() ?: return null, + walletId = single(WALLET_TAG)?.lowercase() ?: return null, + walletKey = single(WALLET_KEY_TAG)?.let { PublicKey.fromHex(it) }?.takeIf { it.isValid() } ?: return null, + chain = single(CHAIN_TAG)?.let(GroupWalletStatementEvent::chainNamed) ?: return null, + xpub = event.content.takeIf { it.isNotBlank() } ?: return null, + receiveDescriptor = descriptor(RECEIVE_MARKER) ?: return null, + changeDescriptor = descriptor(CHANGE_MARKER) ?: return null, + guardians = GuardianTag.parseAll(event.tags)?.takeIf { it.isNotEmpty() } ?: return null, + label = label, + possession = single(POSSESSION_TAG)?.let { ByteVector64(it) } ?: return null, + ) + }.getOrNull() + + /** + * [event] believed, on everything a reader can check without the group's key: + * + * 1. it is a request, signed by the member it names; + * 2. its wallet id is the wallet key's; + * 3. the wallet key signed the possession message; + * 4. its nearest guardian is the group it asks, so a request cannot leave + * out the one group it is asking; + * 5. the wallet key, under those guardians, rederives the xpub and both + * descriptors byte for byte. + * + * Whether the guardians are the ones the group grants is not here: only a + * device holding the group's key can say, and the group's signers do. + */ + fun verified(event: Event): Verified? = runCatching { + val reading = read(event) ?: return null + if (!GroupKeyStateEvent.isSignedByRoom(event, reading.memberPublicKey)) return null + if (MemberWalletDerivation.walletId(reading.walletKey) != reading.walletId) return null + + val message = possessionMessage(reading.memberPublicKey, reading.groupChatRoomId, reading.walletKey, reading.chain) + if (!Crypto.verifySignatureSchnorr(message, reading.possession, reading.walletKey.xOnly())) return null + + if (!reading.guardians.first().chatRoomId.equals(reading.groupChatRoomId, ignoreCase = true)) return null + + val account = MemberWalletDerivation.account(reading.walletKey, reading.chain, reading.guardians) + if (account.xpub != reading.xpub || account.receiveDescriptor != reading.receiveDescriptor || account.changeDescriptor != reading.changeDescriptor) return null + + Verified(request = event, reading = reading, account = account) + }.getOrNull() + + /** + * The signed request an inner event of this kind carries -- or null when its + * content is not one, or was sent by somebody other than the member who + * signed it. A request is passed on by nobody: whoever puts it in the room + * is the one asking. + */ + fun carried(inner: Event): Event? { + if (inner.kind != KIND) return null + val request = Event.fromJsonOrNull(inner.content)?.takeIf { it.kind == KIND } ?: return null + return request.takeIf { it.pubKey.equals(inner.pubKey, ignoreCase = true) } + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEventTest.kt new file mode 100644 index 00000000..8977a5b0 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletRequestEventTest.kt @@ -0,0 +1,127 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.managers.MemberWalletDerivation +import com.machankura.bennu.compose.managers.SharedKeyDerivation +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * A member's request, read and believed on everything that can be checked + * without the group's key -- one mutation per check, each of which has to be + * enough on its own to refuse it. + */ +class MemberWalletRequestEventTest { + private val chain = Chain.Regtest + + private fun privateKey(seed: Long): PrivateKey = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))) + + private val member = privateKey(0x3e3be7) + private val walletPrivateKey = privateKey(0xa11ce) + private val walletKey = walletPrivateKey.publicKey() + private val walletId = MemberWalletDerivation.walletId(walletKey) + + private val groupKey = privateKey(0x6a0b).publicKey().toString() + private val groupRoom = SharedKeyDerivation.marmotGroupId(groupKey) + private val parentKey = privateKey(0x9a9e).publicKey().toString() + private val parentRoom = SharedKeyDerivation.marmotGroupId(parentKey) + + private val grant = GuardianDerivation.grant( + groupKey, groupRoom, GuardianDerivation.grant(parentKey, parentRoom, emptyList(), groupRoom), walletId, + ) + private val account = MemberWalletDerivation.account(walletKey, chain, grant) + + private fun request(label: String? = "Savings", group: String = groupRoom) = + MemberWalletRequestEvent.build(member, group, walletPrivateKey, account, label, createdAt = 1_700_000_000) + + /** [event] with [tags], re-signed by the member, so only the tags are wrong. */ + private fun resigned(event: Event, tags: Array> = event.tags, content: String = event.content): Event { + val id = EventHasher.hashId(event.pubKey, event.createdAt, event.kind, tags, content) + val sig = Crypto.signSchnorr(ByteVector32(id), member, null).toHex() + return Event(id, event.pubKey, event.createdAt, event.kind, tags, content, sig) + } + + private fun Event.replacing(name: String, vararg value: String): Array> = + tags.map { if (it[0] == name) arrayOf(name, *value) else it }.toTypedArray() + + @Test + fun `a request reads and is believed`() { + val verified = assertNotNull(MemberWalletRequestEvent.verified(request())) + assertEquals(member.xOnlyPublicKey().value.toHex(), verified.reading.memberPublicKey) + assertEquals(groupRoom, verified.reading.groupChatRoomId) + assertEquals(walletId, verified.reading.walletId) + assertEquals(grant, verified.reading.guardians) + assertEquals("Savings", verified.reading.label) + assertEquals(account, verified.account) + } + + @Test + fun `a request with no label reads`() { + assertNull(assertNotNull(MemberWalletRequestEvent.verified(request(label = null))).reading.label) + assertNull(MemberWalletRequestEvent.verified(request(label = " ")).let { it?.reading?.label }) + } + + @Test + fun `a request somebody else signed is refused`() { + val signedByAnother = request().let { Event(it.id, it.pubKey, it.createdAt, it.kind, it.tags, it.content, "0".repeat(128)) } + assertNull(MemberWalletRequestEvent.verified(signedByAnother)) + } + + @Test + fun `a wallet id that is not the key's is refused`() { + val event = request() + assertNull(MemberWalletRequestEvent.verified(resigned(event, event.replacing("wallet", "f".repeat(64))))) + } + + @Test + fun `a possession signature by another key is refused`() { + val event = request() + val other = Crypto.signSchnorr(ByteVector32("ab".repeat(32)), privateKey(0xb0b), null).toHex() + assertNull(MemberWalletRequestEvent.verified(resigned(event, event.replacing("possession", other)))) + } + + @Test + fun `a request that leaves out the group it asks is refused`() { + // Signed for the group, but asking a stranger: the nearest guardian is not the group asked. + val event = request() + val stranger = SharedKeyDerivation.marmotGroupId(privateKey(0x57a9).publicKey().toString()) + assertNull(MemberWalletRequestEvent.verified(resigned(event, event.replacing("h", stranger)))) + } + + @Test + fun `a descriptor that does not rederive is refused`() { + val event = request() + val plain = MemberWalletDerivation.account(walletKey, chain, emptyList()) + val tags = event.tags.map { if (it[0] == "descriptor" && it[2] == "receive") arrayOf("descriptor", plain.receiveDescriptor, "receive") else it } + assertNull(MemberWalletRequestEvent.verified(resigned(event, tags.toTypedArray()))) + // The xpub does not depend on the guardians, so it is another key's that does not rederive. + val another = MemberWalletDerivation.account(privateKey(0xb0b).publicKey(), chain, grant) + assertNull(MemberWalletRequestEvent.verified(resigned(event, content = another.xpub))) + } + + @Test + fun `two wallet tags, or none, do not read`() { + val event = request() + assertNull(MemberWalletRequestEvent.read(resigned(event, event.tags + arrayOf(arrayOf("wallet", walletId))))) + assertNull(MemberWalletRequestEvent.read(resigned(event, event.tags.filterNot { it[0] == "wallet" }.toTypedArray()))) + } + + @Test + fun `a request travels whole, sent only by the member who signed it`() { + val signed = request() + fun inner(sender: String) = Event("1".repeat(64), sender, signed.createdAt, MemberWalletRequestEvent.KIND, emptyArray(), signed.toJson(), "") + + assertEquals(signed.id, MemberWalletRequestEvent.carried(inner(signed.pubKey))?.id) + assertNotNull(MemberWalletRequestEvent.verified(MemberWalletRequestEvent.carried(inner(signed.pubKey))!!), "the signature survives the trip") + assertNull(MemberWalletRequestEvent.carried(inner("2".repeat(64))), "nobody passes a request on") + } +}