diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index 83c4127f..ec0f66f1 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -508,7 +508,6 @@
Address %1$s was just paid
Finding the group's coins…
Nothing has been sent to this wallet yet.
- 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.
Coins
Change
Received
@@ -730,7 +729,6 @@
Asked. A member who holds the group's key will answer when their device next reads the room.
This group's guardian keys can't be read by this version of the app.
Guarded wallets for members aren't offered on this network yet.
- This profile has no wallet of its own to watch the chain with, so it couldn't see its own coins.
%1$s would refuse this request: it was asked before the group said it guards members' wallets. Asking again makes a new one.
%1$s has changed its delay since you asked. Asking again makes a new request at the new delay.
%1$s has stopped guarding members' wallets, so this request won't be signed. You can discard it.
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt
index bbb4de52..632be5c3 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/MemberWalletManager.kt
@@ -153,9 +153,6 @@ object MemberWalletManager {
/** Member wallets are not offered on this network yet: `GroupWalletRollout.offersMemberWalletsOn`. */
NOT_ON_THIS_NETWORK,
- /** The profile has no Electrum client, so it could not see its own coins. Read by the screen, not here. */
- CANNOT_WATCH,
-
/**
* The group has not said it guards members' wallets: no policy, as far as
* this device knows. `docs/member-wallet-delay.md`, D8.
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt
index 6c153fa9..59ea8af4 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ActiveProfileScreen.kt
@@ -105,8 +105,8 @@ fun ActiveProfileScreen(
// pending route for every kind.
signOut: SignOutDependencies? = null,
// The member's guarded wallets (docs/member-guarded-wallets.md). The no-op
- // repository lists none, for previews and tests; null wallets is a profile
- // that cannot watch the chain, whose rows show no balance.
+ // repository lists none, and null wallets watch nothing: both for previews
+ // and tests, which compose the screen without an identity.
memberWalletRepository: MemberWalletRepository = MemberWalletRepository.NO_OP,
wallets: GroupOnchainWallets? = null,
) {
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 c8d69d99..6b01498f 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
@@ -133,7 +133,7 @@ fun GroupSendScreen(
initialGroupSendUIState: GroupSendUIState = GroupSendUIState.Loading,
chatRepository: ChatRepository,
frostSigningRepository: FrostSigningRepository,
- wallets: GroupOnchainWallets?,
+ wallets: GroupOnchainWallets,
guardedChatRoomId: String? = null,
fundChatRoomId: String? = null,
onNavigateToRouteAndPopUpInclusive: (Route) -> Unit,
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletAddressesScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletAddressesScreen.kt
index 32ad5341..78ace7c5 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletAddressesScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupWalletAddressesScreen.kt
@@ -13,7 +13,6 @@ import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.selection.SelectionContainer
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
@@ -51,11 +50,9 @@ 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.show_as_a_qr_code
-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.Decorative
-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
@@ -97,7 +94,7 @@ fun GroupWalletAddressesScreen(
chain: Chain,
initialUIState: GroupWalletAddressesUIState = GroupWalletAddressesUIState.Loading,
chatRepository: ChatRepository,
- wallets: GroupOnchainWallets?,
+ wallets: GroupOnchainWallets,
onNavigateBack: () -> Unit,
) {
val addressesViewModel: GroupWalletAddressesViewModel = viewModel(
@@ -148,14 +145,6 @@ fun GroupWalletAddressesScreen(
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) {
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 5f500049..61bfeeb1 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
@@ -140,7 +140,6 @@ import bennu.composeapp.generated.resources.s_dot_s
import bennu.composeapp.generated.resources.s_sats
import bennu.composeapp.generated.resources.s_sats_on_the_way
import bennu.composeapp.generated.resources.this_group_has_not_opened_a_wallet
-import bennu.composeapp.generated.resources.this_profile_cannot_watch_the_chain
import bennu.composeapp.generated.resources.waiting_for_a_confirmation
import bennu.composeapp.generated.resources.watch_only_descriptors_copied
import com.machankura.bennu.compose.managers.GroupWalletDerivation
@@ -191,7 +190,7 @@ fun GroupWalletScreen(
initialGroupWalletUIState: GroupWalletUIState = GroupWalletUIState.Loading,
chatRepository: ChatRepository,
frostSigningRepository: FrostSigningRepository,
- wallets: GroupOnchainWallets?,
+ wallets: GroupOnchainWallets,
watcher: GroupTransactionWatcher? = null,
onNavigateToRoute: (Route) -> Unit,
onNavigateBack: () -> Unit,
@@ -368,7 +367,7 @@ fun GroupWalletScreen(
notify = notify,
// Behind both gates: a share to propose with, and a node to
// see the coins with -- a spend built blind is not one.
- onSend = if (state.canSign && state.canWatch) {
+ onSend = if (state.canSign) {
{
onNavigateToRoute(
GroupSendRoute(
@@ -400,8 +399,8 @@ fun GroupWalletScreen(
} else null,
isPending = groupWalletViewModel.isActionPending.value,
onShare = onShare,
- onSpend = if (state.canSign && state.canWatch) toGuardianSpend else null,
- onFund = if (state.canSign && state.canWatch) toGuardianFund else null,
+ onSpend = if (state.canSign) toGuardianSpend else null,
+ onFund = if (state.canSign) toGuardianFund else null,
onOpenPerson = toPerson,
)
}
@@ -542,14 +541,6 @@ private fun OpenWallet(
}
when {
- !state.canWatch -> item {
- Text(
- text = stringResource(Res.string.this_profile_cannot_watch_the_chain),
- style = MaterialTheme.typography.bodyMedium,
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- )
- }
-
walletState?.receiveAddress == null -> item {
LoadingDataIndicator(
fillScreen = false,
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberSendScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberSendScreen.kt
index d45bdd7c..36c2fab8 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberSendScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberSendScreen.kt
@@ -66,7 +66,7 @@ fun MemberSendScreen(
chain: Chain,
initialUIState: MemberSendUIState = MemberSendUIState.Loading,
memberWalletRepository: MemberWalletRepository,
- wallets: GroupOnchainWallets?,
+ wallets: GroupOnchainWallets,
onNavigateBack: () -> Unit,
) {
val viewModel: MemberSendViewModel = viewModel(
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt
index 58bb4f6a..9108a61f 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/MemberWalletScreen.kt
@@ -78,7 +78,6 @@ import bennu.composeapp.generated.resources.s_took_s_sats_in_s
import bennu.composeapp.generated.resources.show_key
import bennu.composeapp.generated.resources.taken_by_guardians
import bennu.composeapp.generated.resources.the_key_of_this_wallet_is_on_another_device
-import bennu.composeapp.generated.resources.this_profile_cannot_watch_its_own_coins
import bennu.composeapp.generated.resources.waiting_for_someone_in_s_to_put_it_to_the_group
import bennu.composeapp.generated.resources.whoever_holds_these_descriptors_holds_the_coins
import bennu.composeapp.generated.resources.you_re_no_longer_in_s
@@ -123,7 +122,7 @@ fun MemberWalletScreen(
walletId: String,
initialUIState: MemberWalletUIState = MemberWalletUIState.Loading,
memberWalletRepository: MemberWalletRepository,
- wallets: GroupOnchainWallets?,
+ wallets: GroupOnchainWallets,
/** The send form for this wallet, or null where there is none to offer. */
onSend: ((walletId: String) -> Unit)? = null,
onNavigateBack: () -> Unit,
@@ -254,19 +253,11 @@ fun MemberWalletScreen(
}
}
- onSend?.takeIf { wallet.state == WalletState.OPEN && state.canWatch }?.let { send ->
+ onSend?.takeIf { wallet.state == WalletState.OPEN }?.let { send ->
item { SendButton(onClick = { send(wallet.walletId) }) }
}
when {
- !state.canWatch -> item {
- Text(
- stringResource(Res.string.this_profile_cannot_watch_its_own_coins),
- style = MaterialTheme.typography.bodyMedium,
- color = MaterialTheme.colorScheme.onSurfaceVariant,
- )
- }
-
walletState?.receiveAddress == null -> item {
LoadingDataIndicator(fillScreen = false, text = stringResource(Res.string.finding_your_coins))
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt
index be392384..133814d3 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/NewMemberWalletScreen.kt
@@ -55,7 +55,6 @@ import bennu.composeapp.generated.resources.s_can_take_any_coin_without_asking_y
import bennu.composeapp.generated.resources.this_device_does_not_know_what_this_group_signs_with
import bennu.composeapp.generated.resources.this_group_s_guardian_keys_can_t_be_read_to_guard_a_wallet
import bennu.composeapp.generated.resources.this_profile_cannot_sign_a_request
-import bennu.composeapp.generated.resources.this_profile_cannot_watch_its_own_coins
import bennu.composeapp.generated.resources.none_of_your_groups_guards_members_wallets_yet
import com.machankura.bennu.compose.managers.MemberWalletManager
import com.machankura.bennu.compose.repository.MemberWalletRepository
@@ -90,7 +89,6 @@ fun NewMemberWalletScreen(
activeUserPublicKey: HexKey,
chatRoomId: String?,
chain: Chain,
- canWatch: Boolean,
initialUIState: NewMemberWalletUIState = NewMemberWalletUIState.Loading,
memberWalletRepository: MemberWalletRepository,
onNavigateBack: () -> Unit,
@@ -100,7 +98,6 @@ fun NewMemberWalletScreen(
activeUserPublicKey = activeUserPublicKey,
chatRoomId = chatRoomId,
chain = chain,
- canWatch = canWatch,
initialUIState = initialUIState,
memberWalletRepository = memberWalletRepository,
)
@@ -245,7 +242,6 @@ private fun refusalText(refusal: MemberWalletManager.Refusal): String = stringRe
MemberWalletManager.Refusal.KEY_UNKNOWN -> Res.string.this_device_does_not_know_what_this_group_signs_with
MemberWalletManager.Refusal.GUARDIANS_UNREADABLE -> Res.string.this_group_s_guardian_keys_can_t_be_read_to_guard_a_wallet
MemberWalletManager.Refusal.NOT_ON_THIS_NETWORK -> Res.string.member_wallets_are_not_offered_on_this_network
- MemberWalletManager.Refusal.CANNOT_WATCH -> Res.string.this_profile_cannot_watch_its_own_coins
MemberWalletManager.Refusal.NOT_OFFERED -> Res.string.this_group_doesn_t_guard_members_wallets
MemberWalletManager.Refusal.CLOSED -> Res.string.this_group_has_stopped_guarding_members_wallets
}
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 658732b2..23b045a3 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
@@ -170,6 +170,7 @@ import com.machankura.bennu.compose.ui.composable.MemberWalletScreen
import com.machankura.bennu.compose.ui.composable.NewMemberWalletScreen
import com.machankura.bennu.compose.database.repository.DatabaseMemberWalletRepository
import com.machankura.bennu.compose.wallet.GroupOnchainWallets
+import com.machankura.bennu.compose.wallet.IdentityElectrum
import com.machankura.bennu.compose.wallet.GroupTransactionWatcher
import fr.acinq.phoenix.managers.NodeParamsManager
import com.machankura.bennu.compose.ui.composable.navigation.routes.FrostSigningRoute
@@ -262,21 +263,37 @@ fun BennuNavHost(
)
}
- // The group wallets this identity is watching, on its own node's Electrum
- // client -- null for an nsec or npub profile, which has no node and so no
- // chain to watch. Remade with the node and stopped with it, because a switch
- // of profile is a restart and a wallet left subscribing on the last one's
- // connection is a wallet nobody can see.
+ // The Electrum client this identity watches the chain on: its node's, or --
+ // for an nsec or npub profile, which has no node -- one of its own. Remade
+ // with the identity, the last one stopped first, because a switch of profile
+ // is a restart and a wallet left subscribing on the last one's connection is
+ // a wallet nobody can see. See docs/standalone-electrum.md.
val activeIdentityForWallets by sovereignWalletViewModel.activeIdentity.collectAsState()
- // One Electrum connection per network: the node's own for its network, and one of
- // their own for any other a group keeps a wallet on (testnet3, while a Lightning
- // wallet is tried there). Shared by the wallets and the watcher below.
- val groupChainClients = remember(activeIdentityForWallets?.business) {
- activeIdentityForWallets?.business?.let { GroupChainClients.forNode(NodeParamsManager.chain, it.electrumClient, applicationIOScope, it.loggerFactory) }
+ val identityElectrum = remember {
+ IdentityElectrum(IdentityElectrum.standalone(phoenixGlobal.networkMonitor, phoenixGlobal.loggerFactory))
+ }
+ DisposableEffect(identityElectrum) {
+ onDispose { identityElectrum.stop() }
+ }
+ val electrum = remember(activeIdentityForWallets?.id, activeIdentityForWallets?.business) {
+ identityElectrum.clientFor(activeIdentityForWallets)
+ }
+
+ // One Electrum connection per network: the identity's own -- its node's, or the one a
+ // profile with no node is given -- for the node's network, and one of their own for any
+ // other a group keeps a wallet on (testnet3, while a Lightning wallet is tried there).
+ // Shared by the wallets and the watcher below, and remade with the identity's client.
+ val groupChainClients = remember(electrum) {
+ val identity = activeIdentityForWallets
+ if (electrum == null || identity == null) null else GroupChainClients.forNode(NodeParamsManager.chain, electrum) { chain ->
+ IdentityElectrum.standaloneOn(chain, identity, phoenixGlobal.networkMonitor, phoenixGlobal.loggerFactory)
+ }
}
DisposableEffect(groupChainClients) {
onDispose { groupChainClients?.let { clients -> applicationIOScope.launch { clients.stop() } } }
}
+
+ // The group wallets this identity is watching. Remade with the client.
val groupOnchainWallets = remember(groupChainClients) {
groupChainClients?.let { GroupOnchainWallets(it, applicationIOScope) }
}
@@ -286,12 +303,13 @@ fun BennuNavHost(
// The group Lightning nodes this identity is the elected operator of. Behind the
// rollout gate: nothing is built while it is off. Same lifetime as the wallets.
+ // A group's node is not the identity's own, and needs only an Electrum client: so a
+ // profile with no node -- an nsec or an npub, which has one now -- can run it too.
val groupLightningNodes = remember(groupChainClients) {
- val business = activeIdentityForWallets?.business
val clients = groupChainClients
val user = activeIdentityForWallets?.nostrPublicKey
- if (!GroupLightningRollout.ENABLED || business == null || clients == null || user == null) null else {
- val ctx = business.phoenixGlobal.ctx
+ if (!GroupLightningRollout.ENABLED || clients == null || user == null) null else {
+ val ctx = phoenixGlobal.ctx
GroupLightningNodes(
database = auxDatabaseManager.auxDatabase,
userPublicKey = user,
@@ -301,12 +319,12 @@ fun BennuNavHost(
databasesFor = { nodeId, chain ->
PhoenixDatabases(
channels = createSqliteChannelsDb(createChannelsDbDriver(ctx, "group-" + DatabaseManager.channelsDbName(chain, nodeId))),
- payments = createSqlitePaymentsDb(createPaymentsDbDriver(ctx, "group-" + DatabaseManager.paymentsDbName(chain, nodeId)) {}, null, business.loggerFactory),
+ payments = createSqlitePaymentsDb(createPaymentsDbDriver(ctx, "group-" + DatabaseManager.paymentsDbName(chain, nodeId)) {}, null, phoenixGlobal.loggerFactory),
cloudKit = null,
)
},
walletParamsFor = { chain -> LSP.from(chain).walletParams },
- loggerFactory = business.loggerFactory,
+ loggerFactory = phoenixGlobal.loggerFactory,
scope = applicationIOScope,
),
).also { it.start() }
@@ -318,7 +336,7 @@ fun BennuNavHost(
// Sends the group's signed spends to the network from this device too, and
// follows them to a confirmation -- whether or not anybody opens the wallet.
- // Same lifetime as the wallets: the identity's node, and nothing longer.
+ // Same lifetime as the wallets: the identity's client, and nothing longer.
val groupTransactionWatcher = remember(groupChainClients) {
groupChainClients?.let {
GroupTransactionWatcher(auxDatabaseManager.auxDatabase, it, applicationIOScope).also { watcher -> watcher.start() }
@@ -1275,6 +1293,9 @@ fun BennuNavHost(
}
composable { backStackEntry ->
val route = backStackEntry.toRoute()
+ // Null only with no identity, for the frame between a profile
+ // switch and the startup screen: there is no chain to show yet.
+ val wallets = groupOnchainWallets ?: return@composable
GroupWalletScreen(
activeUserPublicKey = route.activeUserPublicKey,
@@ -1282,7 +1303,7 @@ fun BennuNavHost(
chain = route.chain?.let(GroupWalletStatementEvent::chainNamed) ?: NodeParamsManager.chain,
chatRepository = databaseChatRepository,
frostSigningRepository = databaseFrostSigningRepository,
- wallets = groupOnchainWallets,
+ wallets = wallets,
watcher = groupTransactionWatcher,
onNavigateToRoute = { actionRoute ->
navController.navigate(route = actionRoute)
@@ -1294,12 +1315,13 @@ fun BennuNavHost(
}
composable { backStackEntry ->
val route = backStackEntry.toRoute()
+ val wallets = groupOnchainWallets ?: return@composable
MemberWalletScreen(
activeUserPublicKey = route.activeUserPublicKey,
walletId = route.walletId,
memberWalletRepository = databaseMemberWalletRepository,
- wallets = groupOnchainWallets,
+ wallets = wallets,
onSend = { walletId ->
navController.navigate(route = MemberSendRoute(activeUserPublicKey = route.activeUserPublicKey, walletId = walletId))
},
@@ -1310,13 +1332,14 @@ fun BennuNavHost(
}
composable { backStackEntry ->
val route = backStackEntry.toRoute()
+ val wallets = groupOnchainWallets ?: return@composable
MemberSendScreen(
activeUserPublicKey = route.activeUserPublicKey,
walletId = route.walletId,
chain = NodeParamsManager.chain,
memberWalletRepository = databaseMemberWalletRepository,
- wallets = groupOnchainWallets,
+ wallets = wallets,
onNavigateBack = {
navController.popBackStack()
}
@@ -1346,7 +1369,6 @@ fun BennuNavHost(
activeUserPublicKey = route.activeUserPublicKey,
chatRoomId = route.chatRoomId,
chain = NodeParamsManager.chain,
- canWatch = groupOnchainWallets != null,
memberWalletRepository = databaseMemberWalletRepository,
onNavigateBack = {
navController.popBackStack()
@@ -1355,12 +1377,13 @@ fun BennuNavHost(
}
composable { backStackEntry ->
val route = backStackEntry.toRoute()
+ val wallets = groupOnchainWallets ?: return@composable
GroupWalletAddressesScreen(
chatRoomId = route.chatRoomId,
chain = route.chain?.let(GroupWalletStatementEvent::chainNamed) ?: NodeParamsManager.chain,
chatRepository = databaseChatRepository,
- wallets = groupOnchainWallets,
+ wallets = wallets,
onNavigateBack = {
navController.popBackStack()
}
@@ -1368,6 +1391,7 @@ fun BennuNavHost(
}
composable { backStackEntry ->
val route = backStackEntry.toRoute()
+ val wallets = groupOnchainWallets ?: return@composable
GroupSendScreen(
activeUserPublicKey = route.activeUserPublicKey,
@@ -1375,7 +1399,7 @@ fun BennuNavHost(
chain = route.chain?.let(GroupWalletStatementEvent::chainNamed) ?: NodeParamsManager.chain,
chatRepository = databaseChatRepository,
frostSigningRepository = databaseFrostSigningRepository,
- wallets = groupOnchainWallets,
+ wallets = wallets,
guardedChatRoomId = route.guardedChatRoomId,
fundChatRoomId = route.fundChatRoomId,
onNavigateToRouteAndPopUpInclusive = { signingRoute ->
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 4c5ba66a..3a30e1ab 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
@@ -53,7 +53,7 @@ class GroupSendViewModel(
initialGroupSendUIState: GroupSendUIState,
val chatRepository: ChatRepository,
val frostSigningRepository: FrostSigningRepository,
- private val wallets: GroupOnchainWallets?,
+ 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. */
@@ -103,7 +103,7 @@ class GroupSendViewModel(
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 || (fundChatRoomId != null && funded == null)) {
+ if (wallet == null || !canSign || (fundChatRoomId != null && funded == null)) {
groupSendUIState = GroupSendUIState.Unavailable
return@launch
}
@@ -284,7 +284,7 @@ class GroupSendViewModel(
initialGroupSendUIState: GroupSendUIState = GroupSendUIState.Loading,
chatRepository: ChatRepository,
frostSigningRepository: FrostSigningRepository,
- wallets: GroupOnchainWallets?,
+ wallets: GroupOnchainWallets,
guardedChatRoomId: String? = null,
fundChatRoomId: String? = null,
): ViewModelProvider.Factory = viewModelFactory {
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModel.kt
index b40ce5e3..50d49331 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModel.kt
@@ -29,7 +29,7 @@ class GroupWalletAddressesViewModel(
val chain: Chain,
initialUIState: GroupWalletAddressesUIState,
val chatRepository: ChatRepository,
- private val wallets: GroupOnchainWallets?,
+ private val wallets: GroupOnchainWallets,
): ViewModel() {
var uiState: GroupWalletAddressesUIState by mutableStateOf(initialUIState)
private set
@@ -62,10 +62,6 @@ class GroupWalletAddressesViewModel(
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 ->
@@ -91,7 +87,7 @@ class GroupWalletAddressesViewModel(
chain: Chain,
initialUIState: GroupWalletAddressesUIState = GroupWalletAddressesUIState.Loading,
chatRepository: ChatRepository,
- wallets: GroupOnchainWallets?,
+ wallets: GroupOnchainWallets,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
GroupWalletAddressesViewModel(
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt
index a4975f44..5338fa17 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModel.kt
@@ -49,8 +49,8 @@ import kotlinx.coroutines.withContext
* coins are a watch, because a payment arriving while the screen is open is the
* one moment somebody is looking at it.
*
- * [wallets] is null for a profile with no node of its own -- an nsec or an npub
- * -- which can see that the group keeps a wallet, and cannot see the chain.
+ * [wallets] watch on the identity's Electrum client: its node's, or for an nsec
+ * or npub profile one of its own (docs/standalone-electrum.md).
*/
class GroupWalletViewModel(
val activeUserPublicKey: HexKey,
@@ -59,7 +59,7 @@ class GroupWalletViewModel(
initialGroupWalletUIState: GroupWalletUIState,
val chatRepository: ChatRepository,
val frostSigningRepository: FrostSigningRepository,
- private val wallets: GroupOnchainWallets?,
+ private val wallets: GroupOnchainWallets,
private val watcher: GroupTransactionWatcher? = null,
): ViewModel() {
private val logger = Logger.withTag(TAG)
@@ -122,7 +122,6 @@ class GroupWalletViewModel(
localChatRoom = localChatRoom,
wallet = wallet,
walletState = null,
- canWatch = wallets != null,
canSign = canSign,
guardedWallets = guardedRows,
shareable = shareable,
@@ -133,7 +132,7 @@ class GroupWalletViewModel(
// The chain, the room's spends and the wallets it guards, as one
// state: any of them changing redraws the screen, and none may
// overwrite another.
- val chainState = wallets?.walletFor(wallet.account)?.state ?: flowOf(null)
+ val chainState = wallets.walletFor(wallet.account).state
noticeGuardianSpends(wallet.account)
watching = viewModelScope.launch(Dispatchers.IO) {
combine(
@@ -149,10 +148,6 @@ class GroupWalletViewModel(
}
}
- /**
- * Each guarded wallet with what the chain says of it, on the identity's own
- * Electrum client -- or with nothing, for a profile that cannot watch.
- */
/**
* What this device calls each of [guardians]' rooms, for the ones it holds:
* the wallet screen lists each guardian with its own delay, and a room id is
@@ -164,9 +159,9 @@ class GroupWalletViewModel(
chatRepository.getChatRoomByIdentifier(guardian.chatRoomId)?.chatRoom?.subject?.let { guardian.chatRoomId to it }
}.toMap()
+ /** Each guarded wallet with what the chain says of it, on the identity's Electrum client. */
private suspend fun guardedStates(guarded: List): Flow> {
- val wallets = wallets
- if (wallets == null || guarded.isEmpty()) return flowOf(guarded.map { GuardedWalletRow(it, walletState = null) })
+ if (guarded.isEmpty()) return flowOf(emptyList())
val states = guarded.map { wallet -> wallets.walletFor(wallet.account).state.map { GuardedWalletRow(wallet, it) } }
return combine(states) { it.toList() }
@@ -180,7 +175,6 @@ class GroupWalletViewModel(
* 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)
@@ -332,7 +326,7 @@ class GroupWalletViewModel(
initialGroupWalletUIState: GroupWalletUIState = GroupWalletUIState.Loading,
chatRepository: ChatRepository,
frostSigningRepository: FrostSigningRepository,
- wallets: GroupOnchainWallets?,
+ wallets: GroupOnchainWallets,
watcher: GroupTransactionWatcher? = null,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberSendViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberSendViewModel.kt
index 04ff5fa1..de7d23be 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberSendViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberSendViewModel.kt
@@ -47,7 +47,7 @@ class MemberSendViewModel(
val chain: Chain,
initialUIState: MemberSendUIState,
private val memberWalletRepository: MemberWalletRepository,
- private val wallets: GroupOnchainWallets?,
+ private val wallets: GroupOnchainWallets,
) : ViewModel() {
private val logger = Logger.withTag(TAG)
@@ -70,7 +70,7 @@ class MemberSendViewModel(
uiState = MemberSendUIState.Error("Couldn't find this wallet")
return@launch
}
- if (wallet.state != MemberWalletManager.WalletState.OPEN || wallets == null) {
+ if (wallet.state != MemberWalletManager.WalletState.OPEN) {
uiState = MemberSendUIState.Unavailable
return@launch
}
@@ -151,7 +151,6 @@ class MemberSendViewModel(
/** Signs what the form describes and hands it to Electrum. [onSent] when it went, [onFailure] when it did not. */
fun send(onSent: () -> Unit, onFailure: () -> Unit) {
val built = preview() as? GroupSpendBuilder.Result.Built ?: return
- val wallets = wallets ?: return
if (isActionPending.value) return
isActionPending.value = true
@@ -178,7 +177,7 @@ class MemberSendViewModel(
chain: Chain,
initialUIState: MemberSendUIState = MemberSendUIState.Loading,
memberWalletRepository: MemberWalletRepository,
- wallets: GroupOnchainWallets?,
+ wallets: GroupOnchainWallets,
): ViewModelProvider.Factory = viewModelFactory {
initializer { MemberSendViewModel(ownerPublicKey, walletId, chain, initialUIState, memberWalletRepository, wallets) }
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt
index 41253f85..df50ca74 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletViewModel.kt
@@ -39,7 +39,7 @@ class MemberWalletViewModel(
walletId: String,
initialUIState: MemberWalletUIState,
private val memberWalletRepository: MemberWalletRepository,
- private val wallets: GroupOnchainWallets?,
+ private val wallets: GroupOnchainWallets,
) : ViewModel() {
private val logger = Logger.withTag(TAG)
@@ -69,11 +69,11 @@ class MemberWalletViewModel(
uiState = MemberWalletUIState.Error("Couldn't find this wallet")
return@launch
}
- val loaded = MemberWalletUIState.Loaded(wallet = wallet, canWatch = wallets != null)
+ val loaded = MemberWalletUIState.Loaded(wallet = wallet)
uiState = loaded
watching?.cancel()
- if (!wallet.isCertified || wallets == null) return@launch
+ if (!wallet.isCertified) return@launch
watching = viewModelScope.launch(Dispatchers.IO) {
var taken = emptyList()
combine(
@@ -104,7 +104,6 @@ class MemberWalletViewModel(
* record for the next one that does.
*/
private suspend fun follow(spends: List, chain: Chain) {
- val wallets = wallets ?: return
spends.filter { it.confirmedAt == null && it.replacedByTxid == null }.forEach { spend ->
val tx = runCatching { Transaction.read(spend.signedTransaction) }.getOrNull() ?: return@forEach
val confirmations = wallets.confirmationsOf(tx, chain)
@@ -152,7 +151,7 @@ class MemberWalletViewModel(
walletId: String,
initialUIState: MemberWalletUIState = MemberWalletUIState.Loading,
memberWalletRepository: MemberWalletRepository,
- wallets: GroupOnchainWallets?,
+ wallets: GroupOnchainWallets,
): ViewModelProvider.Factory = viewModelFactory {
initializer { MemberWalletViewModel(ownerPublicKey, walletId, initialUIState, memberWalletRepository, wallets) }
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletsViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletsViewModel.kt
index a6d97d86..ab169281 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletsViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/MemberWalletsViewModel.kt
@@ -21,8 +21,8 @@ import kotlinx.coroutines.launch
/**
* A member's guarded wallets, as their profile lists them: each one's state,
- * and -- for the ones a group has certified, on a profile that can watch the
- * chain -- its balance.
+ * and -- for the ones a group has certified -- its balance. [wallets] is null
+ * only where the profile is composed without an identity: previews and tests.
*/
class MemberWalletsViewModel(
private val ownerPublicKey: HexKey,
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModel.kt
index b84d07b8..c902c4dc 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModel.kt
@@ -27,15 +27,11 @@ import kotlinx.coroutines.withContext
* the button is drawn and again inside `MemberWalletManager.request`, the way
* the subgroup picker refuses: the screen keeps a member out of a dead end, the
* manager keeps a bug out of the room.
- *
- * [canWatch] is whether this profile has an Electrum client: one without could
- * not see its own coins, so it is not offered a wallet it cannot see (D3).
*/
class NewMemberWalletViewModel(
val activeUserPublicKey: HexKey,
private val chatRoomId: String?,
private val chain: Chain,
- private val canWatch: Boolean,
initialUIState: NewMemberWalletUIState,
private val memberWalletRepository: MemberWalletRepository,
) : ViewModel() {
@@ -84,7 +80,6 @@ class NewMemberWalletViewModel(
private suspend fun refusal(chatRoomId: String): MemberWalletManager.Refusal? =
memberWalletRepository.refusal(chatRoomId, chain)
- ?: if (!canWatch) MemberWalletManager.Refusal.CANNOT_WATCH else null
fun askForGroupKey() {
val chosen = uiState as? NewMemberWalletUIState.Chosen ?: return
@@ -127,12 +122,11 @@ class NewMemberWalletViewModel(
activeUserPublicKey: HexKey,
chatRoomId: String?,
chain: Chain,
- canWatch: Boolean,
initialUIState: NewMemberWalletUIState = NewMemberWalletUIState.Loading,
memberWalletRepository: MemberWalletRepository,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
- NewMemberWalletViewModel(activeUserPublicKey, chatRoomId, chain, canWatch, initialUIState, memberWalletRepository)
+ NewMemberWalletViewModel(activeUserPublicKey, chatRoomId, chain, initialUIState, memberWalletRepository)
}
}
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletAddressesUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletAddressesUIState.kt
index e175f29c..42b9445e 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletAddressesUIState.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupWalletAddressesUIState.kt
@@ -16,12 +16,6 @@ sealed interface GroupWalletAddressesUIState {
val change: List = emptyList(),
): 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
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 3e35453b..794b10b6 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
@@ -52,15 +52,12 @@ sealed interface GroupWalletUIState {
/**
* An open wallet.
*
- * [walletState] is null in two different situations, told apart by
- * [canWatch]: before Electrum's first answer, and for a profile with no node
- * to watch the chain with at all.
+ * [walletState] is null before Electrum's first answer.
*/
data class Loaded(
val localChatRoom: LocalChatRoom,
val wallet: GroupWallet,
val walletState: GroupWalletState?,
- val canWatch: Boolean,
val canSign: Boolean,
/** The room's spends, newest first. */
val spends: List = emptyList(),
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletUIState.kt
index ea2ddb31..94df027b 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletUIState.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/MemberWalletUIState.kt
@@ -12,10 +12,8 @@ sealed interface MemberWalletUIState {
data class Loaded(
val wallet: MemberWalletManager.MemberWalletRow,
- /** Null before Electrum's first answer, for a wallet no group has certified, and for a profile that cannot watch the chain. */
+ /** Null before Electrum's first answer, and for a wallet no group has certified. */
val walletState: GroupWalletState? = null,
- /** Whether this profile has an Electrum client to watch the chain with. */
- val canWatch: Boolean,
/** What the wallet's guardians took from it, read off the chain: never stored, found again on each look. */
val taken: List = emptyList(),
/** The spends the member signed from it, newest first. */
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainClients.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainClients.kt
index fd7eabf3..d643fb9b 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainClients.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/GroupChainClients.kt
@@ -1,31 +1,20 @@
package com.machankura.bennu.compose.wallet
-import co.touchlab.kermit.Logger
import fr.acinq.bitcoin.Chain
-import fr.acinq.lightning.blockchain.electrum.ElectrumClient
-import fr.acinq.lightning.blockchain.electrum.ElectrumConnectionStatus
-import fr.acinq.lightning.blockchain.electrum.ElectrumServers
import fr.acinq.lightning.blockchain.electrum.IElectrumClient
-import fr.acinq.lightning.io.TcpSocket
-import fr.acinq.lightning.logging.LoggerFactory
-import kotlinx.coroutines.CancellationException
-import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Job
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.isActive
-import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
-import kotlin.time.Duration.Companion.seconds
/**
* The Electrum connection each network's group wallets watch through, for one identity.
*
- * The identity's own node has one, for the network the node runs on, and every wallet on that network
- * shares it as before. A group may keep a wallet on another network as well -- testnet3, while its
- * Lightning wallet is tried there (`docs/group-lightning-wallet.md`, Phase 4) -- and that network gets a
- * connection of its own, made the first time a wallet on it asks and kept for the identity's life, for
- * the reason [GroupOnchainWallets] keeps its wallets: a subscription is cheap and the first answer slow.
+ * The identity has one for the network its node runs on -- the node's own, or for a profile with no
+ * node the one `IdentityElectrum` gives it -- and every wallet on that network shares it. A group may
+ * keep a wallet on another network as well -- testnet3, while its Lightning wallet is tried there
+ * (`docs/group-lightning-wallet.md`, Phase 4) -- and that network gets a [StandaloneElectrum] of its
+ * own, made the first time a wallet on it asks and kept for the identity's life, for the reason
+ * [GroupOnchainWallets] keeps its wallets: a subscription is cheap and the first answer slow. Being the
+ * same loop as the identity's own, it follows the profile's Tor setting.
*/
class GroupChainClients(
private val nodeChain: Chain,
@@ -52,39 +41,15 @@ class GroupChainClients(
GroupChainClients(Chain.Mainnet, client) { Connection(client) {} }
/**
- * The identity's node for its own network, and a standalone [ElectrumClient] on a random public
- * server for any other that lightning-kmp lists servers for (mainnet and testnet3), reconnecting
- * whenever it drops.
+ * The identity's client for its own network -- its node's, or the one a profile with no node
+ * is given -- and, for any other network a group keeps a wallet on, a [StandaloneElectrum]
+ * from [standaloneFor]: the same connection loop the identity's own uses, so the same
+ * server choice, the same pauses, and the same refusal of a clearnet server while Tor is on.
*/
- fun forNode(nodeChain: Chain, nodeClient: IElectrumClient, scope: CoroutineScope, loggerFactory: LoggerFactory): GroupChainClients =
- GroupChainClients(nodeChain, nodeClient) { chain -> standalone(chain, scope, loggerFactory) }
-
- private fun standalone(chain: Chain, scope: CoroutineScope, loggerFactory: LoggerFactory): Connection {
- val logger = Logger.withTag("GroupChainClients")
- val client = ElectrumClient(scope, loggerFactory, pingInterval = 30.seconds, rpcTimeout = 10.seconds)
- val socketBuilder = TcpSocket.Builder()
- val job: Job = scope.launch {
- var backoff = 1.seconds
- while (isActive) {
- if (client.connectionStatus.value is ElectrumConnectionStatus.Closed) {
- val server = ElectrumServers.pickElectrumServer(chain)
- val connected = try {
- client.connect(server, socketBuilder)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Throwable) {
- logger.w("Could not reach ${server.host} for $chain", e)
- false
- }
- backoff = if (connected) 1.seconds else (backoff * 2).coerceAtMost(60.seconds)
- }
- delay(backoff)
- }
+ fun forNode(nodeChain: Chain, nodeClient: IElectrumClient, standaloneFor: (Chain) -> StandaloneElectrum): GroupChainClients =
+ GroupChainClients(nodeChain, nodeClient) { chain ->
+ val standalone = standaloneFor(chain).also { it.start() }
+ Connection(standalone.client) { standalone.stop() }
}
- return Connection(client) {
- job.cancel()
- client.stop()
- }
- }
}
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrum.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrum.kt
new file mode 100644
index 00000000..cc4af47e
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrum.kt
@@ -0,0 +1,90 @@
+package com.machankura.bennu.compose.wallet
+
+import co.touchlab.kermit.Logger
+import com.machankura.bennu.compose.identity.Identity
+import fr.acinq.bitcoin.Chain
+import fr.acinq.lightning.blockchain.electrum.IElectrumClient
+import fr.acinq.lightning.logging.LoggerFactory
+import fr.acinq.phoenix.data.WalletId
+import fr.acinq.phoenix.managers.NodeParamsManager
+import fr.acinq.phoenix.managers.global.NetworkMonitor
+import kotlinx.coroutines.flow.flowOf
+
+/**
+ * The Electrum client the active identity watches the chain on.
+ *
+ * A profile with a node watches on the node's client; one with no node -- an nsec
+ * or an npub -- gets a [StandaloneElectrum] of its own. Never both: a second
+ * connection from a profile that has one would tell a second server the same
+ * addresses, and give the wallets a chain that can disagree with the node's (D1 of
+ * `docs/standalone-electrum.md`). The test is the node client, not the kind, as
+ * `switchToIdentity` tests `business`.
+ *
+ * One per app, held by the nav host. A change of identity stops the last
+ * standalone client *before* the next is made, so a switch between two nsec
+ * profiles never has two connections open; a stopped client cannot be restarted,
+ * so the next is always new.
+ */
+class IdentityElectrum(
+ private val standaloneFor: (Identity) -> StandaloneElectrum,
+) {
+ private val logger = Logger.withTag("IdentityElectrum")
+
+ private var key: Pair? = null
+ private var client: IElectrumClient? = null
+ private var standalone: StandaloneElectrum? = null
+
+ /**
+ * The client for [identity], made the first time it is asked for and kept while
+ * it stays the same identity on the same node. Null only with no identity.
+ */
+ fun clientFor(identity: Identity?, nodeClient: IElectrumClient? = identity?.business?.electrumClient): IElectrumClient? {
+ val next = identity?.let { it.id to nodeClient }
+ if (next == key) return client
+
+ stop()
+ key = next
+ client = when {
+ identity == null -> null
+ nodeClient != null -> nodeClient
+ else -> {
+ logger.i { "starting an Electrum client for ${identity.id}, which has no node" }
+ standaloneFor(identity).also { it.start() }.also { standalone = it }.client
+ }
+ }
+ return client
+ }
+
+ /** Stops the standalone client, if the identity has one. The node's is the node's to stop. */
+ fun stop() {
+ standalone?.stop()
+ standalone = null
+ client = null
+ key = null
+ }
+
+ companion object {
+ /** The real thing: the identity's own Electrum preferences, the device's network, the node's network. */
+ fun standalone(networkMonitor: NetworkMonitor, loggerFactory: LoggerFactory): (Identity) -> StandaloneElectrum = { identity ->
+ standaloneOn(NodeParamsManager.chain, identity, networkMonitor, loggerFactory)
+ }
+
+ /**
+ * A standalone client for [identity] on [chain]. On the node's own network it takes the
+ * identity's custom server, if one is set; on any other -- testnet3, for a group's Lightning
+ * wallet -- that server is for the wrong network, so it takes a random one. Tor and the
+ * device's network apply either way.
+ */
+ fun standaloneOn(chain: Chain, identity: Identity, networkMonitor: NetworkMonitor, loggerFactory: LoggerFactory): StandaloneElectrum {
+ // Idempotent on every platform, and otherwise only the node's daemon calls it.
+ networkMonitor.start()
+ return StandaloneElectrum(
+ chain = chain,
+ networkState = networkMonitor.networkState,
+ isTorEnabled = identity.userPrefs.getIsTorEnabled,
+ customServer = if (chain == NodeParamsManager.chain) identity.userPrefs.getElectrumServer else flowOf(null),
+ link = ElectrumClientLink(loggerFactory),
+ )
+ }
+ }
+}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/StandaloneElectrum.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/StandaloneElectrum.kt
new file mode 100644
index 00000000..ed4d03e3
--- /dev/null
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/StandaloneElectrum.kt
@@ -0,0 +1,207 @@
+package com.machankura.bennu.compose.wallet
+
+import co.touchlab.kermit.Logger
+import fr.acinq.bitcoin.Chain
+import fr.acinq.lightning.blockchain.electrum.ElectrumClient
+import fr.acinq.lightning.blockchain.electrum.IElectrumClient
+import fr.acinq.lightning.io.TcpSocket
+import fr.acinq.lightning.logging.LoggerFactory
+import fr.acinq.lightning.utils.Connection
+import fr.acinq.lightning.utils.ServerAddress
+import fr.acinq.phoenix.data.ElectrumConfig
+import fr.acinq.phoenix.data.mainnetElectrumServers
+import fr.acinq.phoenix.data.mainnetElectrumServersOnion
+import fr.acinq.phoenix.data.platformElectrumRegtestConf
+import fr.acinq.phoenix.data.testnetElectrumServers
+import fr.acinq.phoenix.data.testnetElectrumServersOnion
+import fr.acinq.phoenix.managers.global.NetworkState
+import fr.acinq.phoenix.utils.extensions.isOnion
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.launch
+import kotlin.coroutines.CoroutineContext
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.seconds
+
+/**
+ * An Electrum connection for a profile with no node: an nsec or an npub.
+ *
+ * A mnemonic profile watches the chain on its node's client, which the node's
+ * `AppConnectionsDaemon` keeps connected. That daemon is built from a
+ * `PhoenixBusiness` and cannot be had without one, so this is its Electrum branch
+ * with the business taken out: the same server choice, the same pauses between
+ * attempts, the same handshake timeouts, and the same refusal of a clearnet server
+ * the user asked to reach only over Tor. See `docs/standalone-electrum.md`.
+ *
+ * The server comes from the identity's own preferences -- a custom server if one
+ * is set, a random one for [chain] if not -- and any change to them, or to Tor, or
+ * to the network, drops the connection and starts again, as the daemon does.
+ *
+ * One per identity, and never restarted: [stop] stops the client for good, which
+ * is what `ElectrumClient.stop` means, so a profile switch makes a new one.
+ */
+class StandaloneElectrum(
+ private val chain: Chain,
+ private val networkState: Flow,
+ private val isTorEnabled: Flow,
+ private val customServer: Flow,
+ private val link: ElectrumLink,
+ private val randomServer: (Chain, Boolean) -> ServerAddress? = ::randomElectrumServer,
+ context: CoroutineContext = Dispatchers.Default,
+) {
+ private val logger = Logger.withTag("StandaloneElectrum")
+ private val scope = CoroutineScope(SupervisorJob() + context)
+ private var job: Job? = null
+
+ /** What every wallet of the identity watches on. */
+ val client: IElectrumClient get() = link.client
+
+ /** What the connection depends on: a change in any of it is a fresh start. */
+ private data class Control(
+ val internetIsAvailable: Boolean,
+ val torIsEnabled: Boolean,
+ val customServer: ElectrumConfig.Custom?,
+ )
+
+ fun start() {
+ if (job != null) return
+ job = scope.launch {
+ combine(
+ networkState.map { it == NetworkState.Available },
+ isTorEnabled,
+ customServer,
+ ) { internet, tor, custom -> Control(internet, tor, custom) }
+ .distinctUntilChanged()
+ .collectLatest { control ->
+ // collectLatest has already cancelled the last loop; the socket it
+ // left open is closed here, so the new control starts from CLOSED.
+ link.disconnect()
+ if (control.internetIsAvailable) connectionLoop(control)
+ }
+ }
+ }
+
+ /** Stops the client for good. It cannot be started again. */
+ fun stop() {
+ job?.cancel()
+ job = null
+ link.stop()
+ scope.cancel()
+ }
+
+ /**
+ * Connects whenever the connection is closed, after a pause that grows with each
+ * failure in a row and resets once a connection is made. The daemon's
+ * `connectionLoop`, for one connection.
+ */
+ private suspend fun connectionLoop(control: Control) {
+ var attempt = 0
+ link.client.connectionStatus.map { it.toConnectionState() }.collect { state ->
+ if (state is Connection.CLOSED) {
+ delay(pauseBefore(attempt))
+ attempt++
+ connect(control, attempt)
+ } else if (state == Connection.ESTABLISHED) {
+ attempt = 0
+ }
+ }
+ }
+
+ private suspend fun connect(control: Control, attempt: Int) {
+ val server = control.customServer?.server ?: randomServer(chain, control.torIsEnabled)
+ if (server == null) {
+ logger.w { "no Electrum server for $chain; not connecting" }
+ return
+ }
+ // The same rule as the node's: a custom server the user wants reached only
+ // through Tor is not reached at all while Tor is on and it is not an onion.
+ if (control.torIsEnabled && !server.isOnion && control.customServer?.requireOnionIfTorEnabled == true) {
+ logger.e { "not connecting to ${server.host}: Tor is on and the server must be an onion address" }
+ return
+ }
+ logger.i { "connecting to ${server.host}:${server.port}, attempt $attempt" }
+ try {
+ link.connect(server, handshakeTimeout(attempt, control.torIsEnabled))
+ } catch (e: Exception) {
+ logger.e("could not connect to Electrum", e)
+ }
+ }
+
+ companion object {
+ /** The daemon's `connectionPause`, unchanged. */
+ fun pauseBefore(attempt: Int): Duration = when {
+ attempt <= 0 -> 0.1.seconds
+ attempt == 1 -> 0.25.seconds
+ attempt == 2 -> 0.5.seconds
+ attempt == 3 -> 1.seconds
+ attempt == 4 -> 2.seconds
+ attempt == 5 -> 4.seconds
+ else -> 8.seconds
+ }
+
+ /** The daemon's handshake timeouts: short at first for a snappy start, longer as failures add up. */
+ fun handshakeTimeout(attempt: Int, torIsEnabled: Boolean): Duration = when {
+ torIsEnabled && attempt <= 6 -> 20.seconds
+ torIsEnabled -> 40.seconds
+ attempt <= 3 -> 4.seconds
+ attempt <= 6 -> 7.seconds
+ attempt <= 10 -> 15.seconds
+ else -> 20.seconds
+ }
+ }
+}
+
+/**
+ * The part of an Electrum client the loop drives, beyond what the wallets read.
+ *
+ * A seam so the loop can be tested against a connection status the test moves,
+ * with no socket. [ElectrumClientLink] is the real one.
+ */
+interface ElectrumLink {
+ val client: IElectrumClient
+ suspend fun connect(server: ServerAddress, timeout: Duration)
+ fun disconnect()
+ fun stop()
+}
+
+/** An [ElectrumLink] over lightning-kmp's own client, with the platform's sockets. */
+class ElectrumClientLink(loggerFactory: LoggerFactory) : ElectrumLink {
+ // Its own scope, as PhoenixBusiness gives the node's: the client's listen job
+ // must not take the app's scope down with it, and [stop] cancels it.
+ private val electrumScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ private val electrum = ElectrumClient(scope = electrumScope, loggerFactory = loggerFactory, pingInterval = 30.seconds, rpcTimeout = 10.seconds)
+
+ override val client: IElectrumClient get() = electrum
+
+ override suspend fun connect(server: ServerAddress, timeout: Duration) {
+ electrum.connect(server, TcpSocket.Builder(), timeout)
+ }
+
+ override fun disconnect() = electrum.disconnect()
+
+ override fun stop() {
+ electrum.stop()
+ electrumScope.cancel()
+ }
+}
+
+/**
+ * A random server from the hard-coded list for [chain]: `AppConfigurationManager.randomElectrumServer`,
+ * which needs a business to be called. Null for the networks that list has no
+ * servers for, where the manager's own answer is `TODO()`.
+ */
+fun randomElectrumServer(chain: Chain, isTorEnabled: Boolean): ServerAddress? = when (chain) {
+ Chain.Mainnet -> if (isTorEnabled) mainnetElectrumServersOnion.random() else mainnetElectrumServers.random()
+ Chain.Testnet3 -> if (isTorEnabled) testnetElectrumServersOnion.random() else testnetElectrumServers.random()
+ Chain.Regtest -> platformElectrumRegtestConf()
+ else -> null
+}
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 d6c1de2c..2692d023 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
@@ -1,5 +1,9 @@
package com.machankura.bennu.compose.ui.composable
+import com.machankura.bennu.compose.wallet.GroupOnchainWallets
+import com.machankura.bennu.compose.wallet.FakeElectrum
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.CoroutineScope
import com.machankura.bennu.compose.managers.GuardianDerivation
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
@@ -200,7 +204,8 @@ class GroupSendScreenJvmTest {
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,
+ // Never asked: the state is given, so nothing is watched.
+ wallets = GroupOnchainWallets(FakeElectrum(), CoroutineScope(SupervisorJob())),
onNavigateToRouteAndPopUpInclusive = {},
onNavigateBack = {},
)
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
index 3a71f282..550613b3 100644
--- 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
@@ -1,5 +1,9 @@
package com.machankura.bennu.compose.ui.composable
+import com.machankura.bennu.compose.wallet.GroupOnchainWallets
+import com.machankura.bennu.compose.wallet.FakeElectrum
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.CoroutineScope
import com.machankura.bennu.compose.managers.GuardianDerivation
import com.machankura.bennu.compose.managers.LineageExample
import com.machankura.bennu.compose.managers.LineageExample.heldBy
@@ -110,7 +114,6 @@ class GuardedWalletCardJvmTest {
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))),
)
@@ -130,7 +133,8 @@ class GuardedWalletCardJvmTest {
initialGroupWalletUIState = state,
chatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY,
frostSigningRepository = FrostSigningRepository.NO_OP_FROST_SIGNING_REPOSITORY,
- wallets = null,
+ // Never asked: the state is given, so nothing is watched.
+ wallets = GroupOnchainWallets(FakeElectrum(), CoroutineScope(SupervisorJob())),
onNavigateToRoute = onRoute,
onNavigateBack = {},
)
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 bd9cc020..0f957a28 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
@@ -1,5 +1,10 @@
package com.machankura.bennu.compose.ui.view.model
+import com.machankura.bennu.compose.wallet.GroupOnchainWallets
+import com.machankura.bennu.compose.wallet.FakeElectrum
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.CoroutineScope
import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd
import com.machankura.bennu.compose.database.model.ChatRoom
import com.machankura.bennu.compose.database.model.FrostSigningSession
@@ -63,8 +68,15 @@ class GroupSendViewModelJvmTest {
@BeforeTest
fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher())
+ /** A chain with nothing on it: what is under test here is the form, not the coins. */
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ private val wallets = GroupOnchainWallets(FakeElectrum(), scope)
+
@AfterTest
- fun tearDown() = Dispatchers.resetMain()
+ fun tearDown() {
+ scope.cancel()
+ Dispatchers.resetMain()
+ }
private val chatRoomId = "d4c3b2a1".repeat(8)
private val localChatRoom = LocalChatRoom(
@@ -113,13 +125,13 @@ class GroupSendViewModelJvmTest {
chat: ChatRepository = ChatRepository.NO_OP_CHAT_REPOSITORY,
signing: FrostSigningRepository = RecordingSigning(),
chain: Chain = Chain.Regtest,
- ) = GroupSendViewModel("a".repeat(64), chatRoomId, chain, initial, chat, signing, wallets = null)
+ ) = GroupSendViewModel("a".repeat(64), chatRoomId, chain, initial, chat, signing, wallets = wallets)
@Test
- fun `a profile with no node is not offered the form`() {
+ fun `a member with no share is not offered the form`() {
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 canSign(chatRoomId: String) = false
override suspend fun groupWallet(chatRoomId: String, chain: Chain) = wallet
}
val model = viewModel(GroupSendUIState.Loading, chat).apply { initiate() }
@@ -345,13 +357,13 @@ class GroupSendViewModelJvmTest {
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,
+ val both = GroupSendViewModel("a".repeat(64), chatRoomId, Chain.Regtest, GroupSendUIState.Loading, chat, RecordingSigning(), wallets = wallets,
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,
+ val unknown = GroupSendViewModel("a".repeat(64), chatRoomId, Chain.Regtest, GroupSendUIState.Loading, chat, RecordingSigning(), wallets = wallets,
fundChatRoomId = descendantRoomId).apply { initiate() }
runBlocking { withTimeout(5_000) { while (unknown.groupSendUIState == GroupSendUIState.Loading) delay(10) } }
assertEquals(GroupSendUIState.Unavailable, unknown.groupSendUIState)
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModelJvmTest.kt
index 8da5153d..941f7dfa 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModelJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletAddressesViewModelJvmTest.kt
@@ -73,7 +73,7 @@ class GroupWalletAddressesViewModelJvmTest {
override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = opened
}
- private fun viewModel(opened: GroupWallet?, wallets: GroupOnchainWallets?) =
+ private fun viewModel(opened: GroupWallet?, wallets: GroupOnchainWallets = GroupOnchainWallets(FakeElectrum(), scope)) =
GroupWalletAddressesViewModel(
chatRoomId = chatRoomId,
chain = Chain.Regtest,
@@ -94,15 +94,7 @@ class GroupWalletAddressesViewModelJvmTest {
@Test
fun `a room with no wallet has no addresses to list`() {
- assertIs(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 },
- )
+ assertIs(viewModel(opened = null).until { it != GroupWalletAddressesUIState.Loading })
}
@Test
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt
index 096be9ac..6e3d81c4 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupWalletViewModelJvmTest.kt
@@ -1,5 +1,10 @@
package com.machankura.bennu.compose.ui.view.model
+import com.machankura.bennu.compose.wallet.GroupOnchainWallets
+import com.machankura.bennu.compose.wallet.FakeElectrum
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.CoroutineScope
import kotlin.test.assertTrue
import com.machankura.bennu.compose.nostr.subgroup.WalletPolicyReading
import com.machankura.bennu.compose.nostr.subgroup.SubgroupWalletPolicy
@@ -49,8 +54,14 @@ class GroupWalletViewModelJvmTest {
@BeforeTest
fun setUp() = Dispatchers.setMain(UnconfinedTestDispatcher())
+ /** A chain with nothing on it: the wallet screen's rules, not its coins. */
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
@AfterTest
- fun tearDown() = Dispatchers.resetMain()
+ fun tearDown() {
+ scope.cancel()
+ Dispatchers.resetMain()
+ }
private val chatRoomId = "d4c3b2a1".repeat(8)
private val me = "a".repeat(64)
@@ -118,7 +129,7 @@ class GroupWalletViewModelJvmTest {
initialGroupWalletUIState = GroupWalletUIState.Loading,
chatRepository = chat,
frostSigningRepository = signing,
- wallets = null,
+ wallets = GroupOnchainWallets(FakeElectrum(), scope),
)
private fun GroupWalletViewModel.settled(): GroupWalletUIState = runBlocking {
@@ -146,12 +157,10 @@ class GroupWalletViewModelJvmTest {
}
@Test
- fun `an open wallet on a profile with no node is shown, and says it cannot watch`() {
+ fun `an open wallet is shown`() {
val state = assertIs(viewModel(repository(opened = wallet)).apply { initiate() }.settled())
assertEquals(wallet, state.wallet)
- assertFalse(state.canWatch)
- assertNull(state.walletState)
}
@Test
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModelJvmTest.kt
index 3479f48c..dcb7da8b 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModelJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/NewMemberWalletViewModelJvmTest.kt
@@ -57,7 +57,7 @@ class NewMemberWalletViewModelJvmTest {
}
private fun picking(groups: Map): NewMemberWalletUIState.Picking {
- val viewModel = NewMemberWalletViewModel(me, null, Chain.Regtest, canWatch = true, NewMemberWalletUIState.Loading, repository(groups))
+ val viewModel = NewMemberWalletViewModel(me, null, Chain.Regtest, NewMemberWalletUIState.Loading, repository(groups))
viewModel.initiate()
runBlocking { withTimeout(5_000) { while (viewModel.uiState == NewMemberWalletUIState.Loading) delay(10) } }
return assertIs(viewModel.uiState)
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt
index 83558bbc..5627ecf7 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt
@@ -22,7 +22,6 @@ 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.
@@ -36,7 +35,7 @@ internal class FakeElectrum : IElectrumClient {
val txs = mutableMapOf()
val subscribed = mutableSetOf()
override val notifications = MutableSharedFlow(extraBufferCapacity = 64)
- override val connectionStatus: StateFlow = MutableStateFlow(ElectrumConnectionStatus.Closed(null))
+ override val connectionStatus = 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()
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainClientsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainClientsJvmTest.kt
index a8a99a72..2a9d9692 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainClientsJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/GroupChainClientsJvmTest.kt
@@ -1,10 +1,25 @@
package com.machankura.bennu.compose.wallet
+import fr.acinq.bitcoin.Block
import fr.acinq.bitcoin.Chain
-import kotlinx.coroutines.runBlocking
+import fr.acinq.lightning.blockchain.electrum.ElectrumConnectionStatus
+import fr.acinq.lightning.blockchain.electrum.ServerVersionResponse
+import fr.acinq.lightning.io.TcpSocket
+import fr.acinq.lightning.utils.ServerAddress
+import fr.acinq.phoenix.data.ElectrumConfig
+import fr.acinq.phoenix.managers.global.NetworkState
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
+import kotlin.test.assertTrue
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.seconds
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.advanceTimeBy
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
/**
* One Electrum connection per network: the node's own is used as it is, any other is made once, on
@@ -35,4 +50,45 @@ class GroupChainClientsJvmTest {
clients.clientFor(Chain.Testnet3)
assertEquals(listOf(Chain.Testnet3, Chain.Testnet3), made)
}
+
+ /** A link that only records where the loop sends it. */
+ private class RecordingLink : ElectrumLink {
+ override val client = FakeElectrum()
+ val servers = mutableListOf()
+ var stopped = false
+ override suspend fun connect(server: ServerAddress, timeout: Duration) {
+ servers += server
+ client.connectionStatus.value = ElectrumConnectionStatus.Connected(ServerVersionResponse("fake", "1.4"), 0, Block.RegtestGenesisBlock.header)
+ }
+ override fun disconnect() { client.connectionStatus.value = ElectrumConnectionStatus.Closed(null) }
+ override fun stop() { stopped = true }
+ }
+
+ @Test
+ fun `another network's connection is the identity's own loop, so it keeps to Tor`() = runTest {
+ val onion = ServerAddress("testnetexample.onion", 50001, TcpSocket.TLS.DISABLED)
+ val clearnet = ServerAddress("testnet.example", 50002, TcpSocket.TLS.TRUSTED_CERTIFICATES())
+ val asked = mutableListOf>()
+ val link = RecordingLink()
+ val node = FakeElectrum()
+ val clients = GroupChainClients.forNode(Chain.Mainnet, node) { chain ->
+ StandaloneElectrum(
+ chain = chain,
+ networkState = MutableStateFlow(NetworkState.Available),
+ isTorEnabled = MutableStateFlow(true),
+ customServer = MutableStateFlow(null),
+ link = link,
+ randomServer = { c, tor -> asked += c to tor; if (tor) onion else clearnet },
+ context = StandardTestDispatcher(testScheduler),
+ )
+ }
+ assertSame(node, clients.clientFor(Chain.Mainnet), "the node's own network is the node's client")
+ assertSame(link.client, clients.clientFor(Chain.Testnet3))
+ advanceTimeBy(1.seconds)
+ runCurrent()
+ assertEquals(listOf>(Chain.Testnet3 to true), asked.toList())
+ assertEquals(listOf(onion), link.servers, "with Tor on, the testnet3 connection goes to an onion server")
+ clients.stop()
+ assertTrue(link.stopped, "stopping the identity's clients stops the standalone one")
+ }
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrumJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrumJvmTest.kt
new file mode 100644
index 00000000..5ab48da7
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/IdentityElectrumJvmTest.kt
@@ -0,0 +1,137 @@
+package com.machankura.bennu.compose.wallet
+
+import androidx.datastore.preferences.core.PreferenceDataStoreFactory
+import com.machankura.bennu.compose.identity.Identity
+import com.machankura.bennu.compose.identity.IdentityKind
+import com.machankura.bennu.compose.identity.toWalletId
+import fr.acinq.bitcoin.Chain
+import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.byteVector32
+import fr.acinq.lightning.utils.ServerAddress
+import fr.acinq.phoenix.managers.global.NetworkState
+import fr.acinq.phoenix.managers.nostrPublicKeyHex
+import fr.acinq.phoenix.utils.preferences.InternalPrefs
+import fr.acinq.phoenix.utils.preferences.UserPrefs
+import kotlinx.coroutines.flow.flowOf
+import okio.Path.Companion.toPath
+import org.junit.Rule
+import org.junit.rules.TemporaryFolder
+import kotlin.random.Random
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertNotSame
+import kotlin.test.assertNull
+import kotlin.test.assertSame
+import kotlin.test.assertTrue
+import kotlin.time.Duration
+
+/**
+ * Which client each kind of identity watches on, and that a switch never leaves
+ * the last profile's connection open (D1 of `docs/standalone-electrum.md`).
+ */
+class IdentityElectrumJvmTest {
+ @get:Rule
+ val temporaryFolder = TemporaryFolder()
+
+ /** Never connects: the network is down. What is under test is which client is made, and when it is stopped. */
+ private class IdleLink : ElectrumLink {
+ override val client = FakeElectrum()
+ var stopped = false
+ override suspend fun connect(server: ServerAddress, timeout: Duration) {}
+ override fun disconnect() {}
+ override fun stop() {
+ stopped = true
+ }
+ }
+
+ private val made = mutableListOf>()
+
+ /** For each client made, whether every one made before it had been stopped by then. */
+ private val earlierStopped = mutableListOf()
+
+ private val identityElectrum = IdentityElectrum { identity ->
+ earlierStopped += made.all { it.second.stopped }
+ val link = IdleLink()
+ made += identity to link
+ StandaloneElectrum(
+ chain = Chain.Regtest,
+ networkState = flowOf(NetworkState.NotAvailable),
+ isTorEnabled = flowOf(false),
+ customServer = flowOf(null),
+ link = link,
+ )
+ }
+
+ private fun prefsStore() = PreferenceDataStoreFactory.createWithPath {
+ temporaryFolder.newFolder().resolve("prefs.preferences_pb").path.toPath()
+ }
+
+ private fun key() = PrivateKey(Random.nextBytes(32).byteVector32())
+
+ private fun signing(kind: IdentityKind, key: PrivateKey = key()) = Identity.signing(
+ id = key.publicKey().xOnly().toWalletId(),
+ kind = kind,
+ nostrPrivateKey = key,
+ userPrefs = UserPrefs(prefsStore()),
+ internalPrefs = InternalPrefs(prefsStore()),
+ business = null,
+ )
+
+ private fun readOnly(key: PrivateKey = key()) = Identity.readOnly(
+ id = key.publicKey().xOnly().toWalletId(),
+ nostrPublicKey = key.nostrPublicKeyHex(),
+ userPrefs = UserPrefs(prefsStore()),
+ internalPrefs = InternalPrefs(prefsStore()),
+ )
+
+ @Test
+ fun `a profile with a node watches on the node's client, and no other is made`() {
+ val node = FakeElectrum()
+ val client = identityElectrum.clientFor(signing(IdentityKind.Mnemonic), nodeClient = node)
+ assertSame(node, client)
+ assertEquals(emptyList(), made)
+ }
+
+ @Test
+ fun `an nsec profile and an npub profile each get a client of their own`() {
+ val nsec = signing(IdentityKind.NostrSecret)
+ val nsecClient = identityElectrum.clientFor(nsec)
+ assertSame(made.single { it.first == nsec }.second.client, nsecClient)
+
+ val npub = readOnly()
+ val npubClient = identityElectrum.clientFor(npub)
+ assertSame(made.single { it.first == npub }.second.client, npubClient)
+ }
+
+ @Test
+ fun `the same identity asked again keeps its client`() {
+ val nsec = signing(IdentityKind.NostrSecret)
+ val first = identityElectrum.clientFor(nsec)
+ assertSame(first, identityElectrum.clientFor(nsec))
+ assertEquals(1, made.size)
+ }
+
+ @Test
+ fun `switching from one nsec to another stops the first before the second is made`() {
+ val firstClient = identityElectrum.clientFor(signing(IdentityKind.NostrSecret))
+ val secondClient = identityElectrum.clientFor(signing(IdentityKind.NostrSecret))
+
+ assertEquals(listOf(true, true), earlierStopped)
+ assertNotSame(firstClient, secondClient)
+ assertEquals(listOf(true, false), made.map { it.second.stopped })
+ }
+
+ @Test
+ fun `switching to a profile with a node stops the standalone client`() {
+ identityElectrum.clientFor(signing(IdentityKind.NostrSecret))
+ identityElectrum.clientFor(signing(IdentityKind.Mnemonic), nodeClient = FakeElectrum())
+ assertTrue(made.single().second.stopped)
+ }
+
+ @Test
+ fun `no identity has no client, and the last one is stopped`() {
+ identityElectrum.clientFor(signing(IdentityKind.NostrSecret))
+ assertNull(identityElectrum.clientFor(null))
+ assertTrue(made.single().second.stopped)
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/StandaloneElectrumJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/StandaloneElectrumJvmTest.kt
new file mode 100644
index 00000000..2f352ac3
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/StandaloneElectrumJvmTest.kt
@@ -0,0 +1,180 @@
+package com.machankura.bennu.compose.wallet
+
+import fr.acinq.bitcoin.Block
+import fr.acinq.bitcoin.Chain
+import fr.acinq.lightning.blockchain.electrum.ElectrumConnectionStatus
+import fr.acinq.lightning.blockchain.electrum.ServerVersionResponse
+import fr.acinq.lightning.io.TcpSocket
+import fr.acinq.lightning.utils.ServerAddress
+import fr.acinq.phoenix.data.ElectrumConfig
+import fr.acinq.phoenix.managers.global.NetworkState
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.TestScope
+import kotlinx.coroutines.test.advanceTimeBy
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.seconds
+
+/**
+ * The connection loop of a profile with no node, against a link whose connection
+ * status the test moves. No socket is opened: the loop's job is to decide when to
+ * connect and to where, and that is all it is asked here.
+ */
+class StandaloneElectrumJvmTest {
+ private class FakeLink : ElectrumLink {
+ override val client = FakeElectrum()
+ val attempts = mutableListOf>()
+ var succeeds = true
+ var stopped = false
+
+ override suspend fun connect(server: ServerAddress, timeout: Duration) {
+ attempts += server to timeout
+ client.connectionStatus.value = ElectrumConnectionStatus.Connecting(server)
+ client.connectionStatus.value = if (succeeds) {
+ ElectrumConnectionStatus.Connected(ServerVersionResponse("fake", "1.4"), 0, Block.RegtestGenesisBlock.header)
+ } else {
+ // A fresh exception each time, as the real client makes: two closes in a
+ // row are then two values, not one the StateFlow swallows.
+ ElectrumConnectionStatus.Closed(TcpSocket.IOException.ConnectionRefused())
+ }
+ }
+
+ /** The server hanging up, as the client's listen job reports it. */
+ fun drop() {
+ client.connectionStatus.value = ElectrumConnectionStatus.Closed(TcpSocket.IOException.ConnectionRefused())
+ }
+
+ override fun disconnect() {
+ client.connectionStatus.value = ElectrumConnectionStatus.Closed(null)
+ }
+
+ override fun stop() {
+ stopped = true
+ }
+ }
+
+ private val random = ServerAddress("random.example", 50002, TcpSocket.TLS.TRUSTED_CERTIFICATES())
+ private val onion = ServerAddress("onionaddressexample.onion", 50001, TcpSocket.TLS.DISABLED)
+ private val custom = ElectrumConfig.Custom.create(ServerAddress("mine.example", 50002, TcpSocket.TLS.TRUSTED_CERTIFICATES()), requireOnionIfTorEnabled = true)
+
+ private val network = MutableStateFlow(NetworkState.Available)
+ private val tor = MutableStateFlow(false)
+ private val customServer = MutableStateFlow(null)
+ private val link = FakeLink()
+
+ private fun TestScope.electrum() = StandaloneElectrum(
+ chain = Chain.Testnet3,
+ networkState = network,
+ isTorEnabled = tor,
+ customServer = customServer,
+ link = link,
+ randomServer = { _, torIsEnabled -> if (torIsEnabled) onion else random },
+ context = StandardTestDispatcher(testScheduler),
+ )
+
+ @Test
+ fun `with no custom server, a random one for the network is used`() = runTest {
+ val electrum = electrum().also { it.start() }
+ advanceTimeBy(1.seconds)
+ assertEquals(listOf(random), link.attempts.map { it.first })
+ electrum.stop()
+ }
+
+ @Test
+ fun `a custom server is used when one is set, and setting one reconnects`() = runTest {
+ val electrum = electrum().also { it.start() }
+ advanceTimeBy(1.seconds)
+ customServer.value = custom
+ advanceTimeBy(1.seconds)
+ assertEquals(listOf(random, custom.server), link.attempts.map { it.first })
+ electrum.stop()
+ }
+
+ @Test
+ fun `a closed connection is retried after a pause that grows, and a connection resets it`() = runTest {
+ link.succeeds = false
+ val electrum = electrum().also { it.start() }
+ // 0.1 + 0.25 + 0.5 + 1 seconds: four attempts, the fifth two seconds off.
+ advanceTimeBy(1.9.seconds)
+ // And the handshake is given longer once three have failed.
+ assertEquals(listOf(4.seconds, 4.seconds, 4.seconds, 7.seconds), link.attempts.map { it.second })
+
+ link.succeeds = true
+ advanceTimeBy(2.seconds)
+ assertEquals(5, link.attempts.size)
+
+ // Connected, so the count starts again: the next drop is retried after a tenth of a second.
+ link.drop()
+ advanceTimeBy(0.2.seconds)
+ assertEquals(6, link.attempts.size)
+ electrum.stop()
+ }
+
+ @Test
+ fun `losing the network disconnects, and getting it back connects`() = runTest {
+ val electrum = electrum().also { it.start() }
+ advanceTimeBy(1.seconds)
+ network.value = NetworkState.NotAvailable
+ advanceTimeBy(30.seconds)
+ assertEquals(1, link.attempts.size)
+ assertTrue(link.client.connectionStatus.value is ElectrumConnectionStatus.Closed)
+
+ network.value = NetworkState.Available
+ advanceTimeBy(1.seconds)
+ assertEquals(2, link.attempts.size)
+ electrum.stop()
+ }
+
+ @Test
+ fun `with Tor on, a clearnet custom server that must be an onion is never connected to`() = runTest {
+ tor.value = true
+ customServer.value = custom
+ val electrum = electrum().also { it.start() }
+ advanceTimeBy(30.seconds)
+ assertEquals(emptyList(), link.attempts)
+ electrum.stop()
+ }
+
+ @Test
+ fun `with Tor on and no custom server, only an onion server is tried`() = runTest {
+ tor.value = true
+ val electrum = electrum().also { it.start() }
+ advanceTimeBy(1.seconds)
+ assertEquals(listOf(onion), link.attempts.map { it.first })
+ assertEquals(20.seconds, link.attempts.single().second)
+ electrum.stop()
+ }
+
+ @Test
+ fun `a network with no servers is not connected to, and does not crash`() = runTest {
+ val electrum = StandaloneElectrum(
+ chain = Chain.Signet,
+ networkState = network,
+ isTorEnabled = tor,
+ customServer = customServer,
+ link = link,
+ context = StandardTestDispatcher(testScheduler),
+ ).also { it.start() }
+ advanceTimeBy(30.seconds)
+ assertEquals(emptyList(), link.attempts)
+ electrum.stop()
+ }
+
+ @Test
+ fun `after stop nothing is retried, and the client is stopped`() = runTest {
+ link.succeeds = false
+ val electrum = electrum().also { it.start() }
+ advanceTimeBy(0.5.seconds)
+ val before = link.attempts.size
+ electrum.stop()
+ advanceTimeBy(60.seconds)
+ runCurrent()
+ assertEquals(before, link.attempts.size)
+ assertTrue(link.stopped)
+ }
+}
diff --git a/docs/README.md b/docs/README.md
index 146a0a65..bffc71ab 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -30,6 +30,7 @@ silent, or a decision that looked arbitrary and was not.
| [long-running-sync.md](./long-running-sync.md) | the chat subscriptions that stay open instead of pulling once per screen — why the request queue could not simply hold one, and how the group filter follows the room list |
| [dead-code.md](./dead-code.md) | code in the sync and relay stack that nothing calls, why each piece is still there, and which of it is a bug rather than a leftover |
| [nsec-sign-in.md](./nsec-sign-in.md) | signing in with an existing nostr key — why an nsec can never have a wallet behind it, the ten call sites that make it small, and the sign-in machine that was already built and unreachable |
+| [standalone-electrum.md](./standalone-electrum.md) | a profile with no node watching the chain — why only a nodeless profile gets its own client, why it connects at start rather than on first look, and why Tor on still means no clearnet fallback |
| [npub-sign-in.md](./npub-sign-in.md) | signing in with only a public key — what a key that cannot sign can still see here, why that is a preview rather than a browser, and the four decisions the word settles |
| [multiple-profiles.md](./multiple-profiles.md) | several profiles on one device — why a profile is a credential and a seed is a wallet attached to one, why a switch is a restart rather than a swap, the two entrances the app lacks, and the inbox a switch would silently lose |
| [jvm-target.md](./jvm-target.md) | what desktop support cost, phased — why the native chain was already done, why an empty source set in our phoenix fork was the real blocker, and why DAO tests need none of it |
@@ -145,3 +146,8 @@ wallet note and the ceremony note, and reads as the lightning-kmp fork's
constraints and its decision table before any phase, its trust table before
arguing with either, and its two tables of what the build found before
changing anything it describes.
+
+The standalone-electrum note is a phased plan that has been built, and is the
+group chain wallet note's *An identity without a node* answered: read that
+paragraph and the nsec sign-in note's *The constraint* first, then its seven
+decisions, and its table of where the build chose differently before the code.
diff --git a/docs/group-chain-wallet.md b/docs/group-chain-wallet.md
index 329fbde0..d535add8 100644
--- a/docs/group-chain-wallet.md
+++ b/docs/group-chain-wallet.md
@@ -523,10 +523,11 @@ it knows is re-fetched from Electrum on start.
**An identity without a node.** `Identity.business` is null for an nsec or npub
profile, and with it the Electrum client. Such a member still holds a share if
they are in the quorum, and Phase 7 is built so they can sign without the chain.
-What they cannot do in this phase is see a balance; the screen says so rather
-than showing zero. A standalone `ElectrumClient` for those identities is a
-follow-up, and `AppConfigurationManager.randomElectrumServer` is where its server
-would come from.
+What they could not do in this phase is see a balance; the screen said so rather
+than showing zero. **Since built:** a standalone Electrum client for those
+identities, [standalone-electrum.md](./standalone-electrum.md), which picks its
+server as `AppConfigurationManager.randomElectrumServer` does. The screen's
+*cannot watch* branch is gone with it.
**Test** in `jvmTest`, with a fake `IElectrumClient` — the interface is small and
documented never to throw: funding `/0/2` makes the receive address move to
@@ -839,7 +840,8 @@ same as a shared xpub in any multisig and is stated here so nobody is surprised.
### What is left, when someone wants it
-- A standalone Electrum client for nsec and npub identities (Phase 4).
+- ~~A standalone Electrum client for nsec and npub identities (Phase 4).~~ Built:
+ [standalone-electrum.md](./standalone-electrum.md).
- **Funding from a member's own node.** Phoenix's close-channels flow takes a
destination address (`CloseChannelsConfigurationController` defaults it to
`finalAddress`); offering the group's receive address there, and as a
diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md
index d82ebcac..8d5de94a 100644
--- a/docs/group-lightning-wallet.md
+++ b/docs/group-lightning-wallet.md
@@ -60,7 +60,7 @@ build chose differently, this table says so.
| one channel per group node, because two would share a `shaSeed` | not needed. Channel keys derive from a random funding key *path* per channel, not from the funding key, so two channels have different per-commitment secrets even with the same group funding key. Only `RecoveredChannelKeys`, which a group node never uses, keys off the funding key |
| `HtlcDelayedTx` is node-keyed | it is keyed from the delayed basepoint, so it pays the group too. What stays node-keyed is the HTLC transaction itself and the claims from the counterparty's commitment, which is the in-flight exposure the statement caps |
| *Open a group wallet* offers testnet3 | a second row on the group's screen, *Group onchain wallet on testnet3*, opening the same wallet screen on that network. Behind `GroupLightningRollout.ENABLED`, which stays off until Phase 15, so nothing a member sees changes yet |
-| a testnet3 Electrum client per identity, from `AppConfigurationManager.randomElectrumServer` | from lightning-kmp's `ElectrumServers.pickElectrumServer`, which lists the same servers and needs no Phoenix business to call. The node's own client still serves the node's network |
+| a testnet3 Electrum client per identity, from `AppConfigurationManager.randomElectrumServer` | a `StandaloneElectrum` per identity for each network other than the node's, the same connection loop the main branch gave profiles with no node: the same server choice (`randomElectrumServer`, onion servers when Tor is on), the same pauses, and the same refusal of a clearnet server while Tor is on. It first used lightning-kmp's `ElectrumServers.pickElectrumServer` and connected directly, which ignored Tor: a profile with Tor on would have reached a testnet3 server in the clear. The identity's custom server is for its own network, so another network always takes a random one |
| `GroupOnchainWallets` is keyed by `(chain, account)` | it stays keyed by xpub, which already names one account on one network. What changed is the client: each wallet is made on its own network's |
| a regtest test opens, receives and spends with mainnet unaffected | the existing wallet suites run on regtest unchanged through the new registry, and two new tests check that each spend goes out on its own network's connection, and that a spend naming no known network is left alone |
| the ceremony's participants are sorted by host key | by nostr key. Their set is fixed before anyone speaks, as the holders of the onchain wallet's key that every device already has on record, so ChillDKG's host-key round has nothing to settle. Each key is read as the even point over its x coordinate for `IcebergDkg.Params` |
@@ -112,6 +112,7 @@ build chose differently, this table says so.
| close the old wallet's channel, signed by the old co-signers | the old wallet keeps its own operator statement and node, and `GroupLightningNodes` runs one node per wallet a device operates. Closing every channel it still has is one signing session over one `close` authorisation per channel. If its operator was the member who left, any remaining participant can nominate themselves for it |
| the member-removal flow says so, as it already does for the onchain wallet | the removal flow said nothing about either wallet. It now says what a removal leaves when the member holds a share of the Lightning wallet's key. The onchain wallet's own sentence is left to that wallet's plan |
| one schema version per phase, 27 to 30 | **one, 32.** The main branch used 27 to 31 meanwhile. The four versions this branch made were never on an installed database, so at the merge they became one migration, 31 to 32, that adds every Lightning table |
+| the operator's node needs a profile with a node of its own | it never did in substance -- a group's node is its own `Peer` -- only in the wiring, which took the context and logger from the identity's Phoenix business. Once the main branch gave profiles with no node an Electrum client (`IdentityElectrum`), the wiring takes them from the app instead, so an nsec or npub profile that holds a share can be elected and run the group's node |
| the kinds are taken from 30333 | from **30350**: the guarded-wallet family took 30333-30337 on the main branch meanwhile, and nothing failed when the two met, since each reads the other's events by kind. The family moved at the merge, which costs nothing for rumor kinds that never shipped, and the test now also asserts that it starts past every kind the app uses |
| the kinds are reserved | in code: `GroupLightningEvents`, 30350-30366, with a test asserting the run is unbroken and touches no kind the app already dispatches on |
| library phases land in the forks' `threshold` branches | on a new branch, `claude/group-lightning-wallet`, in `lightning-kmp-app` and in `experimental/lightning-kmp`. It is local and not pushed. The app's submodule pointer follows it, so a checkout of this branch needs those commits from the same machine until they are pushed |
diff --git a/docs/group-wallet-addresses.md b/docs/group-wallet-addresses.md
index 2ff4b332..bbf7107f 100644
--- a/docs/group-wallet-addresses.md
+++ b/docs/group-wallet-addresses.md
@@ -255,7 +255,8 @@ on the old behaviour.
the identity's life, so this is the same instance the wallet screen is already
watching: it adds no subscriptions and does not need a second Electrum answer.
Its own `GroupWalletAddressesUIState` has `Loading`, `Error`, `CannotWatch`
- (no node, the same case as `this_profile_cannot_watch_the_chain`) and
+ (no node, the same case as `this_profile_cannot_watch_the_chain`; both removed
+ by [standalone-electrum.md](./standalone-electrum.md)) and
`Loaded(addresses: List?)`, where a null list is the
waiting-for-Electrum state.
- **Four states**, through `ScreenStateTransition` over the whole body:
diff --git a/docs/member-guarded-wallets.md b/docs/member-guarded-wallets.md
index d240a0d6..2aaeef4e 100644
--- a/docs/member-guarded-wallets.md
+++ b/docs/member-guarded-wallets.md
@@ -272,7 +272,10 @@ opened to its members' wallets: a group that has signed no member-wallet policy,
or whose newest one is closed, takes no request.
A read-only profile cannot sign the request. A profile with no Electrum client
(`GroupOnchainWallets` is null for it) could not see its own coins, so it is not
-offered a wallet it cannot see.
+offered a wallet it cannot see. **Since
+[standalone-electrum.md](./standalone-electrum.md)** there is no such profile:
+an nsec profile watches on a client of its own, the `CANNOT_WATCH` refusal is
+gone, and an nsec profile may ask.
### D4. What the member's device has to know, and the member who joined late
@@ -597,7 +600,7 @@ with a `NavigateBackButton`). It is a consent screen first and a form second:
| refused | because |
|---|---|
| a read-only profile | it cannot sign the request (`LocalCanSign`) |
-| no Electrum client for the profile | it could not see its own coins (D3) |
+| ~~no Electrum client for the profile~~ | gone: every profile has one since [standalone-electrum.md](./standalone-electrum.md) (D3) |
| the group has no key, or is not a Marmot room | there is nobody to sign the certificate, and no room to carry it |
| `groupKeyFor` is null | the grant cannot be worked out. Offer *Ask the group for its key* (Phase 2) |
| `grantFor` is null | `G`'s certificate carries guardian keys this build cannot read. Today that surfaces at the end of a ceremony, and here it is refused up front |
@@ -969,8 +972,9 @@ longer in #Ekklesia* when that is so.
certificate is a signature that exists forever, and the group can only stop
watching.
-**It does not reach a member who cannot watch the chain** (D3), and it does not
-reach a read-only profile at all.
+**It does not reach a read-only profile at all.** It did not reach a member who
+could not watch the chain either (D3), until
+[standalone-electrum.md](./standalone-electrum.md) gave every profile a client.
**It does not survive a re-keyed group**, for the reason the guardians note
gives. The leaf is bound to `K_G`.
diff --git a/docs/nsec-sign-in.md b/docs/nsec-sign-in.md
index e81f660a..37e0f6e3 100644
--- a/docs/nsec-sign-in.md
+++ b/docs/nsec-sign-in.md
@@ -942,6 +942,9 @@ found.
in [The constraint](#the-constraint). Possible as a *second* secret — generate
a seed, attach it to the identity — but then one profile has two things to back
up and every recovery screen in this plan has to say which. Its own plan.
+ *Watching* the chain without a wallet of its own is built: an nsec profile
+ sees its groups' balances on an Electrum client of its own —
+ [standalone-electrum.md](./standalone-electrum.md).
- **Starting the node lazily for mnemonic identities.** Recommended, separable,
and made small by Phase 1. See [The one decision](#the-one-decision-to-make-first).
- **`npub` sign-in (read only).** The skeleton parses it, and `signInToProfile`
diff --git a/docs/standalone-electrum.md b/docs/standalone-electrum.md
new file mode 100644
index 00000000..9f969106
--- /dev/null
+++ b/docs/standalone-electrum.md
@@ -0,0 +1,256 @@
+# An Electrum client for a profile with no node
+
+How an nsec or npub profile comes to watch the chain: the group wallets it can
+already sign for, the member wallets it can already hold, and the spends the group
+has already signed. Today none of them can, because the only Electrum client in
+the app belongs to the Lightning node, and only a mnemonic profile starts one.
+
+Read [nsec-sign-in.md](./nsec-sign-in.md)'s *The constraint* for why an nsec has
+no node, and [group-chain-wallet.md](./group-chain-wallet.md)'s *An identity
+without a node*, which named this plan as its follow-up. Neither changes:
+an nsec still cannot have a Lightning wallet. This plan gives it eyes on the chain, not a
+wallet of its own.
+
+**Built**, phases 1–4, one commit each: `9899c571`, `da48d7b0`, `3f5de588` and
+the commit that changed this paragraph. Written against `3aba04a0`, with the
+`lightning-kmp-app` submodule at `e0d2b82`, which the build did not touch.
+`StandaloneElectrum` is the loop and `IdentityElectrum` is where the nav host
+gets a client. The phases are kept as written; where the build chose differently
+the table below says so.
+
+| what the plan said | what it turned out to be |
+|---|---|
+| the connect seam is a `suspend (ServerAddress, Duration) -> Unit` | an interface, `ElectrumLink`, with `connect`, `disconnect` and `stop`. The loop drops the connection on every change of control, and a test has to see that as a status, not a socket |
+| the resolution is a plain function the nav host calls inside `remember` | a class, `IdentityElectrum`, held for the app's life. A `remember` keyed on the identity computes the new client *before* `DisposableEffect` disposes the old one, so a switch between two nsec profiles would have had both open for a moment. The class stops the last before it makes the next |
+| the standalone client reads the network monitor | and starts it: `NetworkMonitor.start()` is otherwise called only by the node's daemon, so a device that opens an nsec profile first would never have learnt it was online. `start()` is idempotent on all three platforms |
+| `wallets` becomes non-null at every screen | at every screen but the profile's. `ActiveProfileScreen` and `MemberWalletsViewModel` keep a nullable `wallets`, because the previews and `ReadOnlyEntrancesJvmTest` compose the profile without an identity. In the app it is never null there |
+| the nav host passes a non-null `wallets` | it still holds a nullable one, null with no identity, and each wallet route opens with `groupOnchainWallets ?: return@composable`: the frame between a profile switch and the startup screen has no chain to show |
+| the tests that drove the refusal are rewritten or deleted | the addresses view model's *cannot watch* test is deleted; the group send view model's *no node* test became *no share*, the other way to be refused the form; the rest pass a `GroupOnchainWallets` over an empty `FakeElectrum` |
+| `GroupWalletViewModel`'s `watcher` | stays nullable: the tests default it, and nothing in the app passes null |
+
+A real Electrum server has not been reached through this client yet. Every phase
+was checked with `:composeApp:jvmTest` (1,485 tests),
+`:composeApp:compileDebugKotlinAndroid` and `m3-audit.sh --check`. Phase 5, the
+device check, has not been done.
+
+The headline: **every consumer already takes an `IElectrumClient`, and every
+"cannot watch" branch in the app is `wallets == null`. So the work is a connection
+loop, about sixty lines ported from the node's daemon, and one `remember` in
+`BennuNavHost` that hands it to whoever has no node. No screen learns a new state.
+Five of them lose one.**
+
+---
+
+## What is already there
+
+| fact | where | what it means here |
+|---|---|---|
+| `GroupOnchainWallets`, `GroupOnchainWallet` and `GroupTransactionWatcher` take an `IElectrumClient`, not a `PhoenixBusiness` | [wallet/](../composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/) | nothing below the nav host knows where the client came from |
+| both are made from `activeIdentity?.business?.electrumClient` and are null without it | [BennuNavHost.kt:246](../composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/navigation/BennuNavHost.kt) | the one place the null enters |
+| every `canWatch` is `wallets != null`, and `CannotWatch` / `CANNOT_WATCH` are the same test | `GroupWalletViewModel:124`, `MemberWalletViewModel:71`, `GroupWalletAddressesViewModel:65`, `BennuNavHost:1222` | with a client for everyone, the condition never holds |
+| an nsec or npub identity's preferences already carry Tor and a custom Electrum server, *"saved anyway"* | [IdentityWriter.kt:64](../composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/identity/IdentityWriter.kt) `prepareIdentity` | the configuration exists and nothing reads it yet |
+| the server lists are public top-level vals, and `platformElectrumRegtestConf` is a public `expect fun` | `lightning-kmp-app/.../data/ElectrumServers.kt` | a random server can be picked without an `AppConfigurationManager`, which needs a business |
+| `AppConnectionsDaemon` is the only reconnect loop, and its constructor takes a `PhoenixBusiness` | `lightning-kmp-app/.../managers/AppConnectionsDaemon.kt:241` | it cannot be reused. Its Electrum branch is what gets ported |
+| `ElectrumClient.connect` returns after one attempt; reconnecting is the caller's job | `lightning-kmp/.../ElectrumClient.kt:75` | the loop is not optional |
+| `ElectrumClient.stop()` is final: *"the client cannot be used after it has been closed"* | `ElectrumClient.kt:296` | one client per identity, made anew on a switch |
+| `NetworkMonitor` lives on `PhoenixGlobal`, not the business, and `start()` is idempotent on every platform | `PhoenixGlobal.kt:38`, the three `NetworkMonitor.*.kt` | available without a node, and safe to start from a second place |
+| `FakeElectrum` implements `IElectrumClient` for the wallet tests | [FakeElectrum.kt](../composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/wallet/FakeElectrum.kt) | the downstream tests need nothing new |
+
+## Decisions
+
+**D1. Only a profile with no node gets one.** A mnemonic profile keeps the node's
+client. A second connection from the same device would tell a second server the
+same addresses, and would give the group wallets a view of the chain that can
+disagree with the node's. The rule is `identity.business?.electrumClient ?:
+standalone`, tested on `business`, not on the kind, as `switchToIdentity` does.
+
+**D2. It lives in `composeApp`, not the submodule.** The loop is small, and the
+submodule's managers are all shaped around a business. Picking a random server is
+a `when (chain)` over the public lists. That copies five lines of
+`AppConfigurationManager.randomElectrumServer`, which is cheaper than a submodule
+commit to move them. `Testnet4` and `Signet` are `TODO()` there, and they are
+"no server" here, never a crash. A profile on those networks reads as "connecting",
+the same as a node with no server configured.
+
+**D3. The identity's own preferences choose the server**, exactly as
+`BusinessManager` does for a node: `userPrefs.getElectrumServer` if set, a random
+server for `NodeParamsManager.chain` if not, and a reconnect whenever either
+preference changes. The same profile, given a seed later, keeps the same server.
+
+**D4. Tor behaves as it does for the node, and that is not much.** This fork's
+socket builder is plain TCP. `isTorEnabled` only swaps the random list for onion
+addresses, which plain TCP cannot reach, and `requireOnionIfTorEnabled` refuses a
+clearnet custom server. The standalone client copies both rules, so a profile
+with Tor on never falls back to a clearnet connection against the user's choice.
+Its wallets then stay on "connecting", which is what a mnemonic profile with Tor
+on already shows today. A real Tor transport is its own plan; see
+[Out of scope](#out-of-scope).
+
+**D5. It connects when the identity becomes active, not when a wallet screen
+opens.** `GroupTransactionWatcher` sends the group's signed spends and follows
+them to a confirmation *"whether or not anybody opens the wallet"*. A lazy
+client would make that true only for mnemonic profiles. A bare connection reveals
+the device's IP and nothing else. Addresses are still subscribed only when a
+wallet is first asked for, as they are now. **This is a behaviour change:** an
+nsec or npub profile made no Electrum connection before, and from Phase 2 it
+makes one on every start. The note's rollout section must say so.
+
+**D6. An npub watches too.** Watching needs a descriptor, and descriptors come
+from group-signed events, which a read-only profile can already read. Rebroadcasting
+a transaction somebody else signed needs no key. Every send stays gated on
+`canSign` and the share, as now, so an npub sees balances and proposes nothing.
+
+**D7. Foreground only.** The client lives in `applicationIOScope`, as
+`GroupOnchainWallets` does. A mnemonic node is also run headless by Android's
+WorkManager, for payments. A nodeless profile has no payment to wake up for, and
+a watch that only runs in the background would answer a question nobody is asking.
+
+---
+
+## Phase 1 — the connection loop
+
+**Half a day, most of it in the test.**
+
+`wallet/StandaloneElectrum.kt`: owns one `ElectrumClient`, and exposes it as
+`client: IElectrumClient`, with `start()` and `stop()`. Inside is the daemon's
+Electrum branch with the business taken out:
+
+- collects `networkMonitor.networkState`, `userPrefs.getIsTorEnabled` and
+ `userPrefs.getElectrumServer`, combined; any change disconnects and starts the
+ loop again, as `forceDisconnect` does;
+- on `Connection.CLOSED`, waits `connectionPause(attempt)`, the same table, then
+ calls `connect` with the same handshake-timeout ladder;
+- `stop()` cancels the loop and calls `ElectrumClient.stop()`. A stopped instance
+ is never restarted: the client's own comment says it cannot be, so a switch
+ makes a new one.
+
+The connect itself goes behind a small seam: a
+`suspend (ServerAddress, Duration) -> Unit` defaulting to `client.connect(…,
+TcpSocket.Builder(), …)`. The loop can then be tested against a status flow the
+test drives, with no socket.
+
+**Test** in `jvmTest`, `StandaloneElectrumJvmTest`, on a `TestScope`:
+- a custom server is used when set, and a random server from the chain's list when not;
+- a closed connection is retried after the pause, and the attempt count resets on
+ `ESTABLISHED`;
+- losing the network disconnects, and getting it back connects;
+- Tor on with a clearnet custom server that requires onion never calls `connect`;
+- after `stop()`, nothing is retried and the client is stopped.
+
+## Phase 2 — one client per identity, handed to the wallets
+
+**Half a day.**
+
+In `BennuNavHost`, the two `remember(activeIdentityForWallets?.business)` blocks
+become one resolution keyed on the identity:
+
+```kotlin
+val electrum: IElectrumClient? = remember(activeIdentityForWallets?.id, activeIdentityForWallets?.business) {
+ val identity = activeIdentityForWallets ?: return@remember null
+ identity.business?.electrumClient
+ ?: StandaloneElectrum(phoenixGlobal.networkMonitor, identity.userPrefs, NodeParamsManager.chain, applicationIOScope)
+ .also { it.start() }
+ .client
+}
+```
+
+The standalone instance is disposed with the identity, the same as
+`GroupOnchainWallets` (stopped in `onDispose`). `GroupOnchainWallets` and
+`GroupTransactionWatcher` are then made from `electrum`, not from
+`business.electrumClient`. Keyed on `id` *and* `business`, because a switch between two
+nsec profiles changes the first and not the second, and the old profile's client
+must not survive it (the reason `GroupOnchainWallets`' own comment gives).
+
+The resolution is written as a plain function beside `StandaloneElectrum`, so it
+can be tested without composition, and `BennuNavHost` calls it.
+
+**Test**: a mnemonic identity resolves to the business's client and makes no
+standalone; an nsec identity and an npub identity each get one; switching from
+one nsec to another stops the first before the second connects.
+
+After this phase every nodeless profile can watch, and the "cannot watch"
+branches are unreachable but still compiled.
+
+## Phase 3 — the branches that can no longer be taken
+
+**Half a day, all of it deletion.**
+
+`wallets` becomes non-null wherever it is passed: `GroupWalletViewModel`,
+`GroupSendViewModel`, `GroupWalletAddressesViewModel`, `MemberWalletViewModel`,
+`MemberWalletsViewModel`, `MemberSendViewModel`, and the `ActiveProfileRoute` at
+`BennuNavHost:929`. The compiler then finds every `wallets == null` for us.
+Removed with them:
+
+- `GroupWalletAddressesUIState.CannotWatch` and its `EmptyState`;
+- `MemberWalletManager.Refusal.CANNOT_WATCH` and `NewMemberWalletViewModel`'s
+ `canWatch` parameter. The new-member-wallet entrance opens for nsec profiles
+ (D3 of [member-guarded-wallets.md](./member-guarded-wallets.md) said why it was
+ closed, and that reason is gone). An npub still cannot ask, because asking is
+ signed;
+- `canWatch` on `GroupWalletUIState.Loaded` and `MemberWalletUIState.Loaded`.
+ `walletState == null` then means one thing, "before Electrum's first answer",
+ and the KDoc that explained the two meanings goes;
+- the `GroupWalletScreen` send, spend and fund gates lose their `&& canWatch`;
+- the strings `this_profile_cannot_watch_the_chain` and
+ `this_profile_cannot_watch_its_own_coins`.
+
+The tests that drove these with `wallets = null` are rewritten against
+`FakeElectrum`, or deleted where the only thing they checked was the refusal.
+
+`m3-audit.sh --check` should not move: no new strings, no new colours, one
+`EmptyState` fewer.
+
+## Phase 4 — the notes
+
+**An hour.**
+
+- [nsec-sign-in.md](./nsec-sign-in.md): the *Out of scope* bullet keeps "a wallet
+ for an nsec identity", and gains a line that watching shipped here.
+- [group-chain-wallet.md](./group-chain-wallet.md): *An identity without a node*
+ and the follow-up at the end point here and say it is built. Its
+ `MAX_ADDRESS_INDEX` and absolute fee-ceiling rows stay as they are. Both are
+ still right for a member whose client has not answered yet, and a member with a
+ client gets Electrum's fee *suggestion* through `suggestedFeeratePerVbyte`
+ without any change.
+- [member-guarded-wallets.md](./member-guarded-wallets.md): D3 and the refusal
+ table's *no Electrum client* row.
+- This note: **Planned** becomes **Built**, with a table of where the build chose
+ differently, as the other built plans have.
+
+## Phase 5 — on a device
+
+Process, not code. On testnet, with an nsec profile in a group that has a wallet,
+on Android and on desktop:
+
+1. the group wallet shows a balance and a receive address, not "cannot watch";
+2. funding that address moves it to the next one;
+3. a spend this profile co-signs is broadcast from this device and shows as
+ confirmed without the proposer's device being online;
+4. switching to a mnemonic profile and back leaves one Electrum connection open,
+ not two (the server's logs, or `lsof` on desktop);
+5. with Tor on and no custom server, no clearnet connection is made.
+
+---
+
+## Out of scope
+
+- **A Lightning wallet for an nsec profile.** Unchanged from
+ [nsec-sign-in.md](./nsec-sign-in.md): it needs a seed, which is a second secret.
+- **A Tor transport.** The fork has none for the node either (D4). When one
+ exists it is a `TcpSocket.Builder`, and Phase 1's connect seam is where it goes.
+- **One client for every profile, mnemonic included.** This is what starting the node
+ lazily would make possible, and that is already named as a follow-on in
+ nsec-sign-in.md. Phase 2's resolution is the line that would change.
+- **Saying "can't reach Electrum" rather than loading forever.** True for
+ mnemonic profiles today as well. `IElectrumClient.connectionStatus` is on the
+ interface, so it is a screen change for every profile at once, and its own plan.
+
+## Checking the work
+
+```bash
+./gradlew :composeApp:compileDebugKotlinAndroid :composeApp:jvmTest
+```
+
+```bash
+./gradlew :composeApp:m3Audit
+```