diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt index 6f757beb..125ccbfb 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt @@ -1595,7 +1595,8 @@ data class ChatMessage( val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) if (!signed.verifies()) return null val pay = GroupLightningAuthorisationEvent.read(event.tags) - val channelAction = if (pay == null) GroupLightningAuthorisationEvent.readChannelAction(event.tags) ?: return null else null + val buy = if (pay == null) GroupLightningAuthorisationEvent.readBuyLiquidity(event.tags) else null + val channelAction = if (pay == null && buy == null) GroupLightningAuthorisationEvent.readChannelAction(event.tags) ?: return null else null ChatMessage( giftWrapPayloadId = null, messageType = TYPE_GROUP_LIGHTNING_PAYMENT_AUTHORISED, @@ -1607,6 +1608,7 @@ data class ChatMessage( createdAt = createdAt, content = when { pay != null -> "The group authorised a Lightning payment of ${Satoshi(pay.amountMsat / 1000).grouped()} sats. The operator's node pays it." + buy != null -> "The group authorised adding ${Satoshi(buy.amountSat).grouped()} sats of inbound liquidity, for at most ${Satoshi(buy.maxFeeSat).grouped()} sats in fees. The operator's node buys it." channelAction?.action == GroupLightningAuthorisationEvent.FORCE_CLOSE -> "The group authorised force-closing a Lightning channel. Its money reaches the onchain wallet after a delay." else -> "The group authorised closing a Lightning channel to its onchain wallet." } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt index a12fe844..27264885 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt @@ -4,9 +4,12 @@ import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.database.model.FrostSigningSession import com.machankura.bennu.compose.database.model.IcebergBudgetSpend import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.extensions.toHex import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent +import com.machankura.bennu.compose.wallet.GroupLightningRollout import com.vitorpamplona.quartz.nip01Core.core.HexKey +import com.vitorpamplona.quartz.utils.RandomInstance import fr.acinq.bitcoin.ByteVector32 import fr.acinq.lightning.payment.Bolt11Invoice import kotlin.time.Clock @@ -130,4 +133,53 @@ object GroupLightningAuthorisations { val template = GroupLightningAuthorisationEvent.template(action) return FrostSigningManager.proposeSigning(database, localChatRoom, userPublicKey, template.kind, template.tags, template.content) } + + /** Why a liquidity purchase cannot be proposed. */ + sealed class LiquidityProblem { + /** A purchase of nothing. */ + data object NothingToBuy : LiquidityProblem() + /** A purchase that would take the channel over what a channel may hold on this network. */ + data class OverTheCap(val capSat: Long) : LiquidityProblem() + } + + class LiquidityProblemException(val problem: LiquidityProblem) : IllegalArgumentException(problem.toString()) + + /** How long a liquidity purchase stays open: as long as a close, for the same reason. */ + val LIQUIDITY_LIFETIME: Duration = CHANNEL_ACTION_LIFETIME + + /** + * Every liquidity purchase the group has authorised for [wallet], open at [now], oldest first + * (`docs/group-lightning-liquidity.md`, Phase 4). Whether one has already been spent is each + * co-signer's ledger to say. + */ + suspend fun liquidityPurchases(database: BennuDatabase, wallet: GroupLightningWalletManager.Wallet, now: Instant = Clock.System.now()): List = + database.groupSignedEventDao().getByChatRoomIdAndKind(wallet.signedEvent.chatRoomId, GroupLightningAuthorisationEvent.KIND) + .filter { it.verifies() } + .sortedWith(compareBy({ it.createdAt }, { it.id })) + .mapNotNull { GroupLightningAuthorisationEvent.readBuyLiquidity(it.tags) } + .filter { it.chain == wallet.statement.chain && it.wallet == wallet.statement.wallet && it.expiresAt > now.epochSeconds } + + /** + * The purchase of [amountSat] for [channelId], which holds [capacitySat] now, at most [maxFeeSat] in + * fees, or the [LiquidityProblem] with it. The proposer is not trusted on the cap: every co-signer holds the + * new funding output to it again. + */ + fun prepareBuyLiquidity(wallet: GroupLightningWalletManager.Wallet, channelId: String, capacitySat: Long, amountSat: Long, maxFeeSat: Long, now: Instant = Clock.System.now()): Result { + if (amountSat <= 0) return Result.failure(LiquidityProblemException(LiquidityProblem.NothingToBuy)) + GroupLightningRollout.channelCapFor(wallet.statement.chain)?.let { cap -> + if (capacitySat + amountSat > cap.sat) return Result.failure(LiquidityProblemException(LiquidityProblem.OverTheCap(cap.sat))) + } + return Result.success( + GroupLightningAuthorisationEvent.BuyLiquidity( + wallet.statement.chain, wallet.statement.wallet, channelId, amountSat, maxFeeSat.coerceAtLeast(0), + (now + LIQUIDITY_LIFETIME).epochSeconds, RandomInstance.bytes(8).toHex(), + ) + ) + } + + /** Proposes [buy] to the group; the operator's node buys once a quorum signs. */ + suspend fun proposeBuyLiquidity(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, buy: GroupLightningAuthorisationEvent.BuyLiquidity): FrostSigningSession { + val template = GroupLightningAuthorisationEvent.template(buy) + return FrostSigningManager.proposeSigning(database, localChatRoom, userPublicKey, template.kind, template.tags, template.content) + } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt index 15377cd5..3a6823a4 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt @@ -15,8 +15,10 @@ import kotlin.time.Clock * group's commitment offers must pay a hash some authorisation names, within its amount and fee cap. * So the operator cannot add a payment, only make one the group signed for. * - * `pay` is a payment ([Pay]); `close` and `force-close` act on one channel ([ChannelAction]). An action - * this device does not know reads as null, which every caller treats as no authorisation at all. + * `pay` is a payment ([Pay]); `close` and `force-close` act on one channel ([ChannelAction]); + * `buy-liquidity` buys inbound liquidity for one channel by splicing it ([BuyLiquidity], + * `docs/group-lightning-liquidity.md`, Phase 4). An action this device does not know reads as null, + * which every caller treats as no authorisation at all. */ object GroupLightningAuthorisationEvent { val KIND: Kind = GroupLightningEvents.AUTHORISATION @@ -30,12 +32,15 @@ object GroupLightningAuthorisationEvent { private const val EXPIRES_TAG = "expires" private const val CHANNEL_TAG = "channel" + private const val ID_TAG = "id" const val PAY = "pay" /** A mutual close of one channel, to the onchain wallet the statement names. */ const val CLOSE = "close" /** Publishing our own commitment of one channel: what the group does when the LSP has gone away. */ const val FORCE_CLOSE = "force-close" + /** Buying inbound liquidity for one channel from the LSP, by splicing it. */ + const val BUY_LIQUIDITY = "buy-liquidity" /** * A payment the group authorises, at most [amountMsat] plus [maxFeeMsat], until [expiresAt] (epoch @@ -127,4 +132,52 @@ object GroupLightningAuthorisationEvent { val expires = value(EXPIRES_TAG)?.toLongOrNull() ?: return null return ChannelAction(action, chain, wallet, channelId, expires) } + + /** + * Buying [amountSat] of inbound liquidity for [channelId] from the LSP, by splicing the channel, for + * at most [maxFeeSat] in fees -- our share of the splice's mining fee and the purchase's own, mining + * and service, together -- until [expiresAt] (epoch seconds). The fee comes out of the group's + * balance in the channel. [id] tells two purchases for one channel apart. + */ + data class BuyLiquidity( + val chain: Chain, + val wallet: Long, + val channelId: String, + val amountSat: Long, + val maxFeeSat: Long, + val expiresAt: Long, + val id: String, + ) + + fun template(buy: BuyLiquidity, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = + EventTemplate( + createdAt = createdAt, + kind = KIND, + tags = arrayOf( + arrayOf(D_TAG, "${GroupLightningWalletStatementEvent.identifier(buy.chain, buy.wallet)}:$BUY_LIQUIDITY:${buy.channelId}:${buy.id}"), + arrayOf(ACTION_TAG, BUY_LIQUIDITY), + arrayOf(CHANNEL_TAG, buy.channelId), + arrayOf(AMOUNT_TAG, buy.amountSat.toString()), + arrayOf(MAX_FEE_TAG, buy.maxFeeSat.toString()), + arrayOf(EXPIRES_TAG, buy.expiresAt.toString()), + arrayOf(ID_TAG, buy.id), + ), + content = "", + ) + + /** The liquidity purchase [tags] authorise, or null for any other action, or tags that disagree. */ + fun readBuyLiquidity(tags: Array>): BuyLiquidity? { + fun value(name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) + if (value(ACTION_TAG) != BUY_LIQUIDITY) return null + val parts = value(D_TAG)?.split(':') ?: return null + if (parts.size != 5 || parts[2] != BUY_LIQUIDITY) return null + val chain = GroupWalletStatementEvent.chainNamed(parts[0]) ?: return null + val wallet = parts[1].toLongOrNull() ?: return null + val channelId = value(CHANNEL_TAG)?.takeIf { it.length == 64 && it == parts[3] } ?: return null + val id = value(ID_TAG)?.takeIf { it.isNotEmpty() && it == parts[4] } ?: return null + val amount = value(AMOUNT_TAG)?.toLongOrNull()?.takeIf { it > 0 } ?: return null + val maxFee = value(MAX_FEE_TAG)?.toLongOrNull()?.takeIf { it >= 0 } ?: return null + val expires = value(EXPIRES_TAG)?.toLongOrNull() ?: return null + return BuyLiquidity(chain, wallet, channelId, amount, maxFee, expires, id) + } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt index 3b15b1ef..cb9964f6 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt @@ -151,6 +151,14 @@ object ProposedEvent { label = "Close a Lightning channel", detail = "Channel ${action.channelId.take(16)}: its money goes to the group's onchain wallet", ) + } ?: GroupLightningAuthorisationEvent.readBuyLiquidity(event.tags)?.let { buy -> + // Buying liquidity spends the group's money on room to be paid. A signer weighs how much + // room, what it costs at most, and that the LSP may take back what is unused after a year + // (docs/group-lightning-liquidity.md, Phase 4). + Summary( + label = "Add ${Satoshi(buy.amountSat).grouped()} sats of inbound liquidity", + detail = "Channel ${buy.channelId.take(16)}: for at most ${Satoshi(buy.maxFeeSat).grouped()} sats in fees, from the group's balance. The LSP may reclaim what is unused after a year", + ) } ?: Summary(label = "Authorise the Lightning wallet", detail = "An authorisation this device cannot read") // The group agreeing to guard one member's wallet. What a signer weighs 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 new file mode 100644 index 00000000..e628c51c --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningLiquidityJvmTest.kt @@ -0,0 +1,106 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent +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 kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration.Companion.days + +/** + * The group deciding to buy inbound liquidity (`docs/group-lightning-liquidity.md`, Phase 4): a + * `buy-liquidity` authorisation reads back as what it was, an older build reads it as nothing, the + * proposal says what a signer weighs, and a purchase past the mainnet cap is refused before anyone is asked. + */ +abstract class GroupLightningLiquidityCases(chain: Chain) { + private val fixture = GroupLightningFixture(chain = chain) + private val lsp = "02" + KeyPair().pubKey.toHexKey() + private val channelId = "ab".repeat(32) + + @AfterTest + fun close() = fixture.close() + + private suspend fun opened(): Pair, GroupLightningWalletManager.Wallet> { + val all = fixture.group() + fixture.runCeremony(all) + fixture.signSession(all, all[0], GroupLightningWalletManager.proposeWallet(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, fixture.chain, lsp).id) + fixture.signSession(all, all[1], GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, fixture.chain).id) + return all to GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! + } + + @Test + fun `a purchase reads back as what it was, and nothing else reads it`() = runBlocking { + val (_, wallet) = opened() + val buy = GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channelId, capacitySat = 25_000, amountSat = 500_000, maxFeeSat = 7_500).getOrThrow() + assertEquals(500_000, buy.amountSat) + assertEquals(7_500, buy.maxFeeSat) + assertTrue(buy.expiresAt > Clock.System.now().epochSeconds) + val tags = GroupLightningAuthorisationEvent.template(buy).tags + assertEquals(buy, GroupLightningAuthorisationEvent.readBuyLiquidity(tags)) + // An older build, which knows only payments and channel actions, reads it as no authorisation at all. + assertNull(GroupLightningAuthorisationEvent.read(tags)) + assertNull(GroupLightningAuthorisationEvent.readChannelAction(tags)) + // And the purchase reader reads nothing else. + val close = GroupLightningAuthorisationEvent.ChannelAction(GroupLightningAuthorisationEvent.CLOSE, fixture.chain, 0, channelId, buy.expiresAt) + assertNull(GroupLightningAuthorisationEvent.readBuyLiquidity(GroupLightningAuthorisationEvent.template(close).tags)) + + fun with(name: String, value: String) = tags.map { if (it[0] == name) arrayOf(name, value) else it }.toTypedArray() + assertNull(GroupLightningAuthorisationEvent.readBuyLiquidity(with("channel", "cd".repeat(32))), "a channel the identifier does not name") + assertNull(GroupLightningAuthorisationEvent.readBuyLiquidity(with("id", "other")), "an id the identifier does not name") + assertNull(GroupLightningAuthorisationEvent.readBuyLiquidity(with("amount", "0")), "nothing to buy") + assertNull(GroupLightningAuthorisationEvent.readBuyLiquidity(with("maxfee", "-1")), "a negative fee cap") + + // Two purchases for one channel are two events, not one replacing the other. + val again = GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channelId, 25_000, 500_000, 7_500).getOrThrow() + assertNotEquals(GroupLightningAuthorisationEvent.template(buy).tags.first { it[0] == "d" }[1], GroupLightningAuthorisationEvent.template(again).tags.first { it[0] == "d" }[1]) + + val summary = ProposedEvent.summarize(Event("", "", 0, GroupLightningAuthorisationEvent.KIND, tags, "", "")) + assertEquals("Add 500,000 sats of inbound liquidity", summary.label) + assertTrue("7,500 sats" in summary.detail && "after a year" in summary.detail, summary.detail) + } + + @Test + fun `once the group signs, every member reads the open purchase, until it expires`() = runBlocking { + val (all, wallet) = opened() + val buy = GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channelId, 25_000, 200_000, 4_000).getOrThrow() + fixture.signSession(all, all[2], GroupLightningAuthorisations.proposeBuyLiquidity(all[2].db, all[2].room, all[2].publicKey, buy).id) + all.forEach { d -> + val mine = GroupLightningWalletManager.walletFor(d.db, fixture.roomId, fixture.chain)!! + assertEquals(listOf(buy), GroupLightningAuthorisations.liquidityPurchases(d.db, mine), "device ${d.index}") + assertTrue(GroupLightningAuthorisations.liquidityPurchases(d.db, mine, Clock.System.now() + 4.days).isEmpty(), "device ${d.index}: expired") + // A purchase is not a payment budget, nor a close. + assertTrue(GroupLightningAuthorisations.budgets(d.db, mine).isEmpty()) + assertTrue(GroupLightningAuthorisations.channelActions(d.db, fixture.roomId, mine.statement).isEmpty()) + } + } + + @Test + fun `a purchase past what a channel may hold is refused before anyone is asked`() = runBlocking { + val (_, wallet) = opened() + fun problem(capacity: Long, amount: Long) = + (GroupLightningAuthorisations.prepareBuyLiquidity(wallet, channelId, capacity, amount, 1_000).exceptionOrNull() as? GroupLightningAuthorisations.LiquidityProblemException)?.problem + assertEquals(GroupLightningAuthorisations.LiquidityProblem.NothingToBuy, problem(25_000, 0)) + val cap = GroupLightningRollout.channelCapFor(fixture.chain) + if (cap == null) { + assertNull(problem(25_000, 10_000_000), "no cap off mainnet") + } else { + assertNull(problem(25_000, cap.sat - 25_000), "up to the cap exactly") + assertIs(problem(25_000, cap.sat - 24_999)) + } + } +} + +class GroupLightningLiquidityJvmTest : GroupLightningLiquidityCases(Chain.Regtest) + +class GroupLightningLiquidityMainnetJvmTest : GroupLightningLiquidityCases(Chain.Mainnet) diff --git a/docs/group-lightning-liquidity.md b/docs/group-lightning-liquidity.md index 7dcfa0b3..9f9ae90c 100644 --- a/docs/group-lightning-liquidity.md +++ b/docs/group-lightning-liquidity.md @@ -32,6 +32,7 @@ differently, this table says so. | 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 | +| 4 | done: `buy-liquidity` (`GroupLightningAuthorisationEvent.BuyLiquidity`), `liquidityPurchases`, `prepareBuyLiquidity`, `proposeBuyLiquidity`, its summary and its transcript line. `GroupLightningLiquidityJvmTest`, three tests, run on regtest and on mainnet | | what the plan said | what it turned out to be | |---|---| @@ -40,6 +41,8 @@ differently, this table says so. | 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 | +| Phase 4: purchase problems join the invoice's `Problem` | a `LiquidityProblem` of their own. The send screen matches every `Problem` to a sentence about an invoice, and neither of these is one | +| Phase 4: the tags | also an `id`, eight random bytes, in the `d` tag and a tag of its own, so two purchases for one channel are two events rather than one replacing the other | | 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