feat(wallet): a subgroup's transcript names the guardian that spent from it (Phase 8)

Whenever a guarded wallet's coins change, the wallet screen reads every used
address's history off Electrum, recognises a guardian's leaf in the witness
that spent a coin, and writes one transcript line per transaction saying
which group above took how much -- the child's only notice, since nobody in
its room signed it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-10-23 15:40:43 +02:00
1 parent 00df58c1f3
commit 2b44ebcbbc
9 files changed
+320 -1

No files matched your search

@@ -507,6 +507,13 @@ data class ChatMessage(
*/
const val TYPE_GUARDED_WALLET_SHARED = "guardedWalletShared"
/**
* One of this group's guardians spent from its guarded wallet through its
* leaf. Read off the chain by `GuardianManager.takenIn`, and the child's
* only notice of it: nobody in this room signed it.
*/
const val TYPE_GUARDIAN_SPEND = "guardianSpend"
val GROUP_IDENTITY_TYPES = setOf(
TYPE_GROUP_PROFILE_SIGNED,
TYPE_GROUP_RELAYS_SIGNED,
@@ -516,6 +523,7 @@ data class ChatMessage(
TYPE_GROUP_WALLET_OPENED,
TYPE_GROUP_TRANSACTION_CONFIRMED,
TYPE_GUARDED_WALLET_SHARED,
TYPE_GUARDIAN_SPEND,
)
/**
@@ -230,6 +230,13 @@ class DatabaseChatRepository(
0
}
override suspend fun recordGuardianSpends(chatRoomId: String, taken: List<GuardianManager.Taken>): Int = try {
GuardianManager.recordTaken(database, chatRoomId, taken)
} catch (e: Throwable) {
logger.e("Error recording guardian spends from $chatRoomId's wallet", e)
0
}
override suspend fun groupSignedEvent(chatRoomId: String, id: HexKey): GroupSignedEvent? = try {
database.groupSignedEventDao().getById(id)?.takeIf { it.chatRoomId == chatRoomId }
} catch (e: Throwable) {
@@ -2,6 +2,7 @@ package com.machankura.bennu.compose.managers
import co.touchlab.kermit.Logger
import com.machankura.bennu.compose.database.BennuDatabase
import com.machankura.bennu.compose.database.model.ChatMessage
import com.machankura.bennu.compose.database.model.MarmotInnerEvent
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.nostr.frost.GroupKeyStateEvent
@@ -13,6 +14,12 @@ import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.nip01Core.crypto.EventHasher
import fr.acinq.bitcoin.Chain
import fr.acinq.bitcoin.OutPoint
import fr.acinq.bitcoin.Satoshi
import fr.acinq.bitcoin.Transaction
import fr.acinq.bitcoin.TxId
import fr.acinq.bitcoin.TxOut
import fr.acinq.lightning.utils.sum
import kotlin.time.Clock
import kotlin.time.Instant
@@ -233,6 +240,79 @@ object GuardianManager {
return rooms.size
}
/** Coins of a guarded wallet one of its guardians took, in one transaction. */
data class Taken(
val txid: TxId,
val guardian: GuardianDerivation.Guardian,
val amount: Satoshi,
)
/**
* Which guardians of [account] took which of [coins] in [spending] -- one
* entry per guardian -- read off the witnesses alone.
*
* A guardian's input carries three things: a signature, a leaf, and the
* control block proving the leaf is in the address. The leaf is matched
* against the guardian leaves of the address the coin was at, so a leaf is
* named only by a guardian whose key it is; anything else -- the wallet's own
* key-path spend, a witness of another shape -- names nobody.
*/
fun takenIn(
spending: Transaction,
account: GroupWalletDerivation.Account,
coins: Map<OutPoint, Pair<TxOut, GroupWalletDerivation.Derived>>,
): List<Taken> {
if (!account.isGuarded) return emptyList()
return spending.txIn.mapNotNull { input ->
val (txOut, derivation) = coins[input.outPoint] ?: return@mapNotNull null
val stack = input.witness.stack.takeIf { it.size == 3 } ?: return@mapNotNull null
val leaves = GuardianDerivation.leaves(account.guardians, account.chain, account.account, derivation.change, derivation.index)
val position = leaves.indexOfFirst { it.script == stack[1] }.takeIf { it >= 0 } ?: return@mapNotNull null
account.guardians[position] to txOut.amount
}
.groupBy({ it.first }, { it.second })
.map { (guardian, amounts) -> Taken(spending.txid, guardian, amounts.sum()) }
}
/**
* Writes a transcript line in [chatRoomId] for each of [taken] it has no line
* for yet. Returns how many it wrote.
*
* The whole of the child's notice that an ancestor spent from its wallet --
* there is no channel from the ancestor's room into this one -- so it is
* written by whichever device reads the chain first, and every device that
* reads it afterwards finds it already there.
*/
suspend fun recordTaken(database: BennuDatabase, chatRoomId: String, taken: List<Taken>): Int {
val written = database.chatMessageDao().getChatMessagesByChatRoomId(chatRoomId)
.map { it.chatMessage }
.filter { it.messageType == ChatMessage.TYPE_GUARDIAN_SPEND }
.map { it.content }
val fresh = taken.filter { spend -> written.none { it.contains(spend.txid.toString()) } }
fresh.forEach { spend ->
val name = database.chatRoomDao().findChatRoomById(spend.guardian.chatRoomId)?.chatRoom?.subject
?.takeIf { it.isNotBlank() }
?: "A group above this one"
database.chatMessageDao().upsert(
ChatMessage(
senderPublicKey = spend.guardian.chatRoomId,
isUserMessage = false,
giftWrapPayloadId = null,
marmotGroupEventId = null,
marmotInnerEventId = null,
chatRoomId = chatRoomId,
content = "$name took ${spend.amount.sat} sats from this wallet through its guardian leaf, " +
"in transaction ${spend.txid}.",
messageType = ChatMessage.TYPE_GUARDIAN_SPEND,
)
)
logger.i("${spend.guardian.chatRoomId} took ${spend.amount.sat} sats from $chatRoomId's guarded wallet in ${spend.txid}")
}
return fresh.size
}
/**
* What a notice that arrived in [chatRoomId] says, for its transcript line --
* or null when it is not one this room can believe, which gets no line: a
@@ -137,6 +137,9 @@ interface ChatRepository {
/** Tells the groups in [shareable] about its statement, as [userPublicKey]. Returns how many were told. */
suspend fun shareGuardedWallet(shareable: GuardianManager.Shareable, userPublicKey: HexKey): Int
/** Writes a transcript line for each guardian spend from this group's wallet it has none for yet. */
suspend fun recordGuardianSpends(chatRoomId: String, taken: List<GuardianManager.Taken>): Int
/**
* The kind:1s this group signed, newest first.
*
@@ -413,6 +416,11 @@ interface ChatRepository {
userPublicKey: HexKey
): Int = 0
override suspend fun recordGuardianSpends(
chatRoomId: String,
taken: List<GuardianManager.Taken>
): Int = 0
override suspend fun groupPosts(chatRoomId: String): List<GroupPost> = emptyList()
override suspend fun groupSignedEvent(
@@ -13,6 +13,8 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.distinctUntilChangedBy
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
@@ -116,6 +118,7 @@ class GroupWalletViewModel(
// state: any of them changing redraws the screen, and none may
// overwrite another.
val chainState = wallets?.walletFor(wallet.account)?.state ?: flowOf(null)
noticeGuardianSpends(wallet.account)
watching = viewModelScope.launch(Dispatchers.IO) {
combine(
chainState,
@@ -142,6 +145,26 @@ class GroupWalletViewModel(
return combine(states) { it.toList() }
}
private var noticing: Job? = null
/**
* For a guarded wallet: each time its coins change, reads the chain for
* spends a guardian made from it and writes the transcript line for any that
* has none -- the group's only notice, since nobody in it signed them.
*/
private suspend fun noticeGuardianSpends(account: GroupWalletDerivation.Account) {
val wallets = wallets ?: return
if (!account.isGuarded) return
val onchain = wallets.walletFor(account)
noticing?.cancel()
noticing = viewModelScope.launch(Dispatchers.IO) {
onchain.state
.distinctUntilChangedBy { state -> state.utxos.map { it.utxo.outPoint }.toSet() }
.collect { state -> chatRepository.recordGuardianSpends(chatRoomId, wallets.guardianSpends(state)) }
}
}
/**
* Tells the groups above about [shareable]'s guarded wallet: one notice into
* each of their rooms this device is in. What is told stays told, so the
@@ -1,6 +1,12 @@
package com.machankura.bennu.compose.wallet
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import com.machankura.bennu.compose.managers.GuardianManager
import fr.acinq.bitcoin.Crypto
import fr.acinq.bitcoin.OutPoint
import fr.acinq.bitcoin.Transaction
import fr.acinq.bitcoin.TxId
import fr.acinq.bitcoin.byteVector32
import fr.acinq.lightning.blockchain.electrum.IElectrumClient
import fr.acinq.lightning.blockchain.fee.FeeratePerByte
import kotlinx.coroutines.CoroutineScope
@@ -42,6 +48,48 @@ class GroupOnchainWallets(
suspend fun suggestedFeeratePerVbyte(): Long? =
electrum.estimateFees(6)?.let { FeeratePerByte(it).feerate.sat }?.coerceAtLeast(1)
/** Transactions fetched for [guardianSpends], which never change once mined or seen. */
private val transactions = mutableMapOf<TxId, Transaction>()
/**
* Every spend a guardian of [state]'s account made from it, read off the
* history of each address the wallet has used. Empty for an unguarded
* account, and for whatever Electrum cannot answer right now -- the next look
* asks again.
*
* History rather than a watch on coins disappearing: a device asleep when the
* coin moved still finds it, since the chain keeps the record and nothing
* here has to have been running at the time.
*/
suspend fun guardianSpends(state: GroupWalletState): List<GuardianManager.Taken> {
val account = state.account
if (!account.isGuarded) return emptyList()
val used = listOf(GroupWalletDerivation.RECEIVE to state.receive, GroupWalletDerivation.CHANGE to state.change)
.flatMap { (branch, wallet) ->
wallet.addresses.values.filter { it.alreadyUsed }.mapNotNull { address ->
address.meta.indexOrNull?.let { GroupWalletDerivation.derive(account, branch, it.toLong()) }
}
}
val ours = used.associateBy { it.pubkeyScript }
val history = used.flatMap { derived ->
runCatching { electrum.getScriptHashHistory(Crypto.sha256(derived.pubkeyScript).byteVector32().reversed()) }
.getOrDefault(emptyList())
.map { it.txid }
}.distinct().mapNotNull { txid -> transactionOf(txid) }
val coins = history.flatMap { tx ->
tx.txOut.mapIndexedNotNull { index, out -> ours[out.publicKeyScript]?.let { OutPoint(tx, index.toLong()) to (out to it) } }
}.toMap()
return history.flatMap { GuardianManager.takenIn(it, account, coins) }
}
private suspend fun transactionOf(txid: TxId): Transaction? =
mutex.withLock { transactions[txid] }
?: runCatching { electrum.getTx(txid) }.getOrNull()?.also { tx -> mutex.withLock { transactions[txid] = tx } }
suspend fun stop() = mutex.withLock {
wallets.values.forEach { it.stop() }
wallets.clear()