From c07a5a834f2341ba7b4c5fd290c95dec23ec5318 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 12:44:48 +0200 Subject: [PATCH] fix(wallet): the send form follows the room's spends while it is open The form read which coins and change addresses open spends hold once, when it opened. A spend another member proposed while it was open still looked free, so sending everything would ask the group to sign a second spend of coins only one spend can have. The form now combines the chain state with observeGroupTransactions, as the wallet screen does, and re-reads both reservations on every change, as one state. Co-Authored-By: Claude Opus 5.5 --- .../ui/view/model/GroupSendViewModel.kt | 38 ++++++++++-- .../view/model/GroupSendViewModelJvmTest.kt | 59 +++++++++++++++++++ 2 files changed, 92 insertions(+), 5 deletions(-) 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 9825401d..6168caa8 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,11 +20,16 @@ import com.machankura.bennu.compose.text.parseSats import com.machankura.bennu.compose.ui.view.state.GroupSendUIState import com.machankura.bennu.compose.wallet.GroupOnchainWallets import com.machankura.bennu.compose.wallet.GroupSpendBuilder +import com.machankura.bennu.compose.wallet.GroupWalletState import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.Chain import fr.acinq.bitcoin.Satoshi import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -89,11 +94,34 @@ class GroupSendViewModel( } } - val onchainWallet = wallets.walletFor(wallet.account) - watching?.cancel() - watching = viewModelScope.launch(Dispatchers.IO) { - onchainWallet.state.collect { state -> groupSendUIState = ready.copy(walletState = state) } - } + follow(ready, wallets.walletFor(wallet.account).state) + } + } + + /** + * Keeps [ready] current: the coins from [chainState], and which of them -- + * and which change addresses -- the room's open spends hold, re-read every + * time a spend is proposed, fails or settles. Read once, a spend another + * member proposed while this form was open would still look free, and + * sending everything would ask the group to sign a second spend of coins + * only one spend can have. + * + * 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. + */ + @OptIn(ExperimentalCoroutinesApi::class) + internal fun follow(ready: GroupSendUIState.Ready, chainState: Flow) { + val account = ready.wallet.account + val reservations = frostSigningRepository.observeGroupTransactions(chatRoomId).mapLatest { + frostSigningRepository.reservedOutPoints(chatRoomId) to + frostSigningRepository.reservedChangeIndices(chatRoomId, account) + } + watching?.cancel() + watching = viewModelScope.launch(Dispatchers.IO) { + combine(chainState, reservations) { state, (reserved, reservedChange) -> + ready.copy(walletState = state, reserved = reserved, reservedChange = reservedChange) + }.collect { groupSendUIState = it } } } 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 868502b9..a7656d60 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 @@ -4,6 +4,10 @@ import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.FrostSigningSession import com.machankura.bennu.compose.database.model.GroupSignedEvent +import com.machankura.bennu.compose.database.model.GroupTransaction +import kotlinx.coroutines.flow.Flow +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.nostr.wallet.GroupWallet @@ -171,6 +175,61 @@ class GroupSendViewModelJvmTest { assertIs(GroupSpend.check(built.psbt, mainnet)) } + /** The room's spends as the database would report them, and what they hold, set by the test. */ + private class Reserving : FrostSigningRepository by FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY { + val transactions = MutableStateFlow>(emptyList()) + @Volatile var heldCoins: Set = emptySet() + @Volatile var heldChange: 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 + } + + /** Two confirmed coins, 60,000 and 40,000 sats, on the first two receive addresses. */ + private val twoCoins: GroupWalletState = run { + val coins = listOf(60_000L, 40_000L).mapIndexed { index, sats -> + val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong()) + val tx = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { (index + 1).toByte() })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), 0) + val meta = WalletState.AddressMeta.Derived(index) + derived.address(Chain.Regtest) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(tx.txid, 0, 100, tx, meta))) + }.toMap() + walletState.copy(receive = WalletState(coins)) + } + + private fun eventually(read: () -> T?): T = + runBlocking { withTimeout(5_000) { var value = read(); while (value == null) { delay(10); value = read() }; value } } + + @Test + fun `a spend proposed while the form is open takes its coins out of what the form will send`() { + val signing = Reserving() + val ready = GroupSendUIState.Ready(localChatRoom, wallet, walletState = null, reserved = emptySet()) + val model = viewModel(ready, signing = signing) + model.follow(ready, flowOf(twoCoins)) + model.addressField.setTextAndPlaceCursorAtEnd("bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080") + model.feerateField.setTextAndPlaceCursorAtEnd("4") + model.sendEverything.value = true + + val before = eventually { model.preview() as? GroupSpendBuilder.Result.Built } + assertEquals(Satoshi(100_000), before.amount + before.fee, "both coins, before anybody holds one") + + // Another member's proposal arrives: it holds the 60,000 coin and change index 0. + val bigCoin = twoCoins.utxos.single { it.amount == Satoshi(60_000) }.utxo.outPoint + signing.heldCoins = setOf(bigCoin) + signing.heldChange = setOf(0L) + signing.transactions.value = listOf( + GroupTransaction(frostSigningSessionId = "theirs", chatRoomId = chatRoomId, chain = "regtest", account = 0, psbt = "", txid = "t".repeat(64)) + ) + + val following = eventually { (model.groupSendUIState as GroupSendUIState.Ready).takeIf { it.reserved.isNotEmpty() } } + assertEquals(setOf(bigCoin), following.reserved) + assertEquals(setOf(0L), following.reservedChange) + assertEquals(twoCoins, following.walletState, "the coins are kept while the reservations change") + + val after = assertIs(model.preview()) + assertEquals(Satoshi(40_000), after.amount + after.fee, "only the coin nobody holds, without the form being opened again") + assertEquals(Satoshi(40_000), model.spendable()) + } + @Test fun `send everything ignores the amount`() { val model = viewModel(GroupSendUIState.Ready(localChatRoom, wallet, walletState, reserved = emptySet()))