diff --git a/composeApp/src/commonMain/composeResources/values/strings.xml b/composeApp/src/commonMain/composeResources/values/strings.xml
index f8097013..c1fbb96b 100644
--- a/composeApp/src/commonMain/composeResources/values/strings.xml
+++ b/composeApp/src/commonMain/composeResources/values/strings.xml
@@ -775,4 +775,8 @@
Sweep %1$s sats
Nobody runs its node, and its channels close only through it.
Hasn't answered the proposal yet. Their device may need an update that knows Lightning wallets.
+ The group's offer
+ Anyone can pay this offer, as often as they like, without asking for an invoice first. It pays the group's node, the one the group signed for.
+ Copy offer
+ Offer copied
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupIcebergTransport.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupIcebergTransport.kt
index 83b0f70e..c1e6fdc2 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupIcebergTransport.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupIcebergTransport.kt
@@ -24,6 +24,7 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
+import kotlinx.coroutines.withTimeoutOrNull
import kotlin.time.Clock
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
@@ -128,6 +129,24 @@ class GroupIcebergTransport private constructor(
reload()
}
+ /**
+ * Waits until round one is in hand for the next [counters] pool counters, reloading as batches land,
+ * for at most [timeout]. False when the group has not sent enough: a node that connected now could be
+ * asked to sign before it could.
+ */
+ suspend fun awaitPool(counters: Int, timeout: kotlin.time.Duration): Boolean {
+ if (counters <= 0) return true
+ val ready = { (nextCounter until nextCounter + counters).all { it in pool } }
+ return withTimeoutOrNull(timeout) {
+ while (true) {
+ reload()
+ if (ready()) return@withTimeoutOrNull true
+ delay(POLL)
+ }
+ @Suppress("UNREACHABLE_CODE") false
+ } ?: false
+ }
+
override fun contributions(label: ByteVector32): List? = countersByLabel[label]?.let { pool[it] }
override fun verificationLabel(id: FundingSigner.VerificationNonceId): ByteVector32 =
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
index 838a3470..4f302dd4 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningNode.kt
@@ -4,6 +4,7 @@ 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.nostr.lightning.GroupLightningAuthorisationEvent
+import com.machankura.bennu.compose.nostr.lightning.GroupLightningWalletStatementEvent
import com.machankura.bennu.compose.wallet.GroupChainClients
import com.machankura.bennu.compose.wallet.lightning.GroupNodeKeyManager
import com.machankura.bennu.compose.wallet.lightning.GroupSweep
@@ -22,9 +23,11 @@ import fr.acinq.lightning.MilliSatoshi
import fr.acinq.lightning.NodeParams
import fr.acinq.lightning.PaymentEvents
import fr.acinq.lightning.WalletParams
+import fr.acinq.lightning.blockchain.Feerates
import fr.acinq.lightning.blockchain.electrum.ElectrumWatcher
import fr.acinq.lightning.blockchain.fee.FeeratePerByte
import fr.acinq.lightning.blockchain.fee.FeeratePerKw
+import fr.acinq.lightning.blockchain.fee.OnChainFeerates
import fr.acinq.lightning.channel.ChannelCommand
import fr.acinq.lightning.channel.GroupHeldOutputs
import fr.acinq.lightning.channel.states.ChannelStateWithCommitments
@@ -41,6 +44,8 @@ import fr.acinq.lightning.io.TcpSocket
import fr.acinq.lightning.io.WrappedChannelCommand
import fr.acinq.lightning.logging.LoggerFactory
import fr.acinq.lightning.payment.Bolt11Invoice
+import fr.acinq.lightning.payment.LiquidityPolicy
+import fr.acinq.lightning.utils.msat
import kotlin.time.Clock
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
@@ -75,12 +80,22 @@ class GroupLightningNode(
private val now: () -> kotlin.time.Instant = { Clock.System.now() },
private val handoverCheck: Duration = HANDOVER_CHECK,
private val reportEvery: Duration = REPORT_EVERY,
+ /** How many pool counters must hold round one before the node connects; 0 for a test with no co-signers. */
+ private val minimumPool: Int = MINIMUM_POOL,
+ private val poolWait: Duration = POOL_WAIT,
) {
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)
+ class NodeConfiguration(
+ val keyManager: GroupNodeKeyManager,
+ val chain: Chain,
+ val lspNodeId: PublicKey,
+ val transport: GroupIcebergTransport,
+ /** The most the group agreed to pay the LSP for the liquidity a payment needs: its statement's policy. */
+ val maxLiquidityFee: Satoshi = Satoshi(GroupLightningWalletStatementEvent.Policy.DEFAULT.maxLiquidityFeeSat),
+ )
/** What this class needs of a running node. */
interface PeerHandle {
@@ -104,6 +119,8 @@ class GroupLightningNode(
suspend fun forceClose(channelId: String)
/** The outputs closing channels pay to the group's basepoints, for the group to sweep. */
fun heldOutputs(): List
+ /** The node's reusable Bolt12 offer, through the LSP: every member recomputes it from the seed. */
+ fun offer(): String?
}
sealed class State {
@@ -137,6 +154,12 @@ class GroupLightningNode(
val transport = GroupIcebergTransport.create(database, localChatRoom, userPublicKey, wallet, term, scope).also { it.start() }
transport.provision(GroupLightningCoSigner.POOL_WINDOW)
+ // Round one is served synchronously from the pool, so the pool has to be there before the LSP can
+ // ask for anything: a channel that needs a label the pool lacks is aborted.
+ if (!transport.awaitPool(minimumPool, poolWait)) {
+ transport.stop()
+ return State.Refused("the group has not sent enough round one to sign with yet").also { _state.value = it }
+ }
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(
@@ -147,7 +170,7 @@ class GroupLightningNode(
)
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))
+ val handle = peerFactory(NodeConfiguration(keyManager, chain, PublicKey.fromHex(wallet.statement.lspNodeId), transport, Satoshi(wallet.statement.policy.maxLiquidityFeeSat)))
this.transport = transport
peer = handle
_state.value = State.Running(term)
@@ -192,6 +215,7 @@ class GroupLightningNode(
channels = current.first, payments = current.second.takeLast(REPORTED_PAYMENTS),
assignments = transport?.assignments().orEmpty(),
heldOutputs = current.third,
+ offer = handle.offer(),
)
GroupLightningReports.publishSnapshot(database, localChatRoom, userPublicKey, snapshot)
lastReported = current
@@ -287,6 +311,15 @@ class GroupLightningNode(
/** 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
+ /** Pool counters with round one in hand before the node connects: enough to open a channel and pay. */
+ const val MINIMUM_POOL = 8
+ /** How long a starting node waits for them before refusing; it is tried again at the next refresh. */
+ val POOL_WAIT: Duration = 30.seconds
+
+ val FEERATES_REFRESH: Duration = 10.minutes
+ val FEERATES_RETRY: Duration = 30.seconds
+ private val REGTEST_FEERATES = FeeratePerByte(Satoshi(2)).let { Feerates(it, it, it, it, it) }
+
/** How stale a snapshot may grow while nothing changes. */
val REPORT_EVERY: Duration = 5.minutes
/** How many of the newest payments a snapshot carries; members keep every one they have seen. */
@@ -309,6 +342,17 @@ class GroupLightningNode(
features = base.features.copy(activated = base.features.activated + (Feature.SimpleTaprootChannels to FeatureSupport.Mandatory)),
zeroConfPeers = setOf(configuration.lspNodeId),
usePeerStorage = true,
+ // The group's own limit, not lightning-kmp's default of 2,000 sats: the statement it signed
+ // names what a channel opened on the fly may cost.
+ liquidityPolicy = MutableStateFlow(
+ LiquidityPolicy.Auto(
+ inboundLiquidityTarget = null,
+ maxAbsoluteFee = configuration.maxLiquidityFee,
+ maxRelativeFeeBasisPoints = 3_000,
+ skipAbsoluteFeeCheck = false,
+ maxAllowedFeeCredit = 0.msat,
+ )
+ ),
)
val walletParams = walletParamsFor(configuration.chain)
require(walletParams.trampolineNode.id == configuration.lspNodeId) { "the wallet's LSP is not the node it would connect to" }
@@ -316,6 +360,24 @@ class GroupLightningNode(
val watcher = ElectrumWatcher(client, scope, loggerFactory)
val databases = databasesFor(nodeParams.nodeId, configuration.chain)
val peer = Peer(nodeParams, walletParams, client, watcher, databases, TcpSocket.Builder(), scope)
+ // The peer learns the chain's height only from header notifications, and a shared client that
+ // subscribed long ago sends the next one at the next block: until then the node can answer no
+ // invoice request and take no payment. So it is told the current height as it starts.
+ scope.launch {
+ runCatching { peer.currentTipFlow.value = client.startHeaderSubscription().blockHeight }
+ }
+ // lightning-kmp asks for feerates once, as Electrum connects, which suits a phone app that runs
+ // for minutes. The operator's node runs for days, and without feerates it cannot close a channel
+ // at all -- a force close waits for them, silently. So it asks again, often while it has none.
+ // Regtest has nothing to estimate from; there it takes a flat rate.
+ scope.launch {
+ while (isActive) {
+ val feerates = runCatching { client.getFeerates() }.getOrNull()
+ ?: REGTEST_FEERATES.takeIf { configuration.chain == Chain.Regtest }
+ feerates?.let { peer.onChainFeeratesFlow.value = OnChainFeerates(it) }
+ delay(if (feerates == null) FEERATES_RETRY else FEERATES_REFRESH)
+ }
+ }
val payments = mutableListOf()
scope.launch {
nodeParams.nodeEvents.collect { event ->
@@ -376,6 +438,7 @@ class GroupLightningNode(
}
}
}.map(GroupSweep::inputOf).distinctBy { it.txid to it.index }
+ override fun offer(): String = nodeParams.defaultOffer(walletParams.trampolineNode.id).offer.encode()
override suspend fun forceClose(channelId: String) {
peer.send(WrappedChannelCommand(ByteVector32(channelId), ChannelCommand.Close.ForceClose))
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt
index bf45d67e..1af38996 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/managers/GroupLightningReports.kt
@@ -14,7 +14,10 @@ import com.machankura.bennu.compose.wallet.lightning.WalletWire
import com.vitorpamplona.quartz.nip01Core.core.Event
import com.vitorpamplona.quartz.nip01Core.core.HexKey
import com.vitorpamplona.quartz.utils.RandomInstance
+import fr.acinq.bitcoin.ByteVector
+import fr.acinq.bitcoin.PublicKey
import fr.acinq.lightning.payment.Bolt11Invoice
+import fr.acinq.lightning.payment.OfferManager
import kotlin.time.Instant
/**
@@ -59,7 +62,8 @@ object GroupLightningReports {
// anybody else is nobody's.
val operator = GroupLightningOperatorManager.ofTerm(database, localChatRoom.chatRoom.id, wallet.statement.chain, wallet.statement.wallet, snapshot.term)
if (operator?.publicKey != innerEvent.pubKey) return logger.w("Snapshot ${innerEvent.id} is not from the operator of term ${snapshot.term}")
- file(database, innerEvent.pubKey, snapshot)
+ // An offer is kept only if it is the one the group's node derives: the seed says which.
+ file(database, innerEvent.pubKey, snapshot.copy(offer = snapshot.offer?.takeIf { it == offerOf(wallet) }))
// The round-one labels the operator handed out, so whoever operates next signs under them.
val dao = database.icebergCoSigningDao()
snapshot.assignments.forEach { (purpose, counter) ->
@@ -70,6 +74,16 @@ object GroupLightningReports {
}
}
+ /**
+ * The Bolt12 offer the group's node publishes, recomputed from the node seed the way lightning-kmp
+ * derives it ([OfferManager.deterministicOffer]); null on a device that does not hold the seed.
+ */
+ fun offerOf(wallet: GroupLightningWalletManager.Wallet): String? {
+ val seed = wallet.seed ?: return null
+ val nodeKey = GroupLightningCoSigner.keyManagerOf(ByteVector(seed.seed), wallet.statement.chain).nodeKeys.nodeKey.privateKey
+ return OfferManager.deterministicOffer(wallet.statement.chain.chainHash, nodeKey, PublicKey.fromHex(wallet.statement.lspNodeId), null, null, null).offer.encode()
+ }
+
private suspend fun file(database: BennuDatabase, sentBy: HexKey, snapshot: WalletWire.Snapshot) {
val dao = database.groupLightningRecordsDao()
val held = dao.snapshot(snapshot.wallet)
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningReceiveScreen.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningReceiveScreen.kt
index 4cdfa04f..0340212b 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningReceiveScreen.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/composable/GroupLightningReceiveScreen.kt
@@ -17,6 +17,7 @@ import androidx.compose.material.icons.filled.Bolt
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
@@ -38,17 +39,21 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.lifecycle.viewmodel.compose.viewModel
import bennu.composeapp.generated.resources.Res
import bennu.composeapp.generated.resources.amount_in_sats
+import bennu.composeapp.generated.resources.anyone_can_pay_this_offer
import bennu.composeapp.generated.resources.ask_for_an_invoice
import bennu.composeapp.generated.resources.copy_invoice
+import bennu.composeapp.generated.resources.copy_offer
import bennu.composeapp.generated.resources.couldn_t_ask_for_an_invoice
import bennu.composeapp.generated.resources.invoice_copied
import bennu.composeapp.generated.resources.leave_the_amount_empty_to_let_the_payer_choose
import bennu.composeapp.generated.resources.nobody_runs_this_wallet_to_make_an_invoice
+import bennu.composeapp.generated.resources.offer_copied
import bennu.composeapp.generated.resources.receive
import bennu.composeapp.generated.resources.sats
import bennu.composeapp.generated.resources.sats_are_whole_numbers
import bennu.composeapp.generated.resources.that_is_more_sats_than_there_will_ever_be
import bennu.composeapp.generated.resources.that_isn_t_an_amount_in_sats
+import bennu.composeapp.generated.resources.the_group_s_offer
import bennu.composeapp.generated.resources.this_invoice_pays_the_group_s_node
import bennu.composeapp.generated.resources.waiting_for_the_operator_s_device
import bennu.composeapp.generated.resources.what_it_is_for
@@ -95,6 +100,7 @@ fun GroupLightningReceiveScreen(
val notify = rememberNotifier(rememberCoroutineScope())
val couldNotAsk = stringResource(Res.string.couldn_t_ask_for_an_invoice)
val copied = stringResource(Res.string.invoice_copied)
+ val offerCopied = stringResource(Res.string.offer_copied)
val clipboardManager = LocalClipboardManager.current
Scaffold(
@@ -155,6 +161,21 @@ fun GroupLightningReceiveScreen(
Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
Text(stringResource(Res.string.ask_for_an_invoice))
}
+ // The offer needs no operator online to ask: the node answers payers itself.
+ state.offer?.let { offer ->
+ HorizontalDivider()
+ Text(stringResource(Res.string.the_group_s_offer), style = MaterialTheme.typography.titleSmall)
+ Text(stringResource(Res.string.anyone_can_pay_this_offer), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
+ SelectionContainer { Text(offer, style = MaterialTheme.typography.bodySmall, maxLines = 3, overflow = TextOverflow.Ellipsis) }
+ TextButton(onClick = {
+ clipboardManager.setText(buildAnnotatedString { append(offer) })
+ notify(offerCopied)
+ }) {
+ Icon(Icons.Default.ContentCopy, contentDescription = Decorative)
+ Spacer(modifier = Modifier.width(MaterialTheme.spacing.relatedGap))
+ Text(stringResource(Res.string.copy_offer))
+ }
+ }
}
}
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 e5cb3e53..59aaa43b 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
@@ -51,7 +51,7 @@ class GroupLightningReceiveViewModel(
?: 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, wallet.statement.wallet)?.publicKey == null) GroupLightningReceiveUIState.Unavailable
- else GroupLightningReceiveUIState.Form(localChatRoom, wallet)
+ else GroupLightningReceiveUIState.Form(localChatRoom, wallet, lightningRepository.observeReport(chatRoomId, chain, wallet.statement.wallet).first()?.snapshot?.offer)
}
}
diff --git a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningReceiveUIState.kt b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningReceiveUIState.kt
index a19c7fd5..75de1945 100644
--- a/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningReceiveUIState.kt
+++ b/composeApp/src/commonMain/kotlin/com/machankura/bennu/compose/ui/view/state/GroupLightningReceiveUIState.kt
@@ -12,7 +12,8 @@ sealed class GroupLightningReceiveUIState {
/** No wallet, or no operator to run its node. */
data object Unavailable : GroupLightningReceiveUIState()
- data class Form(val localChatRoom: LocalChatRoom, val wallet: GroupLightningWalletManager.Wallet) : GroupLightningReceiveUIState()
+ /** [offer] is the group node's reusable Bolt12 offer, once a snapshot carried one this device checked. */
+ data class Form(val localChatRoom: LocalChatRoom, val wallet: GroupLightningWalletManager.Wallet, val offer: String? = null) : GroupLightningReceiveUIState()
data class Waiting(val requestId: String) : GroupLightningReceiveUIState()
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 71b5ad68..c95052c9 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
@@ -35,6 +35,7 @@ class GroupLightningNodes(
private val scope: CoroutineScope,
private val peerFactory: suspend (GroupLightningNode.NodeConfiguration) -> GroupLightningNode.PeerHandle,
private val chain: Chain = GroupLightningRollout.NETWORK,
+ private val minimumPool: Int = GroupLightningNode.MINIMUM_POOL,
) {
private val logger = Logger.withTag("GroupLightningNodes")
private val mutex = Mutex()
@@ -66,7 +67,7 @@ class GroupLightningNodes(
nodes.remove(key)
continue
}
- val node = existing ?: GroupLightningNode(database, localChatRoom, userPublicKey, wallet, scope, peerFactory).also { nodes[key] = it }
+ val node = existing ?: GroupLightningNode(database, localChatRoom, userPublicKey, wallet, scope, peerFactory, minimumPool = minimumPool).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}")
}
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/FakeGroupNode.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/FakeGroupNode.kt
index 045dfd14..42a4e687 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/FakeGroupNode.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/FakeGroupNode.kt
@@ -11,6 +11,7 @@ import fr.acinq.lightning.Features
import fr.acinq.lightning.Lightning.randomBytes32
import fr.acinq.lightning.MilliSatoshi
import fr.acinq.lightning.payment.Bolt11Invoice
+import fr.acinq.lightning.payment.OfferManager
/**
* A stand-in for the group's lightning-kmp node: no LSP to connect to, channels and payments as a test
@@ -44,6 +45,8 @@ class FakeGroupNode(private val configuration: GroupLightningNode.NodeConfigurat
override suspend fun close(channelId: String, scriptPubKey: ByteVector) { closed += channelId to scriptPubKey }
override suspend fun forceClose(channelId: String) { forceClosed += channelId }
override fun heldOutputs(): List = heldOutputs
+ override fun offer(): String =
+ OfferManager.deterministicOffer(configuration.chain.chainHash, configuration.keyManager.nodeKeys.nodeKey.privateKey, configuration.lspNodeId, null, null, null).offer.encode()
override suspend fun hasPaid(paymentHash: String): Boolean = payments.any { !it.incoming && it.paymentHash == paymentHash }
override suspend fun pay(bolt11: String, amountMsat: Long): WalletWire.PaymentView {
paid += bolt11 to amountMsat
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
index a90bb874..309493ea 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningNodeJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningNodeJvmTest.kt
@@ -76,6 +76,7 @@ class GroupLightningNodeJvmTest {
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,
+ minimumPool = 0,
)
@Test
@@ -131,8 +132,8 @@ class GroupLightningNodeJvmTest {
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)
+ val operatorNodes = GroupLightningNodes(all[3].db, all[3].publicKey, scope, factory, fixture.chain, minimumPool = 0)
+ val otherNodes = GroupLightningNodes(all[0].db, all[0].publicKey, scope, factory, fixture.chain, minimumPool = 0)
operatorNodes.refresh()
otherNodes.refresh()
assertIs(operatorNodes.nodeFor(fixture.roomId)?.state?.value)
@@ -141,4 +142,18 @@ class GroupLightningNodeJvmTest {
assertTrue(peers.single().disconnected)
assertTrue(1.minutes > 0.seconds)
}
+
+ @Test
+ fun `a node does not connect before the group has sent round one`() = runBlocking {
+ val all = ready()
+ elect(all, all[1])
+ heardFromRoom(all[1])
+ // Nobody answers the provision request here, so the pool never fills.
+ val node = GroupLightningNode(
+ all[1].db, all[1].room, all[1].publicKey, GroupLightningWalletManager.walletFor(all[1].db, fixture.roomId, fixture.chain)!!, scope, factory,
+ minimumPool = 4, poolWait = 1.seconds,
+ )
+ assertIs(node.start())
+ assertTrue(peers.isEmpty(), "it never connected")
+ }
}
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 1b5d5ed9..1465c7eb 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
@@ -130,6 +130,7 @@ class GroupLightningPaymentsJvmTest {
operator.db, operator.room, operator.publicKey, GroupLightningWalletManager.walletFor(operator.db, fixture.roomId, fixture.chain)!!, scope,
{ configuration -> FakeGroupNode(configuration).also { nodes += it } },
handoverCheck = 10.minutes,
+ minimumPool = 0,
)
assertIs(node.start())
node.payAuthorised()
@@ -156,6 +157,7 @@ class GroupLightningPaymentsJvmTest {
operator.db, operator.room, operator.publicKey, GroupLightningWalletManager.walletFor(operator.db, fixture.roomId, fixture.chain)!!, scope,
{ configuration -> FakeGroupNode(configuration).also { nodes += it } },
handoverCheck = 10.minutes,
+ minimumPool = 0,
)
assertIs(node.start())
val one = "c1".repeat(32)
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningRegtestJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningRegtestJvmTest.kt
new file mode 100644
index 00000000..d157e991
--- /dev/null
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningRegtestJvmTest.kt
@@ -0,0 +1,297 @@
+package com.machankura.bennu.compose.managers
+
+import co.touchlab.kermit.Severity
+import co.touchlab.kermit.StaticConfig
+import co.touchlab.kermit.platformLogWriter
+import com.machankura.bennu.compose.database.model.MarmotGroupEvent
+import com.machankura.bennu.compose.database.model.NostrEvent
+import com.machankura.bennu.compose.nostr.frost.FrostSigningEvents
+import com.machankura.bennu.compose.nostr.lightning.GroupLightningEvents
+import com.machankura.bennu.compose.wallet.GroupChainClients
+import com.machankura.bennu.compose.wallet.GroupTransactionWatcher
+import fr.acinq.bitcoin.Bitcoin
+import fr.acinq.bitcoin.Chain
+import fr.acinq.bitcoin.PublicKey
+import fr.acinq.lightning.Lightning.randomBytes32
+import fr.acinq.lightning.NodeUri
+import fr.acinq.lightning.blockchain.electrum.ElectrumClient
+import fr.acinq.lightning.io.TcpSocket
+import fr.acinq.lightning.logging.LoggerFactory
+import fr.acinq.lightning.payment.Bolt11Invoice
+import fr.acinq.lightning.utils.ServerAddress
+import fr.acinq.phoenix.db.createChannelsDbDriver
+import fr.acinq.phoenix.db.createPaymentsDbDriver
+import fr.acinq.phoenix.db.createSqliteChannelsDb
+import fr.acinq.phoenix.db.createSqlitePaymentsDb
+import fr.acinq.phoenix.managers.PhoenixDatabases
+import fr.acinq.phoenix.utils.PlatformContext
+import fr.acinq.phoenixd.conf.LSP
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withTimeout
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.jsonArray
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.long
+import org.junit.Assume.assumeTrue
+import java.net.URI
+import java.net.URLEncoder
+import java.net.http.HttpClient
+import java.net.http.HttpRequest
+import java.net.http.HttpResponse
+import java.nio.file.Files
+import java.util.Base64
+import kotlin.test.AfterTest
+import kotlin.test.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertIs
+import kotlin.test.assertNotNull
+import kotlin.test.assertTrue
+import kotlin.time.Clock
+import kotlin.time.Duration
+import kotlin.time.Duration.Companion.minutes
+import kotlin.time.Duration.Companion.seconds
+
+/**
+ * The group Lightning wallet end to end, on the regtest network `testing/regtest/regtest.sh up` builds:
+ * four devices make the key and open the wallet, the operator's device runs a real lightning-kmp node
+ * against an eclair LSP, and the group receives, pays, closes and sweeps
+ * (`docs/group-lightning-wallet.md`, "The regtest run").
+ *
+ * Every message between the devices goes through the same managers the inbound path uses, pumped in the
+ * background; the node's signatures are the group's, made by Iceberg co-signing in the room.
+ *
+ * Skipped unless `BENNU_REGTEST=1`, because it needs the docker network.
+ */
+class GroupLightningRegtestJvmTest {
+ private val enabled = System.getenv("BENNU_REGTEST") == "1"
+ private val fixture = GroupLightningFixture(chain = Chain.Regtest)
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ private val loggerFactory = LoggerFactory(StaticConfig(Severity.Info, listOf(platformLogWriter())))
+ private val http = HttpClient.newHttpClient()
+ private val json = Json { ignoreUnknownKeys = true }
+
+ @AfterTest
+ fun close() {
+ scope.cancel()
+ fixture.close()
+ }
+
+ // --- the network ------------------------------------------------------------------------------
+
+ private fun post(url: String, auth: String, form: Map = emptyMap(), body: String? = null, contentType: String = "application/x-www-form-urlencoded"): JsonElement {
+ val payload = body ?: form.entries.joinToString("&") { (k, v) -> "$k=${URLEncoder.encode(v, Charsets.UTF_8)}" }
+ val request = HttpRequest.newBuilder(URI(url))
+ .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(auth.toByteArray()))
+ .header("Content-Type", contentType)
+ .POST(HttpRequest.BodyPublishers.ofString(payload))
+ .build()
+ val response = http.send(request, HttpResponse.BodyHandlers.ofString())
+ check(response.statusCode() in 200..299) { "$url ${form.keys}: ${response.statusCode()} ${response.body()}" }
+ return json.parseToJsonElement(response.body())
+ }
+
+ private fun lsp(method: String, form: Map = emptyMap()) = post("http://127.0.0.1:28080/$method", ":lsp", form)
+ private fun payer(method: String, form: Map = emptyMap()) = post("http://127.0.0.1:28081/$method", ":payer", form)
+
+ private fun btc(method: String, vararg params: Any, wallet: String? = null): JsonElement {
+ val args = params.joinToString(",") { if (it is String && !it.startsWith("[")) "\"$it\"" else it.toString() }
+ val response = post("http://127.0.0.1:28443/" + (wallet?.let { "wallet/$it" } ?: ""), "foo:bar", body = """{"jsonrpc":"1.0","id":1,"method":"$method","params":[$args]}""", contentType = "text/plain").jsonObject
+ check(response["error"].toString() == "null") { "bitcoind $method: ${response["error"]}" }
+ return response["result"]!!
+ }
+
+ private fun mine(blocks: Int = 1) {
+ btc("generatetoaddress", blocks, btc("getnewaddress", wallet = "miner").jsonPrimitive.content, wallet = "miner")
+ }
+
+ private fun mempoolSize(): Long = btc("getmempoolinfo").jsonObject["size"]!!.jsonPrimitive.long
+
+ /** What the onchain wallet's first receive address holds, confirmed, in sats. */
+ private fun receivedAtFirstAddress(): Long {
+ val address = Bitcoin.addressFromPublicKeyScript(Chain.Regtest.chainHash, GroupWalletDerivation.derive(fixture.account, GroupWalletDerivation.RECEIVE, 0).pubkeyScript.toByteArray()).right!!
+ val result = btc("scantxoutset", "start", "[\"addr($address)\"]").jsonObject
+ return (result["total_amount"]!!.jsonPrimitive.content.toBigDecimal() * 100_000_000.toBigDecimal()).toLong()
+ }
+
+ /** Waits for [condition], mining a block whenever the mempool holds something, so funding and closing confirm. */
+ private suspend fun mineUntil(what: String, timeout: Duration = 3.minutes, condition: suspend () -> T?): T = try {
+ withTimeout(timeout) {
+ var result = condition()
+ while (result == null) {
+ if (mempoolSize() > 0) mine(1)
+ delay(1.seconds)
+ result = condition()
+ }
+ result
+ }
+ } catch (e: Throwable) {
+ diagnose()
+ throw AssertionError("timed out waiting for $what", e)
+ }
+
+ /** What the run prints when it gets stuck: set once the group exists. */
+ private var diagnose: suspend () -> Unit = {}
+
+ // --- the group ----------------------------------------------------------------------------------
+
+ private val pumping = Mutex()
+
+ /** Delivers everything between the devices, as the inbound path would, until the test ends. */
+ private fun pumpInBackground(all: List) {
+ val base = fixture.dispatch
+ fixture.dispatch = { to, event ->
+ base(to, event)
+ if (event.kind in GroupLightningEvents.CO_SIGNING) GroupLightningCoSigner.process(to.db, to.room, event, to.publicKey)
+ }
+ val kinds = FrostSigningEvents.ALL + GroupLightningEvents.ALL
+ scope.launch {
+ while (isActive) {
+ runCatching { pumping.withLock { fixture.pump(all, kinds) } }.onFailure { println("pump: $it") }
+ delay(100)
+ }
+ }
+ }
+
+ private suspend fun signed(all: List, proposer: GroupLightningFixture.Device, sessionId: String) =
+ pumping.withLock { fixture.signSession(all, proposer, sessionId) }
+
+ 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()))
+ }
+
+ private val key = GroupLightningCoSigner.walletKey(fixture.roomId, Chain.Regtest, 0)
+ private suspend fun report(device: GroupLightningFixture.Device) = GroupLightningReports.latest(device.db, key)
+
+ /**
+ * The payer pays the group [sats], and the channel the LSP opens on the fly for it confirms. It pays the
+ * offer a member's snapshot carries rather than a Bolt11 invoice: an invoice reaches the group's node
+ * through a route hint naming it by a peer-id short channel id, which ACINQ's LSP resolves and public
+ * eclair does not, while an offer's blinded path names the node as a wallet, which eclair funds.
+ */
+ private suspend fun receive(all: List, sats: Long) {
+ val offer = mineUntil("a member's copy of the group's offer", 1.minutes) { report(all[3])?.snapshot?.offer }
+ val paid = payer("payoffer", mapOf("offer" to offer, "amountMsat" to (sats * 1000).toString()))
+ val paymentId = (paid as? JsonObject)?.get("paymentId")?.jsonPrimitive?.content ?: paid.jsonPrimitive.content
+ mineUntil("the payer's payment of $sats sats") {
+ val sent = payer("getsentinfo", mapOf("id" to paymentId)).jsonArray
+ val status = sent.lastOrNull()?.jsonObject?.get("status")?.jsonObject?.get("type")?.jsonPrimitive?.content
+ check(status != "failed") { "the payment failed: $sent" }
+ status?.takeIf { it == "sent" }
+ }
+ }
+
+ @Test
+ fun `four devices open, receive, pay, close and sweep on regtest`() = runBlocking {
+ assumeTrue("set BENNU_REGTEST=1 with testing/regtest up", enabled)
+ val lspId = lsp("getinfo").jsonObject["nodeId"]!!.jsonPrimitive.content
+
+ // Open: the onchain wallet, the key, the Lightning wallet, and its operator.
+ 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, Chain.Regtest, lspId).id)
+ fixture.signSession(all, all[1], GroupLightningOperatorManager.nominateSelf(all[1].db, all[1].room, all[1].publicKey, Chain.Regtest).id)
+ val operator = all[1]
+ val wallet = GroupLightningWalletManager.walletFor(operator.db, fixture.roomId, Chain.Regtest)!!
+ pumpInBackground(all)
+ diagnose = {
+ val dao = operator.db.icebergCoSigningDao()
+ dao.assignments(key).forEach { println("REGTEST assigned ${it.counter} ${it.label.take(16)} ${it.purpose}") }
+ for (c in 0L..6L) println("REGTEST pool $c: ${dao.noncesFor(key, c).size} rows, label ${GroupLightningCoSigner.poolLabel(wallet.statement.icebergKey, c).toHex().take(16)}")
+ }
+
+ val electrum = ElectrumClient(scope, loggerFactory)
+ assertTrue(electrum.connect(ServerAddress("127.0.0.1", 28001, TcpSocket.TLS.DISABLED), TcpSocket.Builder()), "electrs is reachable")
+ val clients = GroupChainClients.single(electrum)
+ val ctx = PlatformContext(Files.createTempDirectory("bennu-regtest").toFile())
+ val walletParams = LSP.from(Chain.Testnet3).walletParams.copy(trampolineNode = NodeUri(PublicKey.fromHex(lspId), "127.0.0.1", 29735))
+ val handles = mutableListOf()
+ val real = GroupLightningNode.lightningKmpPeers(
+ clients = clients,
+ databasesFor = { nodeId, chain ->
+ PhoenixDatabases(
+ channels = createSqliteChannelsDb(createChannelsDbDriver(ctx, "group-channels-$nodeId-${chain.name}.sqlite")),
+ payments = createSqlitePaymentsDb(createPaymentsDbDriver(ctx, "group-payments-$nodeId-${chain.name}.sqlite") {}, null, loggerFactory),
+ cloudKit = null,
+ )
+ },
+ walletParamsFor = { walletParams },
+ loggerFactory = loggerFactory,
+ scope = scope,
+ )
+ heardFromRoom(operator)
+ val node = GroupLightningNode(operator.db, operator.room, operator.publicKey, wallet, scope, { c -> real(c).also { handles += it } }, handoverCheck = 1.seconds, reportEvery = 5.seconds)
+ assertIs(node.start())
+ mineUntil("the LSP to see the group's node", 1.minutes) {
+ lsp("peers").jsonArray.firstOrNull { it.jsonObject["nodeId"]?.jsonPrimitive?.content == wallet.statement.nodeId && it.jsonObject["state"]?.jsonPrimitive?.content == "CONNECTED" }
+ }
+
+ // Receive: a member's Bolt11 request comes back as an invoice for the group's node...
+ val requestId = GroupLightningReports.requestInvoice(all[3].db, all[3].room, all[3].publicKey, wallet, 100_000_000, "first")
+ val invoice = Bolt11Invoice.read(mineUntil("the operator's invoice", 1.minutes) { all[3].db.groupLightningRecordsDao().invoice(key, requestId)?.bolt11 }).get()
+ assertEquals(wallet.statement.nodeId, invoice.nodeId.toString())
+ // ...and the first payment, to the group's offer, opens the channel on the fly.
+ receive(all, 100_000)
+ val received = mineUntil("every member's snapshot of the channel") {
+ all.map { report(it) }.takeIf { reports -> reports.all { it?.snapshot?.channels?.singleOrNull()?.state == "Normal" && it.snapshot.payments.any { p -> p.incoming && p.succeeded } } }
+ }
+ val channel = received.first()!!.snapshot.channels.single()
+ println("REGTEST received: channel ${channel.channelId.take(16)} capacity ${channel.capacitySat}, ours ${channel.oursMsat} msat")
+ assertTrue(channel.oursMsat in 90_000_000..100_000_000, "the group holds the payment, less the LSP's fee: ${channel.oursMsat}")
+ assertTrue(received.count { it!!.checks.single().agrees == true } >= 2, "the members who co-signed agree with the operator")
+
+ // Pay: the group authorises paying the payer, and the operator's node pays it.
+ val owed = payer("createinvoice", mapOf("description" to "back", "amountMsat" to "20000000")).jsonObject
+ val pay = GroupLightningAuthorisations.prepare(wallet, owed["serialized"]!!.jsonPrimitive.content, null, 2_000_000).getOrThrow()
+ signed(all, all[2], GroupLightningAuthorisations.propose(all[2].db, all[2].room, all[2].publicKey, pay).id)
+ mineUntil("the payer to receive 20,000 sats") {
+ payer("getreceivedinfo", mapOf("paymentHash" to pay.paymentHash)).jsonObject["status"]?.jsonObject?.get("type")?.jsonPrimitive?.content?.takeIf { it == "received" }
+ }
+ val paid = mineUntil("the snapshot to show the payment") { report(all[0])?.takeIf { r -> r.snapshot.payments.any { !it.incoming && it.succeeded } } }
+ println("REGTEST paid: ours now ${paid.snapshot.channels.single().oursMsat} msat")
+
+ // Close: mutually, to the onchain wallet.
+ val before = receivedAtFirstAddress()
+ signed(all, all[0], GroupLightningAuthorisations.proposeChannelAction(all[0].db, all[0].room, all[0].publicKey, wallet, channel.channelId, force = false).id)
+ val closedTo = mineUntil("the close to reach the onchain wallet") { receivedAtFirstAddress().takeIf { it > before } }
+ println("REGTEST closed: ${closedTo - before} sats at the onchain wallet's first address")
+ assertTrue(closedTo - before > 70_000, "the group's balance reached its onchain wallet")
+
+ // Sweep: a second channel, force-closed, whose delayed output the group sweeps.
+ receive(all, 100_000)
+ val second = mineUntil("the second channel") {
+ report(all[0])?.snapshot?.channels?.firstOrNull { it.channelId != channel.channelId && it.state == "Normal" }
+ }
+ signed(all, all[3], GroupLightningAuthorisations.proposeChannelAction(all[3].db, all[3].room, all[3].publicKey, wallet, second.channelId, force = true).id)
+ val held = mineUntil("the force close's delayed output") { report(all[3])?.snapshot?.heldOutputs?.takeIf { it.isNotEmpty() } }
+ println("REGTEST force-closed: ${held.size} output(s) to sweep, after ${held.map { it.csvDelay }} blocks")
+ mine(held.maxOf { it.csvDelay }.toInt() + 1)
+ val beforeSweep = receivedAtFirstAddress()
+ val sweeper = all[3]
+ signed(all, sweeper, GroupLightningSweeps.propose(sweeper.db, sweeper.room, sweeper.publicKey, wallet, GroupLightningSweeps.unswept(sweeper.db, fixture.roomId, report(sweeper))).id)
+ val watcher = GroupTransactionWatcher(sweeper.db, clients, scope)
+ val swept = mineUntil("the sweep to confirm") {
+ watcher.pass()
+ receivedAtFirstAddress().takeIf { it > beforeSweep }
+ }
+ println("REGTEST swept: ${swept - beforeSweep} sats into the onchain wallet")
+ assertTrue(swept - beforeSweep > 70_000, "the sweep paid the onchain wallet")
+ assertNotNull(sweeper.db.groupTransactionDao().getByChatRoomId(fixture.roomId).firstOrNull { it.confirmedAt != null || it.seenAt != null })
+ assertEquals(1, held.size)
+ node.stop()
+ }
+}
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
index 0444acae..877faaee 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningRekeyJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningRekeyJvmTest.kt
@@ -90,8 +90,8 @@ class GroupLightningRekeyJvmTest {
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)
+ val oldOperator = GroupLightningNodes(remaining[1].db, remaining[1].publicKey, scope, factory, fixture.chain, minimumPool = 0)
+ val newOperator = GroupLightningNodes(remaining[2].db, remaining[2].publicKey, scope, factory, fixture.chain, minimumPool = 0)
oldOperator.refresh()
newOperator.refresh()
assertIs(oldOperator.nodeFor(fixture.roomId, 0)?.state?.value)
diff --git a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningReportsJvmTest.kt b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningReportsJvmTest.kt
index 7443cf71..6899442e 100644
--- a/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningReportsJvmTest.kt
+++ b/composeApp/src/jvmTest/kotlin/com/machankura/bennu/compose/managers/GroupLightningReportsJvmTest.kt
@@ -12,10 +12,12 @@ import com.vitorpamplona.quartz.nip01Core.core.toHexKey
import com.vitorpamplona.quartz.nip01Core.crypto.KeyPair
import fr.acinq.bitcoin.ByteVector
import fr.acinq.bitcoin.PrivateKey
+import fr.acinq.bitcoin.PublicKey
import fr.acinq.bitcoin.utils.Either
import fr.acinq.lightning.CltvExpiryDelta
import fr.acinq.lightning.Lightning.randomBytes32
import fr.acinq.lightning.payment.Bolt11Invoice
+import fr.acinq.lightning.payment.OfferManager
import fr.acinq.lightning.utils.msat
import kotlin.test.AfterTest
import kotlin.test.Test
@@ -70,6 +72,7 @@ class GroupLightningReportsJvmTest {
{ configuration -> FakeGroupNode(configuration).also { nodes += it } },
// The tests drive reporting themselves.
handoverCheck = 10.minutes,
+ minimumPool = 0,
)
assertIs(node.start())
return all to node
@@ -176,4 +179,18 @@ class GroupLightningReportsJvmTest {
assertNull(all[3].db.groupLightningRecordsDao().invoice(key, "not-the-operator"), "an invoice from a member who is not the operator")
assertNotNull(all[3].db.groupLightningRecordsDao().invoice(key, "good"))
}
+
+ @Test
+ fun `the node's offer reaches every member, and only the one its seed derives is kept`() = runBlocking {
+ val (all, _) = running()
+ fixture.pump(all, setOf(GroupLightningEvents.SNAPSHOT))
+ val wallet = GroupLightningWalletManager.walletFor(all[3].db, fixture.roomId, fixture.chain)!!
+ val expected = GroupLightningReports.offerOf(wallet)
+ all.forEach { assertEquals(expected, GroupLightningReports.latest(it.db, key)!!.snapshot.offer, "device ${it.index}") }
+
+ val someoneElse = OfferManager.deterministicOffer(fixture.chain.chainHash, PrivateKey(randomBytes32()), PublicKey.fromHex(lsp), null, null, null).offer.encode()
+ val lying = WalletWire.Snapshot(key, 1, wallet.statement.nodeId, Clock.System.now().epochSeconds + 60, emptyList(), emptyList(), offer = someoneElse)
+ GroupLightningReports.process(all[3].db, all[3].room, snapshotEvent(all[1], lying))
+ assertNull(GroupLightningReports.latest(all[3].db, key)!!.snapshot.offer, "an offer that pays some other node is dropped")
+ }
}
diff --git a/docs/group-lightning-wallet.md b/docs/group-lightning-wallet.md
index 4f3e9da3..2ab41808 100644
--- a/docs/group-lightning-wallet.md
+++ b/docs/group-lightning-wallet.md
@@ -29,7 +29,7 @@ build chose differently, this table says so.
| phase | state |
|---|---|
-| 0 | done, except the two spikes (see below) |
+| 0 | done, except the testnet3 spikes. The regtest run stands in for the second (a group node against an LSP); the first, how long the LSP waits for a signature, still needs testnet3 |
| 1 | done: `IcebergDkg`, 11 tests, among them a byte-for-byte match against the library's dealer and a signature from every 2-of-4 and 3-of-7 quorum |
| 2 | done, in the fork (`4bc973df`): the three signing methods suspend, `RemoteIcebergFundingSigner`, pings answered outside the channel loop. lightning-kmp's JVM suite, 985 tests, passes |
| 3 | done: in the fork (`e15e31ba`), `withGroupBasepoints`, `GroupHeldOutputs` and `KeyManager.defaultFinalScriptPubKey`, 991 tests passing. In the app, `GroupLightningDerivation`, pinned, with a FROST quorum spending `to_remote` and `to_local` |
@@ -43,7 +43,7 @@ build chose differently, this table says so.
| 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 |
-| 15 | the gates are in code and closed. `GroupLightningRollout.ENABLED` stays `false`: its own condition is a regtest end-to-end run, which has not been done (see Phase 0). Mainnet is refused by `GroupLightningRollout.allows`, whatever a screen offers. The ceremony screen names every participant who has not answered, with a word that their build may not know the new kinds |
+| 15 | the gates are in code and closed. `GroupLightningRollout.ENABLED` stays `false`. The JVM suite and the regtest run pass; what is left of its condition is Phase 0's testnet3 measurement of how long the LSP waits for a signature, and lifting it is a product decision either way. Mainnet is refused by `GroupLightningRollout.allows`, whatever a screen offers. The ceremony screen names every participant who has not answered, with a word that their build may not know the new kinds |
| what the plan said | what it turned out to be |
|---|---|
@@ -83,17 +83,17 @@ build chose differently, this table says so.
| 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 node does not connect while its pool is short | as written, after the regtest run showed why. It provisions the pool as it starts and waits, up to thirty seconds, until round one for `MINIMUM_POOL` counters is in hand (`GroupIcebergTransport.awaitPool`); otherwise it refuses to start and is tried again at the next refresh. The transport asks for more whenever fewer than a third of a window remain |
| 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 |
+| a test runs regtest end to end against the docker eclair | **run**, against eclair v0.14.4 as the LSP: see "The regtest run" below. It passes from a fresh network in about thirty seconds |
| a snapshot is signed by the operator's nostr key | it is an ordinary inner event, so MLS already says who sent it. A member believes it only from the operator the group elected for the term it names (`GroupLightningOperatorManager.ofTerm`), about the node the statement names; an earlier term's snapshot is still filed, as the truth about that term |
| a member compares the operator's balance with what the co-signers last signed | each member compares it with what *its own* device last signed for that channel: our balance in the last counterparty commitment its ledger holds. The figures can differ while a payment is in flight, because the snapshot reports the operator's own commitment and the ledger the counterparty's. The screen shows a mismatch, and nothing acts on it |
| the snapshot carries the pool for handover | it carries the label *assignments*. The contributions are already in every member's database as nonce batches, so the next operator's transport loads the pool itself. A member files each assignment it has not seen, so the next operator signs a force close under the verification nonce this one published |
| payments come from lightning-kmp's payments database | from `nodeParams.nodeEvents`, as they happen while the node runs, because the database has no query for all payments. Members keep every payment a snapshot carried, so a restart only loses what a stopped node would not have reported anyway |
| the operator's node answers an invoice request as it arrives | it reads the room's unanswered requests each time it checks for a handover, because the inbound path has no handle on a running node. An invoice therefore takes up to `HANDOVER_CHECK`, ten seconds, plus the room's own delay. A request whose answer is lost is answered again by the next operator, since the answer is what marks it answered |
-| an optional Bolt12 offer, from `nodeParams.defaultOffer` | **not built.** An offer is long-lived and pays whichever node holds its key; a group whose operator changes needs every member to know the offer still reaches the group's node, and that is the same check as a Bolt11 invoice's, made once. It is a small follow-up once a node has run on testnet3 |
+| an optional Bolt12 offer, from `nodeParams.defaultOffer` | built, because the regtest run needed it. The snapshot carries the node's default offer, and a member keeps it only if it is the offer its own copy of the seed derives (`GroupLightningReports.offerOf`), so the check needs no operator to be trusted. The receive screen shows it beside the invoice request. The offer does not change when the operator does: every operator runs the same node |
| each co-signer has a budget until the payment settles, fails or expires | an authorisation's budget lasts as long as the authorisation, and its *expiry* only closes it to new HTLCs (`CoSignerPolicy`'s `closed`). An HTLC that left before the expiry and settles after it still has to be explained, and dropping the budget at expiry would leave the co-signers refusing the commitment that settles it. A failed HTLC spends nothing, so the budget is still there; a second attempt needs nothing new from the group, only the node to try again |
| the operator's node pays an authorisation once | once per payment hash, ever: a node that tried and failed does not try again by itself. The member who wants another attempt asks the group again, and the co-signers' budgets are what keep two attempts from both paying |
| a fee cap per payment | the fee is not passed to lightning-kmp, whose `payInvoice` takes the trampoline fees from the LSP's wallet parameters. The cap is the co-signers': an HTLC worth more than the amount and the fee cap is over budget, so its commitment is never signed |
@@ -133,6 +133,53 @@ payments.
---
+## The regtest run
+
+`testing/regtest/` builds a network on one machine: bitcoind 31.1, electrs 0.11.1, an eclair
+v0.14.4 LSP and a second eclair, the payer, with a channel to the LSP. `GroupLightningRegtestJvmTest`
+then drives four devices through everything a group does with its wallet, against a real lightning-kmp
+node:
+
+```bash
+testing/regtest/regtest.sh up
+```
+
+```bash
+BENNU_REGTEST=1 ./gradlew :composeApp:jvmTest --tests '*GroupLightningRegtestJvmTest'
+```
+
+| step | what happens | result |
+|---|---|---|
+| open | the four make the onchain wallet, the Iceberg key, the Lightning wallet and its operator; the operator's device starts the node | the node connects with Phoenix's taproot channels |
+| receive | the payer pays the group's offer; the LSP proposes on-the-fly funding, the node opens the channel, every member checks and co-signs the first commitment | 100,000 sats received, 96,900 held after the LSP's 3,100 fee; every member's snapshot shows it, and the members who co-signed agree with the operator |
+| pay | a member proposes paying the payer's invoice, the group signs it, the node pays through the LSP's trampoline; the co-signers let the HTLC through against the authorisation | 20,000 sats arrive, with an 84-sat fee |
+| close | the group authorises a mutual close | the whole balance reaches the onchain wallet's first address |
+| sweep | a second payment opens a second channel; the group authorises a force close; the snapshot lists the delayed output; once 144 blocks pass a member proposes the sweep, the group signs it as a FROST script-path spend, and the watcher sends it | 96,624 sats reach the onchain wallet |
+
+What the run found, all fixed in the same commit:
+
+| found | why it mattered | fix |
+|---|---|---|
+| the node learned the chain's height only at the next block | lightning-kmp reads it from header notifications, and a shared Electrum client sends the next one at the next block. Until then the node could answer no invoice request and take no payment | `lightningKmpPeers` asks for the height as the node starts |
+| the node refused every on-the-fly channel | lightning-kmp's default liquidity policy caps the fee at 2,000 sats, and the statement's `maxLiquidityFeeSat`, which the group signs, was never handed to the node | the node's policy is the statement's |
+| a channel could ask for round one the pool did not hold yet | the transport reloads its pool every two seconds, and the first open came sooner | the node waits for a minimum pool before it connects |
+| a force close waited forever | lightning-kmp fetches feerates once, as Electrum connects, and a force close waits for them; on regtest there are none, and on a long-running node they go stale | the node asks for feerates every ten minutes, every thirty seconds while it has none, and takes a flat rate on regtest only |
+| public eclair cannot route a Bolt11 payment to a wallet | the invoice's route hint names the wallet by a peer-id short channel id, which ACINQ's LSP resolves and public eclair does not | the run's payer pays the group's Bolt12 offer, whose blinded path names the wallet; the offer is now part of the wallet (Phase 11's row above). The Bolt11 request and answer are still checked in the run |
+
+An eclair LSP for Phoenix's wallets needs settings its defaults leave off, all in
+`testing/regtest/lsp.conf`: `option_simple_taproot_phoenix` and `phoenix_zero_reserve` (the channel
+type includes both), `on_the_fly_funding` and `funding_fee_credit` with liquidity ads whose payment
+types include `from_future_htlc`, `peer-wake-up.enabled` (eclair delivers a wallet's messages and
+payments through it even when the wallet is connected), `min-private-funding-satoshis = 0` (an
+on-the-fly opener contributes nothing), `max-htlc-value-in-flight-percent = 100` (an on-the-fly
+channel is the size of the payment), and no `balance-thresholds` (or a channel the other side funded
+advertises a 1-msat maximum until its next update). `option_zeroconf` cannot be on for every peer, and
+does not need to be: eclair takes the wallet's early `channel_ready` when it is the only funder.
+
+What the run does not cover: the LSP's signing deadline (testnet3), more than one channel at a time,
+HTLC-transaction outputs (no HTLC was in flight at the force close), and the operator changing while a
+channel is open.
+
## What was asked, and what exists
| asked for | what exists | what is missing |
diff --git a/testing/regtest/README.md b/testing/regtest/README.md
new file mode 100644
index 00000000..72427797
--- /dev/null
+++ b/testing/regtest/README.md
@@ -0,0 +1,22 @@
+# Regtest network for the group Lightning wallet
+
+`regtest.sh up` builds it from nothing: bitcoind 31.1, electrs, an eclair LSP configured as a Phoenix
+LSP (`lsp.conf`), and a second eclair that pays the group and is paid by it (`payer.conf`), with a
+channel from the payer to the LSP. Every port is on localhost: bitcoind RPC 28443, electrs 28001, the
+LSP 29735 and its API 28080, the payer's API 28081.
+
+```bash
+./regtest.sh up
+```
+
+```bash
+BENNU_REGTEST=1 ../../gradlew -p ../.. :composeApp:jvmTest --tests '*GroupLightningRegtestJvmTest'
+```
+
+```bash
+./regtest.sh down
+```
+
+`./regtest.sh mine 6`, `./regtest.sh btc `, `./regtest.sh lsp -d k=v` and
+`./regtest.sh payer -d k=v` reach each piece by hand. What the run does, and what each LSP
+setting is for, is in `docs/group-lightning-wallet.md`, "The regtest run".
diff --git a/testing/regtest/compose.yml b/testing/regtest/compose.yml
new file mode 100644
index 00000000..e1db96d7
--- /dev/null
+++ b/testing/regtest/compose.yml
@@ -0,0 +1,66 @@
+# A regtest network for the group Lightning wallet's end-to-end run (docs/group-lightning-wallet.md,
+# "The regtest run"): bitcoind, electrs for the group's Electrum client, an eclair LSP speaking
+# Phoenix's taproot channels and on-the-fly funding, and a second eclair that pays the group and is
+# paid by it. Every port is bound to localhost, in a range nothing else on a development machine uses.
+name: bennu-regtest
+
+services:
+ bitcoind:
+ image: bitcoin/bitcoin:31.1
+ command:
+ - -printtoconsole
+ - -regtest=1
+ - -server=1
+ - -txindex=1
+ # foo:bar for eclair and the scripts; the cookie, readable by all, for electrs.
+ - -rpcauth=foo:abd66bf47451e26a7809d47370140dc9$$101b2636d908b296314aaad45c40bb42e0bbf631ea37b3f7767319e638e1662e
+ - -rpccookieperms=all
+ - -rpcallowip=0.0.0.0/0
+ - -rpcbind=0.0.0.0
+ - -fallbackfee=0.0002
+ - -listen=1
+ - -bind=0.0.0.0
+ - -zmqpubhashblock=tcp://0.0.0.0:29000
+ - -zmqpubrawtx=tcp://0.0.0.0:29001
+ volumes:
+ - bitcoind:/home/bitcoin/.bitcoin
+ ports:
+ - "127.0.0.1:28443:18443"
+
+ electrs:
+ image: getumbrel/electrs:v0.11.1
+ # bitcoind's data directory is its own; root is what reads the cookie in it.
+ user: root
+ command:
+ - --network=regtest
+ - --daemon-rpc-addr=bitcoind:18443
+ - --daemon-p2p-addr=bitcoind:18444
+ - --electrum-rpc-addr=0.0.0.0:50001
+ - --cookie-file=/bitcoin/regtest/.cookie
+ - --db-dir=/tmp/electrs
+ depends_on: [bitcoind]
+ volumes:
+ - bitcoind:/bitcoin:ro
+ ports:
+ - "127.0.0.1:28001:50001"
+
+ lsp:
+ image: acinq/eclair:v0.14.4
+ depends_on: [bitcoind]
+ volumes:
+ - ./lsp.conf:/data/eclair.conf:ro
+ ports:
+ - "127.0.0.1:29735:9735"
+ - "127.0.0.1:28080:8080"
+
+ payer:
+ image: acinq/eclair:v0.14.4
+ depends_on: [bitcoind]
+ volumes:
+ - ./payer.conf:/data/eclair.conf:ro
+ ports:
+ - "127.0.0.1:29736:9735"
+ - "127.0.0.1:28081:8080"
+
+volumes:
+ bitcoind:
diff --git a/testing/regtest/lsp.conf b/testing/regtest/lsp.conf
new file mode 100644
index 00000000..7e93d98c
--- /dev/null
+++ b/testing/regtest/lsp.conf
@@ -0,0 +1,64 @@
+// The LSP: what Phoenix's ACINQ node offers a wallet, as far as eclair's public features go. Not
+// zero-conf: eclair takes that only per peer, and the group's node id is not known until its wallet is
+// made, so the run mines the funding transaction instead.
+eclair {
+ chain = "regtest"
+ node-alias = "bennu-lsp"
+ server.binding-ip = "0.0.0.0"
+ api {
+ enabled = true
+ binding-ip = "0.0.0.0"
+ port = 8080
+ password = "lsp"
+ }
+ bitcoind {
+ host = "bitcoind"
+ rpcport = 18443
+ rpcuser = "foo"
+ rpcpassword = "bar"
+ wallet = "lsp"
+ zmqblock = "tcp://bitcoind:29000"
+ zmqtx = "tcp://bitcoind:29001"
+ }
+ trampoline-payments-enable = true
+ // Messages and payments to a wallet node go through eclair's wake-up path, even when it is connected.
+ peer-wake-up.enabled = true
+ features {
+ option_dual_fund = optional
+ option_splice = optional
+ option_quiesce = optional
+ option_simple_close = optional
+ option_simple_taproot_phoenix = optional
+ // part of the Phoenix taproot channel type
+ phoenix_zero_reserve = optional
+ option_provide_storage = optional
+ on_the_fly_funding = optional
+ funding_fee_credit = optional
+ trampoline_payment_prototype = optional
+ }
+ channel {
+ // Advertise the whole channel: eclair otherwise caps an update by the balance it had when it was made,
+ // which for a channel the other side funded is nothing, and refreshes it only now and then.
+ channel-update.balance-thresholds = []
+ // A wallet opening on the fly contributes nothing: the LSP funds the channel and is paid from the payment.
+ min-private-funding-satoshis = 0
+ // How long the group waits for its own output after a force close: short, so the run's sweep comes soon.
+ to-remote-delay-blocks = 144
+ // A channel opened on the fly is the size of the payment that opened it, so all of it is in flight at once.
+ max-htlc-value-in-flight-percent = 100
+ }
+ // On-the-fly funding sells the wallet the inbound liquidity a payment needs, paid from the payment.
+ liquidity-ads {
+ funding-rates = [
+ {
+ min-funding-amount-satoshis = 10000
+ max-funding-amount-satoshis = 10000000
+ funding-weight = 400
+ fee-base-satoshis = 100
+ fee-basis-points = 100
+ channel-creation-fee-satoshis = 1000
+ }
+ ]
+ payment-types = ["from_channel_balance", "from_future_htlc", "from_future_htlc_with_preimage", "from_channel_balance_for_future_htlc"]
+ }
+}
diff --git a/testing/regtest/payer.conf b/testing/regtest/payer.conf
new file mode 100644
index 00000000..cf039058
--- /dev/null
+++ b/testing/regtest/payer.conf
@@ -0,0 +1,29 @@
+// Somebody else on the network: pays the group through the LSP, and is paid by it.
+eclair {
+ chain = "regtest"
+ node-alias = "bennu-payer"
+ server.binding-ip = "0.0.0.0"
+ api {
+ enabled = true
+ binding-ip = "0.0.0.0"
+ port = 8080
+ password = "payer"
+ }
+ bitcoind {
+ host = "bitcoind"
+ rpcport = 18443
+ rpcuser = "foo"
+ rpcpassword = "bar"
+ wallet = "payer"
+ zmqblock = "tcp://bitcoind:29000"
+ zmqtx = "tcp://bitcoind:29001"
+ }
+ // Advertise the whole channel: eclair otherwise caps an update by the balance it had when it was made.
+ channel.channel-update.balance-thresholds = []
+ features {
+ option_dual_fund = optional
+ option_splice = optional
+ option_quiesce = optional
+ option_simple_close = optional
+ }
+}
diff --git a/testing/regtest/regtest.sh b/testing/regtest/regtest.sh
new file mode 100755
index 00000000..e0e7d2a4
--- /dev/null
+++ b/testing/regtest/regtest.sh
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+# The group Lightning wallet's regtest network. `up` builds it from nothing: bitcoind with three
+# wallets (a miner, the LSP's, the payer's), electrs, both eclair nodes, and a channel from the payer to
+# the LSP. `down` removes all of it.
+set -euo pipefail
+cd "$(dirname "$0")"
+
+btc() { docker compose exec -T bitcoind bitcoin-cli -regtest -rpcuser=foo -rpcpassword=bar "$@"; }
+lsp() { local m=$1; shift; curl -sf -u :lsp -X POST "http://127.0.0.1:28080/$m" "$@"; }
+payer() { local m=$1; shift; curl -sf -u :payer -X POST "http://127.0.0.1:28081/$m" "$@"; }
+mine() { btc -rpcwallet=miner generatetoaddress "${1:-1}" "$(btc -rpcwallet=miner getnewaddress)" >/dev/null; }
+wait_for() { for _ in $(seq 1 90); do if eval "$1" >/dev/null 2>&1; then return 0; fi; sleep 1; done; echo "timed out waiting for: $1" >&2; return 1; }
+
+case "${1:-}" in
+ up)
+ docker compose up -d bitcoind
+ wait_for "btc getblockchaininfo"
+ for w in miner lsp payer; do btc -named createwallet wallet_name=$w load_on_startup=true >/dev/null 2>&1 || btc loadwallet $w >/dev/null 2>&1 || true; done
+ mine 150
+ btc -rpcwallet=miner sendtoaddress "$(btc -rpcwallet=lsp getnewaddress)" 10 >/dev/null
+ btc -rpcwallet=miner sendtoaddress "$(btc -rpcwallet=payer getnewaddress)" 10 >/dev/null
+ mine 6
+ docker compose up -d electrs lsp payer
+ wait_for "lsp getinfo"
+ wait_for "payer getinfo"
+ lspId=$(lsp getinfo | python3 -c 'import sys,json; print(json.load(sys.stdin)["nodeId"])')
+ payer connect -d uri="$lspId@lsp:9735" >/dev/null
+ payer open -d nodeId="$lspId" -d fundingSatoshis=5000000 >/dev/null
+ # The funding transaction reaches the mempool a moment after the open is answered.
+ wait_for "[ \$(btc getmempoolinfo | python3 -c 'import sys,json; print(json.load(sys.stdin)[\"size\"])') -gt 0 ]"
+ wait_for "mine 1; payer channels | grep -q NORMAL"
+ echo "LSP $lspId on 127.0.0.1:29735, electrs on 127.0.0.1:28001"
+ ;;
+ down) docker compose down -v ;;
+ mine) mine "${2:-1}" ;;
+ btc) shift; btc "$@" ;;
+ lsp) shift; lsp "$@"; echo ;;
+ payer) shift; payer "$@"; echo ;;
+ *) echo "usage: $0 up | down | mine [n] | btc | lsp [-d k=v] | payer [-d k=v]"; exit 1 ;;
+esac