feat(lightning): members receive into the group's Lightning wallet (Phase 11)

A member asks for an invoice (kind 30347) from the new receive screen; the
operator's running node finds each request no invoice answers yet, makes
one with lightning-kmp's `createInvoice`, and sends it to the room (kind
30348). Every member files an invoice only from the operator, and only if
it pays the node the group's statement names, so the screen never shows
an invoice that pays somebody else.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-10-23 18:20:18 +02:00
1 parent 33a1ef0ed2
commit b4fbae748d
13 files changed
+462 -11

No files matched your search

@@ -737,4 +737,14 @@
<string name="received_s_sats">Received %1$s sats</string>
<string name="sent_s_sats_with_a_fee_of_s_sats">Sent %1$s sats, with a fee of %2$s sats</string>
<string name="couldn_t_send_s_sats">Couldn't send %1$s sats</string>
<string name="receive">Receive</string>
<string name="what_it_is_for">What it's for</string>
<string name="leave_the_amount_empty_to_let_the_payer_choose">Leave the amount empty to let the payer choose.</string>
<string name="ask_for_an_invoice">Ask for an invoice</string>
<string name="waiting_for_the_operator_s_device">Waiting for the operator's device to make the invoice. It has to be online.</string>
<string name="this_invoice_pays_the_group_s_node">This invoice pays the group's node, the one the group signed for. Whatever it receives is the group's.</string>
<string name="copy_invoice">Copy invoice</string>
<string name="invoice_copied">Invoice copied</string>
<string name="nobody_runs_this_wallet_to_make_an_invoice">Nobody runs this wallet yet, so there is no node to make an invoice.</string>
<string name="couldn_t_ask_for_an_invoice">Couldn't ask for an invoice.</string>
</resources>
@@ -7,6 +7,7 @@ import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.database.model.types.IcebergApprovalStep
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.GroupLightningCoSigner
import com.machankura.bennu.compose.managers.GroupLightningOperatorManager
@@ -51,6 +52,12 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr
override fun observePayments(chatRoomId: String, chain: Chain): Flow<List<GroupLightningPaymentRow>> =
database.groupLightningRecordsDao().observePayments(GroupLightningCoSigner.walletKey(chatRoomId, chain, 0L))
override suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String =
GroupLightningReports.requestInvoice(database, localChatRoom, userPublicKey, wallet, amountMsat, description)
override fun observeInvoice(chatRoomId: String, chain: Chain, requestId: String): Flow<GroupLightningInvoiceRow?> =
database.groupLightningRecordsDao().observeInvoice(GroupLightningCoSigner.walletKey(chatRoomId, chain, 0L), requestId)
override fun observeCeremony(sessionId: String): Flow<IcebergKeySession?> =
database.icebergKeySessionDao().observeSessionById(sessionId)
@@ -2,6 +2,7 @@ package com.machankura.bennu.compose.repository
import com.machankura.bennu.compose.database.model.FrostSigningSession
import com.machankura.bennu.compose.database.model.IcebergKeySession
import com.machankura.bennu.compose.database.model.GroupLightningInvoiceRow
import com.machankura.bennu.compose.database.model.GroupLightningPaymentRow
import com.machankura.bennu.compose.managers.GroupLightningOperatorManager
import com.machankura.bennu.compose.managers.GroupLightningReports
@@ -62,4 +63,10 @@ interface GroupLightningRepository {
/** Every payment any snapshot has reported, newest first. */
fun observePayments(chatRoomId: String, chain: Chain): Flow<List<GroupLightningPaymentRow>>
/** Asks the operator's node for an invoice; returns the request id its answer will carry. */
suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String
/** The operator's invoice for [requestId], once it has arrived and been checked. */
fun observeInvoice(chatRoomId: String, chain: Chain, requestId: String): Flow<GroupLightningInvoiceRow?>
}
@@ -0,0 +1,191 @@
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.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.ContentCopy
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.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.buildAnnotatedString
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_for_an_invoice
import bennu.composeapp.generated.resources.copy_invoice
import bennu.composeapp.generated.resources.couldn_t_ask_for_an_invoice
import bennu.composeapp.generated.resources.invoice_copied
import bennu.composeapp.generated.resources.leave_the_amount_empty_to_let_the_payer_choose
import bennu.composeapp.generated.resources.nobody_runs_this_wallet_to_make_an_invoice
import bennu.composeapp.generated.resources.receive
import bennu.composeapp.generated.resources.sats
import bennu.composeapp.generated.resources.sats_are_whole_numbers
import bennu.composeapp.generated.resources.that_is_more_sats_than_there_will_ever_be
import bennu.composeapp.generated.resources.that_isn_t_an_amount_in_sats
import bennu.composeapp.generated.resources.this_invoice_pays_the_group_s_node
import bennu.composeapp.generated.resources.waiting_for_the_operator_s_device
import bennu.composeapp.generated.resources.what_it_is_for
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.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.QRCodeView
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.GroupLightningReceiveViewModel
import com.machankura.bennu.compose.ui.view.state.GroupLightningReceiveUIState
import com.machankura.bennu.compose.wallet.GroupLightningRollout
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import org.jetbrains.compose.resources.stringResource
/**
* Receiving into the group's Lightning wallet: a member asks, the operator's node makes the invoice, and
* it is shown once this device has checked it pays the group's node (`docs/group-lightning-wallet.md`,
* Phase 11).
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GroupLightningReceiveScreen(
activeUserPublicKey: HexKey,
chatRoomId: String,
chatRepository: ChatRepository,
lightningRepository: GroupLightningRepository,
onNavigateBack: () -> Unit,
) {
val viewModel: GroupLightningReceiveViewModel = viewModel(
factory = GroupLightningReceiveViewModel.factory(activeUserPublicKey, chatRoomId, GroupLightningRollout.NETWORK, chatRepository, lightningRepository)
)
LaunchedEffect(true) { viewModel.initiate() }
val notify = rememberNotifier(rememberCoroutineScope())
val couldNotAsk = stringResource(Res.string.couldn_t_ask_for_an_invoice)
val copied = stringResource(Res.string.invoice_copied)
val clipboardManager = LocalClipboardManager.current
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
TopAppBar(
title = { Text(stringResource(Res.string.receive), maxLines = 1, overflow = TextOverflow.Ellipsis) },
navigationIcon = { NavigateBackButton(onNavigateBack) }
)
}
) { padding ->
ScreenStateTransition(viewModel.uiState) { uiState ->
when (val state = uiState) {
GroupLightningReceiveUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding))
is GroupLightningReceiveUIState.Error -> ErrorState(modifier = Modifier.padding(padding), message = state.message, onRetry = null)
GroupLightningReceiveUIState.Unavailable -> EmptyState(
modifier = Modifier.padding(padding).readableContent(),
message = stringResource(Res.string.nobody_runs_this_wallet_to_make_an_invoice),
icon = Icons.Default.Bolt,
)
is GroupLightningReceiveUIState.Form -> {
val amountProblem = when (viewModel.amount()) {
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)
}
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.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 != null,
supportingText = { Text(amountProblem ?: stringResource(Res.string.leave_the_amount_empty_to_let_the_payer_choose)) },
)
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
state = viewModel.descriptionField,
lineLimits = TextFieldLineLimits.SingleLine,
label = { Text(stringResource(Res.string.what_it_is_for)) },
)
Button(
modifier = Modifier.fillMaxWidth(),
onClick = { viewModel.request(onFailure = { notify(couldNotAsk) }) },
enabled = amountProblem == null && !viewModel.isActionPending.value,
) {
Icon(Icons.Default.Bolt, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.ask_for_an_invoice))
}
}
}
is GroupLightningReceiveUIState.Waiting -> Column(
modifier = Modifier.padding(padding).readableContent().fillMaxSize().padding(MaterialTheme.spacing.screenMargin),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
) {
LoadingDataIndicator(modifier = Modifier.fillMaxWidth())
Text(stringResource(Res.string.waiting_for_the_operator_s_device), style = MaterialTheme.typography.bodyLarge)
}
is GroupLightningReceiveUIState.Invoice -> Column(
modifier = Modifier.padding(padding).readableContent().fillMaxSize().verticalScroll(rememberScrollState()).padding(MaterialTheme.spacing.screenMargin),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
) {
// The URI scheme, so a scanning wallet knows what the text is.
QRCodeView("lightning:${state.bolt11}")
Text(stringResource(Res.string.this_invoice_pays_the_group_s_node), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
SelectionContainer { Text(state.bolt11, style = MaterialTheme.typography.bodySmall) }
TextButton(onClick = {
clipboardManager.setText(buildAnnotatedString { append(state.bolt11) })
notify(copied)
}) {
Icon(Icons.Default.ContentCopy, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.copy_invoice))
}
}
}
}
}
}
@@ -55,6 +55,7 @@ import bennu.composeapp.generated.resources.open_a_lightning_wallet
import bennu.composeapp.generated.resources.open_an_onchain_wallet_on_s_first
import bennu.composeapp.generated.resources.opening_a_lightning_wallet_asks
import bennu.composeapp.generated.resources.payments
import bennu.composeapp.generated.resources.receive
import bennu.composeapp.generated.resources.received_s_sats
import bennu.composeapp.generated.resources.reported_by_the_operator_in_term_s
import bennu.composeapp.generated.resources.run_by_s_term_s
@@ -82,6 +83,7 @@ import com.machankura.bennu.compose.repository.ChatRepository
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.GroupWalletRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.IcebergCeremonyRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.Route
@@ -201,6 +203,7 @@ fun GroupLightningWalletScreen(
is GroupLightningWalletUIState.Opened -> OpenedWallet(
modifier = Modifier.padding(padding),
state = state,
onReceive = { onNavigateToRoute(GroupLightningReceiveRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) },
isPending = viewModel.isActionPending.value,
onNominate = { viewModel.nominateSelf(onSession = toSession, onFailure = { notify(couldNotPropose) }) },
onStepDown = { viewModel.stepDown(onSession = toSession, onFailure = { notify(couldNotPropose) }) },
@@ -211,7 +214,7 @@ fun GroupLightningWalletScreen(
}
@Composable
private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, isPending: Boolean, onNominate: () -> Unit, onStepDown: () -> Unit) {
private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> 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)
@@ -221,7 +224,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) }
item { Balance(state.report, onReceive = onReceive.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) }
@@ -267,7 +270,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?) {
private fun Balance(report: GroupLightningReports.Report?, onReceive: (() -> 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)
@@ -278,6 +281,14 @@ private fun Balance(report: GroupLightningReports.Report?) {
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))
}
}
}
}
}
@@ -12,6 +12,8 @@ import com.machankura.bennu.compose.managers.GroupLightningNode
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.navigation.routes.GroupLightningReceiveRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.IcebergCeremonyRoute
import com.machankura.bennu.compose.ui.composable.IcebergCeremonyScreen
import com.machankura.bennu.compose.database.repository.DatabaseGroupLightningRepository
@@ -727,6 +729,19 @@ fun BennuNavHost(
}
)
}
composable<GroupLightningReceiveRoute> { backStackEntry ->
val route = backStackEntry.toRoute<GroupLightningReceiveRoute>()
GroupLightningReceiveScreen(
activeUserPublicKey = route.activeUserPublicKey,
chatRoomId = route.chatRoomId,
chatRepository = databaseChatRepository,
lightningRepository = databaseGroupLightningRepository,
onNavigateBack = {
navController.popBackStack()
}
)
}
composable<IcebergCeremonyRoute> { backStackEntry ->
val route = backStackEntry.toRoute<IcebergCeremonyRoute>()
@@ -0,0 +1,10 @@
package com.machankura.bennu.compose.ui.composable.navigation.routes
import kotlinx.serialization.Serializable
/** Asking the group's Lightning node for an invoice, from the Lightning wallet screen. */
@Serializable
data class GroupLightningReceiveRoute(
val activeUserPublicKey: String,
val chatRoomId: String,
) : Route()
@@ -0,0 +1,97 @@
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.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.GroupLightningReceiveUIState
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.Chain
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Asks the operator's node for an invoice and waits for it. Any member may ask; the invoice arrives
* only once the inbound path has checked that it pays the node the group signed for.
*/
class GroupLightningReceiveViewModel(
val activeUserPublicKey: HexKey,
val chatRoomId: String,
val chain: Chain,
initialUIState: GroupLightningReceiveUIState,
private val chatRepository: ChatRepository,
private val lightningRepository: GroupLightningRepository,
) : ViewModel() {
private val logger = Logger.withTag(TAG)
var uiState: GroupLightningReceiveUIState by mutableStateOf(initialUIState)
private set
val amountField = TextFieldState()
val descriptionField = TextFieldState()
val isActionPending: MutableState<Boolean> = mutableStateOf(false)
fun initiate() {
viewModelScope.launch(Dispatchers.IO) {
val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId)
?: return@launch run { uiState = GroupLightningReceiveUIState.Error("Couldn't find the group") }
val wallet = lightningRepository.lightningWallet(chatRoomId, chain)
uiState = if (wallet == null || lightningRepository.operator(chatRoomId, chain)?.publicKey == null) GroupLightningReceiveUIState.Unavailable
else GroupLightningReceiveUIState.Form(localChatRoom, wallet)
}
}
/** The amount typed, in sats; null for none, and [SatsInput] problems as they are. */
fun amount(): SatsInput = parseSats(amountField.text)
fun request(onFailure: () -> Unit) {
val form = uiState as? GroupLightningReceiveUIState.Form ?: return
val amountMsat = when (val amount = amount()) {
SatsInput.Empty -> null
is SatsInput.Sats -> amount.amount.sat * 1000
else -> return onFailure()
}
if (isActionPending.value) return
isActionPending.value = true
viewModelScope.launch(Dispatchers.IO) {
val requestId = runCatching {
lightningRepository.requestInvoice(form.localChatRoom, activeUserPublicKey, form.wallet, amountMsat, descriptionField.text.toString().trim())
}.onFailure { logger.e("Invoice request in $chatRoomId failed", it) }.getOrNull()
isActionPending.value = false
if (requestId == null) return@launch withContext(Dispatchers.Main) { onFailure() }
uiState = GroupLightningReceiveUIState.Waiting(requestId)
val invoice = lightningRepository.observeInvoice(chatRoomId, chain, requestId).filterNotNull().first()
uiState = GroupLightningReceiveUIState.Invoice(invoice.bolt11)
}
}
companion object {
private const val TAG = "GroupLightningReceiveViewModel"
fun factory(
activeUserPublicKey: HexKey,
chatRoomId: String,
chain: Chain,
chatRepository: ChatRepository,
lightningRepository: GroupLightningRepository,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
GroupLightningReceiveViewModel(activeUserPublicKey, chatRoomId, chain, GroupLightningReceiveUIState.Loading, chatRepository, lightningRepository)
}
}
}
}
@@ -0,0 +1,21 @@
package com.machankura.bennu.compose.ui.view.state
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.managers.GroupLightningWalletManager
/** Asking the operator's node for an invoice: the form, the wait for the operator's device, the invoice. */
sealed class GroupLightningReceiveUIState {
data object Loading : GroupLightningReceiveUIState()
data class Error(val message: String) : GroupLightningReceiveUIState()
/** No wallet, or no operator to run its node. */
data object Unavailable : GroupLightningReceiveUIState()
data class Form(val localChatRoom: LocalChatRoom, val wallet: GroupLightningWalletManager.Wallet) : GroupLightningReceiveUIState()
data class Waiting(val requestId: String) : GroupLightningReceiveUIState()
/** An invoice the operator made, already checked to pay the group's node. */
data class Invoice(val bolt11: String) : GroupLightningReceiveUIState()
}
@@ -3,6 +3,8 @@ package com.machankura.bennu.compose.managers
import com.machankura.bennu.compose.wallet.lightning.WalletWire
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.Lightning.randomBytes32
import fr.acinq.lightning.MilliSatoshi
@@ -28,6 +30,9 @@ class FakeGroupNode(private val configuration: GroupLightningNode.NodeConfigurat
override suspend fun createInvoice(amountMsat: Long?, description: String): String =
Bolt11Invoice.create(
configuration.chain, amountMsat?.let(::MilliSatoshi), randomBytes32(), configuration.keyManager.nodeKeys.nodeKey.privateKey,
Either.Left(description), CltvExpiryDelta(144), Features.empty,
Either.Left(description), CltvExpiryDelta(144), INVOICE_FEATURES,
).also { invoices += it }.write()
}
/** What a Bolt11 invoice must advertise to be read back at all. */
val INVOICE_FEATURES = Features(Feature.VariableLengthOnion to FeatureSupport.Mandatory, Feature.PaymentSecret to FeatureSupport.Mandatory)
@@ -10,13 +10,13 @@ import com.machankura.bennu.compose.wallet.lightning.WalletWire
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.ByteVector
import fr.acinq.bitcoin.PrivateKey
import fr.acinq.bitcoin.utils.Either
import fr.acinq.lightning.CltvExpiryDelta
import fr.acinq.lightning.Lightning.randomBytes32
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import fr.acinq.lightning.payment.Bolt11Invoice
import fr.acinq.lightning.utils.msat
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
@@ -25,12 +25,19 @@ import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.time.Clock
import kotlin.time.Duration.Companion.minutes
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
/**
* What the operator's node tells the room, and what each member makes of it
* (`docs/group-lightning-wallet.md`, Phase 10): a snapshot is believed only from the operator of the term
* it names, every member files it with each channel checked against its own co-signing ledger, and the
* round-one assignments it carries reach whoever operates next.
* round-one assignments it carries reach whoever operates next. And an invoice a member asks for (Phase 11)
* is made by the operator's node and believed only if it pays the group's node.
*/
class GroupLightningReportsJvmTest {
private val fixture = GroupLightningFixture()
@@ -131,4 +138,42 @@ class GroupLightningReportsJvmTest {
assertEquals(GroupLightningCoSigner.poolLabel(wallet.statement.icebergKey, 5).toHex(), assignment.label)
assertNull(all[2].db.icebergCoSigningDao().assignmentFor(key, "verification:x:y:0"))
}
@Test
fun `a member asks for an invoice, and the operator's node makes one that pays the group's node`() = runBlocking<Unit> {
val (all, node) = running()
val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!!
val requestId = GroupLightningReports.requestInvoice(all[3].db, all[3].room, all[3].publicKey, wallet, 21_000_000, "lunch")
fixture.pump(all, setOf(GroupLightningEvents.INVOICE_REQUEST))
node.answerInvoiceRequests()
node.answerInvoiceRequests()
assertEquals(1, nodes.single().invoices.size, "a request is answered once")
fixture.pump(all, setOf(GroupLightningEvents.INVOICE))
all.forEach { d ->
val row = assertNotNull(d.db.groupLightningRecordsDao().invoice(key, requestId), "device ${d.index} has the invoice")
val invoice = Bolt11Invoice.read(row.bolt11).get()
assertEquals(wallet.statement.nodeId, invoice.nodeId.toString())
assertEquals(21_000_000.msat, invoice.amount)
assertEquals("lunch", invoice.description)
}
}
@Test
fun `an invoice is believed only from the operator, and only if it pays the group's node`() = runBlocking<Unit> {
val (all, _) = running()
val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!!
val nodeKey = GroupLightningCoSigner.keyManagerOf(ByteVector(wallet.seed!!.seed), fixture.chain).nodeKeys.nodeKey.privateKey
fun invoice(signer: PrivateKey) = Bolt11Invoice.create(fixture.chain, 1_000.msat, randomBytes32(), signer, Either.Left("x"), CltvExpiryDelta(144), INVOICE_FEATURES).write()
fun reply(from: GroupLightningFixture.Device, requestId: String, bolt11: String) = Event(
randomBytes32().toHex(), from.publicKey, Clock.System.now().epochSeconds, GroupLightningEvents.INVOICE, emptyArray(),
CommonJson.encodeToString(WalletWire.InvoiceReply.serializer(), WalletWire.InvoiceReply(key, requestId, bolt11)), "",
)
GroupLightningReports.process(all[3].db, all[3].room, reply(all[1], "elsewhere", invoice(PrivateKey(randomBytes32()))))
GroupLightningReports.process(all[3].db, all[3].room, reply(all[2], "not-the-operator", invoice(nodeKey)))
GroupLightningReports.process(all[3].db, all[3].room, reply(all[1], "good", invoice(nodeKey)))
assertNull(all[3].db.groupLightningRecordsDao().invoice(key, "elsewhere"), "an invoice paying another node")
assertNull(all[3].db.groupLightningRecordsDao().invoice(key, "not-the-operator"), "an invoice from a member who is not the operator")
assertNotNull(all[3].db.groupLightningRecordsDao().invoice(key, "good"))
}
}
@@ -2,6 +2,7 @@ package com.machankura.bennu.compose.ui.view.model
import com.machankura.bennu.compose.database.model.ChatRoom
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.database.model.GroupSignedEvent
import com.machankura.bennu.compose.database.model.IcebergKeySession
@@ -17,6 +18,7 @@ import com.machankura.bennu.compose.nostr.lightning.GroupLightningOperatorStatem
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.GroupLightningWalletUIState
import com.machankura.bennu.compose.wallet.lightning.WalletWire
import com.vitorpamplona.quartz.nip01Core.core.HexKey
@@ -85,7 +87,9 @@ class GroupLightningWalletViewModelJvmTest {
val thresholds: List<Int> = listOf(2),
val report: GroupLightningReports.Report? = null,
val payments: List<GroupLightningPaymentRow> = emptyList(),
val invoice: GroupLightningInvoiceRow? = null,
) : GroupLightningRepository {
val requests = mutableListOf<Pair<Long?, String>>()
override fun observeCeremony(sessionId: String): Flow<IcebergKeySession?> = flowOf(running)
override fun observeCeremonies(chatRoomId: String): Flow<List<IcebergKeySession>> = flowOf(listOfNotNull(running))
override suspend fun ceremonyMessages(sessionId: String): List<IcebergParticipantMessage> = emptyList()
@@ -104,6 +108,9 @@ class GroupLightningWalletViewModelJvmTest {
override suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain): FrostSigningSession = error("unused")
override fun observeReport(chatRoomId: String, chain: Chain): Flow<GroupLightningReports.Report?> = flowOf(report)
override fun observePayments(chatRoomId: String, chain: Chain): Flow<List<GroupLightningPaymentRow>> = flowOf(payments)
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<GroupLightningInvoiceRow?> = flowOf(invoice?.takeIf { it.requestId == requestId })
}
private val chat = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY {
@@ -169,4 +176,26 @@ class GroupLightningWalletViewModelJvmTest {
assertEquals(true, state.report!!.checks.single().agrees)
assertEquals(listOf(payment), state.payments)
}
@Test
fun `receiving asks the operator for an invoice and shows it once it arrives`() {
assertIs<GroupLightningReceiveUIState.Unavailable>(receiving(Lightning(completed = key, wallet = wallet)).uiState, "nobody runs the node")
val lightning = Lightning(completed = key, wallet = wallet, operator = operator("b".repeat(64)), invoice = GroupLightningInvoiceRow("w", "r1", "lnbcrt1"))
val viewModel = receiving(lightning)
assertIs<GroupLightningReceiveUIState.Form>(viewModel.uiState)
viewModel.amountField.edit { append("2,100") }
viewModel.descriptionField.edit { append(" lunch ") }
viewModel.request(onFailure = { error("the request failed") })
val shown = runBlocking { withTimeout(5_000) { while (viewModel.uiState !is GroupLightningReceiveUIState.Invoice) delay(10); viewModel.uiState } }
assertEquals("lnbcrt1", assertIs<GroupLightningReceiveUIState.Invoice>(shown).bolt11)
assertEquals(listOf<Pair<Long?, String>>(2_100_000L to "lunch"), lightning.requests.toList())
}
private fun receiving(lightning: GroupLightningRepository): GroupLightningReceiveViewModel {
val viewModel = GroupLightningReceiveViewModel(me, chatRoomId, Chain.Testnet3, GroupLightningReceiveUIState.Loading, chat, lightning)
viewModel.initiate()
runBlocking { withTimeout(5_000) { while (viewModel.uiState == GroupLightningReceiveUIState.Loading) delay(10) } }
return viewModel
}
}
+3
View File
@@ -39,6 +39,7 @@ build chose differently, this table says so.
| 9 | done before 8, because the node's transport is half of it: `GroupLightningCoSigner`, `CoSignerPolicy`, `GroupIcebergTransport`, schema 29, and the fork's `SigningContext` (`bd78ed62`). A four-device test co-signs a real commitment that spends its funding output beside a stock counterparty, and five refusals hold. The app's 1,415 JVM tests and the fork's 993 pass |
| 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 |
| what the plan said | what it turned out to be |
|---|---|
@@ -87,6 +88,8 @@ build chose differently, this table says so.
| a member compares the operator's balance with what the co-signers last signed | each member compares it with what *its own* device last signed for that channel: our balance in the last counterparty commitment its ledger holds. The figures can differ while a payment is in flight, because the snapshot reports the operator's own commitment and the ledger the counterparty's. The screen shows a mismatch, and nothing acts on it |
| the snapshot carries the pool for handover | it carries the label *assignments*. The contributions are already in every member's database as nonce batches, so the next operator's transport loads the pool itself. A member files each assignment it has not seen, so the next operator signs a force close under the verification nonce this one published |
| 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 |
| 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 |