diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEvent.kt new file mode 100644 index 00000000..bfb72589 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEvent.kt @@ -0,0 +1,126 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import kotlin.time.Clock + +/** + * A group saying, with a quorum, whether it guards its members' wallets and at + * what delay -- `docs/member-wallet-delay.md`. + * + * ``` + * open: ["d", "member-wallets"], ["guardian_delay", ""] + * closed: ["d", "member-wallets"], ["closed"] + * ``` + * + * Signed by the group's own quorum in its own room, about its own leaf: the + * delay on the group's leaf in every wallet a member asks it to guard from now + * on. Every group above keeps the delay it chose for the group, as it does in a + * subgroup's wallet. + * + * ### The group's opt-in + * + * No policy means the group does not guard members' wallets. A closed one means + * it has stopped: no new member wallets until a newer open one. Closing never + * releases a wallet already guarded -- the group's leaf is in every one of its + * addresses -- and a later policy never changes one, since each wallet's delay + * is fixed in its certificate. + * + * ### Not the birth certificate + * + * The certificate is the parent's statement about the group, signed once at its + * birth, and a root group has none. This is the group's decision about its own + * leaf, which the group can change. See the note's *Where the delay should live*. + * + * ### Why 30337 + * + * After the key notice (30336), the last of the member-wallet kinds. + */ +object MemberWalletPolicyEvent { + val KIND: Kind = 30337 + + /** The `d` tag: one policy about members' wallets per group, the newest winning. */ + const val IDENTIFIER = "member-wallets" + + private const val D_TAG = "d" + private const val DELAY_TAG = "guardian_delay" + private const val CLOSED_TAG = "closed" + + /** The group guards members' wallets, its own leaf at [delay] blocks. */ + fun open(delay: Long, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> { + require(delay in GuardianDerivation.DELAY_RANGE) { + "a guardian's delay is ${GuardianDerivation.MIN_DELAY} to ${GuardianDerivation.MAX_DELAY} blocks, not $delay" + } + return EventTemplate( + createdAt = createdAt, + kind = KIND, + tags = arrayOf(arrayOf(D_TAG, IDENTIFIER), arrayOf(DELAY_TAG, delay.toString())), + content = "", + ) + } + + /** The group takes no new members' wallets. */ + fun closed(createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = EventTemplate( + createdAt = createdAt, + kind = KIND, + tags = arrayOf(arrayOf(D_TAG, IDENTIFIER), arrayOf(CLOSED_TAG)), + content = "", + ) + + /** What a policy says, as its group signed it. */ + sealed interface Policy { + val event: Event + val createdAt: Long get() = event.createdAt + + /** The group guards members' wallets, its own leaf at [delay] blocks. */ + data class Open(val delay: Long, override val event: Event) : Policy + + /** The group has stopped taking new members' wallets. */ + data class Closed(override val event: Event) : Policy + } + + /** + * [event] as [chatRoomId]'s policy, or null when it is not one: + * + * 1. the kind, and the `d` tag; + * 2. exactly one of a `guardian_delay` that reads and is in + * `GuardianDerivation.DELAY_RANGE`, or a bare `closed` -- a policy that + * says both, or neither, says nothing a device can act on; + * 3. signed by [chatRoomId] itself, which any device can check holding the + * room's id alone. + */ + fun verify(event: Event, chatRoomId: String): Policy? = runCatching { + if (event.kind != KIND) return null + if (event.tags.count { it.size >= 2 && it[0] == D_TAG && it[1] == IDENTIFIER } != 1) return null + if (event.tags.any { it.isNotEmpty() && it[0] == D_TAG && (it.size < 2 || it[1] != IDENTIFIER) }) return null + + val delays = event.tags.filter { it.isNotEmpty() && it[0] == DELAY_TAG } + val closed = event.tags.filter { it.isNotEmpty() && it[0] == CLOSED_TAG } + val policy = when { + delays.size == 1 && closed.isEmpty() -> { + val delay = delays.single().getOrNull(1)?.toLongOrNull()?.takeIf { it in GuardianDerivation.DELAY_RANGE } + ?: return null + Policy.Open(delay, event) + } + delays.isEmpty() && closed.size == 1 -> Policy.Closed(event) + else -> return null + } + + if (!GroupKeyStateEvent.isSignedByRoom(event, chatRoomId)) return null + policy + }.getOrNull() + + /** + * The newest of [events] that is [chatRoomId]'s policy, open or closed -- + * by the group's own timestamp, the id breaking a tie, so two devices that + * read the same events in another order agree. + */ + fun newestAmong(events: List, chatRoomId: String): Policy? = + events.mapNotNull { verify(it, chatRoomId) }.maxWithOrNull(ORDER) + + /** The order policies are compared in: [newestAmong]'s, and the signers' staleness check. */ + val ORDER: Comparator = compareBy({ it.createdAt }, { it.event.id }) +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEventTest.kt new file mode 100644 index 00000000..95cf01de --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/MemberWalletPolicyEventTest.kt @@ -0,0 +1,92 @@ +package com.machankura.bennu.compose.nostr.wallet + +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher +import fr.acinq.bitcoin.ByteVector32 +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.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertNull + +/** + * A group's policy on its members' wallets -- `docs/member-wallet-delay.md`, + * Phase 1. The room is a key whose secret the test holds: `isSignedByRoom` asks + * only that the room's id signed it. + */ +class MemberWalletPolicyEventTest { + private val roomKey = PrivateKey(ByteVector32(Hex.decode("07".repeat(32)))) + private val roomId = roomKey.publicKey().xOnly().value.toString() + private val strangerKey = PrivateKey(ByteVector32(Hex.decode("09".repeat(32)))) + + private fun signed( + tags: Array>, + createdAt: Long = 1_700_000_000, + by: PrivateKey = roomKey, + kind: Int = MemberWalletPolicyEvent.KIND, + ): Event { + val pubKey = by.publicKey().xOnly().value.toString() + val id = EventHasher.hashId(pubKey, createdAt, kind, tags, "") + return Event(id, pubKey, createdAt, kind, tags, "", Crypto.signSchnorr(ByteVector32(id), by, null).toString()) + } + + private fun open(delay: Long, createdAt: Long = 1_700_000_000) = signed(MemberWalletPolicyEvent.open(delay, createdAt).tags, createdAt) + private fun closed(createdAt: Long = 1_700_000_000) = signed(MemberWalletPolicyEvent.closed(createdAt).tags, createdAt) + + @Test + fun `an open policy and a closed one each read back`() { + val opened = assertIs(MemberWalletPolicyEvent.verify(open(144), roomId)) + assertEquals(144L, opened.delay) + assertIs(MemberWalletPolicyEvent.verify(closed(), roomId)) + } + + @Test + fun `a policy that does not say one thing a device can act on does not read`() { + val d = arrayOf("d", MemberWalletPolicyEvent.IDENTIFIER) + val cases = mapOf( + "another kind" to signed(arrayOf(d, arrayOf("guardian_delay", "144")), kind = 30336), + "no d tag" to signed(arrayOf(arrayOf("guardian_delay", "144"))), + "another d tag" to signed(arrayOf(arrayOf("d", "subgroups"), arrayOf("guardian_delay", "144"))), + "two delays" to signed(arrayOf(d, arrayOf("guardian_delay", "144"), arrayOf("guardian_delay", "12"))), + "five blocks" to signed(arrayOf(d, arrayOf("guardian_delay", "5"))), + "65,536 blocks" to signed(arrayOf(d, arrayOf("guardian_delay", "65536"))), + "a word" to signed(arrayOf(d, arrayOf("guardian_delay", "twelve"))), + "both a delay and closed" to signed(arrayOf(d, arrayOf("guardian_delay", "144"), arrayOf("closed"))), + "neither" to signed(arrayOf(d)), + "another room's signature" to signed(MemberWalletPolicyEvent.open(144).tags, by = strangerKey), + ) + cases.forEach { (name, event) -> assertNull(MemberWalletPolicyEvent.verify(event, roomId), "a policy with $name read") } + } + + @Test + fun `the newest decides, open or closed, in any order`() { + val first = open(12, createdAt = 1_700_000_000) + val shut = closed(createdAt = 1_700_000_100) + val reopened = open(1_008, createdAt = 1_700_000_200) + + listOf(listOf(first, shut, reopened), listOf(reopened, first, shut), listOf(shut, reopened, first)).forEach { events -> + assertEquals(1_008L, assertIs(MemberWalletPolicyEvent.newestAmong(events, roomId)).delay) + } + assertIs(MemberWalletPolicyEvent.newestAmong(listOf(shut, first), roomId)) + assertNull(MemberWalletPolicyEvent.newestAmong(emptyList(), roomId)) + } + + @Test + fun `a tie on the timestamp goes to the larger id, on every device`() { + val a = open(144, createdAt = 1_700_000_000) + val b = open(1_008, createdAt = 1_700_000_000) + val larger = listOf(a, b).maxBy { it.id } + + assertEquals(larger.id, MemberWalletPolicyEvent.newestAmong(listOf(a, b), roomId)?.event?.id) + assertEquals(larger.id, MemberWalletPolicyEvent.newestAmong(listOf(b, a), roomId)?.event?.id) + } + + @Test + fun `an open policy outside the range cannot be built`() { + assertFailsWith { MemberWalletPolicyEvent.open(5) } + assertFailsWith { MemberWalletPolicyEvent.open(65_536) } + } +}