diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index b1e47688..7dd87438 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -622,6 +622,17 @@ Receive address Copy address Address copied + All addresses + Addresses + Each payment should go to a new address. If someone else in the group is already sharing the current one, share one of the ones after it. + Being handed out now + Not used yet + Paid · %1$s sats + Paid · spent since + Copy address %1$s + Address %1$s + Show as a QR code + Address %1$s was just paid Finding the group's coins… Nothing has been sent to this wallet yet. This profile has no wallet of its own to watch the chain with, so the balance and the next address can't be shown here. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletAddressesScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletAddressesScreen.kt new file mode 100644 index 00000000..32ad5341 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletAddressesScreen.kt @@ -0,0 +1,368 @@ +package com.machankura.bennu.compose.ui.composable + +import androidx.compose.foundation.clickable +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.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.text.selection.SelectionContainer +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Visibility +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.ListItem +import androidx.compose.material3.ListItemDefaults +import androidx.compose.material3.MaterialTheme +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.material3.minimumInteractiveComponentSize +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.font.FontFamily +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_copied +import bennu.composeapp.generated.resources.address_s +import bennu.composeapp.generated.resources.address_s_was_just_paid +import bennu.composeapp.generated.resources.addresses +import bennu.composeapp.generated.resources.addresses_explainer +import bennu.composeapp.generated.resources.being_handed_out_now +import bennu.composeapp.generated.resources.change +import bennu.composeapp.generated.resources.copy_address +import bennu.composeapp.generated.resources.copy_address_s +import bennu.composeapp.generated.resources.finding_the_group_s_coins +import bennu.composeapp.generated.resources.not_used_yet +import bennu.composeapp.generated.resources.paid_s_sats +import bennu.composeapp.generated.resources.paid_spent_since +import bennu.composeapp.generated.resources.show_as_a_qr_code +import bennu.composeapp.generated.resources.this_profile_cannot_watch_the_chain +import com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.text.grouped +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.dialogs.ModalBottomSheet +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.GroupWalletAddressesViewModel +import com.machankura.bennu.compose.ui.view.state.GroupWalletAddressesUIState +import com.machankura.bennu.compose.wallet.GroupAddress +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import com.machankura.bennu.compose.wallet.bip21Uri +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Satoshi +import org.jetbrains.compose.resources.stringResource + +/** + * The group wallet's receive addresses, newest first: every one paid, the one + * the wallet screen is handing out, and the few after it. + * + * Modelled on Phoenix's swap-in address list, with the look-ahead cut to what is + * worth handing out. The addresses after the current one are there so that two + * members sharing the wallet at once can each give a payer a different one; + * the sentence above the list says so, or nobody would use anything but the top. + * Tapping an unused one opens it as a QR code, in a sheet that closes itself if + * the address is paid while it is open. + * + * No block explorer: a tap that sends every address of the group's wallet to a + * third party's server is the leak the watch-only export warns about, made + * without asking. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun GroupWalletAddressesScreen( + chatRoomId: String, + chain: Chain, + initialUIState: GroupWalletAddressesUIState = GroupWalletAddressesUIState.Loading, + chatRepository: ChatRepository, + wallets: GroupOnchainWallets?, + onNavigateBack: () -> Unit, +) { + val addressesViewModel: GroupWalletAddressesViewModel = viewModel( + factory = GroupWalletAddressesViewModel.factory( + chatRoomId = chatRoomId, + chain = chain, + initialUIState = initialUIState, + chatRepository = chatRepository, + wallets = wallets, + ) + ) + + LaunchedEffect(true) { + if (initialUIState == GroupWalletAddressesUIState.Loading) { + addressesViewModel.initiate() + } + } + + val notify = rememberNotifier(rememberCoroutineScope()) + + Scaffold( + snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) }, + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(Res.string.addresses), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + }, + navigationIcon = { NavigateBackButton(onNavigateBack) } + ) + } + ) { padding -> + ScreenStateTransition(addressesViewModel.uiState) { uiState -> + when (val state = uiState) { + is GroupWalletAddressesUIState.Error -> { + // Nothing to retry: the room came from a navigation argument. + ErrorState( + modifier = Modifier.padding(padding), + message = state.message, + onRetry = null + ) + } + + GroupWalletAddressesUIState.Loading -> { + LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding)) + } + + GroupWalletAddressesUIState.CannotWatch -> { + EmptyState( + modifier = Modifier.padding(padding).readableContent(), + message = stringResource(Res.string.this_profile_cannot_watch_the_chain), + icon = Icons.Default.Visibility, + ) + } + + is GroupWalletAddressesUIState.Loaded -> { + val receive = state.receive + if (receive == null) { + LoadingDataIndicator( + modifier = Modifier.fillMaxWidth().padding(padding), + text = stringResource(Res.string.finding_the_group_s_coins) + ) + } else { + AddressList( + modifier = Modifier.padding(padding), + receive = receive, + change = state.change, + notify = notify, + onShow = { index, paid -> addressesViewModel.show(index) { notify(paid) } }, + ) + + val shown = addressesViewModel.shown?.let { index -> receive.firstOrNull { it.derivation.index == index } } + if (shown != null) { + AddressSheet( + address = shown, + notify = notify, + onDismiss = addressesViewModel::dismiss, + ) + } + } + } + } + } + } +} + +@Composable +private fun AddressList( + modifier: Modifier, + receive: List, + change: List, + notify: (String) -> Unit, + onShow: (index: Long, paidMessage: String) -> Unit, +) { + val clipboardManager = LocalClipboardManager.current + val addressCopied = stringResource(Res.string.address_copied) + val copy = { address: GroupAddress -> + clipboardManager.setText(buildAnnotatedString { append(address.address) }) + notify(addressCopied) + } + // Both branches start at index 0, so the index alone is not a row's identity. + val key = { address: GroupAddress -> "${address.derivation.change}/${address.derivation.index}" } + + LazyColumn( + modifier = modifier.readableContent().fillMaxSize() + .padding(MaterialTheme.spacing.screenMargin), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap) + ) { + item { + Text( + text = stringResource(Res.string.addresses_explainer), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + items(receive, key = key) { address -> + // Read here rather than in the click: the index is the row's, and a + // click handler is not composable. + val paid = stringResource(Res.string.address_s_was_just_paid, address.derivation.index.toString()) + AddressRow( + address = address, + onCopy = { copy(address) }, + // A used address is never offered for scanning: copying it is for + // checking, a QR code is for being paid. + onShow = if (address.status != GroupAddress.Status.USED) { + { onShow(address.derivation.index, paid) } + } else null, + ) + } + + // The group's money too, and what a watch-only import will show beside + // the receive addresses -- but chosen by a spend, so never offered here. + if (change.isNotEmpty()) { + item { + Text( + text = stringResource(Res.string.change), + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.padding(top = MaterialTheme.spacing.sectionGap), + ) + } + items(change, key = key) { address -> + AddressRow(address = address, onCopy = { copy(address) }, onShow = null) + } + } + } +} + +/** + * One unused address, ready to be paid: what the wallet screen's receive card + * shows for the current address, for whichever one this member is handing out. + * + * The title carries the index so a member reading it to a payer can say which + * one they gave. + */ +@Composable +private fun AddressSheet( + address: GroupAddress, + notify: (String) -> Unit, + onDismiss: () -> Unit, +) { + val clipboardManager = LocalClipboardManager.current + val addressCopied = stringResource(Res.string.address_copied) + + ModalBottomSheet( + onDismiss = onDismiss, + skipPartiallyExpanded = true, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) + ) { + Text( + text = stringResource(Res.string.address_s, address.derivation.index.toString()), + style = MaterialTheme.typography.titleMedium, + ) + Text( + text = address.status.label(address.balance), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + // BIP21, so a scanning wallet knows what the text is. + QRCodeView(bip21Uri(address.address)) + SelectionContainer { + Text(text = address.address, style = MaterialTheme.typography.bodyMedium) + } + TextButton( + onClick = { + clipboardManager.setText(buildAnnotatedString { append(address.address) }) + notify(addressCopied) + } + ) { + Icon(Icons.Default.ContentCopy, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.copy_address)) + } + } + } +} + +/** + * One address: its index, the address itself, and what it has been used for. + * + * The current address takes the secondary container rather than Phoenix's + * leading bar, so the emphasis is a colour pairing the theme has already + * measured in all six schemes. + */ +@Composable +private fun AddressRow(address: GroupAddress, onCopy: () -> Unit, onShow: (() -> Unit)?) { + val showLabel = stringResource(Res.string.show_as_a_qr_code) + val colors = if (address.status == GroupAddress.Status.CURRENT) { + val onContainer = MaterialTheme.colorScheme.onSecondaryContainer + ListItemDefaults.colors( + containerColor = MaterialTheme.colorScheme.secondaryContainer, + headlineColor = onContainer, + supportingColor = onContainer, + leadingIconColor = onContainer, + trailingIconColor = onContainer, + ) + } else { + ListItemDefaults.colors() + } + + ListItem( + modifier = if (onShow != null) { + Modifier.clickable(onClickLabel = showLabel, onClick = onShow).minimumInteractiveComponentSize() + } else Modifier, + colors = colors, + leadingContent = { + Text( + text = address.derivation.index.toString(), + style = MaterialTheme.typography.labelLarge, + ) + }, + headlineContent = { + Text( + text = address.address, + style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace), + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + ) + }, + supportingContent = { Text(address.status.label(address.balance)) }, + trailingContent = { + IconButton(onClick = onCopy) { + Icon( + Icons.Default.ContentCopy, + contentDescription = stringResource(Res.string.copy_address_s, address.derivation.index.toString()) + ) + } + }, + ) +} + +@Composable +private fun GroupAddress.Status.label(balance: Satoshi): String = when (this) { + GroupAddress.Status.CURRENT -> stringResource(Res.string.being_handed_out_now) + GroupAddress.Status.NEXT -> stringResource(Res.string.not_used_yet) + GroupAddress.Status.USED -> if (balance > Satoshi(0)) { + stringResource(Res.string.paid_s_sats, balance.grouped()) + } else { + stringResource(Res.string.paid_spent_since) + } +} 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 817bb209..fd1ea3d8 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 @@ -19,6 +19,7 @@ import bennu.composeapp.generated.resources.couldn_t_bump_the_fee import androidx.compose.material.icons.filled.Send import bennu.composeapp.generated.resources.send import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletAddressesRoute import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer @@ -32,6 +33,7 @@ import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.AccountBalanceWallet import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.FormatListNumbered import androidx.compose.material.icons.filled.Visibility import androidx.compose.material3.Button import androidx.compose.material3.Card @@ -56,6 +58,7 @@ 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_copied +import bennu.composeapp.generated.resources.all_addresses import bennu.composeapp.generated.resources.anyone_with_these_can_see_every_address import bennu.composeapp.generated.resources.balance import bennu.composeapp.generated.resources.balance_not_known_yet @@ -242,6 +245,14 @@ fun GroupWalletScreen( ) } } else null, + onOpenAddresses = { + onNavigateToRoute( + GroupWalletAddressesRoute( + activeUserPublicKey = activeUserPublicKey, + chatRoomId = chatRoomId + ) + ) + }, onOpenSpend = toSession, onSendAgain = if (watcher != null) { { sessionId -> groupWalletViewModel.sendAgain(sessionId) { notify(sentAgain) } } @@ -292,6 +303,7 @@ private fun OpenWallet( state: GroupWalletUIState.Loaded, notify: (String) -> Unit, onSend: (() -> Unit)?, + onOpenAddresses: () -> Unit, onOpenSpend: (sessionId: String) -> Unit, onSendAgain: ((sessionId: String) -> Unit)?, onBump: ((sessionId: String) -> Unit)?, @@ -362,6 +374,14 @@ private fun OpenWallet( Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) Text(stringResource(Res.string.copy_address)) } + // In the card because it answers the question the card + // raises: which address to give, when somebody else in + // the group may be giving this one. + TextButton(onClick = onOpenAddresses) { + Icon(Icons.Default.FormatListNumbered, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.all_addresses)) + } } } } 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 6b4896cb..5342fe5d 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 @@ -51,6 +51,7 @@ import com.machankura.bennu.compose.ui.composable.EditGroupRelaysScreen import com.machankura.bennu.compose.ui.composable.GroupNostrProfileScreen import com.machankura.bennu.compose.ui.composable.GroupRelaysScreen import com.machankura.bennu.compose.ui.composable.GroupWalletScreen +import com.machankura.bennu.compose.ui.composable.GroupWalletAddressesScreen import com.machankura.bennu.compose.ui.composable.GroupPostsScreen import com.machankura.bennu.compose.ui.composable.HomeScreen import com.machankura.bennu.compose.ui.composable.ImplementationPendingScreen @@ -154,6 +155,7 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRel import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute +import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletAddressesRoute import com.machankura.bennu.compose.wallet.GroupOnchainWallets import com.machankura.bennu.compose.wallet.GroupTransactionWatcher import fr.acinq.phoenix.managers.NodeParamsManager @@ -1250,6 +1252,19 @@ fun BennuNavHost( } ) } + composable { backStackEntry -> + val route = backStackEntry.toRoute() + + GroupWalletAddressesScreen( + chatRoomId = route.chatRoomId, + chain = NodeParamsManager.chain, + chatRepository = databaseChatRepository, + wallets = groupOnchainWallets, + onNavigateBack = { + navController.popBackStack() + } + ) + } composable { backStackEntry -> val route = backStackEntry.toRoute() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletAddressesRoute.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletAddressesRoute.kt new file mode 100644 index 00000000..915c1963 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/routes/GroupWalletAddressesRoute.kt @@ -0,0 +1,13 @@ +package com.machankura.bennu.compose.ui.composable.navigation.routes + +import kotlinx.serialization.Serializable + +/** + * The group wallet's receive addresses: every one paid, the one being handed + * out, and the next few -- pushed from the wallet screen's receive card. + */ +@Serializable +data class GroupWalletAddressesRoute( + val activeUserPublicKey: String, + val chatRoomId: String, +): Route() diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModel.kt new file mode 100644 index 00000000..b40ce5e3 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModel.kt @@ -0,0 +1,107 @@ +package com.machankura.bennu.compose.ui.view.model + +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 com.machankura.bennu.compose.repository.ChatRepository +import com.machankura.bennu.compose.ui.view.state.GroupWalletAddressesUIState +import com.machankura.bennu.compose.wallet.GroupAddress +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import fr.acinq.bitcoin.Chain +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * The group wallet's addresses, watched for as long as the screen is open. + * + * [wallets] hands back the wallet the wallet screen is already watching, so the + * list costs no subscriptions of its own and agrees with that screen about which + * address is current. + */ +class GroupWalletAddressesViewModel( + val chatRoomId: String, + val chain: Chain, + initialUIState: GroupWalletAddressesUIState, + val chatRepository: ChatRepository, + private val wallets: GroupOnchainWallets?, +): ViewModel() { + var uiState: GroupWalletAddressesUIState by mutableStateOf(initialUIState) + private set + + /** The index of the address the sheet is showing as a QR code, or null when it is closed. */ + var shown: Long? by mutableStateOf(null) + private set + + private var onShownPaid: (() -> Unit)? = null + + /** + * Opens the sheet on the receive address at [index]. [onPaid] runs once if + * that address is paid while the sheet is open, as the sheet closes: whoever + * is scanning it then has already paid, and nobody else should. + */ + fun show(index: Long, onPaid: () -> Unit) { + shown = index + onShownPaid = onPaid + } + + fun dismiss() { + shown = null + onShownPaid = null + } + + fun initiate() { + viewModelScope.launch(Dispatchers.IO) { + val wallet = chatRepository.groupWallet(chatRoomId, chain) + if (wallet == null) { + uiState = GroupWalletAddressesUIState.Error("This group has not opened a wallet") + return@launch + } + if (wallets == null) { + uiState = GroupWalletAddressesUIState.CannotWatch + return@launch + } + + uiState = GroupWalletAddressesUIState.Loaded(receive = null) + wallets.walletFor(wallet.account).state.collect { state -> + val receive = state.receiveAddresses + uiState = GroupWalletAddressesUIState.Loaded(receive = receive, change = state.changeAddresses.orEmpty()) + + val index = shown ?: return@collect + val status = receive?.firstOrNull { it.derivation.index == index }?.status ?: return@collect + if (status == GroupAddress.Status.USED) { + val paid = onShownPaid + withContext(Dispatchers.Main) { + dismiss() + paid?.invoke() + } + } + } + } + } + + companion object { + fun factory( + chatRoomId: String, + chain: Chain, + initialUIState: GroupWalletAddressesUIState = GroupWalletAddressesUIState.Loading, + chatRepository: ChatRepository, + wallets: GroupOnchainWallets?, + ): ViewModelProvider.Factory = viewModelFactory { + initializer { + GroupWalletAddressesViewModel( + chatRoomId = chatRoomId, + chain = chain, + initialUIState = initialUIState, + chatRepository = chatRepository, + wallets = wallets, + ) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletAddressesUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletAddressesUIState.kt new file mode 100644 index 00000000..e175f29c --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletAddressesUIState.kt @@ -0,0 +1,30 @@ +package com.machankura.bennu.compose.ui.view.state + +import com.machankura.bennu.compose.wallet.GroupAddress + +sealed interface GroupWalletAddressesUIState { + /** + * The wallet's addresses as the chain last said. + * + * [receive] is null until Electrum has said which are used: before that every + * address reads as unused, and a list that called `/0/0` current would be + * wrong about a group paid there before. + */ + data class Loaded( + val receive: List?, + /** The change addresses that have been used, newest first: empty for a wallet that has never sent. */ + val change: List = emptyList(), + ): GroupWalletAddressesUIState + + /** + * A profile with no node of its own -- an nsec or an npub -- which knows the + * group keeps a wallet and cannot see which of its addresses are used. + */ + data object CannotWatch: GroupWalletAddressesUIState + + data class Error( + val message: String + ): GroupWalletAddressesUIState + + data object Loading: GroupWalletAddressesUIState +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallet.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallet.kt index 766023ca..6b51bf65 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallet.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallet.kt @@ -94,6 +94,37 @@ class GroupOnchainWallet( * have at once before the next is told to wait. */ const val CHANGE_LOOKAHEAD: UInt = 10u + + /** + * Unused receive addresses the address list offers past the current one, + * so several members can each hand out a different one. Every one of them + * has to be watched already, or a payment to it would go unseen. + */ + const val ADDRESSES_AHEAD: Int = 2 + + init { + require(ADDRESSES_AHEAD < RECEIVE_LOOKAHEAD.toInt()) { "the address list would offer addresses the wallet does not watch" } + } + } +} + +/** One of the wallet's addresses as the address list shows it. */ +data class GroupAddress( + val derivation: GroupWalletDerivation.Derived, + val address: String, + val status: Status, + /** What it holds now: zero for an address never paid, and for one paid and spent. */ + val balance: Satoshi, +) { + enum class Status { + /** The address the wallet screen is handing out. */ + CURRENT, + + /** Not paid yet, and past the current one. */ + NEXT, + + /** Paid at least once, whether or not the coins have moved since. */ + USED, } } @@ -145,6 +176,60 @@ data class GroupWalletState( */ val receiveAddress: String? get() = receive.firstUnusedDerivedAddress?.first + /** + * The receive addresses worth listing, newest first: every one paid, the one + * being handed out, and [GroupOnchainWallet.ADDRESSES_AHEAD] after it -- or + * null until Electrum has said which are used, for the reason + * [receiveAddress] is. + * + * The list reaches the highest paid address even past the current one plus + * the addresses ahead: the current address is the *lowest* unused one, so a + * watch-only wallet paid further up leaves it where it was. + */ + val receiveAddresses: List? by lazy { + val current = receive.firstUnusedDerivedAddress?.second?.index ?: return@lazy null + listed(GroupWalletDerivation.RECEIVE, receive, current) + } + + /** + * The change addresses that have been used, newest first, or null until + * Electrum has answered. Never a current or a next one: change is chosen by + * a spend, and is not handed out to be paid. + */ + val changeAddresses: List? by lazy { + change.firstUnusedDerivedAddress ?: return@lazy null + listed(GroupWalletDerivation.CHANGE, change, current = null) + } + + /** + * [branch]'s addresses up to the highest used one, and -- given the branch's + * [current] index -- up to [GroupOnchainWallet.ADDRESSES_AHEAD] past that. + * Without a current index, only the used ones. + */ + private fun listed(branch: Long, state: WalletState, current: Int?): List { + val derived = state.addresses.mapNotNull { (address, addressState) -> + (addressState.meta as? WalletState.AddressMeta.Derived)?.let { Triple(address, it.index, addressState) } + } + val highestUsed = derived.filter { it.third.alreadyUsed }.maxOfOrNull { it.second } ?: -1 + val last = current?.let { maxOf(it + GroupOnchainWallet.ADDRESSES_AHEAD, highestUsed) } ?: highestUsed + + return derived + .filter { (_, index, addressState) -> index <= last && (current != null || addressState.alreadyUsed) } + .sortedByDescending { (_, index, _) -> index } + .map { (address, index, addressState) -> + GroupAddress( + derivation = GroupWalletDerivation.derive(account, branch, index.toLong()), + address = address, + status = when { + addressState.alreadyUsed -> GroupAddress.Status.USED + index == current -> GroupAddress.Status.CURRENT + else -> GroupAddress.Status.NEXT + }, + balance = addressState.utxos.map { it.amount }.sum(), + ) + } + } + /** Whether Electrum has answered for any change address yet: before it has, there is no next one to name. */ val changeKnown: Boolean get() = change.addresses.values.any { !it.alreadyUsed } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModelJvmTest.kt new file mode 100644 index 00000000..8da5153d --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModelJvmTest.kt @@ -0,0 +1,157 @@ +package com.machankura.bennu.compose.ui.view.model + +import com.machankura.bennu.compose.database.model.GroupSignedEvent +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.ui.view.state.GroupWalletAddressesUIState +import com.machankura.bennu.compose.wallet.FakeElectrum +import com.machankura.bennu.compose.wallet.GroupAddress +import com.machankura.bennu.compose.wallet.GroupOnchainWallets +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PrivateKey +import fr.acinq.bitcoin.Satoshi +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +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.assertNull +import kotlin.time.Instant + +/** Which of its states the address list is in, and that it follows the chain while it is open. */ +@OptIn(ExperimentalCoroutinesApi::class) +class GroupWalletAddressesViewModelJvmTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + @BeforeTest + fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher()) + + @AfterTest + fun tearDown() { + scope.cancel() + Dispatchers.resetMain() + } + + private val chatRoomId = "d4c3b2a1".repeat(8) + + private val account = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), + Chain.Regtest, + ) + + private val wallet = GroupWallet( + signedEvent = 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 = account, + ) + + private fun repository(opened: GroupWallet?) = + object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY { + override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = opened + } + + private fun viewModel(opened: GroupWallet?, wallets: GroupOnchainWallets?) = + GroupWalletAddressesViewModel( + chatRoomId = chatRoomId, + chain = Chain.Regtest, + initialUIState = GroupWalletAddressesUIState.Loading, + chatRepository = repository(opened), + wallets = wallets, + ).apply { initiate() } + + private fun GroupWalletAddressesViewModel.until(predicate: (GroupWalletAddressesUIState) -> Boolean): GroupWalletAddressesUIState = + runBlocking { + withTimeout(10_000) { + while (!predicate(uiState)) delay(10) + uiState + } + } + + private fun receive(index: Long) = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index) + + @Test + fun `a room with no wallet has no addresses to list`() { + assertIs(viewModel(opened = null, wallets = null).until { it != GroupWalletAddressesUIState.Loading }) + } + + @Test + fun `a profile with no node is told it cannot watch rather than shown nothing`() { + assertEquals( + GroupWalletAddressesUIState.CannotWatch, + viewModel(opened = wallet, wallets = null).until { it != GroupWalletAddressesUIState.Loading }, + ) + } + + @Test + fun `the list follows a payment while the screen is open`() { + val electrum = FakeElectrum() + val addresses = viewModel(opened = wallet, wallets = GroupOnchainWallets(electrum, scope)) + + addresses.until { (it as? GroupWalletAddressesUIState.Loaded)?.receive != null } + runBlocking { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } + + val state = addresses.until { loaded -> + (loaded as? GroupWalletAddressesUIState.Loaded)?.receive?.any { it.status == GroupAddress.Status.USED } == true + } + val current = assertIs(state).receive!!.single { it.status == GroupAddress.Status.CURRENT } + assertEquals(1L, current.derivation.index) + } + + private fun GroupWalletAddressesViewModel.untilListed(index: Long, status: GroupAddress.Status) = until { loaded -> + (loaded as? GroupWalletAddressesUIState.Loaded)?.receive?.any { it.derivation.index == index && it.status == status } == true + } + + @Test + fun `the sheet closes once when the address it shows is paid`() { + val electrum = FakeElectrum() + val addresses = viewModel(opened = wallet, wallets = GroupOnchainWallets(electrum, scope)) + addresses.untilListed(1L, GroupAddress.Status.NEXT) + + var paid = 0 + addresses.show(1L) { paid++ } + runBlocking { electrum.pay(receive(1).pubkeyScript, Satoshi(25_000)) } + addresses.untilListed(1L, GroupAddress.Status.USED) + runBlocking { withTimeout(10_000) { while (addresses.shown != null) delay(10) } } + + assertNull(addresses.shown) + assertEquals(1, paid) + } + + @Test + fun `the sheet stays open when some other address is paid`() { + val electrum = FakeElectrum() + val addresses = viewModel(opened = wallet, wallets = GroupOnchainWallets(electrum, scope)) + addresses.untilListed(1L, GroupAddress.Status.NEXT) + + var paid = 0 + addresses.show(1L) { paid++ } + runBlocking { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } + addresses.untilListed(1L, GroupAddress.Status.CURRENT) + + assertEquals(1L, addresses.shown, "the address it shows became the current one, which is still unused") + assertEquals(0, paid) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt new file mode 100644 index 00000000..f2d51fbe --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt @@ -0,0 +1,88 @@ +package com.machankura.bennu.compose.wallet + +import fr.acinq.bitcoin.Block +import fr.acinq.bitcoin.BlockHeader +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Crypto +import fr.acinq.bitcoin.OutPoint +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.lightning.blockchain.electrum.ElectrumConnectionStatus +import fr.acinq.lightning.blockchain.electrum.ElectrumSubscriptionResponse +import fr.acinq.lightning.blockchain.electrum.GetMerkleResponse +import fr.acinq.lightning.blockchain.electrum.HeaderSubscriptionResponse +import fr.acinq.lightning.blockchain.electrum.IElectrumClient +import fr.acinq.lightning.blockchain.electrum.ScriptHashSubscriptionResponse +import fr.acinq.lightning.blockchain.electrum.TransactionHistoryItem +import fr.acinq.lightning.blockchain.electrum.UnspentItem +import fr.acinq.lightning.blockchain.fee.FeeratePerKw +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +/** + * A chain that only exists in a test. + * + * `IElectrumClient` is small and documented never to throw, so a fake of it is + * a few maps: what each script has been paid, what of it is unspent, and the + * transactions that paid it. + */ +internal class FakeElectrum : IElectrumClient { + val unspents = mutableMapOf>() + val txs = mutableMapOf() + val subscribed = mutableSetOf() + override val notifications = MutableSharedFlow(extraBufferCapacity = 64) + override val connectionStatus: StateFlow = MutableStateFlow(ElectrumConnectionStatus.Closed(null)) + + /** How many transactions have touched each script: Electrum's status is over the history, not the unspents. */ + private val history = mutableMapOf() + + private fun status(scriptHash: ByteVector32): String? = history[scriptHash]?.let { "used:$it" } + + /** Pays [script] in a fresh transaction, confirmed at [height] (0 for the mempool), and tells the wallet. */ + suspend fun pay(script: ByteVector, amount: Satoshi, height: Long = 100) { + val tx = Transaction( + version = 2, + txIn = listOf(TxIn(OutPoint(TxId(ByteVector32(Crypto.sha256(script.toByteArray() + txs.size.toByte()))), 0), ByteVector.empty, 0xffffffffL)), + txOut = listOf(TxOut(amount, script)), + lockTime = 0, + ) + txs[tx.txid] = tx + val hash = scriptHash(script) + unspents[hash] = unspents[hash].orEmpty() + UnspentItem(tx.txid, 0, amount.sat, height) + history[hash] = (history[hash] ?: 0) + 1 + notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash))) + } + + /** Spends everything [script] holds: its unspents go, its history stays. */ + suspend fun spend(script: ByteVector) { + val hash = scriptHash(script) + unspents.remove(hash) + history[hash] = (history[hash] ?: 0) + 1 + notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash))) + } + + override suspend fun startScriptHashSubscription(scriptHash: ByteVector32): ScriptHashSubscriptionResponse { + subscribed += scriptHash + return ScriptHashSubscriptionResponse(scriptHash, status(scriptHash)) + } + + override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = unspents[scriptHash].orEmpty() + override suspend fun getTx(txId: TxId): Transaction? = txs[txId] + override suspend fun getHeader(blockHeight: Int): BlockHeader? = null + override suspend fun getHeaders(startHeight: Int, count: Int): List = emptyList() + override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null + override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = emptyList() + override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid + override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null + override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header) + + companion object { + /** Electrum's script hash: sha256 of the script, byte-reversed. */ + fun scriptHash(script: ByteVector): ByteVector32 = ByteVector32(Crypto.sha256(script.toByteArray()).reversedArray()) + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWalletJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWalletJvmTest.kt index 62627d0c..61150c11 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWalletJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWalletJvmTest.kt @@ -2,36 +2,16 @@ package com.machankura.bennu.compose.wallet import com.machankura.bennu.compose.managers.GroupWalletDerivation import fr.acinq.bitcoin.Block -import fr.acinq.bitcoin.BlockHeader -import fr.acinq.bitcoin.ByteVector import fr.acinq.bitcoin.ByteVector32 import fr.acinq.bitcoin.Chain -import fr.acinq.bitcoin.Crypto -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.lightning.blockchain.electrum.ElectrumConnectionStatus -import fr.acinq.lightning.blockchain.electrum.ElectrumSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.GetMerkleResponse import fr.acinq.lightning.blockchain.electrum.HeaderSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.IElectrumClient -import fr.acinq.lightning.blockchain.electrum.ScriptHashSubscriptionResponse -import fr.acinq.lightning.blockchain.electrum.TransactionHistoryItem -import fr.acinq.lightning.blockchain.electrum.UnspentItem -import fr.acinq.lightning.blockchain.fee.FeeratePerKw import fr.acinq.secp256k1.Hex import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel -import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.MutableSharedFlow -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout @@ -42,56 +22,9 @@ import kotlin.test.assertNull import kotlin.test.assertTrue /** - * The group's wallet watching a chain that only exists in this file. - * - * `IElectrumClient` is small and documented never to throw, so a fake of it is - * a few maps: what each script has been paid, and the transactions that paid it. + * The group's wallet watching a chain that only exists in [FakeElectrum]. */ class GroupOnchainWalletJvmTest { - private class FakeElectrum : IElectrumClient { - val unspents = mutableMapOf>() - val txs = mutableMapOf() - val subscribed = mutableSetOf() - override val notifications = MutableSharedFlow(extraBufferCapacity = 64) - override val connectionStatus: StateFlow = MutableStateFlow(ElectrumConnectionStatus.Closed(null)) - - private fun status(scriptHash: ByteVector32): String? = unspents[scriptHash]?.takeIf { it.isNotEmpty() }?.let { "used" } - - /** Pays [script] in a fresh transaction, confirmed at [height] (0 for the mempool), and tells the wallet. */ - suspend fun pay(script: ByteVector, amount: Satoshi, height: Long = 100) { - val tx = Transaction( - version = 2, - txIn = listOf(TxIn(OutPoint(TxId(ByteVector32(Crypto.sha256(script.toByteArray() + txs.size.toByte()))), 0), ByteVector.empty, 0xffffffffL)), - txOut = listOf(TxOut(amount, script)), - lockTime = 0, - ) - txs[tx.txid] = tx - val hash = scriptHash(script) - unspents[hash] = unspents[hash].orEmpty() + UnspentItem(tx.txid, 0, amount.sat, height) - notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash))) - } - - override suspend fun startScriptHashSubscription(scriptHash: ByteVector32): ScriptHashSubscriptionResponse { - subscribed += scriptHash - return ScriptHashSubscriptionResponse(scriptHash, status(scriptHash)) - } - - override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = unspents[scriptHash].orEmpty() - override suspend fun getTx(txId: TxId): Transaction? = txs[txId] - override suspend fun getHeader(blockHeight: Int): BlockHeader? = null - override suspend fun getHeaders(startHeight: Int, count: Int): List = emptyList() - override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null - override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = emptyList() - override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid - override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null - override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header) - - companion object { - /** Electrum's script hash: sha256 of the script, byte-reversed. */ - fun scriptHash(script: ByteVector): ByteVector32 = ByteVector32(Crypto.sha256(script.toByteArray()).reversedArray()) - } - } - private fun key(seed: Int): String = PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() @@ -187,4 +120,126 @@ class GroupOnchainWalletJvmTest { assertEquals(lookAhead - 1, state.nextChangeIndex(held - (lookAhead - 1))) assertEquals(null, state.nextChangeIndex(held)) } + + private fun GroupWalletState.listed(): List>? = + receiveAddresses?.map { it.derivation.index to it.status } + + @Test + fun `a fresh wallet lists the current address and the two after it`() { + val wallet = GroupOnchainWallet(account, FakeElectrum(), scope) + + val state = eventually { wallet.state.first { it.receiveAddresses != null } } + assertEquals( + listOf(2L to GroupAddress.Status.NEXT, 1L to GroupAddress.Status.NEXT, 0L to GroupAddress.Status.CURRENT), + state.listed(), + ) + assertEquals(state.receiveAddress, state.receiveAddresses!!.last().address, "the current row is the address the wallet screen shows") + } + + @Test + fun `a paid address stays in the list and the list moves on with it`() { + val electrum = FakeElectrum() + val wallet = GroupOnchainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.receiveAddresses != null } } + eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } + + val state = eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } } + assertEquals( + listOf( + 3L to GroupAddress.Status.NEXT, + 2L to GroupAddress.Status.NEXT, + 1L to GroupAddress.Status.CURRENT, + 0L to GroupAddress.Status.USED, + ), + state.listed(), + ) + assertEquals(Satoshi(25_000), state.receiveAddresses!!.last().balance) + } + + @Test + fun `a paid address that has been spent from is still used`() { + val electrum = FakeElectrum() + val wallet = GroupOnchainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.receiveAddresses != null } } + eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } + eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } } + eventually { electrum.spend(receive(0).pubkeyScript) } + + val state = eventually { wallet.state.first { it.utxos.isEmpty() && it.receiveAddresses != null } } + val spent = state.receiveAddresses!!.single { it.derivation.index == 0L } + assertEquals(GroupAddress.Status.USED, spent.status) + assertEquals(Satoshi(0), spent.balance) + assertEquals(receive(1).address(Chain.Regtest), state.receiveAddress, "an emptied address is not handed out again") + } + + @Test + fun `a payment past the current address is listed however far up it is`() { + val electrum = FakeElectrum() + val wallet = GroupOnchainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.receiveAddresses != null } } + eventually { electrum.pay(receive(6).pubkeyScript, Satoshi(10_000)) } + + val state = eventually { wallet.state.first { it.receiveAddresses?.any { it.status == GroupAddress.Status.USED } == true } } + assertEquals( + listOf(6L to GroupAddress.Status.USED) + + (5L downTo 1L).map { it to GroupAddress.Status.NEXT } + + listOf(0L to GroupAddress.Status.CURRENT), + state.listed(), + "the lowest unused address is still the current one", + ) + } + + @Test + fun `every listed address is one the wallet watches`() { + val electrum = FakeElectrum() + val wallet = GroupOnchainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.receiveAddresses != null } } + eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(1_000)) } + eventually { electrum.pay(receive(1).pubkeyScript, Satoshi(1_000)) } + + val state = eventually { wallet.state.first { it.receiveAddress == receive(2).address(Chain.Regtest) } } + val watched = state.receive.addresses.keys + state.receiveAddresses!!.forEach { assertTrue(it.address in watched, "${it.derivation.index} is listed but not watched") } + } + + @Test + fun `change addresses are never listed for receiving`() { + val electrum = FakeElectrum() + val wallet = GroupOnchainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.nextChangeIndex() == 0L } } + eventually { electrum.pay(change(0).pubkeyScript, Satoshi(7_000)) } + + val state = eventually { wallet.state.first { it.nextChangeIndex() == 1L && it.receiveAddresses != null } } + assertTrue(state.receiveAddresses!!.none { it.address == change(0).address(Chain.Regtest) }) + assertTrue(state.receiveAddresses!!.all { it.derivation.change == GroupWalletDerivation.RECEIVE }) + } + + @Test + fun `a wallet that has never sent lists no change addresses`() { + val wallet = GroupOnchainWallet(account, FakeElectrum(), scope) + + val state = eventually { wallet.state.first { it.changeAddresses != null } } + assertEquals(emptyList(), state.changeAddresses, "unused change is never offered, not even as the next one") + } + + @Test + fun `used change addresses are listed and the receive list is untouched`() { + val electrum = FakeElectrum() + val wallet = GroupOnchainWallet(account, electrum, scope) + + val before = eventually { wallet.state.first { it.receiveAddresses != null && it.changeAddresses != null } } + eventually { electrum.pay(change(0).pubkeyScript, Satoshi(7_000)) } + + val state = eventually { wallet.state.first { it.changeAddresses?.isNotEmpty() == true } } + val used = state.changeAddresses!!.single() + assertEquals(change(0), used.derivation) + assertEquals(GroupAddress.Status.USED, used.status) + assertEquals(Satoshi(7_000), used.balance) + assertEquals(before.listed(), state.listed()) + } } diff --git a/docs/README.md b/docs/README.md index 64ac7d50..5c195699 100644 --- a/docs/README.md +++ b/docs/README.md @@ -12,6 +12,7 @@ silent, or a decision that looked arbitrary and was not. | [frost-batch-signing.md](./frost-batch-signing.md) | signing several events in one ceremony — why one nonce can never cover two messages, and the phased schema, wire and UI work that follows from it | | [group-chain-wallet.md](./group-chain-wallet.md) | an on-chain wallet the group's threshold key holds, modelled on Phoenix's final wallet — why the path is BIP86's unhardened tail under a public account step, why each input is a batch item with its own cache, and the seven checks a member makes before signing a spend | | [group-send-an-amount.md](./group-send-an-amount.md) | sending an amount in sats from the group's wallet, with change — why the gate as written could never lift and is removed in favour of the mainnet cap, the decimal point the gated form multiplies by ten, and change addresses reserved like coins | +| [group-wallet-addresses.md](./group-wallet-addresses.md) | listing the group wallet's receive addresses as Phoenix lists its swap-in ones — why the list stops at the current address plus two, why a paid address past that still shows, and why a used address can be copied but never shown as a QR code | | [frost-session-resend.md](./frost-session-resend.md) | asking the members who never got a signing proposal to look again — why a proposer can repeat only what it wrote, why a member's availability signal needs no repeating, and the one half that has to come from the silent member's own device | | [marmot-membership.md](./marmot-membership.md) | how members join an MLS group, and the epoch race that makes a missing member look like a successful invite | | [member-chronicle.md](./member-chronicle.md) | handing a member added after the work was done the group's signed record — why the events are not on the wire at all, and why the room's id is enough to verify them | @@ -42,6 +43,10 @@ jvm-target note is unrelated to all of them: it is a build and packaging story. The subgroups note is a phased plan that has been built; it assumes both shared-key notes and reads as the ceremony's second half — what a group does once it has a key, and what it can say about a group that does not yet. +The group-wallet-addresses note is a phased plan that has been built, and is the +group-chain-wallet note's Phase 5 taken one screen further: read that note's +Phases 4 and 5 first, and its own table of where the build chose differently +before the code. The Material Design note is a phased plan that has not been built, and is the only one about what the app looks like rather than what it does; read the jvm-target note first if you want to know why its adaptive-layout phase exists. diff --git a/docs/group-chain-wallet.md b/docs/group-chain-wallet.md index b5d8c0b3..c0ee5df7 100644 --- a/docs/group-chain-wallet.md +++ b/docs/group-chain-wallet.md @@ -497,7 +497,9 @@ script hashes it does not know. **Gap limit.** Phoenix's final wallet watches one address; the swap-in wallet's default `lookAhead` is 3. A group hands addresses out from several devices, so two members can show the same next address and the gap is mostly bounded by deposits -nobody made. Start at 10 for receive and 3 for change — each is one Electrum +nobody made. (The address list in +[group-wallet-addresses.md](./group-wallet-addresses.md) is what lets them hand +out different ones.) Start at 10 for receive and 3 for change — each is one Electrum subscription per group, and a member in twenty groups pays for all of them. `derivationOf` searches only addresses the wallets have generated, which is the bound on how far Phase 7's checks will look. diff --git a/docs/group-wallet-addresses.md b/docs/group-wallet-addresses.md new file mode 100644 index 00000000..44f4e207 --- /dev/null +++ b/docs/group-wallet-addresses.md @@ -0,0 +1,399 @@ +# The group wallet's addresses + +A screen that lists the group wallet's receive addresses: every one that has been +paid, the one the wallet is handing out now, and the next two after it. It is +modelled on Phoenix's *Swap-in addresses* screen, and this note says where it +follows that screen and the three places it does not. + +Read [group-chain-wallet.md](./group-chain-wallet.md) first, Phases 4 and 5 in +particular: this list is a view over the same `ElectrumMiniWallet` state that +picks the receive address, and it adds nothing to what the wallet watches. + +**Built**, phases 1-5, one commit per phase. Written against the code as it stood +at `707e1465`, with the `lightning-kmp-app` submodule at `e0d2b82`. +`GroupWalletState.receiveAddresses` and `changeAddresses` are the entry points, +and `GroupWalletAddressesScreen` is the screen they feed. The phases are kept as +written; where the build chose differently the table below says so. + +| what the plan said | what it turned out to be | +|---|---| +| the explainer ends *share one of the next two* | *share one of the ones after it*, so the sentence does not have to change if `ADDRESSES_AHEAD` does | +| `FakeElectrum` gains a `spend` and a history | and moves out of `GroupOnchainWalletJvmTest` into a file of its own, `FakeElectrum.kt`, so the view model's tests can drive a chain too | +| rows keyed by index | keyed by branch and index: Phase 4's change section starts at index 0 too, and a `LazyColumn` with two rows under one key throws | +| `receiveAddresses` is one function over the receive branch | one private `listed(branch, state, current)` behind both it and Phase 4's `changeAddresses`; a branch with no current index lists only its used addresses | +| an unused row is clickable | and says what a click does: `onClickLabel` is *Show as a QR code*, so a screen reader announces it rather than an unlabelled action | +| the sheet is the `BottomSheetDialog` widget | the `ModalBottomSheet` wrapper that `BottomSheetDialog.kt` declares, as `ChatRoomDetailScreen` calls it | +| the sheet closes when its address's status is anything other than current or next | when it is `USED`, which is the same thing: those are the three there are | +| one view-model test for the sheet | two, the second that a payment to *another* address leaves the sheet open: paying the current address can turn the shown one from next into current, and that is not a reason to close it | +| the copy button's description is *Copy address %1$s* with the index | it is, and a receive row and a change row with the same index therefore share it. The section heading between them is what tells them apart to a screen reader | + +A real wallet has not been looked at through this screen yet. Every phase was +checked with `:composeApp:jvmTest`, `:composeApp:compileDebugKotlinAndroid` and +`m3-audit.sh --check`, and the list's rules are tested against the fake chain, +but no device has drawn it over an Electrum server. + +The headline: **the list is indices `0` through `max(current + 2, highest used)`, +newest first, read straight off the receive mini-wallet's `WalletState`. Nothing +is stored and nothing new is subscribed to.** The two addresses after the current +one are there so that up to three members can each hand out a different address +on purpose. The `highest used` term exists because the wallet's lowest-unused rule +can put the current address *below* a paid one. + +--- + +## What Phoenix's screen is, and what carries over + +`SwapInAddresses.kt` and `SwapInAddressesViewModel.kt` in +`phoenix-android/.../settings/walletinfo/`. The view model collects +`swapInWallet.wallet.walletStateFlow`. On each emission it takes every +`AddressMeta.Derived` entry, sorts them by index with the newest first, and marks +the one that equals `firstUnusedDerivedAddress` as current. Each row has: + +- a 3dp bar on the leading edge: primary for the current address, a border grey + for a used one, and nothing for one not used yet; +- the derivation index, in monospace; +- the address, in monospace on one line with a middle ellipsis, bold if current; +- a copy button; +- and a tap on the whole row, which opens the address in a block explorer. + +A legacy single address gets a section of its own underneath. While the list is +empty the screen shows *Synchronizing…*. + +What carries over unchanged: the source of truth (the mini-wallet's state, nothing +stored), newest first, the current address marked, index and address on one row, +copy on every row, and a loading state until Electrum has answered. + +What does not: + +| Phoenix | here | why | +|---|---|---| +| every generated address, the whole look-ahead | `0 … max(current + 2, highest used)` | a swap-in wallet belongs to one person, so a look-ahead address is never handed out by anyone else. A group's look-ahead is 10 (`RECEIVE_LOOKAHEAD`), and seven unused addresses past the useful ones is a list that reads as "this wallet has seventeen addresses", when it really has the ones that were paid | +| tapping a row opens a block explorer | tapping a row opens the address's QR code, and only for an address not used yet | the app has no explorer helper, and handing every address of a group's wallet to a third party's server ties them to this member's IP. That is the leak the watch-only export already warns about, made without being asked. And the thing a member wants to do with a *next* address is show it to the payer | +| one section per address type | a receive section, then (Phase 4) a short section of used change addresses | the group wallet has one address type and two branches. Change is the group's money too, but it is never handed out, so it gets no current marker and no next addresses | + +--- + +## The bound + +`current` is `receive.firstUnusedDerivedAddress`'s index: the lowest index whose +Electrum status has always been null. `highest used` is the largest index whose +`AddressState.alreadyUsed` is true, or −1 if none is. + +``` +last = max(current + AHEAD, highestUsed) AHEAD = 2 +rows = 0 … last, newest first +``` + +**Why `+ 2`.** The address the wallet screen shows is computed on each device +separately, and every device computes the same one. Two members showing the +wallet to two payers in the same hour hand out the same address, and the group +reuses it. Offering `current + 1` and `current + 2` beside it gives a second and +third member something else to hand out. Both are already watched, because the +look-ahead keeps the wallet subscribed to `current … current + 9`, so a payment +to either is seen the moment it reaches the mempool. + +**Why `highest used`.** `firstUnusedDerivedAddress` takes the *lowest* unused +index, so a payment above `current` does not move `current`. If `/0/3` is +current and a payer uses `/0/5`, current stays at 3 and `current + 2` is still 5, +so the paid address is listed. This screen never offers anything past +`current + 2`, so on its own it never needs the second term. But a watch-only +wallet importing the group's descriptors can hand out any address up to the +look-ahead. If it is paid at `/0/8` while `/0/3` is current, `current + 2` stops +at 5. A list of "every address that has been paid" that leaves out `/0/8` would +be false, so the bound reaches up to the highest used address too. + +**Why `AHEAD` must stay below the look-ahead.** A row this screen offers has to be +one the wallet is subscribed to, or a payment to it is invisible until the +look-ahead catches up. `current + AHEAD ≤ current + RECEIVE_LOOKAHEAD - 1` holds +for anything up to 9. Phase 1 states it as a `require` next to the constant, so +anyone who raises one has to look at the other. + +**Before Electrum has answered,** there is no list. This is the same rule +`receiveAddress` already follows: before the first answer every address reads as +unused, and a list showing `/0/0` as current to a group that has been paid there +fifty times would misstate the history. The list is null whenever +`receiveAddress` is. + +--- + +## What "used" means, and what a row says + +`AddressState.alreadyUsed` is true once Electrum's status for the script hash is +non-null, which means the address has *any* history, in a block or in the +mempool. It does not go back to false when the coins are spent. That is +the right meaning for this screen: a paid address whose coins have since moved +has still been used, and handing it out again is still reuse. + +Each row can therefore say one of four things: + +| status | condition | supporting text | +|---|---|---| +| current | index == `current` | *Being handed out now* | +| next | index > `current`, not used | *Not used yet* | +| used, holding coins | `alreadyUsed`, `utxos` not empty | *Paid · 12,000 sats* | +| used, empty | `alreadyUsed`, `utxos` empty | *Paid · spent since* | + +An unused address *below* `current` cannot happen, because `current` is the +lowest unused index by definition. An unused address *between* `current` and +`highest used` can. It reads as *next*, which is true. + +The amount is `AddressState.utxos`' sum, which already includes coins still in +the mempool. Whether they are confirmed is on the wallet screen's coin rows, and +is not repeated here. + +--- + +## Phase 0 — before any code + +**An hour, to settle three things the phases assume.** + +1. **The bound is `max(current + 2, highest used)`, and `AHEAD` is a constant.** + Not a setting: two is what the request asked for and is enough for three + members at once. A setting nobody changes is a decision deferred to someone + who has less context. +2. **No block explorer.** If one is wanted later, it goes behind its own + decision about which explorer and what it learns. It should not ride in on a + list screen. +3. **A used address offers copy but never a QR code.** Copy is for checking, for + example pasting into a watch-only wallet or matching a payer's receipt. A + QR code is for being paid, and a used address should not be. + +--- + +## Phase 1 — `GroupWalletState.receiveAddresses` + +**Half a day, most of it the test.** + +In `composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallet.kt`, +beside `receiveAddress`: + +```kotlin +/** One receive address as the address list shows it. */ +data class GroupAddress( + val derivation: GroupWalletDerivation.Derived, + val address: String, + val status: Status, + /** What it holds now: zero for an address never paid, and for one paid and spent. */ + val balance: Satoshi, +) { + enum class Status { CURRENT, NEXT, USED } +} + +/** + * The receive addresses worth listing, newest first: every one paid, the one + * being handed out, and [ADDRESSES_AHEAD] after it -- or null until Electrum + * has said which are used, for the reason [receiveAddress] is. + */ +val receiveAddresses: List? by lazy { … } +``` + +and in `GroupOnchainWallet.Companion`: + +```kotlin +/** + * Unused receive addresses the address list offers past the current one, so + * several members can each hand out a different one. Every one of them has to + * be watched already, or a payment to it would go unseen. + */ +const val ADDRESSES_AHEAD: Int = 2 + +init { require(ADDRESSES_AHEAD < RECEIVE_LOOKAHEAD.toInt()) } +``` + +The body reads `receive.addresses`, keeps the `AddressMeta.Derived` entries, +computes `current` and `highestUsed`, then filters to the bound, maps each entry +through `GroupWalletDerivation.derive(account, RECEIVE, index)` and sorts +descending. It is a pure function of the state, `lazy` like `utxos`, because the +screen reads it on every recomposition. + +A `Status.USED` with a zero balance is the *spent since* row. There is no fourth +enum value, because the balance already says it. + +**The test fake needs one change first.** `FakeElectrum.status` in +`GroupOnchainWalletJvmTest` reports `"used"` only while a script has unspents. +Real Electrum reports a status for any history, so an address that has been spent +from reads as unused in the fake and as used on the chain. Phase 1 adds a +`spend(script)` to the fake that removes the unspents but keeps a `history` +entry, and makes `status` read the history. The existing four tests do not depend +on the old behaviour. + +**Tests**, in `GroupOnchainWalletJvmTest`: + +- a fresh wallet lists `/0/2`, `/0/1`, `/0/0`, with `/0/0` current and the + other two next; +- paying `/0/0` lists `/0/3 … /0/0`: `/0/1` current, `/0/0` used with its amount; +- paying `/0/0` and then spending it leaves `/0/0` used with a zero balance, and + current does not go back to 0; +- paying `/0/6` while `/0/0` is current lists `/0/6 … /0/0`, with `/0/0` current, + `/0/6` used and `/0/1 … /0/5` next. This is the gap rule; +- every listed index is one the wallet has generated. The test checks this + against `receive.addresses.keys` and fails if `ADDRESSES_AHEAD` ever outgrows + the look-ahead; +- change addresses never appear, even when `/1/0` has been paid. + +--- + +## Phase 2 — the screen + +**A day and a half.** + +- `GroupWalletAddressesRoute(activeUserPublicKey, chatRoomId)` in + `ui/composable/navigation/routes/`, and a `composable` + in `BennuNavHost` beside `GroupWalletRoute`'s, with `onNavigateBack = + { navController.popBackStack() }`. It is a pushed screen, so it gets + `NavigateBackButton` in the leading slot of its `TopAppBar`. +- **The way in** is a `TextButton` at the bottom of the receive-address card in + `OpenWallet` (`GroupWalletScreen.kt`), under *Copy address*: *All addresses*, + with a `Decorative` list icon. It is in the card rather than in the app bar + because it answers the question the card raises: *which address do I give?* +- **`GroupWalletAddressesViewModel`** reads the room the way + `GroupWalletViewModel.initiate` does (`chatRepository.groupWallet(chatRoomId, + chain)`), then collects `wallets.walletFor(wallet.account).state` and maps it + to `receiveAddresses`. `GroupOnchainWallets` keeps one wallet per account for + the identity's life, so this is the same instance the wallet screen is already + watching: it adds no subscriptions and does not need a second Electrum answer. + Its own `GroupWalletAddressesUIState` has `Loading`, `Error`, `CannotWatch` + (no node, the same case as `this_profile_cannot_watch_the_chain`) and + `Loaded(addresses: List?)`, where a null list is the + waiting-for-Electrum state. +- **Four states**, through `ScreenStateTransition` over the whole body: + `LoadingDataIndicator` while the room loads and again (with + *Finding the group's coins…*) while the list is null. `ErrorState` with + `onRetry = null`, for the same reason the wallet screen gives. `EmptyState` + for `CannotWatch`, with that screen's sentence. Then the list. A loaded list is + never empty, because a fresh wallet has three rows. +- **The rows**, a `LazyColumn` with `readableContent()` on its root, keyed by + index. Each row is a `ListItem`: + - `leadingContent`: the index in `labelLarge`. The leading-edge bar from Phoenix + is replaced by the M3 pairing: the current row's `ListItem` takes + `colors = ListItemDefaults.colors(containerColor = secondaryContainer)`, and + its text takes the matching `onSecondaryContainer`. A 3dp bar would be a + dimension literal and a colour with no pairing; a container role is both + already decided. + - `headlineContent`: the address, `bodyMedium` in the monospace family + already used for keys elsewhere, one line, `TextOverflow.MiddleEllipsis`. + `DkgRitualScreen` and `KeyPackageManagementScreen` use the same overflow, so + it is known to work on the pinned Compose 1.11.1. + - `supportingContent`: the status sentence from the table above. + - `trailingContent`: an `IconButton` with `ContentCopy`, whose + `contentDescription` is *Copy address %1$s* with the index as the format + argument. The icon carries the row's meaning and the index tells a screen + reader which row it is, so it is not decorative. +- **Copy** writes the full address to the clipboard and reports *Address copied* + through `rememberNotifier`, which is the string the wallet screen already uses, + read above the handler. +- **Strings**, sentence case, in the group-wallet block of `strings.xml`: + `all_addresses` (*All addresses*), `addresses` (*Addresses*, the title), + `being_handed_out_now`, `not_used_yet`, `paid_s_sats` (*Paid · %1$s sats*), + `paid_spent_since`, `copy_address_s`. Plus one line above the list, + `addresses_explainer`: *Each payment should go to a new address. If someone + else in the group is already sharing the current one, share one of the next + two.* That sentence is the reason the next two rows exist, and a member who + is not told it will only ever use the top one. + +`./gradlew :composeApp:m3Audit`, then +`./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest`, before the +commit. The audit counts this screen's spacing, colour, string, target and +description budgets like any other screen's. + +--- + +## Phase 3 — handing out a next address + +**A day.** + +Tapping a *current* or *next* row opens a `ModalBottomSheet` holding the same +three things the wallet screen's receive card holds for its one address: a +`QRCodeView(bip21Uri(address))` (whose modules are already +`m3-color-exempt`), the full address in a `SelectionContainer`, and *Copy +address*. Its title is *Address %1$s*, with the index as the argument, so a member +reading it to a payer over the phone can say which one they gave. The sheet is +the existing `BottomSheetDialog` widget, as `ChatRoomDetailScreen` uses it. + +A *used* row is not clickable. It has the copy button and nothing else, which is +Phase 0's third decision. The row stays a plain `ListItem` with no +`Modifier.clickable`, so it is not an unguarded target. + +The sheet closes by itself when its address stops being unused, which means a +payment arrived while it was open. The view model already emits a new list, +the sheet's address is looked up in it by index, and a status other than +`CURRENT` or `NEXT` dismisses it with *Address %1$s was just paid*. The payer +scanning it at that moment has already paid, and nobody else should. + +**Test**, in `jvmTest`, on the view model with the Phase 1 fake: open the sheet +on `/0/1`, pay `/0/1`, and assert the sheet state clears and the notifier was +called once. + +--- + +## Phase 4 — used change addresses + +**Half a day. Optional, and the first thing to drop if the rest runs long.** + +A second section under the receive rows, *Change*, listing only the change +addresses with `alreadyUsed`. That means no current row and no next rows, +because change is chosen by a spend and never handed out. Each row has an +index, an address, *Paid · %1$s sats* or *Paid · spent since*, and copy. There is +no sheet and no QR code. The section is hidden when no change address has been +used, which is every wallet that has never sent. + +It is worth having because "every address this wallet has been paid at" without +change is not the whole of that, and a member reconciling against a watch-only +import will see change addresses there. `GroupWalletState.changeAddresses` is +the same function as Phase 1's, over `change` and with the bound set to +`highestUsed`. + +**Test**: after one spend with change to `/1/0`, the change section lists exactly +`/1/0`, and the receive section is unchanged. + +--- + +## Phase 5 — the notes + +**An hour.** + +- This note's status line becomes **Built**, with a table of where the build + chose differently, as every built plan here has. +- A row in [README.md](./README.md)'s table, and a sentence in its reading order + that places it after the group-chain-wallet note. +- In [group-chain-wallet.md](./group-chain-wallet.md)'s Phase 4, the sentence + "two members can show the same next address" gains a pointer here: that is the + hazard this screen exists to reduce. + +--- + +## What is left, when someone wants it + +- **Saying which member has handed out which address.** It would make "share one + of the next two" a choice the app makes rather than one the member makes. The + app cannot know it without a group event per address handed out, which would + put every receive address in the room's history before it is paid. That is a + privacy cost for a coordination gain, and a decision on its own. +- **A label per address**, for example *Thandi's invoice*. It is local or + group-shared, with the same split. Local is simple and is all Phoenix's swap + list has (none). Group-shared is an event kind. +- **A block explorer link**, behind Phase 0's second decision. + +--- + +## Appendix — what was considered and rejected + +**Recording "shown" on this device.** "Used or shown" could mean every address +this device has ever displayed. It would need storage the wallet has +deliberately never had (*"nothing about the wallet is stored"*, +`GroupOnchainWallet`'s kdoc). It would differ from device to device, so two +members' lists would disagree about the same wallet. And it would still miss +the case that matters, which is the address another member showed. The chain is +the only record every device shares, and `current` is the address this device +is showing. + +**Raising `RECEIVE_LOOKAHEAD` and listing all of it.** That is Phoenix's choice, +and it makes the list longer without making it more useful. Every extra +look-ahead address is one more Electrum subscription per group for every member, +and a member in twenty groups pays for all of them (group-chain-wallet.md, +Phase 4). + +**A separate `ElectrumMiniWallet` for the list.** A second subscriber to the same +script hashes would answer the same question twice, and could briefly disagree +with the wallet screen about which address is current. `walletFor` returns the +existing instance, and that is the one to read.