diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 6af932d9..6bf12e24 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -822,4 +822,20 @@ Fee: %1$s sats, at %2$s sats per byte Spends %1$s of the group's coins Signed by the group, not by you. Once enough members sign, any member's device can send it to the network. + Send + Send from the group's wallet + Address + Amount in sats + Send everything + Fee rate in sats per byte + Ask the group to send + Sends %1$s sats, with a fee of %2$s sats. + %1$s sats come back to the group as change. + That isn't an address on %1$s. + The group has nothing confirmed to spend yet. + The group doesn't have that much confirmed, after the fee. + That is too little to send: the network won't relay an output that small. + Couldn't ask the group to send. + Sending needs a share of the group's key, and a wallet of your own on this profile to see the group's coins with. + Nothing leaves the wallet until a quorum of members has seen this spend and signed it. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt new file mode 100644 index 00000000..e198fd46 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreen.kt @@ -0,0 +1,264 @@ +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 +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.AccountBalanceWallet +import androidx.compose.material.icons.filled.Send +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.Switch +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.Alignment +import androidx.compose.ui.Modifier +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.address +import bennu.composeapp.generated.resources.amount_in_sats +import bennu.composeapp.generated.resources.ask_the_group_to_send +import bennu.composeapp.generated.resources.couldn_t_ask_the_group_to_send +import bennu.composeapp.generated.resources.feerate_in_sats_per_byte +import bennu.composeapp.generated.resources.finding_the_group_s_coins +import bennu.composeapp.generated.resources.nothing_leaves_until_a_quorum_signs +import bennu.composeapp.generated.resources.s_sats_come_back_to_the_group_as_change +import bennu.composeapp.generated.resources.send_everything +import bennu.composeapp.generated.resources.send_from_the_group_s_wallet +import bennu.composeapp.generated.resources.sending_needs_a_share_and_a_node +import bennu.composeapp.generated.resources.sends_s_sats_with_a_fee_of_s_sats +import bennu.composeapp.generated.resources.that_is_too_little_to_send +import bennu.composeapp.generated.resources.that_isn_t_an_address_on_s +import bennu.composeapp.generated.resources.the_group_doesn_t_have_that_much_confirmed +import bennu.composeapp.generated.resources.the_group_has_nothing_confirmed_to_spend +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +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.GroupSendViewModel +import com.machankura.bennu.compose.ui.view.state.GroupSendUIState +import com.machankura.bennu.compose.wallet.GroupChainWallets +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import org.jetbrains.compose.resources.stringResource + +/** + * A spend from the group's wallet, proposed. + * + * The form says what it would build as it is filled in -- what leaves, the fee, + * what comes back as change -- from the same build the proposal is made of, so + * nothing a member reads here is an estimate of something else. Proposing it + * moves onto the signing session: nothing has left the wallet, and nothing will + * until a quorum has seen it and signed. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupSendScreen( + activeUserPublicKey: HexKey, + chatRoomId: String, + chain: Chain, + initialGroupSendUIState: GroupSendUIState = GroupSendUIState.Loading, + chatRepository: ChatRepository, + frostSigningRepository: FrostSigningRepository, + wallets: GroupChainWallets?, + onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, + onNavigateBack: () -> Unit, +) { + val groupSendViewModel: GroupSendViewModel = viewModel( + factory = GroupSendViewModel.factory( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + chain = chain, + initialGroupSendUIState = initialGroupSendUIState, + chatRepository = chatRepository, + frostSigningRepository = frostSigningRepository, + wallets = wallets, + ) + ) + + LaunchedEffect(true) { + if (initialGroupSendUIState == GroupSendUIState.Loading) groupSendViewModel.initiate() + } + + val notify = rememberNotifier(rememberCoroutineScope()) + val couldNotSend = stringResource(Res.string.couldn_t_ask_the_group_to_send) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(Res.string.send_from_the_group_s_wallet), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + }, + navigationIcon = { NavigateBackButton(onNavigateBack) } + ) + } + ) { padding -> + ScreenStateTransition(groupSendViewModel.groupSendUIState) { uiState -> + when (val state = uiState) { + is GroupSendUIState.Error -> ErrorState( + modifier = Modifier.padding(padding), + message = state.message, + onRetry = null + ) + + GroupSendUIState.Loading -> LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) + + GroupSendUIState.Unavailable -> EmptyState( + modifier = Modifier.padding(padding).readableContent(), + message = stringResource(Res.string.sending_needs_a_share_and_a_node), + icon = Icons.Default.AccountBalanceWallet, + ) + + is GroupSendUIState.Ready -> Column( + modifier = Modifier.padding(padding).readableContent().fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = groupSendViewModel.addressField, + lineLimits = TextFieldLineLimits.SingleLine, + label = { Text(stringResource(Res.string.address)) }, + ) + + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text(stringResource(Res.string.send_everything)) + Switch( + checked = groupSendViewModel.sendEverything.value, + onCheckedChange = { groupSendViewModel.sendEverything.value = it }, + ) + } + + if (!groupSendViewModel.sendEverything.value) { + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = groupSendViewModel.amountField, + lineLimits = TextFieldLineLimits.SingleLine, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + label = { Text(stringResource(Res.string.amount_in_sats)) }, + ) + } + + OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = groupSendViewModel.feerateField, + lineLimits = TextFieldLineLimits.SingleLine, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + label = { Text(stringResource(Res.string.feerate_in_sats_per_byte)) }, + ) + + if (state.walletState == null) { + LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_the_group_s_coins)) + } + + val preview = groupSendViewModel.preview() + preview?.let { SendPreview(it, chain) } + + Text( + text = stringResource(Res.string.nothing_leaves_until_a_quorum_signs), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + Button( + enabled = preview is GroupSpendBuilder.Result.Built && !groupSendViewModel.isActionPending.value, + onClick = { + groupSendViewModel.propose( + onSuccess = { sessionId -> + // Onto the session: the spend exists once it is + // signed, and this form has done its part. + onNavigateToRouteAndPopUpInclusive( + FrostSigningRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + sessionId = sessionId, + ) + ) + }, + onFailure = { notify(couldNotSend) }, + ) + } + ) { + Icon(Icons.Default.Send, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.ask_the_group_to_send)) + } + } + } + } + } +} + +/** What the form would build, or why it cannot. */ +@Composable +private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain) { + when (result) { + is GroupSpendBuilder.Result.Built -> Column(verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) { + Text( + text = stringResource(Res.string.sends_s_sats_with_a_fee_of_s_sats, result.amount.grouped(), result.fee.grouped()), + style = MaterialTheme.typography.bodyLarge, + ) + result.change?.let { change -> + Text( + text = stringResource(Res.string.s_sats_come_back_to_the_group_as_change, change.grouped()), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + + else -> Text( + text = when (result) { + GroupSpendBuilder.Result.NotAnAddress -> + stringResource(Res.string.that_isn_t_an_address_on_s, GroupWalletStatementEvent.chainName(chain)) + GroupSpendBuilder.Result.NothingToSpend -> stringResource(Res.string.the_group_has_nothing_confirmed_to_spend) + GroupSpendBuilder.Result.NotEnough -> stringResource(Res.string.the_group_doesn_t_have_that_much_confirmed) + else -> stringResource(Res.string.that_is_too_little_to_send) + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt index 9f94af92..e741e7c3 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt @@ -1,5 +1,8 @@ package com.machankura.bennu.compose.ui.composable +import androidx.compose.material.icons.filled.Send +import bennu.composeapp.generated.resources.send +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer @@ -203,6 +206,19 @@ fun GroupWalletScreen( modifier = Modifier.padding(padding), state = state, notify = notify, + // Behind both gates: a share to propose with, and a node to + // see the coins with -- a spend built blind is not one. + onSend = if (state.canSign && state.canWatch) { + { + onNavigateToRoute( + GroupSendRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId, + relayHint = null + ) + ) + } + } else null, ) } } @@ -243,6 +259,7 @@ private fun OpenWallet( modifier: Modifier, state: GroupWalletUIState.Loaded, notify: (String) -> Unit, + onSend: (() -> Unit)?, ) { val clipboardManager = LocalClipboardManager.current val addressCopied = stringResource(Res.string.address_copied) @@ -256,6 +273,16 @@ private fun OpenWallet( ) { item { BalanceCard(walletState) } + onSend?.let { send -> + item { + Button(onClick = send) { + Icon(Icons.Default.Send, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.send)) + } + } + } + when { !state.canWatch -> item { Text( 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 23acce26..93e9a721 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 @@ -1,5 +1,7 @@ package com.machankura.bennu.compose.ui.composable.navigation +import com.machankura.bennu.compose.ui.composable.GroupSendScreen +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.material3.MaterialTheme @@ -1246,6 +1248,28 @@ fun BennuNavHost( } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + GroupSendScreen( + activeUserPublicKey = route.activeUserPublicKey, + chatRoomId = route.chatRoomId, + chain = NodeParamsManager.chain, + chatRepository = databaseChatRepository, + frostSigningRepository = databaseFrostSigningRepository, + wallets = groupChainWallets, + onNavigateToRouteAndPopUpInclusive = { signingRoute -> + // Replace the form so back returns to the wallet rather + // than to a spend that has already been proposed. + navController.navigate(route = signingRoute) { + popUpTo { inclusive = true } + } + }, + onNavigateBack = { + navController.popBackStack() + } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt new file mode 100644 index 00000000..52db5baa --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupSendRoute.kt @@ -0,0 +1,11 @@ +package com.machankura.bennu.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** The form a member proposes a spend from the group's wallet with. */ +@Serializable +data class GroupSendRoute( + val activeUserPublicKey: String, + val chatRoomId: String, + val relayHint: String? +): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt new file mode 100644 index 00000000..4c3fcc8a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModel.kt @@ -0,0 +1,157 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd +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.FrostSigningRepository +import com.machankura.bennu.compose.ui.view.state.GroupSendUIState +import com.machankura.bennu.compose.wallet.GroupChainWallets +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Satoshi +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * A spend from the group's wallet, built as the member types and proposed when + * they ask. + * + * The preview the screen shows is [preview] over the same inputs the proposal is + * built from, so the fee a member reads before pressing the button is the fee + * the group is then asked to sign -- there is no second build. + */ +class GroupSendViewModel( + val activeUserPublicKey: HexKey, + val chatRoomId: String, + val chain: Chain, + initialGroupSendUIState: GroupSendUIState, + val chatRepository: ChatRepository, + val frostSigningRepository: FrostSigningRepository, + private val wallets: GroupChainWallets?, +): ViewModel() { + private val logger = Logger.withTag(TAG) + + var groupSendUIState: GroupSendUIState by mutableStateOf(initialGroupSendUIState) + private set + + val addressField = TextFieldState() + val amountField = TextFieldState() + val feerateField = TextFieldState() + val sendEverything: MutableState = mutableStateOf(false) + + val isActionPending: MutableState = mutableStateOf(false) + + private var watching: Job? = null + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId) + if (localChatRoom == null) { + groupSendUIState = GroupSendUIState.Error("Couldn't find the group") + return@launch + } + + val wallet = chatRepository.groupWallet(chatRoomId, chain) + val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) + if (wallet == null || !canSign || wallets == null) { + groupSendUIState = GroupSendUIState.Unavailable + return@launch + } + + val ready = GroupSendUIState.Ready( + localChatRoom = localChatRoom, + wallet = wallet, + walletState = null, + reserved = frostSigningRepository.reservedOutPoints(chatRoomId), + ) + groupSendUIState = ready + + wallets.suggestedFeeratePerVbyte()?.let { suggested -> + withContext(Dispatchers.Main) { + if (feerateField.text.isEmpty()) feerateField.setTextAndPlaceCursorAtEnd(suggested.toString()) + } + } + + val chainWallet = wallets.walletFor(wallet.account) + watching?.cancel() + watching = viewModelScope.launch(Dispatchers.IO) { + chainWallet.state.collect { state -> groupSendUIState = ready.copy(walletState = state) } + } + } + } + + /** + * The spend the form describes right now, or null while it is incomplete -- + * no wallet state yet, no feerate, no amount. + */ + fun preview(): GroupSpendBuilder.Result? { + val state = groupSendUIState as? GroupSendUIState.Ready ?: return null + val walletState = state.walletState ?: return null + val feerate = feerateField.text.toString().trim().toLongOrNull()?.takeIf { it > 0 } ?: return null + val address = addressField.text.toString().trim().takeIf { it.isNotEmpty() } ?: return null + + return if (sendEverything.value) { + GroupSpendBuilder.sendAll(walletState, address, feerate, state.reserved) + } else { + val amount = amountField.text.toString().filter { it.isDigit() }.toLongOrNull() ?: return null + GroupSpendBuilder.send(walletState, address, Satoshi(amount), feerate, state.reserved) + } + } + + fun propose(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + val state = groupSendUIState as? GroupSendUIState.Ready ?: return + val built = preview() as? GroupSpendBuilder.Result.Built ?: return + if (isActionPending.value) return + isActionPending.value = true + + viewModelScope.launch(Dispatchers.IO) { + val session = runCatching { + frostSigningRepository.proposeSpend( + localChatRoom = state.localChatRoom, + userPublicKey = activeUserPublicKey, + psbt = built.psbt, + chain = chain, + ) + }.onFailure { logger.e("Failed to propose a spend from $chatRoomId", it) }.getOrNull() + + withContext(Dispatchers.Main) { + if (session != null) onSuccess(session.id) else onFailure() + } + isActionPending.value = false + } + } + + companion object { + private const val TAG = "GroupSendViewModel" + + fun factory( + activeUserPublicKey: HexKey, + chatRoomId: String, + chain: Chain, + initialGroupSendUIState: GroupSendUIState = GroupSendUIState.Loading, + chatRepository: ChatRepository, + frostSigningRepository: FrostSigningRepository, + wallets: GroupChainWallets?, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + GroupSendViewModel( + activeUserPublicKey, chatRoomId, chain, initialGroupSendUIState, + chatRepository, frostSigningRepository, wallets, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt new file mode 100644 index 00000000..b1736a00 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupSendUIState.kt @@ -0,0 +1,27 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.wallet.GroupWalletState +import fr.acinq.bitcoin.OutPoint + +sealed interface GroupSendUIState { + /** + * A wallet this device can propose a spend from: it holds a share, and it has + * a node to see the coins with. [walletState] is null until Electrum answers. + */ + data class Ready( + val localChatRoom: LocalChatRoom, + val wallet: GroupWallet, + val walletState: GroupWalletState?, + /** The coins open spends already hold, which a new one leaves alone. */ + val reserved: Set, + ): GroupSendUIState + + /** A room this device cannot propose from -- no wallet, no share, or no node. */ + data object Unavailable: GroupSendUIState + + data class Error(val message: String): GroupSendUIState + + data object Loading: GroupSendUIState +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallets.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallets.kt index bfb12cda..10f9e8ca 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallets.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallets.kt @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.wallet import com.machankura.bennu.compose.managers.GroupWalletDerivation import fr.acinq.lightning.blockchain.electrum.IElectrumClient +import fr.acinq.lightning.blockchain.fee.FeeratePerByte import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock @@ -28,6 +29,14 @@ class GroupChainWallets( wallets.getOrPut(account.xpub) { GroupChainWallet(account, electrum, scope) } } + /** + * A feerate to start the send form at, in sats per virtual byte: Electrum's + * estimate for six blocks, or null when it has none. A suggestion the member + * edits, never a value a spend is built on without them seeing it. + */ + suspend fun suggestedFeeratePerVbyte(): Long? = + electrum.estimateFees(6)?.let { FeeratePerByte(it).feerate.sat }?.coerceAtLeast(1) + suspend fun stop() = mutex.withLock { wallets.values.forEach { it.stop() } wallets.clear() diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModelJvmTest.kt new file mode 100644 index 00000000..d4c6b86e --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupSendViewModelJvmTest.kt @@ -0,0 +1,144 @@ +package com.machankura.bennu.compose.ui.view.model + +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd +import com.machankura.bennu.compose.database.model.ChatRoom +import com.machankura.bennu.compose.database.model.FrostSigningSession +import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.nostr.wallet.GroupWallet +import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.repository.FrostSigningRepository +import com.machankura.bennu.compose.ui.view.state.GroupSendUIState +import com.machankura.bennu.compose.wallet.GroupSpend +import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.machankura.bennu.compose.wallet.GroupWalletState +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.OutPoint +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.bitcoin.Transaction +import fr.acinq.bitcoin.TxId +import fr.acinq.bitcoin.TxIn +import fr.acinq.bitcoin.TxOut +import fr.acinq.bitcoin.psbt.Psbt +import fr.acinq.lightning.blockchain.electrum.WalletState +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.UnconfinedTestDispatcher +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.setMain +import kotlinx.coroutines.withTimeout +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.time.Instant + +/** + * The send form: what it previews is what it proposes, and it is not offered to + * a device that cannot both sign and see the coins. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class GroupSendViewModelJvmTest { + @BeforeTest + fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterTest + fun tearDown() = Dispatchers.resetMain() + + private val chatRoomId = "d4c3b2a1".repeat(8) + private val localChatRoom = LocalChatRoom( + chatRoom = ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "Treasury", description = null, initialGiftWrapPayloadId = "p", mlsGroupState = "state") + ) + private val account = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), Chain.Regtest, + ) + private val wallet = GroupWallet( + GroupSignedEvent( + id = "e".repeat(64), chatRoomId = chatRoomId, publicKey = chatRoomId, kind = GroupWalletStatementEvent.KIND, + tags = GroupWalletStatementEvent.template(account).tags, content = account.xpub, signature = "f".repeat(128), + createdAt = Instant.fromEpochSeconds(1_700_000_000), + ), + account, + ) + + private val walletState: GroupWalletState = run { + val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0) + val tx = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 1 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(100_000), derived.pubkeyScript)), 0) + val meta = WalletState.AddressMeta.Derived(0) + val change = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0) + GroupWalletState( + account, + WalletState(mapOf(derived.address(Chain.Regtest) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(tx.txid, 0, 100, tx, meta))))), + WalletState(mapOf(change.address(Chain.Regtest) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()))), + tipHeight = 110, + ) + } + + private class RecordingSigning : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { + var proposed: Psbt? = null + override suspend fun proposeSpend(localChatRoom: LocalChatRoom, userPublicKey: HexKey, psbt: Psbt, chain: Chain): FrostSigningSession? { + proposed = psbt + return null + } + } + + private fun viewModel(initial: GroupSendUIState, chat: ChatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY, signing: FrostSigningRepository = RecordingSigning()) = + GroupSendViewModel("a".repeat(64), chatRoomId, Chain.Regtest, initial, chat, signing, wallets = null) + + @Test + fun `a profile with no node is not offered the form`() { + val chat = object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun getChatRoomByIdentifier(identifier: String) = localChatRoom + override suspend fun canSign(chatRoomId: String) = true + override suspend fun groupWallet(chatRoomId: String, chain: Chain) = wallet + } + val model = viewModel(GroupSendUIState.Loading, chat).apply { initiate() } + + runBlocking { withTimeout(5_000) { while (model.groupSendUIState == GroupSendUIState.Loading) delay(10) } } + assertEquals(GroupSendUIState.Unavailable, model.groupSendUIState) + } + + @Test + fun `the preview waits for the form, and what it builds is what is proposed`() { + val signing = RecordingSigning() + val model = viewModel(GroupSendUIState.Ready(localChatRoom, wallet, walletState, reserved = emptySet()), signing = signing) + + assertNull(model.preview(), "nothing to build before an address and a feerate") + + model.addressField.setTextAndPlaceCursorAtEnd("bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080") + model.feerateField.setTextAndPlaceCursorAtEnd("4") + model.amountField.setTextAndPlaceCursorAtEnd("40,000") + val built = assertIs(model.preview()) + assertEquals(Satoshi(40_000), built.amount) + assertNotNull(built.change) + + model.propose(onSuccess = {}, onFailure = {}) + runBlocking { withTimeout(5_000) { while (signing.proposed == null) delay(10) } } + assertEquals(built.psbt, signing.proposed) + assertIs(GroupSpend.check(signing.proposed!!, account), "the other members would accept it") + } + + @Test + fun `send everything ignores the amount`() { + val model = viewModel(GroupSendUIState.Ready(localChatRoom, wallet, walletState, reserved = emptySet())) + model.addressField.setTextAndPlaceCursorAtEnd("bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080") + model.feerateField.setTextAndPlaceCursorAtEnd("4") + model.sendEverything.value = true + + val built = assertIs(model.preview()) + assertEquals(Satoshi(100_000), built.amount + built.fee) + assertNull(built.change) + } +} diff --git a/docs/group-chain-wallet.md b/docs/group-chain-wallet.md index a3dea9ab..fb20f7f7 100644 --- a/docs/group-chain-wallet.md +++ b/docs/group-chain-wallet.md @@ -40,6 +40,9 @@ kept as written; where the build chose differently the table below says so. | the account comes from the statement, never from the proposal | and the proposal carries `chain` and `account` tags to say *which* statement. Acceptance then looks the statement up under the ceremony's own key, which is also what refuses a spend opened under a subgroup's ceremony held in its parent's room | | a new `TYPE_GROUP_TRANSACTION_SIGNED` line | none: `TYPE_FROST_COMPLETE` with a spend's wording — sats sent, sats in fees — since it is the settlement line the transcript and the proposal list already read, and a new type would need adding to five sets | | `complete()` for a transaction | `completeSpend`, which re-runs `GroupSpend.check` over the stored PSBT so every signature is checked against the coin it spends, then runs `correctlySpends` before writing `signedTransaction` | +| the feerate comes from `FeerateManager`'s `halfHour` | from Electrum's six-block estimate, through `GroupChainWallets` — the wallet already holds the identity's Electrum client, and the business's fee manager would be a second way in to the same node. Prefilled, never used unseen | +| the inputs behind a disclosure on the approval screen | a line saying how many of the group's coins it spends. Each was checked against the wallet before the screen was drawn, so there is nothing about them a member could check by opening one | +| the composer marks coins reserved | `FrostSigningManager.reservedOutPoints`: every coin an open spend holds, released when its session fails, held by a finished one until Electrum stops reporting the coin | The headline: **the best path is BIP86's own unhardened tail, `//`, hung under an account key the group's threshold key is tweaked to, with the