feat(lightning): the group decides to buy inbound liquidity (liquidity, Phase 4)

A fourth action for kind 30363, `buy-liquidity`: one channel, an amount of inbound, a cap on the fee
(our share of the splice's mining fee and the purchase's own together), an expiry, and an id so two
purchases for one channel are two events. An older build reads it as no authorisation at all, and
refuses the splice that follows.

GroupLightningAuthorisations gains liquidityPurchases, prepareBuyLiquidity -- which refuses a purchase
of nothing, or one past the mainnet channel cap, with a LiquidityProblem of its own -- and
proposeBuyLiquidity. The proposal reads "Add 500,000 sats of inbound liquidity", with the fee cap and
the LSP's year, and the room gets a line once the group signs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-11-01 12:14:55 +02:00
1 parent 89504df765
commit 28f2d5a72a
6 files changed
+227 -3

No files matched your search

@@ -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."
}
@@ -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<GroupLightningAuthorisationEvent.BuyLiquidity> =
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<GroupLightningAuthorisationEvent.BuyLiquidity> {
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)
}
}
@@ -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<Nothing>(
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<Array<String>>): 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)
}
}
@@ -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