feat(lightning): the group closes and force-closes its channels (Phase 13, part 1)
Two new authorisation actions on kind 30346, `close` and `force-close`, each naming one channel and open for three days. The operator's node acts on each once: a mutual close to the onchain wallet's first address, or publishing our own commitment. Any member proposes one from the channel's menu on the wallet screen. Co-signers sign our own commitment only under a force-close authorisation, only after rebuilding it, and never one more than a step behind the counterparty commitment they last signed: anything older is revoked. A four-device test force-closes with a signature that spends the funding output. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d69344fe1b
commit
cb6934b806
16 files changed
+298
-20
No files matched your search
@@ -757,4 +757,7 @@
|
||||
<string name="that_invoice_has_expired">That invoice has expired.</string>
|
||||
<string name="that_invoice_names_no_amount">That invoice names no amount, so give one.</string>
|
||||
<string name="that_invoice_pays_this_wallet">That invoice pays this wallet's own node.</string>
|
||||
<string name="close_to_the_onchain_wallet">Close to the onchain wallet</string>
|
||||
<string name="force_close">Force close</string>
|
||||
<string name="channel_actions">Channel actions</string>
|
||||
</resources>
|
||||
+7
-2
@@ -1782,7 +1782,8 @@ data class ChatMessage(
|
||||
GroupLightningAuthorisationEvent.KIND -> {
|
||||
val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId)
|
||||
if (!signed.verifies()) return null
|
||||
val pay = GroupLightningAuthorisationEvent.read(event.tags) ?: return null
|
||||
val pay = GroupLightningAuthorisationEvent.read(event.tags)
|
||||
val channelAction = if (pay == null) GroupLightningAuthorisationEvent.readChannelAction(event.tags) ?: return null else null
|
||||
ChatMessage(
|
||||
giftWrapPayloadId = null,
|
||||
messageType = TYPE_GROUP_LIGHTNING_PAYMENT_AUTHORISED,
|
||||
@@ -1792,7 +1793,11 @@ data class ChatMessage(
|
||||
isUserMessage = isUserMessage,
|
||||
chatRoomId = groupId,
|
||||
createdAt = createdAt,
|
||||
content = "The group authorised a Lightning payment of ${Satoshi(pay.amountMsat / 1000).grouped()} sats. The operator's node pays it."
|
||||
content = when {
|
||||
pay != null -> "The group authorised a Lightning payment of ${Satoshi(pay.amountMsat / 1000).grouped()} sats. The operator's node pays 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."
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+3
@@ -63,6 +63,9 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr
|
||||
override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession =
|
||||
GroupLightningAuthorisations.propose(database, localChatRoom, userPublicKey, pay)
|
||||
|
||||
override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession =
|
||||
GroupLightningAuthorisations.proposeChannelAction(database, localChatRoom, userPublicKey, wallet, channelId, force)
|
||||
|
||||
override fun observeCeremony(sessionId: String): Flow<IcebergKeySession?> =
|
||||
database.icebergKeySessionDao().observeSessionById(sessionId)
|
||||
|
||||
|
||||
+26
-4
@@ -20,8 +20,8 @@ import kotlin.time.Instant
|
||||
*
|
||||
* An authorisation is a group-signed event (kind 30346, [GroupLightningAuthorisationEvent]). The group
|
||||
* may sign two for one invoice -- once more after the first expired, say. They are one payment: the
|
||||
* budget is the larger, and it is open while either is. Force closes are Phase 13's, and none is
|
||||
* authorised until then.
|
||||
* budget is the larger, and it is open while either is. A close or force close names one channel, and
|
||||
* lasts [CHANNEL_ACTION_LIFETIME].
|
||||
*/
|
||||
object GroupLightningAuthorisations {
|
||||
/** How long an authorisation stays open when its invoice does not say sooner. */
|
||||
@@ -96,6 +96,28 @@ object GroupLightningAuthorisations {
|
||||
return FrostSigningManager.proposeSigning(database, localChatRoom, userPublicKey, template.kind, template.tags, template.content)
|
||||
}
|
||||
|
||||
/** Whether the group has authorised a force close of [channelId]: never, until Phase 13. */
|
||||
suspend fun forceCloseAuthorised(database: BennuDatabase, chatRoomId: String, statement: GroupLightningWalletStatementEvent.Statement, channelId: ByteVector32): Boolean = false
|
||||
/** How long a close or force close stays open: long enough for the operator's device to come online. */
|
||||
val CHANNEL_ACTION_LIFETIME: Duration = 72.hours
|
||||
|
||||
/** Every close and force close the group has authorised in [chatRoomId] for the wallet [statement] names, open at [now]. */
|
||||
suspend fun channelActions(database: BennuDatabase, chatRoomId: String, statement: GroupLightningWalletStatementEvent.Statement, now: Instant = Clock.System.now()): List<GroupLightningAuthorisationEvent.ChannelAction> =
|
||||
database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, GroupLightningAuthorisationEvent.KIND)
|
||||
.filter { it.verifies() }
|
||||
.sortedWith(compareBy({ it.createdAt }, { it.id }))
|
||||
.mapNotNull { GroupLightningAuthorisationEvent.readChannelAction(it.tags) }
|
||||
.filter { it.chain == statement.chain && it.wallet == statement.wallet && it.expiresAt > now.epochSeconds }
|
||||
|
||||
/** Whether the group has authorised a force close of [channelId] that is still open. */
|
||||
suspend fun forceCloseAuthorised(database: BennuDatabase, chatRoomId: String, statement: GroupLightningWalletStatementEvent.Statement, channelId: ByteVector32): Boolean =
|
||||
channelActions(database, chatRoomId, statement).any { it.action == GroupLightningAuthorisationEvent.FORCE_CLOSE && it.channelId == channelId.toHex() }
|
||||
|
||||
/** Proposes that the operator's node close [channelId] -- mutually, or by force when [force]. */
|
||||
suspend fun proposeChannelAction(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession {
|
||||
val action = GroupLightningAuthorisationEvent.ChannelAction(
|
||||
if (force) GroupLightningAuthorisationEvent.FORCE_CLOSE else GroupLightningAuthorisationEvent.CLOSE,
|
||||
wallet.statement.chain, wallet.statement.wallet, channelId, (Clock.System.now() + CHANNEL_ACTION_LIFETIME).epochSeconds,
|
||||
)
|
||||
val template = GroupLightningAuthorisationEvent.template(action)
|
||||
return FrostSigningManager.proposeSigning(database, localChatRoom, userPublicKey, template.kind, template.tags, template.content)
|
||||
}
|
||||
}
|
||||
+37
-1
@@ -308,11 +308,47 @@ object GroupLightningCoSigner {
|
||||
return when (context.type) {
|
||||
"remote" -> checkRemote(database, wallet, request, context, params, tx, pinned)
|
||||
"closing" -> checkClosing(statement, context, tx, closeTo)
|
||||
"local" -> if (GroupLightningAuthorisations.forceCloseAuthorised(database, roomId, statement, params.channelId)) null else "the group has not authorised a force close"
|
||||
"local" -> checkLocal(database, wallet, request, context, params, tx, pinned)
|
||||
else -> "an unknown kind of transaction"
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Our own commitment, which the group signs only to force-close: authorised, rebuilt from its context,
|
||||
* and no older than the counterparty commitment this device last signed for the channel, less one.
|
||||
* The two numbers move together, so a local commitment further behind than that is one this channel
|
||||
* has revoked, and publishing it would hand the counterparty everything.
|
||||
*/
|
||||
private suspend fun checkLocal(
|
||||
database: BennuDatabase,
|
||||
wallet: GroupLightningWalletManager.Wallet,
|
||||
request: CoSigningWire.SigningRequest,
|
||||
context: CoSigningWire.Context,
|
||||
params: fr.acinq.lightning.channel.ChannelParams,
|
||||
tx: Transaction,
|
||||
pinned: IcebergChannelLedger?,
|
||||
): String? {
|
||||
if (!GroupLightningAuthorisations.forceCloseAuthorised(database, wallet.signedEvent.chatRoomId, wallet.statement, params.channelId)) return "the group has not authorised a force close"
|
||||
val seed = wallet.seed ?: return "this device does not hold the node's seed, and cannot rebuild the commitment"
|
||||
val commitParams = CoSigningWire.commit(context.commit ?: return "no commitment parameters")
|
||||
val commitIndex = context.commitIndex ?: return "no commitment number"
|
||||
pinned?.let { if (commitIndex < load(it.ledger).commitIndex - 1) return "commitment $commitIndex is older than this channel's current one, and revoked" }
|
||||
val keys = keyManagerOf(ByteVector(seed.seed), wallet.statement.chain).channelKeys(params.localParams.fundingKeyPath)
|
||||
.withGroupBasepoints(wallet.basepoints.forChannel)
|
||||
val (rebuilt, _) = Commitments.makeLocalTxs(
|
||||
channelParams = params,
|
||||
commitParams = commitParams,
|
||||
commitKeys = keys.localCommitmentKeys(params, commitIndex),
|
||||
commitTxNumber = commitIndex,
|
||||
localFundingPubkey = PublicKey.fromHex(wallet.statement.icebergKey),
|
||||
remoteFundingPubKey = PublicKey.fromHex(request.remoteFundingPubKey),
|
||||
commitmentInput = CoSigningWire.inputInfo(request.input),
|
||||
commitmentFormat = Transactions.CommitmentFormat.SimpleTaprootChannels,
|
||||
spec = CoSigningWire.spec(context.spec, params.channelId),
|
||||
)
|
||||
return if (rebuilt.tx != tx) "the commitment its context rebuilds to is not the one it asks to sign" else null
|
||||
}
|
||||
|
||||
private suspend fun checkRemote(
|
||||
database: BennuDatabase,
|
||||
wallet: GroupLightningWalletManager.Wallet,
|
||||
|
||||
+41
@@ -3,6 +3,7 @@ package com.machankura.bennu.compose.managers
|
||||
import co.touchlab.kermit.Logger
|
||||
import com.machankura.bennu.compose.database.BennuDatabase
|
||||
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
|
||||
import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent
|
||||
import com.machankura.bennu.compose.wallet.GroupChainClients
|
||||
import com.machankura.bennu.compose.wallet.lightning.GroupNodeKeyManager
|
||||
import com.machankura.bennu.compose.wallet.lightning.WalletWire
|
||||
@@ -11,6 +12,7 @@ import fr.acinq.bitcoin.ByteVector
|
||||
import fr.acinq.bitcoin.ByteVector32
|
||||
import fr.acinq.bitcoin.Chain
|
||||
import fr.acinq.bitcoin.PublicKey
|
||||
import fr.acinq.bitcoin.Satoshi
|
||||
import fr.acinq.bitcoin.utils.Either
|
||||
import fr.acinq.lightning.Feature
|
||||
import fr.acinq.lightning.FeatureSupport
|
||||
@@ -20,6 +22,9 @@ import fr.acinq.lightning.NodeParams
|
||||
import fr.acinq.lightning.PaymentEvents
|
||||
import fr.acinq.lightning.WalletParams
|
||||
import fr.acinq.lightning.blockchain.electrum.ElectrumWatcher
|
||||
import fr.acinq.lightning.blockchain.fee.FeeratePerByte
|
||||
import fr.acinq.lightning.blockchain.fee.FeeratePerKw
|
||||
import fr.acinq.lightning.channel.ChannelCommand
|
||||
import fr.acinq.lightning.channel.states.ChannelStateWithCommitments
|
||||
import fr.acinq.lightning.crypto.RemoteIcebergFundingSigner
|
||||
import fr.acinq.lightning.db.Databases
|
||||
@@ -29,6 +34,7 @@ import fr.acinq.lightning.db.WalletPayment
|
||||
import fr.acinq.lightning.io.PaymentSent
|
||||
import fr.acinq.lightning.io.Peer
|
||||
import fr.acinq.lightning.io.TcpSocket
|
||||
import fr.acinq.lightning.io.WrappedChannelCommand
|
||||
import fr.acinq.lightning.logging.LoggerFactory
|
||||
import fr.acinq.lightning.payment.Bolt11Invoice
|
||||
import kotlin.time.Clock
|
||||
@@ -88,6 +94,10 @@ class GroupLightningNode(
|
||||
suspend fun hasPaid(paymentHash: String): Boolean
|
||||
/** Pays [bolt11] [amountMsat], through the LSP, and says how it went. */
|
||||
suspend fun pay(bolt11: String, amountMsat: Long): WalletWire.PaymentView
|
||||
/** Starts a mutual close of [channelId] to [scriptPubKey]. */
|
||||
suspend fun close(channelId: String, scriptPubKey: ByteVector)
|
||||
/** Publishes our own commitment of [channelId]. */
|
||||
suspend fun forceClose(channelId: String)
|
||||
}
|
||||
|
||||
sealed class State {
|
||||
@@ -210,6 +220,30 @@ class GroupLightningNode(
|
||||
}
|
||||
}
|
||||
|
||||
private val closing = mutableSetOf<String>()
|
||||
|
||||
/**
|
||||
* Closes every channel the group has authorised closing, once per authorisation this run: mutually to
|
||||
* the onchain wallet's first address, which is where the channel's own closing script already
|
||||
* points, or by force.
|
||||
*/
|
||||
internal suspend fun closeAuthorised() {
|
||||
val handle = peer ?: return
|
||||
val open = handle.channels().map { it.channelId }.toSet()
|
||||
val actions = GroupLightningAuthorisations.channelActions(database, localChatRoom.chatRoom.id, wallet.statement, now())
|
||||
if (actions.isEmpty()) return
|
||||
val onchain = GroupWalletManager.walletFor(database, localChatRoom.chatRoom.id, chain, wallet.statement.onchainAccount) ?: return
|
||||
val closeTo = GroupWalletDerivation.derive(onchain.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript
|
||||
actions.filter { it.channelId in open }.forEach { action ->
|
||||
if (!closing.add("${action.action}:${action.channelId}")) return@forEach
|
||||
when (action.action) {
|
||||
GroupLightningAuthorisationEvent.FORCE_CLOSE -> handle.forceClose(action.channelId)
|
||||
else -> handle.close(action.channelId, closeTo)
|
||||
}
|
||||
logger.i("${action.action} of ${action.channelId.take(16)}, as the group authorised")
|
||||
}
|
||||
}
|
||||
|
||||
/** Stops the node as soon as the room's newest operator statement names a later term. */
|
||||
private fun watchForHandover(term: Long) {
|
||||
watching?.cancel()
|
||||
@@ -225,6 +259,7 @@ class GroupLightningNode(
|
||||
runCatching { report(term) }.onFailure { logger.e("Could not report the wallet to the room", it) }
|
||||
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) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -309,6 +344,12 @@ class GroupLightningNode(
|
||||
peer.createInvoice(Lightning.randomBytes32(), amountMsat?.let(::MilliSatoshi), Either.Left(description)).write()
|
||||
override suspend fun hasPaid(paymentHash: String): Boolean =
|
||||
databases.payments.listLightningOutgoingPayments(ByteVector32(paymentHash)).isNotEmpty()
|
||||
override suspend fun close(channelId: String, scriptPubKey: ByteVector) {
|
||||
peer.mutualClose(ByteVector32(channelId), scriptPubKey, peer.onChainFeeratesFlow.value?.mutualCloseFeerate ?: FeeratePerKw(FeeratePerByte(Satoshi(2))))
|
||||
}
|
||||
override suspend fun forceClose(channelId: String) {
|
||||
peer.send(WrappedChannelCommand(ByteVector32(channelId), ChannelCommand.Close.ForceClose))
|
||||
}
|
||||
override suspend fun pay(bolt11: String, amountMsat: Long): WalletWire.PaymentView {
|
||||
val invoice = Bolt11Invoice.read(bolt11).get()
|
||||
return when (val result = peer.payInvoice(MilliSatoshi(amountMsat), invoice)) {
|
||||
|
||||
+41
-2
@@ -15,8 +15,8 @@ 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.
|
||||
*
|
||||
* Only `pay` exists so far. Closing, force-closing and splicing out are Phase 13's, and 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]). 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
|
||||
@@ -29,7 +29,13 @@ object GroupLightningAuthorisationEvent {
|
||||
private const val HASH_TAG = "hash"
|
||||
private const val EXPIRES_TAG = "expires"
|
||||
|
||||
private const val CHANNEL_TAG = "channel"
|
||||
|
||||
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"
|
||||
|
||||
/**
|
||||
* A payment the group authorises, at most [amountMsat] plus [maxFeeMsat], until [expiresAt] (epoch
|
||||
@@ -88,4 +94,37 @@ object GroupLightningAuthorisationEvent {
|
||||
if (expires > invoice.timestampSeconds + (invoice.expirySeconds ?: Bolt11Invoice.DEFAULT_EXPIRY_SECONDS.toLong())) return null
|
||||
return Pay(chain, wallet, bolt11, amount, maxFee, hash, expires)
|
||||
}
|
||||
|
||||
/** A [CLOSE] or [FORCE_CLOSE] of [channelId], open until [expiresAt] (epoch seconds). */
|
||||
data class ChannelAction(val action: String, val chain: Chain, val wallet: Long, val channelId: String, val expiresAt: Long) {
|
||||
init {
|
||||
require(action == CLOSE || action == FORCE_CLOSE) { "not a channel action: $action" }
|
||||
}
|
||||
}
|
||||
|
||||
fun template(channelAction: ChannelAction, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> =
|
||||
EventTemplate<Nothing>(
|
||||
createdAt = createdAt,
|
||||
kind = KIND,
|
||||
tags = arrayOf(
|
||||
arrayOf(D_TAG, "${GroupLightningWalletStatementEvent.identifier(channelAction.chain, channelAction.wallet)}:${channelAction.action}:${channelAction.channelId}"),
|
||||
arrayOf(ACTION_TAG, channelAction.action),
|
||||
arrayOf(CHANNEL_TAG, channelAction.channelId),
|
||||
arrayOf(EXPIRES_TAG, channelAction.expiresAt.toString()),
|
||||
),
|
||||
content = "",
|
||||
)
|
||||
|
||||
/** The channel action [tags] authorise, or null for a payment, an unknown action, or tags that disagree. */
|
||||
fun readChannelAction(tags: Array<Array<String>>): ChannelAction? {
|
||||
fun value(name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1)
|
||||
val action = value(ACTION_TAG)?.takeIf { it == CLOSE || it == FORCE_CLOSE } ?: return null
|
||||
val parts = value(D_TAG)?.split(':') ?: return null
|
||||
if (parts.size != 4 || parts[2] != action) 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 expires = value(EXPIRES_TAG)?.toLongOrNull() ?: return null
|
||||
return ChannelAction(action, chain, wallet, channelId, expires)
|
||||
}
|
||||
}
|
||||
+3
@@ -73,4 +73,7 @@ interface GroupLightningRepository {
|
||||
|
||||
/** Proposes [pay] to the group; the operator's node pays it once a quorum signs. */
|
||||
suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession
|
||||
|
||||
/** Proposes closing [channelId] to the onchain wallet, or force-closing it when [force]. */
|
||||
suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession
|
||||
}
|
||||
@@ -240,6 +240,16 @@ object ProposedEvent {
|
||||
invoice?.description?.takeIf { it.isNotBlank() }?.let { append(", for \"$it\"") }
|
||||
},
|
||||
)
|
||||
} ?: GroupLightningAuthorisationEvent.readChannelAction(event.tags)?.let { action ->
|
||||
// Closing moves the channel's money to the onchain wallet; forcing it does so slowly, at a
|
||||
// cost, and is for when the LSP has gone. The summary says which, because that is the choice.
|
||||
if (action.action == GroupLightningAuthorisationEvent.FORCE_CLOSE) Summary(
|
||||
label = "Force-close a Lightning channel",
|
||||
detail = "Channel ${action.channelId.take(16)}: the group's own commitment is published, and its money reaches the onchain wallet after a delay",
|
||||
) else Summary(
|
||||
label = "Close a Lightning channel",
|
||||
detail = "Channel ${action.channelId.take(16)}: its money goes to the group's onchain wallet",
|
||||
)
|
||||
} ?: Summary(label = "Authorise the Lightning wallet", detail = "An authorisation this device cannot read")
|
||||
|
||||
else -> Summary(label = "Event of kind ${event.kind}", detail = event.content)
|
||||
|
||||
+31
-3
@@ -1,6 +1,7 @@
|
||||
package com.machankura.bennu.compose.ui.composable
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
@@ -17,12 +18,16 @@ import androidx.compose.material.icons.automirrored.filled.CallReceived
|
||||
import androidx.compose.material.icons.filled.AccountBalanceWallet
|
||||
import androidx.compose.material.icons.filled.Bolt
|
||||
import androidx.compose.material.icons.filled.Key
|
||||
import androidx.compose.material.icons.filled.MoreVert
|
||||
import androidx.compose.material.icons.filled.Router
|
||||
import androidx.compose.material.icons.filled.Warning
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.Card
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.ListItem
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
@@ -32,7 +37,11 @@ import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TopAppBar
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
@@ -41,9 +50,12 @@ import bennu.composeapp.generated.resources.Res
|
||||
import bennu.composeapp.generated.resources.a_lightning_wallet_needs_four_signers
|
||||
import bennu.composeapp.generated.resources.at_most_s_sats_in_flight
|
||||
import bennu.composeapp.generated.resources.balance
|
||||
import bennu.composeapp.generated.resources.channel_actions
|
||||
import bennu.composeapp.generated.resources.channels
|
||||
import bennu.composeapp.generated.resources.close_to_the_onchain_wallet
|
||||
import bennu.composeapp.generated.resources.couldn_t_propose_this
|
||||
import bennu.composeapp.generated.resources.couldn_t_send_s_sats
|
||||
import bennu.composeapp.generated.resources.force_close
|
||||
import bennu.composeapp.generated.resources.group_wallet_on_s
|
||||
import bennu.composeapp.generated.resources.lightning_wallet
|
||||
import bennu.composeapp.generated.resources.lsp_s
|
||||
@@ -208,6 +220,7 @@ fun GroupLightningWalletScreen(
|
||||
state = state,
|
||||
onReceive = { onNavigateToRoute(GroupLightningReceiveRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) },
|
||||
onSend = { onNavigateToRoute(GroupLightningSendRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) },
|
||||
onClose = { channelId, force -> viewModel.close(channelId, force, onSession = toSession, onFailure = { notify(couldNotPropose) }) },
|
||||
isPending = viewModel.isActionPending.value,
|
||||
onNominate = { viewModel.nominateSelf(onSession = toSession, onFailure = { notify(couldNotPropose) }) },
|
||||
onStepDown = { viewModel.stepDown(onSession = toSession, onFailure = { notify(couldNotPropose) }) },
|
||||
@@ -218,7 +231,7 @@ fun GroupLightningWalletScreen(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> Unit, onSend: () -> Unit, isPending: Boolean, onNominate: () -> Unit, onStepDown: () -> Unit) {
|
||||
private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> Unit, onSend: () -> Unit, onClose: (channelId: String, force: Boolean) -> Unit, isPending: Boolean, onNominate: () -> Unit, onStepDown: () -> Unit) {
|
||||
val statement = state.wallet.statement
|
||||
val operatorName = state.operator?.publicKey?.let { key ->
|
||||
if (state.isOperator) stringResource(Res.string.you)
|
||||
@@ -231,7 +244,7 @@ private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.
|
||||
item { Balance(state.report, onReceive = onReceive.takeIf { state.operator?.publicKey != null }, onSend = onSend.takeIf { state.operator?.publicKey != null }) }
|
||||
state.report?.takeIf { it.checks.isNotEmpty() }?.let { report ->
|
||||
item { Text(stringResource(Res.string.channels), style = MaterialTheme.typography.titleSmall) }
|
||||
items(report.checks, key = { it.channel.channelId }) { ChannelRow(it) }
|
||||
items(report.checks, key = { it.channel.channelId }) { ChannelRow(it, onClose = { force: Boolean -> onClose(it.channel.channelId, force) }.takeIf { !isPending }) }
|
||||
}
|
||||
item { Text(stringResource(Res.string.payments), style = MaterialTheme.typography.titleSmall) }
|
||||
if (state.payments.isEmpty()) {
|
||||
@@ -311,7 +324,7 @@ private fun Balance(report: GroupLightningReports.Report?, onReceive: (() -> Uni
|
||||
|
||||
/** One channel, and whether the operator's figure for it is the one this device co-signed. */
|
||||
@Composable
|
||||
private fun ChannelRow(check: GroupLightningReports.ChannelCheck) {
|
||||
private fun ChannelRow(check: GroupLightningReports.ChannelCheck, onClose: ((force: Boolean) -> Unit)?) {
|
||||
val channel = check.channel
|
||||
ListItem(
|
||||
leadingContent = {
|
||||
@@ -332,6 +345,21 @@ private fun ChannelRow(check: GroupLightningReports.ChannelCheck) {
|
||||
color = if (check.agrees == false) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
// Closing is a proposal like any other: the menu only opens the signing session.
|
||||
trailingContent = onClose?.let { close ->
|
||||
{
|
||||
var expanded by remember { mutableStateOf(false) }
|
||||
Box {
|
||||
IconButton(onClick = { expanded = true }) {
|
||||
Icon(Icons.Default.MoreVert, contentDescription = stringResource(Res.string.channel_actions))
|
||||
}
|
||||
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
|
||||
DropdownMenuItem(text = { Text(stringResource(Res.string.close_to_the_onchain_wallet)) }, onClick = { expanded = false; close(false) })
|
||||
DropdownMenuItem(text = { Text(stringResource(Res.string.force_close)) }, onClick = { expanded = false; close(true) })
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
+6
@@ -115,6 +115,12 @@ class GroupLightningWalletViewModel(
|
||||
act(onSession, onFailure) { lightningRepository.stepDown(state.localChatRoom, activeUserPublicKey, chain) }
|
||||
}
|
||||
|
||||
/** Proposes closing [channelId] to the onchain wallet, or by force when the LSP is gone. */
|
||||
fun close(channelId: String, force: Boolean, onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) {
|
||||
val state = uiState as? GroupLightningWalletUIState.Opened ?: return
|
||||
act(onSession, onFailure) { lightningRepository.proposeClose(state.localChatRoom, activeUserPublicKey, state.wallet, channelId, force) }
|
||||
}
|
||||
|
||||
private fun act(onSession: (String) -> Unit, onFailure: () -> Unit, propose: suspend () -> FrostSigningSession) {
|
||||
if (isActionPending.value) return
|
||||
isActionPending.value = true
|
||||
|
||||
Reference in new issue
Block a user