Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .claude/plugins/spark-regtest/skills/spark-regtest/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,10 @@ for port in 23535 23536 23537 23049 23090 60001; do adb reverse tcp:$port tcp:$p
- An existing dev install keeps the Electrum server saved in its settings, which includes the old default. Uninstall
first (backups are off, so nothing comes back), or use Settings › Advanced › Electrum Server › Reset To Default, then
Connect To Host (Reset only fills the form).
- On Android the local stack turns off Transfer to Spending and exit fees paid from Savings
(`Env.sparkSharesNodeChain`). Fund Spark with `./spark send <deposit address> <sats>` or
`./spark pay <Spending invoice> [sats]`, and pay exit funding with `./spark send`. iOS allows both when its URLs match the fixture.
- Transfer to Spending and exit fees paid from Savings need Spark and Savings on one chain
(`Env.sparkSharesNodeChain`): the Spark URL is the fixture's `23090` on `E2E_LOCAL_HOST` or `127.0.0.1`, and the
node runs on Electrum `E2E_LOCAL_HOST:60001` with no `ESPLORA_URL`. Otherwise fund Spark with
`./spark send <deposit address> <sats>` or `./spark pay <Spending invoice> [sats]`, and pay exit funding with `./spark send`.
- A deposit is claimed after 1 block here.
- Mine with `./spark mine`, not `./bitcoin-cli mine`: only `spark-bitcoind` relays Spark's v3 packages.
- A phone over adb: set `E2E_LOCAL_HOST=127.0.0.1` and keep the `adb reverse` loop. Over the LAN: run `export SPARK_PUBLIC_HOST=<LAN IP>`
Expand Down
41 changes: 35 additions & 6 deletions app/src/main/java/to/bitkit/env/Env.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package to.bitkit.env

import android.os.Build
import com.synonym.bitkitcore.UsdtDestination
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.map
import org.lightningdevkit.ldknode.LogLevel
import org.lightningdevkit.ldknode.Network
import to.bitkit.BuildConfig
Expand Down Expand Up @@ -159,15 +162,39 @@ internal object Env {
Network.REGTEST -> "https://mempool.bitkit.stag0.blocktank.to/"
}

/** The Electrum server the running node syncs from; null while no node runs or it uses Esplora. */
val activeElectrumServerUrl = MutableStateFlow<String?>(null)

/**
* Whether the node's chain is the one Spark watches, so an on-chain funding of Spark from Savings or a hardware
* wallet reaches it. Hosted regtest supports the node's Spark Esplora proxy. The local fixture config selects
* Spark's chain only; the node and hardware wallet can use independently configured Electrum servers.
* wallet reaches it. Hosted regtest supports the node's Spark Esplora proxy. A local fixture shares it only while
* Spark reads the fixture's REST on [localHost], or on loopback forwarded there by `adb reverse`, and the node runs
* on the fixture's Electrum. Hardware wallets read the node's Electrum setting, so a server selected by a restore
* or in settings keeps it false.
*/
fun sparkSharesNodeChain(network: Network, regtestEsploraUrl: String?, localSpark: LocalSparkSettings?): Boolean =
network != Network.REGTEST || (localSpark == null && regtestEsploraUrl != null)
fun sparkSharesNodeChain(
network: Network,
regtestEsploraUrl: String?,
localSpark: LocalSparkSettings?,
nodeElectrumUrl: String?,
localHost: String = e2eLocalHost,
): Boolean = when {
network != Network.REGTEST -> true
localSpark == null -> regtestEsploraUrl != null
else ->
regtestEsploraUrl == null &&
localSpark.isComplete &&
localSpark.chainUrl in setOf(localHost, "127.0.0.1").map { "http://$it:23090/api" } &&
nodeElectrumUrl == ElectrumServers.REGTEST.local(localHost)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}

val sparkSharesNodeChain: Boolean get() = sparkSharesNodeChain(network, regtestEsploraUrl, localSparkSettings)
val sparkSharesNodeChain: Boolean get() = sparkSharesChainWith(activeElectrumServerUrl.value)

/** [sparkSharesNodeChain] as the running node changes, for screens that show it. */
val sparkSharesNodeChainFlow: Flow<Boolean> = activeElectrumServerUrl.map(::sparkSharesChainWith)

private fun sparkSharesChainWith(nodeElectrumUrl: String?): Boolean =
sparkSharesNodeChain(network, regtestEsploraUrl, localSparkSettings, nodeElectrumUrl)

