From b770b07472f07a4ada0025e702c1334854a6279e Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 18:53:43 +0200 Subject: [PATCH] feat(lightning): the group sweeps closed channels into its onchain wallet (Phase 13, part 2) The operator's snapshot now lists what closing channels pay to the group's basepoints, found by the fork's `GroupHeldOutputs`. Any member proposes a sweep from the wallet screen. A sweep is a FROST session of its own subject, `SWEEP`: every input is a taproot script-path spend, signed under the leaf key each member derives from its own basepoints, and every output must be a receive address of the onchain wallet. `GroupSweep.check` refuses anything else. A signed sweep is a `GroupTransaction` row like a spend, so the watcher sends it, again every ten minutes until the network accepts it once the delay is over. The approval screen, the proposal list and the onchain wallet's history say what a sweep is. A four-device test sweeps a to_remote and a to_local output built with lightning-kmp's own scripts, and the interpreter accepts the result. Splicing out is not built; the plan's doc says why. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 6 + .../model/types/FrostSigningSubject.kt | 8 + .../DatabaseFrostSigningRepository.kt | 8 + .../DatabaseGroupLightningRepository.kt | 8 + .../compose/managers/FrostSigningManager.kt | 253 ++++++++++++++++++ .../compose/managers/GroupLightningNode.kt | 33 ++- .../compose/managers/GroupLightningSweeps.kt | 49 ++++ .../compose/nostr/frost/FrostSigningEvents.kt | 13 + .../repository/FrostSigningRepository.kt | 4 + .../repository/GroupLightningRepository.kt | 7 + .../bennu/compose/text/ProposedSpend.kt | 13 + .../ui/composable/FrostSigningScreen.kt | 111 +++++--- .../composable/GroupLightningWalletScreen.kt | 17 +- .../ui/composable/GroupWalletScreen.kt | 2 +- .../ui/view/model/ChatMessageListViewModel.kt | 2 + .../ui/view/model/FrostSigningViewModel.kt | 6 + .../model/GroupLightningWalletViewModel.kt | 10 +- .../ui/view/model/GroupWalletViewModel.kt | 5 +- .../ui/view/model/ProposalListViewModel.kt | 4 +- .../ui/view/state/FrostSigningUIState.kt | 3 + .../view/state/GroupLightningWalletUIState.kt | 3 + .../ui/view/state/GroupWalletUIState.kt | 5 +- .../compose/wallet/lightning/GroupSweep.kt | 194 ++++++++++++++ .../compose/wallet/lightning/WalletWire.kt | 2 + .../bennu/compose/managers/FakeGroupNode.kt | 3 + .../managers/GroupLightningSweepJvmTest.kt | 133 +++++++++ .../GroupLightningWalletViewModelJvmTest.kt | 3 + docs/group-lightning-wallet.md | 6 +- 28 files changed, 863 insertions(+), 48 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningSweeps.kt create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupSweep.kt create mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningSweepJvmTest.kt diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 5e175135..8c1169c9 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -760,4 +760,10 @@ Close to the onchain wallet Force close Channel actions + This device could not check this sweep, so it cannot be signed here. + Sweep into the group's onchain wallet + Spends %1$s outputs a closed Lightning channel left the group. Every one goes to the group's own onchain wallet. + %1$s sats wait in closed channels + They are the group's alone, under its own keys. Sweeping asks the group to sign moving them to the onchain wallet; the sweep is sent once the channel's delay is over. + Sweep into the onchain wallet diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/types/FrostSigningSubject.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/types/FrostSigningSubject.kt index d1604fbf..5165b3b8 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/types/FrostSigningSubject.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/types/FrostSigningSubject.kt @@ -17,4 +17,12 @@ enum class FrostSigningSubject { * account the coin it spends is. */ TRANSACTION, + + /** + * A sweep of what a closed Lightning channel left the group into its onchain + * wallet: each item is one input, a taproot script-path spend under a key + * derived from the group's basepoints, its message that input's sighash. + * See `GroupSweep`. + */ + SWEEP, } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt index d469f05b..b90a59f8 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.database.repository import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.OutPoint import fr.acinq.bitcoin.psbt.Psbt @@ -155,6 +156,13 @@ class DatabaseFrostSigningRepository( null } + override suspend fun checkedSweep(sessionId: String): GroupSweep.Checked? = try { + FrostSigningManager.checkedSweep(database, sessionId) + } catch (e: Throwable) { + logger.e("Error checking the sweep of $sessionId", e) + null + } + override suspend fun reservedOutPoints(chatRoomId: String): Set = try { FrostSigningManager.reservedOutPoints(database, chatRoomId) } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt index 8a8a078e..61f3380c 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt @@ -22,6 +22,8 @@ import com.machankura.bennu.compose.nostr.lightning.GroupLightningEvents import com.machankura.bennu.compose.repository.GroupLightningRepository import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.Chain +import com.machankura.bennu.compose.managers.GroupLightningSweeps +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map @@ -66,6 +68,12 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr 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 suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List = + GroupLightningSweeps.unswept(database, chatRoomId, report) + + override suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession = + GroupLightningSweeps.propose(database, localChatRoom, userPublicKey, wallet, inputs) + override fun observeCeremony(sessionId: String): Flow = database.icebergKeySessionDao().observeSessionById(sessionId) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt index b56c419d..0f9b9e63 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt @@ -14,6 +14,8 @@ import fr.acinq.bitcoin.crypto.frost.TweakCache import fr.acinq.bitcoin.psbt.Psbt import fr.acinq.secp256k1.Hex import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.network.serialization.CommonJson +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import com.vitorpamplona.quartz.nip01Core.core.Kind @@ -407,6 +409,14 @@ object FrostSigningManager { sessionId = sessionId, userPublicKey = userPublicKey ) + } else if (innerEvent.kind == FrostSigningEvents.TRANSACTION_PROPOSAL && FrostSigningEvents.parseSweep(innerEvent.tags) != null) { + acceptSweepProposal( + database = database, + localChatRoom = localChatRoom, + innerEvent = innerEvent, + sessionId = sessionId, + userPublicKey = userPublicKey + ) } else if (innerEvent.kind == FrostSigningEvents.TRANSACTION_PROPOSAL) { acceptSpendProposal( database = database, @@ -840,6 +850,226 @@ object FrostSigningManager { return transaction to GroupWalletDerivation.account(thresholdPublicKey, chain, transaction.account) } + /** + * Opens a sweep of what a closed Lightning channel left the group into the + * onchain wallet at [account] on [chain], after every check [GroupSweep.check] + * makes. Like a spend, proposing it is agreeing to it. + */ + suspend fun proposeSweep( + database: BennuDatabase, + localChatRoom: LocalChatRoom, + userPublicKey: HexKey, + sweep: GroupSweep.Sweep, + chain: Chain, + account: Long = 0L, + ): FrostSigningSession { + val chatRoomId = localChatRoom.chatRoom.id + val ceremony = completedKey(database, chatRoomId) + ?: throw IllegalStateException("This group has no shared key to sign with") + val thresholdPublicKey = ceremony.thresholdPublicKey + ?: throw IllegalStateException("Ceremony ${ceremony.id} holds no threshold key") + val signerId = signerIdOf(database, ceremony, userPublicKey) + ?: throw IllegalStateException("This device is not a participant in ceremony ${ceremony.id}") + val checked = when (val result = checkSweep(database, chatRoomId, thresholdPublicKey, chain, account, sweep)) { + is GroupSweep.Result.Ok -> result.checked + is GroupSweep.Result.Refused -> throw IllegalArgumentException("This sweep ${result.reason}") + } + + val session = FrostSigningSession( + id = RandomInstance.bytes(32).toHex(), + chatRoomId = chatRoomId, + coordinatorPublicKey = userPublicKey, + userPublicKey = userPublicKey, + dkgSessionId = ceremony.id, + threshold = ceremony.threshold, + participantCount = ceremony.participantCount, + signerId = signerId, + derivationPath = null, + subject = FrostSigningSubject.SWEEP, + signApprovedAt = Clock.System.now() + ) + writeSweep(database, session, checked, chain, account) + announceStarted(database, session) + logger.i("Proposing sweep ${session.id}: ${checked.inputs.size} output(s), ${checked.amount.sat} sats to the wallet, ${checked.fee.sat} sats fee") + + broadcast( + database = database, + localChatRoom = localChatRoom, + session = session, + kind = FrostSigningEvents.TRANSACTION_PROPOSAL, + content = CommonJson.encodeToString(GroupSweep.Sweep.serializer(), sweep), + includeKey = true, + extraTags = FrostSigningEvents.sweepTags(GroupWalletStatementEvent.chainName(chain), account, sweep.wallet) + ) + advance(database, localChatRoom, session.id) + return session + } + + /** + * Records a proposed sweep, after every check [GroupSweep.check] makes, against + * the group's own basepoints and the onchain wallet the room opened. Write-once, + * as a spend is. + */ + private suspend fun acceptSweepProposal( + database: BennuDatabase, + localChatRoom: LocalChatRoom, + innerEvent: Event, + sessionId: String, + userPublicKey: HexKey + ): FrostSigningSession? { + val sweep = decodeSweep(innerEvent.content) + database.frostSigningSessionDao().getSessionById(sessionId)?.let { existing -> + val stored = database.groupTransactionDao().getBySessionId(sessionId)?.let { decodeSweep(it.psbt) } + if (existing.subject != FrostSigningSubject.SWEEP || stored == null || stored != sweep) { + logger.w("Session $sessionId re-proposed with a different sweep; ignoring") + } + return existing + } + if (sweep == null) { + logger.w("Sweep proposal $sessionId does not carry a sweep; dropping") + return null + } + val key = FrostSigningEvents.parseKey(innerEvent.tags) + ?.let { database.dkgSessionDao().getSessionById(it) } + ?.takeIf { it.stage == DkgRitualStage.COMPLETE } + val thresholdPublicKey = key?.thresholdPublicKey + if (key == null || thresholdPublicKey == null) { + logger.w("Sweep proposal $sessionId names a key this device does not hold; dropping") + return null + } + val signerId = signerIdOf(database, key, userPublicKey) ?: run { + logger.w("Sweep proposal $sessionId is for a ceremony this device did not take part in; dropping") + return null + } + val (chainName, account) = FrostSigningEvents.parseWallet(innerEvent.tags) ?: run { + logger.w("Sweep proposal $sessionId names no wallet; dropping") + return null + } + val chain = GroupWalletStatementEvent.chainNamed(chainName) ?: return null + if (FrostSigningEvents.parseSweep(innerEvent.tags) != sweep.wallet) { + logger.w("Sweep proposal $sessionId names one Lightning wallet in its tags and another in its content; dropping") + return null + } + val checked = when (val result = checkSweep(database, localChatRoom.chatRoom.id, thresholdPublicKey, chain, account, sweep)) { + is GroupSweep.Result.Ok -> result.checked + is GroupSweep.Result.Refused -> { + logger.w("Sweep proposal $sessionId ${result.reason}; dropping") + return null + } + } + val session = FrostSigningSession( + id = sessionId, + chatRoomId = localChatRoom.chatRoom.id, + coordinatorPublicKey = innerEvent.pubKey, + userPublicKey = userPublicKey, + dkgSessionId = key.id, + threshold = key.threshold, + participantCount = key.participantCount, + signerId = signerId, + derivationPath = null, + subject = FrostSigningSubject.SWEEP, + ) + writeSweep(database, session, checked, chain, account) + announceStarted(database, session) + logger.i("Recorded sweep $sessionId: ${checked.amount.sat} sats to the wallet, ${checked.fee.sat} sats fee; awaiting approval") + announceApprovalNeeded(database, session) + replayStoredMessages(database, localChatRoom, session) + return session + } + + /** + * [sweep] checked against the Lightning wallet the room agreed for its + * network and number, whose basepoints derive from [thresholdPublicKey], and + * the onchain wallet at [account] it must pay. + */ + private suspend fun checkSweep(database: BennuDatabase, chatRoomId: String, thresholdPublicKey: HexKey, chain: Chain, account: Long, sweep: GroupSweep.Sweep): GroupSweep.Result { + GroupLightningWalletManager.walletFor(database, chatRoomId, chain, sweep.wallet) + ?: return GroupSweep.Result.Refused("sweeps a Lightning wallet the group has not opened") + val onchain = GroupWalletManager.walletFor(database, chatRoomId, thresholdPublicKey, chain, account) + ?: return GroupSweep.Result.Refused("pays an onchain wallet the group has not opened") + return GroupSweep.check(sweep, GroupLightningDerivation.basepoints(thresholdPublicKey, chain, sweep.wallet), onchain.account) + } + + private suspend fun writeSweep(database: BennuDatabase, session: FrostSigningSession, checked: GroupSweep.Checked, chain: Chain, account: Long) { + database.frostSigningSessionDao().upsert(session) + database.frostSigningSessionDao().upsertItems( + checked.inputs.map { input -> + FrostSigningItem( + sessionId = session.id, + itemIndex = input.index, + unsignedEventJson = """{"input":${input.index}}""", + eventId = input.sighash.toHex(), + nonceRandom = RandomInstance.bytes(32).toHex(), + inputIndex = input.index, + ) + } + ) + // The row a spend keeps, so the watcher broadcasts the sweep like any of the group's + // transactions; its PSBT column holds the sweep as proposed instead. + database.groupTransactionDao().insertIfAbsent( + GroupTransaction( + frostSigningSessionId = session.id, + chatRoomId = session.chatRoomId, + chain = GroupWalletStatementEvent.chainName(chain), + account = account, + psbt = CommonJson.encodeToString(GroupSweep.Sweep.serializer(), checked.sweep), + txid = checked.tx.txid.toString(), + ) + ) + } + + private fun decodeSweep(content: String): GroupSweep.Sweep? = + runCatching { CommonJson.decodeFromString(GroupSweep.Sweep.serializer(), content) }.getOrNull() + + /** The sweep a sweep session signs, checked again from its row, or null. */ + private suspend fun sweepOf(database: BennuDatabase, session: FrostSigningSession, thresholdPublicKey: HexKey): GroupSweep.Checked? { + val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null + val sweep = decodeSweep(transaction.psbt) ?: return null + val chain = GroupWalletStatementEvent.chainNamed(transaction.chain) ?: return null + return (checkSweep(database, session.chatRoomId, thresholdPublicKey, chain, transaction.account, sweep) as? GroupSweep.Result.Ok)?.checked + } + + /** The sweep [sessionId] signs, as the approval screen shows it, or null for any other session. */ + suspend fun checkedSweep(database: BennuDatabase, sessionId: String): GroupSweep.Checked? { + val session = database.frostSigningSessionDao().getSessionById(sessionId) ?: return null + if (session.subject != FrostSigningSubject.SWEEP) return null + val thresholdPublicKey = database.dkgSessionDao().getSessionById(session.dkgSessionId)?.thresholdPublicKey ?: return null + return sweepOf(database, session, thresholdPublicKey) + } + + /** A sweep's signatures, each checked under its leaf key, witnessed, and run through the interpreter. */ + private suspend fun completeSweep(database: BennuDatabase, session: FrostSigningSession, items: List) { + val thresholdPublicKey = database.dkgSessionDao().getSessionById(session.dkgSessionId)?.thresholdPublicKey + ?: throw IllegalStateException("The ceremony this sweep signs under is gone") + val checked = sweepOf(database, session, thresholdPublicKey) ?: throw IllegalStateException("This sweep no longer checks out") + val signatures = items.mapIndexed { index, item -> + val input = checked.inputs[index] + val signature = ByteVector64(item.signature!!) + if (!Crypto.verifySignatureSchnorr(input.sighash, signature, input.leafKey)) { + throw IllegalStateException("The aggregated signature for input $index does not verify under its leaf key") + } + signature + } + val signed = GroupSweep.witnessed(checked.tx, checked.inputs, signatures) + signed.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + update(database, session) { it.copy(stage = FrostSigningStage.COMPLETE) } + try { + val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return + database.groupTransactionDao().upsert(transaction.copy(signedTransaction = Hex.encode(Transaction.write(signed)))) + } catch (e: Throwable) { + logger.e("Signed sweep ${session.id} but could not record it", e) + } + announce( + database = database, + session = session, + messageType = ChatMessage.TYPE_FROST_COMPLETE, + content = "The group signed a sweep of ${checked.amount.sat} sats from its Lightning wallet into its onchain wallet, " + + "with ${checked.fee.sat} sats in fees. It is sent once its delay is over.", + actor = session.coordinatorPublicKey + ) + logger.i("Sweep ${session.id} complete: txid ${signed.txid}") + } + /** * The spend a transaction session signs, checked again from its stored PSBT, * or null for an event session or one whose spend no longer checks out. @@ -1368,6 +1598,10 @@ object FrostSigningManager { FrostSigningSubject.TRANSACTION -> spendDerivations(database, session, thresholdPublicKey, items) ?.map { it.cache } ?: throw IllegalStateException("The coins this transaction spends no longer derive under the group's wallet") + + FrostSigningSubject.SWEEP -> sweepOf(database, session, thresholdPublicKey) + ?.inputs?.map { it.cache } + ?: throw IllegalStateException("The outputs this sweep spends no longer derive under the group's basepoints") } val messages = items.map { ByteVector(it.eventId.hexToByteArray()) } @@ -1557,6 +1791,10 @@ object FrostSigningManager { completeSpend(database, session, items) return } + if (session.subject == FrostSigningSubject.SWEEP) { + completeSweep(database, session, items) + return + } // Every signature is checked before any event is applied. A batch is // all-or-nothing, so a bad one anywhere has to fail the session rather @@ -2542,6 +2780,21 @@ object FrostSigningManager { FrostSigningEvents.walletTags(transaction.chain, transaction.account) ) } + + // The sweep as proposed, which the transaction row keeps where a spend keeps its PSBT. + FrostSigningSubject.SWEEP -> { + val transaction = database.groupTransactionDao().getBySessionId(sessionId) + val sweep = transaction?.let { decodeSweep(it.psbt) } + if (transaction == null || sweep == null) { + logger.w("Session $sessionId: no sweep on file; nothing to resend") + return false + } + Triple( + FrostSigningEvents.TRANSACTION_PROPOSAL, + transaction.psbt, + FrostSigningEvents.sweepTags(transaction.chain, transaction.account, sweep.wallet) + ) + } } logger.i( 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 f42ef913..838a3470 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 @@ -6,6 +6,7 @@ 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.GroupSweep import com.machankura.bennu.compose.wallet.lightning.WalletWire import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.ByteVector @@ -25,7 +26,10 @@ 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.GroupHeldOutputs import fr.acinq.lightning.channel.states.ChannelStateWithCommitments +import fr.acinq.lightning.channel.states.Closed +import fr.acinq.lightning.channel.states.Closing import fr.acinq.lightning.crypto.RemoteIcebergFundingSigner import fr.acinq.lightning.db.Databases import fr.acinq.lightning.db.LightningIncomingPayment @@ -98,6 +102,8 @@ class GroupLightningNode( suspend fun close(channelId: String, scriptPubKey: ByteVector) /** Publishes our own commitment of [channelId]. */ suspend fun forceClose(channelId: String) + /** The outputs closing channels pay to the group's basepoints, for the group to sweep. */ + fun heldOutputs(): List } sealed class State { @@ -112,7 +118,7 @@ class GroupLightningNode( private var peer: PeerHandle? = null private var transport: GroupIcebergTransport? = null private var watching: Job? = null - private var lastReported: Pair, List>? = null + private var lastReported: Triple, List, List>? = null private var lastReportedAt: kotlin.time.Instant? = null /** Starts the node if this device may run it now; otherwise says why not. */ @@ -178,13 +184,14 @@ class GroupLightningNode( internal suspend fun report(term: Long, force: Boolean = false) { val handle = peer ?: return val now = now() - val current = handle.channels() to handle.payments() + val current = Triple(handle.channels(), handle.payments(), handle.heldOutputs()) val due = force || current != lastReported || 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, channels = current.first, payments = current.second.takeLast(REPORTED_PAYMENTS), assignments = transport?.assignments().orEmpty(), + heldOutputs = current.third, ) GroupLightningReports.publishSnapshot(database, localChatRoom, userPublicKey, snapshot) lastReported = current @@ -347,6 +354,28 @@ class GroupLightningNode( override suspend fun close(channelId: String, scriptPubKey: ByteVector) { peer.mutualClose(ByteVector32(channelId), scriptPubKey, peer.onChainFeeratesFlow.value?.mutualCloseFeerate ?: FeeratePerKw(FeeratePerByte(Satoshi(2)))) } + override fun heldOutputs(): List = peer.channelsFlow.value.values.mapNotNull { state -> + when (state) { + is Closing -> state + is Closed -> state.state + else -> null + } + }.flatMap { closing -> + val latest = closing.commitments.latest + val keys = configuration.keyManager.channelKeys(closing.commitments.channelParams.localParams.fundingKeyPath) + buildList { + closing.localCommitPublished?.let { published -> + GroupHeldOutputs.inLocalCommit(keys, latest, published.commitTx)?.let(::add) + // Our HTLC transactions, once they spend our commitment: their delayed outputs are the group's too. + published.irrevocablySpent.values.filter { tx -> tx.txIn.any { it.outPoint.txid == published.commitTx.txid } } + .forEach { htlcTx -> GroupHeldOutputs.inHtlcTx(keys, latest, htlcTx)?.let(::add) } + } + closing.remoteCommitPublished?.let { GroupHeldOutputs.inRemoteCommit(keys, latest, latest.remoteCommit.remotePerCommitmentPoint, it.commitTx)?.let(::add) } + closing.nextRemoteCommitPublished?.let { published -> + latest.nextRemoteCommit?.let { next -> GroupHeldOutputs.inRemoteCommit(keys, latest, next.remotePerCommitmentPoint, published.commitTx)?.let(::add) } + } + } + }.map(GroupSweep::inputOf).distinctBy { it.txid to it.index } 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/managers/GroupLightningSweeps.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningSweeps.kt new file mode 100644 index 00000000..82cd676a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningSweeps.kt @@ -0,0 +1,49 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.database.model.types.FrostSigningSubject +import com.machankura.bennu.compose.network.serialization.CommonJson +import com.machankura.bennu.compose.wallet.lightning.GroupSweep +import com.vitorpamplona.quartz.nip01Core.core.HexKey + +/** + * Which of what closed channels left the group is still to be swept, and the sweep that moves it + * (`docs/group-lightning-wallet.md`, Phase 13). The outputs come from the operator's snapshot; the + * sweep is checked by every member as [GroupSweep] says, so a snapshot that lies about an output only + * makes a sweep nobody can mine. + */ +object GroupLightningSweeps { + /** + * The feerate a sweep pays, in sats per virtual byte. A sweep is never urgent -- what it spends is + * the group's alone -- so it pays little, and the watcher keeps sending it until it confirms. + */ + const val FEERATE_SAT_PER_VBYTE: Long = 2 + + /** The held outputs [report] lists that no open or finished sweep in the room already spends. */ + suspend fun unswept(database: BennuDatabase, chatRoomId: String, report: GroupLightningReports.Report?): List { + val outputs = report?.snapshot?.heldOutputs.orEmpty() + if (outputs.isEmpty()) return outputs + val taken = database.groupTransactionDao().getByChatRoomId(chatRoomId) + .filter { row -> + val session = database.frostSigningSessionDao().getSessionById(row.frostSigningSessionId) + session?.subject == FrostSigningSubject.SWEEP && session.stage != FrostSigningStage.FAILED + } + .mapNotNull { runCatching { CommonJson.decodeFromString(GroupSweep.Sweep.serializer(), it.psbt) }.getOrNull() } + .flatMap { sweep -> sweep.inputs.map { it.txid to it.index } } + .toSet() + return outputs.filter { (it.txid to it.index) !in taken } + } + + /** Proposes sweeping [inputs] into the onchain wallet [wallet] closes to, at its first receive address. */ + suspend fun propose(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession { + val statement = wallet.statement + val onchain = GroupWalletManager.walletFor(database, localChatRoom.chatRoom.id, statement.chain, statement.onchainAccount) + ?: throw IllegalStateException("The onchain wallet this Lightning wallet closes to is not open") + val sweep = GroupSweep.build(statement.wallet, inputs, onchain.account, receiveIndex = 0, feeratePerVbyte = FEERATE_SAT_PER_VBYTE) + ?: throw IllegalArgumentException("There is too little to sweep to pay its fee") + return FrostSigningManager.proposeSweep(database, localChatRoom, userPublicKey, sweep, statement.chain, statement.onchainAccount) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt index 28db33d5..c879f8ef 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/frost/FrostSigningEvents.kt @@ -168,6 +168,19 @@ object FrostSigningEvents { fun walletTags(chain: String, account: Long): Array> = arrayOf(arrayOf(CHAIN_TAG, chain), arrayOf(ACCOUNT_TAG, account.toString())) + private const val SWEEP_TAG = "sweep" + + /** + * The tags of a [TRANSACTION_PROPOSAL] that is a sweep from the Lightning wallet [lightningWallet] into + * the onchain wallet: the wallet's tags, and which Lightning wallet the outputs are from. + */ + fun sweepTags(chain: String, account: Long, lightningWallet: Long): Array> = + walletTags(chain, account) + arrayOf(arrayOf(SWEEP_TAG, lightningWallet.toString())) + + /** The Lightning wallet a sweep proposal sweeps from, or null for an ordinary spend. */ + fun parseSweep(tags: Array>): Long? = + tags.firstOrNull { it.size >= 2 && it[0] == SWEEP_TAG }?.get(1)?.toLongOrNull() + /** The network and account a [TRANSACTION_PROPOSAL] names, or null when it names either badly. */ fun parseWallet(tags: Array>): Pair? { val chain = tags.firstOrNull { it.size >= 2 && it[0] == CHAIN_TAG }?.get(1) ?: return null diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt index 34f0b0ef..548c2283 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt @@ -3,6 +3,7 @@ package com.machankura.bennu.compose.repository import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.managers.GroupWalletDerivation import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.OutPoint import fr.acinq.bitcoin.psbt.Psbt @@ -244,6 +245,9 @@ interface FrostSigningRepository { /** The spend a transaction session signs, checked again; null for anything else. */ suspend fun checkedSpend(sessionId: String): GroupSpend.Checked? + /** The sweep a sweep session signs, checked again; null for anything else. */ + suspend fun checkedSweep(sessionId: String): GroupSweep.Checked? = null + /** The coins the room's open spends are already spending. */ suspend fun reservedOutPoints(chatRoomId: String): Set diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt index fe98789a..017d3ac4 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt @@ -13,6 +13,7 @@ import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.database.model.types.IcebergApprovalStep import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.Chain +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import kotlinx.coroutines.flow.Flow /** @@ -76,4 +77,10 @@ interface GroupLightningRepository { /** 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 + + /** What closed channels left the group that no sweep spends yet, from [report]. */ + suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List + + /** Proposes sweeping [inputs] into the onchain wallet. */ + suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt index a465b636..feeb6953 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt @@ -1,6 +1,7 @@ package com.machankura.bennu.compose.text import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import fr.acinq.bitcoin.Bitcoin import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.Chain @@ -24,6 +25,18 @@ object ProposedSpend { fun addressOf(script: ByteVector, chain: Chain): String = Bitcoin.addressFromPublicKeyScript(chain.chainHash, script.toByteArray()).right ?: script.toHex() + /** A sweep from the Lightning wallet: what reaches the onchain wallet, which is all a member is agreeing to. */ + fun summarize(sweep: GroupSweep.Checked): ProposedEvent.Summary = + ProposedEvent.Summary( + label = "Sweep into the group's onchain wallet", + detail = "${sweep.amount.grouped()} sats a closed Lightning channel left the group, after ${sweep.fee.grouped()} sats in fees" + ) + + val UNREADABLE_SWEEP = ProposedEvent.Summary( + label = "Sweep into the group's onchain wallet", + detail = "A sweep this device cannot check" + ) + /** What a summary says for a spend this device cannot check: nothing a member could sign on. */ val UNREADABLE = ProposedEvent.Summary( label = "Spend from the group's wallet", diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/FrostSigningScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/FrostSigningScreen.kt index 38ef3f40..d37c92b9 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/FrostSigningScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/FrostSigningScreen.kt @@ -1,16 +1,5 @@ package com.machankura.bennu.compose.ui.composable -import com.machankura.bennu.compose.wallet.GroupSpend -import com.machankura.bennu.compose.database.model.types.FrostSigningSubject -import com.machankura.bennu.compose.text.ProposedSpend -import com.machankura.bennu.compose.text.grouped -import bennu.composeapp.generated.resources.this_spend_could_not_be_checked -import bennu.composeapp.generated.resources.spend_from_the_group_s_wallet -import bennu.composeapp.generated.resources.s_sats -import bennu.composeapp.generated.resources.s_sats_back_to_the_group_as_change -import bennu.composeapp.generated.resources.fee_s_sats_at_s_sats_per_byte -import bennu.composeapp.generated.resources.spends_s_of_the_group_s_coins -import bennu.composeapp.generated.resources.signed_by_the_group_any_member_can_send_it import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row @@ -40,6 +29,7 @@ import androidx.compose.material3.Icon import androidx.compose.material3.ListItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton @@ -53,50 +43,64 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.core.HexKey -import com.machankura.bennu.compose.database.model.ChatRoom -import com.machankura.bennu.compose.database.model.FrostSigningSession -import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom -import com.machankura.bennu.compose.database.model.types.FrostSigningStage -import com.machankura.bennu.compose.managers.FrostSigningManager -import com.machankura.bennu.compose.repository.ChatRepository -import com.machankura.bennu.compose.repository.FrostSigningRepository -import com.machankura.bennu.compose.text.ProposedEvent -import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar -import com.machankura.bennu.compose.ui.theme.BennuTheme -import com.machankura.bennu.compose.ui.view.model.FrostSigningViewModel -import com.machankura.bennu.compose.ui.view.state.FrostSigningUIState -import com.machankura.bennu.compose.ui.theme.spacing -import com.machankura.bennu.compose.ui.composable.widgets.Decorative import bennu.composeapp.generated.resources.Res -import org.jetbrains.compose.resources.stringResource import bennu.composeapp.generated.resources.ask_again import bennu.composeapp.generated.resources.asked_again import bennu.composeapp.generated.resources.asked_again_recently import bennu.composeapp.generated.resources.asked_again_to_sign import bennu.composeapp.generated.resources.declined_to_sign +import bennu.composeapp.generated.resources.don_t_sign +import bennu.composeapp.generated.resources.events_signed_together import bennu.composeapp.generated.resources.everyone_has_answered_this_session import bennu.composeapp.generated.resources.everyone_has_signed_this_session +import bennu.composeapp.generated.resources.fee_s_sats_at_s_sats_per_byte +import bennu.composeapp.generated.resources.has_not_taken_part_yet +import bennu.composeapp.generated.resources.members import bennu.composeapp.generated.resources.members_have_not_answered import bennu.composeapp.generated.resources.one_member_has_not_answered import bennu.composeapp.generated.resources.one_signer_has_not_signed -import bennu.composeapp.generated.resources.signers_have_not_signed -import bennu.composeapp.generated.resources.don_t_sign -import bennu.composeapp.generated.resources.has_not_taken_part_yet -import bennu.composeapp.generated.resources.members import bennu.composeapp.generated.resources.read_to_the_end_of_the_list_to_sign import bennu.composeapp.generated.resources.ready_to_sign +import bennu.composeapp.generated.resources.s_sats +import bennu.composeapp.generated.resources.s_sats_back_to_the_group_as_change import bennu.composeapp.generated.resources.sign import bennu.composeapp.generated.resources.sign_with_the_group_s_key +import bennu.composeapp.generated.resources.signed_by_the_group_any_member_can_send_it import bennu.composeapp.generated.resources.signed_their_part -import bennu.composeapp.generated.resources.events_signed_together -import androidx.compose.material3.SnackbarHost +import bennu.composeapp.generated.resources.signers_have_not_signed +import bennu.composeapp.generated.resources.spend_from_the_group_s_wallet +import bennu.composeapp.generated.resources.spends_s_of_the_group_s_coins +import bennu.composeapp.generated.resources.sweep_into_the_group_s_onchain_wallet +import bennu.composeapp.generated.resources.sweeps_s_outputs_a_closed_channel_left_the_group +import bennu.composeapp.generated.resources.this_spend_could_not_be_checked +import bennu.composeapp.generated.resources.this_sweep_could_not_be_checked +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.database.model.types.FrostSigningSubject +import com.machankura.bennu.compose.managers.FrostSigningManager +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.text.ProposedEvent +import com.machankura.bennu.compose.text.ProposedSpend +import com.machankura.bennu.compose.text.grouped +import com.machankura.bennu.compose.ui.composable.widgets.Decorative import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState -import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton -import com.machankura.bennu.compose.ui.theme.readableContent +import com.machankura.bennu.compose.ui.composable.widgets.profile.ProfileAvatar +import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier +import com.machankura.bennu.compose.ui.theme.BennuTheme import com.machankura.bennu.compose.ui.theme.ConformancePreviews +import com.machankura.bennu.compose.ui.theme.readableContent +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.FrostSigningViewModel +import com.machankura.bennu.compose.ui.view.state.FrostSigningUIState +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.lightning.GroupSweep +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import org.jetbrains.compose.resources.stringResource /** * One signing session, and the member's decision about it. @@ -189,7 +193,8 @@ fun FrostSigningScreen( val session = state.session ?: return@Scaffold Loading(padding) val isSpend = session.subject == FrostSigningSubject.TRANSACTION - val proposed = if (isSpend) emptyList() else frostSigningViewModel.proposedEvents(state.items) + val isSweep = session.subject == FrostSigningSubject.SWEEP + val proposed = if (isSpend || isSweep) emptyList() else frostSigningViewModel.proposedEvents(state.items) // Every event of the batch has to be readable before any of it can // be signed. A member cannot check what they cannot see, and a @@ -198,13 +203,15 @@ fun FrostSigningScreen( // device has checked it, every input accounted for. val readable = state.items.isNotEmpty() && if (isSpend) { state.spend?.inputs?.size == state.items.size + } else if (isSweep) { + state.sweep?.inputs?.size == state.items.size } else { proposed.size == state.items.size } // What has to be scrolled past before signing: each event of a // batch, or each output of a spend. - val listed = if (isSpend) state.spend?.outputs?.size ?: 0 else proposed.size + val listed = if (isSpend) state.spend?.outputs?.size ?: 0 else if (isSweep) 1 else proposed.size val scrollState = rememberScrollState() @@ -217,7 +224,11 @@ fun FrostSigningScreen( .padding(MaterialTheme.spacing.space250), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space200) ) { - if (isSpend) WhatIsBeingSpent(state.spend) else WhatIsBeingSigned(proposed, state.items.size) + when { + isSpend -> WhatIsBeingSpent(state.spend) + isSweep -> WhatIsBeingSwept(state.sweep) + else -> WhatIsBeingSigned(proposed, state.items.size) + } HorizontalDivider() @@ -521,6 +532,28 @@ private fun WhatIsBeingSigned(events: List, expected: Int) { * but the coins being spent, which are the group's own and were each checked * against the wallet before this was drawn. */ +/** A sweep: the address it pays, which is the group's own, and what reaches it. */ +@Composable +private fun WhatIsBeingSwept(sweep: GroupSweep.Checked?) { + if (sweep == null) { + Text(text = stringResource(Res.string.this_sweep_could_not_be_checked), color = MaterialTheme.colorScheme.error) + return + } + Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.space200)) { + Text(text = stringResource(Res.string.sweep_into_the_group_s_onchain_wallet), style = MaterialTheme.typography.labelMedium) + Text(text = stringResource(Res.string.s_sats, sweep.amount.grouped()), style = MaterialTheme.typography.titleMedium) + Text( + text = stringResource(Res.string.fee_s_sats_at_s_sats_per_byte, sweep.fee.grouped(), sweep.feeratePerVbyte.toString()), + style = MaterialTheme.typography.bodyMedium + ) + Text( + text = stringResource(Res.string.sweeps_s_outputs_a_closed_channel_left_the_group, sweep.inputs.size.toString()), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } +} + @Composable private fun WhatIsBeingSpent(spend: GroupSpend.Checked?) { if (spend == null) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt index b054bcc7..71cff96d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt @@ -47,6 +47,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow import androidx.lifecycle.viewmodel.compose.viewModel import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.a_closed_channel_s_outputs_go_to_the_onchain_wallet 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 @@ -76,11 +77,13 @@ import bennu.composeapp.generated.resources.run_this_wallet_on_my_device import bennu.composeapp.generated.resources.s_of_s_sats_are_the_group_s import bennu.composeapp.generated.resources.s_sats import bennu.composeapp.generated.resources.s_sats_can_be_received +import bennu.composeapp.generated.resources.s_sats_wait_in_closed_channels import bennu.composeapp.generated.resources.see_the_key_ceremony import bennu.composeapp.generated.resources.send import bennu.composeapp.generated.resources.sent_s_sats_with_a_fee_of_s_sats import bennu.composeapp.generated.resources.signers_needed_s_of_s import bennu.composeapp.generated.resources.step_down +import bennu.composeapp.generated.resources.sweep_into_the_onchain_wallet import bennu.composeapp.generated.resources.the_group_is_making_its_lightning_wallet_key import bennu.composeapp.generated.resources.the_operator_hasn_t_reported_the_wallet_yet import bennu.composeapp.generated.resources.the_operator_s_device_runs_the_node @@ -221,6 +224,7 @@ fun GroupLightningWalletScreen( 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) }) }, + onSweep = { viewModel.sweep(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) }) }, @@ -231,7 +235,7 @@ fun GroupLightningWalletScreen( } @Composable -private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> Unit, onSend: () -> Unit, onClose: (channelId: String, force: Boolean) -> 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, onSweep: () -> 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) @@ -242,6 +246,17 @@ private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState. verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), ) { item { Balance(state.report, onReceive = onReceive.takeIf { state.operator?.publicKey != null }, onSend = onSend.takeIf { state.operator?.publicKey != null }) } + if (state.unswept.isNotEmpty()) { + item { + Card(modifier = Modifier.fillMaxWidth()) { + Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text(stringResource(Res.string.s_sats_wait_in_closed_channels, Satoshi(state.unswept.sumOf { it.amountSat }).grouped()), style = MaterialTheme.typography.titleMedium) + Text(stringResource(Res.string.a_closed_channel_s_outputs_go_to_the_onchain_wallet), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Button(onClick = onSweep, enabled = !isPending) { Text(stringResource(Res.string.sweep_into_the_onchain_wallet)) } + } + } + } + } 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, onClose = { force: Boolean -> onClose(it.channel.channelId, force) }.takeIf { !isPending }) } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt index 2a4c1d2a..c77bfd1a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt @@ -471,7 +471,7 @@ private fun SpendRowCard( ListItem( headlineContent = { Text( - text = (row.spend?.let { ProposedSpend.summarize(it, chain) } ?: ProposedSpend.UNREADABLE).detail, + text = (row.spend?.let { ProposedSpend.summarize(it, chain) } ?: row.sweep?.let(ProposedSpend::summarize) ?: ProposedSpend.UNREADABLE).detail, maxLines = 2, overflow = TextOverflow.Ellipsis, ) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt index 31fbbd42..3b9e247f 100755 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatMessageListViewModel.kt @@ -234,6 +234,8 @@ class ChatMessageListViewModel( // to say what kind of thing is waiting, and the // signing screen is where the spend is checked. ProposedSpend.UNREADABLE.copy(detail = "") + } else if (local.session.subject == FrostSigningSubject.SWEEP) { + ProposedSpend.UNREADABLE_SWEEP.copy(detail = "") } else { local.items.firstNotNullOfOrNull { item -> Event.fromJsonOrNull(item.unsignedEventJson) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/FrostSigningViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/FrostSigningViewModel.kt index 871e540c..885c4968 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/FrostSigningViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/FrostSigningViewModel.kt @@ -1,6 +1,7 @@ package com.machankura.bennu.compose.ui.view.model import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import com.machankura.bennu.compose.database.model.types.FrostSigningSubject import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue @@ -90,6 +91,9 @@ class FrostSigningViewModel( if (session?.subject == FrostSigningSubject.TRANSACTION && checkedSpend == null) { checkedSpend = frostSigningRepository.checkedSpend(session.id) } + if (session?.subject == FrostSigningSubject.SWEEP && checkedSweep == null) { + checkedSweep = frostSigningRepository.checkedSweep(session.id) + } frostSigningUIState = FrostSigningUIState.Loaded( localChatRoom = localChatRoom, @@ -110,12 +114,14 @@ class FrostSigningViewModel( .toSet(), silent = owed, spend = checkedSpend, + sweep = checkedSweep, ) } } } private var checkedSpend: GroupSpend.Checked? = null + private var checkedSweep: GroupSweep.Checked? = null /** One emission of everything the screen is drawn from -- the fourth flow outgrew `Triple`. */ private data class Observed( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModel.kt index 8f609747..0fb2a7bd 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModel.kt @@ -93,7 +93,8 @@ class GroupLightningWalletViewModel( watching = viewModelScope.launch(Dispatchers.IO) { combine(lightningRepository.observeReport(chatRoomId, chain), lightningRepository.observePayments(chatRoomId, chain)) { report, payments -> report to payments } .collect { (report, payments) -> - (uiState as? GroupLightningWalletUIState.Opened)?.let { uiState = it.copy(report = report, payments = payments) } + val unswept = lightningRepository.unswept(chatRoomId, report) + (uiState as? GroupLightningWalletUIState.Opened)?.let { uiState = it.copy(report = report, payments = payments, unswept = unswept) } } } } @@ -121,6 +122,13 @@ class GroupLightningWalletViewModel( act(onSession, onFailure) { lightningRepository.proposeClose(state.localChatRoom, activeUserPublicKey, state.wallet, channelId, force) } } + /** Proposes sweeping everything closed channels left the group into the onchain wallet. */ + fun sweep(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) { + val state = uiState as? GroupLightningWalletUIState.Opened ?: return + if (state.unswept.isEmpty()) return + act(onSession, onFailure) { lightningRepository.proposeSweep(state.localChatRoom, activeUserPublicKey, state.wallet, state.unswept) } + } + private fun act(onSession: (String) -> Unit, onFailure: () -> Unit, propose: suspend () -> FrostSigningSession) { if (isActionPending.value) return isActionPending.value = true diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt index a2638dbd..c6d95d12 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt @@ -4,6 +4,7 @@ import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.ui.view.state.SpendRow import com.machankura.bennu.compose.ui.view.state.SpendStatus import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import com.machankura.bennu.compose.wallet.GroupSpendBuilder import com.machankura.bennu.compose.wallet.GroupTransactionWatcher import kotlinx.coroutines.flow.combine @@ -105,12 +106,14 @@ class GroupWalletViewModel( /** Checked once per session: the PSBT is write-once, so what it says cannot change. */ private val checkedSpends = mutableMapOf() + private val checkedSweeps = mutableMapOf() private suspend fun rowOf(transaction: GroupTransaction): SpendRow { val sessionId = transaction.frostSigningSessionId val spend = checkedSpends.getOrPut(sessionId) { frostSigningRepository.checkedSpend(sessionId) } + val sweep = if (spend == null) checkedSweeps.getOrPut(sessionId) { frostSigningRepository.checkedSweep(sessionId) } else null val stage = frostSigningRepository.getSessionById(sessionId)?.stage - return SpendRow(transaction = transaction, status = SpendStatus.of(stage, transaction), spend = spend) + return SpendRow(transaction = transaction, status = SpendStatus.of(stage, transaction), spend = spend, sweep = sweep) } /** Sends a signed spend again now. Only worth anything while Electrum has not reported it back. */ diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposalListViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposalListViewModel.kt index 67566e6b..00f37770 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposalListViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ProposalListViewModel.kt @@ -169,12 +169,14 @@ class ProposalListViewModel( ?.let { ProposedSpend.summarize(it, it.account.chain) } ?: ProposedSpend.UNREADABLE ) + } else if (local.session.subject == FrostSigningSubject.SWEEP) { + listOf(frostSigningRepository.checkedSweep(local.session.id)?.let(ProposedSpend::summarize) ?: ProposedSpend.UNREADABLE_SWEEP) } else { events.map { ProposedEvent.summarize(it) } }, // A spend's inputs are not events, and none of them is unreadable on // its own: the spend is checked whole, and says so in its summary. - unreadable = if (local.session.subject == FrostSigningSubject.TRANSACTION) 0 else items.size - events.size, + unreadable = if (local.session.subject != FrostSigningSubject.EVENTS) 0 else items.size - events.size, awaitsYou = FrostSigningManager.isAwaitingApproval(local.session, items), noncesOffered = counted(FrostSigningEvents.NONCE), partialSignatures = counted(FrostSigningEvents.PARTIAL_SIGNATURE), diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/FrostSigningUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/FrostSigningUIState.kt index 305a36e8..1371117d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/FrostSigningUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/FrostSigningUIState.kt @@ -1,6 +1,7 @@ package com.machankura.bennu.compose.ui.view.state import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import com.vitorpamplona.quartz.nip01Core.core.HexKey import kotlin.time.Clock import kotlin.time.Instant @@ -65,6 +66,8 @@ sealed interface FrostSigningUIState { * the screen refuses to let anybody sign. */ val spend: GroupSpend.Checked? = null, + /** The sweep a sweep session signs, as this device checked it; null for anything else. */ + val sweep: GroupSweep.Checked? = null, ): FrostSigningUIState { /** * The members the session can be answered by, as rows to draw. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningWalletUIState.kt index 47544c16..8a2ab370 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningWalletUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningWalletUIState.kt @@ -6,6 +6,7 @@ import com.machankura.bennu.compose.database.model.GroupLightningPaymentRow import com.machankura.bennu.compose.managers.GroupLightningOperatorManager import com.machankura.bennu.compose.managers.GroupLightningReports import com.machankura.bennu.compose.managers.GroupLightningWalletManager +import com.machankura.bennu.compose.wallet.lightning.GroupSweep /** * The group's Lightning wallet screen, through every state a group passes on its way to one: no onchain @@ -35,5 +36,7 @@ sealed class GroupLightningWalletUIState { /** The operator's newest snapshot, or null before the first arrives. */ val report: GroupLightningReports.Report? = null, val payments: List = emptyList(), + /** What closed channels left the group that no sweep spends yet. */ + val unswept: List = emptyList(), ) : GroupLightningWalletUIState() } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt index 6fa85a52..303c923f 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt @@ -5,6 +5,7 @@ import com.machankura.bennu.compose.managers.GroupWalletDerivation import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.wallet.GroupWalletState import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import com.machankura.bennu.compose.database.model.GroupTransaction import com.machankura.bennu.compose.database.model.types.FrostSigningStage @@ -77,8 +78,10 @@ enum class SpendStatus { data class SpendRow( val transaction: GroupTransaction, val status: SpendStatus, - /** The spend, checked again; null where this device cannot check it. */ + /** The spend, checked again; null where this device cannot check it, or for a sweep. */ val spend: GroupSpend.Checked?, + /** A sweep from the Lightning wallet into this one, checked again; null for a spend. */ + val sweep: GroupSweep.Checked? = null, ) { /** Signed, never reported back: the one moment sending it again is worth anything. */ val canSendAgain: Boolean get() = status == SpendStatus.SIGNED diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupSweep.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupSweep.kt new file mode 100644 index 00000000..0d9e8260 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupSweep.kt @@ -0,0 +1,194 @@ +package com.machankura.bennu.compose.wallet.lightning + +import com.machankura.bennu.compose.managers.FrostSigningManager +import com.machankura.bennu.compose.managers.GroupLightningDerivation +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.ByteVector64 +import fr.acinq.bitcoin.OP_CHECKSEQUENCEVERIFY +import fr.acinq.bitcoin.OP_CHECKSIGVERIFY +import fr.acinq.bitcoin.OP_PUSHDATA +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptTree +import fr.acinq.bitcoin.ScriptWitness +import fr.acinq.bitcoin.SigHash +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.bitcoin.XonlyPublicKey +import fr.acinq.bitcoin.crypto.frost.TweakCache +import fr.acinq.lightning.channel.GroupHeldOutputs +import fr.acinq.lightning.transactions.Scripts +import fr.acinq.secp256k1.Hex +import kotlinx.serialization.Serializable + +/** + * Moving what a closed channel left the group into its onchain wallet (`docs/group-lightning-wallet.md`, + * Phase 13): a FROST spend whose inputs are taproot *script* paths, one leaf of an output a commitment + * or HTLC transaction pays to the group's basepoints. + * + * Every member checks a sweep the way [com.machankura.bennu.compose.wallet.GroupSpend] checks a spend, + * trusting nothing the proposer computed: + * + * - **The key is the group's.** Each input names a basepoint and a tweak; the member derives the leaf key + * from its own basepoints ([GroupLightningDerivation.leafCache]) and rebuilds the one leaf it signs -- + * ` OP_CHECKSIGVERIFY OP_CHECKSEQUENCEVERIFY`, the only shape lightning-kmp gives a + * group-held output. A tweak the proposer made up gives a key the group can sign for and nobody else + * can, so it costs nothing. + * - **Everything goes to the onchain wallet.** Every output is a receive address of the wallet the + * statement closes to, at an index the member derives. + * - **What is spent is what the sighash says.** BIP341's script-path sighash commits to every spent + * amount and script and to the leaf, so a lie about any of them is a transaction nobody can mine, + * not one that pays someone else. + * + * The internal key and the control block are the proposer's to get right, for the same reason. + */ +object GroupSweep { + /** The highest feerate a sweep may pay, in sats per virtual byte: the onchain wallet's own limit. */ + const val MAX_FEERATE_SAT_PER_VBYTE: Long = com.machankura.bennu.compose.wallet.GroupSpend.MAX_FEERATE_SAT_PER_VBYTE + + const val PAYMENT = "payment" + const val DELAYED = "delayed" + + /** One output to sweep, as a proposal carries it. [tweak] is null for an output under the payment basepoint itself. */ + @Serializable + data class Input( + val txid: String, + val index: Long, + val amountSat: Long, + val script: String, + val basepoint: String, + val tweak: String? = null, + val leafScript: String, + val controlBlock: String, + val csvDelay: Long, + ) + + /** A sweep proposal: the unsigned transaction, what each input spends, and which receive address each output is. */ + @Serializable + data class Sweep(val wallet: Long, val tx: String, val inputs: List, val receiveIndices: List) + + data class CheckedInput( + val index: Int, + val outPoint: OutPoint, + val txOut: TxOut, + val leafKey: XonlyPublicKey, + val cache: TweakCache, + val leafScript: ByteVector, + val controlBlock: ByteVector, + val sighash: ByteVector32, + ) + + data class Checked(val sweep: Sweep, val tx: Transaction, val inputs: List, val fee: Satoshi, val weight: Int) { + val amount: Satoshi get() = Satoshi(tx.txOut.sumOf { it.amount.sat }) + val spentOutputs: List get() = inputs.map { it.txOut } + val feeratePerVbyte: Long get() = fee.sat / ((weight.toLong() + 3) / 4) + } + + sealed interface Result { + data class Ok(val checked: Checked) : Result + data class Refused(val reason: String) : Result + } + + /** The one leaf a group-held output is spent by, for [leafKey] after [csvDelay] blocks. */ + fun leafScript(leafKey: XonlyPublicKey, csvDelay: Long): ByteVector = + ByteVector(Script.write(listOf(OP_PUSHDATA(leafKey), OP_CHECKSIGVERIFY, Scripts.encodeNumber(csvDelay), OP_CHECKSEQUENCEVERIFY))) + + /** Checks [sweep] against the group's [basepoints] and the onchain [account] it must pay. */ + fun check(sweep: Sweep, basepoints: GroupLightningDerivation.Basepoints, account: GroupWalletDerivation.Account): Result { + val tx = runCatching { Transaction.read(sweep.tx) }.getOrElse { return Result.Refused("is not a transaction") } + if (tx.txIn.isEmpty()) return Result.Refused("spends nothing") + if (tx.txIn.size != sweep.inputs.size) return Result.Refused("describes ${sweep.inputs.size} inputs of ${tx.txIn.size}") + if (tx.txIn.size > FrostSigningManager.MAX_BATCH_SIZE) return Result.Refused("spends more than ${FrostSigningManager.MAX_BATCH_SIZE} outputs") + if (tx.version != 2L) return Result.Refused("is version ${tx.version}, not 2") + if (tx.lockTime != 0L) return Result.Refused("has a lock time") + if (tx.txOut.isEmpty() || tx.txOut.size != sweep.receiveIndices.size) return Result.Refused("does not say where every output goes") + tx.txOut.zip(sweep.receiveIndices).forEach { (out, index) -> + if (index !in 0..com.machankura.bennu.compose.wallet.GroupSpend.MAX_ADDRESS_INDEX) return Result.Refused("names receive address $index") + if (out.publicKeyScript != GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index).pubkeyScript) { + return Result.Refused("pays somewhere that is not the group's onchain wallet") + } + } + + val spent = sweep.inputs.map { TxOut(Satoshi(it.amountSat), ByteVector(it.script)) } + val inputs = sweep.inputs.mapIndexed { i, input -> + val txIn = tx.txIn[i] + if (txIn.outPoint != OutPoint(TxId(input.txid), input.index)) return Result.Refused("input $i is not the output it describes") + if (input.csvDelay !in 1..0xFFFF) return Result.Refused("input $i has a delay of ${input.csvDelay}") + if (txIn.sequence != input.csvDelay) return Result.Refused("input $i does not wait the ${input.csvDelay} blocks its leaf asks") + val basepoint = when (input.basepoint) { + PAYMENT -> basepoints.payment + DELAYED -> basepoints.delayedPayment + else -> return Result.Refused("input $i names no basepoint of the group's") + } + val tweak = input.tweak?.let { runCatching { ByteVector32(it) }.getOrElse { return Result.Refused("input $i has an unreadable tweak") } } + if (input.basepoint == DELAYED && tweak == null) return Result.Refused("input $i is a delayed output with no per-commitment tweak") + val cache = GroupLightningDerivation.leafCache(basepoint, tweak) + val leaf = leafScript(cache.tweakedPublicKey, input.csvDelay) + if (ByteVector(input.leafScript) != leaf) return Result.Refused("input $i is not spent by the group's own leaf") + val sighash = tx.hashForSigningTaprootScriptPath(i, spent, SigHash.SIGHASH_DEFAULT, ScriptTree.Leaf(leaf.toByteArray().let(Script::parse)).hash()) + CheckedInput(i, txIn.outPoint, spent[i], cache.tweakedPublicKey, cache, leaf, ByteVector(input.controlBlock), sighash) + } + + val fee = spent.sumOf { it.amount.sat } - tx.txOut.sumOf { it.amount.sat } + if (fee < 0) return Result.Refused("pays out more than it spends") + val weight = witnessed(tx, inputs, inputs.map { ByteVector64.Zeroes }).weight() + val checked = Checked(sweep, tx, inputs, Satoshi(fee), weight) + if (checked.feeratePerVbyte > MAX_FEERATE_SAT_PER_VBYTE) return Result.Refused("pays ${checked.feeratePerVbyte} sats per vbyte in fees") + return Result.Ok(checked) + } + + /** [tx] with each input's witness: the group's signature, the leaf, and the control block. */ + fun witnessed(tx: Transaction, inputs: List, signatures: List): Transaction = + inputs.zip(signatures).fold(tx) { acc, (input, signature) -> + acc.updateWitness(input.index, ScriptWitness(listOf(signature, input.leafScript, input.controlBlock))) + } + + /** What a proposal carries for [output], as lightning-kmp found it in a published transaction. */ + fun inputOf(output: GroupHeldOutputs.Output): Input { + val witness = output.witness(ByteVector64.Zeroes) + return Input( + txid = output.outPoint.txid.toString(), + index = output.outPoint.index, + amountSat = output.txOut.amount.sat, + script = Hex.encode(output.txOut.publicKeyScript.toByteArray()), + basepoint = if (output.kind == GroupHeldOutputs.Kind.TO_REMOTE) PAYMENT else DELAYED, + tweak = output.tweak?.toHex(), + leafScript = Hex.encode(witness.stack[1].toByteArray()), + controlBlock = Hex.encode(witness.stack[2].toByteArray()), + csvDelay = output.csvDelay, + ) + } + + /** + * A sweep of [inputs] to the onchain wallet's receive address [receiveIndex], paying [feeratePerVbyte], + * or null when there is nothing left after the fee. + */ + fun build(wallet: Long, inputs: List, account: GroupWalletDerivation.Account, receiveIndex: Long, feeratePerVbyte: Long): Sweep? { + if (inputs.isEmpty()) return null + val to = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, receiveIndex).pubkeyScript + val total = inputs.sumOf { it.amountSat } + fun txPaying(amount: Long) = Transaction( + version = 2, + txIn = inputs.map { TxIn(OutPoint(TxId(it.txid), it.index), ByteVector.empty, it.csvDelay) }, + txOut = listOf(TxOut(Satoshi(amount), to)), + lockTime = 0, + ) + // Weighed with stand-in signatures: a script-path witness is the same size whatever it signs. + val draft = txPaying(total).let { tx -> + inputs.foldIndexed(tx) { i, acc, input -> + acc.updateWitness(i, ScriptWitness(listOf(ByteVector64.Zeroes, ByteVector(input.leafScript), ByteVector(input.controlBlock)))) + } + } + val fee = feeratePerVbyte * ((draft.weight().toLong() + 3) / 4) + if (total - fee < DUST_SAT) return null + return Sweep(wallet, Hex.encode(Transaction.write(txPaying(total - fee))), inputs, listOf(receiveIndex)) + } + + /** The smallest output a sweep leaves: anything under is not worth the fee to sweep. */ + private const val DUST_SAT = 330L +} 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 92107764..bcc6388c 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 @@ -48,6 +48,8 @@ object WalletWire { val payments: List, val offer: String? = null, val assignments: Map = emptyMap(), + /** What closed channels left the group, for any member to sweep into the onchain wallet. */ + val heldOutputs: 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 3f30d612..045dfd14 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 @@ -1,5 +1,6 @@ package com.machankura.bennu.compose.managers +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import com.machankura.bennu.compose.wallet.lightning.WalletWire import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.utils.Either @@ -28,6 +29,7 @@ class FakeGroupNode(private val configuration: GroupLightningNode.NodeConfigurat /** Every close asked of the node, as (channel, script), and every force close, by channel. */ val closed = mutableListOf>() val forceClosed = mutableListOf() + var heldOutputs = listOf() override suspend fun connect(): Boolean { connected = true; return true } override fun disconnect() { disconnected = true } @@ -41,6 +43,7 @@ class FakeGroupNode(private val configuration: GroupLightningNode.NodeConfigurat ).also { invoices += it }.write() override suspend fun close(channelId: String, scriptPubKey: ByteVector) { closed += channelId to scriptPubKey } override suspend fun forceClose(channelId: String) { forceClosed += channelId } + override fun heldOutputs(): List = heldOutputs 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/GroupLightningSweepJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningSweepJvmTest.kt new file mode 100644 index 00000000..c4b47bb2 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningSweepJvmTest.kt @@ -0,0 +1,133 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.database.model.types.FrostSigningStage +import com.machankura.bennu.compose.wallet.lightning.GroupSweep +import com.machankura.bennu.compose.wallet.lightning.WalletWire +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Script +import fr.acinq.bitcoin.ScriptFlags +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxOut +import fr.acinq.bitcoin.byteVector32 +import fr.acinq.lightning.CltvExpiryDelta +import fr.acinq.lightning.Lightning.randomBytes32 +import fr.acinq.lightning.channel.GroupHeldOutputs +import fr.acinq.lightning.crypto.ChannelKeys +import fr.acinq.lightning.crypto.CommitmentPublicKeys +import fr.acinq.lightning.transactions.Scripts +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.runBlocking +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Sweeping what a closed channel left the group into its onchain wallet (`docs/group-lightning-wallet.md`, + * Phase 13). The outputs are built with lightning-kmp's own scripts, as a published commitment carries + * them; the group signs them with FROST, every member checking the sweep first; and the script + * interpreter judges the result. + */ +class GroupLightningSweepJvmTest { + private val fixture = GroupLightningFixture() + private val lsp = "02" + KeyPair().pubKey.toHexKey() + + @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) + return all to GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! + } + + private fun key() = PrivateKey(randomBytes32()).publicKey() + private fun keys(remotePayment: fr.acinq.bitcoin.PublicKey = key(), localDelayed: fr.acinq.bitcoin.PublicKey = key()) = + CommitmentPublicKeys(localDelayed, remotePayment, key(), key(), key()) + + /** Our main output in the counterparty's commitment, under the payment basepoint. */ + private fun toRemote(wallet: GroupLightningWalletManager.Wallet, amount: Long): GroupHeldOutputs.Output { + val basepoint = wallet.basepoints.payment.publicKey + val commitment = keys(remotePayment = basepoint) + val leaf = Scripts.Taproot.toRemoteScriptTree(commitment) + val outPoint = OutPoint(TxId(randomBytes32()), 1) + return GroupHeldOutputs.Output(GroupHeldOutputs.Kind.TO_REMOTE, outPoint, TxOut(Satoshi(amount), Script.write(Scripts.Taproot.toRemote(commitment))), basepoint, null, basepoint, Scripts.Taproot.NUMS_POINT.xOnly(), leaf, leaf, 1) + } + + /** Our main output in our own commitment, under the delayed basepoint and a per-commitment point. */ + private fun toLocal(wallet: GroupLightningWalletManager.Wallet, amount: Long, delay: Int = 144): GroupHeldOutputs.Output { + val basepoint = wallet.basepoints.delayedPayment.publicKey + val point = key() + val leafKey = ChannelKeys.remotePerCommitmentPublicKey(basepoint, point) + val commitment = keys(localDelayed = leafKey) + val tree = Scripts.Taproot.toLocalScriptTree(commitment, CltvExpiryDelta(delay)) + val outPoint = OutPoint(TxId(randomBytes32()), 0) + val tweak = Crypto.sha256(point.value + basepoint.value).byteVector32() + return GroupHeldOutputs.Output(GroupHeldOutputs.Kind.TO_LOCAL, outPoint, TxOut(Satoshi(amount), Script.write(Scripts.Taproot.toLocal(commitment, CltvExpiryDelta(delay)))), basepoint, tweak, leafKey, Scripts.Taproot.NUMS_POINT.xOnly(), tree.localDelayed, tree.scriptTree, delay.toLong()) + } + + @Test + fun `the group sweeps both kinds of output into its onchain wallet, and the transaction is valid`() = runBlocking { + val (all, wallet) = opened() + val outputs = listOf(toRemote(wallet, 300_000), toLocal(wallet, 500_000)) + val inputs = outputs.map(GroupSweep::inputOf) + val sweep = assertNotNull(GroupSweep.build(wallet.statement.wallet, inputs, fixture.account, receiveIndex = 0, feeratePerVbyte = 2)) + val session = FrostSigningManager.proposeSweep(all[3].db, all[3].room, all[3].publicKey, sweep, fixture.chain) + fixture.signSession(all, all[3], session.id) + + all.forEach { d -> + assertEquals(FrostSigningStage.COMPLETE, d.db.frostSigningSessionDao().getSessionById(session.id)?.stage, "device ${d.index}") + } + val signed = Transaction.read(assertNotNull(all[0].db.groupTransactionDao().getBySessionId(session.id)?.signedTransaction)) + Transaction.correctlySpends(signed, outputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + assertEquals(GroupWalletDerivation.derive(fixture.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript, signed.txOut.single().publicKeyScript) + assertEquals(listOf(1L, 144L), signed.txIn.map { it.sequence }, "each input waits its leaf's delay") + val checked = assertNotNull(FrostSigningManager.checkedSweep(all[1].db, session.id)) + assertEquals(800_000 - checked.fee.sat, checked.amount.sat) + assertTrue(checked.feeratePerVbyte in 1..3, "${checked.feeratePerVbyte} sats per vbyte") + + // A proposed sweep's outputs are not offered again. + val report = GroupLightningReports.Report(WalletWire.Snapshot("w", 1, wallet.statement.nodeId, 0, emptyList(), emptyList(), heldOutputs = inputs + GroupSweep.inputOf(toRemote(wallet, 10_000))), emptyList()) + assertEquals(1, GroupLightningSweeps.unswept(all[2].db, fixture.roomId, report).size) + } + + @Test + fun `a sweep that pays anyone else, or signs under a key that is not the group's, is refused`() = runBlocking { + val (_, wallet) = opened() + val input = GroupSweep.inputOf(toLocal(wallet, 500_000)) + val good = assertNotNull(GroupSweep.build(wallet.statement.wallet, listOf(input), fixture.account, 0, 2)) + assertIs(GroupSweep.check(good, wallet.basepoints, fixture.account)) + + fun refused(sweep: GroupSweep.Sweep, why: String) = assertIs(GroupSweep.check(sweep, wallet.basepoints, fixture.account), why) + val tx = Transaction.read(good.tx) + val elsewhere = tx.copy(txOut = listOf(tx.txOut.single().copy(publicKeyScript = ByteVector(Script.write(Script.pay2wpkh(key())))))) + refused(good.copy(tx = Hex.encode(Transaction.write(elsewhere))), "paying an address that is not the wallet's") + refused(good.copy(receiveIndices = listOf(1)), "claiming another receive index") + refused(good.copy(inputs = listOf(input.copy(tweak = null))), "a delayed output with no tweak") + refused(good.copy(inputs = listOf(input.copy(tweak = ByteVector32(randomBytes32()).toHex()))), "a tweak whose key is not the leaf's") + refused(good.copy(inputs = listOf(input.copy(basepoint = GroupSweep.PAYMENT))), "the wrong basepoint for the leaf") + refused(good.copy(inputs = listOf(input.copy(csvDelay = 1))), "a delay the transaction does not wait") + val greedy = tx.copy(txOut = listOf(tx.txOut.single().copy(amount = Satoshi(100_000)))) + refused(good.copy(tx = Hex.encode(Transaction.write(greedy))), "a fee far over the limit") + } + + @Test + fun `the leaf a member rebuilds is the leaf lightning-kmp writes`() = runBlocking { + val (_, wallet) = opened() + val remote = toRemote(wallet, 1_000) + assertEquals(remote.leaf.script, GroupSweep.leafScript(wallet.basepoints.payment.publicKey.xOnly(), 1)) + val local = toLocal(wallet, 1_000, delay = 720) + assertEquals(local.leaf.script, GroupSweep.leafScript(local.leafKey.xOnly(), 720)) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt index ba280ec5..17357b9b 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt @@ -23,6 +23,7 @@ import com.machankura.bennu.compose.repository.GroupLightningRepository import com.machankura.bennu.compose.ui.view.state.GroupLightningReceiveUIState import com.machankura.bennu.compose.ui.view.state.GroupLightningSendUIState import com.machankura.bennu.compose.ui.view.state.GroupLightningWalletUIState +import com.machankura.bennu.compose.wallet.lightning.GroupSweep import com.machankura.bennu.compose.wallet.lightning.WalletWire import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.ByteVector32 @@ -123,6 +124,8 @@ class GroupLightningWalletViewModelJvmTest { override fun observeInvoice(chatRoomId: String, chain: Chain, requestId: String): Flow = flowOf(invoice?.takeIf { it.requestId == requestId }) override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession = error("unused") override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession = error("unused") + override suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List = report?.snapshot?.heldOutputs.orEmpty() + override suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession = error("unused") } private val chat = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md index fdb19b07..29f4d7b9 100644 --- a/docs/group-lightning-wallet.md +++ b/docs/group-lightning-wallet.md @@ -41,7 +41,7 @@ build chose differently, this table says so. | 10 | done: `GroupLightningReports`, the node's reporting loop, schema 30 (`GroupLightningSnapshotRow`, `GroupLightningPaymentRow`, `GroupLightningInvoiceRow`), and balance, channels and payments on the wallet screen, each channel checked against the device's own co-signing ledger. Four new tests | | 11 | done: invoice requests and answers through `GroupLightningReports`, the running node answering each request once, and the receive screen (`GroupLightningReceiveScreen`). A member files an invoice only from the operator, and only if it pays the node the statement names. Three new tests | | 12 | done: `GroupLightningAuthorisationEvent` (kind 30346, `pay`), budgets read from the signed authorisations, the node paying each once, its summary and transcript line, and the send screen (`GroupLightningSendScreen`). The co-signers now hold offered HTLCs under the statement's in-flight cap. Seven new tests | -| 13 | in part. Done: `close` and `force-close` authorisations, the node acting on each once, the co-signers signing our own commitment only under a force-close authorisation and only after rebuilding it, and the channel menu on the wallet screen. Two new tests, one of them a force close whose signature spends the funding output. Sweeping and splicing out follow | +| 13 | done, except splicing out. `close` and `force-close` authorisations, the node acting on each once, the co-signers signing our own commitment only under a force-close authorisation and only after rebuilding it, and the channel menu on the wallet screen. Sweeps: the snapshot lists what closed channels left the group, any member proposes a sweep (`GroupSweep`, a new FROST subject), every member checks it against its own basepoints and the onchain wallet, and the watcher sends it. Five new tests: a force close and a two-input sweep both pass the script interpreter | | what the plan said | what it turned out to be | |---|---| @@ -101,6 +101,10 @@ build chose differently, this table says so. | a close needs a `close` authorisation on every co-signer | the *operator's node* acts only on one, but a co-signer signs any mutual close that passes check 7, because a close that pays the group's onchain wallet is the outcome every close is for. Refusing an LSP-initiated close would only make the LSP force-close, at the group's cost | | co-signers sign our own commitment under a force-close authorisation | and only after rebuilding it with `Commitments.makeLocalTxs`, and only if its number is no more than one behind the counterparty commitment the device last signed for the channel. The two numbers move together, so anything further behind is a revoked state, which would hand the LSP the channel | | a force close lightning-kmp starts itself | is refused like any other until the group authorises it, and lightning-kmp's `fullySignedCommitTx` assumes the signature cannot fail, so the attempt throws in the channel. The group's own force closes are only asked for once authorised. Making that path return a failure is a fork change, left for the review of Phase 13 | +| sweeping follows `ChannelAction` rows in `GroupTransactionWatcher` | the operator's snapshot carries the outputs (`heldOutputs`, from `GroupHeldOutputs` over each closing channel), and a sweep is a `GroupTransaction` row like a spend, so the watcher sends it with nothing new. A sweep signed before its delay is over is refused by the network and sent again every ten minutes until it is accepted, so nobody has to watch for the delay to end | +| `GroupSpend.check` gains a script-path input type | a separate check, `GroupSweep.check`, and a FROST subject of its own, `SWEEP`. A PSBT cannot carry a taproot leaf in bitcoin-kmp, and a sweep's rules are not a spend's: every output must be the group's own, and every input must be the one leaf lightning-kmp gives a group-held output, rebuilt by the member from its own basepoints. The sweep rides in the transaction row's PSBT column, and every PSBT reader skips what it cannot decode | +| the sweep's tweak comes from a per-commitment point the member derives | the proposal carries the tweak. Any tweak gives a key only the group can sign for, and BIP341 commits the signature to the leaf and to every spent output, so a made-up tweak is a sweep nobody can mine, never one that pays someone else | +| splice out to an onchain wallet address | **not built.** The co-signers pin a channel to its funding output the first time they sign for it, and a splice moves the channel to a new one. Letting it move means checking the splice transaction itself, its shared input, the new funding output and the splice-out output, inside lightning-kmp's interactive negotiation. Until then money leaves the Lightning wallet by being paid out, or by closing | | the kinds are reserved | in code: `GroupLightningEvents`, 30333-30349, with a test asserting the run is unbroken and touches no kind the app already dispatches on | | library phases land in the forks' `threshold` branches | on a new branch, `claude/group-lightning-wallet`, in `lightning-kmp-app` and in `experimental/lightning-kmp`. It is local and not pushed. The app's submodule pointer follows it, so a checkout of this branch needs those commits from the same machine until they are pushed |