diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index 94d160e6..f5e2ad0a 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -473,6 +473,14 @@
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
+ Fund %1$s's guarded wallet
+ %1$s sats arriving
+ To
+ %1$s's guarded wallet
+ 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 +533,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/database/repository/DatabaseFrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt
index 1308606a..d31bd046 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseFrostSigningRepository.kt
@@ -186,6 +186,13 @@ class DatabaseFrostSigningRepository(
emptySet()
}
+ override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = try {
+ FrostSigningManager.reservedFundingIndices(database, chatRoomId, account)
+ } catch (e: Throwable) {
+ logger.e("Error reading the funding addresses reserved in $chatRoomId", e)
+ emptySet()
+ }
+
override fun observeGroupTransactions(chatRoomId: String): Flow> =
database.groupTransactionDao().observeByChatRoomId(chatRoomId)
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 6b9b8be7..59eeffd6 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
@@ -692,7 +692,7 @@ object FrostSigningManager {
val wallet = GroupWalletManager.walletFor(database, chatRoomId, thresholdPublicKey, chain, account)
?: throw IllegalStateException("This group has not opened a wallet on ${GroupWalletStatementEvent.chainName(chain)}")
- val checked = when (val result = GroupSpend.check(psbt, wallet.account)) {
+ val checked = when (val result = GroupSpend.check(psbt, wallet.account).withFundings(database, chatRoomId)) {
is GroupSpend.Result.Ok -> result.checked
is GroupSpend.Result.Refused -> throw IllegalArgumentException("This spend ${result.reason}")
}
@@ -770,7 +770,7 @@ object FrostSigningManager {
val guarded = GuardianManager.guardedWalletFor(database, chatRoomId, descendantChatRoomId, chain, account)
?: throw IllegalStateException("This group guards no wallet of $descendantChatRoomId on ${GroupWalletStatementEvent.chainName(chain)}")
- val checked = when (val result = GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey))) {
+ val checked = when (val result = GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey)).withFundings(database, chatRoomId)) {
is GroupSpend.Result.Ok -> result.checked
is GroupSpend.Result.Refused -> throw IllegalArgumentException("This spend ${result.reason}")
}
@@ -900,7 +900,7 @@ object FrostSigningManager {
guarded.account to guarded.spender(thresholdPublicKey)
}
- val checked = when (val result = GroupSpend.check(psbt, walletAccount, spender)) {
+ val checked = when (val result = GroupSpend.check(psbt, walletAccount, spender).withFundings(database, localChatRoom.chatRoom.id)) {
is GroupSpend.Result.Ok -> result.checked
is GroupSpend.Result.Refused -> {
logger.w("Spend proposal $sessionId ${result.reason}; dropping")
@@ -1072,7 +1072,26 @@ object FrostSigningManager {
?: return null
val context = spendContext(database, session, thresholdPublicKey) ?: return null
val psbt = GroupSpend.decode(context.transaction.psbt) ?: return null
- return (GroupSpend.check(psbt, context.account, context.spender) as? GroupSpend.Result.Ok)?.checked
+ return (GroupSpend.check(psbt, context.account, context.spender).withFundings(database, context.transaction.chatRoomId) as? GroupSpend.Result.Ok)?.checked
+ }
+
+ /**
+ * A checked spend with its payments into descendants' guarded wallets read
+ * against the ones [chatRoomId] holds -- `GroupSpend.fundingsOf` -- or
+ * refused for a claim that does not derive. Every place a spend is checked
+ * for a member to read or sign reads its fundings here, so the label a
+ * signer sees is the one every other signer's device derived too.
+ *
+ * A spend none of whose payments claims anything -- every spend to a typed
+ * address -- reads no guarded wallets at all.
+ */
+ private suspend fun GroupSpend.Result.withFundings(database: BennuDatabase, chatRoomId: String): GroupSpend.Result {
+ val checked = (this as? GroupSpend.Result.Ok)?.checked ?: return this
+ if (checked.payments.all { checked.psbt.outputs[it.index].taprootDerivationPaths.isEmpty() }) return this
+ return when (val reading = GroupSpend.fundingsOf(checked, GuardianManager.guardedWalletsOf(database, chatRoomId))) {
+ is GroupSpend.FundingReading.Ok -> GroupSpend.Result.Ok(checked.copy(fundings = reading.fundings))
+ is GroupSpend.FundingReading.Refused -> GroupSpend.Result.Refused(reading.reason)
+ }
}
/**
@@ -1101,6 +1120,21 @@ object FrostSigningManager {
.flatMap { GroupSpend.claimedChangeIndices(it, account) }
.toSet()
+ /**
+ * The receive addresses of [account] -- a descendant's guarded wallet -- that
+ * a room's open spends fund, which a new funding should not pay as well.
+ * Held by the same sessions as [reservedOutPoints], for the reason
+ * [reservedChangeIndices] gives.
+ */
+ suspend fun reservedFundingIndices(
+ database: BennuDatabase,
+ chatRoomId: String,
+ account: GroupWalletDerivation.Account,
+ ): Set =
+ openSpends(database, chatRoomId)
+ .flatMap { GroupSpend.claimedFundingIndices(it, account) }
+ .toSet()
+
/** The PSBT of every spend in the room whose session has not failed. */
private suspend fun openSpends(database: BennuDatabase, chatRoomId: String): List =
database.groupTransactionDao().getByChatRoomId(chatRoomId)
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt
index 6c7bcdd9..846c48b3 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/FrostSigningRepository.kt
@@ -263,6 +263,9 @@ interface FrostSigningRepository {
/** The change indices under [account] the room's open spends already pay back to. */
suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set
+ /** The receive indices of [account], a descendant's guarded wallet, the room's open spends already fund. */
+ suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set
+
/** Every spend the room has proposed, newest first, as it moves from proposed to confirmed. */
fun observeGroupTransactions(chatRoomId: String): Flow>
@@ -352,6 +355,7 @@ interface FrostSigningRepository {
override suspend fun reservedOutPoints(chatRoomId: String): Set = emptySet()
override suspend fun reservedChangeIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = emptySet()
+ override suspend fun reservedFundingIndices(chatRoomId: String, account: GroupWalletDerivation.Account): Set = emptySet()
override fun observeGroupTransactions(chatRoomId: String): Flow> = flowOf(emptyList())
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt
index a95f079b..180fa4b6 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/text/ProposedSpend.kt
@@ -4,6 +4,7 @@ import com.machankura.bennu.compose.wallet.GroupSpend
import fr.acinq.bitcoin.Bitcoin
import fr.acinq.bitcoin.ByteVector
import fr.acinq.bitcoin.Chain
+import fr.acinq.bitcoin.Satoshi
/**
* A spend the group is being asked to sign, said in words -- [ProposedEvent]'s
@@ -15,16 +16,29 @@ object ProposedSpend {
ProposedEvent.Summary(
// A guardian's spend takes a descendant's coins, so whose they are
// is the first thing a signer reads.
+ // A funding comes next: where the money goes, as every signer's
+ // device derived it -- never the proposer's word for it.
label = when (val guardian = spend.spender as? GroupSpend.Spender.Guardian) {
- null -> "Spend from the group's wallet"
+ null -> spend.fundings.singleOrNull()?.takeIf { spend.payments.size == 1 }
+ ?.let { "Fund ${nameOf(it)}'s guarded wallet" }
+ ?: "Spend from the group's wallet"
else -> "Spend from ${guardian.name ?: "a subgroup"}'s guarded wallet"
},
detail = when (val payment = spend.payments.singleOrNull()) {
- null -> "Send ${spend.amountSent.grouped()} sats to ${spend.payments.size} addresses"
- else -> "Send ${payment.txOut.amount.grouped()} sats to ${addressOf(payment.txOut.publicKeyScript, chain)}"
+ null -> "Send ${spend.amountSent.grouped()} sats to ${spend.payments.size} addresses" + when (val funding = spend.fundings.singleOrNull()) {
+ null -> if (spend.fundings.isEmpty()) "" else
+ ", ${Satoshi(spend.fundings.sumOf { spend.tx.txOut[it.outputIndex].amount.sat }).grouped()} of them to ${spend.fundings.size} guarded wallets"
+ else -> ", ${spend.tx.txOut[funding.outputIndex].amount.grouped()} of them to ${nameOf(funding)}'s guarded wallet"
+ }
+ else -> when (val funding = spend.fundings.singleOrNull()) {
+ null -> "Send ${payment.txOut.amount.grouped()} sats to ${addressOf(payment.txOut.publicKeyScript, chain)}"
+ else -> "Send ${payment.txOut.amount.grouped()} sats to ${nameOf(funding)}'s guarded wallet, address ${funding.derived.index}"
+ }
}
)
+ private fun nameOf(funding: GroupSpend.Funding): String = funding.wallet.displayName ?: "a subgroup"
+
/** The address [script] pays, or the script itself where it has no address. */
fun addressOf(script: ByteVector, chain: Chain): String =
Bitcoin.addressFromPublicKeyScript(chain.chainHash, script.toByteArray()).right ?: script.toHex()
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 3fb5489c..723e1b44 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
@@ -8,6 +8,18 @@ import bennu.composeapp.generated.resources.s_sats_come_back_to_this_wallet_as_c
import bennu.composeapp.generated.resources.this_wallet_has_nothing_confirmed_to_spend
import bennu.composeapp.generated.resources.this_wallet_doesn_t_have_that_much_confirmed
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.s_s_guarded_wallet
+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
@@ -119,6 +131,7 @@ fun GroupSendScreen(
frostSigningRepository: FrostSigningRepository,
wallets: GroupOnchainWallets?,
guardedChatRoomId: String? = null,
+ fundChatRoomId: String? = null,
onNavigateToRouteAndPopUpInclusive: (Route) -> Unit,
onNavigateBack: () -> Unit,
) {
@@ -132,6 +145,7 @@ fun GroupSendScreen(
frostSigningRepository = frostSigningRepository,
wallets = wallets,
guardedChatRoomId = guardedChatRoomId,
+ fundChatRoomId = fundChatRoomId,
)
)
@@ -148,11 +162,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.displayName ?: stringResource(Res.string.a_subgroup))
+ else -> stringResource(Res.string.send_from_the_group_s_wallet)
+ },
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
@@ -185,6 +205,9 @@ fun GroupSendScreen(
) {
val preview = groupSendViewModel.preview()
+ // A funding's destination is fixed, not typed: the title names
+ // the wallet, and an address field could make it pay another.
+ // A funded wallet's address not known yet is said on its card.
SpendForm(
addressField = groupSendViewModel.addressField,
amountField = groupSendViewModel.amountField,
@@ -196,6 +219,9 @@ fun GroupSendScreen(
amountProblem = preview?.takeIf { groupSendViewModel.isAboutTheAmount(it) },
coinsKnown = state.walletState != null,
chain = chain,
+ destination = state.funding?.let { funding -> { FundingDestination(funding) } },
+ fundedName = state.funding?.wallet?.let { it.displayName ?: stringResource(Res.string.a_subgroup) },
+ waitingOnFunding = state.funding != null && state.funding.address == null,
)
Text(
@@ -241,7 +267,9 @@ fun GroupSendScreen(
* its quorum, a member signs alone.
*
* [ownWallet] is a member spending their own guarded wallet, which changes the
- * words -- "your coins", "this wallet" -- and nothing else.
+ * words -- "your coins", "this wallet" -- and nothing else. [destination], when
+ * there is one, takes the address field's place: a funding pays a wallet the
+ * form names rather than an address somebody types.
*/
@Composable
internal fun SpendForm(
@@ -258,10 +286,15 @@ internal fun SpendForm(
coinsKnown: Boolean,
chain: Chain,
ownWallet: Boolean = false,
+ destination: (@Composable () -> Unit)? = null,
+ /** The wallet a funding pays, as the preview names it. */
+ fundedName: String? = null,
+ /** A funding whose address is not known yet: its card says so, and there is no preview to show. */
+ waitingOnFunding: Boolean = false,
) {
// No column of its own: the fields go into the caller's, under its spacing,
// exactly as they did before the form was shared.
- OutlinedTextField(
+ destination?.invoke() ?: OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
state = addressField,
lineLimits = TextFieldLineLimits.SingleLine,
@@ -319,18 +352,70 @@ internal fun SpendForm(
// Still finding change is still finding coins: neither is anything to correct.
if (!coinsKnown || preview == GroupSpendBuilder.Result.FindingChange) {
LoadingDataIndicator(fillScreen = false, text = stringResource(if (ownWallet) Res.string.finding_your_coins else Res.string.finding_the_group_s_coins))
- } else if (amountProblem == null) {
- preview?.let { SendPreview(it, chain, ownWallet) }
+ } else if (amountProblem == null && !waitingOnFunding) {
+ preview?.let { SendPreview(it, chain, ownWallet, fundedName) }
}
}
-/** 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, ownWallet: Boolean) {
+private fun FundingDestination(funding: FundingTarget) {
+ val name = funding.wallet.displayName ?: 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.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, ownWallet: Boolean, 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/GroupWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletScreen.kt
index cfc52221..2508f264 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
@@ -4,6 +4,14 @@ import bennu.composeapp.generated.resources.the_group_above_decided_this_wallet_
import bennu.composeapp.generated.resources.the_group_above_decided_this_wallet_is_guarded
import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading
import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.material3.OutlinedCard
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import bennu.composeapp.generated.resources.fund
+import bennu.composeapp.generated.resources.fund_s_s_guarded_wallet
+import bennu.composeapp.generated.resources.s_sats_arriving
+import bennu.composeapp.generated.resources.spend_from_s_s_guarded_wallet
import androidx.compose.foundation.layout.Row
import com.machankura.bennu.compose.text.ProposedSpend
import com.machankura.bennu.compose.ui.view.state.SpendRow
@@ -198,6 +206,18 @@ fun GroupWalletScreen(
)
)
}
+ // Behind the room's own send's gates, since a funding is one: a share to
+ // propose with, and a node to see this group's coins with.
+ val toGuardianFund = { row: GuardedWalletRow ->
+ onNavigateToRoute(
+ GroupSendRoute(
+ activeUserPublicKey = activeUserPublicKey,
+ chatRoomId = chatRoomId,
+ relayHint = null,
+ fundChatRoomId = row.wallet.descendantChatRoomId,
+ )
+ )
+ }
val onShare = { shareable: GuardianManager.Shareable ->
groupWalletViewModel.share(shareable, onShared = { notify(shared) }, onFailure = { notify(couldNotShare) })
}
@@ -298,6 +318,8 @@ fun GroupWalletScreen(
isPending = groupWalletViewModel.isActionPending.value,
onShare = onShare,
onSpend = if (state.canSign && wallets != null) toGuardianSpend else null,
+ // A group with no wallet of its own has nothing to fund with.
+ onFund = null,
)
}
}
@@ -341,6 +363,7 @@ fun GroupWalletScreen(
isPending = groupWalletViewModel.isActionPending.value,
onShare = onShare,
onSpend = if (state.canSign && state.canWatch) toGuardianSpend else null,
+ onFund = if (state.canSign && state.canWatch) toGuardianFund else null,
)
}
}
@@ -441,6 +464,7 @@ private fun OpenWallet(
isPending: Boolean,
onShare: (GuardianManager.Shareable) -> Unit,
onSpend: ((GuardedWalletRow) -> Unit)?,
+ onFund: ((GuardedWalletRow) -> Unit)?,
) {
val clipboardManager = LocalClipboardManager.current
val addressCopied = stringResource(Res.string.address_copied)
@@ -606,6 +630,7 @@ private fun OpenWallet(
isPending = isPending,
onShare = onShare,
onSpend = onSpend,
+ onFund = onFund,
)
}
}
@@ -663,6 +688,7 @@ private fun LazyListScope.guardianItems(
isPending: Boolean,
onShare: (GuardianManager.Shareable) -> Unit,
onSpend: ((GuardedWalletRow) -> Unit)?,
+ onFund: ((GuardedWalletRow) -> Unit)?,
) {
if (guardedWallets.isNotEmpty()) {
item {
@@ -676,24 +702,7 @@ private fun LazyListScope.guardianItems(
)
}
items(guardedWallets, key = { "guarded-" + it.wallet.statement.id }) { row ->
- ListItem(
- leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) },
- headlineContent = { Text(guardedName(row.wallet.subject), maxLines = 1, overflow = TextOverflow.Ellipsis) },
- supportingContent = {
- val reach = row.withinReach?.let { stringResource(Res.string.s_sats_within_this_group_s_reach, it.grouped()) }
- ?: stringResource(Res.string.balance_not_known_yet)
- // A member's label says which of their wallets it is.
- val label = (row.wallet.subject as? GuardianManager.GuardedSubject.Member)?.label
- Text(label?.let { stringResource(Res.string.s_dot_s, it, reach) } ?: reach)
- },
- trailingContent = onSpend?.let { spend ->
- {
- TextButton(onClick = { spend(row) }) {
- Text(stringResource(Res.string.spend))
- }
- }
- },
- )
+ GuardedWalletCard(row = row, onSpend = onSpend, onFund = onFund)
}
}
@@ -723,6 +732,67 @@ private fun LazyListScope.guardianItems(
}
}
+/**
+ * One descendant's guarded wallet: its name and what is within reach, and under
+ * them the actions, in the card's own row rather than the list item's trailing
+ * slot. Two buttons there would leave the name -- the one thing that says which
+ * wallet this is -- a few characters at large text sizes, and a flow row wraps
+ * them instead. Each button names its wallet, since a screen reader hears every
+ * row's *Fund* and *Spend* alike. See `docs/guarded-wallet-funding.md`, Phase 5.
+ */
+@Composable
+private fun GuardedWalletCard(
+ row: GuardedWalletRow,
+ onSpend: ((GuardedWalletRow) -> Unit)?,
+ onFund: ((GuardedWalletRow) -> Unit)?,
+) {
+ val name = guardedName(row.wallet.subject)
+ OutlinedCard(modifier = Modifier.fillMaxWidth()) {
+ ListItem(
+ leadingContent = { Icon(Icons.Default.AccountBalanceWallet, contentDescription = Decorative) },
+ // Two lines, since the name is what says which wallet the buttons act on.
+ headlineContent = { Text(name, maxLines = 2, overflow = TextOverflow.Ellipsis) },
+ supportingContent = {
+ val reach = row.withinReach?.let { stringResource(Res.string.s_sats_within_this_group_s_reach, it.grouped()) }
+ val arriving = row.arriving?.takeIf { it.sat > 0 }?.let { stringResource(Res.string.s_sats_arriving, it.grouped()) }
+ val amounts = when {
+ reach == null -> stringResource(Res.string.balance_not_known_yet)
+ arriving == null -> reach
+ else -> stringResource(Res.string.s_dot_s, reach, arriving)
+ }
+ // A member's label says which of their wallets it is.
+ val label = (row.wallet.subject as? GuardianManager.GuardedSubject.Member)?.label
+ Text(label?.let { stringResource(Res.string.s_dot_s, it, amounts) } ?: amounts)
+ },
+ )
+ if (onFund != null || onSpend != null) {
+ val fundLabel = stringResource(Res.string.fund_s_s_guarded_wallet, name)
+ val spendLabel = stringResource(Res.string.spend_from_s_s_guarded_wallet, name)
+ FlowRow(
+ modifier = Modifier.fillMaxWidth().padding(
+ start = MaterialTheme.spacing.containerPadding,
+ end = MaterialTheme.spacing.containerPadding,
+ bottom = MaterialTheme.spacing.compactPadding,
+ ),
+ horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.targetGap, Alignment.End),
+ ) {
+ // Money in before money out, at equal weight: neither is the one
+ // every member wants, and a filled button would say it was.
+ onFund?.let { fund ->
+ TextButton(onClick = { fund(row) }, modifier = Modifier.semantics { contentDescription = fundLabel }) {
+ Text(stringResource(Res.string.fund))
+ }
+ }
+ onSpend?.let { spend ->
+ TextButton(onClick = { spend(row) }, modifier = Modifier.semantics { contentDescription = spendLabel }) {
+ Text(stringResource(Res.string.spend))
+ }
+ }
+ }
+ }
+ }
+}
+
/**
* A guarded wallet as an ancestor's list names it: a subgroup by the name its
* parent certified -- `#Translation` -- and a member by their profile's name --
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 c7f3168c..9825b82a 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
@@ -1231,6 +1231,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/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 baf38de0..1ed598cf 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
@@ -88,6 +88,18 @@ data class GuardedWalletRow(
get() = walletState?.let { state ->
state.utxos.filter { state.confirmations(it) >= GuardianDerivation.ANCESTOR_DELAY }.map { it.amount }.sum()
}
+
+ /**
+ * Coins in the wallet not yet within reach: in the mempool, or confirmed
+ * less deeply than the leaf's lock. What a funding looks like for the two
+ * hours after it lands -- without it, [withinReach] would make the money
+ * look gone. Every such coin, whoever paid it, which is all this group can
+ * know. Null while the chain is not known.
+ */
+ val arriving: Satoshi?
+ get() = walletState?.let { state ->
+ state.utxos.filter { state.confirmations(it) < GuardianDerivation.ANCESTOR_DELAY }.map { it.amount }.sum()
+ }
}
/** Where one of the room's spends has got to, as one fact a member reads. */
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 6b51bf65..b7294d5e 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
@@ -230,6 +230,35 @@ data class GroupWalletState(
}
}
+ /**
+ * The receive address an ancestor pays when it funds this wallet: the lowest
+ * unused index from [GroupOnchainWallet.ADDRESSES_AHEAD] past the current one
+ * that [reserved] -- the indices open fundings already pay -- does not hold,
+ * and that the wallet watches. Null before Electrum has answered, for the
+ * reason [receiveAddress] is, and when every such index is held.
+ *
+ * Not the current address: the wallet's own members are handing that one
+ * out, and every device computes the same one. Starting at the top of the
+ * address list's window and going up keeps an ancestor out of their way.
+ * See `docs/guarded-wallet-funding.md`, D2.
+ */
+ fun fundingAddress(reserved: Set = emptySet()): GroupAddress? {
+ val current = receive.firstUnusedDerivedAddress?.second?.index ?: return null
+ val window = (current + GroupOnchainWallet.ADDRESSES_AHEAD) until (current + GroupOnchainWallet.RECEIVE_LOOKAHEAD.toInt())
+ val (address, index) = receive.addresses.entries
+ .filterNot { it.value.alreadyUsed }
+ .mapNotNull { (address, addressState) -> addressState.meta.indexOrNull?.let { address to it } }
+ .filter { (_, index) -> index in window && index.toLong() !in reserved }
+ .minByOrNull { (_, index) -> index }
+ ?: return null
+ return GroupAddress(
+ derivation = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong()),
+ address = address,
+ status = GroupAddress.Status.NEXT,
+ balance = Satoshi(0),
+ )
+ }
+
/** 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/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt
index 22204027..871bf960 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpend.kt
@@ -2,6 +2,7 @@ package com.machankura.bennu.compose.wallet
import com.machankura.bennu.compose.managers.FrostSigningManager
import com.machankura.bennu.compose.managers.GroupWalletDerivation
+import com.machankura.bennu.compose.managers.GuardianManager
import com.machankura.bennu.compose.managers.GuardianDerivation
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import fr.acinq.bitcoin.ByteVector
@@ -149,6 +150,12 @@ object GroupSpend {
*/
val weight: Int,
val spender: Spender = Spender.Owner,
+ /**
+ * The payments that fund a descendant's guarded wallet, each claim derived
+ * again -- [fundingsOf]. Empty until a caller holding the room's guarded
+ * wallets has read them, which [check] alone cannot.
+ */
+ val fundings: List = emptyList(),
) {
val tx: Transaction get() = psbt.global.tx
@@ -173,6 +180,59 @@ object GroupSpend {
data class Refused(val reason: String) : Result
}
+ /** A payment into a descendant's guarded wallet, at [derived] under its account -- the claim, derived again. */
+ data class Funding(
+ val outputIndex: Int,
+ val wallet: GuardianManager.GuardedWallet,
+ val derived: GroupWalletDerivation.Derived,
+ )
+
+ sealed interface FundingReading {
+ data class Ok(val fundings: List) : FundingReading
+ data class Refused(val reason: String) : FundingReading
+ }
+
+ /**
+ * Which of [checked]'s payments fund one of [guarded] -- the descendants'
+ * guarded wallets the room holds -- read off each payment's derivation and
+ * derived again, the way change is. `docs/guarded-wallet-funding.md`, D4:
+ *
+ * - a claim under a wallet in [guarded] that derives to the payment's script
+ * is a funding;
+ * - a claim under a wallet in [guarded] that does not -- another index,
+ * another branch, another key -- refuses the spend, so no proposer can put
+ * a descendant's name on a payment to an address it does not own;
+ * - a claim under any other account is not this device's to check, and the
+ * payment is read as the bare address it is.
+ *
+ * Fingerprints are four bytes, so every held wallet sharing one is tried
+ * before a claim is refused.
+ */
+ fun fundingsOf(checked: Checked, guarded: List): FundingReading {
+ val fundings = checked.payments.mapNotNull { payment ->
+ val paths = checked.psbt.outputs[payment.index].taprootDerivationPaths
+ val (internalKey, path, candidates) = paths.entries.firstNotNullOfOrNull { (internalKey, path) ->
+ guarded.filter { it.chain == checked.account.chain && isOurs(path, it.account) }
+ .takeIf { it.isNotEmpty() }
+ ?.let { Triple(internalKey, path, it) }
+ } ?: return@mapNotNull null
+
+ val (branch, index) = path.keyPath.path.takeIf { it.size == 2 && path.leaves.isEmpty() }
+ ?: return FundingReading.Refused("output ${payment.index} claims a place in a guarded wallet that is not one")
+ if (branch != GroupWalletDerivation.RECEIVE || index !in 0L..MAX_ADDRESS_INDEX) {
+ return FundingReading.Refused("output ${payment.index} claims $branch/$index, which is not a receive address")
+ }
+ candidates.firstNotNullOfOrNull { wallet ->
+ GroupWalletDerivation.derive(wallet.account, branch, index)
+ .takeIf { it.pubkeyScript == payment.txOut.publicKeyScript && it.internalKey == internalKey }
+ ?.let { Funding(payment.index, wallet, it) }
+ } ?: return FundingReading.Refused(
+ "output ${payment.index} claims $branch/$index of ${candidates.first().displayName ?: "a subgroup"}'s guarded wallet, which is not where it pays"
+ )
+ }
+ return FundingReading.Ok(fundings)
+ }
+
/**
* The checks a member makes before signing, in the order `docs/group-chain-wallet.md`
* numbers them, against [account] -- which comes from the room's verified
@@ -298,6 +358,19 @@ object GroupSpend {
.mapNotNull { path -> path.keyPath.path.takeIf { it.size == 2 && it[0] == GroupWalletDerivation.CHANGE }?.get(1) }
.toSet()
+ /**
+ * The receive indices under [account] -- a descendant's guarded wallet --
+ * that [psbt]'s outputs claim to fund: what an open funding holds, so the
+ * next one pays a different address. Claims, as [claimedChangeIndices] are,
+ * for the same reason. See `docs/guarded-wallet-funding.md`.
+ */
+ fun claimedFundingIndices(psbt: Psbt, account: GroupWalletDerivation.Account): Set =
+ psbt.outputs
+ .flatMap { it.taprootDerivationPaths.values }
+ .filter { isOurs(it, account) }
+ .mapNotNull { path -> path.keyPath.path.takeIf { it.size == 2 && it[0] == GroupWalletDerivation.RECEIVE }?.get(1) }
+ .toSet()
+
/**
* The one derivation under [account] a PSBT field names, or null when it names
* none, several, or one this wallet will not walk.
@@ -336,12 +409,18 @@ object GroupSpend {
* The PSBT a proposer sends: [tx] with every input's spent output and
* derivation, and every change output's derivation, so that a signer is
* *told* what is change -- and [check] is how they decide whether to believe it.
+ *
+ * A [funding] output -- one paying a descendant's guarded wallet -- carries
+ * its derivation the same way, under the descendant's account rather than
+ * this one, so it is never mistaken for change and a signer holding that
+ * wallet can derive it again. See `docs/guarded-wallet-funding.md`.
*/
fun psbtOf(
tx: Transaction,
spent: List>,
change: Map,
account: GroupWalletDerivation.Account,
+ funding: Map> = emptyMap(),
): Psbt {
require(spent.size == tx.txIn.size) { "one spent output per input" }
@@ -354,11 +433,13 @@ object GroupSpend {
).right ?: throw IllegalArgumentException("could not describe input $index")
}
- return change.entries.fold(withInputs) { psbt, (index, derivation) ->
+ val outputs = change.mapValues { (_, derivation) -> account to derivation } + funding
+ return outputs.entries.fold(withInputs) { psbt, (index, claim) ->
+ val (owner, derivation) = claim
psbt.updateWitnessOutput(
outputIndex = index,
taprootInternalKey = derivation.internalKey,
- taprootDerivationPaths = mapOf(derivation.internalKey to pathOf(derivation, account)),
+ taprootDerivationPaths = mapOf(derivation.internalKey to pathOf(derivation, owner)),
).right ?: throw IllegalArgumentException("could not describe output $index")
}
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt
index b4725d19..35627cec 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupSpendBuilder.kt
@@ -27,11 +27,28 @@ import fr.acinq.lightning.utils.sum
* [GroupSpend.Spender.Guardian] -- takes only coins its leaf's lock has already
* let go of, puts that lock on every input, and weighs each input by its leaf
* and control block. Its change, if any, goes back to the descendant.
+ *
+ * A spend can also *fund* a descendant's guarded wallet: a [Destination.Funding]
+ * pays the receive address `GroupWalletState.fundingAddress` chose, and the PSBT
+ * says so on that output, in the derivation field change already uses, so every
+ * signer can derive it again. See `docs/guarded-wallet-funding.md`.
*/
object GroupSpendBuilder {
/** Phoenix's floor, kept: an output below it is one no node will relay. */
val DUST: Satoshi = Satoshi(546)
+ /** Where a spend's payment goes. */
+ sealed interface Destination {
+ /** What the member typed: whatever it is, it is not the group's to vouch for. */
+ data class Address(val address: String) : Destination
+
+ /**
+ * A descendant's guarded wallet, at [derived] under its [account] -- the
+ * receive address `GroupWalletState.fundingAddress` chose.
+ */
+ data class Funding(val account: GroupWalletDerivation.Account, val derived: GroupWalletDerivation.Derived) : Destination
+ }
+
sealed interface Result {
data class Built(
val psbt: Psbt,
@@ -40,6 +57,8 @@ object GroupSpendBuilder {
val change: Satoshi?,
/** What [fee] holds beyond the feerate: change too small to send back, paid to the miner instead. */
val absorbed: Satoshi = Satoshi(0),
+ /** The guarded wallet the payment funds, or null for a payment to a typed address. */
+ val funded: Destination.Funding? = null,
) : Result
data object NotAnAddress : Result
data object NothingToSpend : Result
@@ -72,8 +91,18 @@ object GroupSpendBuilder {
feeratePerVbyte: Long,
reserved: Set,
spender: GroupSpend.Spender = GroupSpend.Spender.Owner,
+ ): Result = sendAll(state, Destination.Address(address), feeratePerVbyte, reserved, spender)
+
+ /** Every confirmed, unreserved coin, to [destination], less the fee. */
+ fun sendAll(
+ state: GroupWalletState,
+ destination: Destination,
+ feeratePerVbyte: Long,
+ reserved: Set,
+ spender: GroupSpend.Spender = GroupSpend.Spender.Owner,
): Result {
- val script = scriptOf(state, address) ?: return Result.NotAnAddress
+ val script = scriptOf(state, destination) ?: return Result.NotAnAddress
+ val funded = destination as? Destination.Funding
val coins = spendable(state, reserved, spender).ifEmpty { return Result.NothingToSpend }
val total = coins.map { it.amount }.sum()
@@ -82,7 +111,7 @@ object GroupSpendBuilder {
if (amount < DUST) return Result.BelowDust
val tx = transaction(state, coins, listOf(TxOut(amount, script)), spender)
- return Result.Built(psbtOf(state, tx, coins, change = emptyMap()), amount, fee, change = null)
+ return Result.Built(psbtOf(state, tx, coins, change = emptyMap(), funded), amount, fee, change = null, funded = funded)
}
/**
@@ -98,8 +127,20 @@ object GroupSpendBuilder {
reserved: Set,
reservedChange: Set = emptySet(),
spender: GroupSpend.Spender = GroupSpend.Spender.Owner,
+ ): Result = send(state, Destination.Address(address), amount, feeratePerVbyte, reserved, reservedChange, spender)
+
+ /** [amount] to [destination], as [send] to an address does. */
+ fun send(
+ state: GroupWalletState,
+ destination: Destination,
+ amount: Satoshi,
+ feeratePerVbyte: Long,
+ reserved: Set,
+ reservedChange: Set = emptySet(),
+ spender: GroupSpend.Spender = GroupSpend.Spender.Owner,
): Result {
- val script = scriptOf(state, address) ?: return Result.NotAnAddress
+ val script = scriptOf(state, destination) ?: return Result.NotAnAddress
+ val funded = destination as? Destination.Funding
if (amount < DUST) return Result.BelowDust
val coins = spendable(state, reserved, spender).sortedByDescending { it.amount.sat }.ifEmpty { return Result.NothingToSpend }
@@ -116,7 +157,7 @@ object GroupSpendBuilder {
if (leftover >= DUST) {
val tx = transaction(state, chosen, listOf(TxOut(amount, script), TxOut(leftover, change.pubkeyScript)), spender)
- return Result.Built(psbtOf(state, tx, chosen, mapOf(1 to change)), amount, withChange, leftover)
+ return Result.Built(psbtOf(state, tx, chosen, mapOf(1 to change), funded), amount, withChange, leftover, funded = funded)
}
// Enough to pay without change: the remainder, under dust, goes to fees.
@@ -124,8 +165,9 @@ object GroupSpendBuilder {
if (total - amount >= withoutChange) {
val tx = transaction(state, chosen, listOf(TxOut(amount, script)), spender)
return Result.Built(
- psbtOf(state, tx, chosen, emptyMap()), amount, total - amount, change = null,
+ psbtOf(state, tx, chosen, emptyMap(), funded), amount, total - amount, change = null,
absorbed = total - amount - withoutChange,
+ funded = funded,
)
}
}
@@ -148,17 +190,20 @@ object GroupSpendBuilder {
if (reduced < DUST) return Result.NotEnough
val tx = spend.tx.copy(txOut = spend.tx.txOut.mapIndexed { index, out -> if (index == target.index) out.copy(amount = reduced) else out })
+ // A funding keeps its claim, or the bump would read as a payment to a bare address.
val psbt = GroupSpend.psbtOf(
tx,
spend.inputs.map { it.txOut to it.derivation },
spend.outputs.mapNotNull { output -> output.change?.let { output.index to it } }.toMap(),
spend.account,
+ funding = spend.fundings.associate { it.outputIndex to (it.wallet.account to it.derived) },
)
return Result.Built(
psbt = psbt,
amount = if (target.isChange) spend.amountSent else reduced,
fee = fee,
change = if (target.isChange) reduced else null,
+ funded = spend.fundings.singleOrNull()?.let { Destination.Funding(it.wallet.account, it.derived) },
)
}
@@ -191,9 +236,17 @@ object GroupSpendBuilder {
private fun lockOf(state: GroupWalletState, spender: GroupSpend.Spender): Long? =
(spender as? GroupSpend.Spender.Guardian)?.let { state.account.guardians[it.position].delay }
- private fun scriptOf(state: GroupWalletState, address: String): ByteVector? =
- Bitcoin.addressToPublicKeyScript(state.account.chain.chainHash, address.trim()).right
+ /**
+ * What [destination] pays: a typed address's script, or the funded wallet's
+ * own derivation -- never a string round trip, so a funding is always an
+ * address. Null for text that is not an address on this network, and for a
+ * funding on another network.
+ */
+ private fun scriptOf(state: GroupWalletState, destination: Destination): ByteVector? = when (destination) {
+ is Destination.Address -> Bitcoin.addressToPublicKeyScript(state.account.chain.chainHash, destination.address.trim()).right
?.let { ByteVector(Script.write(it)) }
+ is Destination.Funding -> destination.derived.pubkeyScript.takeIf { destination.account.chain == state.account.chain }
+ }
private fun transaction(state: GroupWalletState, coins: List, outputs: List, spender: GroupSpend.Spender) = Transaction(
version = 2,
@@ -226,6 +279,15 @@ object GroupSpendBuilder {
return Satoshi(feeratePerVbyte * ((weight + 3) / 4))
}
- private fun psbtOf(state: GroupWalletState, tx: Transaction, coins: List, change: Map) =
- GroupSpend.psbtOf(tx, coins.map { it.utxo.txOut to it.derivation }, change, state.account)
+ /** The payment is always output 0, so a funding's claim goes there. */
+ private fun psbtOf(
+ state: GroupWalletState,
+ tx: Transaction,
+ coins: List,
+ change: Map,
+ funded: Destination.Funding?,
+ ) = GroupSpend.psbtOf(
+ tx, coins.map { it.utxo.txOut to it.derivation }, change, state.account,
+ funding = funded?.let { mapOf(0 to (it.account to it.derived)) }.orEmpty(),
+ )
}
diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/ui/view/state/GuardedWalletRowTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/ui/view/state/GuardedWalletRowTest.kt
new file mode 100644
index 00000000..0136d3eb
--- /dev/null
+++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/ui/view/state/GuardedWalletRowTest.kt
@@ -0,0 +1,80 @@
+package com.machankura.bennu.compose.ui.view.state
+
+import com.machankura.bennu.compose.managers.GroupWalletDerivation
+import com.machankura.bennu.compose.managers.GuardianDerivation
+import com.machankura.bennu.compose.managers.GuardianManager
+import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
+import com.machankura.bennu.compose.wallet.GroupWalletState
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import fr.acinq.bitcoin.ByteVector
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.Chain
+import fr.acinq.bitcoin.OutPoint
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.Satoshi
+import fr.acinq.bitcoin.Transaction
+import fr.acinq.bitcoin.TxId
+import fr.acinq.bitcoin.TxIn
+import fr.acinq.bitcoin.TxOut
+import fr.acinq.lightning.blockchain.electrum.WalletState
+import fr.acinq.secp256k1.Hex
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNull
+
+/**
+ * What an ancestor's wallet screen says about a descendant's guarded wallet: a
+ * funding is *arriving* until the leaf's lock lets it go, and then *within
+ * reach* -- never neither, which would make the money look gone.
+ */
+class GuardedWalletRowTest {
+ private val descendantRoomId = "c".repeat(64)
+ private val account = GroupWalletDerivation.account(
+ PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), Chain.Regtest,
+ )
+ private val wallet = GuardianManager.GuardedWallet(
+ ancestorChatRoomId = "d".repeat(64),
+ descendantChatRoomId = descendantRoomId,
+ statement = Event("1".repeat(64), descendantRoomId, 1_700_000_000, GroupWalletStatementEvent.KIND, emptyArray(), "", ""),
+ account = account,
+ certificate = Event("2".repeat(64), "d".repeat(64), 1_700_000_000, 0, emptyArray(), "", ""),
+ lineage = listOf(descendantRoomId),
+ )
+
+ /** One coin of 50,000 sats at the first receive address, confirmed at [height] (0 in the mempool), with the tip at [tip]. */
+ private fun holding(height: Long, tip: Int): GroupWalletState {
+ val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0)
+ val tx = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 7 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(50_000), derived.pubkeyScript)), 0)
+ val meta = WalletState.AddressMeta.Derived(0)
+ return GroupWalletState(
+ account,
+ WalletState(mapOf(derived.address(Chain.Regtest) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(tx.txid, 0, height, tx, meta))))),
+ WalletState.empty,
+ tipHeight = tip,
+ )
+ }
+
+ @Test
+ fun `a coin is arriving until the lock lets it go, then within reach`() {
+ val lock = GuardianDerivation.ANCESTOR_DELAY.toInt()
+
+ val mempool = GuardedWalletRow(wallet, holding(height = 0, tip = 100))
+ assertEquals(Satoshi(50_000), mempool.arriving)
+ assertEquals(Satoshi(0), mempool.withinReach)
+
+ val young = GuardedWalletRow(wallet, holding(height = 100, tip = 100 + lock - 2))
+ assertEquals(Satoshi(50_000), young.arriving, "${lock - 1} confirmations")
+ assertEquals(Satoshi(0), young.withinReach)
+
+ val old = GuardedWalletRow(wallet, holding(height = 100, tip = 100 + lock - 1))
+ assertEquals(Satoshi(0), old.arriving, "$lock confirmations")
+ assertEquals(Satoshi(50_000), old.withinReach)
+ }
+
+ @Test
+ fun `nothing is said before the chain is known`() {
+ val row = GuardedWalletRow(wallet, walletState = null)
+ assertNull(row.arriving)
+ assertNull(row.withinReach)
+ }
+}
diff --git a/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFundingTest.kt b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFundingTest.kt
new file mode 100644
index 00000000..1fc0c296
--- /dev/null
+++ b/composeApp/src/commonTest/kotlin/com/machankura/bennu/compose/wallet/GroupSpendFundingTest.kt
@@ -0,0 +1,127 @@
+package com.machankura.bennu.compose.wallet
+
+import com.machankura.bennu.compose.managers.GroupWalletDerivation
+import fr.acinq.bitcoin.ByteVector
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.Chain
+import fr.acinq.bitcoin.OutPoint
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.Satoshi
+import fr.acinq.bitcoin.Transaction
+import fr.acinq.bitcoin.TxId
+import fr.acinq.bitcoin.TxIn
+import fr.acinq.bitcoin.TxOut
+import fr.acinq.lightning.blockchain.electrum.WalletState
+import fr.acinq.secp256k1.Hex
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertIs
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+
+/**
+ * A spend that funds a descendant's wallet: the payment carries its place under
+ * the descendant's account, and that claim has to survive the wire and never
+ * be taken for change. See `docs/guarded-wallet-funding.md`, Phase 2.
+ */
+class GroupSpendFundingTest {
+ private fun accountFrom(seed: Int): GroupWalletDerivation.Account = GroupWalletDerivation.account(
+ PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString(),
+ Chain.Regtest,
+ )
+
+ private val account = accountFrom(0x1c0ffee)
+
+ /** The first descendant account, counting up, whose fingerprint has its top bit set: the one the wire reads back signed. */
+ private val descendant: GroupWalletDerivation.Account = generateSequence(1) { it + 1 }
+ .map { accountFrom(it) }
+ .first { it.fingerprint >= 0x80000000L }
+
+ private val funding = GroupSpendBuilder.Destination.Funding(
+ descendant, GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, 7),
+ )
+ private val typed = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080"
+ private val feerate = 5L
+
+ private fun coin(index: Int, sats: Long): Pair {
+ val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index.toLong())
+ val tx = Transaction(
+ 2,
+ listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { index.toByte() })), 0), ByteVector.empty, 0xffffffffL)),
+ listOf(TxOut(Satoshi(sats), derived.pubkeyScript)),
+ 0,
+ )
+ val meta = WalletState.AddressMeta.Derived(index)
+ return derived.address(Chain.Regtest) to WalletState.AddressState(
+ meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(tx.txid, 0, 100, tx, meta)),
+ )
+ }
+
+ private fun state(vararg coins: Pair): GroupWalletState {
+ val change = WalletState(mapOf(
+ GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, 0).address(Chain.Regtest) to
+ WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList())
+ ))
+ return GroupWalletState(account, WalletState(coins.toMap()), change, tipHeight = 110)
+ }
+
+ @Test
+ fun `a funding's claim survives the wire for a high fingerprint`() {
+ val built = assertIs(
+ GroupSpendBuilder.send(state(coin(0, 60_000)), funding, Satoshi(30_000), feerate, emptySet())
+ )
+ assertEquals(funding, built.funded)
+ assertEquals(funding.derived.pubkeyScript, built.psbt.global.tx.txOut[0].publicKeyScript)
+
+ assertTrue(descendant.fingerprint >= 0x80000000L)
+ val received = GroupSpend.decode(GroupSpend.encode(built.psbt))!!
+ assertEquals(setOf(7L), GroupSpend.claimedFundingIndices(received, descendant))
+ assertEquals(setOf(0L), GroupSpend.claimedChangeIndices(received, account), "the change is still the room's own")
+ assertEquals(emptySet(), GroupSpend.claimedFundingIndices(received, account), "the room's own account funds nothing")
+ }
+
+ @Test
+ fun `a funding is a payment, not change`() {
+ val built = assertIs(
+ GroupSpendBuilder.send(state(coin(0, 60_000)), funding, Satoshi(30_000), feerate, emptySet())
+ )
+ val received = GroupSpend.decode(GroupSpend.encode(built.psbt))!!
+
+ val checked = assertIs(GroupSpend.check(received, account)).checked
+ assertEquals(listOf(false, true), checked.outputs.map { it.isChange })
+ assertEquals(Satoshi(30_000), checked.amountSent)
+ }
+
+ @Test
+ fun `sending everything can fund too`() {
+ val built = assertIs(
+ GroupSpendBuilder.sendAll(state(coin(0, 60_000), coin(1, 40_000)), funding, feerate, emptySet())
+ )
+ assertEquals(funding, built.funded)
+ assertEquals(setOf(7L), GroupSpend.claimedFundingIndices(built.psbt, descendant))
+ assertIs(GroupSpend.check(built.psbt, account))
+ }
+
+ @Test
+ fun `a send to a typed address claims nothing about its payment`() {
+ val built = assertIs(
+ GroupSpendBuilder.send(state(coin(0, 60_000)), typed, Satoshi(30_000), feerate, emptySet())
+ )
+ assertNull(built.funded)
+ assertTrue(built.psbt.outputs[0].taprootDerivationPaths.isEmpty())
+ assertEquals(1, built.psbt.outputs[1].taprootDerivationPaths.size, "change is described as it always was")
+ }
+
+ @Test
+ fun `a wallet on another network is not one to fund`() {
+ val elsewhere = GroupWalletDerivation.account(
+ PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(),
+ Chain.Signet,
+ )
+ val across = GroupSpendBuilder.Destination.Funding(elsewhere, GroupWalletDerivation.derive(elsewhere, GroupWalletDerivation.RECEIVE, 0))
+ assertEquals(
+ GroupSpendBuilder.Result.NotAnAddress,
+ GroupSpendBuilder.send(state(coin(0, 60_000)), across, Satoshi(30_000), feerate, emptySet()),
+ )
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt
index 45e22bf8..6eece51e 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GuardianSigningJvmTest.kt
@@ -625,4 +625,131 @@ class GuardianSigningJvmTest {
val psbt = GroupSpend.psbtOf(unlocked, listOf(funding.txOut[0] to GroupWalletDerivation.derive(guarded.account, 0, 0)), emptyMap(), guarded.account)
assertIs(GroupSpend.check(psbt, guarded.account, guarded.spender(thresholdPublicKey)))
}
+
+ // ---- Funding a descendant's guarded wallet -------------------------------
+
+ /** The room opens its own plain wallet, signed by a quorum, so it has coins to fund with. */
+ private suspend fun openOwnWallet(proposer: Device, other: Device): GroupWalletDerivation.Account {
+ val own = GroupWalletDerivation.account(thresholdPublicKey, chain)
+ val template = GroupWalletStatementEvent.template(own)
+ val session = FrostSigningManager.proposeSigning(proposer.db, proposer.room, proposer.publicKey, template.kind, template.tags, template.content)
+ pump(proposer, other)
+ FrostSigningManager.approve(other.db, other.room, session.id)
+ pump(proposer, other)
+ listOf(proposer, other).forEach { assertNotNull(GroupWalletManager.walletFor(it.db, roomId, chain), "the room's own wallet is open") }
+ return own
+ }
+
+ /** The room's own wallet holding one confirmed coin at its first receive address. */
+ private fun ownState(own: GroupWalletDerivation.Account): GroupWalletState {
+ val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0)
+ val paid = Transaction(
+ 2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 0x71 })), 0), ByteVector.empty, 0xffffffffL)),
+ listOf(TxOut(Satoshi(80_000), coin.pubkeyScript)), 0,
+ )
+ val meta = WalletState.AddressMeta.Derived(0)
+ val receive = WalletState(mapOf(coin.address(chain) to WalletState.AddressState(meta, alreadyUsed = true, utxos = listOf(WalletState.Utxo(paid.txid, 0, 100, paid, meta)))))
+ val change = WalletState((0 until 3).associate { index ->
+ GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, index.toLong()).address(chain) to
+ WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList())
+ })
+ return GroupWalletState(own, receive, change, tipHeight = 110)
+ }
+
+ private fun fundingTo(guarded: GuardianManager.GuardedWallet, index: Long) =
+ GroupSpendBuilder.Destination.Funding(guarded.account, GroupWalletDerivation.derive(guarded.account, GroupWalletDerivation.RECEIVE, index))
+
+ @Test
+ fun `a funding is read as one by every device holding the wallet, and its address is held`(): Unit = runBlocking {
+ val proposer = device(members[0], signerIndex = 0)
+ val other = device(members[1], signerIndex = 1)
+ val statement = guardedStatement()
+ tell(proposer, statement)
+ tell(other, statement)
+ val own = openOwnWallet(proposer, other)
+
+ val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0))
+ val built = assertIs(
+ GroupSpendBuilder.send(ownState(own), fundingTo(guarded, 2), Satoshi(30_000), 2, emptySet())
+ )
+ val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, chain)
+ pump(proposer, other)
+
+ val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id))
+ val funding = seen.fundings.single()
+ assertEquals(guardedChildRoomId, funding.wallet.descendantChatRoomId)
+ assertEquals(2L, funding.derived.index)
+ assertEquals(
+ com.machankura.bennu.compose.text.ProposedEvent.Summary(
+ "Fund Translation team's guarded wallet",
+ "Send 30,000 sats to Translation team's guarded wallet, address 2",
+ ),
+ com.machankura.bennu.compose.text.ProposedSpend.summarize(seen, chain),
+ )
+ assertEquals(setOf(2L), FrostSigningManager.reservedFundingIndices(other.db, roomId, guarded.account))
+
+ // A bump keeps the claim, or it would read as a payment to a bare address.
+ val bumped = assertIs(GroupSpendBuilder.bump(seen, 5))
+ assertEquals(setOf(2L), GroupSpend.claimedFundingIndices(bumped.psbt, guarded.account))
+ assertEquals(2L, bumped.funded?.derived?.index)
+
+ // Abandoned, it lets the address go.
+ other.db.frostSigningSessionDao().upsert(other.session(session.id)!!.copy(stage = FrostSigningStage.FAILED))
+ assertEquals(emptySet(), FrostSigningManager.reservedFundingIndices(other.db, roomId, guarded.account))
+ }
+
+ @Test
+ fun `a funding claiming an address it does not pay is refused by every device that can tell`(): Unit = runBlocking {
+ val proposer = device(members[0], signerIndex = 0)
+ val other = device(members[1], signerIndex = 1)
+ // Only the other device holds the wallet, so only it can check the claim.
+ tell(other, guardedStatement())
+ val own = openOwnWallet(proposer, other)
+
+ val guarded = assertNotNull(GuardianManager.guardedWalletFor(other.db, roomId, guardedChildRoomId, chain, 0))
+ val honest = assertIs(
+ GroupSpendBuilder.send(ownState(own), fundingTo(guarded, 2), Satoshi(30_000), 2, emptySet())
+ )
+ // Pays address 2, says address 3.
+ val claimed = GroupWalletDerivation.derive(guarded.account, GroupWalletDerivation.RECEIVE, 3)
+ val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0)
+ val lying = GroupSpend.psbtOf(
+ honest.psbt.global.tx,
+ listOf(TxOut(Satoshi(80_000), coin.pubkeyScript) to coin),
+ mapOf(1 to GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, 0)),
+ own,
+ funding = mapOf(0 to (guarded.account to claimed)),
+ )
+ assertIs(
+ GroupSpend.fundingsOf(assertIs(GroupSpend.check(lying, own)).checked, listOf(guarded))
+ )
+
+ val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, lying, chain)
+ pump(proposer, other)
+ assertNull(other.session(session.id), "the device that holds the wallet never puts it to the member")
+ }
+
+ @Test
+ fun `a device never told about the wallet reads a funding as the bare address it pays`(): Unit = runBlocking {
+ val proposer = device(members[0], signerIndex = 0)
+ val other = device(members[1], signerIndex = 1)
+ tell(proposer, guardedStatement())
+ val own = openOwnWallet(proposer, other)
+
+ val guarded = assertNotNull(GuardianManager.guardedWalletFor(proposer.db, roomId, guardedChildRoomId, chain, 0))
+ val destination = fundingTo(guarded, 2)
+ val built = assertIs(
+ GroupSpendBuilder.send(ownState(own), destination, Satoshi(30_000), 2, emptySet())
+ )
+ val session = FrostSigningManager.proposeSpend(proposer.db, proposer.room, proposer.publicKey, built.psbt, chain)
+ pump(proposer, other)
+
+ val seen = assertNotNull(FrostSigningManager.checkedSpend(other.db, session.id), "accepted: the address is the truth")
+ assertEquals(emptyList(), seen.fundings)
+ assertEquals(
+ "Send 30,000 sats to ${destination.derived.address(chain)}",
+ com.machankura.bennu.compose.text.ProposedSpend.summarize(seen, chain).detail,
+ )
+ assertEquals(1, assertNotNull(FrostSigningManager.checkedSpend(proposer.db, session.id)).fundings.size, "and the proposer's own device still names it")
+ }
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt
index c6cad631..4d5ea6ae 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/MemberWalletGuardianJvmTest.kt
@@ -202,4 +202,38 @@ class MemberWalletGuardianJvmTest {
val early = unsigned.updateWitness(0, input.witness(signWith(parent, input.cache, sighash)))
assertFails { early.correctlySpends(checked.inputs.associate { it.outPoint to it.txOut }, ScriptFlags.STANDARD_SCRIPT_VERIFY_FLAGS) }
}
+
+ @Test
+ fun `a group funds its member's wallet, and its signers read where the money goes`(): Unit = runBlocking {
+ GroupFixtures.seedProfile(db, memberPublicKey, name = "alice")
+ inRoom(group, guardedCertificate(parent, group))
+ fileSigned(certificate())
+ val wallet = GuardianManager.guardedWalletsOf(db, groupRoom).single()
+
+ // The group's own wallet, with one coin to fund from.
+ val own = GroupWalletDerivation.account(thresholdKeyOf(group), chain)
+ val coin = GroupWalletDerivation.derive(own, GroupWalletDerivation.RECEIVE, 0)
+ val funding = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 5 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(90_000), coin.pubkeyScript)), 0)
+ val meta = WalletState.AddressMeta.Derived(0)
+ val ownState = GroupWalletState(
+ own,
+ WalletState(mapOf(coin.address(chain) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(funding.txid, 0, 100, funding, meta))))),
+ WalletState(mapOf(GroupWalletDerivation.derive(own, GroupWalletDerivation.CHANGE, 0).address(chain) to WalletState.AddressState(WalletState.AddressMeta.Derived(0), false, emptyList()))),
+ tipHeight = 110,
+ )
+
+ // The member's address two past their current one.
+ val target = GroupWalletDerivation.derive(wallet.account, GroupWalletDerivation.RECEIVE, 2)
+ val built = assertIs(
+ GroupSpendBuilder.send(ownState, GroupSpendBuilder.Destination.Funding(wallet.account, target), Satoshi(20_000), 3L, emptySet())
+ )
+ val checked = assertIs(GroupSpend.check(built.psbt, own)).checked
+ val reading = assertIs(GroupSpend.fundingsOf(checked, listOf(wallet)))
+
+ val funded = reading.fundings.single()
+ assertEquals(walletId, funded.wallet.descendantChatRoomId)
+ assertEquals(target.pubkeyScript, checked.tx.txOut[funded.outputIndex].publicKeyScript)
+ val summary = com.machankura.bennu.compose.text.ProposedSpend.summarize(checked.copy(fundings = reading.fundings), chain)
+ assertEquals("Fund @alice's guarded wallet", summary.label)
+ }
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreenJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreenJvmTest.kt
index 197071e3..4d54fd35 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreenJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GroupSendScreenJvmTest.kt
@@ -19,6 +19,9 @@ import com.machankura.bennu.compose.database.model.ChatRoom
import com.machankura.bennu.compose.database.model.GroupSignedEvent
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.managers.GroupWalletDerivation
+import com.machankura.bennu.compose.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
@@ -106,6 +109,40 @@ class GroupSendScreenJvmTest {
onNodeWithText("Ask the group to send").assertIsNotEnabled()
}
+ @Test
+ fun `funding a guarded wallet names it, shows where it pays, and takes no address`() = render(Chain.Regtest, funded = true) {
+ onNodeWithText("Fund Savings's guarded wallet").assertIsDisplayed()
+ onNodeWithText("Savings's guarded wallet").assertIsDisplayed()
+ onNodeWithText("Address").assertDoesNotExist()
+ onNodeWithText("Address 2").assertIsDisplayed()
+ onNodeWithText("This group can spend these coins again once they have 12 confirmations.").assertIsDisplayed()
+
+ onNodeWithText("Fee rate in sats per byte").performTextInput("4")
+ onNodeWithText("Amount in sats").performTextInput("40000")
+ onNodeWithText("Sends 40,000 sats to Savings's guarded wallet", substring = true).assertIsDisplayed()
+ onNodeWithText("Ask the group to send").assertIsEnabled()
+ }
+
+ private fun funding(chain: Chain): FundingTarget {
+ val descendantRoomId = "c".repeat(64)
+ val descendant = GroupWalletDerivation.account(
+ PrivateKey(ByteVector32(Hex.decode("decaf".padStart(64, '0')))).publicKey().toString(), chain,
+ )
+ 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),
+ )
+ val receive = (0 until 10).associate { index ->
+ GroupWalletDerivation.derive(descendant, GroupWalletDerivation.RECEIVE, index.toLong()).address(chain) to
+ WalletState.AddressState(WalletState.AddressMeta.Derived(index), alreadyUsed = false, utxos = emptyList())
+ }
+ return FundingTarget(guarded, GroupWalletState(descendant, WalletState(receive), WalletState.empty, tipHeight = 110))
+ }
+
private fun ComposeUiTest.fill(address: String, amount: String) {
onNodeWithText("Address").performTextInput(address)
onNodeWithText("Fee rate in sats per byte").performTextInput("4")
@@ -146,7 +183,7 @@ class GroupSendScreenJvmTest {
return GroupSendUIState.Ready(room, wallet, walletState, reserved = emptySet())
}
- private fun render(chain: Chain, assertions: ComposeUiTest.() -> Unit) =
+ private fun render(chain: Chain, funded: Boolean = false, assertions: ComposeUiTest.() -> Unit) =
runDesktopComposeUiTest(width = 400, height = 1200) {
setContent {
BennuTheme {
@@ -156,7 +193,7 @@ class GroupSendScreenJvmTest {
activeUserPublicKey = "a".repeat(64),
chatRoomId = chatRoomId,
chain = chain,
- initialGroupSendUIState = ready(chain),
+ initialGroupSendUIState = ready(chain).let { if (funded) it.copy(funding = funding(chain)) else it },
chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY,
frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY,
wallets = null,
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GuardedWalletCardJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GuardedWalletCardJvmTest.kt
new file mode 100644
index 00000000..58831b5b
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/composable/GuardedWalletCardJvmTest.kt
@@ -0,0 +1,167 @@
+package com.machankura.bennu.compose.ui.composable
+
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.runtime.CompositionLocalProvider
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.test.ComposeUiTest
+import androidx.compose.ui.test.ExperimentalTestApi
+import androidx.compose.ui.test.assertIsDisplayed
+import androidx.compose.ui.test.onNodeWithContentDescription
+import androidx.compose.ui.test.onNodeWithText
+import androidx.compose.ui.test.performClick
+import androidx.compose.ui.test.runDesktopComposeUiTest
+import androidx.compose.ui.unit.Density
+import com.machankura.bennu.compose.database.model.ChatRoom
+import com.machankura.bennu.compose.database.model.GroupSignedEvent
+import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
+import com.machankura.bennu.compose.managers.GroupWalletDerivation
+import com.machankura.bennu.compose.managers.GuardianManager
+import com.machankura.bennu.compose.nostr.wallet.GroupWallet
+import com.machankura.bennu.compose.nostr.wallet.GroupWalletStatementEvent
+import com.machankura.bennu.compose.repository.ChatRepository
+import com.machankura.bennu.compose.repository.FrostSigningRepository
+import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute
+import com.machankura.bennu.compose.ui.composable.navigation.routes.Route
+import com.machankura.bennu.compose.ui.composable.widgets.ProvideSnackbarHost
+import com.machankura.bennu.compose.ui.theme.BennuTheme
+import com.machankura.bennu.compose.ui.view.state.GroupWalletUIState
+import com.machankura.bennu.compose.ui.view.state.GuardedWalletRow
+import com.machankura.bennu.compose.wallet.GroupWalletState
+import com.vitorpamplona.quartz.nip01Core.core.Event
+import fr.acinq.bitcoin.ByteVector
+import fr.acinq.bitcoin.ByteVector32
+import fr.acinq.bitcoin.Chain
+import fr.acinq.bitcoin.OutPoint
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.Satoshi
+import fr.acinq.bitcoin.Transaction
+import fr.acinq.bitcoin.TxId
+import fr.acinq.bitcoin.TxIn
+import fr.acinq.bitcoin.TxOut
+import fr.acinq.lightning.blockchain.electrum.WalletState
+import fr.acinq.secp256k1.Hex
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.time.Instant
+
+/**
+ * A descendant's guarded wallet on an ancestor's wallet screen: a card whose
+ * actions sit under the name rather than squeezing it, each one telling a
+ * screen reader which wallet it acts on. `docs/guarded-wallet-funding.md`, Phase 5.
+ */
+@OptIn(ExperimentalTestApi::class)
+class GuardedWalletCardJvmTest {
+ private val chatRoomId = "d4c3b2a1".repeat(8)
+ private val descendantRoomId = "c".repeat(64)
+
+ private fun account(seed: String) = GroupWalletDerivation.account(
+ PrivateKey(ByteVector32(Hex.decode(seed.padStart(64, '0')))).publicKey().toString(), Chain.Regtest,
+ )
+
+ private fun holding(account: GroupWalletDerivation.Account, sats: Long, height: Long, tip: Int): GroupWalletState {
+ val derived = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 0)
+ val next = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, 1)
+ val tx = Transaction(2, listOf(TxIn(OutPoint(TxId(ByteVector32(ByteArray(32) { 3 })), 0), ByteVector.empty, 0xffffffffL)), listOf(TxOut(Satoshi(sats), derived.pubkeyScript)), 0)
+ val meta = WalletState.AddressMeta.Derived(0)
+ return GroupWalletState(
+ account,
+ WalletState(mapOf(
+ derived.address(Chain.Regtest) to WalletState.AddressState(meta, true, listOf(WalletState.Utxo(tx.txid, 0, height, tx, meta))),
+ next.address(Chain.Regtest) to WalletState.AddressState(WalletState.AddressMeta.Derived(1), false, emptyList()),
+ )),
+ WalletState.empty,
+ tipHeight = tip,
+ )
+ }
+
+ private fun loaded(name: String): GroupWalletUIState.Loaded {
+ val own = account("1c0ffee")
+ val descendant = account("decaf")
+ 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", name)), "", ""),
+ lineage = listOf(descendantRoomId),
+ )
+ val wallet = GroupWallet(
+ GroupSignedEvent(
+ id = "e".repeat(64), chatRoomId = chatRoomId, publicKey = chatRoomId, kind = GroupWalletStatementEvent.KIND,
+ tags = GroupWalletStatementEvent.template(own).tags, content = own.xpub, signature = "f".repeat(128),
+ createdAt = Instant.fromEpochSeconds(1_700_000_000),
+ ),
+ own,
+ )
+ val room = LocalChatRoom(ChatRoom(id = chatRoomId, userPublicKey = "a".repeat(64), subject = "Treasury", description = null, initialGiftWrapPayloadId = "p", mlsGroupState = "state"))
+ return GroupWalletUIState.Loaded(
+ localChatRoom = room,
+ wallet = wallet,
+ walletState = holding(own, 100_000, height = 100, tip = 200),
+ canWatch = true,
+ canSign = true,
+ guardedWallets = listOf(GuardedWalletRow(guarded, holding(descendant, 50_000, height = 0, tip = 200))),
+ )
+ }
+
+ private fun render(state: GroupWalletUIState, fontScale: Float = 1f, width: Int = 400, onRoute: (Route) -> Unit = {}, assertions: ComposeUiTest.() -> Unit) =
+ runDesktopComposeUiTest(width = width, height = 2400) {
+ setContent {
+ BennuTheme {
+ ProvideSnackbarHost {
+ CompositionLocalProvider(LocalDensity provides Density(LocalDensity.current.density, fontScale)) {
+ Box(modifier = Modifier.fillMaxSize()) {
+ GroupWalletScreen(
+ activeUserPublicKey = "a".repeat(64),
+ chatRoomId = chatRoomId,
+ chain = Chain.Regtest,
+ initialGroupWalletUIState = state,
+ chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY,
+ frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY,
+ wallets = null,
+ onNavigateToRoute = onRoute,
+ onNavigateBack = {},
+ )
+ }
+ }
+ }
+ }
+ }
+ assertions()
+ }
+
+ @Test
+ fun `each guarded wallet offers fund beside spend, each naming its wallet`() = render(loaded("Savings")) {
+ onNodeWithText("Savings").assertIsDisplayed()
+ onNodeWithText("0 sats within this group's reach · 50,000 sats arriving").assertIsDisplayed()
+ onNodeWithContentDescription("Fund Savings's guarded wallet").assertIsDisplayed()
+ onNodeWithContentDescription("Spend from Savings's guarded wallet").assertIsDisplayed()
+ }
+
+ @Test
+ fun `fund opens the send form paying the descendant, from the room's own wallet`() {
+ var opened: Route? = null
+ render(loaded("Savings"), onRoute = { opened = it }) {
+ onNodeWithContentDescription("Fund Savings's guarded wallet").performClick()
+ }
+ assertEquals(
+ GroupSendRoute(activeUserPublicKey = "a".repeat(64), chatRoomId = chatRoomId, relayHint = null, fundChatRoomId = descendantRoomId),
+ opened,
+ )
+ }
+
+ @Test
+ fun `a device that cannot sign is offered neither`() = render(loaded("Savings").copy(canSign = false)) {
+ onNodeWithText("Savings").assertIsDisplayed()
+ onNodeWithText("Fund").assertDoesNotExist()
+ onNodeWithText("Spend").assertDoesNotExist()
+ }
+
+ @Test
+ fun `at twice the text size the buttons stay whole`() = render(loaded("Savings"), fontScale = 2f) {
+ onNodeWithContentDescription("Fund Savings's guarded wallet").assertIsDisplayed()
+ onNodeWithContentDescription("Spend from Savings's guarded wallet").assertIsDisplayed()
+ }
+}
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)
+ }
}
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 61150c11..d1915e8b 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
@@ -7,6 +7,7 @@ import fr.acinq.bitcoin.Chain
import fr.acinq.bitcoin.PrivateKey
import fr.acinq.bitcoin.Satoshi
import fr.acinq.lightning.blockchain.electrum.HeaderSubscriptionResponse
+import fr.acinq.lightning.blockchain.electrum.WalletState
import fr.acinq.secp256k1.Hex
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -242,4 +243,79 @@ class GroupOnchainWalletJvmTest {
assertEquals(Satoshi(7_000), used.balance)
assertEquals(before.listed(), state.listed())
}
+
+ @Test
+ fun `a fresh wallet is funded two past the current address`() {
+ val wallet = GroupOnchainWallet(account, FakeElectrum(), scope)
+
+ val state = eventually { wallet.state.first { it.receive.addresses.size == GroupOnchainWallet.RECEIVE_LOOKAHEAD.toInt() } }
+ val funding = state.fundingAddress()!!
+ assertEquals(receive(2), funding.derivation)
+ assertEquals(receive(2).address(Chain.Regtest), funding.address)
+ assertEquals(GroupAddress.Status.NEXT, funding.status)
+ }
+
+ @Test
+ fun `an open funding holds its address and the window ends where the watching does`() {
+ val wallet = GroupOnchainWallet(account, FakeElectrum(), scope)
+ val lookAhead = GroupOnchainWallet.RECEIVE_LOOKAHEAD.toLong()
+
+ val state = eventually { wallet.state.first { it.receive.addresses.size == lookAhead.toInt() } }
+ assertEquals(receive(3), state.fundingAddress(setOf(2L))!!.derivation)
+ val held = (GroupOnchainWallet.ADDRESSES_AHEAD.toLong() until lookAhead).toSet()
+ assertEquals(receive(lookAhead - 1), state.fundingAddress(held - (lookAhead - 1))!!.derivation)
+ assertNull(state.fundingAddress(held), "past the last watched address the child would not see the payment")
+ }
+
+ @Test
+ fun `being paid moves the funding address on`() {
+ val electrum = FakeElectrum()
+ val wallet = GroupOnchainWallet(account, electrum, scope)
+
+ eventually { wallet.state.first { it.receiveAddress != null } }
+ eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) }
+
+ val state = eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } }
+ assertEquals(receive(3), state.fundingAddress()!!.derivation)
+ }
+
+ @Test
+ fun `a paid address above the current one is never funded`() {
+ val electrum = FakeElectrum()
+ val wallet = GroupOnchainWallet(account, electrum, scope)
+
+ eventually { wallet.state.first { it.receiveAddress != null } }
+ eventually { electrum.pay(receive(4).pubkeyScript, Satoshi(10_000)) }
+
+ val state = eventually { wallet.state.first { it.receiveAddresses?.any { it.status == GroupAddress.Status.USED } == true } }
+ assertEquals(receive(0).address(Chain.Regtest), state.receiveAddress)
+ assertEquals(receive(2), state.fundingAddress()!!.derivation)
+ assertEquals(receive(3), state.fundingAddress(setOf(2L))!!.derivation)
+ assertEquals(receive(5), state.fundingAddress(setOf(2L, 3L))!!.derivation)
+ }
+
+ @Test
+ fun `no funding address before Electrum has answered`() {
+ val state = GroupWalletState(account, WalletState.empty, WalletState.empty, tipHeight = null)
+ assertNull(state.fundingAddress())
+ }
+
+ @Test
+ fun `every funding address is one the wallet watches`() {
+ val electrum = FakeElectrum()
+ val wallet = GroupOnchainWallet(account, electrum, scope)
+
+ eventually { wallet.state.first { it.receiveAddress != null } }
+ eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(1_000)) }
+
+ val state = eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } }
+ val watched = state.receive.addresses.keys
+ var reserved = emptySet()
+ while (true) {
+ val funding = state.fundingAddress(reserved) ?: break
+ assertTrue(funding.address in watched, "${funding.derivation.index} is funded but not watched")
+ reserved = reserved + funding.derivation.index
+ }
+ assertEquals(GroupOnchainWallet.RECEIVE_LOOKAHEAD.toInt() - GroupOnchainWallet.ADDRESSES_AHEAD, reserved.size)
+ }
}
diff --git a/docs/README.md b/docs/README.md
index 10a760db..3207efa9 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -16,6 +16,7 @@ silent, or a decision that looked arbitrary and was not.
| [group-wallet-guardians.md](./group-wallet-guardians.md) | letting an ancestor group spend from a subgroup's wallet through a taproot leaf — why the parent signs the guardian keys into the child's certificate, why every inherited key is derived one step further per child, and why every ancestor waits 12 blocks |
| [subgroup-wallet-policy.md](./subgroup-wallet-policy.md) | the parent deciding, at a subgroup's birth, whether its wallet is guarded or unguarded — why the choice is signed three times, why *unguarded* means no keys in the certificate, why a guarded group's subgroups are all guarded, and why the rule is every honest client's rather than the chain's |
| [member-guarded-wallets.md](./member-guarded-wallets.md) | a guarded wallet a group keeps for one member — why the member makes the key and the leaves before asking, why the group signs a certificate of its own kind rather than a birth certificate, and why a member's wallet shows as `@name` and opens their profile |
+| [guarded-wallet-funding.md](./guarded-wallet-funding.md) | a group paying into a descendant's guarded wallet — why the address is the first unreserved one from `current + 2`, why the claim rides in the PSBT output's derivation and every signer rederives it, and how the guarded wallet row makes room for *Fund* beside *Spend* |
| [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 |
@@ -63,6 +64,11 @@ The subgroup-wallet-policy note is a phased plan that has been built. It
reads as the guardians note's *whose choice it is* reversed: read
that section, then this note's Phase 0, whose five decisions shape every phase
after it, and its table of where the build chose differently before the code.
+The guarded-wallet-funding note is a phased plan that has been built. It
+reads as the guardians note run the other way, coins in rather than out: read
+that note and the address note's *Why `+ 2`* first, then its seven decisions
+before its phases, and its 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-wallet-addresses.md b/docs/group-wallet-addresses.md
index 44f4e207..2ff4b332 100644
--- a/docs/group-wallet-addresses.md
+++ b/docs/group-wallet-addresses.md
@@ -90,7 +90,9 @@ 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.
+to either is seen the moment it reaches the mempool. An ancestor funding a
+guarded wallet starts at the top of that window, `current + 2`, and goes up, so
+it stays out of the members' way -- [guarded-wallet-funding.md](./guarded-wallet-funding.md), D2.
**Why `highest used`.** `firstUnusedDerivedAddress` takes the *lowest* unused
index, so a payment above `current` does not move `current`. If `/0/3` is
diff --git a/docs/group-wallet-guardians.md b/docs/group-wallet-guardians.md
index 7195d032..a1de6b18 100644
--- a/docs/group-wallet-guardians.md
+++ b/docs/group-wallet-guardians.md
@@ -453,7 +453,8 @@ the group does not un-know a key*, inherited one level down.
**It does not tell the child before it happens**, and it does not constrain where
the coins go. "Only back into the child, at a new address" is a covenant, and
there is none on mainnet to write it with (`OP_CHECKTEMPLATEVERIFY`,
-`OP_VAULT`).
+`OP_VAULT`). The other direction is supported: an ancestor paying coins *into*
+a guarded wallet is [guarded-wallet-funding.md](./guarded-wallet-funding.md).
## Appendix — what was considered and rejected
diff --git a/docs/guarded-wallet-funding.md b/docs/guarded-wallet-funding.md
new file mode 100644
index 00000000..4269b4bb
--- /dev/null
+++ b/docs/guarded-wallet-funding.md
@@ -0,0 +1,534 @@
+# Funding a guarded wallet: a group paying into a descendant's wallet
+
+An ancestor group can already *take* from a descendant's guarded wallet. This
+plan is about the other direction: **the group pays coins from its own wallet
+into the descendant's guarded wallet, using an address its own devices derive
+and every signer checks.** It is a send from the group's wallet with the
+destination filled in, as the request guessed. What the request did not settle
+is what that destination should be, how a signer can tell it is really the
+descendant's address and not one the proposer typed, and how the guarded
+wallet row on the wallet screen fits a second button. This plan answers those
+three.
+
+Read [group-wallet-guardians.md](./group-wallet-guardians.md),
+[group-send-an-amount.md](./group-send-an-amount.md) and
+[group-wallet-addresses.md](./group-wallet-addresses.md) first. This plan uses
+the forwarded statement from the first, the send form and its reservations from
+the second, and the "current plus two" rule from the third. It changes no
+format, no derivation and no schema.
+
+**Built**, phases 1-6, one commit each, written against the code as it stood
+at `8cb6f04e`, schema v29, with the `lightning-kmp-app` submodule at `e0d2b82`;
+the build changes no schema. `GroupWalletState.fundingAddress`,
+`GroupSpendBuilder.Destination.Funding`, `GroupSpend.fundingsOf` and
+`GroupSendRoute.fundChatRoomId` are the entry points. The phases below are kept
+as written; where the build chose differently the table says so.
+
+| what the plan said | what it turned out to be |
+|---|---|
+| Phase 1 tests `claimedFundingIndices` | Phase 2 does: until the builder writes a claim there is no PSBT to read one from. Phase 1's watched-window test also counts the slots, eight, so the bound and the look-ahead cannot drift apart unnoticed |
+| Phase 2: `send` and `sendAll` take a destination rather than an address string | both, as overloads: the string versions build a `Destination.Address` and call through, so the thirty-odd existing call sites, most of them tests, did not change. The claim always goes on output 0, where both builders put the payment |
+| Phase 3: the check runs in `acceptSpendProposal` and `checkedSpend` | and in `proposeSpend` and `proposeGuardianSpend`, so a proposal every other device would refuse is refused before it is sent. It is one extension, `GroupSpend.Result.withFundings`, and a spend none of whose payments claims anything reads no guarded wallets at all |
+| nothing about bumping | `GroupSpendBuilder.bump` rebuilt the PSBT without the claim, so a bumped funding would have read as a payment to a bare address and released its index. It carries `Checked.fundings` across |
+| Phase 3's test is in the shape of `GuardianSpendRoundTest` | it is three tests in `GuardianSigningJvmTest`, which already holds an ancestor, a guarded child and the forwarding. The refusal test has the lie proposed by a device never told about the wallet -- the realistic way one arrives, since a device that holds the wallet refuses to propose it |
+| Phase 4: the card says *To* and then the wallet's name | *To* and then *Savings's guarded wallet*. The title already says *Fund …*, and the card repeating it read twice. The index uses the address list's own *Address %1$s* |
+| Phase 4: `MiddleEllipsis` on the address | as written, and on the desktop target it ellipsises at the end, as the address list does there |
+| Phase 5: the name stays on one line | two: at 200% text a one-line name was cut to a word, and the name is what says which wallet the buttons act on |
+| Phase 5: a `GroupWalletViewModelJvmTest` case for `arriving` | `GuardedWalletRowTest` in commonTest, since `arriving` is a property of the row and needs no view model; and `GuardedWalletCardJvmTest` renders the card, including at twice the text size |
+
+Still to do by hand: the signet funding between two real devices that the end
+of Phase 6 asks for.
+
+The headline: **the group already watches every guarded wallet below it, so its
+devices already know which of that wallet's receive addresses are unused. A
+funding spend pays the first unreserved address from `current + 2` upward, and
+the PSBT output carries that address's derivation under the descendant's
+account, the same field change already uses. Every signer derives that address
+again from the forwarded statement it already holds, and then shows the spend as
+*Fund Thandi's group's guarded wallet* rather than as a bare address. If the
+derivation does not reach the address, the signer refuses the spend.**
+
+---
+
+## What is already there
+
+Funding needs no new knowledge, because the ancestor already has it:
+
+| what funding needs | where it already is |
+|---|---|
+| the descendant's account xpub and script tree | the forwarded guarded statement, checked by `GuardianManager.verify` and listed by `guardedWalletsOf` |
+| which of its receive addresses are used | `GroupWalletViewModel` already subscribes to `wallets.walletFor(guarded.account)` for every guarded row; `GroupWalletState.receiveAddresses` reads that state |
+| coins to send, change, reservations, the mainnet cap | `GroupSendViewModel` and `GroupSpendBuilder`, unchanged for the room's own wallet |
+| a place in the PSBT to say *this output is under that account at that index* | `taprootDerivationPaths` on an output, which `GroupSpend.psbtOf` already writes for change |
+| a signer who rebuilds a claim rather than trusting it | `GroupSpend.check`, step 5: change is change only if it derives |
+
+So the work is: choosing the address, writing the claim, checking it, and
+showing it. There is no protocol work.
+
+---
+
+## Phase 0 — decisions, before any code
+
+Seven, each with a recommendation. The phases assume the recommended answer.
+
+### D1. Pre-fill the address field, or replace it?
+
+**Recommended: replace it with a fixed destination card.** The request guessed
+"pre-fill the spend screen", and that is close. But an editable field that
+starts with the descendant's address and can then be changed makes the title
+(*Fund X's guarded wallet*) a claim the form cannot keep. A member who wants to
+send somewhere else already has *Send*. In fund mode the form shows:
+
+```
+┌──────────────────────────────────────────────┐
+│ To Thandi's group's guarded wallet │
+│ bc1p8q…x7kd · address 5 │
+│ │
+│ This group can spend these coins again once │
+│ they have 12 confirmations. │
+└──────────────────────────────────────────────┘
+ Send everything ( )
+ Amount in sats [ ] sats
+ Feerate in sats per byte [ ]
+ Sends 50,000 sats to Thandi's group's
+ guarded wallet with a fee of 420 sats
+ [ Ask the group to send ]
+```
+
+The amount, feerate, send-everything and preview all work as they do now.
+
+### D2. Which address?
+
+**Recommended: the lowest index from `current + ADDRESSES_AHEAD` upward that no
+open spend in this room already pays, and below `current + RECEIVE_LOOKAHEAD`.**
+
+- **Not `current`.** The child's own members are handing out `current` to their
+ own payers right now; that is the reason the address list exists. Every
+ device computes the same `current`, the ancestor's included, so funding to it
+ is the address-reuse hazard
+ [group-wallet-addresses.md](./group-wallet-addresses.md#the-bound) describes,
+ caused by an ancestor this time.
+- **From `current + 2` upward.** The child's members start at `current` and go
+ up through the next two. Starting the ancestor at the top of that window and
+ going higher keeps the two sides out of each other's way. Only one index is
+ shared (`current + 2`), and only when a third child member is handing out
+ addresses at the same moment.
+- **Reserved like change.** Until the funding confirms, its address still reads
+ as unused, so a second funding proposal would pick the same address. Open
+ spends' claimed funding indices are held exactly as
+ `reservedChangeIndices` holds change (Phase 3).
+- **Bounded by the look-ahead.** The child watches `current … current + 9`. An
+ address past that would be paid and the child would not see it until its own
+ look-ahead caught up. With eight slots (`current + 2 … current + 9`), a
+ room with that many open fundings into one wallet is told to wait, the way
+ `TooManyOpen` already handles change.
+
+### D3. How does the proposal say where the money goes?
+
+**Recommended: in the PSBT, as the output's `tap_bip32_derivation` under the
+descendant's account fingerprint, with no new nostr tag.** That is the field a
+change output already carries, read with the same code, and it is where
+[the guardian spend chose to put its claim](./group-wallet-guardians.md)
+for the same reason: a second place to say it would be a second thing to
+disagree. An old client's `check` sees a derivation whose fingerprint is not its
+account's, treats the output as a plain payment, and shows the address, which is
+the right thing for an old client to do.
+
+### D4. What does a signer do with the claim?
+
+**Recommended: one rule for each of three cases.**
+
+| the output's claim | the signer's device | result |
+|---|---|---|
+| a fingerprint of a guarded wallet it holds, at an index that derives to this output's script | shows *Fund X's guarded wallet* | signed as usual |
+| a fingerprint of a guarded wallet it holds, at an index that does **not** derive to the script | refuses the proposal before it is shown | the same refusal step 5 gives a change claim that does not derive |
+| a fingerprint it does not recognise (no forwarded statement on this device, or a wallet it never verified) | ignores the claim and shows the bare address | as today |
+
+The second row is what makes the label safe: no proposer can put a friendly
+name on a payment to an address the descendant does not own. The third row
+means a member who never got the forwarded statement still sees the truth,
+just less of it.
+
+### D5. A rollout gate?
+
+**Recommended: none.** A funding spend is a send from the group's own wallet to
+an address, and it is already held to `GroupWalletRollout.MAINNET_CAP`. A
+mixed-version group loses nothing: old signers see a payment to an address,
+which is exactly what it is.
+
+### D6. What can be funded, and from what?
+
+**Recommended: only guarded wallets of groups below this one that this room
+holds a verified statement for, and only from the room's own wallet.**
+
+- Unguarded subgroups: no. Their statements are never forwarded upward, so the
+ ancestor has no xpub to derive an address from. *What is left* covers this.
+- Siblings, ancestors, unrelated groups: no. There is no statement for them in
+ this room, and *Send* with a pasted address works.
+- From a guarded wallet into another guarded wallet (a guardian moving coins
+ between two descendants): no. `GroupSendRoute` already uses
+ `guardedChatRoomId` to mean the *source*. A route naming both a source and a
+ destination is refused (Phase 4). Rebalancing is its own decision.
+
+### D7. Does the child learn who paid it?
+
+**Recommended: not in this plan.** The child sees a coin arrive at an address it
+did not hand out, on its address list as *Paid · 50,000 sats*. Saying *from the
+parent* means sending a notice down the hierarchy, which no flow does today.
+Only a member who sits in both rooms could carry it, and the child could verify
+only that the transaction pays its own address, not who funded it. *What is
+left* has the shape of it.
+
+---
+
+## Phase 1 — choosing the address, pure
+
+**Half a day, most of it tests.**
+
+In `wallet/GroupOnchainWallet.kt`, beside `receiveAddresses`:
+
+```kotlin
+/**
+ * The receive address an ancestor pays when it funds this wallet: the lowest
+ * unused index from [GroupOnchainWallet.ADDRESSES_AHEAD] past the current one
+ * that [reserved] does not already hold, and that the wallet still watches --
+ * or null before Electrum has answered, and when every such index is held.
+ * See `docs/guarded-wallet-funding.md`, D2.
+ */
+fun fundingAddress(reserved: Set): GroupAddress?
+```
+
+It reads the same `current` as `receiveAddresses`, so the two never disagree,
+and it skips any index that is already `alreadyUsed` (the gap rule from the
+address note: a watch-only wallet may have been paid above `current`).
+
+In `wallet/GroupSpend.kt`, beside `claimedChangeIndices`:
+
+```kotlin
+/** The receive indices under [account] that [psbt]'s outputs claim to fund. Claims, not checks, as for change. */
+fun claimedFundingIndices(psbt: Psbt, account: GroupWalletDerivation.Account): Set
+```
+
+**Tests**, in `GroupOnchainWalletJvmTest` against `FakeElectrum`:
+
+- a fresh wallet funds `/0/2`;
+- with `/0/2` reserved it funds `/0/3`; with `/0/2 … /0/9` reserved it returns null;
+- paying `/0/0` moves the funding address to `/0/3`;
+- a payment to `/0/4` while `/0/0` is current is skipped: `/0/2`, then `/0/3`, then `/0/5`;
+- the address is null until Electrum has answered, as `receiveAddress` is;
+- every index returned is one `receive.addresses` has generated. This fails if
+ the bound and the look-ahead ever drift apart.
+
+---
+
+## Phase 2 — the builder writes the claim
+
+**Half a day.**
+
+`GroupSpendBuilder.send` and `sendAll` take a destination rather than an
+address string:
+
+```kotlin
+sealed interface Destination {
+ /** What the member typed: whatever it is, it is not the group's to vouch for. */
+ data class Address(val address: String) : Destination
+ /** A descendant's guarded wallet, at the receive address Phase 1 chose. */
+ data class Funding(val account: GroupWalletDerivation.Account, val derived: GroupWalletDerivation.Derived) : Destination
+}
+```
+
+`Funding` pays `derived.pubkeyScript`, the guarded address with its tree. There
+is no string round trip, so `NotAnAddress` cannot happen for it.
+`GroupSpend.psbtOf` gains a `funding: Map>` beside
+`change`, and writes each one with `pathOf(derived, descendantAccount)`. This
+is the same call change uses, with the descendant's fingerprint instead of the
+room's. `Built` gains `funded: Funding?` so the preview can say where it goes.
+
+**Tests**, in `commonTest` beside the builder's existing ones:
+
+- a funding output's derivation survives `Psbt.write` / `Psbt.read` with its
+ fingerprint intact, for a fingerprint whose top bit is set. This is the
+ unsigned-read bug the guardians note fixed, checked again on a new field;
+- `GroupSpend.check` against the room's own account accepts the PSBT and lists
+ the funding output among `payments`, not as change;
+- a `send` to a typed address builds exactly the PSBT it built before.
+
+---
+
+## Phase 3 — every signer checks the claim, and says it
+
+**A day and a half.** This is the phase that makes the label safe, so it lands
+before any button that produces one.
+
+**The check.** A pure function in `GroupSpend`, separate from `check` so that
+`check` stays about the room's own account:
+
+```kotlin
+data class Funding(val outputIndex: Int, val wallet: GuardianManager.GuardedWallet, val derived: GroupWalletDerivation.Derived)
+
+sealed interface FundingReading {
+ data class Ok(val fundings: List) : FundingReading
+ data class Refused(val reason: String) : FundingReading
+}
+
+/** D4's three rows, over [checked]'s payments, against the guarded wallets this room holds. */
+fun fundingsOf(checked: Checked, guarded: List): FundingReading
+```
+
+Fingerprints are four bytes, so two held wallets can share one. Every wallet
+with a matching fingerprint is tried, and the claim is refused only if none of
+them derives to the script.
+
+**Where it runs:**
+
+- `FrostSigningManager.acceptSpendProposal`, straight after `GroupSpend.check`.
+ A `Refused` drops the proposal with the reason logged, as a failed `check`
+ does. Guardian spends (`spender is Guardian`) are checked too, since a
+ guardian could pay one descendant from another's coins once D6 is revisited.
+- `FrostSigningManager.checkedSpend`, so the approval screen and the proposal
+ list read the same answer. `Checked` gains `fundings: List =
+ emptyList()`, filled here rather than in `check`.
+- `FrostSigningManager.reservedFundingIndices(database, chatRoomId, account)`,
+ over `openSpends` like `reservedChangeIndices`, with a
+ `FrostSigningRepository` method for the form.
+
+**What it says.** `ProposedSpend.summarize` reads `spend.fundings`:
+
+| spend | label | detail |
+|---|---|---|
+| one payment, a funding | *Fund Thandi's group's guarded wallet* | *Send 50,000 sats to Thandi's group's guarded wallet, address 5* |
+| several payments, one a funding | *Spend from the group's wallet* | *Send 70,000 sats to 2 addresses, 50,000 of them to Thandi's group's guarded wallet* |
+| no funding | unchanged | unchanged |
+
+That one function feeds the signing screen, the room's proposal list
+(`ProposalListViewModel`) and the wallet screen's *Spends* rows
+(`SpendRowCard`), so all three change together. A name is the descendant's
+certified name, `GuardedWallet.name`, falling back to *a subgroup* as the
+guardian spend's label does.
+
+**Tests**, a jvmTest in the shape of `GuardianSpendRoundTest`, with a parent
+and child ceremony and the child's statement forwarded:
+
+- a true claim is accepted and summarised as *Fund … guarded wallet*;
+- a claim at the wrong index is refused at `acceptSpendProposal`, and no session
+ is written;
+- the same PSBT read by a member whose device holds no forwarded statement is
+ accepted and shown as a bare address;
+- an open funding's index is reserved, and a failed one's is released.
+
+---
+
+## Phase 4 — the form in fund mode
+
+**A day.**
+
+**The route.** `GroupSendRoute` gains `fundChatRoomId: String? = null`: the
+descendant whose guarded wallet this send pays. It is a second field, not a
+second meaning for `guardedChatRoomId`, which names where coins come *from*. A
+route with both set is `GroupSendUIState.Unavailable` (D6).
+
+**The view model.** `GroupSendViewModel.initiate` finds the guarded wallet the
+same way it already does for a guardian spend
+(`chatRepository.guardedWallets(chatRoomId)`, matched on room and chain). The
+wallet being spent is still the room's own. `Ready` gains:
+
+```kotlin
+/** The descendant's guarded wallet this send pays, with where it is up to -- or null for a send to a typed address. */
+val funding: FundingTarget? = null
+
+data class FundingTarget(
+ val wallet: GuardianManager.GuardedWallet,
+ val walletState: GroupWalletState?,
+ val reserved: Set,
+) {
+ val address: GroupAddress? get() = walletState?.fundingAddress(reserved)
+}
+```
+
+`follow` combines a third flow, `wallets.walletFor(guarded.account).state`,
+with the two it already has, and re-reads `reservedFundingIndices` whenever
+the room's transactions change. If somebody pays the chosen address while the
+form is open, the next emission moves the destination to the next index, and
+the preview follows. That is why the card shows the index: a member who sees it
+change knows why. `preview()` builds with `Destination.Funding` when `funding`
+is set, and returns null while its address is null.
+
+**The screen** (`GroupSendScreen`):
+
+- the title becomes *Fund %1$s's guarded wallet*, beside the existing guardian
+ title, for the same reason that one is there: the title is where the form says
+ whose money moves where;
+- `OutlinedTextField(addressField)` is replaced by the destination card from
+ D1: an `OutlinedCard` with *To* in `labelMedium`, the wallet's name in
+ `titleMedium`, the address in the monospace style with
+ `TextOverflow.MiddleEllipsis` and *address %1$d*, and under it, in
+ `bodyMedium`/`onSurfaceVariant`, *This group can spend these coins again once
+ they have %1$d confirmations.* with `ANCESTOR_DELAY`. That sentence answers
+ the request's last question: what is worth saying while funding a guarded
+ wallet is that the money stays within the group's reach;
+- while the address is null, a `LoadingDataIndicator(fillScreen = false)` with
+ *Finding an address in %1$s's wallet…* in the card's place, and a null address
+ once Electrum has answered (D2's eight slots all held) shows *Wait for this
+ group's open payments to %1$s to confirm* in `error`;
+- `SendPreview` says *Sends %1$s sats to %2$s's guarded wallet with a fee of
+ %3$s sats* for a funding;
+- the propose button is unchanged and calls `proposeSpend`, because this is the
+ room's own spend.
+
+**Tests**, in `GroupSendViewModelJvmTest`, with `follow` and the fake chain:
+
+- the preview builds to `/0/2` of the descendant's account, with the claim;
+- an open funding at `/0/2` makes the next one go to `/0/3`;
+- paying `/0/2` while the form is open moves it to `/0/3`;
+- both `guardedChatRoomId` and `fundChatRoomId` set gives `Unavailable`.
+
+---
+
+## Phase 5 — *Fund* on the wallet screen, without crowding the row
+
+**A day.**
+
+**Where the button goes.** On each row of the *Guarded wallets* section
+(`guardianItems` in `GroupWalletScreen.kt`), next to *Spend*, as the request
+asks. Today the row is a `ListItem` with *Spend* as a `TextButton` in
+`trailingContent`. A second button there would squeeze the headline (the
+group's name, already ellipsised), and at large text sizes the two buttons
+would leave the name a few characters. So the actions move out of the trailing
+slot and below the content, in the row's own card:
+
+```
+ today after
+┌─────────────────────────────────────┐ ┌─────────────────────────────────────┐
+│ ▣ Thandi's group's… [ Spend ] │ │ ▣ Thandi's group's savings │
+│ 12,000 sats within this group's… │ │ 12,000 sats within this group's │
+└─────────────────────────────────────┘ │ reach · 50,000 sats arriving │
+ │ [ Fund ] [ Spend ]│
+ └─────────────────────────────────────┘
+```
+
+- **An `OutlinedCard` per guarded wallet**, holding the existing `ListItem`
+ (with no `trailingContent`) and then the actions. A card is how M3 groups
+ content with the actions that apply to it. With several wallets listed, a bare
+ row of buttons under each `ListItem` would leave it unclear which wallet a
+ button belongs to.
+- **The actions in a `FlowRow`**, aligned to the end with
+ `Arrangement.spacedBy(MaterialTheme.spacing.targetGap, Alignment.End)`, so at
+ 200% text the two buttons wrap onto two lines instead of truncating. This is
+ `SpendRowCard`'s *Send again* / *Bump the fee* row, with wrapping added.
+ `FlowRow` is new to this codebase. It is in `foundation.layout`, and the audit
+ counts it as neither spacing nor a dimension.
+- **Both `TextButton`s**, equal weight: neither is the obvious primary action
+ for every wallet, and a filled *Fund* would read as a recommendation. *Fund*
+ first and *Spend* second, so money in reads before money out.
+- **Each button names its wallet to a screen reader.** Two rows of *Fund* /
+ *Spend* are four identical labels when read without the layout. Each gets
+ `Modifier.semantics { contentDescription = … }` with *Fund %1$s's guarded
+ wallet* / *Spend from %1$s's guarded wallet*. The second string already
+ exists. This fixes the *Spend* button as it is today too.
+- **Each button has its own gate**, so a row can show either one alone. *Fund*
+ appears only in the `Loaded` state (the room has a wallet of its own to pay
+ from), behind `canSign && canWatch`, the same gates as the room's *Send*.
+ The `NotOpened` branch passes `onFund = null`, because a group with no wallet
+ has nothing to fund with. *Spend* keeps the gates it has.
+- **What is arriving.** After a funding, `withinReach` stays the same for two
+ hours, which looks like the money vanished. `GuardedWalletRow` gains
+ `arriving: Satoshi?`: coins in the wallet with fewer than `ANCESTOR_DELAY`
+ confirmations. The supporting line adds *· %1$s sats arriving* when it is
+ non-zero. It counts every such coin, not only this group's funding. That is
+ true, and it is all the ancestor can know.
+
+`toGuardianFund` sits beside `toGuardianSpend` in `GroupWalletScreen` and
+navigates to `GroupSendRoute(…, fundChatRoomId = row.wallet.descendantChatRoomId)`.
+
+**Strings**, sentence case, in the guardian block of `strings.xml`: `fund`,
+`fund_s_s_guarded_wallet`, `to`, `address_d`,
+`this_group_can_spend_these_coins_again_once_they_have_d_confirmations`,
+`finding_an_address_in_s_s_wallet`, `wait_for_this_group_s_open_payments_to_s_to_confirm`,
+`sends_s_sats_to_s_s_guarded_wallet_with_a_fee_of_s_sats`, `s_sats_arriving`.
+Apostrophes are written plain, as `spend_from_s_s_guarded_wallet` is, because
+Compose Resources does not unescape `\'`.
+
+**Tests**: a `GroupWalletViewModelJvmTest` case that `arriving` counts an
+unconfirmed coin and drops it at 12 confirmations. The layout is checked by
+`m3Audit`, which has to stay at 0 on every budget, and by looking at it at
+compact width and at 200% text.
+
+---
+
+## Phase 6 — the notes
+
+**An hour.**
+
+- This note becomes **Built**, with a table of where the build chose
+ differently.
+- A row in [README.md](./README.md), and a sentence in its reading order after
+ the guardians and policy notes.
+- [group-wallet-guardians.md](./group-wallet-guardians.md)'s *What this does not
+ do* says guardians cannot constrain where coins go. It gains a line pointing
+ here for the direction that is supported: coins coming in.
+- [group-wallet-addresses.md](./group-wallet-addresses.md)'s *Why `+ 2`* gains a
+ sentence: an ancestor funding the wallet starts at the top of that window
+ and goes up.
+
+Each phase is one commit, checked with
+`./gradlew :composeApp:m3Audit` and
+`./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest`. Before
+Phase 6's status line says built, a funding should be made by hand on signet
+between two real devices, one in each room, and the child's address list
+checked to show it at `current + 2`.
+
+---
+
+## What this does not do
+
+**It does not fund an unguarded subgroup.** The parent has no xpub for it. The
+child could forward its plain statement upward the way a guarded one is, but
+that gives the parent a full view of a wallet whose point is that the parent
+has no part in it, so it is a decision of its own.
+
+**It does not fund a subgroup that has not opened a wallet.** There is no
+statement and so no address. The guarded row only exists once one is forwarded.
+
+**It does not tell the child who paid.** See D7.
+
+**It does not stop the child spending the coins at once.** Funding is a gift
+into a wallet whose own quorum holds the key path. The 12-block delay is on the
+ancestor's leaf, not the child's key. The destination card says what the
+ancestor keeps (a way back after 12 confirmations), and it says nothing that
+suggests the coins are locked for the child.
+
+**It does not make the address private from the child's members.** It is one of
+the child's own addresses. They see the payment and its amount, and anyone in
+both rooms can match it to the parent's spend.
+
+---
+
+## What is left, when someone wants it
+
+- **A notice to the child.** A member in both rooms, on seeing a funding of this
+ room confirm, posts a transcript line in the child's room: *Parent group sent
+ 50,000 sats to this wallet*. The child's devices check that the transaction
+ pays one of their addresses, and attribute it to the member who posted it,
+ since the child cannot check that the parent sent it. This is the reverse of
+ the upward forwarding, and it needs the same overlap one level at a time.
+- **Funding an unguarded child**, behind the decision in *What this does not do*.
+- **Moving coins between two guarded descendants** in one guardian spend: a
+ source and a destination on one route, D6's third bullet.
+- **A guarded wallet's own screen**, reached by tapping its card, with its
+ coins, its address list and both actions. The card's two buttons are enough
+ for now. A third action would be the time to build it.
+
+---
+
+## Appendix — what was considered and rejected
+
+| idea | why not |
+|---|---|
+| pre-fill the address field and leave it editable | the label would be a claim the form cannot keep; *Send* is already there for any other address (D1) |
+| fund `current` | it is the address the child's own members are handing out (D2) |
+| a nostr tag `["funds", , ]` on the proposal | the PSBT already has a field for *this output is under that account*, read by code that exists; a second place would be a second thing to disagree (D3) |
+| recognise a funding by scanning every payment against the descendant's addresses, with no claim | it costs a derivation per address per output per signer, it misses an address past the window, and it would quietly label a typed address that happens to be the child's. The claim states what the proposer meant, and the signer checks it |
+| refuse a claim the signer cannot verify | it would make a funding unsignable by every member who missed the forwarded statement, for no safety gain: the bare address is the truth (D4) |
+| *Fund* in an overflow menu on the row | it hides the one action this plan adds, behind an icon whose meaning nobody can guess; there are only two actions |
+| *Fund* in the trailing slot beside *Spend* | the name, the only thing that says which wallet a row is, shrinks to a few characters at large text sizes |
+| *Fund* as a filled button | neither action is the one every member wants; a filled button would be a recommendation the app cannot make |