From ee40309e77fa6f8161a680d717501d0bdba5bbf2 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 16:51:49 +0200 Subject: [PATCH] feat(lightning): a closing channel pays the group, not the node (Phase 3) The fork's channel keys can take a group's payment and delayed-payment basepoints, the node skips the claims it holds no key for, and GroupHeldOutputs says where those outputs are and how to spend them. In the app, GroupLightningDerivation derives the basepoints from the group's threshold key, and a FROST quorum spends both kinds of output. Co-Authored-By: Claude Opus 5.5 --- .../managers/GroupLightningDerivation.kt | 103 ++++++++++++ .../managers/GroupLightningDerivationTest.kt | 147 ++++++++++++++++++ docs/group-lightning-wallet.md | 6 + lightning-kmp-app | 2 +- 4 files changed, 257 insertions(+), 1 deletion(-) create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningDerivation.kt create mode 100644 composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningDerivationTest.kt diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningDerivation.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningDerivation.kt new file mode 100644 index 00000000..2d6db5c5 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningDerivation.kt @@ -0,0 +1,103 @@ +package com.machankura.bennu.compose.managers + +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.nip01Core.core.hexToByteArray +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.DeterministicWallet +import fr.acinq.bitcoin.KeyPath +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.crypto.Pack +import fr.acinq.bitcoin.crypto.frost.TweakCache +import fr.acinq.bitcoin.utils.Either +import fr.acinq.lightning.crypto.GroupBasepoints + +/** + * The two commitment basepoints a group's Lightning wallet holds instead of its operator's node, derived + * from the group's ChillDKG threshold key -- the same key its on-chain wallet is. + * + * ``` + * I = HMAC-SHA512("bennu/group-lightning/basepoints/v1", serP(K) || chainHash || ser32(wallet)) + * K_b = K + I[0:32]·G, chain code I[32:64] + * payment basepoint = CKDpub((K_b, c_b), 0) + * delayed basepoint = CKDpub((K_b, c_b), 1) + * ``` + * + * Why these keys, and not the node's: whoever holds the node seed can make the LSP force-close, and in + * a stock channel the output that pays us after a force close is keyed from that seed. With these + * basepoints it is keyed from the group's key, so only a FROST quorum moves it. See constraint 7 in + * `docs/group-lightning-wallet.md`. + * + * The shape is [GroupWalletDerivation]'s account step with its own tag, so it is a different key that + * every member recomputes from what they already hold. It is not an account of the on-chain wallet: + * these keys sign tapscript leaves, never a key path, so a descriptor that found them would only + * mislead a watch-only wallet. + * + * ### Signing as them + * + * Both are script-path keys, used x-only inside a leaf. `to_remote`'s leaf key is the payment basepoint + * itself; `to_local`'s and an HTLC transaction's is the delayed basepoint plus + * `SHA256(per_commitment_point || basepoint)·G`. Each is a FROST session over [leafCache] with no + * TapTweak, because nothing commits a script tree to these keys -- they are the leaf. + */ +object GroupLightningDerivation { + /** Frozen once a channel exists under it, for the reason [GroupWalletDerivation]'s account tag is. */ + private const val TAG = "bennu/group-lightning/basepoints/v1" + + const val PAYMENT: Long = 0L + const val DELAYED_PAYMENT: Long = 1L + + private const val MAX_INDEX: Long = 0x7FFFFFFFL + + /** One basepoint: the full point lightning-kmp puts in `open_channel`, and the cache that signs as it. */ + class Basepoint internal constructor(val which: Long, val publicKey: PublicKey, val cache: TweakCache) + + class Basepoints internal constructor(val chain: Chain, val wallet: Long, val payment: Basepoint, val delayedPayment: Basepoint) { + /** What a group node's channel keys take: [fr.acinq.lightning.crypto.ChannelKeys.withGroupBasepoints]. */ + val forChannel: GroupBasepoints get() = GroupBasepoints(payment.publicKey, delayedPayment.publicKey) + } + + /** + * @param wallet the Lightning wallet's number in the room, as its statement's `wallet` tag says; a + * re-keyed wallet is the next number, and gets unrelated basepoints. + */ + fun basepoints(thresholdPublicKey: HexKey, chain: Chain, wallet: Long): Basepoints { + require(wallet in 0L..MAX_INDEX) { "wallet $wallet 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(TAG.encodeToByteArray(), root.value.toByteArray() + chain.chainHash.value.toByteArray() + Pack.writeInt32BE(wallet.toInt())) + val tweak = ByteVector32(i.copyOfRange(0, 32)) + require(Crypto.isPrivKeyValid(tweak.toByteArray())) { "the basepoint step for wallet $wallet landed on an invalid scalar" } + val stepKey = root + PrivateKey(tweak).publicKey() + val stepCache = plainTweak(TweakCache.create(root), tweak, "the basepoint step") + require(stepCache.tweakedPublicKey == stepKey.xOnly()) { "the basepoint cache does not reach the step key" } + val step = DeterministicWallet.ExtendedPublicKey(publickeybytes = stepKey.value, chaincode = ByteVector32(i.copyOfRange(32, 64)), depth = 0, path = KeyPath.empty, parent = 0L) + + fun child(which: Long): Basepoint { + val key = step.derivePublicKey(which).publicKey + val childTweak = ByteVector32(Crypto.hmac512(step.chaincode.toByteArray(), step.publickeybytes.toByteArray() + Pack.writeInt32BE(which.toInt())).copyOfRange(0, 32)) + val cache = plainTweak(stepCache, childTweak, "basepoint $which") + require(cache.tweakedPublicKey == key.xOnly()) { "the cache does not reach basepoint $which" } + return Basepoint(which, key, cache) + } + return Basepoints(chain, wallet, child(PAYMENT), child(DELAYED_PAYMENT)) + } + + /** + * The cache a FROST session signs a leaf with: [basepoint] itself when [perCommitmentTweak] is null + * (`to_remote`), or the basepoint plus that tweak (`to_local`, an HTLC transaction's output) -- + * lightning-kmp's `GroupHeldOutputs.Output.tweak`. + */ + fun leafCache(basepoint: Basepoint, perCommitmentTweak: ByteVector32?): TweakCache = + if (perCommitmentTweak == null) basepoint.cache else plainTweak(basepoint.cache, perCommitmentTweak, "the per-commitment tweak") + + 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/GroupLightningDerivationTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningDerivationTest.kt new file mode 100644 index 00000000..fbda3a95 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningDerivationTest.kt @@ -0,0 +1,147 @@ +package com.machankura.bennu.compose.managers + +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.PublicKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.ScriptTree +import fr.acinq.bitcoin.ScriptWitness +import fr.acinq.bitcoin.SigHash +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.bitcoin.XonlyPublicKey +import fr.acinq.bitcoin.byteVector32 +import fr.acinq.bitcoin.crypto.dkg.chill.ChillDKG +import fr.acinq.bitcoin.crypto.dkg.chill.ParticipantFinalizeResult +import fr.acinq.bitcoin.crypto.frost.IndividualNonce +import fr.acinq.bitcoin.crypto.frost.SecretNonce +import fr.acinq.bitcoin.crypto.frost.Session +import fr.acinq.bitcoin.crypto.frost.TweakCache +import fr.acinq.lightning.CltvExpiryDelta +import fr.acinq.lightning.crypto.ChannelKeys +import fr.acinq.lightning.crypto.CommitmentPublicKeys +import fr.acinq.lightning.transactions.Scripts +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFails +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue + +/** + * The Lightning wallet's basepoints, pinned, and spent by FROST the way a closing channel's outputs + * would be. + * + * The spends are built with lightning-kmp's own `Scripts.Taproot`, so a leaf this test signs is the leaf + * a real commitment carries; the judge is the script interpreter. Several per-commitment points are + * used because a parity mistake in a plain tweak passes half the time. + */ +class GroupLightningDerivationTest { + private val participants = 3 + private val threshold = 2 + + private val dkg: List = run { + val hostSecretKeys = (1..participants).map { PrivateKey(ByteVector32(ByteArray(32) { i -> (it * 5 + i).toByte() })) } + val hostPublicKeys = hostSecretKeys.map { ChillDKG.hostPublicKey(it) } + val step1 = hostSecretKeys.mapIndexed { i, key -> ChillDKG.participantStep1(key, hostPublicKeys, threshold, ByteVector32(ByteArray(32) { (i + 3).toByte() })) } + val coordinator1 = ChillDKG.coordinatorStep1(step1.map { it.message }, hostPublicKeys, threshold) + val step2 = hostSecretKeys.mapIndexed { i, key -> ChillDKG.participantStep2(key, step1[i].state, coordinator1.message, ByteVector32(ByteArray(32) { (i + 17).toByte() })) } + val certificate = ChillDKG.coordinatorFinalize(coordinator1.state, step2.map { it.certEqSignature }, threshold).certificate + (0 until participants).map { i -> ChillDKG.participantFinalize(step2[i].state, certificate, participants, threshold) } + .onEach { assertTrue(it.fault.isOk) } + } + private val k: PublicKey = dkg[0].thresholdPublicKey!! + private val basepoints = GroupLightningDerivation.basepoints(k.toString(), Chain.Regtest, wallet = 0) + + private fun key(seed: Int) = PrivateKey(ByteVector32(ByteArray(32) { (seed + it).toByte() })) + + /** A FROST signature by members 0 and 2, under [cache], over [message]. */ + private fun frost(message: ByteVector32, cache: TweakCache, seed: Int): ByteVector64 { + val signers = listOf(0, 2) + val nonces = signers.map { id -> + SecretNonce.generate(ByteVector32(ByteArray(32) { (seed * 16 + id).toByte() }), dkg[id].secretShare!!, dkg[0].publicShares[id], cache.tweakedPublicKey, message, null) + } + val session = Session.create(IndividualNonce.aggregate(nonces.map { it.second }).right!!, signers.map { it.toUInt() }, signers.map { dkg[0].publicShares[it] }, participants, threshold, cache, message) + val partials = signers.mapIndexed { i, id -> session.sign(nonces[i].first, dkg[id].secretShare!!, id.toUInt()).right!! } + return session.aggregateSigs(partials).right!! + } + + /** Spend a leaf of a NUMS-keyed output the way the group sweeps one. */ + private fun spendsUnderFrost(script: List, leaf: ScriptTree.Leaf, tree: ScriptTree, csv: Long, cache: TweakCache, seed: Int): Boolean { + val output = TxOut(Satoshi(50_000), script) + val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 7 })), 0), 0xffffffffL)), listOf(output), 0) + val unsigned = Transaction(2, listOf(TxIn(OutPoint(funding, 0), csv)), listOf(TxOut(Satoshi(49_000), Script.pay2wpkh(key(90).publicKey()))), 0) + val sighash = unsigned.hashForSigningTaprootScriptPath(0, listOf(output), SigHash.SIGHASH_DEFAULT, leaf.hash()) + val sig = frost(sighash, cache, seed) + val signed = unsigned.updateWitness(0, Script.witnessScriptPathPay2tr(Scripts.Taproot.NUMS_POINT.xOnly(), leaf, ScriptWitness(listOf(sig)), tree)) + return runCatching { Transaction.correctlySpends(signed, mapOf(OutPoint(funding, 0) to output), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) }.isSuccess + } + + private fun commitmentKeys(remotePayment: PublicKey = key(1).publicKey(), localDelayed: PublicKey = key(2).publicKey()) = + CommitmentPublicKeys(localDelayed, remotePayment, key(3).publicKey(), key(4).publicKey(), key(5).publicKey()) + + @Test + fun `a quorum spends to_remote under the payment basepoint`() { + val keys = commitmentKeys(remotePayment = basepoints.payment.publicKey) + val leaf = Scripts.Taproot.toRemoteScriptTree(keys) + assertTrue(spendsUnderFrost(Scripts.Taproot.toRemote(keys), leaf, leaf, 1, GroupLightningDerivation.leafCache(basepoints.payment, null), seed = 1)) + } + + @Test + fun `a quorum spends to_local under the delayed basepoint plus each commitment's tweak`() { + val delay = CltvExpiryDelta(144) + for (n in 0 until 8) { + val pcp = key(40 + n).publicKey() + val leafKey = ChannelKeys.remotePerCommitmentPublicKey(basepoints.delayedPayment.publicKey, pcp) + val tweak = Crypto.sha256(pcp.value + basepoints.delayedPayment.publicKey.value).byteVector32() + val keys = commitmentKeys(localDelayed = leafKey) + val tree = Scripts.Taproot.toLocalScriptTree(keys, delay) + val cache = GroupLightningDerivation.leafCache(basepoints.delayedPayment, tweak) + assertEquals(leafKey.xOnly(), cache.tweakedPublicKey, "commitment $n") + assertTrue(spendsUnderFrost(Scripts.Taproot.toLocal(keys, delay), tree.localDelayed, tree.scriptTree, delay.toLong(), cache, seed = 10 + n), "commitment $n") + // The untweaked basepoint is not the leaf key. + assertTrue(!spendsUnderFrost(Scripts.Taproot.toLocal(keys, delay), tree.localDelayed, tree.scriptTree, delay.toLong(), basepoints.delayedPayment.cache, seed = 30 + n)) + } + } + + @Test + fun `the derivation is pinned`() { + // A fixed K, so the tag, the byte order of the chain hash and the order of the HMAC's inputs are + // frozen here. Changing any of them moves every group's basepoints: a protocol fork. + val fixed = PrivateKey(ByteVector32(ByteArray(32) { 0x2a })).publicKey().toString() + val regtest = GroupLightningDerivation.basepoints(fixed, Chain.Regtest, 0) + val mainnet = GroupLightningDerivation.basepoints(fixed, Chain.Mainnet, 0) + val next = GroupLightningDerivation.basepoints(fixed, Chain.Regtest, 1) + assertEquals("020c73decf91066ea570ede057f2ef4521914a4902ceb12c124a54132f8c0cc319", regtest.payment.publicKey.toString()) + assertEquals("02c7d1b23df4878458422d042342d16b157f7628381e9977efc85d1be6d470eb14", regtest.delayedPayment.publicKey.toString()) + assertEquals("03fc539a36e31dc5940a34e06be922aeb65dd8b6a72bc414d34c8d0f88c44ca5e4", mainnet.payment.publicKey.toString()) + assertEquals("03c5901c78139d459aef3ed252431090c3d12a4e14b0f094c89284a8d4d58931d4", mainnet.delayedPayment.publicKey.toString()) + assertEquals("0309dac3e80cd059749ff10add118a4d85cb90688021f54be3be55de782c4391c6", next.payment.publicKey.toString()) + assertEquals("02b8fe5fe20854fb244ae7f95b0827a9d9c2a3b974cef24c8e0d92a72cd3f66dfe", next.delayedPayment.publicKey.toString()) + } + + @Test + fun `the basepoints are unrelated to every other key the group holds`() { + val wallet = GroupWalletDerivation.account(k.toString(), Chain.Regtest) + val others = setOf( + k.xOnly(), + SharedKeyDerivation.derive(k.toString()).publicKey, + wallet.extendedPublicKey.publicKey.xOnly(), + GroupWalletDerivation.derive(wallet, GroupWalletDerivation.RECEIVE, 0).internalKey, + GroupWalletDerivation.derive(wallet, GroupWalletDerivation.CHANGE, 0).internalKey, + ) + assertTrue(basepoints.payment.publicKey.xOnly() !in others) + assertTrue(basepoints.delayedPayment.publicKey.xOnly() !in others) + assertNotEquals(basepoints.payment.publicKey, basepoints.delayedPayment.publicKey) + assertNotEquals(basepoints.payment.publicKey, GroupLightningDerivation.basepoints(k.toString(), Chain.Mainnet, 0).payment.publicKey) + assertNotEquals(basepoints.payment.publicKey, GroupLightningDerivation.basepoints(k.toString(), Chain.Regtest, 1).payment.publicKey) + assertFails { GroupLightningDerivation.basepoints(k.toString(), Chain.Regtest, 0x80000000L) } + } +} diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md index e708a898..a42007dc 100644 --- a/docs/group-lightning-wallet.md +++ b/docs/group-lightning-wallet.md @@ -32,6 +32,7 @@ build chose differently, this table says so. | 0 | done, except the two spikes (see below) | | 1 | done: `IcebergDkg`, 11 tests, among them a byte-for-byte match against the library's dealer and a signature from every 2-of-4 and 3-of-7 quorum | | 2 | done, in the fork (`4bc973df`): the three signing methods suspend, `RemoteIcebergFundingSigner`, pings answered outside the channel loop. lightning-kmp's JVM suite, 985 tests, passes | +| 3 | done: in the fork (`e15e31ba`), `withGroupBasepoints`, `GroupHeldOutputs` and `KeyManager.defaultFinalScriptPubKey`, 991 tests passing. In the app, `GroupLightningDerivation`, pinned, with a FROST quorum spending `to_remote` and `to_local` | | what the plan said | what it turned out to be | |---|---| @@ -42,6 +43,11 @@ build chose differently, this table says so. | `Peer` answers `Ping` in its own coroutine | in `Peer.send`, before the command is queued, whenever the ping arrives on the adopted connection. The receive loop goes through `send` too. A ping that arrives before the connection is adopted falls through to the old handler | | a channel that times out disconnects | the signer returns `IcebergSigningTimeout` and the channel treats it as any failed signature. Disconnecting is the operator node's response (Phase 8), not lightning-kmp's | | a test drops one answer in ten | a test with a group that never answers, and checks the retry gets a new label. The channel suite runs with random delays, and asserts after every test that no label was asked to sign two messages | +| lightning-kmp emits a `ChannelAction` naming each group-held output | it emits nothing. It skips the four claims it would have signed, and `GroupHeldOutputs.inLocalCommit`, `inRemoteCommit` and `inHtlcTx` find the output in a published transaction instead, with the leaf, the key, the per-commitment tweak and the delay. The operator's node calls them when a channel enters `Closing`. A new action would have reached every state that handles closing, and the Peer, for a fact the published transaction already carries | +| our anchor CPFP is turned off for group channels | there is nothing to turn off: lightning-kmp's taproot channels publish no anchor spend (`anchorOutput = null` throughout `Helpers.Closing`) | +| the closing script comes from a provider the app supplies | `KeyManager.defaultFinalScriptPubKey`, defaulting to `finalOnChainWallet`'s first address. It is fixed in a channel's parameters when the channel opens, as it always was. A close to a different onchain wallet address goes through `Shutdown`'s script override | +| one channel per group node, because two would share a `shaSeed` | not needed. Channel keys derive from a random funding key *path* per channel, not from the funding key, so two channels have different per-commitment secrets even with the same group funding key. Only `RecoveredChannelKeys`, which a group node never uses, keys off the funding key | +| `HtlcDelayedTx` is node-keyed | it is keyed from the delayed basepoint, so it pays the group too. What stays node-keyed is the HTLC transaction itself and the claims from the counterparty's commitment, which is the in-flight exposure the statement caps | | the kinds are reserved | in code: `GroupLightningEvents`, 30333-30349, with a test asserting the run is unbroken and touches no kind the app already dispatches on | | library phases land in the forks' `threshold` branches | on a new branch, `claude/group-lightning-wallet`, in `lightning-kmp-app` and in `experimental/lightning-kmp`. It is local and not pushed. The app's submodule pointer follows it, so a checkout of this branch needs those commits from the same machine until they are pushed | diff --git a/lightning-kmp-app b/lightning-kmp-app index 0ed1e416..38e58157 160000 --- a/lightning-kmp-app +++ b/lightning-kmp-app @@ -1 +1 @@ -Subproject commit 0ed1e416a8863586676628e7f831a4fb2bde4d3f +Subproject commit 38e5815771d0d1114a277b2e85e440abf3af42b5