From 784855954786b8d91b46480e6695c97a585fa286 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Sat, 24 Oct 2026 07:34:33 +0200 Subject: [PATCH] feat(wallet): the send form funds a descendant's guarded wallet (Phase 4) GroupSendRoute.fundChatRoomId opens the form in fund mode: the address field gives way to a fixed destination card naming the wallet, the address fundingAddress chose and its index, and that the group can spend the coins again after the leaf's lock. The form follows the descendant's chain state and the room's open fundings, so a paid or held address moves on while it is open. A route naming both a source and a destination is not opened. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 6 + .../compose/ui/composable/GroupSendScreen.kt | 109 +++++++++++++--- .../ui/composable/navigation/BennuNavHost.kt | 1 + .../navigation/routes/GroupSendRoute.kt | 5 + .../ui/view/model/GroupSendViewModel.kt | 67 +++++++--- .../compose/ui/view/state/GroupSendUIState.kt | 22 ++++ .../view/model/GroupSendViewModelJvmTest.kt | 116 ++++++++++++++++++ 7 files changed, 296 insertions(+), 30 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 52c5e968..449eecf8 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -473,6 +473,11 @@ Spend from %1$s's guarded wallet Wallets of groups below this one. This group can spend a coin in them once it has %1$d confirmations. %1$s sats within this group's reach + Fund %1$s's guarded wallet + To + This group can spend these coins again once they have %1$d confirmations. + Finding an address in %1$s's wallet… + Wait for this group's open payments to %1$s to confirm. Tell the groups above Not yet shared with the groups above that you're in Share @@ -525,6 +530,7 @@ Fee rate in sats per byte Ask the group to send Sends %1$s sats, with a fee of %2$s sats. + Sends %1$s sats to %2$s's guarded wallet, with a fee of %3$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. 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 index 4df3ce63..d089fed7 100644 --- 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 @@ -1,6 +1,17 @@ package com.machankura.bennu.compose.ui.composable import bennu.composeapp.generated.resources.while_the_wallet_is_new_at_most_s_sats +import androidx.compose.material3.OutlinedCard +import androidx.compose.ui.text.font.FontFamily +import bennu.composeapp.generated.resources.address_s +import bennu.composeapp.generated.resources.finding_an_address_in_s_s_wallet +import bennu.composeapp.generated.resources.fund_s_s_guarded_wallet +import bennu.composeapp.generated.resources.sends_s_sats_to_s_s_guarded_wallet_with_a_fee_of_s_sats +import bennu.composeapp.generated.resources.this_group_can_spend_these_coins_again +import bennu.composeapp.generated.resources.to +import bennu.composeapp.generated.resources.wait_for_this_group_s_open_payments_to_s +import com.machankura.bennu.compose.managers.GuardianDerivation +import com.machankura.bennu.compose.ui.view.state.FundingTarget import androidx.compose.foundation.selection.toggleable import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.ui.semantics.Role @@ -112,6 +123,7 @@ fun GroupSendScreen( frostSigningRepository: FrostSigningRepository, wallets: GroupOnchainWallets?, guardedChatRoomId: String? = null, + fundChatRoomId: String? = null, onNavigateToRouteAndPopUpInclusive: (Route) -> Unit, onNavigateBack: () -> Unit, ) { @@ -125,6 +137,7 @@ fun GroupSendScreen( frostSigningRepository = frostSigningRepository, wallets = wallets, guardedChatRoomId = guardedChatRoomId, + fundChatRoomId = fundChatRoomId, ) ) @@ -141,11 +154,17 @@ fun GroupSendScreen( TopAppBar( title = { // Whose wallet is in the title: a guardian's spend takes a - // descendant's coins, and nothing else on the form says so. - val guardian = ((groupSendViewModel.groupSendUIState as? GroupSendUIState.Ready)?.spender as? GroupSpend.Spender.Guardian) + // descendant's coins, and nothing else on the form says so -- + // and a funding pays one, which the title says the same way. + val ready = groupSendViewModel.groupSendUIState as? GroupSendUIState.Ready + val guardian = ready?.spender as? GroupSpend.Spender.Guardian + val funded = ready?.funding?.wallet Text( - text = if (guardian == null) stringResource(Res.string.send_from_the_group_s_wallet) - else stringResource(Res.string.spend_from_s_s_guarded_wallet, guardian.name ?: stringResource(Res.string.a_subgroup)), + text = when { + guardian != null -> stringResource(Res.string.spend_from_s_s_guarded_wallet, guardian.name ?: stringResource(Res.string.a_subgroup)) + funded != null -> stringResource(Res.string.fund_s_s_guarded_wallet, funded.name ?: stringResource(Res.string.a_subgroup)) + else -> stringResource(Res.string.send_from_the_group_s_wallet) + }, maxLines = 1, overflow = TextOverflow.Ellipsis ) @@ -180,12 +199,17 @@ fun GroupSendScreen( // A problem with the amount is said on the amount field, beside what caused it. val amountProblem = preview?.takeIf { groupSendViewModel.isAboutTheAmount(it) } - OutlinedTextField( - modifier = Modifier.fillMaxWidth(), - state = groupSendViewModel.addressField, - lineLimits = TextFieldLineLimits.SingleLine, - label = { Text(stringResource(Res.string.address)) }, - ) + // A funding's destination is fixed, not typed: the title names + // the wallet, and an address field could make it pay another. + when (val funding = state.funding) { + null -> OutlinedTextField( + modifier = Modifier.fillMaxWidth(), + state = groupSendViewModel.addressField, + lineLimits = TextFieldLineLimits.SingleLine, + label = { Text(stringResource(Res.string.address)) }, + ) + else -> FundingDestination(funding) + } // The row is the target, so the label toggles too: one 48dp control with one name. Row( @@ -238,10 +262,13 @@ fun GroupSendScreen( ) // Still finding change is still finding coins: neither is anything to correct. + // A funded wallet's address not known yet is said on its card, not here. + val fundedName = state.funding?.wallet?.let { it.name ?: stringResource(Res.string.a_subgroup) } + val waitingOnFunding = state.funding != null && state.funding.address == null if (state.walletState == null || preview == GroupSpendBuilder.Result.FindingChange) { LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_the_group_s_coins)) - } else if (amountProblem == null) { - preview?.let { SendPreview(it, chain) } + } else if (amountProblem == null && !waitingOnFunding) { + preview?.let { SendPreview(it, chain, fundedName) } } Text( @@ -279,13 +306,65 @@ fun GroupSendScreen( } } -/** What the form would build, or why it cannot. */ +/** + * Where a funding goes: the descendant's wallet, the address in it this send + * pays and its index, and what the group keeps over the coins once they land. + * While the address is not known yet, or every one is held, it says that instead. + */ @Composable -private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain) { +private fun FundingDestination(funding: FundingTarget) { + val name = funding.wallet.name ?: stringResource(Res.string.a_subgroup) + OutlinedCard(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), + verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap), + ) { + Text(text = stringResource(Res.string.to), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + Text(text = stringResource(Res.string.fund_s_s_guarded_wallet, name), style = MaterialTheme.typography.titleMedium) + val address = funding.address + when { + address != null -> { + Text( + text = address.address, + style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace), + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + ) + Text( + text = stringResource(Res.string.address_s, address.derivation.index.toString()), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + funding.allHeld -> Text( + text = stringResource(Res.string.wait_for_this_group_s_open_payments_to_s, name), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error, + ) + else -> LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_an_address_in_s_s_wallet, name)) + } + // What funding a guarded wallet means for this group: the coins come + // back within its reach, through its leaf, after the lock. + Text( + text = stringResource(Res.string.this_group_can_spend_these_coins_again, GuardianDerivation.ANCESTOR_DELAY.toInt()), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +/** What the form would build, or why it cannot. [fundedName] names the wallet a funding pays. */ +@Composable +private fun SendPreview(result: GroupSpendBuilder.Result, chain: Chain, fundedName: String? = null) { 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()), + text = if (result.funded != null && fundedName != null) { + stringResource(Res.string.sends_s_sats_to_s_s_guarded_wallet_with_a_fee_of_s_sats, result.amount.grouped(), fundedName, result.fee.grouped()) + } else { + 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 -> 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 7ea98d38..8d0a799c 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 @@ -1170,6 +1170,7 @@ fun BennuNavHost( frostSigningRepository = databaseFrostSigningRepository, wallets = groupOnchainWallets, guardedChatRoomId = route.guardedChatRoomId, + fundChatRoomId = route.fundChatRoomId, onNavigateToRouteAndPopUpInclusive = { signingRoute -> // Replace the form so back returns to the wallet rather // than to a spend that has already been proposed. 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 index b18b67d2..55d19763 100644 --- 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 @@ -6,6 +6,10 @@ import kotlinx.serialization.Serializable * The form a member proposes a spend from the group's wallet with -- or, with * [guardedChatRoomId], from that descendant's guarded wallet, through the * group's guardian leaf. + * + * [fundChatRoomId] is where the coins go instead of where they come from: the + * descendant whose guarded wallet a send from the group's own wallet pays. A + * route naming both is not one the form opens -- `docs/guarded-wallet-funding.md`, D6. */ @Serializable data class GroupSendRoute( @@ -13,4 +17,5 @@ data class GroupSendRoute( val chatRoomId: String, val relayHint: String?, val guardedChatRoomId: String? = null, + val fundChatRoomId: String? = null, ): 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 index e3eb9088..97f983bb 100644 --- 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 @@ -20,6 +20,7 @@ import com.machankura.bennu.compose.repository.ChatRepository import com.machankura.bennu.compose.repository.FrostSigningRepository import com.machankura.bennu.compose.text.SatsInput import com.machankura.bennu.compose.text.parseSats +import com.machankura.bennu.compose.ui.view.state.FundingTarget import com.machankura.bennu.compose.ui.view.state.GroupSendUIState import com.machankura.bennu.compose.wallet.GroupOnchainWallets import com.machankura.bennu.compose.wallet.GroupSpendBuilder @@ -32,6 +33,7 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -54,6 +56,8 @@ class GroupSendViewModel( private val wallets: GroupOnchainWallets?, /** The descendant whose guarded wallet this form spends from, or null for the room's own. */ val guardedChatRoomId: String? = null, + /** The descendant whose guarded wallet this form pays, or null for a payment to a typed address. */ + val fundChatRoomId: String? = null, ): ViewModel() { private val logger = Logger.withTag(TAG) @@ -77,20 +81,29 @@ class GroupSendViewModel( return@launch } + // Spending from one descendant's wallet into another's is a decision + // of its own, not one this form makes -- docs/guarded-wallet-funding.md, D6. + if (guardedChatRoomId != null && fundChatRoomId != null) { + groupSendUIState = GroupSendUIState.Unavailable + return@launch + } + // A descendant's guarded wallet, as this room was told it, with the // group as its guardian -- or the room's own wallet. - val guarded = guardedChatRoomId?.let { descendant -> - chatRepository.guardedWallets(chatRoomId).firstOrNull { - it.descendantChatRoomId.equals(descendant, ignoreCase = true) && it.chain == chain - } + val heldByRoom = if (guardedChatRoomId != null || fundChatRoomId != null) chatRepository.guardedWallets(chatRoomId) else emptyList() + fun held(descendant: String?) = descendant?.let { + heldByRoom.firstOrNull { wallet -> wallet.descendantChatRoomId.equals(it, ignoreCase = true) && wallet.chain == chain } } + val guarded = held(guardedChatRoomId) + // The wallet a send from the room's own pays, when it funds one. + val funded = held(fundChatRoomId) val wallet = when { guardedChatRoomId == null -> chatRepository.groupWallet(chatRoomId, chain) guarded == null -> null else -> GroupWallet(GroupSignedEvent.fromEvent(guarded.statement, chatRoomId = guarded.descendantChatRoomId), guarded.account) } val canSign = localChatRoom.chatRoom.mlsGroupState != null && chatRepository.canSign(chatRoomId) - if (wallet == null || !canSign || wallets == null) { + if (wallet == null || !canSign || wallets == null || (fundChatRoomId != null && funded == null)) { groupSendUIState = GroupSendUIState.Unavailable return@launch } @@ -102,6 +115,7 @@ class GroupSendViewModel( reserved = frostSigningRepository.reservedOutPoints(chatRoomId), reservedChange = frostSigningRepository.reservedChangeIndices(chatRoomId, wallet.account), spender = guarded?.spender() ?: GroupSpend.Spender.Owner, + funding = funded?.let { FundingTarget(it, walletState = null, reserved = frostSigningRepository.reservedFundingIndices(chatRoomId, it.account)) }, ) groupSendUIState = ready @@ -111,7 +125,7 @@ class GroupSendViewModel( } } - follow(ready, wallets.walletFor(wallet.account).state) + follow(ready, wallets.walletFor(wallet.account).state, funded?.let { wallets.walletFor(it.account).state }) } } @@ -126,18 +140,35 @@ class GroupSendViewModel( * One state from both, as the wallet screen does, so no frame shows new * coins against old reservations. Apart from [initiate] so that it can be * followed without an Electrum client. + * + * A send that funds a descendant's wallet follows [fundingState] too, and + * the addresses the room's open fundings hold: if the address it was going + * to pay is paid or taken while the form is open, the next one is shown. */ @OptIn(ExperimentalCoroutinesApi::class) - internal fun follow(ready: GroupSendUIState.Ready, chainState: Flow) { + internal fun follow( + ready: GroupSendUIState.Ready, + chainState: Flow, + fundingState: Flow? = null, + ) { val account = ready.wallet.account + val fundedAccount = ready.funding?.wallet?.account val reservations = frostSigningRepository.observeGroupTransactions(chatRoomId).mapLatest { - frostSigningRepository.reservedOutPoints(chatRoomId) to - frostSigningRepository.reservedChangeIndices(chatRoomId, account) + Triple( + frostSigningRepository.reservedOutPoints(chatRoomId), + frostSigningRepository.reservedChangeIndices(chatRoomId, account), + fundedAccount?.let { frostSigningRepository.reservedFundingIndices(chatRoomId, it) }.orEmpty(), + ) } watching?.cancel() watching = viewModelScope.launch(Dispatchers.IO) { - combine(chainState, reservations) { state, (reserved, reservedChange) -> - ready.copy(walletState = state, reserved = reserved, reservedChange = reservedChange) + combine(chainState, fundingState ?: flowOf(null), reservations) { state, funded, (reserved, reservedChange, reservedFunding) -> + ready.copy( + walletState = state, + reserved = reserved, + reservedChange = reservedChange, + funding = ready.funding?.copy(walletState = funded, reserved = reservedFunding), + ) }.collect { groupSendUIState = it } } } @@ -185,12 +216,17 @@ class GroupSendViewModel( } val feerate = feerateField.text.toString().trim().toLongOrNull()?.takeIf { it > 0 } ?: return null - val address = addressField.text.toString().trim().takeIf { it.isNotEmpty() } ?: return null + // A funding pays the address its target chose, never one typed: the + // title says whose wallet it is, and a typed one would make that a claim. + val destination = when (val funding = state.funding) { + null -> GroupSpendBuilder.Destination.Address(addressField.text.toString().trim().takeIf { it.isNotEmpty() } ?: return null) + else -> GroupSpendBuilder.Destination.Funding(funding.wallet.account, funding.address?.derivation ?: return null) + } val built = if (amount == null) { - GroupSpendBuilder.sendAll(walletState, address, feerate, state.reserved, state.spender) + GroupSpendBuilder.sendAll(walletState, destination, feerate, state.reserved, state.spender) } else { - GroupSpendBuilder.send(walletState, address, amount, feerate, state.reserved, state.reservedChange, state.spender) + GroupSpendBuilder.send(walletState, destination, amount, feerate, state.reserved, state.reservedChange, state.spender) } return GroupSpendBuilder.capped(built, GroupWalletRollout.capFor(chain)) } @@ -239,11 +275,12 @@ class GroupSendViewModel( frostSigningRepository: FrostSigningRepository, wallets: GroupOnchainWallets?, guardedChatRoomId: String? = null, + fundChatRoomId: String? = null, ): ViewModelProvider.Factory = viewModelFactory { initializer { GroupSendViewModel( activeUserPublicKey, chatRoomId, chain, initialGroupSendUIState, - chatRepository, frostSigningRepository, wallets, guardedChatRoomId, + chatRepository, frostSigningRepository, wallets, guardedChatRoomId, fundChatRoomId, ) } } 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 index b5b0969e..82dc3523 100644 --- 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 @@ -1,6 +1,8 @@ package com.machankura.bennu.compose.ui.view.state import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.wallet.GroupAddress import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.wallet.GroupSpend import com.machankura.bennu.compose.wallet.GroupWalletState @@ -25,6 +27,8 @@ sealed interface GroupSendUIState { * the descendant's. */ val spender: GroupSpend.Spender = GroupSpend.Spender.Owner, + /** The descendant's guarded wallet this send pays, or null for a send to a typed address. */ + val funding: FundingTarget? = null, ): GroupSendUIState /** A room this device cannot propose from -- no wallet, no share, or no node. */ @@ -34,3 +38,21 @@ sealed interface GroupSendUIState { data object Loading: GroupSendUIState } + +/** + * A descendant's guarded wallet a send funds, with where it is up to: its chain + * state as this device watches it, and the receive indices the room's open + * fundings already hold. See `docs/guarded-wallet-funding.md`. + */ +data class FundingTarget( + val wallet: GuardianManager.GuardedWallet, + /** Null until Electrum has answered for the descendant's addresses. */ + val walletState: GroupWalletState?, + val reserved: Set = emptySet(), +) { + /** The address the send pays, moving on whenever the one before it is paid or held. */ + val address: GroupAddress? get() = walletState?.fundingAddress(reserved) + + /** Electrum has answered, and open fundings hold every address the wallet watches. */ + val allHeld: Boolean get() = walletState?.receiveAddress != null && address == null +} 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 index a7656d60..bd9cc020 100644 --- 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 @@ -10,6 +10,9 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOf import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GuardianManager +import com.machankura.bennu.compose.ui.view.state.FundingTarget +import com.vitorpamplona.quartz.nip01Core.core.Event import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent import com.machankura.bennu.compose.repository.ChatRepository @@ -180,9 +183,11 @@ class GroupSendViewModelJvmTest { val transactions = MutableStateFlow>(emptyList()) @Volatile var heldCoins: Set = emptySet() @Volatile var heldChange: Set = emptySet() + @Volatile var heldFunding: Set = emptySet() override fun observeGroupTransactions(chatRoomId: String): Flow> = transactions override suspend fun reservedOutPoints(chatRoomId: String): Set = heldCoins override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = heldChange + override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = heldFunding } /** Two confirmed coins, 60,000 and 40,000 sats, on the first two receive addresses. */ @@ -241,4 +246,115 @@ class GroupSendViewModelJvmTest { assertEquals(Satoshi(100_000), built.amount + built.fee) assertNull(built.change) } + + // ---- Funding a descendant's guarded wallet --------------------------------- + + private val descendantRoomId = "c".repeat(64) + private val descendant: GroupWalletDerivation.Account = GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), Chain.Regtest, + ) + private val guarded = GuardianManager.GuardedWallet( + ancestorChatRoomId = chatRoomId, + descendantChatRoomId = descendantRoomId, + statement = Event("1".repeat(64), descendantRoomId, 1_700_000_000, GroupWalletStatementEvent.KIND, emptyArray(), "", ""), + account = descendant, + certificate = Event("2".repeat(64), chatRoomId, 1_700_000_000, 0, arrayOf(arrayOf("name", "Savings")), "", ""), + lineage = listOf(descendantRoomId), + ) + + /** The descendant's receive branch as Electrum reports it: its first ten addresses watched, [paid] of them used. */ + private fun descendantState(paid: Set = emptySet()): GroupWalletState { + val receive = (0 until 10).associate { index -> + GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, index.toLong()).address(Chain.Regtest) to + WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = index in paid, utxos = emptyList()) + } + return GroupWalletState(descendant, WalletState(receive), WalletState.empty, tipHeight = 110) + } + + private fun fundingForm(signing: FrostSigningRepository, fundingState: Flow): GroupSendViewModel { + val ready = GroupSendUIState.Ready(localChatRoom, wallet, walletState = null, reserved = emptySet(), funding = FundingTarget(guarded, walletState = null)) + return viewModel(ready, signing = signing).apply { + follow(ready, flowOf(walletState), fundingState) + feerateField.setTextAndPlaceCursorAtEnd("4") + amountField.setTextAndPlaceCursorAtEnd("30,000") + } + } + + @Test + fun `a funding pays two past the descendant's current address, and says so in the PSBT`() { + val signing = RecordingSigning() + val model = fundingForm(signing, flowOf(descendantState())) + + val built = eventually { model.preview() as? GroupSpendBuilder.Result.Built } + assertEquals(2L, built.funded?.derived?.index) + assertEquals(GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, 2).pubkeyScript, built.psbt.global.tx.txOut[0].publicKeyScript) + assertEquals(setOf(2L), GroupSpend.claimedFundingIndices(built.psbt, descendant)) + + // The address field plays no part: whatever is typed there, the funding goes where it goes. + model.addressField.setTextAndPlaceCursorAtEnd("bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080") + assertEquals(built.psbt, assertIs(model.preview()).psbt) + + model.propose(onSuccess = {}, onFailure = {}) + runBlocking { withTimeout(5_000) { while (signing.proposed == null) delay(10) } } + assertEquals(built.psbt, signing.proposed, "proposed as the room's own spend") + } + + @Test + fun `an open funding moves the next one on`() { + val signing = Reserving() + val model = fundingForm(signing, flowOf(descendantState())) + assertEquals(2L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded }.derived.index) + + signing.heldFunding = setOf(2L) + signing.transactions.value = listOf( + GroupTransaction(frostSigningSessionId = "theirs", chatRoomId = chatRoomId, chain = "regtest", account = 0, psbt = "", txid = "t".repeat(64)) + ) + assertEquals(3L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded?.takeIf { it.derived.index != 2L } }.derived.index) + } + + @Test + fun `a payment to the address while the form is open moves it on`() { + val chain = MutableStateFlow(descendantState()) + val model = fundingForm(RecordingSigning(), chain) + assertEquals(2L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded }.derived.index) + + chain.value = descendantState(paid = setOf(2)) + assertEquals(3L, eventually { (model.preview() as? GroupSpendBuilder.Result.Built)?.funded?.takeIf { it.derived.index != 2L } }.derived.index) + } + + @Test + fun `nothing is built while the descendant's addresses are not known, or every one is held`() { + val waiting = fundingForm(RecordingSigning(), flowOf(null)) + val state = eventually { (waiting.groupSendUIState as GroupSendUIState.Ready).takeIf { it.walletState != null } } + assertNull(waiting.preview()) + assertEquals(false, state.funding?.allHeld) + + val signing = Reserving().apply { heldFunding = (2L until 10L).toSet() } + val full = fundingForm(signing, flowOf(descendantState())) + val held = eventually { (full.groupSendUIState as GroupSendUIState.Ready).takeIf { it.funding?.walletState != null } } + assertEquals(true, held.funding?.allHeld) + assertNull(full.preview()) + } + + @Test + fun `a route naming a source and a destination is not opened, nor one funding a wallet the room does not hold`() { + var asked = 0 + 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 + override suspend fun guardedWallets(chatRoomId: String): List { asked++; return emptyList() } + } + val both = GroupSendViewModel("a".repeat(64), chatRoomId, Chain.Regtest, GroupSendUIState.Loading, chat, RecordingSigning(), wallets = null, + guardedChatRoomId = descendantRoomId, fundChatRoomId = descendantRoomId).apply { initiate() } + runBlocking { withTimeout(5_000) { while (both.groupSendUIState == GroupSendUIState.Loading) delay(10) } } + assertEquals(GroupSendUIState.Unavailable, both.groupSendUIState) + assertEquals(0, asked, "refused before either wallet is looked for") + + val unknown = GroupSendViewModel("a".repeat(64), chatRoomId, Chain.Regtest, GroupSendUIState.Loading, chat, RecordingSigning(), wallets = null, + fundChatRoomId = descendantRoomId).apply { initiate() } + runBlocking { withTimeout(5_000) { while (unknown.groupSendUIState == GroupSendUIState.Loading) delay(10) } } + assertEquals(GroupSendUIState.Unavailable, unknown.groupSendUIState) + assertEquals(1, asked) + } }