diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index 8c1169c9..0558c661 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -134,6 +134,7 @@
This group was disbanded. Nothing more can be sent into it, and nobody can rejoin.
Ends the group for everyone. Nobody can rejoin; a new conversation is a new group.
Removal sent; it takes effect once a relay accepts it
+ Removal sent; it takes effect once a relay accepts it. They still hold a share of the Lightning wallet's key and its node's seed until the group opens a new Lightning wallet without them.
Library
Lightning invoice
LIVE
@@ -766,4 +767,11 @@
%1$s sats wait in closed channels
They are the group's alone, under its own keys. Sweeping asks the group to sign moving them to the onchain wallet; the sweep is sent once the channel's delay is over.
Sweep into the onchain wallet
+ %1$s people who have left the group still hold a share of this wallet's key and its node's seed. Make a new Lightning wallet without them, then close this one's channels.
+ Open a new Lightning wallet
+ Earlier wallet %1$s
+ %1$s sats in %2$s channels
+ Close its channels
+ Sweep %1$s sats
+ Nobody runs its node, and its channels close only through it.
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt
index 67f0128e..ed14be7d 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseChatRepository.kt
@@ -1,6 +1,7 @@
package com.machankura.bennu.compose.database.repository
import fr.acinq.bitcoin.Chain
+import com.machankura.bennu.compose.managers.GroupLightningWalletManager
import com.machankura.bennu.compose.managers.GroupWalletManager
import com.machankura.bennu.compose.managers.GroupWalletDerivation
import com.machankura.bennu.compose.nostr.wallet.GroupWallet
@@ -187,6 +188,9 @@ class DatabaseChatRepository(
emptyList()
}
+ override suspend fun lightningParticipants(chatRoomId: String, chain: Chain): Set =
+ runCatching { GroupLightningWalletManager.current(database, chatRoomId, chain)?.statement?.participants?.toSet() }.getOrNull().orEmpty()
+
override suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet? = try {
GroupWalletManager.walletFor(database, chatRoomId, chain)
} catch (e: Throwable) {
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt
index 61f3380c..5d9e813a 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/repository/DatabaseGroupLightningRepository.kt
@@ -31,10 +31,19 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr
override suspend fun completedCeremony(chatRoomId: String): IcebergKeySession? = IcebergRitualManager.completedKey(database, chatRoomId)
override suspend fun lightningWallet(chatRoomId: String, chain: Chain): GroupLightningWalletManager.Wallet? =
- GroupLightningWalletManager.walletFor(database, chatRoomId, chain)
+ GroupLightningWalletManager.current(database, chatRoomId, chain)
- override suspend fun operator(chatRoomId: String, chain: Chain): GroupLightningOperatorManager.Operator? =
- GroupLightningOperatorManager.current(database, chatRoomId, chain)
+ override suspend fun earlierWallets(chatRoomId: String, chain: Chain): List =
+ GroupLightningWalletManager.wallets(database, chatRoomId, chain).dropLast(1)
+
+ override suspend fun departed(wallet: GroupLightningWalletManager.Wallet): List =
+ GroupLightningWalletManager.departed(database, wallet)
+
+ override suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean =
+ GroupLightningWalletManager.unusedKey(database, chatRoomId, chain) != null
+
+ override suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator? =
+ GroupLightningOperatorManager.current(database, chatRoomId, chain, wallet)
override fun lspNodeId(chain: Chain): HexKey? =
runCatching { LSP.from(chain).walletParams.trampolineNode.id.toString() }.getOrNull()
@@ -42,25 +51,25 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr
override suspend fun proposeWallet(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, chain: Chain): FrostSigningSession =
GroupLightningWalletManager.proposeWallet(database, localChatRoom, userPublicKey, nostrPrivateKey, chain, requireNotNull(lspNodeId(chain)) { "No LSP is known for ${chain.name}" })
- override suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain): FrostSigningSession =
- GroupLightningOperatorManager.nominateSelf(database, localChatRoom, userPublicKey, chain)
+ override suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession =
+ GroupLightningOperatorManager.nominateSelf(database, localChatRoom, userPublicKey, chain, wallet)
- override suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain): FrostSigningSession =
- GroupLightningOperatorManager.stepDown(database, localChatRoom, userPublicKey, chain)
+ override suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession =
+ GroupLightningOperatorManager.stepDown(database, localChatRoom, userPublicKey, chain, wallet)
- override fun observeReport(chatRoomId: String, chain: Chain): Flow {
- val key = GroupLightningCoSigner.walletKey(chatRoomId, chain, 0L)
+ override fun observeReport(chatRoomId: String, chain: Chain, wallet: Long): Flow {
+ val key = GroupLightningCoSigner.walletKey(chatRoomId, chain, wallet)
return database.groupLightningRecordsDao().observeSnapshot(key).map { GroupLightningReports.latest(database, key) }
}
- override fun observePayments(chatRoomId: String, chain: Chain): Flow> =
- database.groupLightningRecordsDao().observePayments(GroupLightningCoSigner.walletKey(chatRoomId, chain, 0L))
+ override fun observePayments(chatRoomId: String, chain: Chain, wallet: Long): Flow> =
+ database.groupLightningRecordsDao().observePayments(GroupLightningCoSigner.walletKey(chatRoomId, chain, wallet))
override suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String =
GroupLightningReports.requestInvoice(database, localChatRoom, userPublicKey, wallet, amountMsat, description)
- override fun observeInvoice(chatRoomId: String, chain: Chain, requestId: String): Flow =
- database.groupLightningRecordsDao().observeInvoice(GroupLightningCoSigner.walletKey(chatRoomId, chain, 0L), requestId)
+ override fun observeInvoice(chatRoomId: String, chain: Chain, wallet: Long, requestId: String): Flow =
+ database.groupLightningRecordsDao().observeInvoice(GroupLightningCoSigner.walletKey(chatRoomId, chain, wallet), requestId)
override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession =
GroupLightningAuthorisations.propose(database, localChatRoom, userPublicKey, pay)
@@ -68,6 +77,9 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr
override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession =
GroupLightningAuthorisations.proposeChannelAction(database, localChatRoom, userPublicKey, wallet, channelId, force)
+ override suspend fun proposeCloseAll(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession =
+ GroupLightningAuthorisations.proposeCloseAll(database, localChatRoom, userPublicKey, wallet, channelIds)
+
override suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List =
GroupLightningSweeps.unswept(database, chatRoomId, report)
@@ -87,10 +99,10 @@ class DatabaseGroupLightningRepository(private val database: BennuDatabase) : Gr
IcebergRitualManager.pendingApproval(database, session)
override suspend fun ceremonyThresholds(chatRoomId: String): List =
- FrostSigningManager.completedKey(database, chatRoomId)?.let(IcebergRitualManager::thresholdsFor).orEmpty()
+ IcebergRitualManager.thresholds(database, chatRoomId)
override suspend fun keyHolderCount(chatRoomId: String): Int =
- FrostSigningManager.completedKey(database, chatRoomId)?.participantPublicKeySet()?.size ?: 0
+ FrostSigningManager.completedKey(database, chatRoomId)?.let { IcebergRitualManager.holdersInRoom(database, chatRoomId, it).size } ?: 0
override suspend fun hasOnchainWallet(chatRoomId: String, chain: Chain): Boolean =
GroupWalletManager.walletFor(database, chatRoomId, chain) != null
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt
index 4d682f33..2b3d59c2 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningAuthorisations.kt
@@ -111,6 +111,16 @@ object GroupLightningAuthorisations {
suspend fun forceCloseAuthorised(database: BennuDatabase, chatRoomId: String, statement: GroupLightningWalletStatementEvent.Statement, channelId: ByteVector32): Boolean =
channelActions(database, chatRoomId, statement).any { it.action == GroupLightningAuthorisationEvent.FORCE_CLOSE && it.channelId == channelId.toHex() }
+ /** Proposes closing every one of [channelIds] of [wallet] to the onchain wallet, as one signing session. */
+ suspend fun proposeCloseAll(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession {
+ require(channelIds.isNotEmpty()) { "There are no channels to close" }
+ val expires = (Clock.System.now() + CHANNEL_ACTION_LIFETIME).epochSeconds
+ val templates = channelIds.map { channelId ->
+ GroupLightningAuthorisationEvent.template(GroupLightningAuthorisationEvent.ChannelAction(GroupLightningAuthorisationEvent.CLOSE, wallet.statement.chain, wallet.statement.wallet, channelId, expires))
+ }
+ return FrostSigningManager.proposeSigningBatch(database, localChatRoom, userPublicKey, templates)
+ }
+
/** Proposes that the operator's node close [channelId] -- mutually, or by force when [force]. */
suspend fun proposeChannelAction(database: BennuDatabase, localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession {
val action = GroupLightningAuthorisationEvent.ChannelAction(
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt
index 11fc2a9a..d1d6337b 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningWalletManager.kt
@@ -60,6 +60,38 @@ object GroupLightningWalletManager {
fun nodeIdOf(seed: ByteVector, chain: Chain): PublicKey =
DeterministicWallet.generate(seed).derivePrivateKey(LocalKeyManager.nodeKeyBasePath(chain)).publicKey
+ /**
+ * Every Lightning wallet [chatRoomId] has opened on [chain] that this device believes, the newest
+ * statement for each wallet number, lowest number first. The last is the current one; the others are
+ * wallets a re-key left behind, whose channels are still to be closed (Phase 14).
+ */
+ suspend fun wallets(database: BennuDatabase, chatRoomId: String, chain: Chain): List =
+ database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, GroupLightningWalletStatementEvent.KIND)
+ .sortedWith(compareByDescending { it.createdAt }.thenBy { it.id })
+ .mapNotNull { verify(database, chatRoomId, it)?.takeIf { wallet -> wallet.statement.chain == chain } }
+ .distinctBy { it.statement.wallet }
+ .sortedBy { it.statement.wallet }
+
+ /** The wallet a room uses on [chain] now: the highest-numbered one it has opened, or null. */
+ suspend fun current(database: BennuDatabase, chatRoomId: String, chain: Chain): Wallet? = wallets(database, chatRoomId, chain).lastOrNull()
+
+ /** The participants of [wallet] who are no longer in its room: each still holds a share and the seed. */
+ suspend fun departed(database: BennuDatabase, wallet: Wallet): List {
+ val inRoom = database.participantDao().findParticipantsByChatRoomId(wallet.signedEvent.chatRoomId).filter { it.deletedAt == null }.map { it.participantPublicKey.lowercase() }.toSet()
+ return wallet.statement.participants.filter { it !in inRoom }
+ }
+
+ /**
+ * A completed Iceberg key in [chatRoomId] that this device holds a share of and that no wallet the
+ * room opened uses yet: what a new wallet -- the first, or the one a re-key makes -- is opened under.
+ */
+ suspend fun unusedKey(database: BennuDatabase, chatRoomId: String, chain: Chain): IcebergKeySession? {
+ val used = database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, GroupLightningWalletStatementEvent.KIND)
+ .mapNotNull { GroupLightningWalletStatementEvent.read(it.tags)?.ceremonyId }.toSet()
+ return database.icebergKeySessionDao().getSessionsForChatRoom(chatRoomId)
+ .firstOrNull { it.stage == IcebergRitualStage.COMPLETE && it.share != null && it.id !in used }
+ }
+
/** The newest statement for [chain] and [wallet] in [chatRoomId] that this device believes, or null. */
suspend fun walletFor(database: BennuDatabase, chatRoomId: String, chain: Chain, wallet: Long = 0L): Wallet? =
database.groupSignedEventDao().getByChatRoomIdAndKind(chatRoomId, GroupLightningWalletStatementEvent.KIND)
@@ -82,9 +114,11 @@ object GroupLightningWalletManager {
logger.w("Lightning wallet ${signed.id} closes to an onchain wallet this room has not opened")
return null
}
+ // D1 as Phase 14 narrows it: every participant holds the onchain key. A wallet made after a member
+ // left names fewer of them; the one before still names everyone, and both stay believable.
FrostSigningManager.completedKey(database, chatRoomId)?.participantPublicKeySet()?.let { holders ->
- if (holders.map { it.lowercase() }.sorted() != statement.participants) {
- logger.w("Lightning wallet ${signed.id} names participants who are not the onchain key's holders")
+ if (!holders.map { it.lowercase() }.containsAll(statement.participants)) {
+ logger.w("Lightning wallet ${signed.id} names participants who do not hold the onchain key")
return null
}
}
@@ -119,14 +153,16 @@ object GroupLightningWalletManager {
nostrPrivateKey: ByteArray,
chain: Chain,
lspNodeId: HexKey,
- wallet: Long = 0L,
+ wallet: Long? = null,
onchainAccount: Long = 0L,
policy: GroupLightningWalletStatementEvent.Policy = GroupLightningWalletStatementEvent.Policy.DEFAULT,
): FrostSigningSession {
require(GroupLightningRollout.allows(chain)) { "A Lightning wallet cannot be opened on ${chain.name}" }
val roomId = localChatRoom.chatRoom.id
- val ceremony = IcebergRitualManager.completedKey(database, roomId)
- ?: throw IllegalStateException("This group has no Lightning wallet key yet")
+ val ceremony = unusedKey(database, roomId, chain)
+ ?: throw IllegalStateException("This group has no Lightning wallet key that no wallet uses yet")
+ // The next number: a re-key opens a new wallet beside the old one, whose channels still need closing.
+ val wallet = wallet ?: ((wallets(database, roomId, chain).maxOfOrNull { it.statement.wallet } ?: -1L) + 1)
requireNotNull(GroupWalletManager.walletFor(database, roomId, chain, onchainAccount)) {
"Open a group onchain wallet on ${chain.name} first: it is where the Lightning wallet closes to"
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergRitualManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergRitualManager.kt
index 02983d1a..10293faa 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergRitualManager.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/IcebergRitualManager.kt
@@ -87,6 +87,26 @@ object IcebergRitualManager {
fun thresholdsFor(onchainKey: DkgSession): List =
onchainKey.participantPublicKeySet()?.let { IcebergDkg.deployableThresholds(it.size) }.orEmpty()
+ /** The thresholds a ceremony in [chatRoomId] could use now, over [holdersInRoom]; empty if none. */
+ suspend fun thresholds(database: BennuDatabase, chatRoomId: String): List {
+ val onchainKey = FrostSigningManager.completedKey(database, chatRoomId) ?: return emptyList()
+ return IcebergDkg.deployableThresholds(holdersInRoom(database, chatRoomId, onchainKey).size)
+ }
+
+ /**
+ * Who a ceremony in [chatRoomId] is over (decision D1, as Phase 14 narrows it): the holders of the
+ * onchain key [onchainKey] who are still in the room, as this device's MLS state has it. A member
+ * who was removed keeps their onchain share, but a new Lightning wallet is made without them.
+ *
+ * The removal commit is an earlier epoch than any proposal sent after it, so a device reading a
+ * proposal has already applied it, and every device computes the same set.
+ */
+ suspend fun holdersInRoom(database: BennuDatabase, chatRoomId: String, onchainKey: DkgSession): Set {
+ val holders = onchainKey.participantPublicKeySet()?.map { it.lowercase() }?.toSet().orEmpty()
+ val inRoom = database.participantDao().findParticipantsByChatRoomId(chatRoomId).filter { it.deletedAt == null }.map { it.participantPublicKey.lowercase() }.toSet()
+ return holders intersect inRoom
+ }
+
/** A participant's nostr key as the compressed point [IcebergDkg.Params] orders and binds. */
private fun asPoint(nostrKey: HexKey): PublicKey = PublicKey(ByteVector("02$nostrKey"))
@@ -123,8 +143,8 @@ object IcebergRitualManager {
requireNotNull(GroupWalletManager.walletFor(database, roomId, chain)) {
"Open a group onchain wallet on ${chain.name} before a Lightning wallet: it is where the Lightning wallet closes to"
}
- val members = requireNotNull(onchainKey.participantPublicKeySet()) { "The onchain key does not record who holds it" }
- require(userPublicKey in members) { "This device does not hold the onchain key" }
+ val members = holdersInRoom(database, roomId, onchainKey)
+ require(userPublicKey.lowercase() in members) { "This device does not hold the onchain key" }
require(IcebergDkg.isDeployable(members.size, threshold)) { "$threshold-of-${members.size} is not a deployable Iceberg group" }
val session = IcebergKeySession(
@@ -194,9 +214,9 @@ object IcebergRitualManager {
return null
}
// D1, checked rather than trusted: the people the proposal names must be exactly the people
- // who hold the onchain key it names, as this device's own record of that ceremony says.
+ // who hold the onchain key it names and are still in the room, as this device's own records say.
val onchainKey = onchainId?.let { database.dkgSessionDao().getSessionById(it) }
- if (onchainKey?.participantPublicKeySet()?.map { it.lowercase() }?.toSet() != members) {
+ if (onchainKey == null || holdersInRoom(database, localChatRoom.chatRoom.id, onchainKey) != members) {
logger.w("Iceberg proposal $sessionId names people who are not the holders of onchain key $onchainId; dropping")
return null
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt
index 5e2d8aaa..f39387eb 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/ChatRepository.kt
@@ -113,6 +113,12 @@ interface ChatRepository {
*/
suspend fun groupWallet(chatRoomId: String, chain: Chain): GroupWallet?
+ /**
+ * Who holds a share of the key of the Lightning wallet this group uses on [chain], and its node's
+ * seed: the people a removal leaves able to grief it until a new wallet replaces it (Phase 14).
+ */
+ suspend fun lightningParticipants(chatRoomId: String, chain: Chain): Set = emptySet()
+
/**
* The account this group *would* open on [chain], whether or not it has, or
* null for a room with no key: what a statement proposing the wallet carries.
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt
index 017d3ac4..d4719acd 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/repository/GroupLightningRepository.kt
@@ -46,31 +46,40 @@ interface GroupLightningRepository {
/** The newest completed Lightning wallet key this device holds a share of, or null. */
suspend fun completedCeremony(chatRoomId: String): IcebergKeySession?
- /** The wallet the room agreed on [chain], as this device can check it, or null. */
+ /** The wallet the room uses on [chain] now -- the highest-numbered it agreed -- as this device can check it, or null. */
suspend fun lightningWallet(chatRoomId: String, chain: Chain): GroupLightningWalletManager.Wallet?
- suspend fun operator(chatRoomId: String, chain: Chain): GroupLightningOperatorManager.Operator?
+ /** The wallets a re-key left behind on [chain], lowest number first: their channels are still to close. */
+ suspend fun earlierWallets(chatRoomId: String, chain: Chain): List
+
+ /** The participants of [wallet] who have left its room, and still hold a share of its key and its seed. */
+ suspend fun departed(wallet: GroupLightningWalletManager.Wallet): List
+
+ /** Whether the room has a completed Lightning wallet key no wallet uses yet, for a new wallet to open under. */
+ suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean
+
+ suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator?
/** The LSP a Lightning wallet on [chain] opens channels with, or null for a network with none. */
fun lspNodeId(chain: Chain): HexKey?
suspend fun proposeWallet(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, chain: Chain): FrostSigningSession
- suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain): FrostSigningSession
+ suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession
- suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain): FrostSigningSession
+ suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession
/** The operator's newest snapshot of the wallet on [chain], each channel checked against this device's ledger. */
- fun observeReport(chatRoomId: String, chain: Chain): Flow
+ fun observeReport(chatRoomId: String, chain: Chain, wallet: Long): Flow
/** Every payment any snapshot has reported, newest first. */
- fun observePayments(chatRoomId: String, chain: Chain): Flow>
+ fun observePayments(chatRoomId: String, chain: Chain, wallet: Long): Flow>
/** Asks the operator's node for an invoice; returns the request id its answer will carry. */
suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String
/** The operator's invoice for [requestId], once it has arrived and been checked. */
- fun observeInvoice(chatRoomId: String, chain: Chain, requestId: String): Flow
+ fun observeInvoice(chatRoomId: String, chain: Chain, wallet: Long, requestId: String): Flow
/** Proposes [pay] to the group; the operator's node pays it once a quorum signs. */
suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession
@@ -78,6 +87,9 @@ interface GroupLightningRepository {
/** Proposes closing [channelId] to the onchain wallet, or force-closing it when [force]. */
suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession
+ /** Proposes closing every one of [channelIds] to the onchain wallet, in one signing session. */
+ suspend fun proposeCloseAll(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession
+
/** What closed channels left the group that no sweep spends yet, from [report]. */
suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt
index 57414a73..8ae76194 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/ChatRoomDetailScreen.kt
@@ -2,6 +2,7 @@ package com.machankura.bennu.compose.ui.composable
import androidx.compose.material.icons.filled.Bolt
import bennu.composeapp.generated.resources.lightning_wallet
+import bennu.composeapp.generated.resources.member_removal_requested_lightning
import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningWalletRoute
import bennu.composeapp.generated.resources.group_wallet_on_s
import fr.acinq.phoenix.managers.NodeParamsManager
@@ -199,6 +200,7 @@ fun ChatRoomDetailScreen(
// composable, and a lambda passed to onClick is not.
val notify = rememberNotifier(rememberCoroutineScope())
val removalRequested = stringResource(Res.string.member_removal_requested)
+ val removalLeavesLightningShare = stringResource(Res.string.member_removal_requested_lightning)
ScreenStateTransition(chatRoomDetailViewModel.chatRoomDetailUIState) { uiState ->
when (val chatRoomDetailUIState = uiState) {
@@ -791,7 +793,12 @@ fun ChatRoomDetailScreen(
chatRoomDetailViewModel.removeMember(
localChatRoom = chatRoomDetailUIState.localChatRoom,
memberPublicKey = memberPublicKey,
- ) { failure -> notify(failure ?: removalRequested) }
+ ) { failure ->
+ // They keep a share of the Lightning wallet's key and its seed: say so,
+ // since only a new wallet takes it from them (Phase 14).
+ val holdsShare = memberPublicKey.lowercase() in chatRoomDetailUIState.lightningParticipants
+ notify(failure ?: if (holdsShare) removalLeavesLightningShare else removalRequested)
+ }
}
) {
Icon(
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt
index 71cff96d..19947ce6 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningWalletScreen.kt
@@ -53,9 +53,11 @@ import bennu.composeapp.generated.resources.at_most_s_sats_in_flight
import bennu.composeapp.generated.resources.balance
import bennu.composeapp.generated.resources.channel_actions
import bennu.composeapp.generated.resources.channels
+import bennu.composeapp.generated.resources.close_its_channels
import bennu.composeapp.generated.resources.close_to_the_onchain_wallet
import bennu.composeapp.generated.resources.couldn_t_propose_this
import bennu.composeapp.generated.resources.couldn_t_send_s_sats
+import bennu.composeapp.generated.resources.earlier_wallet_s
import bennu.composeapp.generated.resources.force_close
import bennu.composeapp.generated.resources.group_wallet_on_s
import bennu.composeapp.generated.resources.lightning_wallet
@@ -64,8 +66,10 @@ import bennu.composeapp.generated.resources.make_a_key
import bennu.composeapp.generated.resources.matches_what_your_device_signed
import bennu.composeapp.generated.resources.no_payments_yet
import bennu.composeapp.generated.resources.nobody_runs_this_wallet
+import bennu.composeapp.generated.resources.nobody_runs_this_wallet_s_node
import bennu.composeapp.generated.resources.node_s
import bennu.composeapp.generated.resources.open_a_lightning_wallet
+import bennu.composeapp.generated.resources.open_a_new_lightning_wallet
import bennu.composeapp.generated.resources.open_an_onchain_wallet_on_s_first
import bennu.composeapp.generated.resources.opening_a_lightning_wallet_asks
import bennu.composeapp.generated.resources.payments
@@ -75,8 +79,10 @@ import bennu.composeapp.generated.resources.reported_by_the_operator_in_term_s
import bennu.composeapp.generated.resources.run_by_s_term_s
import bennu.composeapp.generated.resources.run_this_wallet_on_my_device
import bennu.composeapp.generated.resources.s_of_s_sats_are_the_group_s
+import bennu.composeapp.generated.resources.s_people_who_left_still_hold_a_share
import bennu.composeapp.generated.resources.s_sats
import bennu.composeapp.generated.resources.s_sats_can_be_received
+import bennu.composeapp.generated.resources.s_sats_in_s_channels
import bennu.composeapp.generated.resources.s_sats_wait_in_closed_channels
import bennu.composeapp.generated.resources.see_the_key_ceremony
import bennu.composeapp.generated.resources.send
@@ -84,6 +90,7 @@ import bennu.composeapp.generated.resources.sent_s_sats_with_a_fee_of_s_sats
import bennu.composeapp.generated.resources.signers_needed_s_of_s
import bennu.composeapp.generated.resources.step_down
import bennu.composeapp.generated.resources.sweep_into_the_onchain_wallet
+import bennu.composeapp.generated.resources.sweep_s_sats
import bennu.composeapp.generated.resources.the_group_is_making_its_lightning_wallet_key
import bennu.composeapp.generated.resources.the_operator_hasn_t_reported_the_wallet_yet
import bennu.composeapp.generated.resources.the_operator_s_device_runs_the_node
@@ -225,6 +232,12 @@ fun GroupLightningWalletScreen(
onSend = { onNavigateToRoute(GroupLightningSendRoute(activeUserPublicKey = activeUserPublicKey, chatRoomId = chatRoomId)) },
onClose = { channelId, force -> viewModel.close(channelId, force, onSession = toSession, onFailure = { notify(couldNotPropose) }) },
onSweep = { viewModel.sweep(onSession = toSession, onFailure = { notify(couldNotPropose) }) },
+ onRekey = {
+ if (state.canOpenNew) viewModel.openWallet(onSession = toSession, onFailure = { notify(couldNotPropose) }) else toCeremony(null)
+ },
+ onCloseEarlier = { viewModel.closeEarlier(it, onSession = toSession, onFailure = { notify(couldNotPropose) }) },
+ onSweepEarlier = { viewModel.sweepEarlier(it, onSession = toSession, onFailure = { notify(couldNotPropose) }) },
+ onRunEarlier = { viewModel.nominateSelf(onSession = toSession, onFailure = { notify(couldNotPropose) }, wallet = it.wallet.statement.wallet) },
isPending = viewModel.isActionPending.value,
onNominate = { viewModel.nominateSelf(onSession = toSession, onFailure = { notify(couldNotPropose) }) },
onStepDown = { viewModel.stepDown(onSession = toSession, onFailure = { notify(couldNotPropose) }) },
@@ -235,7 +248,12 @@ fun GroupLightningWalletScreen(
}
@Composable
-private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> Unit, onSend: () -> Unit, onClose: (channelId: String, force: Boolean) -> Unit, onSweep: () -> Unit, isPending: Boolean, onNominate: () -> Unit, onStepDown: () -> Unit) {
+private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.Opened, onReceive: () -> Unit, onSend: () -> Unit, onClose: (channelId: String, force: Boolean) -> Unit, onSweep: () -> Unit,
+ onRekey: () -> Unit,
+ onCloseEarlier: (GroupLightningWalletUIState.Earlier) -> Unit,
+ onSweepEarlier: (GroupLightningWalletUIState.Earlier) -> Unit,
+ onRunEarlier: (GroupLightningWalletUIState.Earlier) -> Unit,
+ isPending: Boolean, onNominate: () -> Unit, onStepDown: () -> Unit) {
val statement = state.wallet.statement
val operatorName = state.operator?.publicKey?.let { key ->
if (state.isOperator) stringResource(Res.string.you)
@@ -245,6 +263,19 @@ private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.
modifier = modifier.readableContent().fillMaxSize().padding(MaterialTheme.spacing.screenMargin),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap),
) {
+ // A member left: until a new wallet replaces this one, they can still grief it with the seed.
+ if (state.departed.isNotEmpty()) {
+ item {
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
+ Text(stringResource(Res.string.s_people_who_left_still_hold_a_share, state.departed.size.toString()), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error)
+ Button(onClick = onRekey, enabled = !isPending) {
+ Text(stringResource(if (state.canOpenNew) Res.string.open_a_new_lightning_wallet else Res.string.make_a_key))
+ }
+ }
+ }
+ }
+ }
item { Balance(state.report, onReceive = onReceive.takeIf { state.operator?.publicKey != null }, onSend = onSend.takeIf { state.operator?.publicKey != null }) }
if (state.unswept.isNotEmpty()) {
item {
@@ -283,6 +314,16 @@ private fun OpenedWallet(modifier: Modifier, state: GroupLightningWalletUIState.
}
}
}
+ items(state.earlier, key = { "earlier:${it.wallet.statement.wallet}" }) { earlier ->
+ EarlierWallet(
+ earlier = earlier,
+ canRun = earlier.operator?.publicKey == null && state.localChatRoom.chatRoom.userPublicKey.lowercase() in earlier.wallet.statement.participants,
+ isPending = isPending,
+ onClose = { onCloseEarlier(earlier) },
+ onSweep = { onSweepEarlier(earlier) },
+ onRun = { onRunEarlier(earlier) },
+ )
+ }
item {
ListItem(
leadingContent = { Icon(Icons.Default.Key, contentDescription = Decorative) },
@@ -395,3 +436,27 @@ private fun PaymentRow(payment: GroupLightningPaymentRow) {
supportingContent = payment.description?.let { { Text(it, maxLines = 2, overflow = TextOverflow.Ellipsis) } },
)
}
+
+/** A wallet a re-key left behind: what is still in it, and the two ways it reaches the onchain wallet. */
+@Composable
+private fun EarlierWallet(earlier: GroupLightningWalletUIState.Earlier, canRun: Boolean, isPending: Boolean, onClose: () -> Unit, onSweep: () -> Unit, onRun: () -> Unit) {
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Column(modifier = Modifier.padding(MaterialTheme.spacing.containerPadding), verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.relatedGap)) {
+ Text(stringResource(Res.string.earlier_wallet_s, earlier.wallet.statement.wallet.toString()), style = MaterialTheme.typography.titleSmall)
+ earlier.report?.let { report ->
+ Text(stringResource(Res.string.s_sats_in_s_channels, Satoshi(report.snapshot.spendableMsat / 1000).grouped(), report.checks.size.toString()), style = MaterialTheme.typography.bodyMedium)
+ }
+ if (earlier.operator?.publicKey == null && earlier.openChannels.isNotEmpty()) {
+ Text(stringResource(Res.string.nobody_runs_this_wallet_s_node), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.itemGap)) {
+ if (earlier.openChannels.isNotEmpty()) OutlinedButton(onClick = onClose, enabled = !isPending) { Text(stringResource(Res.string.close_its_channels)) }
+ if (earlier.unswept.isNotEmpty()) {
+ OutlinedButton(onClick = onSweep, enabled = !isPending) { Text(stringResource(Res.string.sweep_s_sats, Satoshi(earlier.unswept.sumOf { it.amountSat }).grouped())) }
+ }
+ }
+ if (canRun) OutlinedButton(onClick = onRun, enabled = !isPending) { Text(stringResource(Res.string.run_this_wallet_on_my_device)) }
+ }
+ }
+}
+
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt
index fcf7bad6..39c5adf2 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/ChatRoomDetailViewModel.kt
@@ -102,6 +102,7 @@ class ChatRoomDetailViewModel(
testNetworkWallet = if (GroupLightningRollout.ENABLED && GroupLightningRollout.NETWORK != NodeParamsManager.chain) {
chatRepository.groupWallet(chatRoomId, GroupLightningRollout.NETWORK)
} else null,
+ lightningParticipants = if (GroupLightningRollout.ENABLED) chatRepository.lightningParticipants(chatRoomId, GroupLightningRollout.NETWORK) else emptySet(),
canEditNostrProfile = canSign,
canAddSubgroup = canSign,
canGovern = canGovern,
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningReceiveViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningReceiveViewModel.kt
index 2dd0f921..e5cb3e53 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningReceiveViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningReceiveViewModel.kt
@@ -50,7 +50,7 @@ class GroupLightningReceiveViewModel(
val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId)
?: return@launch run { uiState = GroupLightningReceiveUIState.Error("Couldn't find the group") }
val wallet = lightningRepository.lightningWallet(chatRoomId, chain)
- uiState = if (wallet == null || lightningRepository.operator(chatRoomId, chain)?.publicKey == null) GroupLightningReceiveUIState.Unavailable
+ uiState = if (wallet == null || lightningRepository.operator(chatRoomId, chain, wallet.statement.wallet)?.publicKey == null) GroupLightningReceiveUIState.Unavailable
else GroupLightningReceiveUIState.Form(localChatRoom, wallet)
}
}
@@ -74,7 +74,7 @@ class GroupLightningReceiveViewModel(
isActionPending.value = false
if (requestId == null) return@launch withContext(Dispatchers.Main) { onFailure() }
uiState = GroupLightningReceiveUIState.Waiting(requestId)
- val invoice = lightningRepository.observeInvoice(chatRoomId, chain, requestId).filterNotNull().first()
+ val invoice = lightningRepository.observeInvoice(chatRoomId, chain, form.wallet.statement.wallet, requestId).filterNotNull().first()
uiState = GroupLightningReceiveUIState.Invoice(invoice.bolt11)
}
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningSendViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningSendViewModel.kt
index 6d5290b2..66514ace 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningSendViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningSendViewModel.kt
@@ -53,7 +53,7 @@ class GroupLightningSendViewModel(
val localChatRoom = chatRepository.getChatRoomByIdentifier(chatRoomId)
?: return@launch run { uiState = GroupLightningSendUIState.Error("Couldn't find the group") }
val wallet = lightningRepository.lightningWallet(chatRoomId, chain)
- uiState = if (wallet == null || lightningRepository.operator(chatRoomId, chain)?.publicKey == null) GroupLightningSendUIState.Unavailable
+ uiState = if (wallet == null || lightningRepository.operator(chatRoomId, chain, wallet.statement.wallet)?.publicKey == null) GroupLightningSendUIState.Unavailable
else GroupLightningSendUIState.Form(localChatRoom, wallet)
}
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModel.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModel.kt
index 0fb2a7bd..e9f68a6d 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModel.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModel.kt
@@ -60,19 +60,30 @@ class GroupLightningWalletViewModel(
val key = lightningRepository.completedCeremony(chatRoomId)
when {
wallet != null -> {
- val operator = lightningRepository.operator(chatRoomId, chain)
+ val operator = lightningRepository.operator(chatRoomId, chain, wallet.statement.wallet)
GroupLightningWalletUIState.Opened(
localChatRoom = localChatRoom,
wallet = wallet,
operator = operator,
isParticipant = activeUserPublicKey.lowercase() in wallet.statement.participants && wallet.ceremony?.share != null,
isOperator = operator?.publicKey == activeUserPublicKey,
+ departed = lightningRepository.departed(wallet),
+ canOpenNew = lightningRepository.hasUnusedKey(chatRoomId, chain) && canPropose(),
+ earlier = lightningRepository.earlierWallets(chatRoomId, chain).map { earlier ->
+ val report = lightningRepository.observeReport(chatRoomId, chain, earlier.statement.wallet).first()
+ GroupLightningWalletUIState.Earlier(
+ wallet = earlier,
+ operator = lightningRepository.operator(chatRoomId, chain, earlier.statement.wallet),
+ report = report,
+ unswept = lightningRepository.unswept(chatRoomId, report),
+ )
+ },
)
}
key != null -> GroupLightningWalletUIState.NotOpened(
localChatRoom = localChatRoom,
key = key,
- canPropose = lightningRepository.lspNodeId(chain) != null && activeIdentityStateFlow.value?.nostrPrivateKey != null,
+ canPropose = canPropose(),
)
else -> {
val running = lightningRepository.observeCeremonies(chatRoomId).first().firstOrNull { it.stage != IcebergRitualStage.FAILED }
@@ -85,13 +96,17 @@ class GroupLightningWalletViewModel(
}
}
+ /** Whether this device can propose a wallet statement: an LSP to name, and a key to send the seed with. */
+ private fun canPropose(): Boolean = lightningRepository.lspNodeId(chain) != null && activeIdentityStateFlow.value?.nostrPrivateKey != null
+
private var watching: Job? = null
/** Keeps an opened wallet's snapshot and payments current as the operator's reports arrive. */
private fun watchReports() {
watching?.cancel()
watching = viewModelScope.launch(Dispatchers.IO) {
- combine(lightningRepository.observeReport(chatRoomId, chain), lightningRepository.observePayments(chatRoomId, chain)) { report, payments -> report to payments }
+ val wallet = (uiState as? GroupLightningWalletUIState.Opened)?.wallet?.statement?.wallet ?: return@launch
+ combine(lightningRepository.observeReport(chatRoomId, chain, wallet), lightningRepository.observePayments(chatRoomId, chain, wallet)) { report, payments -> report to payments }
.collect { (report, payments) ->
val unswept = lightningRepository.unswept(chatRoomId, report)
(uiState as? GroupLightningWalletUIState.Opened)?.let { uiState = it.copy(report = report, payments = payments, unswept = unswept) }
@@ -101,19 +116,37 @@ class GroupLightningWalletViewModel(
/** Proposes the wallet's statement; the wallet exists once a quorum signs, on the session it returns. */
fun openWallet(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) {
- val state = uiState as? GroupLightningWalletUIState.NotOpened ?: return
+ // The first wallet, or the one a re-key opens beside the current one under a new key.
+ val localChatRoom = (uiState as? GroupLightningWalletUIState.NotOpened)?.localChatRoom
+ ?: (uiState as? GroupLightningWalletUIState.Opened)?.takeIf { it.canOpenNew }?.localChatRoom
+ ?: return
val privateKey = activeIdentityStateFlow.value?.nostrPrivateKey?.value?.toByteArray() ?: return onFailure()
- act(onSession, onFailure) { lightningRepository.proposeWallet(state.localChatRoom, activeUserPublicKey, privateKey, chain) }
+ act(onSession, onFailure) { lightningRepository.proposeWallet(localChatRoom, activeUserPublicKey, privateKey, chain) }
}
- fun nominateSelf(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) {
+ /** Nominates this device to run [wallet]'s node: the current wallet's when null. */
+ fun nominateSelf(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit, wallet: Long? = null) {
val state = uiState as? GroupLightningWalletUIState.Opened ?: return
- act(onSession, onFailure) { lightningRepository.nominateSelf(state.localChatRoom, activeUserPublicKey, chain) }
+ act(onSession, onFailure) { lightningRepository.nominateSelf(state.localChatRoom, activeUserPublicKey, chain, wallet ?: state.wallet.statement.wallet) }
}
fun stepDown(onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) {
val state = uiState as? GroupLightningWalletUIState.Opened ?: return
- act(onSession, onFailure) { lightningRepository.stepDown(state.localChatRoom, activeUserPublicKey, chain) }
+ act(onSession, onFailure) { lightningRepository.stepDown(state.localChatRoom, activeUserPublicKey, chain, state.wallet.statement.wallet) }
+ }
+
+ /** Proposes closing every channel an earlier wallet still has, so its money reaches the onchain wallet. */
+ fun closeEarlier(earlier: GroupLightningWalletUIState.Earlier, onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) {
+ val state = uiState as? GroupLightningWalletUIState.Opened ?: return
+ if (earlier.openChannels.isEmpty()) return
+ act(onSession, onFailure) { lightningRepository.proposeCloseAll(state.localChatRoom, activeUserPublicKey, earlier.wallet, earlier.openChannels) }
+ }
+
+ /** Proposes sweeping what an earlier wallet's closed channels left the group. */
+ fun sweepEarlier(earlier: GroupLightningWalletUIState.Earlier, onSession: (sessionId: String) -> Unit, onFailure: () -> Unit) {
+ val state = uiState as? GroupLightningWalletUIState.Opened ?: return
+ if (earlier.unswept.isEmpty()) return
+ act(onSession, onFailure) { lightningRepository.proposeSweep(state.localChatRoom, activeUserPublicKey, earlier.wallet, earlier.unswept) }
}
/** Proposes closing [channelId] to the onchain wallet, or by force when the LSP is gone. */
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt
index c2199fb3..78b57943 100755
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/ChatRoomDetailUIState.kt
@@ -98,6 +98,8 @@ sealed interface ChatRoomDetailUIState {
* Lightning wallet is not offered on this build (`GroupLightningRollout`).
*/
val testNetworkWallet: GroupWallet? = null,
+ /** Who holds a share of the group's Lightning wallet key, so removing one of them can say what it leaves. */
+ val lightningParticipants: Set = emptySet(),
/**
* Whether this device could sign an event for the group, which on this
* screen gates the paste at the end of the identity block. Each of the
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningWalletUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningWalletUIState.kt
index 8a2ab370..42f9f12f 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningWalletUIState.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningWalletUIState.kt
@@ -1,6 +1,7 @@
package com.machankura.bennu.compose.ui.view.state
import com.machankura.bennu.compose.database.model.IcebergKeySession
+import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.database.model.GroupLightningPaymentRow
import com.machankura.bennu.compose.managers.GroupLightningOperatorManager
@@ -38,5 +39,21 @@ sealed class GroupLightningWalletUIState {
val payments: List = emptyList(),
/** What closed channels left the group that no sweep spends yet. */
val unswept: List = emptyList(),
+ /** Participants who have left the room, and still hold a share of the key and the node's seed. */
+ val departed: List = emptyList(),
+ /** Whether a new wallet can be opened now: a key no wallet uses, and this device can propose. */
+ val canOpenNew: Boolean = false,
+ /** The wallets a re-key left behind, whose channels are still to be closed and swept. */
+ val earlier: List = emptyList(),
) : GroupLightningWalletUIState()
+
+ /** A wallet a re-key left behind, with what its operator last said of it. */
+ data class Earlier(
+ val wallet: GroupLightningWalletManager.Wallet,
+ val operator: GroupLightningOperatorManager.Operator?,
+ val report: GroupLightningReports.Report?,
+ val unswept: List,
+ ) {
+ val openChannels: List get() = report?.checks?.map { it.channel.channelId }.orEmpty()
+ }
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupLightningNodes.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupLightningNodes.kt
index db31cc25..71b5ad68 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupLightningNodes.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupLightningNodes.kt
@@ -41,25 +41,35 @@ class GroupLightningNodes(
private val nodes = mutableMapOf()
private var job: Job? = null
- fun nodeFor(chatRoomId: String): GroupLightningNode? = nodes[chatRoomId]
+ /** The node of [chatRoomId]'s wallet [wallet] -- its current one when null -- if this device runs it. */
+ fun nodeFor(chatRoomId: String, wallet: Long? = null): GroupLightningNode? =
+ if (wallet != null) nodes[key(chatRoomId, wallet)]
+ else nodes.filterKeys { it.startsWith("$chatRoomId:") }.maxByOrNull { it.value.wallet.statement.wallet }?.value
- /** Starts every node this device may run, and forgets the ones that stopped. */
+ private fun key(chatRoomId: String, wallet: Long) = "$chatRoomId:$wallet"
+
+ /**
+ * Starts every node this device may run, and forgets the ones that stopped. After a re-key a room has
+ * two wallets, each with its own operator: the old one runs until its channels are closed (Phase 14).
+ */
suspend fun refresh() = mutex.withLock {
if (!GroupLightningRollout.ENABLED && chain != Chain.Regtest) return@withLock
val rooms = database.icebergKeySessionDao().getCompletedSessions().filter { it.userPublicKey == userPublicKey }.map { it.chatRoomId }.toSet()
for (roomId in rooms) {
val localChatRoom = database.chatRoomDao().findChatRoomById(roomId) ?: continue
- val wallet = GroupLightningWalletManager.walletFor(database, roomId, chain) ?: continue
- val operator = GroupLightningOperatorManager.current(database, roomId, chain, wallet.statement.wallet)
- val existing = nodes[roomId]
- if (existing?.state?.value is GroupLightningNode.State.Running) continue
- if (operator?.publicKey != userPublicKey) {
- nodes.remove(roomId)
- continue
+ for (wallet in GroupLightningWalletManager.wallets(database, roomId, chain)) {
+ val key = key(roomId, wallet.statement.wallet)
+ val operator = GroupLightningOperatorManager.current(database, roomId, chain, wallet.statement.wallet)
+ val existing = nodes[key]
+ if (existing?.state?.value is GroupLightningNode.State.Running) continue
+ if (operator?.publicKey != userPublicKey) {
+ nodes.remove(key)
+ continue
+ }
+ val node = existing ?: GroupLightningNode(database, localChatRoom, userPublicKey, wallet, scope, peerFactory).also { nodes[key] = it }
+ val state = runCatching { node.start() }.onFailure { logger.e("Could not start the node for $key", it) }.getOrNull()
+ if (state is GroupLightningNode.State.Refused) logger.i("Not running the node for $key: ${state.reason}")
}
- val node = existing ?: GroupLightningNode(database, localChatRoom, userPublicKey, wallet, scope, peerFactory).also { nodes[roomId] = it }
- val state = runCatching { node.start() }.onFailure { logger.e("Could not start the node for $roomId", it) }.getOrNull()
- if (state is GroupLightningNode.State.Refused) logger.i("Not running the node for $roomId: ${state.reason}")
}
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningFixture.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningFixture.kt
index fb5feb40..d209054d 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningFixture.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningFixture.kt
@@ -9,6 +9,7 @@ import com.machankura.bennu.compose.database.model.DkgSession
import com.machankura.bennu.compose.database.model.IcebergKeySession
import com.machankura.bennu.compose.database.model.MarmotInnerEvent
import com.machankura.bennu.compose.database.model.NostrEvent
+import com.machankura.bennu.compose.database.model.Participant
import com.machankura.bennu.compose.database.model.Profile
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.database.model.types.DkgRitualStage
@@ -62,6 +63,11 @@ class GroupLightningFixture(val n: Int = 4, val frostThreshold: Int = 3, val cha
fun close() = devices.forEach { it.db.close() }
+ /** [member] leaves the room on every device in [on], as an applied removal commit leaves it. */
+ suspend fun remove(member: HexKey, on: List) = on.forEach { d ->
+ d.db.participantDao().delete(d.db.participantDao().findParticipantsByChatRoomId(roomId).filter { it.participantPublicKey == member })
+ }
+
suspend fun device(index: Int, holders: List = members): Device {
val db = getRoomDatabase(Room.inMemoryDatabaseBuilder())
members.forEach { member ->
@@ -71,6 +77,7 @@ class GroupLightningFixture(val n: Int = 4, val frostThreshold: Int = 3, val cha
}
val chatRoom = ChatRoom(id = roomId, userPublicKey = members[index], subject = "Treasury", description = SharedKeyDerivation.describe("Treasury."), mlsGroupState = "00")
db.chatRoomDao().upsert(chatRoom)
+ db.participantDao().upsert(members.map { Participant(participantPublicKey = it, chatRoomId = roomId, relayHint = null) })
db.dkgSessionDao().upsert(
DkgSession(
id = onchainCeremonyId, chatRoomId = roomId, coordinatorPublicKey = members.first(), userPublicKey = members[index],
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningPaymentsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningPaymentsJvmTest.kt
index dcc31c4c..1b5d5ed9 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningPaymentsJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningPaymentsJvmTest.kt
@@ -170,10 +170,12 @@ class GroupLightningPaymentsJvmTest {
assertEquals(listOf(two), nodes.single().forceClosed)
val actions = GroupLightningAuthorisations.channelActions(all[0].db, fixture.roomId, wallet.statement)
- assertEquals(listOf(GroupLightningAuthorisationEvent.CLOSE, GroupLightningAuthorisationEvent.FORCE_CLOSE), actions.map { it.action })
- val summary = ProposedEvent.summarize(Event("", "", 0, GroupLightningAuthorisationEvent.KIND, GroupLightningAuthorisationEvent.template(actions[1]).tags, "", ""))
+ // Both signed in the same second, so in no particular order.
+ assertEquals(mapOf(one to GroupLightningAuthorisationEvent.CLOSE, two to GroupLightningAuthorisationEvent.FORCE_CLOSE), actions.associate { it.channelId to it.action })
+ val forced = actions.single { it.action == GroupLightningAuthorisationEvent.FORCE_CLOSE }
+ val summary = ProposedEvent.summarize(Event("", "", 0, GroupLightningAuthorisationEvent.KIND, GroupLightningAuthorisationEvent.template(forced).tags, "", ""))
assertEquals("Force-close a Lightning channel", summary.label)
assertTrue(GroupLightningAuthorisations.channelActions(all[0].db, fixture.roomId, wallet.statement, Clock.System.now() + 4.days).isEmpty(), "both have expired")
- assertNull(GroupLightningAuthorisationEvent.read(GroupLightningAuthorisationEvent.template(actions[0]).tags), "a close is not a payment")
+ assertNull(GroupLightningAuthorisationEvent.read(GroupLightningAuthorisationEvent.template(forced).tags), "a close is not a payment")
}
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningRekeyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningRekeyJvmTest.kt
new file mode 100644
index 00000000..0444acae
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningRekeyJvmTest.kt
@@ -0,0 +1,115 @@
+package com.machankura.bennu.compose.managers
+
+import com.machankura.bennu.compose.database.model.MarmotGroupEvent
+import com.machankura.bennu.compose.database.model.NostrEvent
+import com.machankura.bennu.compose.database.model.types.IcebergRitualStage
+import com.machankura.bennu.compose.nostr.lightning.GroupLightningAuthorisationEvent
+import com.machankura.bennu.compose.nostr.lightning.GroupLightningEvents
+import com.machankura.bennu.compose.wallet.lightning.GroupLightningNodes
+import com.vitorpamplona.quartz.nip01Core.core.toHexKey
+import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
+import fr.acinq.lightning.Lightning.randomBytes32
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.runBlocking
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertIs
+import kotlin.test.assertNotEquals
+import kotlin.test.assertNull
+import kotlin.test.assertTrue
+import kotlin.time.Clock
+
+/**
+ * A member leaves a group with a Lightning wallet (`docs/group-lightning-wallet.md`, Phase 14). Iceberg
+ * cannot reshare, so the group makes a new key without them and opens a second wallet beside the first,
+ * whose channels it then closes. Five members, so that four remain: a 2-of-n Iceberg key needs n >= 4.
+ */
+class GroupLightningRekeyJvmTest {
+ private val fixture = GroupLightningFixture(n = 5, frostThreshold = 3)
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ private val lsp = "02" + KeyPair().pubKey.toHexKey()
+ private val nodes = mutableListOf()
+
+ @AfterTest
+ fun close() {
+ scope.cancel()
+ fixture.close()
+ }
+
+ private suspend fun heardFromRoom(device: GroupLightningFixture.Device) {
+ val id = randomBytes32().toHex()
+ device.db.nostrEventDao().upsert(NostrEvent(id = id, pubKey = device.publicKey, kind = 445, tags = emptyArray(), content = "", sig = "0".repeat(128)))
+ device.db.marmotGroupEventDao().upsert(MarmotGroupEvent(id = id, userPublicKey = device.publicKey, publicKey = device.publicKey, chatRoomId = fixture.roomId, signature = "", encryptedContent = "", expiresAt = null, savedAt = Clock.System.now()))
+ }
+
+ @Test
+ fun `the group re-keys without a member who left, and keeps the old wallet until its channels close`() = runBlocking {
+ val all = fixture.group()
+ fixture.runCeremony(all)
+ fixture.signSession(all, all[0], GroupLightningWalletManager.proposeWallet(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, fixture.chain, lsp).id)
+ fixture.signSession(all, all[1], GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, fixture.chain, 0).id)
+ val first = GroupLightningWalletManager.current(all[0].db, fixture.roomId, fixture.chain)!!
+ assertEquals(0, first.statement.wallet)
+ assertEquals(5, first.statement.participants.size)
+
+ // The last member is removed; the four who remain apply the commit.
+ val leaver = all[4]
+ val remaining = all.take(4)
+ fixture.remove(leaver.publicKey, remaining)
+ assertEquals(listOf(leaver.publicKey.lowercase()), GroupLightningWalletManager.departed(all[0].db, first))
+ assertEquals(listOf(2), IcebergRitualManager.thresholds(all[0].db, fixture.roomId), "four remain, so 2-of-4")
+
+ // The leaver's device, which never saw its own removal, cannot pull the others into a ceremony with it.
+ val stale = IcebergRitualManager.proposeCeremony(leaver.db, leaver.room, leaver.publicKey, leaver.privateKey, 2, fixture.chain)
+ fixture.pump(all, GroupLightningEvents.CEREMONY)
+ remaining.forEach { assertNull(it.ceremony(stale.id), "device ${it.index} refused a ceremony naming someone who left") }
+
+ val second = fixture.runCeremony(remaining, proposer = remaining[0])
+ remaining.forEach { assertEquals(IcebergRitualStage.COMPLETE, it.ceremony(second.id)?.stage) }
+ assertEquals(4, remaining[0].ceremony(second.id)!!.participants().size)
+ assertTrue(leaver.publicKey.lowercase() !in remaining[0].ceremony(second.id)!!.participants())
+
+ fixture.signSession(remaining, remaining[0], GroupLightningWalletManager.proposeWallet(remaining[0].db, remaining[0].room, remaining[0].publicKey, remaining[0].privateKey, fixture.chain, lsp).id)
+ remaining.forEach { d ->
+ val wallets = GroupLightningWalletManager.wallets(d.db, fixture.roomId, fixture.chain)
+ assertEquals(listOf(0L, 1L), wallets.map { it.statement.wallet }, "device ${d.index} believes both")
+ val current = wallets.last()
+ assertEquals(second.id, current.statement.ceremonyId)
+ assertNotEquals(first.statement.nodeId, current.statement.nodeId)
+ assertTrue(GroupLightningWalletManager.departed(d.db, current).isEmpty())
+ assertEquals(null, GroupLightningWalletManager.unusedKey(d.db, fixture.roomId, fixture.chain), "both keys are in use")
+ }
+
+ // The new wallet gets its own operator; the old one keeps its own until its channels are closed.
+ fixture.signSession(remaining, remaining[2], GroupLightningOperatorManager.nominateSelf(remaining[2].db, remaining[2].room, remaining[2].publicKey, fixture.chain, 1).id)
+ assertEquals(remaining[1].publicKey, GroupLightningOperatorManager.current(remaining[0].db, fixture.roomId, fixture.chain, 0)?.publicKey)
+ assertEquals(remaining[2].publicKey, GroupLightningOperatorManager.current(remaining[0].db, fixture.roomId, fixture.chain, 1)?.publicKey)
+ val factory: suspend (GroupLightningNode.NodeConfiguration) -> GroupLightningNode.PeerHandle = { FakeGroupNode(it).also { node -> nodes += node } }
+ remaining.forEach { heardFromRoom(it) }
+ val oldOperator = GroupLightningNodes(remaining[1].db, remaining[1].publicKey, scope, factory, fixture.chain)
+ val newOperator = GroupLightningNodes(remaining[2].db, remaining[2].publicKey, scope, factory, fixture.chain)
+ oldOperator.refresh()
+ newOperator.refresh()
+ assertIs(oldOperator.nodeFor(fixture.roomId, 0)?.state?.value)
+ assertNull(oldOperator.nodeFor(fixture.roomId, 1))
+ assertIs(newOperator.nodeFor(fixture.roomId, 1)?.state?.value)
+ assertEquals(1, newOperator.nodeFor(fixture.roomId)?.wallet?.statement?.wallet, "a room's node is its current wallet's")
+
+ // Closing the old wallet's channels is one decision, whatever their number.
+ val channels = listOf("a1".repeat(32), "a2".repeat(32))
+ val old = GroupLightningWalletManager.walletFor(remaining[3].db, fixture.roomId, fixture.chain, 0)!!
+ val session = GroupLightningAuthorisations.proposeCloseAll(remaining[3].db, remaining[3].room, remaining[3].publicKey, old, channels)
+ assertEquals(2, remaining[3].db.frostSigningSessionDao().getItems(session.id).size)
+ fixture.signSession(remaining, remaining[3], session.id)
+ val actions = GroupLightningAuthorisations.channelActions(remaining[1].db, fixture.roomId, old.statement)
+ assertEquals(channels.toSet(), actions.map { it.channelId }.toSet())
+ assertTrue(actions.all { it.action == GroupLightningAuthorisationEvent.CLOSE && it.wallet == 0L })
+ assertTrue(GroupLightningAuthorisations.channelActions(remaining[1].db, fixture.roomId, GroupLightningWalletManager.walletFor(remaining[1].db, fixture.roomId, fixture.chain, 1)!!.statement).isEmpty(), "the new wallet's channels are not touched")
+ oldOperator.stop()
+ newOperator.stop()
+ }
+}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/IcebergCeremonyJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/IcebergCeremonyJvmTest.kt
index 0bd0f8b9..6a78d199 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/IcebergCeremonyJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/IcebergCeremonyJvmTest.kt
@@ -10,6 +10,7 @@ import com.machankura.bennu.compose.database.model.DkgSession
import com.machankura.bennu.compose.database.model.IcebergKeySession
import com.machankura.bennu.compose.database.model.MarmotInnerEvent
import com.machankura.bennu.compose.database.model.NostrEvent
+import com.machankura.bennu.compose.database.model.Participant
import com.machankura.bennu.compose.database.model.Profile
import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom
import com.machankura.bennu.compose.database.model.types.DkgRitualStage
@@ -95,6 +96,8 @@ class IcebergCeremonyJvmTest {
}
val chatRoom = ChatRoom(id = roomId, userPublicKey = members[index], subject = "Treasury", description = SharedKeyDerivation.describe("Treasury."), mlsGroupState = "00")
db.chatRoomDao().upsert(chatRoom)
+ // Everyone is in the room: a ceremony is over the onchain key's holders who still are.
+ db.participantDao().upsert(members.map { Participant(participantPublicKey = it, chatRoomId = roomId, relayHint = null) })
db.dkgSessionDao().upsert(
DkgSession(
id = onchainCeremonyId, chatRoomId = roomId, coordinatorPublicKey = members.first(), userPublicKey = members[index],
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt
index 17357b9b..79bcf937 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/ui/view/model/GroupLightningWalletViewModelJvmTest.kt
@@ -99,6 +99,9 @@ class GroupLightningWalletViewModelJvmTest {
val report: GroupLightningReports.Report? = null,
val payments: List = emptyList(),
val invoice: GroupLightningInvoiceRow? = null,
+ val departedMembers: List = emptyList(),
+ val earlier: List = emptyList(),
+ val unusedKey: Boolean = false,
) : GroupLightningRepository {
val requests = mutableListOf>()
override fun observeCeremony(sessionId: String): Flow = flowOf(running)
@@ -112,18 +115,22 @@ class GroupLightningWalletViewModelJvmTest {
override suspend fun approveCeremony(localChatRoom: LocalChatRoom, sessionId: String, step: IcebergApprovalStep, nostrPrivateKey: ByteArray) = Unit
override suspend fun completedCeremony(chatRoomId: String): IcebergKeySession? = completed
override suspend fun lightningWallet(chatRoomId: String, chain: Chain): GroupLightningWalletManager.Wallet? = wallet
- override suspend fun operator(chatRoomId: String, chain: Chain): GroupLightningOperatorManager.Operator? = operator
+ override suspend fun operator(chatRoomId: String, chain: Chain, wallet: Long): GroupLightningOperatorManager.Operator? = operator
override fun lspNodeId(chain: Chain): HexKey? = "02" + "44".repeat(32)
override suspend fun proposeWallet(localChatRoom: LocalChatRoom, userPublicKey: HexKey, nostrPrivateKey: ByteArray, chain: Chain): FrostSigningSession = error("unused")
- override suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain): FrostSigningSession = error("unused")
- override suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain): FrostSigningSession = error("unused")
- override fun observeReport(chatRoomId: String, chain: Chain): Flow = flowOf(report)
- override fun observePayments(chatRoomId: String, chain: Chain): Flow> = flowOf(payments)
+ override suspend fun nominateSelf(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession = error("unused")
+ override suspend fun stepDown(localChatRoom: LocalChatRoom, userPublicKey: HexKey, chain: Chain, wallet: Long): FrostSigningSession = error("unused")
+ override fun observeReport(chatRoomId: String, chain: Chain, wallet: Long): Flow = flowOf(report)
+ override fun observePayments(chatRoomId: String, chain: Chain, wallet: Long): Flow> = flowOf(payments)
override suspend fun requestInvoice(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, amountMsat: Long?, description: String): String =
"r1".also { requests += amountMsat to description }
- override fun observeInvoice(chatRoomId: String, chain: Chain, requestId: String): Flow = flowOf(invoice?.takeIf { it.requestId == requestId })
+ override fun observeInvoice(chatRoomId: String, chain: Chain, wallet: Long, requestId: String): Flow = flowOf(invoice?.takeIf { it.requestId == requestId })
override suspend fun proposePayment(localChatRoom: LocalChatRoom, userPublicKey: HexKey, pay: GroupLightningAuthorisationEvent.Pay): FrostSigningSession = error("unused")
override suspend fun proposeClose(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelId: String, force: Boolean): FrostSigningSession = error("unused")
+ override suspend fun earlierWallets(chatRoomId: String, chain: Chain): List = earlier
+ override suspend fun departed(wallet: GroupLightningWalletManager.Wallet): List = departedMembers
+ override suspend fun hasUnusedKey(chatRoomId: String, chain: Chain): Boolean = unusedKey
+ override suspend fun proposeCloseAll(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, channelIds: List): FrostSigningSession = error("unused")
override suspend fun unswept(chatRoomId: String, report: GroupLightningReports.Report?): List = report?.snapshot?.heldOutputs.orEmpty()
override suspend fun proposeSweep(localChatRoom: LocalChatRoom, userPublicKey: HexKey, wallet: GroupLightningWalletManager.Wallet, inputs: List): FrostSigningSession = error("unused")
}
@@ -240,4 +247,16 @@ class GroupLightningWalletViewModelJvmTest {
val problem = (viewModel.preview()!!.exceptionOrNull() as GroupLightningAuthorisations.ProblemException).problem
assertEquals(GroupLightningAuthorisations.Problem.OtherNetwork, problem)
}
+
+ @Test
+ fun `after a member leaves, the wallet says so, and lists the wallet a re-key left behind`() {
+ val earlier = wallet.copy(statement = wallet.statement.copy(wallet = 0))
+ val current = wallet.copy(statement = wallet.statement.copy(wallet = 1))
+ val state = assertIs(
+ settled(Lightning(completed = key, wallet = current, departedMembers = listOf("d".repeat(64)), earlier = listOf(earlier), unusedKey = true))
+ )
+ assertEquals(listOf("d".repeat(64)), state.departed)
+ assertEquals(listOf(0L), state.earlier.map { it.wallet.statement.wallet })
+ assertTrue(!state.canOpenNew, "a profile with no private key to send the seed with cannot open the new wallet")
+ }
}
diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md
index 29f4d7b9..9e16452a 100644
--- a/docs/group-lightning-wallet.md
+++ b/docs/group-lightning-wallet.md
@@ -42,6 +42,7 @@ build chose differently, this table says so.
| 11 | done: invoice requests and answers through `GroupLightningReports`, the running node answering each request once, and the receive screen (`GroupLightningReceiveScreen`). A member files an invoice only from the operator, and only if it pays the node the statement names. Three new tests |
| 12 | done: `GroupLightningAuthorisationEvent` (kind 30346, `pay`), budgets read from the signed authorisations, the node paying each once, its summary and transcript line, and the send screen (`GroupLightningSendScreen`). The co-signers now hold offered HTLCs under the statement's in-flight cap. Seven new tests |
| 13 | done, except splicing out. `close` and `force-close` authorisations, the node acting on each once, the co-signers signing our own commitment only under a force-close authorisation and only after rebuilding it, and the channel menu on the wallet screen. Sweeps: the snapshot lists what closed channels left the group, any member proposes a sweep (`GroupSweep`, a new FROST subject), every member checks it against its own basepoints and the onchain wallet, and the watcher sends it. Five new tests: a force close and a two-input sweep both pass the script interpreter |
+| 14 | done: a room can have several Lightning wallets on a network, the highest-numbered current. A member who leaves is named on the wallet screen until a new wallet replaces it; the new key is made over the onchain key's holders who are still in the room; the old wallet keeps its operator and node until its channels are closed, in one decision for all of them; and removing a share holder says what it leaves. A five-device test re-keys after a removal |
| what the plan said | what it turned out to be |
|---|---|
@@ -105,6 +106,10 @@ build chose differently, this table says so.
| `GroupSpend.check` gains a script-path input type | a separate check, `GroupSweep.check`, and a FROST subject of its own, `SWEEP`. A PSBT cannot carry a taproot leaf in bitcoin-kmp, and a sweep's rules are not a spend's: every output must be the group's own, and every input must be the one leaf lightning-kmp gives a group-held output, rebuilt by the member from its own basepoints. The sweep rides in the transaction row's PSBT column, and every PSBT reader skips what it cannot decode |
| the sweep's tweak comes from a per-commitment point the member derives | the proposal carries the tweak. Any tweak gives a key only the group can sign for, and BIP341 commits the signature to the leaf and to every spent output, so a made-up tweak is a sweep nobody can mine, never one that pays someone else |
| splice out to an onchain wallet address | **not built.** The co-signers pin a channel to its funding output the first time they sign for it, and a splice moves the channel to a new one. Letting it move means checking the splice transaction itself, its shared input, the new funding output and the splice-out output, inside lightning-kmp's interactive negotiation. Until then money leaves the Lightning wallet by being paid out, or by closing |
+| D1: Iceberg participants are the onchain key's holders | the holders *still in the room*, which Phase 14 needs: a removed member keeps an onchain share, so a ceremony over every holder would include them again. A statement is believed when every participant holds the onchain key, so the wallet before a removal and the one after both verify. Each device reads the room from its own MLS state, and a removal commit is an earlier epoch than any proposal sent after it, so every device computes the same set |
+| a new wallet statement with the next `wallet` number | as written, opened under the newest completed Iceberg key no statement uses yet (`GroupLightningWalletManager.unusedKey`). The screen shows the highest-numbered wallet, and the ones before it as earlier wallets with their balance and a way to close them |
+| 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 |
| the kinds are reserved | in code: `GroupLightningEvents`, 30333-30349, 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 |