diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt index 548a1b91..a843c700 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt @@ -13,6 +13,7 @@ import fr.acinq.bitcoin.KeyPath import fr.acinq.bitcoin.PrivateKey import fr.acinq.bitcoin.PublicKey import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptTree import fr.acinq.bitcoin.XonlyPublicKey import fr.acinq.bitcoin.crypto.Pack import fr.acinq.bitcoin.crypto.frost.TweakCache @@ -54,6 +55,15 @@ import fr.acinq.bitcoin.utils.Either * key for any address recovers the group's threshold key -- the room, every * address of every account, and every event the group can sign. Nothing here or * anywhere else reconstructs one. The only export is the account xpub. + * + * ### A guarded account + * + * An account opened with guardians -- the keys a subgroup's birth certificate + * grants it, see `GuardianDerivation` -- is the same account with one change at + * the very end: each address commits to a tree of one leaf per guardian, so the + * last tweak is BIP341's script-path tweak over that tree rather than BIP86's + * empty one. The internal key, and so the group's own key-path spend, is + * untouched. `docs/group-wallet-guardians.md` says why. */ object GroupWalletDerivation { /** BIP44's external chain: addresses handed out to be paid. */ @@ -86,7 +96,16 @@ object GroupWalletDerivation { val extendedPublicKey: DeterministicWallet.ExtendedPublicKey, /** The threshold key tweaked to [extendedPublicKey]'s key: what the account's sessions start from. */ internal val cache: TweakCache, + /** + * The ancestors that can spend from every address of this account, nearest + * first -- empty for an account nobody guards, which is every account a + * group that is nobody's subgroup opens. + */ + val guardians: List = emptyList(), ) { + /** Whether its addresses carry guardian leaves. */ + val isGuarded: Boolean get() = guardians.isNotEmpty() + /** The account key's own fingerprint, as a descriptor's key origin and a PSBT's derivation name it. */ val fingerprint: Long get() = extendedPublicKey.fingerprint() @@ -109,14 +128,20 @@ object GroupWalletDerivation { val changeDescriptor: String get() = descriptor(CHANGE) private fun descriptor(change: Long): String { - val body = "tr([$fingerprintHex]$xpub/$change/*)" + val tree = if (isGuarded) "," + GuardianDerivation.descriptorTree(guardians, chain, account, change) else "" + val body = "tr([$fingerprintHex]$xpub/$change/*$tree)" return "$body#${Descriptor.checksum(body)}" } - override fun equals(other: Any?): Boolean = - other is Account && chain == other.chain && account == other.account && extendedPublicKey == other.extendedPublicKey + /** The same account with [guardians] in every address. */ + fun guardedBy(guardians: List): Account = + Account(chain, account, extendedPublicKey, cache, guardians) - override fun hashCode(): Int = extendedPublicKey.hashCode() + override fun equals(other: Any?): Boolean = + other is Account && chain == other.chain && account == other.account && + extendedPublicKey == other.extendedPublicKey && guardians == other.guardians + + override fun hashCode(): Int = extendedPublicKey.hashCode() * 31 + guardians.hashCode() } /** @@ -134,12 +159,22 @@ object GroupWalletDerivation { /** BIP86's output key `Q`: the key in the output script, and the key a spend's signature verifies against. */ val outputKey: XonlyPublicKey, val cache: TweakCache, + /** The guardian leaves this address commits to, or null for BIP86's empty tree. */ + val tree: ScriptTree? = null, ) { + /** The tweak from [internalKey] to [outputKey]: over [tree] when there is one, BIP86's otherwise. */ + val taprootTweak: Crypto.TaprootTweak + get() = tree?.let { Crypto.TaprootTweak.ScriptPathTweak(it.hash()) } ?: Crypto.TaprootTweak.KeyPathTweak + /** `OP_1 `. */ val pubkeyScript: ByteVector - get() = ByteVector(Script.write(Script.pay2tr(internalKey, Crypto.TaprootTweak.KeyPathTweak))) + get() = ByteVector(Script.write(Script.pay2tr(internalKey, taprootTweak))) - fun address(chain: Chain): String = Bitcoin.computeBIP86Address(internalKey, chain.chainHash) + fun address(chain: Chain): String = when (tree) { + null -> Bitcoin.computeBIP86Address(internalKey, chain.chainHash) + else -> Bitcoin.addressFromPublicKeyScript(chain.chainHash, pubkeyScript.toByteArray()).right + ?: throw IllegalStateException("a taproot output always has an address") + } /** The path below the account, as a PSBT's `tap_bip32_derivation` carries it. */ val keyPath: KeyPath get() = KeyPath(listOf(change, index)) @@ -153,7 +188,12 @@ object GroupWalletDerivation { * or the HMAC lands on an invalid scalar -- around 2^-127, and BIP32 throws at * the same place. */ - fun account(thresholdPublicKey: HexKey, chain: Chain, account: Long = 0L): Account { + fun account( + thresholdPublicKey: HexKey, + chain: Chain, + account: Long = 0L, + guardians: List = emptyList(), + ): Account { require(account in 0L..MAX_INDEX) { "account $account is not an unhardened index" } val root = PublicKey(ByteVector(thresholdPublicKey.hexToByteArray())) @@ -185,6 +225,7 @@ object GroupWalletDerivation { parent = 0L, ), cache = cache, + guardians = guardians, ) } @@ -197,19 +238,27 @@ object GroupWalletDerivation { * a parity mistake in the cache and a wallet whose signatures do not verify. */ fun derive(account: Account, change: Long, index: Long): Derived = - deriveBelow(account.extendedPublicKey, account.cache, change, index) + deriveBelow( + account.extendedPublicKey, + account.cache, + change, + index, + tree = GuardianDerivation.treeAt(account.guardians, account.chain, account.account, change, index), + ) /** - * The tail on its own: BIP32 public derivation and the BIP341 key-path tweak, - * from any account-level key and the cache that signs as it. Split out so the - * tail can be tested against BIP86's published vectors, which start from a - * seed's account key rather than from a threshold key. + * The tail on its own: BIP32 public derivation and the BIP341 tweak -- over + * [tree] when there is one, BIP86's key-path tweak otherwise -- from any + * account-level key and the cache that signs as it. Split out so the tail can + * be tested against BIP86's published vectors, which start from a seed's + * account key rather than from a threshold key. */ internal fun deriveBelow( accountKey: DeterministicWallet.ExtendedPublicKey, accountCache: TweakCache, change: Long, index: Long, + tree: ScriptTree? = null, ): Derived { require(change == RECEIVE || change == CHANGE) { "change must be $RECEIVE or $CHANGE, not $change" } require(index in 0L..MAX_INDEX) { "index $index is not an unhardened index" } @@ -224,15 +273,16 @@ object GroupWalletDerivation { val internalKey = childKey.publicKey.xOnly() require(cache.tweakedPublicKey == internalKey) { "the cache does not reach the internal key at $change/$index" } - cache = when (val tweaked = cache.tweak(internalKey.tweak(Crypto.TaprootTweak.KeyPathTweak), isXonly = true)) { - is Either.Left -> throw IllegalArgumentException("Could not apply the key-path tweak at $change/$index", tweaked.value) + val taprootTweak = tree?.let { Crypto.TaprootTweak.ScriptPathTweak(it.hash()) } ?: Crypto.TaprootTweak.KeyPathTweak + cache = when (val tweaked = cache.tweak(internalKey.tweak(taprootTweak), isXonly = true)) { + is Either.Left -> throw IllegalArgumentException("Could not apply the taproot tweak at $change/$index", tweaked.value) is Either.Right -> tweaked.value.first } - val outputKey = internalKey.outputKey(Crypto.TaprootTweak.KeyPathTweak).first + val outputKey = internalKey.outputKey(taprootTweak).first require(cache.tweakedPublicKey == outputKey) { "the cache does not reach the output key at $change/$index" } - return Derived(change = change, index = index, internalKey = internalKey, outputKey = outputKey, cache = cache) + return Derived(change = change, index = index, internalKey = internalKey, outputKey = outputKey, cache = cache, tree = tree) } /** BIP32's `I_L` for one unhardened step: the scalar CKDpub adds, which a FROST cache takes as a plain tweak. */ diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt index 1587e43a..a72e7c4d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWallet.kt @@ -54,17 +54,32 @@ data class GroupWallet( * Newest by the group's own timestamp with the id breaking a tie, for the * reason `GroupRelayList.newestAmong` gives: two devices reading the same * events in different orders have to agree. + * + * Two rules first, for a guarded account, each of which keeps a later + * statement from moving every address of one already holding coins: + * + * 1. a guarded statement outranks a plain one -- an account opened guarded + * stays guarded, whatever a client that predates guardians signs later; + * 2. among guarded ones the earliest decides the guardians, and a later one + * naming others is ignored. Changing who guards a wallet is another + * account. */ fun newestAmong( signedEvents: List, thresholdPublicKey: HexKey, chain: Chain, account: Long = 0L, - ): GroupWallet? = - signedEvents - .asSequence() + ): GroupWallet? { + val order = compareBy({ it.openedAt }, { it.signedEvent.id }) + val opened = signedEvents .mapNotNull { of(it, thresholdPublicKey) } .filter { it.chain == chain && it.account.account == account } - .maxWithOrNull(compareBy({ it.openedAt }, { it.signedEvent.id })) + + val guarded = opened.filter { it.account.isGuarded } + val first = guarded.minWithOrNull(order) + ?: return opened.maxWithOrNull(order) + + return guarded.filter { it.account.guardians == first.account.guardians }.maxWithOrNull(order) + } } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt index c00421d0..aa3d5705 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEvent.kt @@ -1,6 +1,12 @@ 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.SharedKeyDerivation +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.subgroup.tags.GuardianTag +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 import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate @@ -33,6 +39,16 @@ import kotlin.time.Clock * statement naming any xpub but the rederived one is not the group's wallet, * whoever signed it. * + * ### A guarded statement + * + * A subgroup whose birth certificate grants it guardian keys may open its wallet + * *guarded*: every address carries a leaf per ancestor, and the statement is the + * child's quorum agreeing to that. It carries the guardians as [GuardianTag]s + * and the certificate itself, whole, so that a member who holds no key state -- + * one welcomed in after the founding -- can still check every address, and so + * that an ancestor it is forwarded to can check where its own key came from. + * See `docs/group-wallet-guardians.md`. + * * ### Never on a relay * * The xpub is every address and the whole balance, to whoever has it. Like the @@ -70,13 +86,24 @@ object GroupWalletStatementEvent { val xpub: String, val receiveDescriptor: String, val changeDescriptor: String, + /** The guardians it names, nearest first; empty for a plain statement. */ + val guardians: List = emptyList(), + /** The birth certificate a guarded statement carries, unverified. */ + val certificate: Event? = null, ) { /** * The account this statement describes, if [thresholdPublicKey] rederives * every value it carries; null otherwise. + * + * For a guarded one, also: the certificate certifies the room the key + * makes, it names that key, and its guardian keys are exactly the ones + * the statement names -- the guardians come from the parent's signature + * and the child's agreement together, or the statement opens nothing. */ fun verifiedAgainst(thresholdPublicKey: HexKey): GroupWalletDerivation.Account? { - val account = runCatching { GroupWalletDerivation.account(thresholdPublicKey, chain, account) } + if (guardians.isNotEmpty() && !guardiansCheckOut(thresholdPublicKey)) return null + + val account = runCatching { GroupWalletDerivation.account(thresholdPublicKey, chain, account, guardians) } .getOrNull() ?: return null @@ -86,6 +113,16 @@ object GroupWalletStatementEvent { it.changeDescriptor == changeDescriptor } } + + private fun guardiansCheckOut(thresholdPublicKey: HexKey): Boolean = runCatching { + val certificate = certificate ?: return false + val chatRoomId = SharedKeyDerivation.marmotGroupId(thresholdPublicKey) + val parentChatRoomId = SubgroupBirthCertificateEvent.parseParentChatRoomId(certificate.tags) ?: return false + + SubgroupBirthCertificateEvent.certifies(certificate, chatRoomId, parentChatRoomId) && + SubgroupBirthCertificateEvent.parseThresholdPublicKey(certificate.tags).equals(thresholdPublicKey, ignoreCase = true) && + SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) == guardians + }.getOrDefault(false) } /** @@ -94,8 +131,24 @@ object GroupWalletStatementEvent { */ fun identifier(chain: Chain, account: Long): String = "${chainName(chain)}:$account" - fun template(account: GroupWalletDerivation.Account, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = - EventTemplate( + /** + * The statement opening [account]. A guarded account needs the [certificate] + * its guardians were granted in, which the statement carries whole. + */ + fun template( + account: GroupWalletDerivation.Account, + certificate: Event? = null, + createdAt: Long = Clock.System.now().epochSeconds, + ): EventTemplate<*> { + require(!account.isGuarded || certificate != null) { "a guarded wallet's statement carries the certificate that granted its guardians" } + + val guarded = if (account.isGuarded) { + account.guardians.map(GuardianTag::assemble) + listOf(SubgroupBirthCertificateTag.assemble(certificate!!)) + } else { + emptyList() + } + + return EventTemplate( createdAt = createdAt, kind = KIND, tags = arrayOf( @@ -104,9 +157,10 @@ object GroupWalletStatementEvent { arrayOf(ACCOUNT_TAG, account.account.toString()), arrayOf(DESCRIPTOR_TAG, account.receiveDescriptor, RECEIVE_MARKER), arrayOf(DESCRIPTOR_TAG, account.changeDescriptor, CHANGE_MARKER), - ), + ) + guarded, content = account.xpub, ) + } /** The statement's fields, or null when any is missing or unreadable. Nothing is verified here. */ fun read(tags: Array>, content: String): Reading? { @@ -123,7 +177,11 @@ object GroupWalletStatementEvent { // account both stand; reading it back here keeps "newest per account" one rule. if (value(D_TAG) != identifier(chain, account)) return null - return Reading(chain, account, content, receive, change) + // Guardians that do not all read are not a shorter list of guardians. + val guardians = GuardianTag.parseAll(tags) ?: return null + val certificate = tags.firstNotNullOfOrNull(SubgroupBirthCertificateTag::parse)?.certificate + + return Reading(chain, account, content, receive, change, guardians, certificate) } /** diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt index f707eb15..e088e616 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/nostr/wallet/GroupWalletStatementEventTest.kt @@ -2,6 +2,10 @@ package com.machankura.bennu.compose.nostr.wallet import com.machankura.bennu.compose.database.model.GroupSignedEvent import com.machankura.bennu.compose.managers.GroupWalletDerivation +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.GuardianTag import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher import fr.acinq.bitcoin.ByteVector32 @@ -13,6 +17,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull +import kotlin.test.assertTrue /** * A wallet statement, read and believed. @@ -47,7 +52,7 @@ class GroupWalletStatementEventTest { } private fun statement(account: GroupWalletDerivation.Account, createdAt: Long = 1_700_000_000): GroupSignedEvent { - val template = GroupWalletStatementEvent.template(account, createdAt) + val template = GroupWalletStatementEvent.template(account, createdAt = createdAt) return signed(template.tags, template.content, createdAt) } @@ -120,6 +125,99 @@ class GroupWalletStatementEventTest { assertNull(GroupWallet.newestAmong(listOf(older, newer), thresholdKey, Chain.Signet)) } + // ---- A guarded statement --------------------------------------------- + + /** + * The parent, as a key whose secret the test holds: `certifies` asks only + * that the room the certificate names as parent signed it. + */ + private val parentKey = PrivateKey(ByteVector32(Hex.decode("0b".repeat(32)))) + private val parentRoomId = parentKey.publicKey().xOnly().value.toString() + private val childRoomId = SharedKeyDerivation.marmotGroupId(thresholdKey) + private val grant = GuardianDerivation.grant(key(0x9a4e47), parentRoomId, emptyList(), childRoomId) + + private fun certificate(guardians: List = grant, childKey: String = thresholdKey): Event { + val tags = SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = SharedKeyDerivation.marmotGroupId(childKey), + parentChatRoomId = parentRoomId, + thresholdPublicKey = childKey, + adminPublicKeys = listOf("a".repeat(64)), + name = "Translation team", + guardians = guardians, + ) + val content = SharedKeyDerivation.marmotGroupId(childKey) + val id = EventHasher.hashId(parentRoomId, 1_700_000_000, SubgroupBirthCertificateEvent.KIND, tags, content) + val sig = Crypto.signSchnorr(ByteVector32(id), parentKey, null).toString() + return Event(id, parentRoomId, 1_700_000_000, SubgroupBirthCertificateEvent.KIND, tags, content, sig) + } + + private val guarded = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = grant) + + private fun guardedStatement( + account: GroupWalletDerivation.Account = guarded, + certificate: Event = certificate(), + createdAt: Long = 1_700_000_000, + ): GroupSignedEvent { + val template = GroupWalletStatementEvent.template(account, certificate, createdAt) + return signed(template.tags, template.content, createdAt) + } + + @Test + fun `a guarded statement reads back as the guarded account, tree and all`() { + val wallet = assertNotNull(GroupWallet.of(guardedStatement(), thresholdKey)) + + assertEquals(guarded, wallet.account) + assertEquals(grant, wallet.account.guardians) + assertTrue(wallet.account.receiveDescriptor.contains("and_v(v:pk("), wallet.account.receiveDescriptor) + // Same internal key as the plain account, different address: only the tree differs. + val plainAddress = GroupWalletDerivation.derive(mainnet, 0, 0) + val guardedAddress = GroupWalletDerivation.derive(guarded, 0, 0) + assertEquals(plainAddress.internalKey, guardedAddress.internalKey) + assertTrue(plainAddress.address(Chain.Mainnet) != guardedAddress.address(Chain.Mainnet)) + assertTrue(guardedAddress.address(Chain.Mainnet).startsWith("bc1p")) + assertEquals(guardedAddress.outputKey, guardedAddress.cache.tweakedPublicKey, "the cache signs the key path of the guarded address") + } + + @Test + fun `guardians the certificate does not grant open nothing`() { + val stranger = GuardianDerivation.grant(key(0x5), parentRoomId, emptyList(), childRoomId) + val wrongGuardians = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = stranger) + + assertNull(GroupWallet.of(guardedStatement(account = wrongGuardians), thresholdKey), "guardians the parent never granted") + assertNull(GroupWallet.of(guardedStatement(certificate = certificate(childKey = otherThresholdKey)), thresholdKey), "a certificate for another child") + } + + @Test + fun `a guarded statement with its guardians stripped is no wallet at all`() { + // What a client that predates guardians sees: descriptors with a tree it + // does not build. It refuses rather than hand out plain addresses under + // the guarded account's name. + val template = GroupWalletStatementEvent.template(guarded, certificate()) + val stripped = template.tags.filterNot { it[0] == GuardianTag.TAG_NAME }.toTypedArray() + + assertNull(GroupWallet.of(signed(stripped, template.content), thresholdKey)) + } + + @Test + fun `an account opened guarded stays guarded, under its first guardians`() { + val firstGuarded = guardedStatement(createdAt = 1_700_000_000) + val laterPlain = statement(mainnet, createdAt = 1_700_000_200) + val laterOtherGuardians = run { + // The parent re-certified with other keys; a later statement adopting + // them would move every address, so it is ignored. + val other = GuardianDerivation.grant(key(0x77), parentRoomId, emptyList(), childRoomId) + guardedStatement( + account = GroupWalletDerivation.account(thresholdKey, Chain.Mainnet, guardians = other), + certificate = certificate(other), + createdAt = 1_700_000_300, + ) + } + + val wallet = assertNotNull(GroupWallet.newestAmong(listOf(laterPlain, firstGuarded, laterOtherGuardians), thresholdKey, Chain.Mainnet)) + assertEquals(firstGuarded.id, wallet.signedEvent.id) + assertEquals(laterPlain.id, GroupWallet.newestAmong(listOf(laterPlain), thresholdKey, Chain.Mainnet)?.signedEvent?.id) + } + @Test fun `every network name round trips`() { listOf(Chain.Mainnet, Chain.Testnet3, Chain.Testnet4, Chain.Signet, Chain.Regtest).forEach {