From 4ab47ba4322e00ee3df15a393513eb249ba5797a Mon Sep 17 00:00:00 2001 From: Kgothatso Ngako Date: Fri, 23 Oct 2026 08:05:28 +0200 Subject: [PATCH] feat(wallet): watch a group's wallet on the identity's Electrum client (Phase 4) GroupChainWallet is Phoenix's FinalWallet for a group: two ElectrumMiniWallets, one per BIP44 branch since a mini-wallet holds one generator, gap-limited at 10 for receive and 3 for change, on the shared client. GroupWalletState gives the coins with the derivation that spends each, the confirmed and pending balances, the next receive address and change index, and derivationOf -- bounded by the addresses the wallet has generated, which is how far a check of a claim will look. Tested against a fake IElectrumClient: a payment moves the receive address on, change is counted and never offered, and two groups on one client see only their own coins. Co-Authored-By: Claude Opus 5.5 --- .../bennu/compose/wallet/GroupChainWallet.kt | 169 +++++++++++++++++ .../bennu/compose/wallet/GroupChainWallets.kt | 35 ++++ .../compose/wallet/GroupChainWalletJvmTest.kt | 175 ++++++++++++++++++ docs/group-chain-wallet.md | 2 + 4 files changed, 381 insertions(+) create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallet.kt create mode 100644 composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallets.kt create mode 100644 composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainWalletJvmTest.kt diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallet.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallet.kt new file mode 100644 index 00000000..1421040b --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallet.kt @@ -0,0 +1,169 @@ +package com.machankura.bennu.compose.wallet + +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.Satoshi +import fr.acinq.lightning.blockchain.electrum.ElectrumConnectionStatus +import fr.acinq.lightning.blockchain.electrum.ElectrumMiniWallet +import fr.acinq.lightning.blockchain.electrum.HeaderSubscriptionResponse +import fr.acinq.lightning.blockchain.electrum.IElectrumClient +import fr.acinq.lightning.blockchain.electrum.WalletState +import fr.acinq.lightning.utils.sum +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.filterIsInstance +import kotlinx.coroutines.launch + +/** + * A group's wallet on chain: the counterpart of Phoenix's `FinalWallet`, watching + * the addresses [account] derives. + * + * Phoenix's final wallet watches one address forever. A group hands addresses out + * from several devices and keeps change, so this watches both BIP44 branches, each + * gap-limited -- and because an `ElectrumMiniWallet` holds one address generator, + * that is two of them. Both share the identity's Electrum client, which is safe: + * each ignores script hashes it does not know. + * + * In memory, as Phoenix's is. Everything it knows is fetched again from Electrum + * when it starts, and nothing about the wallet is stored -- the addresses are a + * derivation, and the coins are on chain. + */ +class GroupChainWallet( + val account: GroupWalletDerivation.Account, + electrum: IElectrumClient, + scope: CoroutineScope, + logger: Logger = Logger.withTag("GroupChainWallet"), +) { + private val receive = ElectrumMiniWallet(account.chain.chainHash, electrum, scope, logger, lookAhead = RECEIVE_LOOKAHEAD) + private val change = ElectrumMiniWallet(account.chain.chainHash, electrum, scope, logger, lookAhead = CHANGE_LOOKAHEAD) + + private val tip = MutableStateFlow((electrum.connectionStatus.value as? ElectrumConnectionStatus.Connected)?.height) + + /** The best block this wallet has heard of, or null before Electrum has connected. */ + val tipHeight: StateFlow = tip.asStateFlow() + + init { + receive.addAddressGenerator { index -> addressAt(GroupWalletDerivation.RECEIVE, index) } + change.addAddressGenerator { index -> addressAt(GroupWalletDerivation.CHANGE, index) } + + // The tip, for confirmations. A connection reports the height it found and + // every new block arrives as a header notification on the shared client. + scope.launch { + electrum.connectionStatus.filterIsInstance().collect { connected -> + tip.value = maxOf(tip.value ?: 0, connected.height) + } + } + scope.launch { + electrum.notifications.filterIsInstance().collect { header -> + tip.value = maxOf(tip.value ?: 0, header.blockHeight) + } + } + } + + /** Both branches and the tip, as one value. */ + val state: Flow = + combine(receive.walletStateFlow, change.walletStateFlow, tip) { receiveState, changeState, height -> + GroupWalletState(account, receiveState, changeState, height) + } + + fun stop() { + receive.stop() + change.stop() + } + + private fun addressAt(change: Long, index: Int): String = + GroupWalletDerivation.derive(account, change, index.toLong()).address(account.chain) + + companion object { + /** + * Receive addresses watched past the first unused one. Phoenix's swap-in + * wallet uses 3; a group has several devices showing "the next address", + * so two members can each hand one out before either is paid. + */ + const val RECEIVE_LOOKAHEAD: UInt = 10u + + /** Change addresses are only ever chosen by a spend, one at a time. */ + const val CHANGE_LOOKAHEAD: UInt = 3u + } +} + +/** + * One coin the group holds, and where under the account it is. + * + * [derivation] is what a spend needs to sign it -- the cache -- and what a signer + * checks the coin's script against. + */ +data class GroupUtxo( + val utxo: WalletState.Utxo, + val derivation: GroupWalletDerivation.Derived, +) { + val amount: Satoshi get() = utxo.amount + val isConfirmed: Boolean get() = utxo.blockHeight > 0 +} + +/** + * The group's wallet at one moment: both branches' coins, the next addresses to + * use, and how deep each coin is. + */ +data class GroupWalletState( + val account: GroupWalletDerivation.Account, + val receive: WalletState, + val change: WalletState, + val tipHeight: Int?, +) { + /** Every coin, receive and change alike, with the derivation that spends it. */ + val utxos: List by lazy { + listOf(GroupWalletDerivation.RECEIVE to receive, GroupWalletDerivation.CHANGE to change).flatMap { (branch, state) -> + state.utxos.mapNotNull { utxo -> + val index = utxo.addressMeta.indexOrNull ?: return@mapNotNull null + GroupUtxo(utxo, GroupWalletDerivation.derive(account, branch, index.toLong())) + } + } + } + + val confirmedBalance: Satoshi get() = utxos.filter { it.isConfirmed }.map { it.amount }.sum() + + /** In the mempool: the group's, but not yet spendable by the send-all builder. */ + val pendingBalance: Satoshi get() = utxos.filterNot { it.isConfirmed }.map { it.amount }.sum() + + /** + * The address to hand out, or null until Electrum has said which are used. + * + * Null rather than index 0 on purpose: before the first answer every address + * reads as unused, and showing `/0/0` to a group that has been paid there + * fifty times would be address reuse with a straight face. + */ + val receiveAddress: String? get() = receive.firstUnusedDerivedAddress?.first + + /** The change index a spend should pay back to, or null until Electrum has answered. */ + val nextChangeIndex: Long? get() = change.firstUnusedDerivedAddress?.second?.index?.toLong() + + /** How many confirmations [utxo] has: 0 in the mempool, and 0 until the tip is known. */ + fun confirmations(utxo: GroupUtxo): Int { + val height = tipHeight ?: return 0 + val confirmedAt = utxo.utxo.blockHeight.toInt() + return if (confirmedAt == 0) 0 else height - confirmedAt + 1 + } + + /** + * Where under the account [script] is, among the addresses this wallet has + * generated, or null if it is not one of them. + * + * The generated range is the bound on how far a check of somebody else's + * claim will look: a derivation the wallet has never watched is not one it + * will vouch for. + */ + fun derivationOf(script: ByteVector): GroupWalletDerivation.Derived? = + listOf(GroupWalletDerivation.RECEIVE to receive, GroupWalletDerivation.CHANGE to change) + .asSequence() + .flatMap { (branch, state) -> + state.addresses.values.asSequence().mapNotNull { it.meta.indexOrNull }.map { branch to it.toLong() } + } + .map { (branch, index) -> GroupWalletDerivation.derive(account, branch, index) } + .firstOrNull { it.pubkeyScript == script } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallets.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallets.kt new file mode 100644 index 00000000..bfb12cda --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainWallets.kt @@ -0,0 +1,35 @@ +package com.machankura.bennu.compose.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import fr.acinq.lightning.blockchain.electrum.IElectrumClient +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * The group wallets one identity is watching, on that identity's Electrum client. + * + * One per identity, made where the identity's node is, and stopped with it: a + * profile switch is a restart, and a wallet left watching on the last profile's + * connection would be a wallet nobody can see subscribing to addresses nobody + * asked about. Wallets are made on first use -- opening a group's wallet screen + * -- and kept for the life of the identity, because an Electrum subscription is + * cheap and the first answer is slow. + */ +class GroupChainWallets( + private val electrum: IElectrumClient, + private val scope: CoroutineScope, +) { + private val mutex = Mutex() + private val wallets = mutableMapOf() + + /** The wallet watching [account], made the first time it is asked for. Keyed by xpub, which names one account of one group on one network. */ + suspend fun walletFor(account: GroupWalletDerivation.Account): GroupChainWallet = mutex.withLock { + wallets.getOrPut(account.xpub) { GroupChainWallet(account, electrum, scope) } + } + + suspend fun stop() = mutex.withLock { + wallets.values.forEach { it.stop() } + wallets.clear() + } +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainWalletJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainWalletJvmTest.kt new file mode 100644 index 00000000..528bb7f9 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainWalletJvmTest.kt @@ -0,0 +1,175 @@ +package com.machankura.bennu.compose.wallet + +import com.machankura.bennu.compose.managers.GroupWalletDerivation +import fr.acinq.bitcoin.Block +import fr.acinq.bitcoin.BlockHeader +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.ByteVector32 +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.Crypto +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.ElectrumConnectionStatus +import fr.acinq.lightning.blockchain.electrum.ElectrumSubscriptionResponse +import fr.acinq.lightning.blockchain.electrum.GetMerkleResponse +import fr.acinq.lightning.blockchain.electrum.HeaderSubscriptionResponse +import fr.acinq.lightning.blockchain.electrum.IElectrumClient +import fr.acinq.lightning.blockchain.electrum.ScriptHashSubscriptionResponse +import fr.acinq.lightning.blockchain.electrum.TransactionHistoryItem +import fr.acinq.lightning.blockchain.electrum.UnspentItem +import fr.acinq.lightning.blockchain.fee.FeeratePerKw +import fr.acinq.secp256k1.Hex +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * The group's wallet watching a chain that only exists in this file. + * + * `IElectrumClient` is small and documented never to throw, so a fake of it is + * a few maps: what each script has been paid, and the transactions that paid it. + */ +class GroupChainWalletJvmTest { + private class FakeElectrum : IElectrumClient { + val unspents = mutableMapOf>() + val txs = mutableMapOf() + val subscribed = mutableSetOf() + override val notifications = MutableSharedFlow(extraBufferCapacity = 64) + override val connectionStatus: StateFlow = MutableStateFlow(ElectrumConnectionStatus.Closed(null)) + + private fun status(scriptHash: ByteVector32): String? = unspents[scriptHash]?.takeIf { it.isNotEmpty() }?.let { "used" } + + /** Pays [script] in a fresh transaction, confirmed at [height] (0 for the mempool), and tells the wallet. */ + suspend fun pay(script: ByteVector, amount: Satoshi, height: Long = 100) { + val tx = Transaction( + version = 2, + txIn = listOf(TxIn(OutPoint(TxId(ByteVector32(Crypto.sha256(script.toByteArray() + txs.size.toByte()))), 0), ByteVector.empty, 0xffffffffL)), + txOut = listOf(TxOut(amount, script)), + lockTime = 0, + ) + txs[tx.txid] = tx + val hash = scriptHash(script) + unspents[hash] = unspents[hash].orEmpty() + UnspentItem(tx.txid, 0, amount.sat, height) + notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash))) + } + + override suspend fun startScriptHashSubscription(scriptHash: ByteVector32): ScriptHashSubscriptionResponse { + subscribed += scriptHash + return ScriptHashSubscriptionResponse(scriptHash, status(scriptHash)) + } + + override suspend fun getScriptHashUnspents(scriptHash: ByteVector32): List = unspents[scriptHash].orEmpty() + override suspend fun getTx(txId: TxId): Transaction? = txs[txId] + override suspend fun getHeader(blockHeight: Int): BlockHeader? = null + override suspend fun getHeaders(startHeight: Int, count: Int): List = emptyList() + override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null + override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List = emptyList() + override suspend fun broadcastTransaction(tx: Transaction): TxId = tx.txid + override suspend fun estimateFees(confirmations: Int): FeeratePerKw? = null + override suspend fun startHeaderSubscription() = HeaderSubscriptionResponse(0, Block.RegtestGenesisBlock.header) + + companion object { + /** Electrum's script hash: sha256 of the script, byte-reversed. */ + fun scriptHash(script: ByteVector): ByteVector32 = ByteVector32(Crypto.sha256(script.toByteArray()).reversedArray()) + } + } + + private fun key(seed: Int): String = + PrivateKey(ByteVector32(Hex.decode(seed.toString(16).padStart(64, '0')))).publicKey().toString() + + private val account = GroupWalletDerivation.account(key(0x1c0ffee), Chain.Regtest) + private fun receive(index: Long) = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index) + private fun change(index: Long) = GroupWalletDerivation.derive(account, GroupWalletDerivation.CHANGE, index) + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + @AfterTest + fun tearDown() = scope.cancel() + + private fun eventually(block: suspend () -> T): T = runBlocking { withTimeout(10_000) { block() } } + + @Test + fun `being paid moves the receive address on`() { + val electrum = FakeElectrum() + val wallet = GroupChainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.receiveAddress == receive(0).address(Chain.Regtest) } } + eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) } + + val paid = eventually { wallet.state.first { it.receiveAddress == receive(1).address(Chain.Regtest) } } + assertEquals(Satoshi(25_000), paid.confirmedBalance) + assertEquals(receive(0), paid.utxos.single().derivation) + } + + @Test + fun `change is the group's money and is not handed out to be paid`() { + val electrum = FakeElectrum() + val wallet = GroupChainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.nextChangeIndex == 0L } } + eventually { electrum.pay(change(0).pubkeyScript, Satoshi(7_000), height = 0) } + + val state = eventually { wallet.state.first { it.nextChangeIndex == 1L && it.receiveAddress != null } } + assertEquals(Satoshi(7_000), state.pendingBalance, "in the mempool, so pending") + assertEquals(Satoshi(0), state.confirmedBalance) + assertEquals(receive(0).address(Chain.Regtest), state.receiveAddress, "a change address is never offered for receiving") + assertEquals(change(0), state.derivationOf(change(0).pubkeyScript)) + } + + @Test + fun `two groups on one client see only their own coins`() { + val electrum = FakeElectrum() + val other = GroupWalletDerivation.account(key(0xdecaf), Chain.Regtest) + val ours = GroupChainWallet(account, electrum, scope) + val theirs = GroupChainWallet(other, electrum, scope) + + eventually { ours.state.first { it.receiveAddress != null } } + eventually { theirs.state.first { it.receiveAddress != null } } + eventually { electrum.pay(GroupWalletDerivation.derive(other, 0, 0).pubkeyScript, Satoshi(50_000)) } + + eventually { theirs.state.first { it.confirmedBalance == Satoshi(50_000) } } + val state = eventually { ours.state.first { it.receiveAddress != null } } + assertTrue(state.utxos.isEmpty()) + assertNull(state.derivationOf(GroupWalletDerivation.derive(other, 0, 0).pubkeyScript), "another group's address is not ours to vouch for") + } + + @Test + fun `confirmations follow the tip`() { + val electrum = FakeElectrum() + val wallet = GroupChainWallet(account, electrum, scope) + + eventually { wallet.state.first { it.receiveAddress != null } } + eventually { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000), height = 100) } + eventually { electrum.notifications.emit(HeaderSubscriptionResponse(105, Block.RegtestGenesisBlock.header)) } + + val state = eventually { wallet.state.first { it.tipHeight == 105 && it.utxos.isNotEmpty() } } + assertEquals(6, state.confirmations(state.utxos.single())) + } + + @Test + fun `the receive branch is watched past the first unused address`() { + val electrum = FakeElectrum() + GroupChainWallet(account, electrum, scope).let { wallet -> + eventually { wallet.state.first { it.receive.addresses.size == GroupChainWallet.RECEIVE_LOOKAHEAD.toInt() } } + } + assertTrue(FakeElectrum.scriptHash(receive(9).pubkeyScript) in electrum.subscribed) + } +} diff --git a/docs/group-chain-wallet.md b/docs/group-chain-wallet.md index 2e815cba..20ef8435 100644 --- a/docs/group-chain-wallet.md +++ b/docs/group-chain-wallet.md @@ -27,6 +27,8 @@ kept as written; where the build chose differently the table below says so. | late members get the statement through the chronicle | they do not: `ChronicleEvent`'s allowlist carries document kinds only, and leaves out every group-signed statement *about* the group — relay lists and profile included — for the replay reason its kdoc gives. A member who joined later sees *Open a group wallet* instead, and signing it again is harmless: a statement for one account is the same values under the same `d` tag, and the newest replaces the rest | | the descriptor rides in a `descriptor` tag | two, each marked `receive` or `change`, and the `d` tag is read back and checked against the network and account, so "newest per account" cannot be split by a `d` that disagrees with the fields | | the transcript line is checked by signature | by signature *and* rederivation, through `GroupWallet.of` — a line people will send money on is held to the same check as the wallet screen | +| `GroupWalletManager` starts a wallet for every room with a statement, under the identity's `collectLatest` | `GroupChainWallets`, one per identity, makes a room's wallet the first time its screen asks and keeps it for the identity's life. Starting every room's at launch would subscribe a member in twenty groups to two hundred addresses before they looked at one; `GroupWalletManager` kept the reads (the key, the account, the statement) and nothing that runs | +| `receiveAddress` is the first unused address | it is, and that is `ElectrumMiniWallet`'s rule: the *lowest* unused index, so a gap below a paid address is refilled before the next one is offered. Null until Electrum has answered, rather than `/0/0` | The headline: **the best path is BIP86's own unhardened tail, `//`, hung under an account key the group's threshold key is tweaked to, with the