From be90715dd3eea03dee17d791fb3b0a444dda1cb9 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sun, 1 Nov 2026 12:33:50 +0200 Subject: [PATCH] feat(lightning): the operator's node buys the liquidity the group authorised (liquidity, Phase 6) GroupLightningNode.buyAuthorised runs with the node's other actions, on the watch of kind 30363: for each open buy-liquidity it has not taken on, it finds the LSP's rate for the amount, estimates at the node's own feerate, and splices only if the estimate is within the authorisation's cap, buying at the feerate the estimate raised to, as Phoenix does. Once per authorisation; not while the channel has a splice that has not locked, which eclair would refuse; a failure is reported and not retried. The snapshot now carries the LSP's rates and the node's feerate, for a member to price a purchase from, each purchase's state (waiting, pending, locked, failed with its reason), how many funding outputs each channel has live, and the purchase as a `liquidity` payment. Co-Authored-By: Claude Opus 5.5 --- .../compose/managers/GroupLightningNode.kt | 83 ++++++++++- .../compose/wallet/lightning/WalletWire.kt | 45 ++++++ .../bennu/compose/managers/FakeGroupNode.kt | 13 ++ .../GroupLightningLiquidityJvmTest.kt | 130 +++++++++++++++++- docs/group-lightning-liquidity.md | 4 + 5 files changed, 273 insertions(+), 2 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt index 84b4d1be..028dcc6e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt @@ -31,6 +31,9 @@ import fr.acinq.lightning.blockchain.fee.FeeratePerByte import fr.acinq.lightning.blockchain.fee.FeeratePerKw import fr.acinq.lightning.blockchain.fee.OnChainFeerates import fr.acinq.lightning.channel.ChannelCommand +import kotlinx.coroutines.flow.update +import com.machankura.bennu.compose.wallet.lightning.CoSigningWire +import fr.acinq.lightning.channel.ChannelFundingResponse import fr.acinq.lightning.channel.GroupHeldOutputs import fr.acinq.lightning.channel.states.ChannelStateWithCommitments import fr.acinq.lightning.channel.states.Closed @@ -142,6 +145,15 @@ class GroupLightningNode( fun heldOutputs(): List /** The node's reusable Bolt12 offer, through the LSP: every member recomputes it from the seed. */ fun offer(): String? + /** The LSP's liquidity rates, as its `init` sent them, or null before it has. */ + fun fundingRates(): WalletWire.FundingRates? + /** The feerate the node would splice at, in sat/vbyte, or null while it has none. */ + fun feeratePerByte(): Long? + /** + * Buys [amountSat] of inbound liquidity for [channelId] from the LSP, by splicing, if its estimate is + * at most [maxFeeSat], and says what came of it, under the authorisation [id]. + */ + suspend fun buyLiquidity(id: String, channelId: String, amountSat: Long, maxFeeSat: Long): WalletWire.LiquidityPurchase } sealed class State { @@ -161,6 +173,9 @@ class GroupLightningNode( /** Held while the node acts on what the room asked of it, so no two callers act on one request at once. */ private val acting = Mutex() private var lastReported: Triple, List, List>? = null + private var lastPurchases: List = emptyList() + /** What came of each liquidity purchase this node took on, by authorisation id. */ + private val purchases = MutableStateFlow>(emptyMap()) private var lastReportedAt: kotlin.time.Instant? = null /** Starts the node if this device may run it now; otherwise says why not. */ @@ -239,7 +254,8 @@ class GroupLightningNode( val handle = peer ?: return val now = now() val current = Triple(handle.channels(), handle.payments(), handle.heldOutputs()) - val due = force || current != lastReported || lastReportedAt.let { it == null || now - it >= reportEvery } + val bought = purchasesFor(current.first) + val due = force || current != lastReported || bought != lastPurchases || lastReportedAt.let { it == null || now - it >= reportEvery } if (!due) return val snapshot = WalletWire.Snapshot( wallet = walletKey, term = term, nodeId = wallet.statement.nodeId, sentAt = now.epochSeconds, @@ -247,9 +263,13 @@ class GroupLightningNode( assignments = transport?.assignments().orEmpty(), heldOutputs = current.third, offer = handle.offer(), + fundingRates = handle.fundingRates(), + feeratePerByte = handle.feeratePerByte(), + purchases = bought, ) GroupLightningReports.publishSnapshot(database, localChatRoom, userPublicKey, snapshot) lastReported = current + lastPurchases = bought lastReportedAt = now } @@ -282,6 +302,39 @@ class GroupLightningNode( } } + /** Every purchase this node took on, a pending one read as locked once its channel is on that output alone. */ + private fun purchasesFor(channels: List): List = purchases.value.values.map { p -> + val channel = channels.firstOrNull { it.channelId == p.channelId } + if (p.state == WalletWire.PENDING && channel != null && channel.fundingTxId == p.fundingTxId && channel.liveFundingOutputs == 1) p.copy(state = WalletWire.LOCKED) else p + }.sortedBy { it.id } + + /** + * Buys the inbound liquidity the group has authorised, once per authorisation + * (`docs/group-lightning-liquidity.md`, Phase 6). Not while the channel has a splice that has not + * locked: eclair refuses another until it does, so the purchase waits, and is tried at the next check + * after. A purchase that fails is not tried again by itself; the group signs a new one for another + * attempt, and every co-signer holds the fee to the cap whichever it is. + */ + internal suspend fun buyAuthorised() = acting.withLock { + val handle = peer ?: return@withLock + val channels = handle.channels().associateBy { it.channelId } + GroupLightningAuthorisations.liquidityPurchases(database, wallet, now()).forEach { buy -> + if (purchases.value[buy.id]?.state.let { it != null && it != WalletWire.WAITING }) return@forEach + val channel = channels[buy.channelId] ?: return@forEach + if (channel.liveFundingOutputs > 1) { + purchases.update { it + (buy.id to WalletWire.LiquidityPurchase(buy.id, buy.channelId, buy.amountSat, WalletWire.WAITING, fundingTxId = channel.fundingTxId)) } + return@forEach + } + purchases.update { it + (buy.id to WalletWire.LiquidityPurchase(buy.id, buy.channelId, buy.amountSat, WalletWire.PENDING)) } + scope.launch { + val outcome = runCatching { handle.buyLiquidity(buy.id, buy.channelId, buy.amountSat, buy.maxFeeSat) } + .getOrElse { WalletWire.LiquidityPurchase(buy.id, buy.channelId, buy.amountSat, WalletWire.FAILED, reason = it.message ?: it::class.simpleName) } + purchases.update { it + (buy.id to outcome) } + logger.i("Liquidity purchase ${buy.id}: ${outcome.state}${outcome.reason?.let { r -> ", $r" }.orEmpty()}") + } + } + } + private val closing = mutableSetOf() /** @@ -364,6 +417,7 @@ class GroupLightningNode( runCatching { answerInvoiceRequests() }.onFailure { logger.e("Could not answer an invoice request", it) } runCatching { payAuthorised() }.onFailure { logger.e("Could not make an authorised payment", it) } runCatching { closeAuthorised() }.onFailure { logger.e("Could not close an authorised channel", it) } + runCatching { buyAuthorised() }.onFailure { logger.e("Could not buy authorised liquidity", it) } } /** @@ -560,6 +614,7 @@ class GroupLightningNode( fundingTxId = latest.fundingTxId.toString(), fundingIndex = latest.fundingInput.index, commitIndex = latest.localCommit.index, + liveFundingOutputs = state.commitments.active.size, ) } }.sortedBy { it.channelId } @@ -594,6 +649,32 @@ class GroupLightningNode( } }.map(GroupSweep::inputOf).distinctBy { it.txid to it.index } override fun offer(): String = nodeParams.defaultOffer(walletParams.trampolineNode.id).offer.encode() + override fun fundingRates(): WalletWire.FundingRates? = peer.remoteFundingRates.value?.let { rates -> + WalletWire.FundingRates( + rates.fundingRates.map { WalletWire.FundingRate(it.minAmount.sat, it.maxAmount.sat, it.fundingWeight, it.feeProportional, it.feeBase.sat, it.channelCreationFee.sat) }, + rates.paymentTypes.map(CoSigningWire::paymentTypeName), + ) + } + override fun feeratePerByte(): Long? = peer.onChainFeeratesFlow.value?.fundingFeerate?.let { FeeratePerByte(it).feerate.sat } + override suspend fun buyLiquidity(id: String, channelId: String, amountSat: Long, maxFeeSat: Long): WalletWire.LiquidityPurchase { + fun failed(reason: String) = WalletWire.LiquidityPurchase(id, channelId, amountSat, WalletWire.FAILED, reason = reason) + val amount = Satoshi(amountSat) + val rate = peer.remoteFundingRates.value?.findRate(amount) ?: return failed("the LSP sells no liquidity in that amount") + val feerate = peer.onChainFeeratesFlow.value?.fundingFeerate ?: return failed("the node has no feerate yet") + // As Phoenix does: estimate, then buy at the feerate the estimate raised to, not the target. + val (actual, fees) = peer.estimateFeeForInboundLiquidity(amount, feerate, rate) ?: return failed("the channel is not ready") + if (fees.total.sat > maxFeeSat) return failed("it would cost ${fees.total.sat} sats, over the $maxFeeSat the group agreed to") + return when (val response = peer.requestInboundLiquidity(amount, actual, rate)) { + null -> failed("the channel is not ready") + is ChannelFundingResponse.Success -> WalletWire.LiquidityPurchase(id, channelId, amountSat, WalletWire.PENDING, response.fundingTxId.toString(), fees.total.sat).also { + payments += WalletWire.PaymentView( + id = "liquidity:${response.fundingTxId}", incoming = false, amountMsat = fees.total.sat * 1000, feesMsat = fees.total.sat * 1000, + completedAt = Clock.System.now().toEpochMilliseconds(), succeeded = true, kind = WalletWire.LIQUIDITY, liquiditySat = amountSat, + ) + } + is ChannelFundingResponse.Failure -> failed(response::class.simpleName ?: "the splice failed") + } + } override suspend fun forceClose(channelId: String) { peer.send(WrappedChannelCommand(ByteVector32(channelId), ChannelCommand.Close.ForceClose)) } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/WalletWire.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/WalletWire.kt index b7108502..4c6e7a83 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/WalletWire.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/WalletWire.kt @@ -18,6 +18,11 @@ object WalletWire { val fundingTxId: String, val fundingIndex: Long, val commitIndex: Long, + /** + * How many funding outputs carry commitments: 1, or 2 while a splice has not locked, when the LSP + * refuses another (`docs/group-lightning-liquidity.md`, Phase 6). + */ + val liveFundingOutputs: Int = 1, ) /** One payment the node made or received. [id] is lightning-kmp's own. */ @@ -31,8 +36,43 @@ object WalletWire { val description: String? = null, val completedAt: Long? = null, val succeeded: Boolean, + /** [PAYMENT], or [LIQUIDITY] for inbound bought: then [amountMsat] is its fee, as in Phoenix, and [liquiditySat] what it bought. */ + val kind: String = PAYMENT, + val liquiditySat: Long? = null, ) + const val PAYMENT = "payment" + const val LIQUIDITY = "liquidity" + + /** One of the LSP's liquidity-ads rates, as lightning-kmp's `LiquidityAds.FundingRate` has it. */ + @Serializable + data class FundingRate(val minAmountSat: Long, val maxAmountSat: Long, val fundingWeight: Int, val feeProportional: Int, val feeBaseSat: Long, val channelCreationFeeSat: Long) + + /** What the LSP sells, as its `init` said: [rates], paid by any of [paymentTypes] (BOLT names). */ + @Serializable + data class FundingRates(val rates: List, val paymentTypes: List) + + /** + * What came of one `buy-liquidity` authorisation, [id], on the operator's node: [WAITING] for an + * earlier splice of the channel to lock, [PENDING] with the splice's [fundingTxId] once the LSP signed + * it, [LOCKED] once the channel is on that output alone, or [FAILED] with [reason]. + */ + @Serializable + data class LiquidityPurchase( + val id: String, + val channelId: String, + val amountSat: Long, + val state: String, + val fundingTxId: String? = null, + val feeSat: Long? = null, + val reason: String? = null, + ) + + const val WAITING = "waiting" + const val PENDING = "pending" + const val LOCKED = "locked" + const val FAILED = "failed" + /** * Kind 30362: the operator's claim about the wallet, sent when something changes and every few * minutes while the node runs. [assignments] is the round-one pool's assignments, so an operator @@ -50,6 +90,11 @@ object WalletWire { val assignments: Map = emptyMap(), /** What closed channels left the group, for any member to sweep into the onchain wallet. */ val heldOutputs: List = emptyList(), + /** What the LSP sells, for a member to price a purchase from, and the feerate the node would buy at, in sat/vbyte: the operator's claim. */ + val fundingRates: FundingRates? = null, + val feeratePerByte: Long? = null, + /** What came of each liquidity purchase the group authorised. */ + val purchases: List = emptyList(), ) { val spendableMsat: Long get() = channels.sumOf { it.oursMsat } val inboundMsat: Long get() = channels.sumOf { it.theirsMsat } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/FakeGroupNode.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/FakeGroupNode.kt index 84ef573f..b43a5a2b 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/FakeGroupNode.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/FakeGroupNode.kt @@ -38,6 +38,12 @@ class FakeGroupNode(private val configuration: GroupLightningNode.NodeConfigurat val closed = mutableListOf>() val forceClosed = mutableListOf() var heldOutputs = listOf() + var rates: WalletWire.FundingRates? = null + var feerate: Long? = 2 + /** Every purchase asked of the node, as (authorisation id, amount, fee cap). */ + val bought = mutableListOf>() + /** What a purchase costs here, and so whether it is made: one over the cap is never sent. */ + var purchaseFee = 2_521L override suspend fun connect(attempt: Int): Boolean { connected = true; connects++; attempts += attempt; return true } override fun disconnect() { disconnected = true } @@ -55,6 +61,13 @@ class FakeGroupNode(private val configuration: GroupLightningNode.NodeConfigurat override fun heldOutputs(): List = heldOutputs override fun offer(): String = OfferManager.deterministicOffer(configuration.chain.chainHash, configuration.keyManager.nodeKeys.nodeKey.privateKey, configuration.lspNodeId, null, null, null).offer.encode() + override fun fundingRates(): WalletWire.FundingRates? = rates + override fun feeratePerByte(): Long? = feerate + override suspend fun buyLiquidity(id: String, channelId: String, amountSat: Long, maxFeeSat: Long): WalletWire.LiquidityPurchase { + if (purchaseFee > maxFeeSat) return WalletWire.LiquidityPurchase(id, channelId, amountSat, WalletWire.FAILED, reason = "it would cost $purchaseFee sats, over the $maxFeeSat the group agreed to") + bought += Triple(id, amountSat, maxFeeSat) + return WalletWire.LiquidityPurchase(id, channelId, amountSat, WalletWire.PENDING, fundingTxId = "cd".repeat(32), feeSat = purchaseFee) + } override suspend fun hasPaid(paymentHash: String): Boolean = payments.any { !it.incoming && it.paymentHash == paymentHash } override suspend fun pay(bolt11: String, amountMsat: Long): WalletWire.PaymentView { paid += bolt11 to amountMsat diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningLiquidityJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningLiquidityJvmTest.kt index e628c51c..0c727508 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningLiquidityJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningLiquidityJvmTest.kt @@ -1,13 +1,25 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.database.model.MarmotGroupEvent +import com.machankura.bennu.compose.database.model.NostrEvent +import com.machankura.bennu.compose.network.serialization.CommonJson import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent +import com.machankura.bennu.compose.nostr.lightning.GroupLightningEvents +import com.machankura.bennu.compose.wallet.lightning.WalletWire import com.machankura.bennu.compose.text.ProposedEvent import com.machankura.bennu.compose.wallet.GroupLightningRollout import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.toHexKey import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair import fr.acinq.bitcoin.Chain +import fr.acinq.lightning.Lightning.randomBytes32 +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout import kotlin.test.AfterTest import kotlin.test.Test import kotlin.test.assertEquals @@ -17,6 +29,8 @@ import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Duration.Companion.days +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds /** * The group deciding to buy inbound liquidity (`docs/group-lightning-liquidity.md`, Phase 4): a @@ -28,8 +42,46 @@ abstract class GroupLightningLiquidityCases(chain: Chain) { private val lsp = "02" + KeyPair().pubKey.toHexKey() private val channelId = "ab".repeat(32) + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val nodes = mutableListOf() + @AfterTest - fun close() = fixture.close() + fun close() { + scope.cancel() + fixture.close() + } + + /** The operator's node, on a stand-in peer holding one channel of [capacitySat], [live] funding outputs live. */ + private suspend fun runningNode(all: List, live: Int = 1): GroupLightningNode { + val operator = all[1] + val id = randomBytes32().toHex() + operator.db.nostrEventDao().upsert(NostrEvent(id = id, pubKey = operator.publicKey, kind = 445, tags = emptyArray(), content = "", sig = "0".repeat(128))) + operator.db.marmotGroupEventDao().upsert(MarmotGroupEvent(id = id, userPublicKey = operator.publicKey, publicKey = operator.publicKey, chatRoomId = fixture.roomId, signature = "", encryptedContent = "", expiresAt = null, savedAt = Clock.System.now())) + val node = GroupLightningNode( + operator.db, operator.room, operator.publicKey, GroupLightningWalletManager.walletFor(operator.db, fixture.roomId, fixture.chain)!!, scope, + { configuration -> FakeGroupNode(configuration).also { fake -> + fake.channels = listOf(WalletWire.ChannelView(channelId, "Normal", 25_000, 21_900_000, 3_100_000, "ab".repeat(32), 0, 3, liveFundingOutputs = live)) + fake.rates = WalletWire.FundingRates(listOf(WalletWire.FundingRate(10_000, 10_000_000, 400, 100, 100, 1_000)), listOf("from_channel_balance")) + nodes += fake + } }, + handoverCheck = 10.minutes, + minimumPool = 0, + ) + assertIs(node.start()) + return node + } + + private suspend fun authorise(all: List, wallet: GroupLightningWalletManager.Wallet, maxFeeSat: Long = 4_000): GroupLightningAuthorisationEvent.BuyLiquidity { + val buy = GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channelId, 25_000, 200_000, maxFeeSat).getOrThrow() + fixture.signSession(all, all[2], GroupLightningAuthorisations.proposeBuyLiquidity(all[2].db, all[2].room, all[2].publicKey, buy).id) + return buy + } + + private suspend fun reported(all: List, node: GroupLightningNode): WalletWire.Snapshot { + node.report(term = 1, force = true) + fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT)) + return GroupLightningReports.latest(all[3].db, GroupLightningCoSigner.walletKey(fixture.roomId, fixture.chain, 0))!!.snapshot + } private suspend fun opened(): Pair, GroupLightningWalletManager.Wallet> { val all = fixture.group() @@ -85,6 +137,82 @@ abstract class GroupLightningLiquidityCases(chain: Chain) { } } + @Test + fun `the operator's node buys what the group authorised, once, and every member hears how it went`() = runBlocking { + val (all, wallet) = opened() + val node = runningNode(all) + node.buyAuthorised() + assertTrue(nodes.single().bought.isEmpty(), "nothing is authorised") + val buy = authorise(all, wallet) + node.buyAuthorised() + withTimeout(5.seconds) { while (nodes.single().bought.isEmpty()) delay(20) } + node.buyAuthorised() + delay(200) + assertEquals(listOf(Triple(buy.id, 200_000L, 4_000L)), nodes.single().bought, "bought once, for the amount and cap the group signed") + + val snapshot = reported(all, node) + assertEquals(listOf(WalletWire.LiquidityPurchase(buy.id, channelId, 200_000, WalletWire.PENDING, "cd".repeat(32), 2_521)), snapshot.purchases) + assertEquals(nodes.single().rates, snapshot.fundingRates, "what the LSP sells, for a member to price from") + assertEquals(2L, snapshot.feeratePerByte) + // Once the channel is on the splice's output alone, the purchase reads as locked. + nodes.single().channels = nodes.single().channels.map { it.copy(fundingTxId = "cd".repeat(32), capacitySat = 224_779) } + assertEquals(WalletWire.LOCKED, reported(all, node).purchases.single().state) + node.stop() + } + + @Test + fun `a purchase that would cost more than the cap is never sent, and is not tried again`() = runBlocking { + val (all, wallet) = opened() + val node = runningNode(all) + nodes.single().purchaseFee = 9_000 + val buy = authorise(all, wallet) + node.buyAuthorised() + val failed = withTimeout(5.seconds) { + var p: WalletWire.LiquidityPurchase? = null + while (p?.state != WalletWire.FAILED) { p = reported(all, node).purchases.singleOrNull(); delay(20) } + p + } + assertEquals(buy.id, failed.id) + assertTrue("over the 4000 the group agreed to" in failed.reason!!, failed.reason) + nodes.single().purchaseFee = 2_521 + node.buyAuthorised() + delay(200) + assertTrue(nodes.single().bought.isEmpty(), "a failed purchase waits for the group to ask again") + node.stop() + } + + @Test + fun `while an earlier splice has not locked, the purchase waits, and is made once it has`() = runBlocking { + val (all, wallet) = opened() + val node = runningNode(all, live = 2) + val buy = authorise(all, wallet) + node.buyAuthorised() + delay(200) + assertTrue(nodes.single().bought.isEmpty()) + assertEquals(WalletWire.WAITING, reported(all, node).purchases.single().state) + nodes.single().channels = nodes.single().channels.map { it.copy(liveFundingOutputs = 1) } + node.buyAuthorised() + withTimeout(5.seconds) { while (nodes.single().bought.isEmpty()) delay(20) } + assertEquals(buy.id, nodes.single().bought.single().first) + node.stop() + } + + @Test + fun `a snapshot from a build before purchases still reads, and one with them round-trips`() { + val old = """{"wallet":"w","term":1,"nodeId":"n","sentAt":1,"channels":[{"channelId":"c","state":"Normal","capacitySat":1,"oursMsat":1,"theirsMsat":0,"fundingTxId":"f","fundingIndex":0,"commitIndex":0}],"payments":[{"id":"p","incoming":true,"amountMsat":1,"feesMsat":0,"succeeded":true}]}""" + val read = CommonJson.decodeFromString(WalletWire.Snapshot.serializer(), old) + assertEquals(1, read.channels.single().liveFundingOutputs) + assertEquals(WalletWire.PAYMENT, read.payments.single().kind) + assertTrue(read.purchases.isEmpty() && read.fundingRates == null) + val full = read.copy( + fundingRates = WalletWire.FundingRates(listOf(WalletWire.FundingRate(1, 2, 3, 4, 5, 6)), listOf("from_channel_balance")), + feeratePerByte = 3, + purchases = listOf(WalletWire.LiquidityPurchase("i", "c", 200_000, WalletWire.FAILED, reason = "r")), + payments = listOf(WalletWire.PaymentView("liquidity:t", false, 2_521_000, 2_521_000, succeeded = true, kind = WalletWire.LIQUIDITY, liquiditySat = 200_000)), + ) + assertEquals(full, CommonJson.decodeFromString(WalletWire.Snapshot.serializer(), CommonJson.encodeToString(WalletWire.Snapshot.serializer(), full))) + } + @Test fun `a purchase past what a channel may hold is refused before anyone is asked`() = runBlocking { val (_, wallet) = opened() diff --git a/docs/group-lightning-liquidity.md b/docs/group-lightning-liquidity.md index 4fb25bd0..25c68c97 100644 --- a/docs/group-lightning-liquidity.md +++ b/docs/group-lightning-liquidity.md @@ -34,6 +34,7 @@ differently, this table says so. | 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 | | 4 | done: `buy-liquidity` (`GroupLightningAuthorisationEvent.BuyLiquidity`), `liquidityPurchases`, `prepareBuyLiquidity`, `proposeBuyLiquidity`, its summary and its transcript line. `GroupLightningLiquidityJvmTest`, three tests, run on regtest and on mainnet | | 5 | done: a ledger per funding output (schema 35, `IcebergChannelLedger` keyed by output, with `fundingTxIndex`, `parentOutPoint` and `purchaseId`), `CoSignerPolicy.openSplice`, the shared input checked against S1 to S6, and a payment that settles on both live commitments spending its budget once. `GroupLightningSpliceCoSigningJvmTest`, seven four-device tests on regtest and on mainnet, among them a purchase the script interpreter accepts | +| 6 | done: `PeerHandle.fundingRates`, `feeratePerByte` and `buyLiquidity`, `GroupLightningNode.buyAuthorised` on the node's watch, and the snapshot's rates, feerate and purchases. Four tests with the stand-in peer in `GroupLightningLiquidityJvmTest` | | what the plan said | what it turned out to be | |---|---| @@ -49,6 +50,9 @@ differently, this table says so. | the parent ledger is marked `spliced` when the splice confirms | not built: the co-signer has no chain client, and nothing needs it. A commitment on a parent output stays checked against its own ledger, and once the splice confirms it spends an output that no longer exists | | the device that missed the splice follows it, by echoes or by the chain | **not built, and not a splice's problem.** A device that misses any commitment is already out: rule 1 needs each commitment to follow the last one this device signed, so a device that comes back after the group signed on without it refuses every request after. That is [lightning/restored-device-marks.md](./lightning/restored-device-marks.md)'s ground, and a splice adds one more thing for its marks to carry: the ledgers of outputs the device never saw | | budgets, per payment hash, already work across both live outputs | they did not. The same payment settles on both outputs' commitments at one number, and each consumed its budget, so the second was refused for falling under its floor. Each ledger now keeps what its last commitment consumed, and a sibling at the same number spends only the difference. The test fails without it | +| Phase 6: the node records the purchase from the payments database, and on-the-fly opens get the same row | the purchase's row comes from the answer: `buyLiquidity` adds a `liquidity` payment as it returns `PENDING`. On-the-fly opens still report nothing of their own: `LiquidityEvents.Purchased` carries no channel or transaction, and the payments database has no query for every purchase. They are left as they were | +| Phase 6: `requestInboundLiquidity` for the authorisation's channel | for the node's first `Normal` channel, which is all lightning-kmp's `Peer` offers. A group node has one channel to its LSP; the authorisation still names the channel, and every co-signer holds the splice to it | +| Phase 7's *Try again* acts under the same authorisation | a failed purchase is not tried again by the node at all, as a failed payment is not; *Try again* proposes a new authorisation. Every attempt under one authorisation spends the same parent output in any case, so a retry would have bought nothing a new one does not | | 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