From 4330faacd7ccd07885eb589d41c0447106c60c0a Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 07:55:01 +0200 Subject: [PATCH] feat(wallet): derive a group wallet's keys from its threshold key (Phase 1) GroupWalletDerivation: a public account step -- a tagged HMAC over the threshold key, the network and an account number -- gives a depth-0 xpub, and below it BIP86's own unhardened tail, //, with the key-path tweak on top. Each address is computed twice, as points and as tweaks on a FROST cache, and refused if the two disagree. Tests: BIP86's published vectors through the cache prove the tail; a pinned vector freezes the account step; a sweep covers both parities. Co-Authored-By: Claude Opus 5.5 --- .../compose/managers/GroupWalletDerivation.kt | 252 ++++++++++++++++++ .../managers/GroupWalletDerivationTest.kt | 168 ++++++++++++ docs/group-chain-wallet.md | 14 +- 3 files changed, 430 insertions(+), 4 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt create mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivationTest.kt 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 new file mode 100644 index 00000000..fa49f211 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivation.kt @@ -0,0 +1,252 @@ +package com.machankura.bennu.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import fr.acinq.bitcoin.Bitcoin +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.Descriptor +import fr.acinq.bitcoin.DeterministicWallet +import fr.acinq.bitcoin.KeyPath +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.XonlyPublicKey +import fr.acinq.bitcoin.crypto.Pack +import fr.acinq.bitcoin.crypto.frost.TweakCache +import fr.acinq.bitcoin.utils.Either + +/** + * The group's on-chain wallet keys, derived from its ChillDKG threshold key. + * + * A wallet address here is BIP86's -- a taproot key-path output with no script + * tree -- at BIP86's own unhardened tail, `//`, under an account + * key that the threshold key is publicly tweaked to: + * + * ``` + * I = HMAC-SHA512("bennu/group-wallet/account/v1", serP(K) || chainHash || ser32(account)) + * K_a = K + I[0:32]·G, chain code I[32:64] an ordinary depth-0 xpub + * P = xonly(CKDpub(CKDpub(K_a, change), index)) BIP86 internal key + * Q = P + H_TapTweak(P)·G BIP86 output key + * ``` + * + * See `docs/group-chain-wallet.md` for why each level is what it is. In short: + * every hardened level of `m/86'/0'/0'` needs the parent private key, which in a + * threshold group nobody holds; the ceremony is what isolates one group's key + * from another's, and the account step does what `coin'` and `account'` do -- + * mainnet and test networks, and account 0 and account 1, are unrelated keys. + * Below the account the derivation is plain BIP32, which is what lets the group + * export a descriptor any watch-only wallet can follow. + * + * ### Not [SharedKeyDerivation], and never to be confused with it + * + * That object derives nostr keys -- the room's own id among them -- with x-only + * tweaks at every step and a SHA-256 scalar. This one uses plain tweaks and + * HMAC-SHA512 until the last step. The two never share a key, and the wallet + * never sits on the room's key: a wallet at the room's key would be findable by + * anyone who can see the room's id. + * + * ### The rule this inherits + * + * Every tweak is publicly computable from the threshold key, so a leaked private + * 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. + */ +object GroupWalletDerivation { + /** BIP44's external chain: addresses handed out to be paid. */ + const val RECEIVE: Long = 0L + + /** BIP44's internal chain: where a spend sends what it does not pay out. */ + const val CHANGE: Long = 1L + + /** + * The key of the account step's HMAC. An input to every wallet key, so it is + * frozen the moment a group holds coins under it: changing it moves every + * address, and the coins at the old ones are found by nobody. A rename is a + * protocol fork and belongs in a `v2`, never in an edit to this one. + */ + private const val ACCOUNT_TAG = "bennu/group-wallet/account/v1" + + /** The largest unhardened BIP32 index. Hardened ones cannot be walked here. */ + private const val MAX_INDEX: Long = 0x7FFFFFFFL + + /** + * One account of one group on one network: the extended public key every + * address of it is derived under, and the cache that signs as its key. + * + * [extendedPublicKey] is safe to hand out -- it reveals the account's + * addresses and balance, and nothing about the threshold key or the room. + */ + class Account internal constructor( + val chain: Chain, + val account: Long, + val extendedPublicKey: DeterministicWallet.ExtendedPublicKey, + /** The threshold key tweaked to [extendedPublicKey]'s key: what the account's sessions start from. */ + internal val cache: TweakCache, + ) { + /** 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() + + val fingerprintHex: String get() = fingerprint.toString(16).padStart(8, '0') + + /** `xpub` on mainnet, `tpub` on every test network -- BIP86 has no SLIP-132 prefix of its own. */ + val xpub: String + get() = extendedPublicKey.encode( + if (chain.isMainnet()) DeterministicWallet.xpub else DeterministicWallet.tpub + ) + + /** + * The receive branch as a ranged `tr()` descriptor over the account xpub, with the + * account's fingerprint as its key origin and a checksum -- what a watch-only + * wallet imports. + */ + val receiveDescriptor: String get() = descriptor(RECEIVE) + + /** The change branch, as [receiveDescriptor] gives the receive branch. */ + val changeDescriptor: String get() = descriptor(CHANGE) + + private fun descriptor(change: Long): String { + val body = "tr([$fingerprintHex]$xpub/$change/*)" + return "$body#${Descriptor.checksum(body)}" + } + + override fun equals(other: Any?): Boolean = + other is Account && chain == other.chain && account == other.account && extendedPublicKey == other.extendedPublicKey + + override fun hashCode(): Int = extendedPublicKey.hashCode() + } + + /** + * One address of an account, and the cache a signing session for it needs. + * + * [cache] is not an optimisation, for the same reason [SharedKeyDerivation.Derived]'s + * is not: a session created with any other cache aggregates to a signature + * that is perfectly valid for some other key, and the coins are at [outputKey]. + */ + data class Derived( + val change: Long, + val index: Long, + /** BIP86's internal key `P`. */ + val internalKey: XonlyPublicKey, + /** 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, + ) { + /** `OP_1 `. */ + val pubkeyScript: ByteVector + get() = ByteVector(Script.write(Script.pay2tr(internalKey, Crypto.TaprootTweak.KeyPathTweak))) + + fun address(chain: Chain): String = Bitcoin.computeBIP86Address(internalKey, chain.chainHash) + + /** The path below the account, as a PSBT's `tap_bip32_derivation` carries it. */ + val keyPath: KeyPath get() = KeyPath(listOf(change, index)) + } + + /** + * The account step: the threshold key tweaked by a tagged HMAC over itself, + * the network and the account number. + * + * @throws IllegalArgumentException if the threshold key is not a valid point, + * 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 { + require(account in 0L..MAX_INDEX) { "account $account is not an unhardened index" } + + val root = PublicKey(ByteVector(thresholdPublicKey.hexToByteArray())) + require(root.isValid()) { "the threshold key is not a valid point" } + + val i = Crypto.hmac512( + ACCOUNT_TAG.encodeToByteArray(), + root.value.toByteArray() + chain.chainHash.value.toByteArray() + Pack.writeInt32BE(account.toInt()) + ) + val tweak = i.copyOfRange(0, 32) + val chainCode = i.copyOfRange(32, 64) + require(Crypto.isPrivKeyValid(tweak)) { "the account step for account $account landed on an invalid scalar" } + + val accountKey = root + PrivateKey(tweak).publicKey() + val cache = plainTweak(TweakCache.create(root), ByteVector32(tweak), "the account step") + // The cache tracks the full point; the point arithmetic above is the + // reference it has to agree with, or every session for this account signs + // for a key nobody's coins are at. + require(cache.tweakedPublicKey == accountKey.xOnly()) { "the account cache does not reach the account key" } + + return Account( + chain = chain, + account = account, + extendedPublicKey = DeterministicWallet.ExtendedPublicKey( + publickeybytes = accountKey.value, + chaincode = ByteVector32(chainCode), + depth = 0, + path = KeyPath.empty, + parent = 0L, + ), + cache = cache, + ) + } + + /** + * The address at `//` under [account]. + * + * Computed twice -- as points through [DeterministicWallet.ExtendedPublicKey.derivePublicKey], + * and as tweaks on the account's cache -- and refused if the two disagree. + * They are `require`s rather than tests because they are what stands between + * 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) + + /** + * 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. + */ + internal fun deriveBelow( + accountKey: DeterministicWallet.ExtendedPublicKey, + accountCache: TweakCache, + change: Long, + index: Long, + ): 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" } + require(accountCache.tweakedPublicKey == accountKey.publicKey.xOnly()) { "the cache does not sign as this account key" } + + val branchKey = accountKey.derivePublicKey(change) + val childKey = branchKey.derivePublicKey(index) + + var cache = plainTweak(accountCache, childTweak(accountKey, change), "branch $change") + cache = plainTweak(cache, childTweak(branchKey, index), "index $index") + + 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) + is Either.Right -> tweaked.value.first + } + + val outputKey = internalKey.outputKey(Crypto.TaprootTweak.KeyPathTweak).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) + } + + /** BIP32's `I_L` for one unhardened step: the scalar CKDpub adds, which a FROST cache takes as a plain tweak. */ + private fun childTweak(parent: DeterministicWallet.ExtendedPublicKey, index: Long): ByteVector32 = + ByteVector32( + Crypto.hmac512( + parent.chaincode.toByteArray(), + parent.publickeybytes.toByteArray() + Pack.writeInt32BE(index.toInt()) + ).copyOfRange(0, 32) + ) + + private fun plainTweak(cache: TweakCache, tweak: ByteVector32, step: String): TweakCache = + when (val tweaked = cache.tweak(tweak, isXonly = false)) { + is Either.Left -> throw IllegalArgumentException("Could not apply $step to the group's key", tweaked.value) + is Either.Right -> tweaked.value.first + } +} diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivationTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivationTest.kt new file mode 100644 index 00000000..759625d8 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupWalletDerivationTest.kt @@ -0,0 +1,168 @@ +package com.machankura.bennu.compose.managers + +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.DeterministicWallet +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.crypto.frost.TweakCache +import fr.acinq.secp256k1.Hex +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +/** + * The group wallet's derivation, pinned. + * + * Three kinds of assertion, and they guard different things. BIP86's own vectors + * prove the tail *is* BIP86. The pinned vector freezes the account step -- the + * tag, the byte order of the chain hash, the order of the HMAC's inputs -- so a + * change to any of them fails here rather than moving a group's coins. And the + * parity sweep exists because a parity mistake in a cache passes half the time. + */ +class GroupWalletDerivationTest { + /** A threshold key nobody needs the secret of: the test is about public derivation. */ + private fun thresholdKey(seed: Int): String = + PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() + + private val k = thresholdKey(0x1c0ffee) + + @Test + fun `the tail below an account key is BIP86's`() { + // m/86'/0'/0' of "abandon ... about", from BIP86 itself. + val (_, accountKey) = DeterministicWallet.ExtendedPublicKey.decode( + "xpub6BgBgsespWvERF3LHQu6CnqdvfEvtMcQjYrcRzx53QJjSxarj2afYWcLteoGVky7D3UKDP9QyrLprQ3VCECoY49yfdDEHGCtMMj92pReUsQ" + ) + val cache = TweakCache.create(accountKey.publicKey) + + val vectors = listOf( + Triple(0L to 0L, "cc8a4bc64d897bddc5fbc2f670f7a8ba0b386779106cf1223c6fc5d7cd6fc115", "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr"), + Triple(0L to 1L, "83dfe85a3151d2517290da461fe2815591ef69f2b18a2ce63f01697a8b313145", "bc1p4qhjn9zdvkux4e44uhx8tc55attvtyu358kutcqkudyccelu0was9fqzwh"), + Triple(1L to 0L, "399f1b2f4393f29a18c937859c5dd8a77350103157eb880f02e8c08214277cef", "bc1p3qkhfews2uk44qtvauqyr2ttdsw7svhkl9nkm9s9c3x4ax5h60wqwruhk7"), + ) + + vectors.forEach { (path, internalKey, address) -> + val derived = GroupWalletDerivation.deriveBelow(accountKey, cache, path.first, path.second) + assertEquals(internalKey, derived.internalKey.value.toHex(), "internal key at ${path.first}/${path.second}") + assertEquals(address, derived.address(Chain.Mainnet), "address at ${path.first}/${path.second}") + // Through the cache, not only the points: this is the key a session signs for. + assertEquals(derived.outputKey, derived.cache.tweakedPublicKey) + } + } + + @Test + fun `the account step is pinned`() { + val mainnet = GroupWalletDerivation.account(k, Chain.Mainnet) + val regtest = GroupWalletDerivation.account(k, Chain.Regtest) + val second = GroupWalletDerivation.account(k, Chain.Mainnet, account = 1) + + // Frozen. A failure here is not a test to update: it means every group's + // coins would be at different addresses after this change, and the ones + // already received would be found by nobody. + assertEquals( + "xpub661MyMwAqRbcEjmHgZBQ6WrHydBtiy96F6Lh8tj8vTzDYvMyQoqe1yLFytfUoqEkwRd9j8xqY1PZD25cnXn5LjMh5QLbywNqV3qse8Lxfdu", + mainnet.xpub + ) + assertEquals( + "tr([935b59f0]xpub661MyMwAqRbcEjmHgZBQ6WrHydBtiy96F6Lh8tj8vTzDYvMyQoqe1yLFytfUoqEkwRd9j8xqY1PZD25cnXn5LjMh5QLbywNqV3qse8Lxfdu/0/*)#mfhfa9w0", + mainnet.receiveDescriptor + ) + assertEquals( + "tr([935b59f0]xpub661MyMwAqRbcEjmHgZBQ6WrHydBtiy96F6Lh8tj8vTzDYvMyQoqe1yLFytfUoqEkwRd9j8xqY1PZD25cnXn5LjMh5QLbywNqV3qse8Lxfdu/1/*)#2ajgqs7h", + mainnet.changeDescriptor + ) + assertEquals( + "bc1p5v8nnu750wmu3sg5yee2kmj466d44dmr2cd0e0a4frwyqessayhqs442qs", + GroupWalletDerivation.derive(mainnet, 0, 0).address(Chain.Mainnet) + ) + + assertEquals( + "tpubD6NzVbkrYhZ4WoTbDgosM5KFsbzdUShJQHoMYsCSeSSTtniVCq92YbNb3vt2Ywg4njZ2JNeFtNbQStabeYpnXAUVzxYm9behJDvp5YhTvgE", + regtest.xpub + ) + assertEquals( + "bcrt1pkr33dle8ttv5p96se2dl0ujqxhkuxpw0cgapaa7g0578g5nctr9qwsyt55", + GroupWalletDerivation.derive(regtest, 0, 0).address(Chain.Regtest) + ) + + assertEquals( + "xpub661MyMwAqRbcF6PNpyzQvz1jPnpXZ785MJciQPZwyP2AhD9Gs6A2Acn9BnPHb2TUWku5CDARAwCpioDdPvrmjXWcAQbHWCXUZhW1VRyxDA2", + second.xpub + ) + assertEquals( + "bc1ptkqtyu8z5qm2l25p26nfr5ahugjw87vgc4yudevveysjkytw7caqtfjgrg", + GroupWalletDerivation.derive(second, 0, 0).address(Chain.Mainnet) + ) + } + + @Test + fun `both parities derive, at the account and below it`() { + val accountParities = mutableSetOf() + val childParities = mutableSetOf() + + (1..16).forEach { seed -> + val account = GroupWalletDerivation.account(thresholdKey(seed), Chain.Mainnet) + accountParities += account.extendedPublicKey.publicKey.isEven() + + (0L..3L).forEach { index -> + listOf(GroupWalletDerivation.RECEIVE, GroupWalletDerivation.CHANGE).forEach { change -> + // derive refuses to return if the cache and the points disagree, + // so reaching the end of this loop is the assertion. + val derived = GroupWalletDerivation.derive(account, change, index) + childParities += account.extendedPublicKey.derivePublicKey(change).derivePublicKey(index).publicKey.isEven() + assertEquals(derived.outputKey, derived.cache.tweakedPublicKey) + } + } + } + + assertEquals(setOf(true, false), accountParities, "the sweep has to cover both parities of the account key") + assertEquals(setOf(true, false), childParities, "the sweep has to cover both parities of a child key") + } + + @Test + fun `the wallet shares no key with the room or with itself`() { + val room = SharedKeyDerivation.derive(k).publicKey + val mainnet = GroupWalletDerivation.account(k, Chain.Mainnet) + val receive = GroupWalletDerivation.derive(mainnet, GroupWalletDerivation.RECEIVE, 0) + + assertNotEquals(room, receive.outputKey, "the room's key") + assertNotEquals(room, receive.internalKey, "the room's key, untweaked") + assertNotEquals( + mainnet.extendedPublicKey.publicKey.xOnly(), + fr.acinq.bitcoin.PublicKey.fromHex(k).xOnly(), + "the account key is not the threshold key, so the xpub does not reveal it" + ) + + val keys = listOf( + receive.outputKey, + GroupWalletDerivation.derive(mainnet, GroupWalletDerivation.CHANGE, 0).outputKey, + GroupWalletDerivation.derive(mainnet, GroupWalletDerivation.RECEIVE, 1).outputKey, + GroupWalletDerivation.derive(GroupWalletDerivation.account(k, Chain.Regtest), GroupWalletDerivation.RECEIVE, 0).outputKey, + GroupWalletDerivation.derive(GroupWalletDerivation.account(k, Chain.Mainnet, account = 1), GroupWalletDerivation.RECEIVE, 0).outputKey, + ) + assertEquals(keys.size, keys.toSet().size, "receive, change, index, network and account each give a different key") + } + + @Test + fun `hardened and out-of-range steps are refused`() { + val account = GroupWalletDerivation.account(k, Chain.Mainnet) + + assertFailsWith { GroupWalletDerivation.derive(account, 2, 0) } + assertFailsWith { GroupWalletDerivation.derive(account, 0, DeterministicWallet.hardened(0)) } + assertFailsWith { GroupWalletDerivation.derive(account, 0, -1) } + assertFailsWith { GroupWalletDerivation.account(k, Chain.Mainnet, DeterministicWallet.hardened(0)) } + } + + @Test + fun `descriptors carry the account's own fingerprint and a checksum`() { + val account = GroupWalletDerivation.account(k, Chain.Mainnet) + val pattern = Regex("""tr\(\[[0-9a-f]{8}]xpub[1-9A-HJ-NP-Za-km-z]+/[01]/\*\)#[qpzry9x8gf2tvdw0s3jn54khce6mua7l]{8}""") + + assertTrue(pattern.matches(account.receiveDescriptor), account.receiveDescriptor) + assertTrue(pattern.matches(account.changeDescriptor), account.changeDescriptor) + assertTrue(GroupWalletDerivation.account(k, Chain.Regtest).xpub.startsWith("tpub")) + } + + private fun ByteVector32.toHex(): String = toString() +} diff --git a/docs/group-chain-wallet.md b/docs/group-chain-wallet.md index d2260faf..570d9099 100644 --- a/docs/group-chain-wallet.md +++ b/docs/group-chain-wallet.md @@ -14,10 +14,16 @@ wallet makes more expensive to break, and with `k` inputs is a batch of `k` and that note's nonce rule is the one this plan is built around too. -**Not built.** Written against the code as it stood at `b75d4b42`, with the -`lightning-kmp-app` submodule at `e0d2b82`. Every path into the library below is -into that submodule, which a fresh worktree does not have checked out — run -`git submodule update --init --recursive` first. +**Being built**, one commit per phase. Written against the code as it stood at +`b75d4b42`, with the `lightning-kmp-app` submodule at `e0d2b82`. Every path into +the library below is into that submodule, which a fresh worktree does not have +checked out — run `git submodule update --init --recursive` first. The phases are +kept as written; where the build chose differently the table below says so. + +| what the plan said | what it turned out to be | +|---|---| +| one `tr([fp]xpub/<0;1>/*)` descriptor | two, `…/0/*` and `…/1/*`, as bitcoin-kmp's `BIP84Descriptors` does. Many watch-only importers, Bitcoin Core's `importdescriptors` among them, refuse a multipath descriptor | +| `derive(account, thresholdPublicKey, change, index)` | `derive(account, change, index)`: the `Account` carries the cache that signs as its key, so the threshold key is not asked for twice and cannot be passed in mismatched | The headline: **the best path is BIP86's own unhardened tail, `//`, hung under an account key the group's threshold key is tweaked to, with the