feat(wallet): a screen listing the group wallet's addresses (Phase 2)

GroupWalletAddressesScreen, pushed from an "All addresses" button in the
wallet screen's receive card: index, address, and what each has been
used for, newest first, with the current address on the secondary
container and a copy button on every row. Its view model reads the
wallet GroupOnchainWallets already holds, so the list costs no
subscriptions and agrees with the wallet screen about which address is
current.

FakeElectrum moves out of GroupOnchainWalletJvmTest so the view model's
test can drive a chain too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kgothatso NgakoandClaude Opus 5.5 committed 2026-10-23 12:19:47 +02:00
1 parent de76311e1e
commit 5b06c84401
10 files changed
+620 -81

No files matched your search

@@ -622,6 +622,14 @@
<string name="receive_address">Receive address</string>
<string name="copy_address">Copy address</string>
<string name="address_copied">Address copied</string>
<string name="all_addresses">All addresses</string>
<string name="addresses">Addresses</string>
<string name="addresses_explainer">Each payment should go to a new address. If someone else in the group is already sharing the current one, share one of the ones after it.</string>
<string name="being_handed_out_now">Being handed out now</string>
<string name="not_used_yet">Not used yet</string>
<string name="paid_s_sats">Paid · %1$s sats</string>
<string name="paid_spent_since">Paid · spent since</string>
<string name="copy_address_s">Copy address %1$s</string>
<string name="finding_the_group_s_coins">Finding the group's coins…</string>
<string name="nothing_has_been_sent_to_this_wallet_yet">Nothing has been sent to this wallet yet.</string>
<string name="this_profile_cannot_watch_the_chain">This profile has no wallet of its own to watch the chain with, so the balance and the next address can't be shown here.</string>
@@ -0,0 +1,253 @@
package com.machankura.bennu.compose.ui.composable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.viewmodel.compose.viewModel
import bennu.composeapp.generated.resources.Res
import bennu.composeapp.generated.resources.address_copied
import bennu.composeapp.generated.resources.addresses
import bennu.composeapp.generated.resources.addresses_explainer
import bennu.composeapp.generated.resources.being_handed_out_now
import bennu.composeapp.generated.resources.copy_address_s
import bennu.composeapp.generated.resources.finding_the_group_s_coins
import bennu.composeapp.generated.resources.not_used_yet
import bennu.composeapp.generated.resources.paid_s_sats
import bennu.composeapp.generated.resources.paid_spent_since
import bennu.composeapp.generated.resources.this_profile_cannot_watch_the_chain
import com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.text.grouped
import com.machankura.bennu.compose.ui.composable.widgets.EmptyState
import com.machankura.bennu.compose.ui.composable.widgets.ErrorState
import com.machankura.bennu.compose.ui.composable.widgets.LoadingDataIndicator
import com.machankura.bennu.compose.ui.composable.widgets.LocalSnackbarHostState
import com.machankura.bennu.compose.ui.composable.widgets.NavigateBackButton
import com.machankura.bennu.compose.ui.composable.widgets.ScreenStateTransition
import com.machankura.bennu.compose.ui.composable.widgets.rememberNotifier
import com.machankura.bennu.compose.ui.theme.readableContent
import com.machankura.bennu.compose.ui.theme.spacing
import com.machankura.bennu.compose.ui.view.model.GroupWalletAddressesViewModel
import com.machankura.bennu.compose.ui.view.state.GroupWalletAddressesUIState
import com.machankura.bennu.compose.wallet.GroupAddress
import com.machankura.bennu.compose.wallet.GroupOnchainWallets
import fr.acinq.bitcoin.Chain
import fr.acinq.bitcoin.Satoshi
import org.jetbrains.compose.resources.stringResource
/**
* The group wallet's receive addresses, newest first: every one paid, the one
* the wallet screen is handing out, and the few after it.
*
* Modelled on Phoenix's swap-in address list, with the look-ahead cut to what is
* worth handing out. The addresses after the current one are there so that two
* members sharing the wallet at once can each give a payer a different one;
* the sentence above the list says so, or nobody would use anything but the top.
*
* No block explorer: a tap that sends every address of the group's wallet to a
* third party's server is the leak the watch-only export warns about, made
* without asking.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun GroupWalletAddressesScreen(
chatRoomId: String,
chain: Chain,
initialUIState: GroupWalletAddressesUIState = GroupWalletAddressesUIState.Loading,
chatRepository: ChatRepository,
wallets: GroupOnchainWallets?,
onNavigateBack: () -> Unit,
) {
val addressesViewModel: GroupWalletAddressesViewModel = viewModel(
factory = GroupWalletAddressesViewModel.factory(
chatRoomId = chatRoomId,
chain = chain,
initialUIState = initialUIState,
chatRepository = chatRepository,
wallets = wallets,
)
)
LaunchedEffect(true) {
if (initialUIState == GroupWalletAddressesUIState.Loading) {
addressesViewModel.initiate()
}
}
val notify = rememberNotifier(rememberCoroutineScope())
Scaffold(
snackbarHost = { SnackbarHost(LocalSnackbarHostState.current) },
topBar = {
TopAppBar(
title = {
Text(
text = stringResource(Res.string.addresses),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
},
navigationIcon = { NavigateBackButton(onNavigateBack) }
)
}
) { padding ->
ScreenStateTransition(addressesViewModel.uiState) { uiState ->
when (val state = uiState) {
is GroupWalletAddressesUIState.Error -> {
// Nothing to retry: the room came from a navigation argument.
ErrorState(
modifier = Modifier.padding(padding),
message = state.message,
onRetry = null
)
}
GroupWalletAddressesUIState.Loading -> {
LoadingDataIndicator(modifier = Modifier.fillMaxWidth().padding(padding))
}
GroupWalletAddressesUIState.CannotWatch -> {
EmptyState(
modifier = Modifier.padding(padding).readableContent(),
message = stringResource(Res.string.this_profile_cannot_watch_the_chain),
icon = Icons.Default.Visibility,
)
}
is GroupWalletAddressesUIState.Loaded -> {
val receive = state.receive
if (receive == null) {
LoadingDataIndicator(
modifier = Modifier.fillMaxWidth().padding(padding),
text = stringResource(Res.string.finding_the_group_s_coins)
)
} else {
AddressList(
modifier = Modifier.padding(padding),
receive = receive,
notify = notify,
)
}
}
}
}
}
}
@Composable
private fun AddressList(
modifier: Modifier,
receive: List<GroupAddress>,
notify: (String) -> Unit,
) {
val clipboardManager = LocalClipboardManager.current
val addressCopied = stringResource(Res.string.address_copied)
LazyColumn(
modifier = modifier.readableContent().fillMaxSize()
.padding(MaterialTheme.spacing.screenMargin),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)
) {
item {
Text(
text = stringResource(Res.string.addresses_explainer),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
items(receive, key = { it.derivation.index }) { address ->
AddressRow(
address = address,
onCopy = {
clipboardManager.setText(buildAnnotatedString { append(address.address) })
notify(addressCopied)
},
)
}
}
}
/**
* One address: its index, the address itself, and what it has been used for.
*
* The current address takes the secondary container rather than Phoenix's
* leading bar, so the emphasis is a colour pairing the theme has already
* measured in all six schemes.
*/
@Composable
private fun AddressRow(address: GroupAddress, onCopy: () -> Unit) {
val colors = if (address.status == GroupAddress.Status.CURRENT) {
val onContainer = MaterialTheme.colorScheme.onSecondaryContainer
ListItemDefaults.colors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
headlineColor = onContainer,
supportingColor = onContainer,
leadingIconColor = onContainer,
trailingIconColor = onContainer,
)
} else {
ListItemDefaults.colors()
}
ListItem(
colors = colors,
leadingContent = {
Text(
text = address.derivation.index.toString(),
style = MaterialTheme.typography.labelLarge,
)
},
headlineContent = {
Text(
text = address.address,
style = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace),
maxLines = 1,
overflow = TextOverflow.MiddleEllipsis,
)
},
supportingContent = { Text(address.status.label(address.balance)) },
trailingContent = {
IconButton(onClick = onCopy) {
Icon(
Icons.Default.ContentCopy,
contentDescription = stringResource(Res.string.copy_address_s, address.derivation.index.toString())
)
}
},
)
}
@Composable
private fun GroupAddress.Status.label(balance: Satoshi): String = when (this) {
GroupAddress.Status.CURRENT -> stringResource(Res.string.being_handed_out_now)
GroupAddress.Status.NEXT -> stringResource(Res.string.not_used_yet)
GroupAddress.Status.USED -> if (balance > Satoshi(0)) {
stringResource(Res.string.paid_s_sats, balance.grouped())
} else {
stringResource(Res.string.paid_spent_since)
}
}
@@ -19,6 +19,7 @@ import bennu.composeapp.generated.resources.couldn_t_bump_the_fee
import androidx.compose.material.icons.filled.Send
import bennu.composeapp.generated.resources.send
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupSendRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletAddressesRoute
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
@@ -32,6 +33,7 @@ import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBalanceWallet
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.FormatListNumbered
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material3.Button
import androidx.compose.material3.Card
@@ -56,6 +58,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.viewmodel.compose.viewModel
import bennu.composeapp.generated.resources.Res
import bennu.composeapp.generated.resources.address_copied
import bennu.composeapp.generated.resources.all_addresses
import bennu.composeapp.generated.resources.anyone_with_these_can_see_every_address
import bennu.composeapp.generated.resources.balance
import bennu.composeapp.generated.resources.balance_not_known_yet
@@ -242,6 +245,14 @@ fun GroupWalletScreen(
)
}
} else null,
onOpenAddresses = {
onNavigateToRoute(
GroupWalletAddressesRoute(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId
)
)
},
onOpenSpend = toSession,
onSendAgain = if (watcher != null) {
{ sessionId -> groupWalletViewModel.sendAgain(sessionId) { notify(sentAgain) } }
@@ -292,6 +303,7 @@ private fun OpenWallet(
state: GroupWalletUIState.Loaded,
notify: (String) -> Unit,
onSend: (() -> Unit)?,
onOpenAddresses: () -> Unit,
onOpenSpend: (sessionId: String) -> Unit,
onSendAgain: ((sessionId: String) -> Unit)?,
onBump: ((sessionId: String) -> Unit)?,
@@ -362,6 +374,14 @@ private fun OpenWallet(
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.copy_address))
}
// In the card because it answers the question the card
// raises: which address to give, when somebody else in
// the group may be giving this one.
TextButton(onClick = onOpenAddresses) {
Icon(Icons.Default.FormatListNumbered, contentDescription = Decorative)
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.all_addresses))
}
}
}
}
@@ -51,6 +51,7 @@ import com.machankura.bennu.compose.ui.composable.EditGroupRelaysScreen
import com.machankura.bennu.compose.ui.composable.GroupNostrProfileScreen
import com.machankura.bennu.compose.ui.composable.GroupRelaysScreen
import com.machankura.bennu.compose.ui.composable.GroupWalletScreen
import com.machankura.bennu.compose.ui.composable.GroupWalletAddressesScreen
import com.machankura.bennu.compose.ui.composable.GroupPostsScreen
import com.machankura.bennu.compose.ui.composable.HomeScreen
import com.machankura.bennu.compose.ui.composable.ImplementationPendingScreen
@@ -154,6 +155,7 @@ import com.machankura.bennu.compose.ui.composable.navigation.routes.EditGroupRel
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupNostrProfileRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupRelaysRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletRoute
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupWalletAddressesRoute
import com.machankura.bennu.compose.wallet.GroupOnchainWallets
import com.machankura.bennu.compose.wallet.GroupTransactionWatcher
import fr.acinq.phoenix.managers.NodeParamsManager
@@ -1250,6 +1252,19 @@ fun BennuNavHost(
}
)
}
composable<GroupWalletAddressesRoute> { backStackEntry ->
val route = backStackEntry.toRoute<GroupWalletAddressesRoute>()
GroupWalletAddressesScreen(
chatRoomId = route.chatRoomId,
chain = NodeParamsManager.chain,
chatRepository = databaseChatRepository,
wallets = groupOnchainWallets,
onNavigateBack = {
navController.popBackStack()
}
)
}
composable<GroupSendRoute> { backStackEntry ->
val route = backStackEntry.toRoute<GroupSendRoute>()
@@ -0,0 +1,13 @@
package com.machankura.bennu.compose.ui.composable.navigation.routes
import kotlinx.serialization.Serializable
/**
* The group wallet's receive addresses: every one paid, the one being handed
* out, and the next few -- pushed from the wallet screen's receive card.
*/
@Serializable
data class GroupWalletAddressesRoute(
val activeUserPublicKey: String,
val chatRoomId: String,
): Route()
@@ -0,0 +1,73 @@
package com.machankura.bennu.compose.ui.view.model
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.machankura.bennu.compose.repository.ChatRepository
import com.machankura.bennu.compose.ui.view.state.GroupWalletAddressesUIState
import com.machankura.bennu.compose.wallet.GroupOnchainWallets
import fr.acinq.bitcoin.Chain
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
/**
* The group wallet's addresses, watched for as long as the screen is open.
*
* [wallets] hands back the wallet the wallet screen is already watching, so the
* list costs no subscriptions of its own and agrees with that screen about which
* address is current.
*/
class GroupWalletAddressesViewModel(
val chatRoomId: String,
val chain: Chain,
initialUIState: GroupWalletAddressesUIState,
val chatRepository: ChatRepository,
private val wallets: GroupOnchainWallets?,
): ViewModel() {
var uiState: GroupWalletAddressesUIState by mutableStateOf(initialUIState)
private set
fun initiate() {
viewModelScope.launch(Dispatchers.IO) {
val wallet = chatRepository.groupWallet(chatRoomId, chain)
if (wallet == null) {
uiState = GroupWalletAddressesUIState.Error("This group has not opened a wallet")
return@launch
}
if (wallets == null) {
uiState = GroupWalletAddressesUIState.CannotWatch
return@launch
}
uiState = GroupWalletAddressesUIState.Loaded(receive = null)
wallets.walletFor(wallet.account).state.collect { state ->
uiState = GroupWalletAddressesUIState.Loaded(receive = state.receiveAddresses)
}
}
}
companion object {
fun factory(
chatRoomId: String,
chain: Chain,
initialUIState: GroupWalletAddressesUIState = GroupWalletAddressesUIState.Loading,
chatRepository: ChatRepository,
wallets: GroupOnchainWallets?,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
GroupWalletAddressesViewModel(
chatRoomId = chatRoomId,
chain = chain,
initialUIState = initialUIState,
chatRepository = chatRepository,
wallets = wallets,
)
}
}
}
}
@@ -0,0 +1,28 @@
package com.machankura.bennu.compose.ui.view.state
import com.machankura.bennu.compose.wallet.GroupAddress
sealed interface GroupWalletAddressesUIState {
/**
* The wallet's addresses as the chain last said.
*
* [receive] is null until Electrum has said which are used: before that every
* address reads as unused, and a list that called `/0/0` current would be
* wrong about a group paid there before.
*/
data class Loaded(
val receive: List<GroupAddress>?,
): GroupWalletAddressesUIState
/**
* A profile with no node of its own -- an nsec or an npub -- which knows the
* group keeps a wallet and cannot see which of its addresses are used.
*/
data object CannotWatch: GroupWalletAddressesUIState
data class Error(
val message: String
): GroupWalletAddressesUIState
data object Loading: GroupWalletAddressesUIState
}
@@ -0,0 +1,121 @@
package com.machankura.bennu.compose.ui.view.model
import com.machankura.bennu.compose.database.model.GroupSignedEvent
import com.machankura.bennu.compose.managers.GroupWalletDerivation
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.ui.view.state.GroupWalletAddressesUIState
import com.machankura.bennu.compose.wallet.FakeElectrum
import com.machankura.bennu.compose.wallet.GroupAddress
import com.machankura.bennu.compose.wallet.GroupOnchainWallets
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.bitcoin.Chain
import fr.acinq.bitcoin.PrivateKey
import fr.acinq.bitcoin.Satoshi
import fr.acinq.secp256k1.Hex
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import kotlinx.coroutines.withTimeout
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.time.Instant
/** Which of its states the address list is in, and that it follows the chain while it is open. */
@OptIn(ExperimentalCoroutinesApi::class)
class GroupWalletAddressesViewModelJvmTest {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@BeforeTest
fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher())
@AfterTest
fun tearDown() {
scope.cancel()
Dispatchers.resetMain()
}
private val chatRoomId = "d4c3b2a1".repeat(8)
private val account = GroupWalletDerivation.account(
PrivateKey(ByteVector32(Hex.decode("1c0ffee".padStart(64, '0')))).publicKey().toString(),
Chain.Regtest,
)
private val wallet = GroupWallet(
signedEvent = GroupSignedEvent(
id = "e".repeat(64),
chatRoomId = chatRoomId,
publicKey = chatRoomId,
kind = GroupWalletStatementEvent.KIND,
tags = GroupWalletStatementEvent.template(account).tags,
content = account.xpub,
signature = "f".repeat(128),
createdAt = Instant.fromEpochSeconds(1_700_000_000),
),
account = account,
)
private fun repository(opened: GroupWallet?) =
object : ChatRepository by ChatRepository.NO_OP_CHAT_REPOSITORY {
override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = opened
}
private fun viewModel(opened: GroupWallet?, wallets: GroupOnchainWallets?) =
GroupWalletAddressesViewModel(
chatRoomId = chatRoomId,
chain = Chain.Regtest,
initialUIState = GroupWalletAddressesUIState.Loading,
chatRepository = repository(opened),
wallets = wallets,
).apply { initiate() }
private fun GroupWalletAddressesViewModel.until(predicate: (GroupWalletAddressesUIState) -> Boolean): GroupWalletAddressesUIState =
runBlocking {
withTimeout(10_000) {
while (!predicate(uiState)) delay(10)
uiState
}
}
private fun receive(index: Long) = GroupWalletDerivation.derive(account, GroupWalletDerivation.RECEIVE, index)
@Test
fun `a room with no wallet has no addresses to list`() {
assertIs<GroupWalletAddressesUIState.Error>(viewModel(opened = null, wallets = null).until { it != GroupWalletAddressesUIState.Loading })
}
@Test
fun `a profile with no node is told it cannot watch rather than shown nothing`() {
assertEquals(
GroupWalletAddressesUIState.CannotWatch,
viewModel(opened = wallet, wallets = null).until { it != GroupWalletAddressesUIState.Loading },
)
}
@Test
fun `the list follows a payment while the screen is open`() {
val electrum = FakeElectrum()
val addresses = viewModel(opened = wallet, wallets = GroupOnchainWallets(electrum, scope))
addresses.until { (it as? GroupWalletAddressesUIState.Loaded)?.receive != null }
runBlocking { electrum.pay(receive(0).pubkeyScript, Satoshi(25_000)) }
val state = addresses.until { loaded ->
(loaded as? GroupWalletAddressesUIState.Loaded)?.receive?.any { it.status == GroupAddress.Status.USED } == true
}
val current = assertIs<GroupWalletAddressesUIState.Loaded>(state).receive!!.single { it.status == GroupAddress.Status.CURRENT }
assertEquals(1L, current.derivation.index)
}
}
@@ -0,0 +1,88 @@
package com.machankura.bennu.compose.wallet
import fr.acinq.bitcoin.Block
import fr.acinq.bitcoin.BlockHeader
import fr.acinq.bitcoin.ByteVector
import fr.acinq.bitcoin.ByteVector32
import fr.acinq.bitcoin.Crypto
import fr.acinq.bitcoin.OutPoint
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 kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* A chain that only exists in a test.
*
* `IElectrumClient` is small and documented never to throw, so a fake of it is
* a few maps: what each script has been paid, what of it is unspent, and the
* transactions that paid it.
*/
internal class FakeElectrum : IElectrumClient {
val unspents = mutableMapOf<ByteVector32, List<UnspentItem>>()
val txs = mutableMapOf<TxId, Transaction>()
val subscribed = mutableSetOf<ByteVector32>()
override val notifications = MutableSharedFlow<ElectrumSubscriptionResponse>(extraBufferCapacity = 64)
override val connectionStatus: StateFlow<ElectrumConnectionStatus> = MutableStateFlow(ElectrumConnectionStatus.Closed(null))
/** How many transactions have touched each script: Electrum's status is over the history, not the unspents. */
private val history = mutableMapOf<ByteVector32, Int>()
private fun status(scriptHash: ByteVector32): String? = history[scriptHash]?.let { "used:$it" }
/** 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)
history[hash] = (history[hash] ?: 0) + 1
notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash)))
}
/** Spends everything [script] holds: its unspents go, its history stays. */
suspend fun spend(script: ByteVector) {
val hash = scriptHash(script)
unspents.remove(hash)
history[hash] = (history[hash] ?: 0) + 1
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<UnspentItem> = 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<BlockHeader> = emptyList()
override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null
override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List<TransactionHistoryItem> = 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())
}
}
@@ -2,36 +2,16 @@ 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
@@ -42,69 +22,9 @@ 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, what of it is unspent, and the
* transactions that paid it.
* The group's wallet watching a chain that only exists in [FakeElectrum].
*/
class GroupOnchainWalletJvmTest {
private class FakeElectrum : IElectrumClient {
val unspents = mutableMapOf<ByteVector32, List<UnspentItem>>()
val txs = mutableMapOf<TxId, Transaction>()
val subscribed = mutableSetOf<ByteVector32>()
override val notifications = MutableSharedFlow<ElectrumSubscriptionResponse>(extraBufferCapacity = 64)
override val connectionStatus: StateFlow<ElectrumConnectionStatus> = MutableStateFlow(ElectrumConnectionStatus.Closed(null))
/** How many transactions have touched each script: Electrum's status is over the history, not the unspents. */
private val history = mutableMapOf<ByteVector32, Int>()
private fun status(scriptHash: ByteVector32): String? = history[scriptHash]?.let { "used:$it" }
/** 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)
history[hash] = (history[hash] ?: 0) + 1
notifications.emit(ScriptHashSubscriptionResponse(hash, status(hash)))
}
/** Spends everything [script] holds: its unspents go, its history stays. */
suspend fun spend(script: ByteVector) {
val hash = scriptHash(script)
unspents.remove(hash)
history[hash] = (history[hash] ?: 0) + 1
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<UnspentItem> = 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<BlockHeader> = emptyList()
override suspend fun getMerkle(txId: TxId, blockHeight: Int, contextOpt: Transaction?): GetMerkleResponse? = null
override suspend fun getScriptHashHistory(scriptHash: ByteVector32): List<TransactionHistoryItem> = 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()