/** REST endpoint for the Spark SDK. An unconfigured regtest uses the SDK's hosted default. */
fun sparkChainServiceUrl(
Expand Down Expand Up @@ -386,7 +413,9 @@ private object ElectrumServers {

object REGTEST {
const val STAG = "ssl://electrs.bitkit.stag0.blocktank.to:9999"
val LOCAL get() = "tcp://${Env.e2eLocalHost}:60001"
val LOCAL get() = local(Env.e2eLocalHost)

fun local(host: String) = "tcp://$host:60001"
}

const val TESTNET = "ssl://electrum.blockstream.info:60002"
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/java/to/bitkit/services/LightningService.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package to.bitkit.services

import android.os.Process
import androidx.annotation.VisibleForTesting
import com.synonym.bitkitcore.AddressType
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job
Expand All @@ -13,6 +14,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
Expand Down Expand Up @@ -319,6 +321,11 @@ class LightningService internal constructor(

private var listenerJob: Job? = null

// The Electrum server the node being built syncs from; published to Env once that node starts.
@Volatile
@VisibleForTesting
internal var chainElectrumUrl: String? = null

@Volatile
private var watchOnlyReconcileRetryJob: Job? = null
private val watchOnlyReconcileRetryLock = Any()
Expand Down Expand Up @@ -467,6 +474,7 @@ class LightningService internal constructor(
private suspend fun Builder.configureChainSource(customServerUrl: String? = null) {
Env.regtestEsploraUrl?.let { esploraUrl ->
Logger.info("Using onchain source Esplora url: '$esploraUrl'", context = TAG)
chainElectrumUrl = null
setChainSourceEsplora(
serverUrl = esploraUrl,
config = EsploraSyncConfig(
Expand All @@ -481,6 +489,7 @@ class LightningService internal constructor(
}
val serverUrl = customServerUrl ?: settingsStore.data.first().electrumServer
Logger.info("Using onchain source Electrum Sever url: $serverUrl", context = TAG)
chainElectrumUrl = serverUrl
setChainSourceElectrum(
serverUrl = serverUrl,
config = ElectrumSyncConfig(
Expand All @@ -504,6 +513,8 @@ class LightningService internal constructor(
ServiceQueue.LDK.background(ldkQueue) {
try {
node.start()
// Published before the queue returns, so a start whose caller was cancelled still shows it.
Env.activeElectrumServerUrl.update { chainElectrumUrl }
} catch (e: NodeException) {
throw LdkError(e)
}
Expand Down Expand Up @@ -610,6 +621,7 @@ class LightningService internal constructor(
// let the GC free it later on the finalizer thread, racing the next node. This covers the whole
// body, including the listener join, so cancellation during listener cleanup cannot skip it.
suspend fun stop() = withContext(NonCancellable) {
Env.activeElectrumServerUrl.update { null }
watchOnlyReconcileRetryJob?.cancelAndJoin()
shouldListenForEvents = false
// A stop requested from inside an event handler runs on the listener job itself; joining it
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/java/to/bitkit/ui/ContentView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1189,9 +1189,11 @@ private fun RootNavHost(
val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle()
val balances = LocalBalances.current
val hasSeenSpendingIntro by settingsViewModel.hasSeenSpendingIntro.collectAsStateWithLifecycle()
val canFundOnChain by Env.sparkSharesNodeChainFlow
.collectAsStateWithLifecycle(initialValue = Env.sparkSharesNodeChain)
FundingScreen(
canFundWithSpark = sparkState.isUsable,
canFundOnChain = Env.sparkSharesNodeChain,
canFundOnChain = canFundOnChain,
onTransfer = { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) },
onFund = {
scope.launch {
Expand Down
34 changes: 27 additions & 7 deletions app/src/test/java/to/bitkit/env/SparkChainServiceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,32 @@ class SparkChainServiceTest {

@Test
fun `on-chain spark funding needs the spark regtest chain on regtest`() {
assertFalse(Env.sparkSharesNodeChain(Network.REGTEST, regtestEsploraUrl = null, localSpark = null))
assertTrue(Env.sparkSharesNodeChain(Network.REGTEST, "http://10.0.2.2:3999", localSpark = null))
assertTrue(Env.sparkSharesNodeChain(Network.BITCOIN, regtestEsploraUrl = null, localSpark = null))
assertFalse(Env.sparkSharesNodeChain(Network.REGTEST, regtestEsploraUrl = null, localSpark = local))
assertFalse(Env.sparkSharesNodeChain(Network.REGTEST, local.chainUrl, local))
assertFalse(Env.sparkSharesNodeChain(Network.REGTEST, "http://10.0.2.2:3999", local))
assertFalse(Env.sparkSharesNodeChain(Network.REGTEST, null, local.copy(configBase64 = "")))
assertFalse(Env.sparkSharesNodeChain(Network.REGTEST, regtestEsploraUrl = null, null, nodeElectrumUrl = null))
assertTrue(Env.sparkSharesNodeChain(Network.REGTEST, "http://10.0.2.2:3999", null, nodeElectrumUrl = null))
assertTrue(Env.sparkSharesNodeChain(Network.BITCOIN, regtestEsploraUrl = null, null, nodeElectrumUrl = null))
}

@Test
fun `a local fixture shares the node chain only while the node runs on the fixture electrum`() {
fun shares(
spark: LocalSparkSettings? = local,
node: String? = "tcp://10.0.2.2:60001",
esplora: String? = null,
) = Env.sparkSharesNodeChain(Network.REGTEST, esplora, spark, node, localHost = "10.0.2.2")

assertTrue(shares())
assertTrue(shares(spark = local.copy(chainUrl = "http://10.0.2.2:23090/api")))
assertTrue(
Env.sparkSharesNodeChain(Network.REGTEST, null, local, "tcp://127.0.0.1:60001", localHost = "127.0.0.1")
)
assertFalse(shares(node = null))
assertFalse(shares(node = "tcp://regtest.example:60001"))
assertFalse(shares(node = "ssl://electrs.bitkit.stag0.blocktank.to:9999"))
assertFalse(shares(node = "tcp://10.0.2.2:60002"))
assertFalse(shares(esplora = "http://10.0.2.2:3999"))
assertFalse(shares(esplora = local.chainUrl))
assertFalse(shares(spark = local.copy(configBase64 = "")))
assertFalse(shares(spark = local.copy(chainUrl = "http://127.0.0.1:23091/api")))
assertFalse(shares(spark = local.copy(chainUrl = "http://regtest.example:23090/api")))
}
}
17 changes: 17 additions & 0 deletions app/src/test/java/to/bitkit/services/LightningServiceTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import org.lightningdevkit.ldknode.TransactionDetails
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.doAnswer
import org.mockito.kotlin.doNothing
import org.mockito.kotlin.doSuspendableAnswer
import org.mockito.kotlin.doThrow
import org.mockito.kotlin.eq
Expand Down Expand Up @@ -92,6 +93,7 @@ import to.bitkit.repositories.PaykitPaymentRequestId
import to.bitkit.repositories.PreparedOnchainSend
import to.bitkit.repositories.PreparedOnchainSendRefused
import to.bitkit.test.BaseUnitTest
import to.bitkit.utils.AppError
import to.bitkit.utils.LdkError
import to.bitkit.utils.LoggerLdk
import to.bitkit.utils.ServiceError
Expand Down Expand Up @@ -636,6 +638,21 @@ class LightningServiceTest : BaseUnitTest() {
}
}

@Test
fun `start publishes the node's electrum only once the node runs`() = test {
sut.chainElectrumUrl = "tcp://10.0.2.2:60001"
doThrow(NodeException.PersistenceFailed("failed")).doNothing().whenever(node).start()

assertFailsWith<AppError> { sut.start() }
assertNull(Env.activeElectrumServerUrl.value)

sut.start()
assertEquals("tcp://10.0.2.2:60001", Env.activeElectrumServerUrl.value)

sut.stop()
assertNull(Env.activeElectrumServerUrl.value)
}

@Test
fun `stop destroys the node handle and clears it`() = test {
sut.stop()
Expand Down
6 changes: 5 additions & 1 deletion journeys/transfer/spark-transfer-to-spending.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@
sees, so this journey stops before the swipe; the states after it are covered by SettingUpScreen previews and
SparkRepoTest.

Precondition: dev build with Spark connected on its regtest (no key needed), built with `ESPLORA_URL` on Spark's regtest chain through `scripts/spark-regtest-esplora.py` (without it the transfer opens the Transfer Unavailable sheet), a freshly onboarded wallet (so
Precondition: dev build with Spark connected on its regtest (no key needed), on a chain Spark and Savings share:
either hosted regtest with `ESPLORA_URL` on Spark's chain through `scripts/spark-regtest-esplora.py`, or
bitkit-docker's local `./spark` stack, built and forwarded as in `.claude/plugins/spark-regtest/skills/spark-regtest/SKILL.md`
Comment thread
ovitrif marked this conversation as resolved.
Resolved
("Local `./spark` stack"), with the node on the default local Electrum. On any other chain setup Funding disables
the Savings and HW wallet transfers, and Transfer To Spending opens the Transfer Unavailable sheet. Also a freshly onboarded wallet (so
neither intro has been seen) with a positive on-chain Savings balance and no channels, and the Spending
suggestion card on Home. Start on the wallet home screen.
</description>
Expand Down