From cbe5330cac8da6a6d486dea32d7564791bee6cb6 Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 15:17:24 +0200 Subject: [PATCH] feat(wallet): a subgroup opens a guarded wallet, and spends from it as before (Phase 5) A room whose certificate grants guardian keys is offered a guarded wallet, with a plain one beside it, on test networks; mainnet waits behind GroupWalletRollout.GUARDIANS_ON_MAINNET. A spend's account is the one the statement opened, so its own spends sign the guarded addresses' key path, and wallets are watched per descriptor rather than per xpub. Co-Authored-By: Claude Opus 5.5 --- .../composeResources/values/strings.xml | 4 + .../repository/DatabaseChatRepository.kt | 7 ++ .../compose/managers/FrostSigningManager.kt | 6 +- .../compose/managers/GroupWalletManager.kt | 36 +++++++++ .../compose/repository/ChatRepository.kt | 13 ++++ .../ui/composable/GroupWalletScreen.kt | 55 ++++++++++++-- .../ui/view/model/GroupWalletViewModel.kt | 20 ++++- .../ui/view/state/GroupWalletUIState.kt | 6 ++ .../compose/wallet/GroupOnchainWallets.kt | 9 ++- .../compose/wallet/GroupWalletRollout.kt | 12 +++ .../managers/GroupSpendSigningJvmTest.kt | 74 +++++++++++++++++++ .../view/model/GroupWalletViewModelJvmTest.kt | 54 +++++++++++++- 12 files changed, 281 insertions(+), 15 deletions(-) diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml index 7dd87438..c1ac4a99 100644 --- a/composeApp/src/commonMain/composeResources/values/strings.xml +++ b/composeApp/src/commonMain/composeResources/values/strings.xml @@ -616,6 +616,10 @@ Opening a wallet asks the group to agree that it keeps coins here. Any quorum of members can then spend them together, and nobody can spend them alone. Each member's share of the group's key is stored unencrypted on their device. Anyone with an unlocked device, or a copy of its data, holds that member's share. Couldn't ask the group to open a wallet. + The groups above this one have agreed to guard its wallet. In a guarded wallet each of them can spend any coin once it has %1$d confirmations, without this group agreeing. + Open a guarded wallet + Open without guardians + Guarded: the groups above this one can spend any coin here once it has %1$d confirmations. Balance %1$s sats %1$s sats on the way diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt index 67f0128e..3db6572a 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt @@ -201,6 +201,13 @@ class DatabaseChatRepository( null } + override suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain): GroupWalletManager.GuardedOpening? = try { + GroupWalletManager.guardedAccountFor(database, chatRoomId, chain) + } catch (e: Throwable) { + logger.e("Error deriving the guarded wallet account of $chatRoomId", e) + null + } + override suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? = try { database.groupSignedEventDao().getById(id)?.takeIf { it.chatRoomId == chatRoomId } } catch (e: Throwable) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt index e469a04a..8771db08 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/FrostSigningManager.kt @@ -852,7 +852,11 @@ object FrostSigningManager { ): Pair? { val transaction = database.groupTransactionDao().getBySessionId(session.id) ?: return null val chain = GroupWalletStatementEvent.chainNamed(transaction.chain) ?: return null - return transaction to GroupWalletDerivation.account(thresholdPublicKey, chain, transaction.account) + // The account as the room's statement opened it: a guarded one's + // addresses carry its guardians' leaves, and the bare derivation would be + // a plain account at the same key, whose addresses none of these coins are at. + val opened = GroupWalletManager.walletFor(database, transaction.chatRoomId, thresholdPublicKey, chain, transaction.account) + return transaction to (opened?.account ?: GroupWalletDerivation.account(thresholdPublicKey, chain, transaction.account)) } /** diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt index 37c35462..7660df06 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupWalletManager.kt @@ -3,6 +3,8 @@ package com.machankura.bennu.compose.managers import com.machankura.bennu.compose.database.BennuDatabase import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent +import com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent +import com.vitorpamplona.quartz.nip01Core.core.Event import com.vitorpamplona.quartz.nip01Core.core.HexKey import fr.acinq.bitcoin.Chain @@ -35,6 +37,40 @@ object GroupWalletManager { ): GroupWalletDerivation.Account? = thresholdKeyFor(database, chatRoomId)?.let { GroupWalletDerivation.account(it, chain, account) } + /** A guarded account a room could open, and the certificate that granted its guardians, which the statement carries. */ + data class GuardedOpening( + val account: GroupWalletDerivation.Account, + val certificate: Event, + ) + + /** + * The guarded account [chatRoomId] would open on [chain], or null for a room + * whose certificate grants it no guardian keys -- a room nobody's subgroup, + * or one certified before certificates carried them. + * + * Off the verified key state, the one place a certificate this device + * believes is kept. A member who holds no key state cannot open one; that + * member cannot sign, either. + */ + suspend fun guardedAccountFor( + database: BennuDatabase, + chatRoomId: String, + chain: Chain, + account: Long = 0L, + ): GuardedOpening? { + val thresholdPublicKey = thresholdKeyFor(database, chatRoomId) ?: return null + val certificate = GroupKeyStateManager.keyStateFor(database, chatRoomId) + ?.takeIf { it.verifies() } + ?.birthCertificateJson + ?.let { Event.fromJsonOrNull(it) } + ?: return null + val guardians = SubgroupBirthCertificateEvent.parseGuardians(certificate.tags) + ?.takeIf { it.isNotEmpty() } + ?: return null + + return GuardedOpening(GroupWalletDerivation.account(thresholdPublicKey, chain, account, guardians), certificate) + } + /** * The wallet [chatRoomId] has opened on [chain] under [thresholdPublicKey], or * null when the room signed no statement that key rederives. diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt index 5e2d8aaa..1351e00d 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.repository import fr.acinq.bitcoin.Chain import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GroupWalletManager import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.database.model.ChatRoom import com.machankura.bennu.compose.database.model.GiftWrapPayload @@ -119,6 +120,13 @@ interface ChatRepository { */ suspend fun groupWalletAccount(chatRoomId: String, chain: Chain): GroupWalletDerivation.Account? + /** + * The guarded account this group could open on [chain] instead, and the + * certificate granting its guardians -- or null for a group whose birth + * certificate grants it none. + */ + suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain): GroupWalletManager.GuardedOpening? + /** * The kind:1s this group signed, newest first. * @@ -378,6 +386,11 @@ interface ChatRepository { chain: Chain ): GroupWalletDerivation.Account? = null + override suspend fun groupWalletGuardedOpening( + chatRoomId: String, + chain: Chain + ): GroupWalletManager.GuardedOpening? = null + override suspend fun groupPosts(chatRoomId: String): List = emptyList() override suspend fun groupSignedEvent( 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 fd1ea3d8..a2e00a82 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 @@ -36,6 +36,7 @@ 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.OutlinedButton import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon @@ -72,6 +73,11 @@ import bennu.composeapp.generated.resources.finding_the_group_s_coins import bennu.composeapp.generated.resources.group_wallet import bennu.composeapp.generated.resources.nothing_has_been_sent_to_this_wallet_yet import bennu.composeapp.generated.resources.open_a_group_wallet +import bennu.composeapp.generated.resources.open_a_guarded_wallet +import bennu.composeapp.generated.resources.open_without_guardians +import bennu.composeapp.generated.resources.the_groups_above_this_one_have_agreed_to_guard_it +import bennu.composeapp.generated.resources.guarded_the_groups_above_this_one_can_spend +import com.machankura.bennu.compose.managers.GuardianDerivation import bennu.composeapp.generated.resources.opening_a_wallet_asks_the_group_to_agree import bennu.composeapp.generated.resources.receive_address import bennu.composeapp.generated.resources.received @@ -205,8 +211,10 @@ fun GroupWalletScreen( { OpenWalletAction( isPending = groupWalletViewModel.isActionPending.value, - onOpen = { + guardedOffered = state.guarded != null, + onOpen = { guarded -> groupWalletViewModel.openWallet( + guarded = guarded, onSuccess = { sessionId -> // Onto the session: the wallet does // not exist until a quorum signs. @@ -275,7 +283,7 @@ fun GroupWalletScreen( * an unencrypted share on a member's device means once there are coins behind it. */ @Composable -private fun OpenWalletAction(isPending: Boolean, onOpen: () -> Unit) { +private fun OpenWalletAction(isPending: Boolean, guardedOffered: Boolean, onOpen: (guarded: Boolean) -> Unit) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap) @@ -289,10 +297,32 @@ private fun OpenWalletAction(isPending: Boolean, onOpen: () -> Unit) { style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, ) - Button(onClick = onOpen, enabled = !isPending) { - Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) - Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) - Text(stringResource(Res.string.open_a_group_wallet)) + if (guardedOffered) { + // The default for a subgroup whose parent agreed to guard it, and the + // plain wallet beside it rather than hidden: being guarded is the + // group's own choice, and its quorum signing the statement is it + // making that choice. + Text( + text = stringResource( + Res.string.the_groups_above_this_one_have_agreed_to_guard_it, + GuardianDerivation.ANCESTOR_DELAY.toInt() + ), + style = MaterialTheme.typography.bodyMedium, + ) + Button(onClick = { onOpen(true) }, enabled = !isPending) { + Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.open_a_guarded_wallet)) + } + OutlinedButton(onClick = { onOpen(false) }, enabled = !isPending) { + Text(stringResource(Res.string.open_without_guardians)) + } + } else { + Button(onClick = { onOpen(false) }, enabled = !isPending) { + Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) + Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap)) + Text(stringResource(Res.string.open_a_group_wallet)) + } } } } @@ -320,6 +350,19 @@ private fun OpenWallet( ) { item { BalanceCard(walletState) } + if (state.wallet.account.isGuarded) { + item { + Text( + text = stringResource( + Res.string.guarded_the_groups_above_this_one_can_spend, + GuardianDerivation.ANCESTOR_DELAY.toInt() + ), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + onSend?.let { send -> item { Button(onClick = send) { diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt index a2638dbd..7c09ed3f 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt @@ -6,6 +6,7 @@ import com.machankura.bennu.compose.ui.view.state.SpendStatus import com.machankura.bennu.compose.wallet.GroupSpend import com.machankura.bennu.compose.wallet.GroupSpendBuilder import com.machankura.bennu.compose.wallet.GroupTransactionWatcher +import com.machankura.bennu.compose.wallet.GroupWalletRollout import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flowOf import androidx.compose.runtime.MutableState @@ -76,6 +77,9 @@ class GroupWalletViewModel( localChatRoom = localChatRoom, account = chatRepository.groupWalletAccount(chatRoomId, chain), canSign = canSign, + guarded = if (GroupWalletRollout.offersGuardiansOn(chain)) { + chatRepository.groupWalletGuardedOpening(chatRoomId, chain) + } else null, ) return@launch } @@ -159,17 +163,25 @@ class GroupWalletViewModel( * Never batched with anything, for the reason `GroupWalletStatementEvent` * gives -- every spend is opened against this, and it should never be as * available as its worst co-passenger. + * + * [guarded] opens the guarded account the room's certificate grants instead + * of the plain one: the statement then names the guardians and carries the + * certificate, and the group's quorum signing it is the group agreeing to be + * guarded. */ - fun openWallet(onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { + fun openWallet(guarded: Boolean = false, onSuccess: (sessionId: String) -> Unit, onFailure: () -> Unit) { val state = groupWalletUIState as? GroupWalletUIState.NotOpened ?: return - val account = state.account ?: return + val template = if (guarded) { + val opening = state.guarded ?: return + GroupWalletStatementEvent.template(opening.account, opening.certificate) + } else { + GroupWalletStatementEvent.template(state.account ?: return) + } // A second statement for the same account is harmless -- the same values // under the same `d` tag -- but it is a second quorum asked for nothing. if (isActionPending.value) return isActionPending.value = true - val template = GroupWalletStatementEvent.template(account) - viewModelScope.launch(Dispatchers.IO) { val session = runCatching { frostSigningRepository.proposeSigning( diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt index 6fa85a52..d8379218 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletUIState.kt @@ -2,6 +2,7 @@ package com.machankura.bennu.compose.ui.view.state import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom import com.machankura.bennu.compose.managers.GroupWalletDerivation +import com.machankura.bennu.compose.managers.GroupWalletManager import com.machankura.bennu.compose.nostr.wallet.GroupWallet import com.machankura.bennu.compose.wallet.GroupWalletState import com.machankura.bennu.compose.wallet.GroupSpend @@ -16,11 +17,16 @@ sealed interface GroupWalletUIState { * at all -- there is nothing to open then. [canSign] gates the way in, for * the reason every proposing screen gives: `proposeSigning` throws for a * device holding no share. + * + * [guarded] is the guarded account a subgroup could open instead, when its + * birth certificate grants it guardian keys and guarded wallets are offered + * on this network -- see `docs/group-wallet-guardians.md`. */ data class NotOpened( val localChatRoom: LocalChatRoom, val account: GroupWalletDerivation.Account?, val canSign: Boolean, + val guarded: GroupWalletManager.GuardedOpening? = null, ): GroupWalletUIState /** diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt index e1347ffb..bad97e3b 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupOnchainWallets.kt @@ -24,9 +24,14 @@ class GroupOnchainWallets( private val mutex = Mutex() private val wallets = mutableMapOf() - /** The wallet watching [account], made the first time it is asked for. Keyed by xpub, which names one account of one group on one network. */ + /** + * The wallet watching [account], made the first time it is asked for. Keyed + * by its receive descriptor, which names one account of one group on one + * network *and* the guardians in its addresses -- an xpub alone would hand a + * guarded account the plain one's addresses. + */ suspend fun walletFor(account: GroupWalletDerivation.Account): GroupOnchainWallet = mutex.withLock { - wallets.getOrPut(account.xpub) { GroupOnchainWallet(account, electrum, scope) } + wallets.getOrPut(account.receiveDescriptor) { GroupOnchainWallet(account, electrum, scope) } } /** diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt index 94020bed..335946b8 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupWalletRollout.kt @@ -29,4 +29,16 @@ object GroupWalletRollout { val MAINNET_CAP: Satoshi = Satoshi(100_000) fun capFor(chain: Chain): Satoshi? = MAINNET_CAP.takeIf { chain.isMainnet() } + + /** + * Whether a subgroup is offered a guarded wallet on mainnet -- + * `docs/group-wallet-guardians.md`. Test networks are offered one from the + * start. Lifts when a guardian spend has been made on signet by a real + * three-level hierarchy, and every member of a mainnet group runs a build + * that reads guarded statements: an older client sees no wallet, and can open + * a plain one whose addresses the rest do not watch. + */ + const val GUARDIANS_ON_MAINNET: Boolean = false + + fun offersGuardiansOn(chain: Chain): Boolean = GUARDIANS_ON_MAINNET || !chain.isMainnet() } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt index 0edb4897..805632b8 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupSpendSigningJvmTest.kt @@ -452,4 +452,78 @@ class GroupSpendSigningJvmTest { val confirmedLine = lines.single { it.messageType == ChatMessage.TYPE_GROUP_TRANSACTION_CONFIRMED } assertEquals("The group's transaction confirmed: 30000 sats sent.", confirmedLine.content) } + + // ---- A guarded wallet ----------------------------------------------- + + /** + * Files the room's key state as a subgroup's, under a certificate granting + * one guardian -- signed by a parent whose key the test holds, since + * `certifies` asks only that the room it names as parent signed it. + */ + private suspend fun fileGuardedParentage(device: Device): GroupWalletManager.GuardedOpening { + val parentKey = PrivateKey(ByteVector32(ByteArray(32) { 0x0b })) + val parentRoomId = parentKey.publicKey().xOnly().value.toString() + val guardians = GuardianDerivation.grant( + PrivateKey(ByteVector32(ByteArray(32) { 0x0c })).publicKey().toString(), parentRoomId, emptyList(), roomId, + ) + val tags = com.machankura.bennu.compose.nostr.subgroup.SubgroupBirthCertificateEvent.assembleTags( + subgroupChatRoomId = roomId, parentChatRoomId = parentRoomId, thresholdPublicKey = thresholdPublicKey, + adminPublicKeys = members, name = "Treasury", guardians = guardians, + ) + val id = EventHasher.hashId(parentRoomId, 1_700_000_000, 30329, tags, roomId) + val certificate = Event(id, parentRoomId, 1_700_000_000, 30329, tags, roomId, + fr.acinq.bitcoin.Crypto.signSchnorr(ByteVector32(id), parentKey, null).toString()) + + device.db.groupKeyStateDao().upsert( + com.machankura.bennu.compose.database.model.GroupKeyState( + chatRoomId = roomId, dkgSessionId = ceremonyId, thresholdPublicKey = thresholdPublicKey, + derivationPath = SharedKeyDerivation.formatPath(), announcedBy = roomId, + announcedAt = Instant.fromEpochSeconds(1_700_000_000), + parentChatRoomId = parentRoomId, birthCertificateJson = certificate.toJson(), + ) + ) + return assertNotNull(GroupWalletManager.guardedAccountFor(device.db, roomId, chain)) + } + + @Test + fun `a guarded wallet is opened by its quorum, and its own spends stay on the key path`() = runBlocking { + val proposer = device(members[0], signerIndex = 0) + val other = device(members[1], signerIndex = 1) + val opening = fileGuardedParentage(proposer) + fileGuardedParentage(other) + + val template = GroupWalletStatementEvent.template(opening.account, opening.certificate) + val statement = FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content) + pump(proposer, other) + FrostSigningManager.approve(other.db, other.room, statement.id) + pump(proposer, other) + + val guarded = assertNotNull(GroupWalletManager.walletFor(other.db, roomId, chain)).account + assertTrue(guarded.isGuarded) + assertEquals(opening.account, guarded) + + val first = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.RECEIVE, 0) + val change = GroupWalletDerivation.derive(guarded, GroupWalletDerivation.CHANGE, 0) + val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x47 })), 0), ByteVector.empty, 0xffffffffL)), + listOf(TxOut(Satoshi(60_000), first.pubkeyScript)), 0) + val tx = Transaction(2, listOf(TxIn(OutPoint(funding, 0), ByteVector.empty, 0xfffffffdL)), + listOf(TxOut(Satoshi(40_000), elsewhere), TxOut(Satoshi(19_000), change.pubkeyScript)), 0) + val psbt = GroupSpend.psbtOf(tx, listOf(funding.txOut[0] to first), mapOf(1 to change), guarded) + + // The plain account's check refuses the guarded coin: same internal key, another output. + assertIs(GroupSpend.check(psbt, account)) + + val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, psbt, chain) + pump(proposer, other) + assertEquals(listOf(false, true), assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id)).outputs.map { it.isChange }) + FrostSigningManager.approve(other.db, other.room, session.id) + pump(proposer, other) + + listOf(proposer, other).forEach { device -> + assertEquals(FrostSigningStage.COMPLETE, device.session(session.id)?.stage) + val signed = Transaction.read(assertNotNull(device.transaction(session.id)?.signedTransaction)) + signed.correctlySpends(mapOf(OutPoint(funding, 0) to funding.txOut[0]), ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) + assertEquals(1, signed.txIn[0].witness.stack.size, "a key-path spend: one signature, no script, no control block") + } + } } diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt index cd416648..a5526afd 100644 --- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt @@ -106,11 +106,11 @@ class GroupWalletViewModelJvmTest { } } - private fun viewModel(chat: ChatRepository, signing: FrostSigningRepository = RecordingSigning()) = + private fun viewModel(chat: ChatRepository, signing: FrostSigningRepository = RecordingSigning(), chain: Chain = Chain.Mainnet) = GroupWalletViewModel( activeUserPublicKey = me, chatRoomId = chatRoomId, - chain = Chain.Mainnet, + chain = chain, initialGroupWalletUIState = GroupWalletUIState.Loading, chatRepository = chat, frostSigningRepository = signing, @@ -169,6 +169,56 @@ class GroupWalletViewModelJvmTest { runBlocking { withTimeout(5_000) { while (!failed) delay(10) } } } + // ---- a guarded wallet --------------------------------------------------- + + /** What the repository would hand a subgroup whose certificate grants it guardians; the checks behind it are `GroupWalletStatementEventTest`'s. */ + private val certificate = com.vitorpamplona.quartz.nip01Core.core.Event( + "c".repeat(64), "b".repeat(64), 1_700_000_000, 30329, emptyArray(), chatRoomId, "f".repeat(128) + ) + private val guardians = com.machankura.bennu.compose.managers.GuardianDerivation.grant( + PrivateKey(ByteVector32(Hex.decode("9a4e47".padStart(64, '0')))).publicKey().toString(), + "b".repeat(64), emptyList(), chatRoomId, + ) + + private fun guardedRepository(chain: Chain) = object : ChatRepository by repository(opened = null) { + override suspend fun groupWalletGuardedOpening(chatRoomId: String, chain: Chain) = + com.machankura.bennu.compose.managers.GroupWalletManager.GuardedOpening( + GroupWalletDerivation.account( + PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(), + chain, guardians = guardians, + ), + certificate, + ) + } + + @Test + fun `a subgroup is offered a guarded wallet on a test network, and not yet on mainnet`() { + val regtest = assertIs( + viewModel(guardedRepository(Chain.Regtest), chain = Chain.Regtest).apply { initiate() }.settled() + ) + assertEquals(guardians, regtest.guarded?.account?.guardians) + + val mainnet = assertIs( + viewModel(guardedRepository(Chain.Mainnet)).apply { initiate() }.settled() + ) + assertNull(mainnet.guarded, "behind GroupWalletRollout.GUARDIANS_ON_MAINNET") + } + + @Test + fun `opening a guarded wallet proposes a statement naming the guardians and carrying the certificate`() { + val signing = RecordingSigning() + val model = viewModel(guardedRepository(Chain.Regtest), signing, chain = Chain.Regtest).apply { initiate() } + model.settled() + + model.openWallet(guarded = true, onSuccess = {}, onFailure = {}) + runBlocking { withTimeout(5_000) { while (signing.proposed == null || model.isActionPending.value) delay(10) } } + + val (_, tags, content) = assertNotNull(signing.proposed) + val reading = assertNotNull(GroupWalletStatementEvent.read(tags, content)) + assertEquals(guardians, reading.guardians) + assertEquals(certificate.id, reading.certificate?.id) + } + // ---- spends ------------------------------------------------------------ private val coinTx = fr.acinq.bitcoin.Transaction(