diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 8d545821..e1a99feb 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -747,4 +747,14 @@ Invoice copied Nobody runs this wallet yet, so there is no node to make an invoice. Couldn't ask for an invoice. + The invoice names the amount: %1$s sats. + Fee limit in sats + Left empty, %1$s sats. + Ask the group to pay + The group signs for this payment as for any decision. Once it has, the operator's device pays it, and no member's device lets more than the amount and the fee limit leave. + That isn't a Lightning invoice. + That invoice is for another network, not %1$s. + That invoice has expired. + That invoice names no amount, so give one. + That invoice pays this wallet's own node. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt index 391ab7c5..8226f1f6 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/model/ChatMessage.kt @@ -2,6 +2,9 @@ package com.machankura.bennu.compose.database.model import com.machankura.bennu.compose.managers.GroupLightningWalletManager import com.machankura.bennu.compose.nostr.lightning.GroupLightningOperatorStatementEvent +import com.machankura.bennu.compose.text.grouped +import fr.acinq.bitcoin.Satoshi +import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent import androidx.room3.Entity import androidx.room3.ForeignKey @@ -536,6 +539,7 @@ data class ChatMessage( const val TYPE_GROUP_WALLET_OPENED = "groupWalletOpened" const val TYPE_GROUP_LIGHTNING_WALLET_OPENED = "groupLightningWalletOpened" const val TYPE_GROUP_LIGHTNING_OPERATOR_ELECTED = "groupLightningOperatorElected" + const val TYPE_GROUP_LIGHTNING_PAYMENT_AUTHORISED = "groupLightningPaymentAuthorised" /** * A transaction from the group's wallet confirmed. Written by each device @@ -554,6 +558,7 @@ data class ChatMessage( TYPE_GROUP_TRANSACTION_CONFIRMED, TYPE_GROUP_LIGHTNING_WALLET_OPENED, TYPE_GROUP_LIGHTNING_OPERATOR_ELECTED, + TYPE_GROUP_LIGHTNING_PAYMENT_AUTHORISED, ) /** @@ -1772,6 +1777,25 @@ data class ChatMessage( ) } + // A payment the group signed for. The line says how much and that the operator's node + // pays it; whether it went is the snapshot's to say, on the wallet's screen. + GroupLightningAuthorisationEvent.KIND -> { + val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) + if (!signed.verifies()) return null + val pay = GroupLightningAuthorisationEvent.read(event.tags) ?: return null + ChatMessage( + giftWrapPayloadId = null, + messageType = TYPE_GROUP_LIGHTNING_PAYMENT_AUTHORISED, + marmotGroupEventId = marmotGroupEventId, + marmotInnerEventId = marmotInnerEventId, + senderPublicKey = senderPublicKey, + isUserMessage = isUserMessage, + chatRoomId = groupId, + createdAt = createdAt, + content = "The group authorised a Lightning payment of ${Satoshi(pay.amountMsat / 1000).grouped()} sats. The operator's node pays it." + ) + } + in GroupRelaySet.KINDS -> { val signed = GroupSignedEvent.fromEvent(event, chatRoomId = groupId) if (!signed.verifies()) return null 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 95b7cb2e..f841c2f2 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 @@ -9,6 +9,7 @@ import com.machankura.bennu.compose.managers.FrostSigningManager import com.machankura.bennu.compose.database.model.FrostSigningSession import com.machankura.bennu.compose.database.model.GroupLightningInvoiceRow import com.machankura.bennu.compose.database.model.GroupLightningPaymentRow +import com.machankura.bennu.compose.managers.GroupLightningAuthorisations import com.machankura.bennu.compose.managers.GroupLightningCoSigner import com.machankura.bennu.compose.managers.GroupLightningOperatorManager import com.machankura.bennu.compose.managers.GroupLightningReports @@ -16,6 +17,7 @@ import com.machankura.bennu.compose.managers.GroupLightningWalletManager import com.machankura.bennu.compose.managers.GroupWalletManager import fr.acinq.phoenixd.conf.LSP import com.machankura.bennu.compose.managers.IcebergRitualManager +import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningEvents import com.machankura.bennu.compose.repository.GroupLightningRepository import com.vitorpamplona.quartz.nip01Core.core.HexKey @@ -58,6 +60,9 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr override fun observeInvoice(chatRoomId: String, chain: Chain, requestId: String): Flow = database.groupLightningRecordsDao().observeInvoice(GroupLightningCoSigner.walletKey(chatRoomId, chain, 0L), requestId) + override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession = + GroupLightningAuthorisations.propose(database, localChatRoom, userPublicKey, pay) + override fun observeCeremony(sessionId: String): Flow = database.icebergKeySessionDao().observeSessionById(sessionId) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt index 4a4ca41b..bcc7cd64 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt @@ -1,18 +1,48 @@ 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.IcebergBudgetSpend +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent +import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.lightning.payment.Bolt11Invoice +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Instant /** - * What the group has authorised its Lightning wallet to spend, as a co-signer reads it - * (`docs/group-lightning-wallet.md`, Phases 12 and 13). + * What the group has authorised its Lightning wallet to spend, as a co-signer reads it and the operator's + * node acts on it (`docs/group-lightning-wallet.md`, Phases 12 and 13). * - * An authorisation is a group-signed event (kind 30346). Until Phase 12 there are none, so a co-signer - * lets no outgoing payment through and signs no force close: the wallet can receive, and nothing else. + * An authorisation is a group-signed event (kind 30346, [GroupLightningAuthorisationEvent]). The group + * may sign two for one invoice -- once more after the first expired, say. They are one payment: the + * budget is the larger, and it is open while either is. Force closes are Phase 13's, and none is + * authorised until then. */ object GroupLightningAuthorisations { + /** How long an authorisation stays open when its invoice does not say sooner. */ + val DEFAULT_LIFETIME: Duration = 24.hours + + /** Every payment the group has authorised for [wallet], as this device verifies it, oldest first. */ + suspend fun payments(database: BennuDatabase, wallet: GroupLightningWalletManager.Wallet): List = + database.groupSignedEventDao().getByChatRoomIdAndKind(wallet.signedEvent.chatRoomId, GroupLightningAuthorisationEvent.KIND) + .filter { it.verifies() } + .sortedWith(compareBy({ it.createdAt }, { it.id })) + .mapNotNull { GroupLightningAuthorisationEvent.read(it.tags) } + .filter { it.chain == wallet.statement.chain && it.wallet == wallet.statement.wallet } + + /** Every payment the group has authorised, with its whole budget, by payment hash, in millisatoshi. */ + suspend fun authorisedPayments(database: BennuDatabase, wallet: GroupLightningWalletManager.Wallet): Map = + payments(database, wallet).groupBy { it.paymentHash }.mapValues { (_, all) -> all.maxOf { it.budgetMsat } } + + /** The payment hashes whose every authorisation has expired at [now]: no new HTLC pays them. */ + suspend fun expired(database: BennuDatabase, wallet: GroupLightningWalletManager.Wallet, now: Instant = Clock.System.now()): Set = + payments(database, wallet).groupBy { it.paymentHash }.filterValues { all -> all.all { it.expiresAt <= now.epochSeconds } }.keys + /** What each authorised payment has left to spend, by payment hash, in millisatoshi. */ suspend fun budgets(database: BennuDatabase, wallet: GroupLightningWalletManager.Wallet): Map { val key = GroupLightningCoSigner.walletKey(wallet.signedEvent.chatRoomId, wallet.statement.chain, wallet.statement.wallet) @@ -29,8 +59,42 @@ object GroupLightningAuthorisations { consumed.forEach { (hash, amount) -> dao.upsertBudgetSpend(IcebergBudgetSpend(key, hash, (spent[hash] ?: 0) + amount)) } } - /** Every payment the group has authorised, with its whole budget: none until Phase 12. */ - suspend fun authorisedPayments(database: BennuDatabase, wallet: GroupLightningWalletManager.Wallet): Map = emptyMap() + /** The authorised payments the operator's node should make at [now]: open, one per payment hash, oldest first. */ + suspend fun toPay(database: BennuDatabase, wallet: GroupLightningWalletManager.Wallet, now: Instant = Clock.System.now()): List = + payments(database, wallet).filter { it.expiresAt > now.epochSeconds }.distinctBy { it.paymentHash } + + /** Why [bolt11] cannot be authorised for [wallet], or null when it can. */ + sealed class Problem { + data object Unreadable : Problem() + data object OtherNetwork : Problem() + data object Expired : Problem() + data object NeedsAmount : Problem() + /** The invoice pays the group's own node: a payment to itself that would only cost fees. */ + data object PaysTheGroup : Problem() + } + + /** The authorisation [bolt11] would be, or the [Problem] with it. [amountMsat] is used only when the invoice names none. */ + fun prepare(wallet: GroupLightningWalletManager.Wallet, bolt11: String, amountMsat: Long?, maxFeeMsat: Long, now: Instant = Clock.System.now()): Result { + val text = bolt11.trim().removePrefix("lightning:").removePrefix("LIGHTNING:") + val invoice = runCatching { Bolt11Invoice.read(text).get() }.getOrNull() ?: return Result.failure(ProblemException(Problem.Unreadable)) + if (invoice.chain != wallet.statement.chain) return Result.failure(ProblemException(Problem.OtherNetwork)) + if (invoice.isExpired(now.epochSeconds)) return Result.failure(ProblemException(Problem.Expired)) + if (invoice.nodeId.toString() == wallet.statement.nodeId) return Result.failure(ProblemException(Problem.PaysTheGroup)) + val amount = invoice.amount?.msat ?: amountMsat?.takeIf { it > 0 } ?: return Result.failure(ProblemException(Problem.NeedsAmount)) + val invoiceExpiry = invoice.timestampSeconds + (invoice.expirySeconds ?: Bolt11Invoice.DEFAULT_EXPIRY_SECONDS.toLong()) + val expires = minOf(invoiceExpiry, (now + DEFAULT_LIFETIME).epochSeconds) + return Result.success( + GroupLightningAuthorisationEvent.Pay(wallet.statement.chain, wallet.statement.wallet, text, amount, maxFeeMsat, invoice.paymentHash.toHex(), expires) + ) + } + + class ProblemException(val problem: Problem) : IllegalArgumentException(problem.toString()) + + /** Proposes [pay] to the group; it is authorised once a quorum signs. */ + suspend fun propose(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession { + val template = GroupLightningAuthorisationEvent.template(pay) + return FrostSigningManager.proposeSigning(database, localChatRoom, userPublicKey, template.kind, template.tags, template.content) + } /** Whether the group has authorised a force close of [channelId]: never, until Phase 13. */ suspend fun forceCloseAuthorised(database: BennuDatabase, chatRoomId: String, statement: GroupLightningWalletStatementEvent.Statement, channelId: ByteVector32): Boolean = false diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningCoSigner.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningCoSigner.kt index 277089c2..44bad70e 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningCoSigner.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningCoSigner.kt @@ -346,7 +346,8 @@ object GroupLightningCoSigner { // answers to the ledger. if (pinned == null) return null val budgets = GroupLightningAuthorisations.budgets(database, wallet) - return when (val verdict = CoSignerPolicy.checkRemoteCommitment(load(pinned.ledger), commitIndex, tx.txid.toString(), spec, budgets)) { + val closed = GroupLightningAuthorisations.expired(database, wallet) + return when (val verdict = CoSignerPolicy.checkRemoteCommitment(load(pinned.ledger), commitIndex, tx.txid.toString(), spec, budgets, closed, wallet.statement.policy.inFlightCapSat * 1000)) { is CoSignerPolicy.Verdict.Refuse -> verdict.reason is CoSignerPolicy.Verdict.Sign -> null } @@ -376,7 +377,7 @@ object GroupLightningCoSigner { val allowance = wallet.statement.policy.commitmentFeeAllowanceSat * 1000 val next = when (pinned) { null -> CoSignerPolicy.open(context.commitIndex ?: return, tx.txid.toString(), spec, allowance) - else -> when (val verdict = CoSignerPolicy.checkRemoteCommitment(load(pinned.ledger), context.commitIndex ?: return, tx.txid.toString(), spec, GroupLightningAuthorisations.budgets(database, wallet))) { + else -> when (val verdict = CoSignerPolicy.checkRemoteCommitment(load(pinned.ledger), context.commitIndex ?: return, tx.txid.toString(), spec, GroupLightningAuthorisations.budgets(database, wallet), GroupLightningAuthorisations.expired(database, wallet), wallet.statement.policy.inFlightCapSat * 1000)) { is CoSignerPolicy.Verdict.Refuse -> return is CoSignerPolicy.Verdict.Sign -> { GroupLightningAuthorisations.consume(database, wallet, verdict.consumed) 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 3324a557..aeab06b8 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 @@ -8,6 +8,7 @@ import com.machankura.bennu.compose.wallet.lightning.GroupNodeKeyManager import com.machankura.bennu.compose.wallet.lightning.WalletWire import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.PublicKey import fr.acinq.bitcoin.utils.Either @@ -25,9 +26,11 @@ import fr.acinq.lightning.db.Databases import fr.acinq.lightning.db.LightningIncomingPayment import fr.acinq.lightning.db.LightningOutgoingPayment import fr.acinq.lightning.db.WalletPayment +import fr.acinq.lightning.io.PaymentSent import fr.acinq.lightning.io.Peer import fr.acinq.lightning.io.TcpSocket import fr.acinq.lightning.logging.LoggerFactory +import fr.acinq.lightning.payment.Bolt11Invoice import kotlin.time.Clock import kotlin.time.Duration import kotlin.time.Duration.Companion.minutes @@ -81,6 +84,10 @@ class GroupLightningNode( fun payments(): List /** A Bolt11 invoice paying the node, for [amountMsat] or any amount. */ suspend fun createInvoice(amountMsat: Long?, description: String): String + /** Whether the node has tried to pay [paymentHash] before, in this run or an earlier one. */ + suspend fun hasPaid(paymentHash: String): Boolean + /** Pays [bolt11] [amountMsat], through the LSP, and says how it went. */ + suspend fun pay(bolt11: String, amountMsat: Long): WalletWire.PaymentView } sealed class State { @@ -183,6 +190,26 @@ class GroupLightningNode( } } + private val paying = mutableSetOf() + + /** + * Pays every payment the group has authorised and this node has not tried yet, each once. A payment + * that fails is not tried again: the group signs a new authorisation for another attempt, and the + * co-signers' budgets are what stop either from paying twice. + */ + internal suspend fun payAuthorised() { + val handle = peer ?: return + GroupLightningAuthorisations.toPay(database, wallet, now()).forEach { pay -> + if (pay.paymentHash in paying || handle.hasPaid(pay.paymentHash)) return@forEach + paying += pay.paymentHash + scope.launch { + runCatching { handle.pay(pay.invoice, pay.amountMsat) } + .onSuccess { logger.i("Paid ${pay.paymentHash.take(16)}: ${if (it.succeeded) "sent" else "not sent"}") } + .onFailure { logger.e("Paying ${pay.paymentHash.take(16)} failed", it) } + } + } + } + /** Stops the node as soon as the room's newest operator statement names a later term. */ private fun watchForHandover(term: Long) { watching?.cancel() @@ -197,6 +224,7 @@ class GroupLightningNode( } runCatching { report(term) }.onFailure { logger.e("Could not report the wallet to the room", it) } runCatching { answerInvoiceRequests() }.onFailure { logger.e("Could not answer an invoice request", it) } + runCatching { payAuthorised() }.onFailure { logger.e("Could not make an authorised payment", it) } } } } @@ -244,7 +272,8 @@ class GroupLightningNode( require(walletParams.trampolineNode.id == configuration.lspNodeId) { "the wallet's LSP is not the node it would connect to" } val client = clients.clientFor(configuration.chain) val watcher = ElectrumWatcher(client, scope, loggerFactory) - val peer = Peer(nodeParams, walletParams, client, watcher, databasesFor(nodeParams.nodeId, configuration.chain), TcpSocket.Builder(), scope) + val databases = databasesFor(nodeParams.nodeId, configuration.chain) + val peer = Peer(nodeParams, walletParams, client, watcher, databases, TcpSocket.Builder(), scope) val payments = mutableListOf() scope.launch { nodeParams.nodeEvents.collect { event -> @@ -278,6 +307,20 @@ class GroupLightningNode( override fun payments(): List = payments.toList() override suspend fun createInvoice(amountMsat: Long?, description: String): String = peer.createInvoice(Lightning.randomBytes32(), amountMsat?.let(::MilliSatoshi), Either.Left(description)).write() + override suspend fun hasPaid(paymentHash: String): Boolean = + databases.payments.listLightningOutgoingPayments(ByteVector32(paymentHash)).isNotEmpty() + override suspend fun pay(bolt11: String, amountMsat: Long): WalletWire.PaymentView { + val invoice = Bolt11Invoice.read(bolt11).get() + return when (val result = peer.payInvoice(MilliSatoshi(amountMsat), invoice)) { + // A payment that went is reported through the node's events, like every other. + is PaymentSent -> paymentView(result.payment, incoming = false) + else -> WalletWire.PaymentView( + id = result.request.paymentId.toString(), incoming = false, amountMsat = amountMsat, feesMsat = 0, + paymentHash = invoice.paymentHash.toHex(), description = invoice.description, + completedAt = Clock.System.now().toEpochMilliseconds(), succeeded = false, + ).also { payments += it } + } + } } } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt new file mode 100644 index 00000000..02fd2629 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/nostr/lightning/GroupLightningAuthorisationEvent.kt @@ -0,0 +1,91 @@ +package com.machankura.bennu.compose.nostr.lightning + +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.vitorpamplona.quartz.nip01Core.core.Kind +import com.vitorpamplona.quartz.nip01Core.signers.EventTemplate +import fr.acinq.bitcoin.Chain +import fr.acinq.lightning.payment.Bolt11Invoice +import kotlin.time.Clock + +/** + * Something the group lets its Lightning wallet do: kind 30346, FROST-signed, never broadcast + * (`docs/group-lightning-wallet.md`, Phase 12). + * + * The operator's node acts on an authorisation, and every co-signer reads it as a budget: an HTLC the + * group's commitment offers must pay a hash some authorisation names, within its amount and fee cap. + * So the operator cannot add a payment, only make one the group signed for. + * + * Only `pay` exists so far. Closing, force-closing and splicing out are Phase 13's, and an action this + * device does not know reads as null, which every caller treats as no authorisation at all. + */ +object GroupLightningAuthorisationEvent { + val KIND: Kind = GroupLightningEvents.AUTHORISATION + + private const val D_TAG = "d" + private const val ACTION_TAG = "action" + private const val INVOICE_TAG = "invoice" + private const val AMOUNT_TAG = "amount" + private const val MAX_FEE_TAG = "maxfee" + private const val HASH_TAG = "hash" + private const val EXPIRES_TAG = "expires" + + const val PAY = "pay" + + /** + * A payment the group authorises, at most [amountMsat] plus [maxFeeMsat], until [expiresAt] (epoch + * seconds). After that no new HTLC for it is signed; one already in flight still settles against it. + */ + data class Pay( + val chain: Chain, + val wallet: Long, + val invoice: String, + val amountMsat: Long, + val maxFeeMsat: Long, + val paymentHash: String, + val expiresAt: Long, + ) { + val budgetMsat: Long get() = amountMsat + maxFeeMsat + } + + fun template(pay: Pay, createdAt: Long = Clock.System.now().epochSeconds): EventTemplate<*> = + EventTemplate( + createdAt = createdAt, + kind = KIND, + tags = arrayOf( + arrayOf(D_TAG, "${GroupLightningWalletStatementEvent.identifier(pay.chain, pay.wallet)}:${pay.paymentHash}"), + arrayOf(ACTION_TAG, PAY), + arrayOf(INVOICE_TAG, pay.invoice), + arrayOf(AMOUNT_TAG, pay.amountMsat.toString()), + arrayOf(MAX_FEE_TAG, pay.maxFeeMsat.toString()), + arrayOf(HASH_TAG, pay.paymentHash), + arrayOf(EXPIRES_TAG, pay.expiresAt.toString()), + ), + content = "", + ) + + /** + * The payment [tags] authorise, or null for anything this device cannot stand behind: an action it + * does not know, an invoice it cannot read, or one that disagrees with what the tags say it is -- + * another network, another hash, another amount, or an expiry past the invoice's own. + */ + fun read(tags: Array>): Pay? { + fun value(name: String): String? = tags.firstOrNull { it.size >= 2 && it[0] == name }?.get(1) + if (value(ACTION_TAG) != PAY) return null + val d = value(D_TAG) ?: return null + val parts = d.split(':') + if (parts.size != 3) return null + val chain = GroupWalletStatementEvent.chainNamed(parts[0]) ?: return null + val wallet = parts[1].toLongOrNull() ?: return null + val bolt11 = value(INVOICE_TAG) ?: return null + val invoice = runCatching { Bolt11Invoice.read(bolt11).get() }.getOrNull() ?: return null + val amount = value(AMOUNT_TAG)?.toLongOrNull()?.takeIf { it > 0 } ?: return null + val maxFee = value(MAX_FEE_TAG)?.toLongOrNull()?.takeIf { it >= 0 } ?: return null + val hash = value(HASH_TAG) ?: return null + val expires = value(EXPIRES_TAG)?.toLongOrNull() ?: return null + if (invoice.chain != chain) return null + if (parts[2] != hash || invoice.paymentHash.toHex() != hash) return null + if (invoice.amount != null && invoice.amount!!.msat != amount) return null + if (expires > invoice.timestampSeconds + (invoice.expirySeconds ?: Bolt11Invoice.DEFAULT_EXPIRY_SECONDS.toLong())) return null + return Pay(chain, wallet, bolt11, amount, maxFee, hash, expires) + } +} 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 d823d81f..b2a0e129 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 @@ -7,6 +7,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.nostr.lightning.GroupLightningAuthorisationEvent import com.machankura.bennu.compose.database.model.IcebergParticipantMessage import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.database.model.types.IcebergApprovalStep @@ -69,4 +70,7 @@ interface GroupLightningRepository { /** The operator's invoice for [requestId], once it has arrived and been checked. */ fun observeInvoice(chatRoomId: String, chain: Chain, requestId: String): Flow + + /** Proposes [pay] to the group; the operator's node pays it once a quorum signs. */ + suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt index 05ffb401..2e8420cb 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedEvent.kt @@ -1,15 +1,11 @@ package com.machankura.bennu.compose.text -import com.machankura.bennu.compose.nostr.lightning.GroupLightningOperatorStatementEvent -import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent -import com.vitorpamplona.quartz.nip01Core.core.Event -import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent -import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent import com.machankura.bennu.compose.managers.SharedKeyDerivation import com.machankura.bennu.compose.nostr.GroupRelaySet import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent -import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent -import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent +import com.machankura.bennu.compose.nostr.lightning.GroupLightningOperatorStatementEvent +import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent import com.machankura.bennu.compose.nostr.nip30303.ArtifactEvent import com.machankura.bennu.compose.nostr.nip30303.ArtifactVersionEvent import com.machankura.bennu.compose.nostr.nip30303.ChapterEvent @@ -17,6 +13,14 @@ import com.machankura.bennu.compose.nostr.nip30303.DialectEvent import com.machankura.bennu.compose.nostr.nip30303.TranslationArtifactVersionEvent import com.machankura.bennu.compose.nostr.nip30303.TranslationChapterEvent import com.machankura.bennu.compose.nostr.nip30303.TranslationChunkEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.text.grouped +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.metadata.MetadataEvent +import com.vitorpamplona.quartz.nip10Notes.TextNoteEvent +import fr.acinq.bitcoin.Satoshi +import fr.acinq.lightning.payment.Bolt11Invoice /** * An event a group is being asked to sign, said in words. @@ -224,6 +228,20 @@ object ProposedEvent { } ?: "An operator statement this device cannot read" ) + // A payment from the Lightning wallet. What a member agrees to is money leaving, so the + // summary leads with the amount and the most the fee can be, then who is paid and for what as + // the invoice says; the payee is a node key, shortened, since nobody checks one by eye. + GroupLightningAuthorisationEvent.KIND -> GroupLightningAuthorisationEvent.read(event.tags)?.let { pay -> + val invoice = runCatching { Bolt11Invoice.read(pay.invoice).get() }.getOrNull() + Summary( + label = "Pay ${Satoshi(pay.amountMsat / 1000).grouped()} sats", + detail = buildString { + append("To ${invoice?.nodeId?.toString()?.take(16) ?: "a node"}, with a fee of at most ${Satoshi(pay.maxFeeMsat / 1000).grouped()} sats") + invoice?.description?.takeIf { it.isNotBlank() }?.let { append(", for \"$it\"") } + }, + ) + } ?: Summary(label = "Authorise the Lightning wallet", detail = "An authorisation this device cannot read") + else -> Summary(label = "Event of kind ${event.kind}", detail = event.content) } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningSendScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningSendScreen.kt new file mode 100644 index 00000000..47f46a33 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningSendScreen.kt @@ -0,0 +1,207 @@ +package com.machankura.bennu.compose.ui.composable + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.text.input.TextFieldLineLimits +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Bolt +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextOverflow +import androidx.lifecycle.viewmodel.compose.viewModel +import bennu.composeapp.generated.resources.Res +import bennu.composeapp.generated.resources.amount_in_sats +import bennu.composeapp.generated.resources.ask_the_group_to_pay +import bennu.composeapp.generated.resources.couldn_t_propose_this +import bennu.composeapp.generated.resources.fee_limit_in_sats +import bennu.composeapp.generated.resources.left_empty_s_sats +import bennu.composeapp.generated.resources.lightning_invoice +import bennu.composeapp.generated.resources.nobody_runs_this_wallet +import bennu.composeapp.generated.resources.paying_asks_the_group_to_sign +import bennu.composeapp.generated.resources.sats +import bennu.composeapp.generated.resources.sats_are_whole_numbers +import bennu.composeapp.generated.resources.send +import bennu.composeapp.generated.resources.that_invoice_has_expired +import bennu.composeapp.generated.resources.that_invoice_is_for_another_network +import bennu.composeapp.generated.resources.that_invoice_names_no_amount +import bennu.composeapp.generated.resources.that_invoice_pays_this_wallet +import bennu.composeapp.generated.resources.that_is_more_sats_than_there_will_ever_be +import bennu.composeapp.generated.resources.that_isn_t_a_lightning_invoice +import bennu.composeapp.generated.resources.that_isn_t_an_amount_in_sats +import bennu.composeapp.generated.resources.the_invoice_names_the_amount_s_sats +import com.machankura.bennu.compose.managers.GroupLightningAuthorisations +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.GroupLightningRepository +import com.machankura.bennu.compose.text.GroupedSats +import com.machankura.bennu.compose.text.SatsInput +import com.machankura.bennu.compose.text.grouped +import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.Route +import com.machankura.bennu.compose.ui.composable.widgets.Decorative +import com.machankura.bennu.compose.ui.composable.widgets.EmptyState +import com.machankura.bennu.compose.ui.composable.widgets.ErrorState +import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator +import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState +import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton +import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition +import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier +import com.machankura.bennu.compose.ui.theme.readableContent +import com.machankura.bennu.compose.ui.theme.spacing +import com.machankura.bennu.compose.ui.view.model.GroupLightningSendViewModel +import com.machankura.bennu.compose.ui.view.state.GroupLightningSendUIState +import com.machankura.bennu.compose.wallet.GroupLightningRollout +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Satoshi +import org.jetbrains.compose.resources.stringResource + +/** + * Proposing a payment from the group's Lightning wallet (`docs/group-lightning-wallet.md`, Phase 12). The + * proposal opens a signing session; the operator's node pays once the group has signed. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupLightningSendScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + chatRepository: ChatRepository, + lightningRepository: GroupLightningRepository, + onNavigateToRoute: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val viewModel: GroupLightningSendViewModel = viewModel( + factory = GroupLightningSendViewModel.factory(activeUserPublicKey, chatRoomId, GroupLightningRollout.NETWORK, chatRepository, lightningRepository) + ) + LaunchedEffect(true) { viewModel.initiate() } + + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotPropose = stringResource(Res.string.couldn_t_propose_this) + val network = GroupWalletStatementEvent.chainName(GroupLightningRollout.NETWORK) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { Text(stringResource(Res.string.send), maxLines = 1, overflow = TextOverflow.Ellipsis) }, + navigationIcon = { NavigateBackButton(onNavigateBack) } + ) + } + ) { padding -> + ScreenStateTransition(viewModel.uiState) { uiState -> + when (val state = uiState) { + GroupLightningSendUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) + + is GroupLightningSendUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null) + + GroupLightningSendUIState.Unavailable -> EmptyState( + modifier = Modifier.padding(padding).readableContent(), + message = stringResource(Res.string.nobody_runs_this_wallet), + icon = Icons.Default.Bolt, + ) + + is GroupLightningSendUIState.Form -> { + val preview = viewModel.preview() + val pay = preview?.getOrNull() + val invoiceProblem = (preview?.exceptionOrNull() as? GroupLightningAuthorisations.ProblemException)?.problem + val invoiceNamesAmount = viewModel.invoiceAmountMsat() != null + Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize().verticalScroll(rememberScrollState()).padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), + ) { + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = viewModel.invoiceField, + lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 4), + label = { Text(stringResource(Res.string.lightning_invoice)) }, + isError = invoiceProblem != null && invoiceProblem != GroupLightningAuthorisations.Problem.NeedsAmount, + supportingText = invoiceProblem?.let { problem -> { Text(problemWith(problem, network)) } } + ?: pay?.takeIf { invoiceNamesAmount }?.let { { Text(stringResource(Res.string.the_invoice_names_the_amount_s_sats, Satoshi(it.amountMsat / 1000).grouped())) } }, + ) + if (!invoiceNamesAmount) { + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = viewModel.amountField, + outputTransformation = GroupedSats, + lineLimits = TextFieldLineLimits.SingleLine, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Next), + label = { Text(stringResource(Res.string.amount_in_sats)) }, + suffix = { Text(stringResource(Res.string.sats)) }, + isError = amountProblem(viewModel.amount()) != null, + supportingText = amountProblem(viewModel.amount())?.let { { Text(it) } }, + ) + } + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = viewModel.maxFeeField, + outputTransformation = GroupedSats, + lineLimits = TextFieldLineLimits.SingleLine, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number, imeAction = ImeAction.Done), + label = { Text(stringResource(Res.string.fee_limit_in_sats)) }, + suffix = { Text(stringResource(Res.string.sats)) }, + isError = amountProblem(viewModel.maxFee()) != null, + supportingText = { + Text( + amountProblem(viewModel.maxFee()) + ?: stringResource(Res.string.left_empty_s_sats, Satoshi(viewModel.defaultMaxFeeSat((pay?.amountMsat ?: 0) / 1000)).grouped()) + ) + }, + ) + Text(stringResource(Res.string.paying_asks_the_group_to_sign), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Button( + modifier = Modifier.fillMaxWidth(), + onClick = { + viewModel.propose( + onSession = { sessionId -> onNavigateToRoute(FrostSigningRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId, sessionId = sessionId)) }, + onFailure = { notify(couldNotPropose) }, + ) + }, + enabled = pay != null && !viewModel.isActionPending.value, + ) { + Icon(Icons.Default.Bolt, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.ask_the_group_to_pay)) + } + } + } + } + } + } +} + +@Composable +private fun problemWith(problem: GroupLightningAuthorisations.Problem, network: String): String = when (problem) { + GroupLightningAuthorisations.Problem.Unreadable -> stringResource(Res.string.that_isn_t_a_lightning_invoice) + GroupLightningAuthorisations.Problem.OtherNetwork -> stringResource(Res.string.that_invoice_is_for_another_network, network) + GroupLightningAuthorisations.Problem.Expired -> stringResource(Res.string.that_invoice_has_expired) + GroupLightningAuthorisations.Problem.NeedsAmount -> stringResource(Res.string.that_invoice_names_no_amount) + GroupLightningAuthorisations.Problem.PaysTheGroup -> stringResource(Res.string.that_invoice_pays_this_wallet) +} + +@Composable +private fun amountProblem(input: SatsInput): String? = when (input) { + SatsInput.Empty, is SatsInput.Sats -> null + SatsInput.NotWhole -> stringResource(Res.string.sats_are_whole_numbers) + SatsInput.TooLarge -> stringResource(Res.string.that_is_more_sats_than_there_will_ever_be) + else -> stringResource(Res.string.that_isn_t_an_amount_in_sats) +} 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 0a27ab6c..8c310fa3 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 @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.ui.composable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -64,6 +65,7 @@ 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.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 @@ -84,6 +86,7 @@ import com.machankura.bennu.compose.repository.GroupLightningRepository import com.machankura.bennu.compose.text.grouped import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningReceiveRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningSendRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.IcebergCeremonyRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.Route @@ -204,6 +207,7 @@ fun GroupLightningWalletScreen( modifier = Modifier.padding(padding), state = state, onReceive = { onNavigateToRoute(GroupLightningReceiveRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) }, + onSend = { onNavigateToRoute(GroupLightningSendRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) }, isPending = viewModel.isActionPending.value, onNominate = { viewModel.nominateSelf(onSession = toSession, onFailure = { notify(couldNotPropose) }) }, onStepDown = { viewModel.stepDown(onSession = toSession, onFailure = { notify(couldNotPropose) }) }, @@ -214,7 +218,7 @@ fun GroupLightningWalletScreen( } @Composable -private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> Unit, isPending: Boolean, onNominate: () -> Unit, onStepDown: () -> Unit) { +private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> Unit, onSend: () -> 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) @@ -224,7 +228,7 @@ private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState. modifier = modifier.readableContent().fillMaxSize().padding(MaterialTheme.spacing.screenMargin), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap), ) { - item { Balance(state.report, onReceive = onReceive.takeIf { state.operator?.publicKey != null }) } + item { Balance(state.report, onReceive = onReceive.takeIf { state.operator?.publicKey != null }, onSend = onSend.takeIf { state.operator?.publicKey != null }) } state.report?.takeIf { it.checks.isNotEmpty() }?.let { report -> item { Text(stringResource(Res.string.channels), style = MaterialTheme.typography.titleSmall) } items(report.checks, key = { it.channel.channelId }) { ChannelRow(it) } @@ -270,7 +274,7 @@ private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState. /** The operator's figure for what the group can spend and receive, or a word that there is none yet. */ @Composable -private fun Balance(report: GroupLightningReports.Report?, onReceive: (() -> Unit)?) { +private fun Balance(report: GroupLightningReports.Report?, onReceive: (() -> Unit)?, onSend: (() -> Unit)?) { Card(modifier = Modifier.fillMaxWidth()) { Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { Text(stringResource(Res.string.balance), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) @@ -281,12 +285,24 @@ private fun Balance(report: GroupLightningReports.Report?, onReceive: (() -> Uni Text(stringResource(Res.string.s_sats_can_be_received, Satoshi(report.snapshot.inboundMsat / 1000).grouped()), style = MaterialTheme.typography.bodyMedium) Text(stringResource(Res.string.reported_by_the_operator_in_term_s, report.snapshot.term.toString()), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) } - // Whoever runs the node makes the invoice, so there is nothing to ask while nobody does. - onReceive?.let { - OutlinedButton(onClick = it) { - Icon(Icons.AutoMirrored.Filled.CallReceived, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.receive)) + // Whoever runs the node makes the invoice and pays what the group signs for, so there is + // nothing to ask while nobody does. + if (onReceive != null || onSend != null) { + Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) { + onReceive?.let { + OutlinedButton(onClick = it) { + Icon(Icons.AutoMirrored.Filled.CallReceived, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.receive)) + } + } + onSend?.let { + OutlinedButton(onClick = it) { + Icon(Icons.AutoMirrored.Filled.CallMade, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.send)) + } + } } } } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt index 04fecb11..4707a5a3 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt @@ -13,6 +13,8 @@ import com.machankura.bennu.compose.wallet.lightning.GroupLightningNodes import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningWalletRoute import com.machankura.bennu.compose.ui.composable.GroupLightningWalletScreen import com.machankura.bennu.compose.ui.composable.GroupLightningReceiveScreen +import com.machankura.bennu.compose.ui.composable.GroupLightningSendScreen +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningSendRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningReceiveRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.IcebergCeremonyRoute import com.machankura.bennu.compose.ui.composable.IcebergCeremonyScreen @@ -742,6 +744,22 @@ fun BennuNavHost( } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + GroupLightningSendScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + chatRepository = databaseChatRepository, + lightningRepository = databaseGroupLightningRepository, + onNavigateToRoute = { actionRoute -> + navController.navigate(route = actionRoute) + }, + onNavigateBack = { + navController.popBackStack() + } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupLightningSendRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupLightningSendRoute.kt new file mode 100644 index 00000000..87266823 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupLightningSendRoute.kt @@ -0,0 +1,10 @@ +package com.machankura.bennu.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** Proposing a payment from the group's Lightning wallet, from the Lightning wallet screen. */ +@Serializable +data class GroupLightningSendRoute( + val activeUserPublicKey: String, + val chatRoomId: String, +) : Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningSendViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningSendViewModel.kt new file mode 100644 index 00000000..6d5290b2 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningSendViewModel.kt @@ -0,0 +1,115 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.managers.GroupLightningAuthorisations +import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.GroupLightningRepository +import com.machankura.bennu.compose.text.SatsInput +import com.machankura.bennu.compose.text.parseSats +import com.machankura.bennu.compose.ui.view.state.GroupLightningSendUIState +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import fr.acinq.lightning.payment.Bolt11Invoice +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * A payment from the group's Lightning wallet, as a proposal: the invoice, the amount when the invoice + * names none, and the most the fee may be. The group signs it like any decision, and the operator's + * node pays it once it has. + */ +class GroupLightningSendViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + val chain: Chain, + initialUIState: GroupLightningSendUIState, + private val chatRepository: ChatRepository, + private val lightningRepository: GroupLightningRepository, +) : ViewModel() { + private val logger = Logger.withTag(TAG) + + var uiState: GroupLightningSendUIState by mutableStateOf(initialUIState) + private set + + val invoiceField = TextFieldState() + val amountField = TextFieldState() + val maxFeeField = TextFieldState() + val isActionPending: MutableState = mutableStateOf(false) + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + ?: return@launch run { uiState = GroupLightningSendUIState.Error("Couldn't find the group") } + val wallet = lightningRepository.lightningWallet(chatRoomId, chain) + uiState = if (wallet == null || lightningRepository.operator(chatRoomId, chain)?.publicKey == null) GroupLightningSendUIState.Unavailable + else GroupLightningSendUIState.Form(localChatRoom, wallet) + } + } + + fun amount(): SatsInput = parseSats(amountField.text) + + /** The amount the invoice in the field names, or null when it names none or is not an invoice. */ + fun invoiceAmountMsat(): Long? = + runCatching { Bolt11Invoice.read(invoiceField.text.toString().trim().removePrefix("lightning:").removePrefix("LIGHTNING:")).get().amount?.msat }.getOrNull() + fun maxFee(): SatsInput = parseSats(maxFeeField.text) + + /** The fee limit when the field is left empty: a percent of [amountSat], and never under ten sats. */ + fun defaultMaxFeeSat(amountSat: Long): Long = maxOf(MIN_FEE_SAT, amountSat / 100) + + /** What the form would propose, or why it cannot; null while the invoice field is empty. */ + fun preview(): Result? { + val form = uiState as? GroupLightningSendUIState.Form ?: return null + if (invoiceField.text.isBlank()) return null + val amountMsat = (amount() as? SatsInput.Sats)?.amount?.sat?.times(1000) + val first = GroupLightningAuthorisations.prepare(form.wallet, invoiceField.text.toString(), amountMsat, maxFeeMsat = 0) + val pay = first.getOrElse { return first } + val maxFeeMsat = when (val fee = maxFee()) { + SatsInput.Empty -> defaultMaxFeeSat(pay.amountMsat / 1000) * 1000 + is SatsInput.Sats -> fee.amount.sat * 1000 + else -> return null + } + return Result.success(pay.copy(maxFeeMsat = maxFeeMsat)) + } + + fun propose(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) { + val form = uiState as? GroupLightningSendUIState.Form ?: return + val pay = preview()?.getOrNull() ?: return onFailure() + if (isActionPending.value) return + isActionPending.value = true + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { lightningRepository.proposePayment(form.localChatRoom, activeUserPublicKey, pay) } + .onFailure { logger.e("Payment proposal in $chatRoomId failed", it) }.getOrNull() + isActionPending.value = false + withContext(Dispatchers.Main) { if (session != null) onSession(session.id) else onFailure() } + } + } + + companion object { + private const val TAG = "GroupLightningSendViewModel" + const val MIN_FEE_SAT = 10L + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + chain: Chain, + chatRepository: ChatRepository, + lightningRepository: GroupLightningRepository, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + GroupLightningSendViewModel(activeUserPublicKey, chatRoomId, chain, GroupLightningSendUIState.Loading, chatRepository, lightningRepository) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningSendUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningSendUIState.kt new file mode 100644 index 00000000..30b6c96e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningSendUIState.kt @@ -0,0 +1,16 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.GroupLightningWalletManager + +/** Proposing a payment from the group's Lightning wallet. */ +sealed class GroupLightningSendUIState { + data object Loading : GroupLightningSendUIState() + + data class Error(val message: String) : GroupLightningSendUIState() + + /** No wallet, or no operator whose node would pay. */ + data object Unavailable : GroupLightningSendUIState() + + data class Form(val localChatRoom: LocalChatRoom, val wallet: GroupLightningWalletManager.Wallet) : GroupLightningSendUIState() +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSignerPolicy.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSignerPolicy.kt index 8561c30f..490ce81c 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSignerPolicy.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSignerPolicy.kt @@ -62,9 +62,20 @@ object CoSignerPolicy { } /** - * @param budgets what each open authorisation has left to spend, by payment hash, in millisatoshi. + * @param budgets what each authorisation has left to spend, by payment hash, in millisatoshi. + * @param closed the payment hashes whose authorisations have expired: an HTLC already in flight for + * one still settles against its budget, and no new one is offered. + * @param inFlightCapMsat the most the HTLCs the group offers may add up to at once: the statement's cap. */ - fun checkRemoteCommitment(previous: Ledger, commitIndex: Long, commitTxId: String, remoteSpec: CommitmentSpec, budgets: Map): Verdict { + fun checkRemoteCommitment( + previous: Ledger, + commitIndex: Long, + commitTxId: String, + remoteSpec: CommitmentSpec, + budgets: Map, + closed: Set = emptySet(), + inFlightCapMsat: Long = Long.MAX_VALUE, + ): Verdict { if (commitIndex == previous.commitIndex) { return if (commitTxId == previous.commitTxId) Verdict.Sign(previous, emptyMap()) else Verdict.Refuse("commitment $commitIndex was already signed as a different transaction") @@ -84,10 +95,16 @@ object CoSignerPolicy { val added = offered.filterKeys { it !in previous.offered } for ((id, htlc) in added.entries.sortedBy { it.key }) { val left = remaining[htlc.paymentHash] ?: return Verdict.Refuse("HTLC $id pays ${htlc.paymentHash.take(16)}, which the group has not authorised") + if (htlc.paymentHash in closed) return Verdict.Refuse("HTLC $id pays ${htlc.paymentHash.take(16)}, whose authorisation has expired") if (htlc.amountMsat > left) return Verdict.Refuse("HTLC $id sends ${htlc.amountMsat} msat against an authorisation with $left msat left") remaining[htlc.paymentHash] = left - htlc.amountMsat } + // The cap holds only for what the group sends: an HTLC offered to it is the counterparty's to + // add, and refusing to sign over one would stall the channel rather than protect anything. + val outgoing = offered.values.sumOf { it.amountMsat } + if (added.isNotEmpty() && outgoing > inFlightCapMsat) return Verdict.Refuse("$outgoing msat would be in flight, over the cap of $inFlightCapMsat") + // Rule 3: the value against the floor. val value = ours + offered.values.sumOf { it.amountMsat } val decrease = (previous.valueMsat - value).coerceAtLeast(0) diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSignerPolicyTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSignerPolicyTest.kt index 7ce0c83c..295ec0c9 100644 --- a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSignerPolicyTest.kt +++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/lightning/CoSignerPolicyTest.kt @@ -38,8 +38,8 @@ class CoSignerPolicyTest { private fun spec(ours: Long, theirs: Long, vararg htlcs: DirectedHtlc) = CommitmentSpec(htlcs.toSet(), FeeratePerKw(Satoshi(2_500)), toLocal = theirs.msat, toRemote = ours.msat) /** The commitment after [previous]'s, as the counterparty would send it. */ - private fun next(previous: CoSignerPolicy.Ledger, spec: CommitmentSpec, budgets: Map = emptyMap()): CoSignerPolicy.Verdict = - CoSignerPolicy.checkRemoteCommitment(previous, previous.commitIndex + 1, "tx${previous.commitIndex + 1}:$spec".hashCode().toString(), spec, budgets) + private fun next(previous: CoSignerPolicy.Ledger, spec: CommitmentSpec, budgets: Map = emptyMap(), closed: Set = emptySet()): CoSignerPolicy.Verdict = + CoSignerPolicy.checkRemoteCommitment(previous, previous.commitIndex + 1, "tx${previous.commitIndex + 1}:$spec".hashCode().toString(), spec, budgets, closed) private fun signed(verdict: CoSignerPolicy.Verdict) = assertIs(verdict) private fun refused(verdict: CoSignerPolicy.Verdict) = assertIs(verdict) @@ -104,4 +104,25 @@ class CoSignerPolicyTest { refused(CoSignerPolicy.checkRemoteCommitment(start, 0, "other", spec(100_000_000, 900_000_000), emptyMap())) refused(CoSignerPolicy.checkRemoteCommitment(start, 2, "tx2", spec(100_000_000, 900_000_000), emptyMap())) } + + @Test + fun `an expired authorisation settles what is in flight, and offers nothing new`() { + val budgets = mapOf(hash(7).toHex() to 30_000_000L) + val closed = setOf(hash(7).toHex()) + refused(next(start, spec(80_000_000, 900_000_000, offered(0, 20_000_000, 7)), budgets, closed)) + val inFlight = signed(next(start, spec(80_000_000, 900_000_000, offered(0, 20_000_000, 7)), budgets)).ledger + refused(next(inFlight, spec(70_000_000, 900_000_000, offered(0, 20_000_000, 7), offered(1, 10_000_000, 7)), budgets, closed)) + val settled = signed(next(inFlight, spec(80_000_000, 920_000_000), budgets, closed)) + assertEquals(mapOf(hash(7).toHex() to 20_000_000L), settled.consumed) + } + + @Test + fun `what the group offers at once stays under the cap, and what it is offered is not counted`() { + val budgets = mapOf(hash(7).toHex() to 50_000_000L, hash(8).toHex() to 50_000_000L) + fun capped(previous: CoSignerPolicy.Ledger, spec: CommitmentSpec) = + CoSignerPolicy.checkRemoteCommitment(previous, previous.commitIndex + 1, "tx${previous.commitIndex + 1}:$spec".hashCode().toString(), spec, budgets, inFlightCapMsat = 40_000_000) + val one = signed(capped(start, spec(70_000_000, 900_000_000, offered(0, 30_000_000, 7)))).ledger + refused(capped(one, spec(50_000_000, 900_000_000, offered(0, 30_000_000, 7), offered(1, 20_000_000, 8)))) + signed(capped(one, spec(70_000_000, 850_000_000, offered(0, 30_000_000, 7), toUs(1, 50_000_000, 2)))) + } } 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 005bb8fc..a6d93e37 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 @@ -21,6 +21,9 @@ class FakeGroupNode(private val configuration: GroupLightningNode.NodeConfigurat var channels = listOf() val payments = mutableListOf() val invoices = mutableListOf() + /** Every payment asked of the node, as (invoice, amount). */ + val paid = mutableListOf>() + var paymentsSucceed = true override suspend fun connect(): Boolean { connected = true; return true } override fun disconnect() { disconnected = true } @@ -32,6 +35,13 @@ class FakeGroupNode(private val configuration: GroupLightningNode.NodeConfigurat configuration.chain, amountMsat?.let(::MilliSatoshi), randomBytes32(), configuration.keyManager.nodeKeys.nodeKey.privateKey, Either.Left(description), CltvExpiryDelta(144), INVOICE_FEATURES, ).also { invoices += it }.write() + 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 + val invoice = Bolt11Invoice.read(bolt11).get() + return WalletWire.PaymentView("out${paid.size}", incoming = false, amountMsat = amountMsat, feesMsat = 1_000, paymentHash = invoice.paymentHash.toHex(), description = invoice.description, completedAt = 1, succeeded = paymentsSucceed) + .also { payments += it } + } } /** What a Bolt11 invoice must advertise to be read back at all. */ diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningPaymentsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningPaymentsJvmTest.kt new file mode 100644 index 00000000..937450bb --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningPaymentsJvmTest.kt @@ -0,0 +1,146 @@ +package com.machankura.bennu.compose.managers + +import com.machankura.bennu.compose.database.model.MarmotGroupEvent +import com.machankura.bennu.compose.database.model.NostrEvent +import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent +import com.machankura.bennu.compose.text.ProposedEvent +import com.vitorpamplona.quartz.nip01Core.core.Event +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.utils.Either +import fr.acinq.lightning.CltvExpiryDelta +import fr.acinq.lightning.Lightning.randomBytes32 +import fr.acinq.lightning.payment.Bolt11Invoice +import fr.acinq.lightning.utils.msat +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +/** + * Paying from the group's Lightning wallet (`docs/group-lightning-wallet.md`, Phase 12): the group signs an + * authorisation, every co-signer reads it as a budget, and the operator's node pays it once. Nothing the + * group did not sign becomes a budget. + */ +class GroupLightningPaymentsJvmTest { + private val fixture = GroupLightningFixture() + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val lsp = "02" + KeyPair().pubKey.toHexKey() + private val payee = PrivateKey(randomBytes32()) + private val nodes = mutableListOf() + + @AfterTest + fun close() { + scope.cancel() + fixture.close() + } + + private fun invoice(amountMsat: Long? = 12_000_000, chain: Chain = fixture.chain, signer: PrivateKey = payee, expirySeconds: Long? = null, timestamp: Long = Clock.System.now().epochSeconds) = + Bolt11Invoice.create(chain, amountMsat?.msat, randomBytes32(), signer, Either.Left("coffee"), CltvExpiryDelta(144), INVOICE_FEATURES, expirySeconds = expirySeconds, timestampSeconds = timestamp) + + private suspend fun opened(): Pair, GroupLightningWalletManager.Wallet> { + val all = fixture.group() + fixture.runCeremony(all) + fixture.signSession(all, all[0], GroupLightningWalletManager.proposeWallet(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, fixture.chain, lsp).id) + fixture.signSession(all, all[1], GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, fixture.chain).id) + return all to GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! + } + + private suspend fun authorise(all: List, pay: GroupLightningAuthorisationEvent.Pay, proposer: GroupLightningFixture.Device = all[3]) { + fixture.signSession(all, proposer, GroupLightningAuthorisations.propose(proposer.db, proposer.room, proposer.publicKey, pay).id) + } + + @Test + fun `an authorisation reads back as what it was, and refuses to disagree with its invoice`() = runBlocking { + val (_, wallet) = opened() + val pay = GroupLightningAuthorisations.prepare(wallet, "lightning:" + invoice().write(), null, 1_000_000).getOrThrow() + assertEquals(12_000_000, pay.amountMsat) + assertEquals(13_000_000, pay.budgetMsat) + val tags = GroupLightningAuthorisationEvent.template(pay).tags + assertEquals(pay, GroupLightningAuthorisationEvent.read(tags)) + + fun with(name: String, value: String) = tags.map { if (it[0] == name) arrayOf(name, value) else it }.toTypedArray() + assertNull(GroupLightningAuthorisationEvent.read(with("amount", "13000000")), "an amount the invoice does not name") + assertNull(GroupLightningAuthorisationEvent.read(with("hash", "00".repeat(32))), "a hash the invoice does not carry") + assertNull(GroupLightningAuthorisationEvent.read(with("expires", (Clock.System.now() + 2.hours).epochSeconds.toString())), "an expiry past the invoice's") + assertNull(GroupLightningAuthorisationEvent.read(with("action", "splice")), "an action this device does not know") + + val summary = ProposedEvent.summarize(Event("", "", 0, GroupLightningAuthorisationEvent.KIND, tags, "", "")) + assertEquals("Pay 12,000 sats", summary.label) + assertTrue("coffee" in summary.detail && "1,000 sats" in summary.detail, summary.detail) + } + + @Test + fun `what cannot be paid is said before the group is asked`() = runBlocking { + val (_, wallet) = opened() + fun problem(bolt11: String, amount: Long? = null) = + (GroupLightningAuthorisations.prepare(wallet, bolt11, amount, 0).exceptionOrNull() as GroupLightningAuthorisations.ProblemException).problem + assertEquals(GroupLightningAuthorisations.Problem.Unreadable, problem("lnbc1nonsense")) + assertEquals(GroupLightningAuthorisations.Problem.OtherNetwork, problem(invoice(chain = Chain.Mainnet).write())) + assertEquals(GroupLightningAuthorisations.Problem.Expired, problem(invoice(expirySeconds = 60, timestamp = Clock.System.now().epochSeconds - 120).write())) + assertEquals(GroupLightningAuthorisations.Problem.NeedsAmount, problem(invoice(amountMsat = null).write())) + val nodeKey = GroupLightningCoSigner.keyManagerOf(fr.acinq.bitcoin.ByteVector(wallet.seed!!.seed), fixture.chain).nodeKeys.nodeKey.privateKey + assertEquals(GroupLightningAuthorisations.Problem.PaysTheGroup, problem(invoice(signer = nodeKey).write())) + assertEquals(5_000_000, GroupLightningAuthorisations.prepare(wallet, invoice(amountMsat = null).write(), 5_000_000, 0).getOrThrow().amountMsat) + } + + @Test + fun `once the group signs, every co-signer has the budget, and an expired one is closed`() = runBlocking { + val (all, wallet) = opened() + assertTrue(GroupLightningAuthorisations.budgets(all[2].db, wallet).isEmpty(), "nothing is authorised yet") + val pay = GroupLightningAuthorisations.prepare(wallet, invoice().write(), null, 1_000_000).getOrThrow() + authorise(all, pay) + all.forEach { d -> + val mine = GroupLightningWalletManager.walletFor(d.db, fixture.roomId, fixture.chain)!! + assertEquals(mapOf(pay.paymentHash to 13_000_000L), GroupLightningAuthorisations.budgets(d.db, mine), "device ${d.index}") + assertTrue(GroupLightningAuthorisations.expired(d.db, mine).isEmpty()) + assertEquals(listOf(pay), GroupLightningAuthorisations.toPay(d.db, mine)) + } + val later = Clock.System.now() + 2.hours + assertEquals(setOf(pay.paymentHash), GroupLightningAuthorisations.expired(all[2].db, wallet, later)) + assertTrue(GroupLightningAuthorisations.toPay(all[2].db, wallet, later).isEmpty()) + // Still a budget: an HTLC that left before the expiry settles against it. + assertEquals(13_000_000L, GroupLightningAuthorisations.budgets(all[2].db, wallet)[pay.paymentHash]) + } + + @Test + fun `the operator's node pays what the group authorised, once`() = runBlocking { + val (all, _) = opened() + val operator = all[1] + val id = randomBytes32().toHex() + operator.db.nostrEventDao().upsert(NostrEvent(id = id, pubKey = operator.publicKey, kind = 445, tags = emptyArray(), content = "", sig = "0".repeat(128))) + operator.db.marmotGroupEventDao().upsert(MarmotGroupEvent(id = id, userPublicKey = operator.publicKey, publicKey = operator.publicKey, chatRoomId = fixture.roomId, signature = "", encryptedContent = "", expiresAt = null, savedAt = Clock.System.now())) + val node = GroupLightningNode( + operator.db, operator.room, operator.publicKey, GroupLightningWalletManager.walletFor(operator.db, fixture.roomId, fixture.chain)!!, scope, + { configuration -> FakeGroupNode(configuration).also { nodes += it } }, + handoverCheck = 10.minutes, + ) + assertIs(node.start()) + node.payAuthorised() + assertTrue(nodes.single().paid.isEmpty(), "nothing is authorised") + + val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!! + val bolt11 = invoice().write() + authorise(all, GroupLightningAuthorisations.prepare(wallet, bolt11, null, 1_000_000).getOrThrow()) + node.payAuthorised() + withTimeout(5.seconds) { while (nodes.single().paid.isEmpty()) delay(20) } + node.payAuthorised() + delay(200) + assertEquals(listOf(bolt11 to 12_000_000L), nodes.single().paid) + } +} 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 9afdc8a6..2f8be0be 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 @@ -10,21 +10,31 @@ import com.machankura.bennu.compose.database.model.IcebergParticipantMessage import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.database.model.types.IcebergApprovalStep import com.machankura.bennu.compose.database.model.types.IcebergRitualStage +import com.machankura.bennu.compose.managers.GroupLightningAuthorisations import com.machankura.bennu.compose.managers.GroupLightningDerivation 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.nostr.lightning.GroupLightningAuthorisationEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningOperatorStatementEvent import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent import com.machankura.bennu.compose.repository.ChatRepository 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.WalletWire import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.utils.Either +import fr.acinq.lightning.CltvExpiryDelta +import fr.acinq.lightning.Feature +import fr.acinq.lightning.FeatureSupport +import fr.acinq.lightning.Features +import fr.acinq.lightning.payment.Bolt11Invoice +import fr.acinq.lightning.utils.msat import fr.acinq.secp256k1.Hex import kotlin.test.AfterTest import kotlin.test.BeforeTest @@ -111,6 +121,7 @@ class GroupLightningWalletViewModelJvmTest { override suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String = "r1".also { requests += amountMsat to description } 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") } private val chat = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { @@ -198,4 +209,31 @@ class GroupLightningWalletViewModelJvmTest { runBlocking { withTimeout(5_000) { while (viewModel.uiState == GroupLightningReceiveUIState.Loading) delay(10) } } return viewModel } + + @Test + fun `sending previews the authorisation, with a fee limit when none is given`() { + val lightning = Lightning(completed = key, wallet = wallet, operator = operator("b".repeat(64))) + val viewModel = GroupLightningSendViewModel(me, chatRoomId, Chain.Testnet3, GroupLightningSendUIState.Loading, chat, lightning) + viewModel.initiate() + runBlocking { withTimeout(5_000) { while (viewModel.uiState == GroupLightningSendUIState.Loading) delay(10) } } + assertIs(viewModel.uiState) + assertEquals(null, viewModel.preview(), "nothing typed, nothing to say") + + fun invoice(chain: Chain, amount: Long?) = Bolt11Invoice.create( + chain, amount?.msat, ByteVector32(Hex.decode("07".repeat(32))), PrivateKey(ByteVector32(Hex.decode("05".repeat(32)))), Either.Left("tea"), CltvExpiryDelta(144), + Features(Feature.VariableLengthOnion to FeatureSupport.Mandatory, Feature.PaymentSecret to FeatureSupport.Mandatory), + ).write() + viewModel.invoiceField.edit { append(invoice(Chain.Testnet3, 50_000_000)) } + val pay = viewModel.preview()!!.getOrThrow() + assertEquals(50_000_000, pay.amountMsat) + assertEquals(500_000, pay.maxFeeMsat, "a percent of fifty thousand sats") + assertEquals(50_000_000, viewModel.invoiceAmountMsat()) + + viewModel.maxFeeField.edit { append("20") } + assertEquals(20_000, viewModel.preview()!!.getOrThrow().maxFeeMsat) + + viewModel.invoiceField.edit { replace(0, length, invoice(Chain.Mainnet, 1_000)) } + val problem = (viewModel.preview()!!.exceptionOrNull() as GroupLightningAuthorisations.ProblemException).problem + assertEquals(GroupLightningAuthorisations.Problem.OtherNetwork, problem) + } } diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md index 6d76d91e..a2722a2c 100644 --- a/docs/group-lightning-wallet.md +++ b/docs/group-lightning-wallet.md @@ -40,6 +40,7 @@ build chose differently, this table says so. | 8 | done: `GroupLightningNode`, `GroupNodeKeyManager` and `GroupLightningNodes`, wired into the app behind `GroupLightningRollout`. Four tests with a stand-in peer cover the keys, the start gate and the handover. The node has not connected to an LSP: that needs Phase 0's testnet3 run | | 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 | | what the plan said | what it turned out to be | |---|---| @@ -90,6 +91,12 @@ build chose differently, this table says so. | payments come from lightning-kmp's payments database | from `nodeParams.nodeEvents`, as they happen while the node runs, because the database has no query for all payments. Members keep every payment a snapshot carried, so a restart only loses what a stopped node would not have reported anyway | | the operator's node answers an invoice request as it arrives | it reads the room's unanswered requests each time it checks for a handover, because the inbound path has no handle on a running node. An invoice therefore takes up to `HANDOVER_CHECK`, ten seconds, plus the room's own delay. A request whose answer is lost is answered again by the next operator, since the answer is what marks it answered | | an optional Bolt12 offer, from `nodeParams.defaultOffer` | **not built.** An offer is long-lived and pays whichever node holds its key; a group whose operator changes needs every member to know the offer still reaches the group's node, and that is the same check as a Bolt11 invoice's, made once. It is a small follow-up once a node has run on testnet3 | +| each co-signer has a budget until the payment settles, fails or expires | an authorisation's budget lasts as long as the authorisation, and its *expiry* only closes it to new HTLCs (`CoSignerPolicy`'s `closed`). An HTLC that left before the expiry and settles after it still has to be explained, and dropping the budget at expiry would leave the co-signers refusing the commitment that settles it. A failed HTLC spends nothing, so the budget is still there; a second attempt needs nothing new from the group, only the node to try again | +| the operator's node pays an authorisation once | once per payment hash, ever: a node that tried and failed does not try again by itself. The member who wants another attempt asks the group again, and the co-signers' budgets are what keep two attempts from both paying | +| a fee cap per payment | the fee is not passed to lightning-kmp, whose `payInvoice` takes the trampoline fees from the LSP's wallet parameters. The cap is the co-signers': an HTLC worth more than the amount and the fee cap is over budget, so its commitment is never signed | +| the total in flight is under the statement's cap (check 5) | it was not checked until this phase, because nothing could be offered. It is now, for what the group *offers*: an HTLC offered *to* the group is the counterparty's to add, and refusing to sign over one would stall the channel without protecting anything | +| two authorisations for one invoice | one payment: its budget is the larger of the two, and it is open while either is. Signing an invoice a second time therefore only extends its life | +| an offer (Bolt12) can be paid | Bolt11 only. `Peer.payOffer` exists, but the hash an HTLC pays is not known until the offer's invoice is fetched, so a co-signer has nothing to hold it to. An authorisation that names an offer and a per-payment budget is the follow-up | | 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 |