diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/IcebergKeySessionDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/IcebergKeySessionDao.kt index 825d9539..91ff55ee 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/IcebergKeySessionDao.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/IcebergKeySessionDao.kt @@ -22,6 +22,9 @@ interface IcebergKeySessionDao { @Query("SELECT * FROM IcebergKeySession WHERE chatRoomId = :chatRoomId ORDER BY createdAt DESC") fun observeSessionsForChatRoom(chatRoomId: String): Flow> + @Query("SELECT * FROM IcebergKeySession WHERE stage = 'COMPLETE'") + suspend fun getCompletedSessions(): List + @Upsert suspend fun upsert(session: IcebergKeySession) diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MarmotGroupEventDao.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MarmotGroupEventDao.kt index 17270638..628cb2bb 100644 --- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MarmotGroupEventDao.kt +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/database/dao/MarmotGroupEventDao.kt @@ -14,4 +14,11 @@ interface MarmotGroupEventDao { @Query("SELECT * FROM MarmotGroupEvent WHERE id = :id") suspend fun getMarmotGroupEventById(id: HexKey): MarmotGroupEvent? + + /** + * When this device last saved a group event for [chatRoomId]: the nearest thing it has to when it + * last heard from the room, which the Lightning wallet's start gate reads. + */ + @Query("SELECT MAX(savedAt) FROM MarmotGroupEvent WHERE chatRoomId = :chatRoomId") + suspend fun newestSavedAt(chatRoomId: String): kotlin.time.Instant? } diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt new file mode 100644 index 00000000..8178593e --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt @@ -0,0 +1,191 @@ +package com.machankura.bennu.compose.managers + +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.database.model.intermdiate.LocalChatRoom +import com.machankura.bennu.compose.wallet.GroupChainClients +import com.machankura.bennu.compose.wallet.lightning.GroupNodeKeyManager +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.Chain +import fr.acinq.bitcoin.PublicKey +import fr.acinq.lightning.Feature +import fr.acinq.lightning.FeatureSupport +import fr.acinq.lightning.NodeParams +import fr.acinq.lightning.WalletParams +import fr.acinq.lightning.blockchain.electrum.ElectrumWatcher +import fr.acinq.lightning.channel.states.ChannelStateWithCommitments +import fr.acinq.lightning.crypto.RemoteIcebergFundingSigner +import fr.acinq.lightning.db.Databases +import fr.acinq.lightning.io.Peer +import fr.acinq.lightning.io.TcpSocket +import fr.acinq.lightning.logging.LoggerFactory +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds + +/** + * The group's Lightning node, on the operator's device (`docs/group-lightning-wallet.md`, Phase 8). + * + * A second lightning-kmp node beside the identity's own, built from the wallet's seed, with the group's + * funding key, basepoints and closing address ([GroupNodeKeyManager]), and a remote Iceberg signer whose + * transport ([GroupIcebergTransport]) reaches the members through the room. It runs only while this + * device is the elected operator and has heard from the room recently ([GroupLightningOperatorManager.mayRunNode]), + * and it stops itself the moment a newer term names somebody else -- telling the room where its + * channels were as it goes (kind 30349). + * + * The node itself is behind [PeerHandle], so the life cycle can be tested without an LSP to connect to. + */ +class GroupLightningNode( + private val database: BennuDatabase, + private val localChatRoom: LocalChatRoom, + private val userPublicKey: HexKey, + val wallet: GroupLightningWalletManager.Wallet, + private val scope: CoroutineScope, + private val peerFactory: suspend (NodeConfiguration) -> PeerHandle, + private val now: () -> kotlin.time.Instant = { Clock.System.now() }, + private val handoverCheck: Duration = HANDOVER_CHECK, +) { + private val logger = Logger.withTag("GroupLightningNode") + private val chain = wallet.statement.chain + + /** What a node needs to be built, gathered here so a [peerFactory] can build a real one or a fake. */ + class NodeConfiguration(val keyManager: GroupNodeKeyManager, val chain: Chain, val lspNodeId: PublicKey, val transport: GroupIcebergTransport) + + /** What this class needs of a running node. */ + interface PeerHandle { + suspend fun connect(): Boolean + fun disconnect() + /** Each channel's local commitment number, by channel id: what the stopped message reports. */ + fun commitmentNumbers(): Map + } + + sealed class State { + data object Stopped : State() + data class Running(val term: Long) : State() + data class Refused(val reason: String) : State() + } + + private val _state = MutableStateFlow(State.Stopped) + val state: StateFlow = _state + + private var peer: PeerHandle? = null + private var transport: GroupIcebergTransport? = null + private var watching: Job? = null + + /** Starts the node if this device may run it now; otherwise says why not. */ + suspend fun start(): State { + if (_state.value is State.Running) return _state.value + val roomId = localChatRoom.chatRoom.id + val operator = GroupLightningOperatorManager.current(database, roomId, chain, wallet.statement.wallet) + val lastHeard = database.marmotGroupEventDao().newestSavedAt(roomId) + if (!GroupLightningOperatorManager.mayRunNode(database, roomId, chain, userPublicKey, lastHeard, now(), wallet.statement.wallet)) { + return State.Refused( + if (operator?.publicKey != userPublicKey) "this device is not the operator" else "this device has not heard from the room recently enough to be sure it still is" + ).also { _state.value = it } + } + val seed = wallet.seed ?: return State.Refused("this device does not hold the wallet's seed").also { _state.value = it } + val term = operator!!.term + + val transport = GroupIcebergTransport.create(database, localChatRoom, userPublicKey, wallet, term, scope).also { it.start() } + transport.provision(GroupLightningCoSigner.POOL_WINDOW) + val onchain = GroupWalletManager.walletFor(database, roomId, chain, wallet.statement.onchainAccount) + ?: return State.Refused("the onchain wallet it closes to is not open").also { _state.value = it } + val keyManager = GroupNodeKeyManager( + delegate = GroupLightningCoSigner.keyManagerOf(ByteVector(seed.seed), chain), + fundingSigner = RemoteIcebergFundingSigner(PublicKey.fromHex(wallet.statement.icebergKey), transport, SIGNING_DEADLINE), + basepoints = wallet.basepoints.forChannel, + finalScriptPubKey = GroupWalletDerivation.derive(onchain.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript, + ) + check(keyManager.nodeKeys.nodeKey.publicKey.toString() == wallet.statement.nodeId) { "the seed does not produce the statement's node" } + + val handle = peerFactory(NodeConfiguration(keyManager, chain, PublicKey.fromHex(wallet.statement.lspNodeId), transport)) + this.transport = transport + peer = handle + _state.value = State.Running(term) + handle.connect() + watchForHandover(term) + logger.i("The group's node ${wallet.statement.nodeId.take(16)} is running, term $term") + return _state.value + } + + /** Stops the node and tells the room where its channels were. Safe to call when it is not running. */ + suspend fun stop() { + watching?.cancel() + halt() + } + + /** [stop], minus cancelling the handover watch: the watch calls this itself, and must finish saying so. */ + private suspend fun halt() { + val running = _state.value as? State.Running ?: return + val numbers = peer?.commitmentNumbers().orEmpty() + peer?.disconnect() + transport?.stop() + peer = null + transport = null + _state.value = State.Stopped + GroupLightningOperatorManager.announceStopped(database, localChatRoom, userPublicKey, chain, wallet.statement.wallet, running.term, numbers) + logger.i("The group's node stopped at the end of term ${running.term}") + } + + /** Stops the node as soon as the room's newest operator statement names a later term. */ + private fun watchForHandover(term: Long) { + watching?.cancel() + watching = scope.launch { + while (isActive) { + delay(handoverCheck) + val current = GroupLightningOperatorManager.current(database, localChatRoom.chatRoom.id, chain, wallet.statement.wallet) + if (current == null || current.term != term || current.publicKey != userPublicKey) { + logger.i("Term $term is over; stopping the group's node") + halt() + return@launch + } + } + } + } + + companion object { + /** How long a signature may take the group. Phase 0 was to measure what the LSP tolerates; until it is, a minute. */ + val SIGNING_DEADLINE: Duration = 60.seconds + val HANDOVER_CHECK: Duration = 10.seconds + + /** + * Builds real lightning-kmp nodes: simple taproot channels only, peer storage on, zero-conf with the + * LSP alone, on the chain's Electrum connection, persisted in the databases [databasesFor] opens for + * the node's id. + */ + fun lightningKmpPeers( + clients: GroupChainClients, + databasesFor: (nodeId: PublicKey, chain: Chain) -> Databases, + walletParamsFor: (Chain) -> WalletParams, + loggerFactory: LoggerFactory, + scope: CoroutineScope, + ): suspend (NodeConfiguration) -> PeerHandle = { configuration -> + val base = NodeParams(configuration.chain, loggerFactory, configuration.keyManager) + val nodeParams = base.copy( + features = base.features.copy(activated = base.features.activated + (Feature.SimpleTaprootChannels to FeatureSupport.Mandatory)), + zeroConfPeers = setOf(configuration.lspNodeId), + usePeerStorage = true, + ) + val walletParams = walletParamsFor(configuration.chain) + require(walletParams.trampolineNode.id == configuration.lspNodeId) { "the wallet's LSP is not the node it would connect to" } + val client = clients.clientFor(configuration.chain) + val watcher = ElectrumWatcher(client, scope, loggerFactory) + val peer = Peer(nodeParams, walletParams, client, watcher, databasesFor(nodeParams.nodeId, configuration.chain), TcpSocket.Builder(), scope) + object : PeerHandle { + override suspend fun connect(): Boolean = peer.connect(connectTimeout = 10.seconds, handshakeTimeout = 10.seconds) + override fun disconnect() = peer.disconnect() + override fun commitmentNumbers(): Map = peer.channelsFlow.value.mapNotNull { (id, state) -> + (state as? ChannelStateWithCommitments)?.let { id.toHex() to it.commitments.localCommitIndex } + }.toMap() + } + } + } +} 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 48681975..ed419cdb 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 @@ -1,5 +1,15 @@ package com.machankura.bennu.compose.ui.composable.navigation +import fr.acinq.phoenixd.conf.LSP +import fr.acinq.phoenix.db.createPaymentsDbDriver +import fr.acinq.phoenix.db.createSqlitePaymentsDb +import fr.acinq.phoenix.db.createChannelsDbDriver +import fr.acinq.phoenix.db.createSqliteChannelsDb +import fr.acinq.phoenix.managers.PhoenixDatabases +import fr.acinq.phoenix.managers.DatabaseManager +import com.machankura.bennu.compose.wallet.GroupLightningRollout +import com.machankura.bennu.compose.managers.GroupLightningNode +import com.machankura.bennu.compose.wallet.lightning.GroupLightningNodes import com.machankura.bennu.compose.ui.composable.navigation.routes.GroupLightningWalletRoute import com.machankura.bennu.compose.ui.composable.GroupLightningWalletScreen import com.machankura.bennu.compose.ui.composable.navigation.routes.IcebergCeremonyRoute @@ -293,6 +303,38 @@ fun BennuNavHost( onDispose { groupOnchainWallets?.let { wallets -> applicationIOScope.launch { wallets.stop() } } } } + // 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. + 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 + GroupLightningNodes( + database = auxDatabaseManager.auxDatabase, + userPublicKey = user, + scope = applicationIOScope, + peerFactory = GroupLightningNode.lightningKmpPeers( + clients = clients, + 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), + cloudKit = null, + ) + }, + walletParamsFor = { chain -> LSP.from(chain).walletParams }, + loggerFactory = business.loggerFactory, + scope = applicationIOScope, + ), + ).also { it.start() } + } + } + DisposableEffect(groupLightningNodes) { + onDispose { groupLightningNodes?.let { nodes -> applicationIOScope.launch { nodes.stop() } } } + } + // 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. 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 new file mode 100644 index 00000000..db31cc25 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupLightningNodes.kt @@ -0,0 +1,87 @@ +package com.machankura.bennu.compose.wallet.lightning + +import co.touchlab.kermit.Logger +import com.machankura.bennu.compose.database.BennuDatabase +import com.machankura.bennu.compose.managers.GroupLightningNode +import com.machankura.bennu.compose.managers.GroupLightningOperatorManager +import com.machankura.bennu.compose.managers.GroupLightningWalletManager +import com.machankura.bennu.compose.wallet.GroupLightningRollout +import com.vitorpamplona.quartz.nip01Core.core.HexKey +import fr.acinq.bitcoin.Chain +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 +import kotlin.time.Duration.Companion.minutes + +/** + * The group Lightning nodes one identity runs: one for every wallet this device is the elected operator + * of, started when it may run and stopped when it may not (`docs/group-lightning-wallet.md`, Phase 8). + * + * Made where the identity's node is and stopped with it, like the onchain wallets. Every [CHECK] it looks + * again at every Lightning wallet this device holds a share of: a node starts once this device is elected + * and has heard from the room recently, and each running node stops itself when a later term begins. + * + * On Android the node runs while the app does. A foreground service that keeps it running with the app + * in the background is the next piece of work, and the nomination screen says so meanwhile. + */ +class GroupLightningNodes( + private val database: BennuDatabase, + private val userPublicKey: HexKey, + private val scope: CoroutineScope, + private val peerFactory: suspend (GroupLightningNode.NodeConfiguration) -> GroupLightningNode.PeerHandle, + private val chain: Chain = GroupLightningRollout.NETWORK, +) { + private val logger = Logger.withTag("GroupLightningNodes") + private val mutex = Mutex() + private val nodes = mutableMapOf() + private var job: Job? = null + + fun nodeFor(chatRoomId: String): GroupLightningNode? = nodes[chatRoomId] + + /** Starts every node this device may run, and forgets the ones that stopped. */ + 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 + } + 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}") + } + } + + fun start() { + job?.cancel() + job = scope.launch { + while (isActive) { + runCatching { refresh() }.onFailure { logger.e("Could not refresh the group nodes", it) } + delay(CHECK) + } + } + } + + suspend fun stop() { + job?.cancel() + mutex.withLock { + nodes.values.forEach { runCatching { it.stop() } } + nodes.clear() + } + } + + companion object { + val CHECK: Duration = 1.minutes + } +} diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupNodeKeyManager.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupNodeKeyManager.kt new file mode 100644 index 00000000..2781bb12 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/wallet/lightning/GroupNodeKeyManager.kt @@ -0,0 +1,26 @@ +package com.machankura.bennu.compose.wallet.lightning + +import fr.acinq.bitcoin.ByteVector +import fr.acinq.bitcoin.KeyPath +import fr.acinq.lightning.crypto.ChannelKeys +import fr.acinq.lightning.crypto.FundingSigner +import fr.acinq.lightning.crypto.GroupBasepoints +import fr.acinq.lightning.crypto.KeyManager + +/** + * The key manager a group Lightning wallet's node runs on (`docs/group-lightning-wallet.md`, Phase 8): + * the node seed's own keys for everything but three things. Every channel's funding key is the group's + * Iceberg key, held by [fundingSigner]; its payment and delayed-payment basepoints are the group's FROST + * keys ([basepoints]); and it closes to [finalScriptPubKey], the group's onchain wallet. + */ +class GroupNodeKeyManager( + private val delegate: KeyManager, + private val fundingSigner: FundingSigner, + private val basepoints: GroupBasepoints, + private val finalScriptPubKey: ByteVector, +) : KeyManager by delegate { + override fun channelKeys(fundingKeyPath: KeyPath): ChannelKeys = + delegate.channelKeys(fundingKeyPath).withFundingSigner(fundingSigner).withGroupBasepoints(basepoints) + + override val defaultFinalScriptPubKey: ByteVector get() = finalScriptPubKey +} diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningNodeJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningNodeJvmTest.kt new file mode 100644 index 00000000..ea967552 --- /dev/null +++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningNodeJvmTest.kt @@ -0,0 +1,152 @@ +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.network.serialization.CommonJson +import com.machankura.bennu.compose.nostr.lightning.GroupLightningEvents +import com.machankura.bennu.compose.wallet.lightning.GroupLightningNodes +import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair +import com.vitorpamplona.quartz.nip01Core.core.toHexKey +import fr.acinq.bitcoin.PublicKey +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.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlin.time.Duration.Companion.milliseconds +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +/** + * The group's node on the operator's device: built with the group's keys, started only by the elected + * operator who has heard from the room recently, and stopped -- with a word to the room -- the moment a + * later term begins (`docs/group-lightning-wallet.md`, Phase 8). The node itself is a stand-in: there is + * no LSP here to connect to. + */ +class GroupLightningNodeJvmTest { + private val fixture = GroupLightningFixture() + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val lsp = "02" + KeyPair().pubKey.toHexKey() + + @AfterTest + fun close() { + scope.cancel() + fixture.close() + } + + private class FakePeer : GroupLightningNode.PeerHandle { + var connected = false + var disconnected = false + override suspend fun connect(): Boolean { connected = true; return true } + override fun disconnect() { disconnected = true } + override fun commitmentNumbers(): Map = mapOf("ab".repeat(32) to 7L) + } + + private var configurations = mutableListOf() + private val peers = mutableListOf() + private val factory: suspend (GroupLightningNode.NodeConfiguration) -> GroupLightningNode.PeerHandle = { configuration -> + configurations += configuration + FakePeer().also { peers += it } + } + + private suspend fun ready(): List { + val all = fixture.group() + fixture.runCeremony(all) + val session = GroupLightningWalletManager.proposeWallet(all[0].db, all[0].room, all[0].publicKey, all[0].privateKey, fixture.chain, lsp) + fixture.signSession(all, all[0], session.id) + return all + } + + private suspend fun elect(all: List, who: GroupLightningFixture.Device) { + val session = GroupLightningOperatorManager.nominateSelf(who.db, who.room, who.publicKey, fixture.chain) + fixture.signSession(all, who, session.id) + } + + /** As if this device had just heard from the room. */ + private suspend fun heardFromRoom(device: GroupLightningFixture.Device) { + // A kind:445 is a nostr event first, and its row hangs off that one. + 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()) + ) + } + + private suspend fun node(device: GroupLightningFixture.Device) = GroupLightningNode( + device.db, device.room, device.publicKey, GroupLightningWalletManager.walletFor(device.db, fixture.roomId, fixture.chain)!!, scope, factory, + handoverCheck = 100.milliseconds, + ) + + @Test + fun `the node runs on the group's keys`() = runBlocking { + val all = ready() + elect(all, all[1]) + heardFromRoom(all[1]) + val node = node(all[1]) + assertIs(node.start()) + val keys = configurations.single().keyManager + val wallet = node.wallet + assertEquals(wallet.statement.nodeId, keys.nodeKeys.nodeKey.publicKey.toString()) + val channelKeys = keys.channelKeys(keys.newFundingKeyPath(isChannelOpener = false)) + assertEquals(PublicKey.fromHex(wallet.statement.icebergKey), channelKeys.fundingPublicKey(0)) + assertEquals(wallet.basepoints.forChannel.payment, channelKeys.paymentBasePoint) + assertEquals(wallet.basepoints.forChannel.delayedPayment, channelKeys.delayedPaymentBasePoint) + assertEquals(GroupWalletDerivation.derive(fixture.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript, keys.defaultFinalScriptPubKey) + assertTrue(peers.single().connected) + // Starting asked the group for round one ahead of any need. + assertTrue(fixture.outbox(all[1], setOf(GroupLightningEvents.SIGNING_REQUEST)).isNotEmpty()) + assertTrue(fixture.outbox(all[1], setOf(GroupLightningEvents.NONCE_BATCH)).isNotEmpty()) + node.stop() + } + + @Test + fun `only the elected operator, who has heard from the room, may run it`() = runBlocking { + val all = ready() + elect(all, all[1]) + heardFromRoom(all[2]) + assertIs(node(all[2]).start(), "a member who was not elected") + assertIs(node(all[1]).start(), "the operator, who has heard nothing from the room") + assertTrue(peers.isEmpty()) + } + + @Test + fun `a later term stops the node, and the room is told where its channels were`() = runBlocking { + val all = ready() + elect(all, all[1]) + heardFromRoom(all[1]) + val node = node(all[1]) + assertIs(node.start()) + elect(all, all[2]) + withTimeout(5.seconds) { while (node.state.value is GroupLightningNode.State.Running) delay(50) } + assertTrue(peers.single().disconnected) + val stopped = fixture.outbox(all[1], setOf(GroupLightningEvents.STOPPED)).single() + val body = CommonJson.decodeFromString(GroupLightningOperatorManager.Stopped.serializer(), stopped.content) + assertEquals(1, body.term) + assertEquals(mapOf("ab".repeat(32) to 7L), body.commitmentNumbers) + } + + @Test + fun `the identity's nodes start where it operates and nowhere else`() = runBlocking { + val all = ready() + elect(all, all[3]) + all.forEach { heardFromRoom(it) } + val operatorNodes = GroupLightningNodes(all[3].db, all[3].publicKey, scope, factory, fixture.chain) + val otherNodes = GroupLightningNodes(all[0].db, all[0].publicKey, scope, factory, fixture.chain) + operatorNodes.refresh() + otherNodes.refresh() + assertIs(operatorNodes.nodeFor(fixture.roomId)?.state?.value) + assertEquals(null, otherNodes.nodeFor(fixture.roomId)) + operatorNodes.stop() + assertTrue(peers.single().disconnected) + assertTrue(1.minutes > 0.seconds) + } +} diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md index caed36d2..6aa99858 100644 --- a/docs/group-lightning-wallet.md +++ b/docs/group-lightning-wallet.md @@ -37,6 +37,7 @@ build chose differently, this table says so. | 5 | done: `IcebergRitualManager`, schema 27 (`IcebergKeySession`, `IcebergParticipantMessage`), the ceremony screen and its transcript lines. Seven four-device tests, and the app's 1,391 JVM tests pass | | 6, 7 | done together, as their screen and summaries are one piece: the wallet and operator statements, the node seed (schema 28), `GroupLightningWalletManager`, `GroupLightningOperatorManager` and the Lightning wallet screen. Twelve new tests; the app's 1,403 JVM tests pass | | 9 | done before 8, because the node's transport is half of it: `GroupLightningCoSigner`, `CoSignerPolicy`, `GroupIcebergTransport`, schema 29, and the fork's `SigningContext` (`bd78ed62`). A four-device test co-signs a real commitment that spends its funding output beside a stock counterparty, and five refusals hold. The app's 1,415 JVM tests and the fork's 993 pass | +| 8 | done: `GroupLightningNode`, `GroupNodeKeyManager` and `GroupLightningNodes`, wired into the app behind `GroupLightningRollout`. Four tests with a stand-in peer cover the keys, the start gate and the handover. The node has not connected to an LSP: that needs Phase 0's testnet3 run | | what the plan said | what it turned out to be | |---|---| @@ -75,6 +76,12 @@ build chose differently, this table says so. | check 8, splices | refused: the channel is pinned to its funding output the first time a device signs for it, and a request for any other output is refused. Splices arrive with Phase 13 | | a co-signer whose database was restored collects high-water marks from `t` others | **not built.** The ledger is never pruned and a restored device starts with an empty one, so a restored co-signer could echo a label it answered before the restore. The echo rule still stops the label being signed under two messages unless `n-t+1` members echo the second, which needs the restored device and `n-2t+1` others to be wrong. It is listed under what is left | | the operator collects `t` shares | `2t-1`, the quorum the scheme wants online for round two; `aggregatePartialSignatures` degree-checks a set larger than `t` | +| first find out whether `lightning-kmp-app/library` can host a second `PhoenixBusiness` | it does not need to. `GroupLightningNode` builds a lightning-kmp `Peer` itself, on Phoenix's SQLite channel and payment databases (`createSqliteChannelsDb`, `createSqlitePaymentsDb`), under file names prefixed `group-` so they never meet the identity's own | +| the node does not connect while its pool is short | it provisions the pool as it starts, and the transport asks for more whenever fewer than a third of a window remain. It does not wait for the pool before connecting; a channel that needs a label the pool lacks fails by name (`IcebergNonceNotProvisioned`) | +| the start gate reads when the room last synced | the newest group event this device saved for the room (`MarmotGroupEventDao.newestSavedAt`), because the app keeps no sync time. A sync time taken from the live subscription's end-of-stored-events is the follow-up | +| a foreground service keeps the node running on Android | **not built.** The node runs while the app does | +| a signing timeout disconnects the node | not done: lightning-kmp treats the timeout as a failed signature, and the channel retries on its own schedule | +| a test runs regtest end to end against the docker eclair | not run, for Phase 0's reason. The four node tests use a stand-in peer, and the co-signing test in Phase 9 signs real commitments built from channel parameters | | 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 |