diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupIcebergTransport.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupIcebergTransport.kt index c1e6fdc2..c1eb1a70 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupIcebergTransport.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupIcebergTransport.kt @@ -19,6 +19,7 @@ import fr.acinq.bitcoin.utils.Either import fr.acinq.lightning.crypto.FundingSigner import fr.acinq.lightning.crypto.IcebergGroupTransport import fr.acinq.lightning.crypto.IcebergRoundTwoRequest +import fr.acinq.lightning.transactions.Transactions import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay @@ -172,6 +173,7 @@ class GroupIcebergTransport private constructor( contributions = request.contributions.map { it.toByteArray().toHex() }, cosignerAggregatedNonce = request.cosignerAggregatedNonce.data.toHex(), context = CoSigningWire.context(request.context), + extraUtxos = request.extraUtxos.map { (outPoint, txOut) -> CoSigningWire.input(Transactions.InputInfo(outPoint, txOut)) }, ) val content = CommonJson.encodeToString(CoSigningWire.SigningRequest.serializer(), wire) GroupLightningWalletManager.queue(database, localChatRoom, userPublicKey, GroupLightningEvents.SIGNING_REQUEST, content) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningCoSigner.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningCoSigner.kt index ff54f5e5..813201b8 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningCoSigner.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningCoSigner.kt @@ -174,6 +174,9 @@ object GroupLightningCoSigner { /** The provision request: a signing request whose kind is `PROVISION`, asking for contributions up to its counter. */ const val PROVISION = "PROVISION" + /** The context type of a splice's shared input. */ + const val SPLICE = "splice" + private suspend fun handleRequest(database: BennuDatabase, localChatRoom: LocalChatRoom, event: Event, userPublicKey: HexKey) { val request = CommonJson.decodeFromString(CoSigningWire.SigningRequest.serializer(), event.content) val roomId = localChatRoom.chatRoom.id @@ -202,7 +205,7 @@ object GroupLightningCoSigner { ) return } - val message = messageOf(request) + val message = messageOf(request) ?: return // Echo, and commit to this hash under this label for good. A label already answered under any // other message is never answered again. @@ -286,11 +289,19 @@ object GroupLightningCoSigner { .mapNotNull { runCatching { CommonJson.decodeFromString(CoSigningWire.SigningRequest.serializer(), it.content) }.getOrNull() } .firstOrNull { it.requestId == requestId } - /** The hash the request's transaction signs: recomputed, never read off the request. */ - fun messageOf(request: CoSigningWire.SigningRequest): ByteVector32 { + /** + * The hash the request's transaction signs: recomputed, never read off the request. It is the input + * spending [CoSigningWire.SigningRequest.input], over every output the transaction spends, which BIP341 + * commits the signature to. A request that misstates what the other inputs spend gets a signature + * nobody can mine, never one that moves money; one that omits them gets nothing, since there is no + * hash to compute. Null then. + */ + fun messageOf(request: CoSigningWire.SigningRequest): ByteVector32? { val tx = CoSigningWire.tx(request.tx) val input = CoSigningWire.inputInfo(request.input) - return tx.hashForSigningTaprootKeyPath(0, listOf(input.txOut), SigHash.SIGHASH_DEFAULT) + val index = tx.txIn.indexOfFirst { it.outPoint == input.outPoint }.takeIf { it >= 0 } ?: return null + val spent = CoSigningWire.spentOutputs(tx, input, request.extraUtxos) ?: return null + return tx.hashForSigningTaprootKeyPath(index, spent, SigHash.SIGHASH_DEFAULT) } /** @@ -312,10 +323,17 @@ object GroupLightningCoSigner { if (ByteVector(c)[0].toInt() != indexOf(wallet, participant)) return "a contribution carries another participant's index" } - // Check 3: the funding output is the group key with the counterparty's. + // Check 3: the funding output is the group key with the counterparty's. A commitment or a close + // spends it alone; a splice spends it once, beside the counterparty's own inputs. val tx = CoSigningWire.tx(request.tx) val input = CoSigningWire.inputInfo(request.input) - if (tx.txIn.size != 1 || tx.txIn[0].outPoint != input.outPoint) return "the transaction does not spend exactly the funding output" + val isSplice = request.context?.type == SPLICE + if (isSplice) { + if (tx.txIn.count { it.outPoint == input.outPoint } != 1) return "the splice does not spend the funding output once" + } else if (tx.txIn.size != 1 || tx.txIn[0].outPoint != input.outPoint) { + return "the transaction does not spend exactly the funding output" + } + if (messageOf(request) == null) return "the request does not say what every input of the transaction spends" val remoteKey = PublicKey.fromHex(request.remoteFundingPubKey) val groupKey = PublicKey.fromHex(statement.icebergKey) val expected = Transactions.makeFundingInputInfo(input.outPoint.txid, input.outPoint.index, input.txOut.amount, groupKey, remoteKey, Transactions.CommitmentFormat.SimpleTaprootChannels) @@ -340,6 +358,7 @@ object GroupLightningCoSigner { "remote" -> checkRemote(database, wallet, request, context, params, tx, pinned) "closing" -> checkClosing(statement, context, tx, closeTo) "local" -> checkLocal(database, wallet, request, context, params, tx, pinned) + SPLICE -> "a splice, which this device does not sign yet" else -> "an unknown kind of transaction" } } @@ -375,7 +394,7 @@ object GroupLightningCoSigner { remoteFundingPubKey = PublicKey.fromHex(request.remoteFundingPubKey), commitmentInput = CoSigningWire.inputInfo(request.input), commitmentFormat = Transactions.CommitmentFormat.SimpleTaprootChannels, - spec = CoSigningWire.spec(context.spec, params.channelId), + spec = CoSigningWire.spec(context.spec ?: return "no commitment spec", params.channelId), ) return if (rebuilt.tx != tx) "the commitment its context rebuilds to is not the one it asks to sign" else null } @@ -399,7 +418,7 @@ object GroupLightningCoSigner { val commitParams = CoSigningWire.commit(context.commit ?: return "no commitment parameters") val commitIndex = context.commitIndex ?: return "no commitment number" val perCommitmentPoint = PublicKey.fromHex(context.remotePerCommitmentPoint ?: return "no per-commitment point") - val spec = CoSigningWire.spec(context.spec, params.channelId) + val spec = CoSigningWire.spec(context.spec ?: return "no commitment spec", params.channelId) val keys = keyManagerOf(ByteVector(seed.seed), wallet.statement.chain).channelKeys(params.localParams.fundingKeyPath) .withGroupBasepoints(wallet.basepoints.forChannel) val (rebuilt, _) = Commitments.makeRemoteTxs( @@ -431,7 +450,7 @@ object GroupLightningCoSigner { val remote = ByteVector(context.remoteScript ?: return "no counterparty script") if (local != closeTo) return "the close does not pay the group's onchain wallet" if (tx.txOut.any { it.publicKeyScript != local && it.publicKeyScript != remote }) return "the close pays a script it did not name" - val ours = context.spec.toLocalMsat / 1000 + val ours = (context.spec ?: return "no commitment spec").toLocalMsat / 1000 val paid = tx.txOut.filter { it.publicKeyScript == local }.sumOf { it.amount.sat } val allowance = statement.policy.commitmentFeeAllowanceSat return if (ours > allowance && paid < ours - allowance) "the close pays the group $paid sats of its $ours" else null @@ -442,7 +461,7 @@ object GroupLightningCoSigner { val context = request.context ?: return if (context.type != "remote") return val params = CoSigningWire.params(context.params) - val spec = CoSigningWire.spec(context.spec, params.channelId) + val spec = CoSigningWire.spec(context.spec ?: return, params.channelId) val tx = CoSigningWire.tx(request.tx) val dao = database.icebergCoSigningDao() val channelId = params.channelId.toHex() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWire.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWire.kt index 194b565f..d5d3a1a9 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWire.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWire.kt @@ -28,6 +28,7 @@ import fr.acinq.lightning.transactions.IncomingHtlc import fr.acinq.lightning.transactions.OutgoingHtlc import fr.acinq.lightning.transactions.Transactions import fr.acinq.lightning.utils.msat +import fr.acinq.lightning.wire.LiquidityAds import fr.acinq.lightning.wire.OnionRoutingPacket import fr.acinq.lightning.wire.UpdateAddHtlc import fr.acinq.secp256k1.Hex @@ -76,7 +77,32 @@ object CoSigningWire { val nonInitiatorPaysCommitFees: Boolean, ) - /** One of the three things lightning-kmp says it is signing. [type] is `remote`, `local` or `closing`. */ + /** + * Liquidity bought with a splice, as lightning-kmp's `LiquidityAds.Purchase` says it: [amountSat] of + * inbound, for [miningFeeSat] (the LSP's inputs) and [serviceFeeSat], paid as [paymentType] names, a + * BOLT name such as `from_channel_balance`. [feeCreditUsedMsat] is set only when fee credit paid part of it. + */ + @Serializable + data class Purchase( + val amountSat: Long, + val miningFeeSat: Long, + val serviceFeeSat: Long, + val paymentType: String, + val feeCreditUsedMsat: Long? = null, + ) + + /** + * One of the four things lightning-kmp says it is signing. [type] is `remote`, `local`, `closing` or + * `splice`. A commitment names the funding output it is on by [fundingTxIndex]: while a splice is + * unconfirmed there is one per output, at the same commitment number. + * + * A splice is its shared input: the parent funding output [parentFunding], of [parentFundingTxIndex], + * spent by a transaction whose output [fundingOutputIndex] is the new funding output, of + * [fundingTxIndex], shared with the counterparty's [newRemoteFundingPubKey]; what each side added + * ([localContributionSat], [remoteContributionSat]), the [purchase] if it bought liquidity, and the + * feerate it was built at. A splice has no [spec]: the money in the new output is the first commitment + * on it, signed before this. + */ @Serializable data class Context( val type: String, @@ -84,9 +110,18 @@ object CoSigningWire { val commit: Commit? = null, val commitIndex: Long? = null, val remotePerCommitmentPoint: String? = null, - val spec: Spec, + val spec: Spec? = null, val localScript: String? = null, val remoteScript: String? = null, + val fundingTxIndex: Long = 0, + val parentFundingTxIndex: Long? = null, + val parentFunding: Input? = null, + val fundingOutputIndex: Int? = null, + val newRemoteFundingPubKey: String? = null, + val localContributionSat: Long? = null, + val remoteContributionSat: Long? = null, + val purchase: Purchase? = null, + val feeratePerKw: Long? = null, ) @Serializable @@ -109,6 +144,11 @@ object CoSigningWire { val contributions: List, val cosignerAggregatedNonce: String, val context: Context? = null, + /** + * What every other input of [tx] spends. A commitment or a close has one input, [input], and this + * is empty; a splice's shared input is one of several, and its signature commits to all of them. + */ + val extraUtxos: List = emptyList(), ) /** Kind 30359: a co-signer saw [messageHash] under [label], and will sign nothing else under it. */ @@ -195,11 +235,47 @@ object CoSigningWire { fun context(c: FundingSigner.SigningContext): Context? = when (c) { FundingSigner.SigningContext.Unknown -> null - is FundingSigner.SigningContext.RemoteCommitment -> Context("remote", params(c.channelParams), commit(c.commitParams), c.commitIndex, c.remotePerCommitmentPoint.toString(), spec(c.spec)) - is FundingSigner.SigningContext.LocalCommitment -> Context("local", params(c.channelParams), commit(c.commitParams), c.commitIndex, null, spec(c.spec)) + is FundingSigner.SigningContext.RemoteCommitment -> Context("remote", params(c.channelParams), commit(c.commitParams), c.commitIndex, c.remotePerCommitmentPoint.toString(), spec(c.spec), fundingTxIndex = c.fundingTxIndex) + is FundingSigner.SigningContext.LocalCommitment -> Context("local", params(c.channelParams), commit(c.commitParams), c.commitIndex, null, spec(c.spec), fundingTxIndex = c.fundingTxIndex) is FundingSigner.SigningContext.Closing -> Context("closing", params(c.channelParams), null, null, null, spec(c.spec), hex(c.localScript), hex(c.remoteScript)) - // Not on the wire yet, so a co-signer reads it as unsaid and refuses, as it refused every splice before. - is FundingSigner.SigningContext.Splice -> null + is FundingSigner.SigningContext.Splice -> Context( + type = "splice", + params = params(c.channelParams), + fundingTxIndex = c.fundingTxIndex, + parentFundingTxIndex = c.parentFundingTxIndex, + parentFunding = input(c.parentFunding), + fundingOutputIndex = c.fundingOutputIndex, + newRemoteFundingPubKey = c.remoteFundingPubKey.toString(), + localContributionSat = c.localContribution.sat, + remoteContributionSat = c.remoteContribution.sat, + purchase = c.purchase?.let(::purchase), + feeratePerKw = c.feerate.feerate.sat, + ) + } + + fun purchase(p: LiquidityAds.Purchase): Purchase = Purchase( + amountSat = p.amount.sat, + miningFeeSat = p.fees.miningFee.sat, + serviceFeeSat = p.fees.serviceFee.sat, + paymentType = paymentTypeName(p.paymentDetails.paymentType), + feeCreditUsedMsat = (p as? LiquidityAds.Purchase.WithFeeCredit)?.feeCreditUsed?.toLong(), + ) + + /** The BOLT name of a liquidity-ads payment type, which the wire carries: a co-signer reads only `from_channel_balance` as one it signs. */ + fun paymentTypeName(t: LiquidityAds.PaymentType): String = when (t) { + LiquidityAds.PaymentType.FromChannelBalance -> FROM_CHANNEL_BALANCE + LiquidityAds.PaymentType.FromFutureHtlc -> "from_future_htlc" + LiquidityAds.PaymentType.FromFutureHtlcWithPreimage -> "from_future_htlc_with_preimage" + LiquidityAds.PaymentType.FromChannelBalanceForFutureHtlc -> "from_channel_balance_for_future_htlc" + is LiquidityAds.PaymentType.Unknown -> "unknown_${t.bitIndex}" + } + + const val FROM_CHANNEL_BALANCE = "from_channel_balance" + + /** What every input of [tx] spends, [input] among them, in input order; null when one is not known. */ + fun spentOutputs(tx: Transaction, input: Transactions.InputInfo, extra: List): List? { + val known = extra.map(::inputInfo).associate { it.outPoint to it.txOut } + (input.outPoint to input.txOut) + return tx.txIn.map { known[it.outPoint] ?: return null } } fun input(info: Transactions.InputInfo): Input = Input(info.outPoint.txid.toString(), info.outPoint.index, info.txOut.amount.sat, hex(info.txOut.publicKeyScript)) diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWireJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWireJvmTest.kt new file mode 100644 index 00000000..eefad95e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSigningWireJvmTest.kt @@ -0,0 +1,155 @@ +package com.machankura.bennu.compose.wallet.lightning + +import com.machankura.bennu.compose.managers.GroupLightningCoSigner +import com.machankura.bennu.compose.network.serialization.CommonJson +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.bitcoin.byteVector32 +import fr.acinq.lightning.CltvExpiryDelta +import fr.acinq.lightning.Features +import fr.acinq.lightning.blockchain.fee.FeeratePerKw +import fr.acinq.lightning.channel.ChannelConfig +import fr.acinq.lightning.channel.ChannelFeatures +import fr.acinq.lightning.channel.ChannelFlags +import fr.acinq.lightning.channel.ChannelParams +import fr.acinq.lightning.channel.CommitParams +import fr.acinq.lightning.channel.LocalChannelParams +import fr.acinq.lightning.channel.RemoteChannelParams +import fr.acinq.lightning.crypto.FundingSigner +import fr.acinq.lightning.transactions.CommitmentSpec +import fr.acinq.lightning.transactions.Transactions +import fr.acinq.lightning.utils.msat +import fr.acinq.lightning.wire.LiquidityAds +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * The co-signing wire with a splice on it (`docs/group-lightning-liquidity.md`, Phase 3): every context + * survives the trip, a request from a build before it still reads, and the hash a co-signer recomputes + * for a splice's shared input is the one lightning-kmp signs. + */ +class CoSigningWireJvmTest { + private fun key() = PrivateKey(Random.nextBytes(32).byteVector32()) + private fun p2tr() = ByteVector(Script.write(Script.pay2tr(key().publicKey().xOnly(), fr.acinq.bitcoin.Crypto.TaprootTweak.KeyPathTweak))) + + private val params = ChannelParams( + channelId = Random.nextBytes(32).byteVector32(), + channelConfig = ChannelConfig.standard, + channelFeatures = ChannelFeatures(setOf()), + localParams = LocalChannelParams(key().publicKey(), fr.acinq.bitcoin.KeyPath("m/1/2"), isChannelOpener = false, paysCommitTxFees = false, defaultFinalScriptPubKey = ByteVector("0014" + "11".repeat(20)), features = Features.empty), + remoteParams = RemoteChannelParams(key().publicKey(), key().publicKey(), key().publicKey(), key().publicKey(), key().publicKey(), Features.empty), + channelFlags = ChannelFlags(announceChannel = false, nonInitiatorPaysCommitFees = false), + ) + private val commitParams = CommitParams(Satoshi(546), 1_000_000_000L, 1.msat, CltvExpiryDelta(144), 30) + private val spec = CommitmentSpec(setOf(), FeeratePerKw(Satoshi(2_500)), toLocal = 600_000_000.msat, toRemote = 400_000_000.msat) + + private val groupKey = key().publicKey() + private val oldLspKey = key().publicKey() + private val newLspKey = key().publicKey() + private val parent = Transactions.makeFundingInputInfo(TxId(Random.nextBytes(32).byteVector32()), 1, Satoshi(1_000_000), groupKey, oldLspKey, Transactions.CommitmentFormat.SimpleTaprootChannels) + private val lspInput = Transactions.InputInfo(OutPoint(TxId(Random.nextBytes(32).byteVector32()), 0), TxOut(Satoshi(300_000), p2tr())) + private val lspInput2 = Transactions.InputInfo(OutPoint(TxId(Random.nextBytes(32).byteVector32()), 3), TxOut(Satoshi(50_000), p2tr())) + + /** A liquidity purchase as the LSP would put it together: its two inputs around ours, its change, the new funding output. */ + private val newFunding = Transactions.makeFundingInputInfo(TxId(ByteArray(32)), 0, Satoshi(1_199_700), groupKey, newLspKey, Transactions.CommitmentFormat.SimpleTaprootChannels).txOut + private val spliceTx = Transaction( + version = 2, + txIn = listOf(TxIn(lspInput.outPoint, 0xfffffffdL), TxIn(parent.outPoint, 0xfffffffdL), TxIn(lspInput2.outPoint, 0xfffffffdL)), + txOut = listOf(TxOut(Satoshi(149_000), p2tr()), newFunding), + lockTime = 0, + ) + private val purchase = LiquidityAds.Purchase.Standard(Satoshi(200_000), LiquidityAds.Fees(Satoshi(200), Satoshi(2_100)), LiquidityAds.PaymentDetails.FromChannelBalance) + private val splice = FundingSigner.SigningContext.Splice( + channelParams = params, + parentFundingTxIndex = 0, + parentFunding = parent, + fundingTxIndex = 1, + fundingOutputIndex = 1, + remoteFundingPubKey = newLspKey, + localContribution = Satoshi(-300), + remoteContribution = Satoshi(200_000), + purchase = purchase, + feerate = FeeratePerKw(Satoshi(500)), + spentOutputs = mapOf(parent.outPoint to parent.txOut, lspInput.outPoint to lspInput.txOut, lspInput2.outPoint to lspInput2.txOut), + ) + + private fun request(context: FundingSigner.SigningContext, input: Transactions.InputInfo, tx: Transaction, extra: Map = emptyMap()) = CoSigningWire.SigningRequest( + wallet = "room:mainnet:0", term = 1, requestId = "r", kind = "PUBLISHED", label = "00".repeat(32), counter = 0, + tx = CoSigningWire.tx(tx), input = CoSigningWire.input(input), fundingTxId = input.outPoint.txid.toString(), remoteFundingPubKey = oldLspKey.toString(), + contributions = emptyList(), cosignerAggregatedNonce = "", context = CoSigningWire.context(context), + extraUtxos = extra.map { (o, t) -> CoSigningWire.input(Transactions.InputInfo(o, t)) }, + ) + + private fun roundTrip(r: CoSigningWire.SigningRequest) = + CommonJson.decodeFromString(CoSigningWire.SigningRequest.serializer(), CommonJson.encodeToString(CoSigningWire.SigningRequest.serializer(), r)) + + @Test + fun `every context survives the trip, and a commitment names its funding output`() { + val point = key().publicKey() + val remote = assertNotNull(roundTrip(request(FundingSigner.SigningContext.RemoteCommitment(params, commitParams, 7, point, spec, fundingTxIndex = 1), parent, spliceTx)).context) + assertEquals("remote", remote.type) + assertEquals(1, remote.fundingTxIndex) + assertEquals(7, remote.commitIndex) + assertEquals(spec, CoSigningWire.spec(assertNotNull(remote.spec), params.channelId)) + assertEquals(params, CoSigningWire.params(remote.params)) + + val local = assertNotNull(roundTrip(request(FundingSigner.SigningContext.LocalCommitment(params, commitParams, 7, spec, fundingTxIndex = 2), parent, spliceTx)).context) + assertEquals("local", local.type) + assertEquals(2, local.fundingTxIndex) + + val closing = assertNotNull(roundTrip(request(FundingSigner.SigningContext.Closing(params, ByteVector("51"), ByteVector("52"), spec), parent, spliceTx)).context) + assertEquals("closing", closing.type) + assertEquals("51", closing.localScript) + + val read = assertNotNull(roundTrip(request(splice, parent, spliceTx, splice.spentOutputs - parent.outPoint)).context) + assertEquals(GroupLightningCoSigner.SPLICE, read.type) + assertNull(read.spec, "a splice carries no commitment") + assertEquals(0, read.parentFundingTxIndex) + assertEquals(1, read.fundingTxIndex) + assertEquals(parent, CoSigningWire.inputInfo(assertNotNull(read.parentFunding))) + assertEquals(1, read.fundingOutputIndex) + assertEquals(newLspKey.toString(), read.newRemoteFundingPubKey) + assertEquals(-300, read.localContributionSat) + assertEquals(200_000, read.remoteContributionSat) + assertEquals(500, read.feeratePerKw) + assertEquals(CoSigningWire.Purchase(200_000, 200, 2_100, CoSigningWire.FROM_CHANNEL_BALANCE), read.purchase) + } + + @Test + fun `fee credit and other payment types are named, so a co-signer can refuse them`() { + val withCredit = LiquidityAds.Purchase.WithFeeCredit(Satoshi(200_000), LiquidityAds.Fees(Satoshi(200), Satoshi(2_100)), 1_500_000.msat, LiquidityAds.PaymentDetails.FromFutureHtlc(listOf(Random.nextBytes(32).byteVector32()))) + assertEquals(CoSigningWire.Purchase(200_000, 200, 2_100, "from_future_htlc", feeCreditUsedMsat = 1_500_000), CoSigningWire.purchase(withCredit)) + } + + @Test + fun `a request from a build before splices still reads, as a commitment on the first funding output`() { + val old = request(FundingSigner.SigningContext.RemoteCommitment(params, commitParams, 3, key().publicKey(), spec), parent, spliceTx) + val json = CommonJson.encodeToString(CoSigningWire.SigningRequest.serializer(), old) + .replace(",\"fundingTxIndex\":0", "").replace(",\"extraUtxos\":[]", "") + val read = CommonJson.decodeFromString(CoSigningWire.SigningRequest.serializer(), json) + assertEquals(0, read.context!!.fundingTxIndex) + assertEquals(emptyList(), read.extraUtxos) + } + + @Test + fun `the hash a co-signer recomputes for a splice's shared input is the one lightning-kmp signs`() { + val extra = splice.spentOutputs - parent.outPoint + val expected = Transactions.SpliceTx(parent, spliceTx).taprootSighash(extra) + assertEquals(expected, GroupLightningCoSigner.messageOf(request(splice, parent, spliceTx, extra)), "the shared input is input 1 of 3, over all three spent outputs") + // Without what the other inputs spend there is no hash, and so nothing to sign. + assertNull(GroupLightningCoSigner.messageOf(request(splice, parent, spliceTx, extra - lspInput2.outPoint))) + // A commitment is unchanged: one input, no extras. + val commitTx = Transaction(2, listOf(TxIn(parent.outPoint, 0)), listOf(TxOut(Satoshi(999_000), p2tr())), 0) + assertEquals(commitTx.hashForSigningTaprootKeyPath(0, listOf(parent.txOut), fr.acinq.bitcoin.SigHash.SIGHASH_DEFAULT), GroupLightningCoSigner.messageOf(request(splice, parent, commitTx))) + } +} diff --git a/docs/group-lightning-liquidity.md b/docs/group-lightning-liquidity.md index 2349cee7..7dcfa0b3 100644 --- a/docs/group-lightning-liquidity.md +++ b/docs/group-lightning-liquidity.md @@ -31,12 +31,15 @@ differently, this table says so. | 0 | steps 1, 3 and 4 run on regtest (`LiquidityPurchaseRegtestJvmTest`), after Phase 1, which the key check needs; see *What Phase 0 found*. Step 2 and the mainnet half of step 1 are not run: they need a node on mainnet and a purchase with real money, which is the owner's to make | | 1 | done, in the fork: the guard is gone, and `IcebergSpliceTestsCommon` splices a group's channel eight ways. The fork's JVM suite passes but for its Electrum tests, which reach public servers and time out differently on every run | | 2 | done, in the fork: `SigningContext.Splice`, and every commitment's context names its funding index. The regtest run checks the context a real purchase fills | +| 3 | done: the `splice` context and every spent output on the wire, the sighash over all of them, check 3 for a splice. A co-signer still refuses every splice, now by name (*a splice, which this device does not sign yet*), until Phase 5. `CoSigningWireJvmTest`, four tests | | what the plan said | what it turned out to be | |---|---| | Phase 0 before Phase 1 | after: the key check needs a node that names one key at every index, and Phase 1 is what makes `fundingPublicKey(1)` return index 0's key for an injected signer. The stock node in the test injects a private-key signer of its own index-0 key | | Phase 0 waits for the co-signer core release | it did not need to: none of Phase 0 touches the co-signer. Phases 3 and 5 do, and are built on the co-signer as it stands; the release's rewrite will have to be merged over them | | Phase 2 adds a context for the splice and nothing else | also `fundingTxIndex` on `RemoteCommitment` and `LocalCommitment`, defaulted to 0. A co-signer cannot otherwise tell the two commitments of one update apart but by their input, and the plan's ledger per funding output needs to know which is the newer | +| a splice's context carries a `spec` like the others | none: `CoSigningWire.Context.spec` is optional now, and every check that reads it refuses a context without one. A splice's money is in the first commitment on the new output, signed just before it | +| Phase 3: `messageOf` over all of the spent outputs | as written, and it returns null when the request leaves one out, which check 3 refuses before any echo: there is no hash to commit to | | S4: the new funding amount is at least the old one plus the amount less `purchase.fees.miningFee` | less **our own share of the splice's mining fee**, which is the splice's negative local contribution. `purchase.fees.miningFee` is the LSP's inputs' share, which the group pays from its balance with the service fee, in the first commitment on the new output. Phoenix's estimate (`ChannelManagementFees.miningFee`) is the two shares together, so `estimate.total = -localContribution + purchase.fees.total`, and the authorisation's cap covers both | ### What Phase 0 found