From a92ee4381b0d1e0af421d9c49665a2edabbcd38e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 02:51:15 +0100 Subject: [PATCH 001/154] feat: spark emergency exit --- .../bitkit/services/SparkExitRegtestTest.kt | 110 +++ app/src/main/AndroidManifest.xml | 9 + app/src/main/java/to/bitkit/App.kt | 5 + .../main/java/to/bitkit/data/CacheStore.kt | 11 + .../java/to/bitkit/data/dao/TransferDao.kt | 3 + app/src/main/java/to/bitkit/env/Env.kt | 6 + app/src/main/java/to/bitkit/ext/Context.kt | 4 + .../java/to/bitkit/models/TransferType.kt | 7 +- .../to/bitkit/repositories/SparkExitChain.kt | 276 ++++++ .../to/bitkit/repositories/SparkExitDriver.kt | 535 +++++++++++ .../bitkit/repositories/SparkExitFunding.kt | 347 +++++++ .../to/bitkit/repositories/SparkExitRecord.kt | 788 ++++++++++++++++ .../to/bitkit/repositories/SparkExitRepo.kt | 566 ++++++++++++ .../to/bitkit/repositories/SparkExitSweep.kt | 255 ++++++ .../to/bitkit/repositories/SparkExitWorker.kt | 347 +++++++ .../java/to/bitkit/repositories/SparkRepo.kt | 122 ++- .../to/bitkit/repositories/TransferRepo.kt | 38 +- .../java/to/bitkit/repositories/WalletRepo.kt | 6 +- .../java/to/bitkit/services/SparkService.kt | 35 +- app/src/main/java/to/bitkit/ui/ContentView.kt | 88 +- .../screens/transfer/SavingsAdvancedScreen.kt | 2 +- .../screens/transfer/SavingsConfirmScreen.kt | 2 +- .../bitkit/ui/screens/wallets/HomeScreen.kt | 2 +- .../screens/wallets/receive/ReceiveSheet.kt | 2 +- .../LightningConnectionsViewModel.kt | 43 +- .../settings/lightning/SparkDetailScreen.kt | 15 +- .../lightning/SparkDetailViewModel.kt | 11 +- .../settings/lightning/SparkExitComponents.kt | 181 ++++ .../lightning/SparkExitConfirmScreen.kt | 100 +++ .../lightning/SparkExitFundingScreen.kt | 143 +++ .../lightning/SparkExitIntroScreen.kt | 111 +++ .../lightning/SparkExitProgressScreen.kt | 331 +++++++ .../lightning/SparkExitQuoteScreen.kt | 121 +++ .../settings/lightning/SparkExitViewModel.kt | 219 +++++ .../utils/RequestNotificationPermissions.kt | 2 +- .../usecases/DeriveBalanceStateUseCase.kt | 13 +- .../bitkit/utils/BatterySettingsSnapshot.kt | 4 + .../java/to/bitkit/viewmodels/AppViewModel.kt | 7 + .../to/bitkit/viewmodels/TransferViewModel.kt | 2 +- app/src/main/res/values-ar/strings.xml | 71 ++ app/src/main/res/values-b+es+419/strings.xml | 71 ++ app/src/main/res/values-ca/strings.xml | 71 ++ app/src/main/res/values-cs/strings.xml | 71 ++ app/src/main/res/values-de/strings.xml | 71 ++ app/src/main/res/values-el/strings.xml | 71 ++ app/src/main/res/values-es-rES/strings.xml | 71 ++ app/src/main/res/values-es/strings.xml | 71 ++ app/src/main/res/values-fr/strings.xml | 71 ++ app/src/main/res/values-it/strings.xml | 71 ++ app/src/main/res/values-nl/strings.xml | 71 ++ app/src/main/res/values-pl/strings.xml | 71 ++ app/src/main/res/values-pt-rBR/strings.xml | 71 ++ app/src/main/res/values-pt/strings.xml | 71 ++ app/src/main/res/values-ru/strings.xml | 71 ++ app/src/main/res/values/strings.xml | 71 ++ .../repositories/SparkExitAlertsTest.kt | 80 ++ .../bitkit/repositories/SparkExitChainTest.kt | 198 ++++ .../repositories/SparkExitDriverTest.kt | 843 ++++++++++++++++++ .../bitkit/repositories/SparkExitFixtures.kt | 216 +++++ .../repositories/SparkExitFundingTest.kt | 312 +++++++ .../repositories/SparkExitRecordTest.kt | 248 ++++++ .../repositories/SparkExitRegtestTest.kt | 51 ++ .../bitkit/repositories/SparkExitRepoTest.kt | 268 ++++++ .../bitkit/repositories/SparkExitSweepTest.kt | 90 ++ .../to/bitkit/repositories/SparkRepoTest.kt | 31 + .../to/bitkit/services/SparkServiceTest.kt | 2 +- .../LightningConnectionsViewModelTest.kt | 4 + .../lightning/SparkExitViewModelTest.kt | 63 ++ .../viewmodels/AppViewModelSendFlowTest.kt | 1 + .../test/resources/spark-exit-record-ios.json | 1 + changelog.d/next/1697.added.md | 2 +- docs/screens-map.md | 5 + journeys/README.md | 1 + journeys/transfer/spark-emergency-exit.xml | 30 + 74 files changed, 8404 insertions(+), 47 deletions(-) create mode 100644 app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt create mode 100644 app/src/main/java/to/bitkit/repositories/SparkExitChain.kt create mode 100644 app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt create mode 100644 app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt create mode 100644 app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt create mode 100644 app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt create mode 100644 app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt create mode 100644 app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitRegtestTest.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitSweepTest.kt create mode 100644 app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt create mode 100644 app/src/test/resources/spark-exit-record-ios.json create mode 100644 journeys/transfer/spark-emergency-exit.xml diff --git a/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt b/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt new file mode 100644 index 0000000000..e6dffa1a13 --- /dev/null +++ b/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt @@ -0,0 +1,110 @@ +package to.bitkit.services + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import breez_sdk_spark.ConnectRequest +import breez_sdk_spark.CpfpFundingKind +import breez_sdk_spark.ExitLeafSelection +import breez_sdk_spark.PrepareRecoverFundsRequest +import breez_sdk_spark.Seed +import breez_sdk_spark.connect +import breez_sdk_spark.defaultConfig +import breez_sdk_spark.singleKeyCpfpSigner +import io.ktor.client.HttpClient +import kotlinx.coroutines.runBlocking +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.lightningdevkit.ldknode.Network +import to.bitkit.repositories.EsploraSparkExitChain +import to.bitkit.repositories.SparkExitFundingKey +import to.bitkit.repositories.SparkExitQuote +import to.bitkit.repositories.SparkExitSweep +import to.bitkit.test.annotations.DeviceIntegration +import to.bitkit.utils.SignedTransactionId +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import breez_sdk_spark.Network as SparkNetwork + +/** + * Runs the exit's SDK, key and chain calls on a device against Spark's hosted regtest, for a new wallet with nothing + * to exit. It needs the network, so it only runs with the instrumentation argument `sparkExitRegtest true`. + */ +@RunWith(AndroidJUnit4::class) +@DeviceIntegration +class SparkExitRegtestTest { + private val onchain = OnchainService() + + @Before + fun requireOptIn() { + val isOptedIn = InstrumentationRegistry.getArguments().getString("sparkExitRegtest") == "true" + assumeTrue("Pass -e sparkExitRegtest true to run against Spark's regtest", isOptedIn) + } + + @Test + fun quotesAnEmptyWalletAndReadsItsFundingAddress(): Unit = runBlocking { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val storage = File(context.cacheDir, "spark-exit-regtest-${System.nanoTime()}").apply { mkdirs() } + val mnemonic = onchain.generateMnemonic() + val config = defaultConfig(SparkNetwork.REGTEST).apply { + leafOptimizationConfig = leafOptimizationConfig.copy(autoEnabled = false) + } + val sdk = connect(ConnectRequest(config, Seed.Mnemonic(mnemonic, null), storage.path)) + try { + val path = SparkExitFundingKey.path(0, Network.REGTEST) + val address = onchain.deriveBitcoinAddress(mnemonic, path, Network.REGTEST, null) + val again = onchain.deriveBitcoinAddress(mnemonic, path, Network.REGTEST, null) + val secret = SparkExitFundingKey.secretKey(onchain.derivePrivateKey(mnemonic, path, Network.REGTEST, null)) + singleKeyCpfpSigner(secret) + assertEquals("m/84'/1'/7797'/0/0", path) + assertTrue(address.address.startsWith("bcrt1q"), address.address) + assertEquals(66, address.publicKey.length) + assertEquals(32, secret.size) + assertEquals(address, again) + + val feeRate = maxOf(1uL, sdk.recommendedFees().fastestFee) + val prepared = BreezSparkExitRecovering(sdk).prepare( + PrepareRecoverFundsRequest(feeRate, CpfpFundingKind.P2wpkh, address.address, ExitLeafSelection.All), + ) + assertTrue(prepared.leaves.isEmpty()) + assertFalse(SparkExitQuote(prepared).isWorthExiting) + + val chain = EsploraSparkExitChain(EsploraSparkExitChain.defaultHosts("regtest"), HttpClient()) + assertTrue(chain.tipHeight() > 0u) + assertTrue(chain.utxos(address.address).isEmpty()) + } finally { + sdk.disconnect() + storage.deleteRecursively() + } + } + + @Test + fun signsALeftoverSweepWithTheFundingKey(): Unit = runBlocking { + val mnemonic = onchain.generateMnemonic() + val path = SparkExitFundingKey.path(0, Network.REGTEST) + val address = onchain.deriveBitcoinAddress(mnemonic, path, Network.REGTEST, null) + val secret = SparkExitFundingKey.secretKey(onchain.derivePrivateKey(mnemonic, path, Network.REGTEST, null)) + val plan = requireNotNull( + SparkExitSweep.plan( + listOf( + SparkExitSweep.Input("11".repeat(32), 0u, 3_000uL), + SparkExitSweep.Input("22".repeat(32), 2u, 2_035uL), + ), + destination = "bcrt1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqc8gma6", + feeRateSatPerVbyte = 2uL, + ), + ) + + val signed = singleKeyCpfpSigner(secret).signPsbt(SparkExitSweep.psbt(plan, address.address)) + val hex = SparkExitSweep.signedTxHex(plan, signed) + + // Two inputs, each a P2WPKH witness of a DER signature and the funding key. + val witness = Regex("02(4[4-9])30[0-9a-f]+?01(21${address.publicKey})").findAll(hex).toList() + assertEquals(2, witness.size, hex) + assertTrue(hex.startsWith("020000000001"), hex) + assertEquals(64, SignedTransactionId.fromHex(hex).length) + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b845c2d308..eecc4b0cb0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -228,6 +228,15 @@ + + + + + + + @@ -60,6 +64,7 @@ internal open class App : Application(), Configuration.Provider { SingletonImageLoader.setSafe { imageLoader } currentActivity = CurrentActivity().also { registerActivityLifecycleCallbacks(it) } appWidgetRefreshScheduler.ensureScheduled(AppWidgetRefreshReason.APP_START) + sparkExitWork.ensureScheduled() // Initialize btleplug for Bluetooth support (required before any BLE usage) BluetoothInit.ensureInitialized() pubkyAuthHandlerRegistrar.start() diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 1c55b18947..eab61feb87 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -169,6 +169,17 @@ data class AppCacheData( val quickPayLedger: QuickPayLedger? = null, /** LNURL-pay comments by payment hash, kept until the sent payment's activity stores them. */ val pendingLightningMessages: Map = mapOf(), + /** + * When a Spark leaf optimization last ran or was cut short, in epoch milliseconds; cleared once it completed or + * an exit quote waited out the counter-swap grace. Kept across processes, since a swap the app's close cut short + * leaves value in flight. + */ + val sparkOptimizationActivityAt: Long? = null, + /** + * The funding key index the next Spark emergency exit takes, per `{network}/wallet{n}`, so each exit pays its fees + * from an address of its own. + */ + val sparkExitNextFundingIndexes: Map = mapOf(), ) { fun isContactDetached(activityId: String, walletId: String): Boolean = scopedActivityId(walletId, activityId) in detachedActivityContacts diff --git a/app/src/main/java/to/bitkit/data/dao/TransferDao.kt b/app/src/main/java/to/bitkit/data/dao/TransferDao.kt index 84536fee46..0c27ba4540 100644 --- a/app/src/main/java/to/bitkit/data/dao/TransferDao.kt +++ b/app/src/main/java/to/bitkit/data/dao/TransferDao.kt @@ -41,6 +41,9 @@ interface TransferDao { @Query("UPDATE transfers SET isSettled = 1, settledAt = :settledAt WHERE id = :id") suspend fun markSettled(id: String, settledAt: Long) + @Query("UPDATE transfers SET claimableAtHeight = :claimableAtHeight WHERE id = :id") + suspend fun updateClaimableAtHeight(id: String, claimableAtHeight: Int?) + @Query("DELETE FROM transfers WHERE isSettled = 1 AND settledAt < :expirationTimestamp") suspend fun deleteOldSettled(expirationTimestamp: Long) } diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index 09b2fd0dab..53baea558e 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -240,6 +240,12 @@ internal object Env { fun sparkExitRestorePath(walletIndex: Int) = Path(storagePathOf(walletIndex, network.name.lowercase(), "spark-restore"), "exit-state.json").toString() + /** The running Spark emergency exit, if any: its signed recovery and how far it got. */ + fun sparkExitRecordPath(walletIndex: Int): String { + require(::appStoragePath.isInitialized) { "App storage path should be 'context.filesDir.absolutePath'." } + return Path(appStoragePath, network.name.lowercase(), "wallet$walletIndex", "spark-exit.json").toString() + } + fun bitkitCoreStoragePath(walletIndex: Int): String { return storagePathOf(walletIndex, network.name.lowercase(), "core") } diff --git a/app/src/main/java/to/bitkit/ext/Context.kt b/app/src/main/java/to/bitkit/ext/Context.kt index c3d6f252f6..edc146cbe8 100644 --- a/app/src/main/java/to/bitkit/ext/Context.kt +++ b/app/src/main/java/to/bitkit/ext/Context.kt @@ -14,6 +14,7 @@ import android.content.ContextWrapper import android.content.Intent import android.content.pm.PackageManager.PERMISSION_GRANTED import android.hardware.usb.UsbManager +import android.net.ConnectivityManager import android.os.PowerManager import android.provider.Settings import android.text.format.DateFormat @@ -41,6 +42,9 @@ val Context.activityManager: ActivityManager val Context.alarmManager: AlarmManager get() = getSystemService(Context.ALARM_SERVICE) as AlarmManager +val Context.connectivityManager: ConnectivityManager + get() = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + val Context.usbManager: UsbManager get() = getSystemService(Context.USB_SERVICE) as UsbManager diff --git a/app/src/main/java/to/bitkit/models/TransferType.kt b/app/src/main/java/to/bitkit/models/TransferType.kt index cc3ceecdc8..2c88fce680 100644 --- a/app/src/main/java/to/bitkit/models/TransferType.kt +++ b/app/src/main/java/to/bitkit/models/TransferType.kt @@ -5,8 +5,11 @@ enum class TransferType { TO_SAVINGS, MANUAL_SETUP, FORCE_CLOSE, - COOP_CLOSE; + COOP_CLOSE, - fun isToSavings() = this in listOf(TO_SAVINGS, COOP_CLOSE, FORCE_CLOSE) + /** The Spark balance leaving on-chain without the Spark operators. */ + SPARK_EXIT; + + fun isToSavings() = this in listOf(TO_SAVINGS, COOP_CLOSE, FORCE_CLOSE, SPARK_EXIT) fun isToSpending() = this in listOf(TO_SPENDING, MANUAL_SETUP) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt new file mode 100644 index 0000000000..4c3d4e4728 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -0,0 +1,276 @@ +package to.bitkit.repositories + +import breez_sdk_spark.RecoveryTransaction +import io.ktor.client.HttpClient +import io.ktor.client.request.get +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.client.statement.HttpResponse +import io.ktor.client.statement.bodyAsText +import io.ktor.content.TextContent +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.isSuccess +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.longOrNull +import to.bitkit.ext.runSuspendCatching +import to.bitkit.utils.AppError + +data class EsploraTxStatus(val confirmed: Boolean, val blockHeight: UInt? = null) + +data class EsploraUtxo(val txid: String, val vout: UInt, val value: ULong, val status: EsploraTxStatus) + +/** What a broadcast came to. Accepted includes a transaction the node already had. */ +sealed interface SparkExitBroadcastOutcome { + val summary: String + + data object Accepted : SparkExitBroadcastOutcome { + override val summary = "accepted" + } + + /** The host or node could not take it now: the next tick tries again. */ + data class RetryLater(val reason: String) : SparkExitBroadcastOutcome { + override val summary get() = "retry: $reason" + } + + /** Its relative timelock has not matured (`non-BIP68-final`): sent again once it has, never a rejection. */ + data class NotMature(val reason: String) : SparkExitBroadcastOutcome { + override val summary get() = "not mature: $reason" + } + + /** + * An input is missing or already spent: its parent is not visible yet, or, once every parent confirmed, someone + * else (the operators) spent it first. Never a rejection. + */ + data class InputsMissing(val reason: String) : SparkExitBroadcastOutcome { + override val summary get() = "inputs missing: $reason" + } + + /** Refused for good at this fee or policy; a later check or rebuild replaces it. */ + data class Rejected(val reason: String) : SparkExitBroadcastOutcome { + override val summary get() = "rejected: $reason" + } +} + +/** The chain the Spark SDK reads, for what an exit does outside the SDK: broadcasting and the funding address. */ +interface SparkExitChain { + suspend fun tipHeight(): UInt + suspend fun utxos(address: String): List + suspend fun txStatus(txid: String): EsploraTxStatus + suspend fun broadcast(tx: RecoveryTransaction): SparkExitBroadcastOutcome + + /** A transaction of the app's own, such as the sweep of leftover fee funding, as a single `/tx`. */ + suspend fun broadcastHex(hex: String): SparkExitBroadcastOutcome +} + +class SparkExitChainError(message: String) : AppError(message) + +/** + * esplora and mempool.space REST, on the hosts the Spark SDK uses by default: a transaction with a CPFP child goes + * out as a package through `/v1/txs/package` (a JSON array of hex), one without as a single `/tx`. + */ +class EsploraSparkExitChain( + private val hosts: List, + private val client: HttpClient, +) : SparkExitChain { + companion object { + private val json = Json { ignoreUnknownKeys = true } + + /** The Spark SDK's default chain service per network (breez spark-sdk `default_rest_chain_services`). */ + fun defaultHosts(sparkNetwork: String?): List = when (sparkNetwork) { + "mainnet" -> listOf("https://mempool.space/api", "https://blockstream.info/api") + "regtest" -> listOf("https://regtest-mempool.us-west-2.sparkinfra.net/api") + else -> emptyList() + } + + private val NOT_HERE = setOf(404, 405) + } + + override suspend fun tipHeight(): UInt = get("/blocks/tip/height").trim().toUInt() + + override suspend fun utxos(address: String): List = + json.parseToJsonElement(get("/address/$address/utxo")).jsonArray.map { + val o = it.jsonObject + EsploraUtxo( + txid = o.getValue("txid").jsonPrimitive.content, + vout = o.getValue("vout").jsonPrimitive.content.toUInt(), + value = o.getValue("value").jsonPrimitive.content.toULong(), + status = status(o.getValue("status").jsonObject), + ) + } + + override suspend fun txStatus(txid: String): EsploraTxStatus = + status(json.parseToJsonElement(get("/tx/$txid/status")).jsonObject) + + /** Tries each host until one accepts. Otherwise a node's refusal wins over a host that was only unavailable. */ + override suspend fun broadcast(tx: RecoveryTransaction): SparkExitBroadcastOutcome { + val outcomes = mutableListOf() + for (host in hosts) { + val child = tx.cpfpTxHex + val attempt = if (child != null) { + submitPackage(host, listOf(tx.txHex, child), tx.txid) + } else { + submitSingle(host, tx.txHex) + } + // null: this host cannot take it (no package endpoint, unreachable). + if (attempt == SparkExitBroadcastOutcome.Accepted) return attempt + attempt?.let { outcomes += it } + } + return outcomes.firstOrNull { it is SparkExitBroadcastOutcome.Rejected } + ?: outcomes.firstOrNull() + ?: SparkExitBroadcastOutcome.RetryLater("no chain host reachable") + } + + override suspend fun broadcastHex(hex: String): SparkExitBroadcastOutcome { + val outcomes = hosts.mapNotNull { host -> + submitSingle(host, hex).also { if (it == SparkExitBroadcastOutcome.Accepted) return it } + } + return outcomes.firstOrNull { it is SparkExitBroadcastOutcome.Rejected } + ?: outcomes.firstOrNull() + ?: SparkExitBroadcastOutcome.RetryLater("no chain host reachable") + } + + private suspend fun submitPackage( + host: String, + hexes: List, + parentTxid: String, + ): SparkExitBroadcastOutcome? { + val body = JsonArray(hexes.map(::JsonPrimitive)).toString() + for (path in listOf("/v1/txs/package", "/txs/package")) { + val response = post("$host$path", TextContent(body, ContentType.Application.Json)) ?: return null + if (response.status.value in NOT_HERE) continue + return SparkExitBroadcastClassifier.pkg(response.status.value, response.bodyAsText(), parentTxid) + } + return null + } + + private suspend fun submitSingle(host: String, hex: String): SparkExitBroadcastOutcome? { + val response = post("$host/tx", TextContent(hex, ContentType.Text.Plain)) ?: return null + if (response.status.value in NOT_HERE) return null + return SparkExitBroadcastClassifier.single(response.status.value, response.bodyAsText()) + } + + private suspend fun post(url: String, content: TextContent): HttpResponse? = + runSuspendCatching { + client.post(url) { + // The shared client defaults to JSON; the body carries its own type. + headers.remove(HttpHeaders.ContentType) + setBody(content) + } + }.getOrNull() + + private suspend fun get(path: String): String { + var lastError: Throwable = SparkExitChainError("No chain host configured") + for (host in hosts) { + runSuspendCatching { + val response = client.get("$host$path") + if (!response.status.isSuccess()) { + throw SparkExitChainError( + "HTTP '${response.status.value}' for '$path'" + ) + } + response.bodyAsText() + }.onSuccess { return it }.onFailure { lastError = it } + } + throw lastError + } + + private fun status(o: JsonObject) = EsploraTxStatus( + confirmed = o["confirmed"]?.jsonPrimitive?.booleanOrNull == true, + blockHeight = (o["block_height"] as? JsonPrimitive)?.longOrNull?.toUInt(), + ) +} + +/** + * Reads node responses: mempool returns the RPC code only (`sendrawtransaction RPC error: {"code":-25}`), esplora the + * message too, and a package the per-transaction errors. + */ +object SparkExitBroadcastClassifier { + private val knownMessages = listOf( + "txn-already-in-mempool", + "txn-already-known", + "txn-same-nonwitness-data-in-mempool", + "already in block chain", + ) + private val notMatureMessages = listOf("non-BIP68-final", "non-final") + private val inputsMissingMessages = listOf("bad-txns-inputs-missingorspent", "missing-inputs", "missingorspent") + private val json = Json { ignoreUnknownKeys = true } + + fun single(status: Int, body: String): SparkExitBroadcastOutcome { + if (status in 200..299) return SparkExitBroadcastOutcome.Accepted + return unavailable(status) ?: classify(body) + } + + /** + * A package's outcome. An error on the step itself, [parentTxid], decides it. Missing inputs reported on the CPFP + * child alone (its fee funding or chained change) say nothing about the step, which is then retried. + */ + fun pkg(status: Int, body: String, parentTxid: String? = null): SparkExitBroadcastOutcome { + unavailable(status)?.let { return it } + val root = runCatching { json.parseToJsonElement(body) as? JsonObject }.getOrNull() + if (status !in 200..299 || root == null) return classify(body) + val message = (root["package_msg"] as? JsonPrimitive)?.contentOrNull + if (message == "success") return SparkExitBroadcastOutcome.Accepted + val results = (root["tx-results"] as? JsonObject)?.values?.mapNotNull { it as? JsonObject }.orEmpty() + // The step's own error decides, whatever its child reports and in whatever order the results come. + val own = results.firstOrNull { (it["txid"] as? JsonPrimitive)?.contentOrNull == parentTxid } + (own?.get("error") as? JsonPrimitive)?.contentOrNull?.let(::classify) + ?.takeIf { it != SparkExitBroadcastOutcome.Accepted } + ?.let { return it } + val outcomes = results.mapNotNull { result -> + val error = (result["error"] as? JsonPrimitive)?.contentOrNull ?: return@mapNotNull null + val txid = (result["txid"] as? JsonPrimitive)?.contentOrNull + val isChild = parentTxid != null && txid != null && txid != parentTxid + val outcome = classify(error) + if (isChild && outcome is SparkExitBroadcastOutcome.InputsMissing) { + SparkExitBroadcastOutcome.RetryLater(error) + } else { + outcome + } + } + if (outcomes.isEmpty()) { + return if (results.isEmpty()) { + SparkExitBroadcastOutcome.RetryLater( + body + ) + } else { + SparkExitBroadcastOutcome.Accepted + } + } + // A child reports missing inputs, or another error, when its parent is the one not yet mature. + return outcomes.firstOrNull { it is SparkExitBroadcastOutcome.NotMature } + ?: outcomes.firstOrNull { it is SparkExitBroadcastOutcome.Rejected } + ?: outcomes.firstOrNull { it != SparkExitBroadcastOutcome.Accepted } + ?: SparkExitBroadcastOutcome.Accepted + } + + /** A host that is down, rate limiting or behind a challenge page says nothing about the transaction. */ + private fun unavailable(status: Int): SparkExitBroadcastOutcome? = + if (status >= 500 || status == 429 || status == 403) { + SparkExitBroadcastOutcome.RetryLater( + "HTTP $status" + ) + } else { + null + } + + fun classify(text: String): SparkExitBroadcastOutcome = when { + knownMessages.any { it in text } || hasRpcCode(-27, text) -> SparkExitBroadcastOutcome.Accepted + notMatureMessages.any { it in text } -> SparkExitBroadcastOutcome.NotMature(text) + inputsMissingMessages.any { it in text } || hasRpcCode(-25, text) -> SparkExitBroadcastOutcome.InputsMissing( + text + ) + else -> SparkExitBroadcastOutcome.Rejected(text) + } + + /** The RPC code, also when the node's error sits JSON-escaped inside mempool's own error object. */ + private fun hasRpcCode(code: Int, text: String) = Regex("""code\\?"\s*:\s*$code\b""").containsMatchIn(text) +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt new file mode 100644 index 0000000000..99193a71eb --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -0,0 +1,535 @@ +package to.bitkit.repositories + +import breez_sdk_spark.CheckRecoverFundsResponse +import breez_sdk_spark.CpfpFundingKind +import breez_sdk_spark.CpfpSigner +import breez_sdk_spark.ExitLeafSelection +import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.PrepareRecoverFundsRequest +import breez_sdk_spark.PrepareRecoverFundsResponse +import breez_sdk_spark.RecoverFundsRequest +import breez_sdk_spark.RecoverFundsResponse +import breez_sdk_spark.RecoveryTransaction +import breez_sdk_spark.RecoveryVerdict +import breez_sdk_spark.SdkException +import breez_sdk_spark.SkippedLeafReason +import to.bitkit.ext.runSuspendCatching +import to.bitkit.models.safe +import to.bitkit.utils.Logger +import to.bitkit.utils.SignedTransactionId +import kotlin.time.Duration.Companion.minutes + +/** The SDK calls an exit makes. The Breez SDK in the app, a fake in tests. */ +interface SparkExitRecovering { + suspend fun prepare(request: PrepareRecoverFundsRequest): PrepareRecoverFundsResponse + suspend fun recover(request: RecoverFundsRequest, signer: CpfpSigner?): RecoverFundsResponse + suspend fun check(recovery: RecoverFundsResponse): CheckRecoverFundsResponse +} + +/** + * Moves an exit one step forward each tick: builds it once its fee funding confirms, broadcasts what is ready, + * rebuilds when the chain diverged, and finishes when everything confirmed. Without the SDK (a background start, or + * operators down at connect) it still broadcasts the stored, already signed transactions whose parents confirmed. + * Every built recovery is saved before anything of it is broadcast, and each broadcast as it happens, so a run killed + * partway, as background runs can be, never sends the same transactions again before they are due. + */ +class SparkExitDriver( + private val chain: SparkExitChain, + /** Null while the Spark SDK is not connected. */ + private val recovering: SparkExitRecovering?, + private val makeSigner: suspend () -> CpfpSigner, + private val save: (SparkExitRecord) -> Unit, + private val nowMillis: () -> Long, +) { + companion object { + private const val TAG = "SparkExitDriver" + + /** A ready transaction accepted in this generation is sent again after this long, in case a node dropped it. */ + val REBROADCAST_INTERVAL = 10.minutes + + /** After this many rejections of one transaction the progress screen shows the error. */ + const val REJECTIONS_TO_SURFACE = 3 + + /** The least time between two builds, so a divergence that persists does not rebuild every tick. */ + val REBUILD_INTERVAL = 10.minutes + + const val LOST_REASON = "Claimed by an older state" + + const val NO_LEAF_REASON = "No leaf can be exited" + } + + suspend fun tick(start: SparkExitRecord): SparkExitRecord { + var record = start + when (record.phase) { + SparkExitRecord.Phase.Done, is SparkExitRecord.Phase.Failed -> { + if (!record.isLeftoverSweepPending) return record + record = sweepLeftover(record) + save(record) + return record + } + is SparkExitRecord.Phase.AwaitingFunding, is SparkExitRecord.Phase.NeedsFunding -> { + val sdk = recovering ?: return record + val shortfall = record.fundingShortfallSats + // Nothing to fund when every leaf is recovered cooperatively. + if (shortfall != null) record = adoptFunding(record, shortfall) ?: return record + record = build(record, sdk) + } + SparkExitRecord.Phase.Running if record.isRebuilding -> { + // The diverged generation is never broadcast again; only a rebuild moves on from here. + val sdk = recovering ?: return record + if (!isRebuildDue(record)) return record + record = build(record, sdk) + } + SparkExitRecord.Phase.Running -> { + record = recovering?.let { check(record, it) } ?: broadcastWithoutSdk(record) + } + } + record = record.copy(claimableAtHeight = record.recovery?.let(SparkExitMath::claimableAtHeight)) + // The tick that ends the exit also sends its leftover fee funding to savings. + if (record.isLeftoverSweepPending) record = sweepLeftover(record) + save(record) + return record + } + + /** + * Adds every confirmed UTXO of new funding at the funding address once together they cover [requiredSats]; null + * while they do not. Several small payments count: the SDK spends every funding input it is given. + */ + private suspend fun adoptFunding(record: SparkExitRecord, requiredSats: ULong): SparkExitRecord? { + val first = record.funding.firstOrNull() ?: return null + val candidates = SparkExitMath.newFunding(chain.utxos(first.address), record) + val utxos = SparkExitMath.fundingTopUp(candidates, requiredSats) ?: return null + val adopted = utxos.map { first.copy(txid = it.txid, vout = it.vout, valueSats = it.value) } + val funding = if (record.funding.size == 1 && first.txid == null) adopted else record.funding + adopted + return record.copy(funding = funding) + } + + private suspend fun build(start: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { + val (record, prepared) = prepare(start, sdk) + if (prepared == null) { + // The last leaf lost on a tick that could not read the funding address ends here, still as lost. + val reason = if (record.isEveryLeafLost) LOST_REASON else NO_LEAF_REASON + val failed = record.copy(phase = SparkExitRecord.Phase.Failed(reason), isRebuilding = false) + return end(failed, record) + } + if (prepared.leaves.isEmpty()) { + // A leaf the chain could not be read for comes back on a later tick; finished leaves are not listed. + if (prepared.skipped.any { it.reason == SkippedLeafReason.Unverified }) return record + val ended = record.copy( + skippedLeafCount = maxOf(record.skippedLeafCount, prepared.skipped.size), + phase = if (record.recovery == null) { + SparkExitRecord.Phase.Failed("Nothing left to recover") + } else { + SparkExitRecord.Phase.Done + }, + ) + // Fee funding this exit no longer spends, such as a payment adopted just before, goes back to savings. + return end(ended, record) + } + val needsFunding = prepared.funding != null + val built = runSuspendCatching { + sdk.recover( + RecoverFundsRequest(prepared, if (needsFunding) record.fundingInputs else emptyList()), + if (needsFunding) makeSigner() else null, + ) + }.getOrElse { + // A leaf the SDK refuses to build is left behind, and the rest rebuilt on the next tick. + SparkExitUnexitable.parse(it)?.takeIf { refusal -> refusal.leafId in record.exitLeafIds }?.let { refusal -> + Logger.warn("Leaving behind Spark exit leaf '${refusal.leafId}': '${refusal.reason}'", context = TAG) + return record.leaveBehind(refusal.leafId, refusal.reason).copy(isRebuilding = true, lastBuildAt = null) + } + if (it !is SdkException.InsufficientCpfpFunds) throw it + // The SDK names the total its funding inputs must hold (CPFP cost plus change dust), not what is missing. + // After a Redo the inputs are partly spent, so what the address still holds decides the shortfall. + Logger.warn("Needs '${it.requiredSats}' sats of fee funding in total for the Spark exit", context = TAG) + val held = record.funding.firstOrNull()?.address?.let { address -> + runSuspendCatching { chain.utxos(address) }.getOrNull()?.let { SparkExitMath.heldSats(it, record) } + } + val needed = SparkExitMath.neededFunding(it.requiredSats, record.fundedSats, held) + return record.copy(phase = SparkExitRecord.Phase.NeedsFunding(needed)) + } + if (built.transactions.isEmpty()) { + // Cooperative leaves the operators could not co-sign now are tried again on the next tick. + if (built.failed.isNotEmpty()) return record.copy(failedLeafCount = built.failed.size) + return end(record.copy(phase = SparkExitRecord.Phase.Failed("Nothing to recover")), record) + } + val lost = record.lostLeaves(built) + if (lost.isNotEmpty()) return loseLeaves(record, lost) + val adopted = record.adopt(built, nowMillis()) + // Saved before any of it is broadcast, so a crash never leaves broadcast transactions without their record. + save(adopted) + Logger.info( + "Built Spark exit generation '${adopted.generation}' of '${built.transactions.size}' transactions", + context = TAG, + ) + return broadcastReady(adopted) + } + + private fun prepareRequest(record: SparkExitRecord, selection: ExitLeafSelection) = PrepareRecoverFundsRequest( + feeRateSatPerVbyte = record.feeRateSatPerVbyte, + fundingKind = CpfpFundingKind.P2wpkh, + destination = record.destination, + selection = selection, + ) + + /** + * Prepares the exit's leaves. A leaf the SDK refuses to exit, such as a fee-ladder leaf whose refund cannot pay its + * own fee at this rate, fails the whole prepare: it is dropped and the rest prepared again. When the refused leaf + * cannot be told, the leaves still recoverable are prepared instead, and the exit's leaves left out are dropped. + * The prepared response is null once no leaves remain. + */ + private suspend fun prepare( + start: SparkExitRecord, + sdk: SparkExitRecovering, + ): Pair { + var record = start + while (true) { + val ids = record.exitLeafIds + if (ids.isEmpty()) return record to null + val result = runSuspendCatching { sdk.prepare(prepareRequest(record, ExitLeafSelection.Specific(ids))) } + result.getOrNull()?.let { return record to it } + val error = requireNotNull(result.exceptionOrNull()) + val refusal = SparkExitUnexitable.parse(error) ?: throw error + Logger.warn("Leaving behind Spark exit leaf '${refusal.leafId}': '${refusal.reason}'", context = TAG) + if (refusal.leafId in ids) { + record = record.leaveBehind(refusal.leafId, refusal.reason) + continue + } + val prepared = sdk.prepare(prepareRequest(record, ExitLeafSelection.RecoverableOnly)) + val listed = prepared.leaves.map { it.leafId }.toSet() + ids.filter { it !in listed }.forEach { + record = record.leaveBehind(it, SparkExitUnexitable.NOT_RECOVERABLE) + } + return record to prepared + } + } + + /** + * Leaves the rebuild unadopted and drops [lost] from the exit: an older state of this wallet claimed them, and + * every rebuild would reproduce the same spent refund. The next tick rebuilds at once without them. + */ + private suspend fun loseLeaves(record: SparkExitRecord, lost: List): SparkExitRecord { + Logger.warn("Dropping Spark exit leaves '${lost.map { it.leafId }}' claimed by an older state", context = TAG) + val updated = record.copy(lostLeaves = record.lostLeaves + lost, isRebuilding = true, lastBuildAt = null) + if (updated.exitLeafIds.isNotEmpty()) return updated + return end(updated.copy(phase = SparkExitRecord.Phase.Failed(LOST_REASON), isRebuilding = false), updated) + } + + private suspend fun check(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { + val stored = record.recovery ?: return record.copy(phase = SparkExitRecord.Phase.AwaitingFunding(0uL)) + val checked = sdk.check(withConfirmations(stored)) + Logger.debug("Checked Spark exit generation '${record.generation}': '${checked.verdict}'", context = TAG) + val updated = record.copy(recovery = checked.recovery) + return when (checked.verdict) { + RecoveryVerdict.Valid -> broadcastReady(updated) + RecoveryVerdict.Done -> end(updated.copy(phase = SparkExitRecord.Phase.Done), updated) + is RecoveryVerdict.Redo -> { + Logger.warn( + "Rebuilding Spark exit diverged on-chain as generation '${record.generation + 1}'", + context = TAG, + ) + val rebuilding = updated.copy(isRebuilding = true) + save(rebuilding) + if (!isRebuildDue(rebuilding)) return rebuilding + build(rebuilding, sdk) + } + } + } + + /** + * Marks the next steps the chain host shows in a block as confirmed. The SDK asks the chain about a step only once + * the caller saw it in a block; otherwise it looks for who spent its input, which an Electrum-backed mempool, + * such as Spark's regtest, does not report. + */ + private suspend fun withConfirmations(recovery: RecoverFundsResponse): RecoverFundsResponse { + val confirmed = recovery.transactions + .filter { it.status is ExitTransactionStatus.Confirmed } + .map { it.txid } + .toMutableSet() + val transactions = recovery.transactions.map { tx -> + if (tx.txid in confirmed || !tx.dependsOn.all { it in confirmed }) return@map tx + val status = runSuspendCatching { chain.txStatus(tx.txid) }.getOrNull() + if (status?.confirmed != true) return@map tx + confirmed += tx.txid + tx.copy(status = ExitTransactionStatus.Confirmed(status.blockHeight)) + } + return recovery.copy(transactions = transactions) + } + + /** + * Sends what the ended exit left at its funding address to [SparkExitRecord.destination] in one transaction, once + * every UTXO there confirmed, at the exit's fee rate. Built and saved before it is sent, then sent again each tick + * until a node accepts it; not after a rejection. Dust is not sent. + */ + private suspend fun sweepLeftover(record: SparkExitRecord): SparkExitRecord { + val built = record.leftoverSweep + if (built?.txHex != null) { + if (built.isAccepted) { + val status = runSuspendCatching { chain.txStatus(requireNotNull(built.txid)) }.getOrNull() + if (status?.confirmed == true) return record.copy(leftoverSweep = built.copy(isConfirmed = true)) + } + // Sent again until it confirms; a node that already has it accepts it again. + return sendSweep(record, built, built.txHex) + } + val address = record.funding.firstOrNull()?.address ?: return record + val utxos = runSuspendCatching { chain.utxos(address) }.getOrNull() ?: return record + if (utxos.isEmpty()) return record.copy(leftover = emptyList()) + if (utxos.any { !it.status.confirmed }) return record + val inputs = utxos.map { SparkExitSweep.Input(it.txid, it.vout, it.value) } + val total = utxos.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + val plan = runSuspendCatching { SparkExitSweep.plan(inputs, record.destination, record.feeRateSatPerVbyte) } + .getOrElse { + Logger.error("Failed to plan the Spark exit leftover sweep", it, context = TAG) + return record + } + ?: return record.copy(leftoverSweep = SparkExitRecord.LeftoverSweep(null, null, total)) + val sweep = runSuspendCatching { + val signed = makeSigner().signPsbt(SparkExitSweep.psbt(plan, address)) + val hex = SparkExitSweep.signedTxHex(plan, signed) + SparkExitRecord.LeftoverSweep(SignedTransactionId.fromHex(hex), hex, plan.amountSats) + }.getOrElse { + Logger.error("Failed to build the Spark exit leftover sweep", it, context = TAG) + return record + } + val hex = requireNotNull(sweep.txHex) + val saved = record.copy(leftoverSweep = sweep) + save(saved) + return sendSweep(saved, sweep, hex) + } + + private suspend fun sendSweep( + record: SparkExitRecord, + sweep: SparkExitRecord.LeftoverSweep, + hex: String, + ): SparkExitRecord { + val outcome = chain.broadcastHex(hex) + Logger.info("Broadcast Spark exit leftover sweep '${sweep.txid}': '${outcome.summary}'", context = TAG) + return when (outcome) { + SparkExitBroadcastOutcome.Accepted -> record.copy(leftoverSweep = sweep.copy(isAccepted = true)) + is SparkExitBroadcastOutcome.Rejected -> record.copy(leftoverSweep = sweep.copy(rejection = outcome.reason)) + is SparkExitBroadcastOutcome.RetryLater, + is SparkExitBroadcastOutcome.NotMature, + is SparkExitBroadcastOutcome.InputsMissing, + -> record + } + } + + private fun isRebuildDue(record: SparkExitRecord): Boolean { + val last = record.lastBuildAt ?: return true + return nowMillis() - last >= REBUILD_INTERVAL.inWholeMilliseconds + } + + /** What is left at the funding address, null when it could not be read. */ + private suspend fun leftover(record: SparkExitRecord): List? { + val address = record.funding.firstOrNull()?.address ?: return emptyList() + return runSuspendCatching { chain.utxos(address) }.getOrNull() + ?.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) } + } + + /** + * [ended] with the leftover at its funding address, or [unchanged] while the address cannot be read: an exit that + * ended without its leftover read would never sweep it. + */ + private suspend fun end(ended: SparkExitRecord, unchanged: SparkExitRecord): SparkExitRecord { + val leftover = leftover(ended) ?: return unchanged + return ended.copy(leftover = leftover) + } + + private suspend fun broadcastReady(record: SparkExitRecord): SparkExitRecord { + var current = record + val recovery = current.recovery ?: return current + // Unverified: the SDK could not read its parent from the chain; nodes refuse it harmlessly if it is not final. + recovery.transactions + .filter { it.status == ExitTransactionStatus.Ready || it.status == ExitTransactionStatus.Unverified } + .filter { isDue(it.txid, current) } + // A ready step's parents are confirmed, as the SDK saw them. + .forEach { + current = broadcastAndSave(it, current, parentsConfirmed = it.status == ExitTransactionStatus.Ready) + } + return current + } + + /** + * Without the SDK: each unconfirmed transaction whose parents are confirmed on the chain host and whose relative + * timelock has matured, by the SDK's own rule. A stale one is refused by nodes as a conflict, and only the current + * generation is stored. A step whose input someone else spent is not sent again; the next SDK check rebuilds. + */ + private suspend fun broadcastWithoutSdk(record: SparkExitRecord): SparkExitRecord { + val recovery = record.recovery ?: return record + val tip = chain.tipHeight() + val statuses = recovery.transactions + .mapNotNull { tx -> (tx.status as? ExitTransactionStatus.Confirmed)?.let { tx.txid to it.blockHeight } } + .associate { (txid, height) -> txid to EsploraTxStatus(true, height) } + .toMutableMap() + suspend fun status(txid: String): EsploraTxStatus? { + if (txid !in statuses) statuses[txid] = runSuspendCatching { chain.txStatus(txid) }.getOrNull() + return statuses[txid] + } + var current = record + val transactions = recovery.transactions.map { tx -> + if (tx.status is ExitTransactionStatus.Confirmed) return@map tx + val own = status(tx.txid) + if (own?.confirmed == true) return@map tx.copy(status = ExitTransactionStatus.Confirmed(own.blockHeight)) + if (!tx.dependsOn.all { status(it)?.confirmed == true }) return@map tx + // A height the SDK already worked out still holds. + val known = (tx.status as? ExitTransactionStatus.WaitingForTimelock)?.spendableAtHeight + if (known != null && !SparkExitMath.isMature(known, tip)) return@map tx + if (tx.csvTimelockBlocks != null) { + val parents = SparkExitTxInputs.decode(tx.txHex)?.filter { it.relativeLockBlocks > 0u } + ?.map { it.prevTxid } ?: tx.dependsOn + val heights = parents.associateWith { parentHeight(it, status(it)) } + // A parent whose height is unknown leaves maturity unknown: wait. + val spendable = SparkExitMath.spendableAtHeight(tx, heights) ?: return@map tx + if (!SparkExitMath.isMature(spendable, tip)) { + return@map tx.copy(status = ExitTransactionStatus.WaitingForTimelock(spendable)) + } + } + if (isInputSpent(tx.txid, current)) return@map tx + if (isDue(tx.txid, current)) current = broadcastAndSave(tx, current, parentsConfirmed = true) + tx + } + return current.copy(recovery = recovery.copy(transactions = transactions)) + } + + /** A confirmed parent's height, read from the chain host when the stored confirmation carries none. */ + private suspend fun parentHeight(txid: String, known: EsploraTxStatus?): UInt? { + if (known?.confirmed != true) return null + return known.blockHeight ?: runSuspendCatching { chain.txStatus(txid) }.getOrNull()?.blockHeight + } + + private fun isInputSpent(txid: String, record: SparkExitRecord): Boolean = + record.broadcastLog.any { it.generation == record.generation && it.txid == txid && it.isInputSpent } + + private fun isDue(txid: String, record: SparkExitRecord): Boolean { + val last = record.broadcastLog + .firstOrNull { it.generation == record.generation && it.txid == txid } + ?: return true + return !last.isAccepted || nowMillis() - last.lastAttemptAt >= REBROADCAST_INTERVAL.inWholeMilliseconds + } + + private suspend fun broadcastAndSave( + tx: RecoveryTransaction, + record: SparkExitRecord, + parentsConfirmed: Boolean, + ): SparkExitRecord = broadcast(tx, record, parentsConfirmed).also(save) + + /** + * Sends [tx] and logs the outcome. With every parent confirmed, missing inputs mean someone else spent one first: + * the operators, which a rebuild recovers, or an older state of this wallet, which rebuilds keep reproducing. + */ + private suspend fun broadcast( + tx: RecoveryTransaction, + record: SparkExitRecord, + parentsConfirmed: Boolean, + ): SparkExitRecord { + val outcome = chain.broadcast(tx) + val isInputSpent = parentsConfirmed && outcome is SparkExitBroadcastOutcome.InputsMissing + Logger.info("Broadcast Spark exit '${tx.kind}' '${tx.txid}': '${outcome.summary}'", context = TAG) + val isAccepted = outcome == SparkExitBroadcastOutcome.Accepted + val rejection = if (outcome is SparkExitBroadcastOutcome.Rejected) 1 else 0 + val existing = record.broadcastLog.firstOrNull { it.generation == record.generation && it.txid == tx.txid } + val entry = existing?.copy( + attempts = existing.attempts + 1, + rejections = existing.rejections + rejection, + lastAttemptAt = nowMillis(), + lastOutcome = outcome.summary, + isAccepted = isAccepted, + isInputSpent = existing.isInputSpent || isInputSpent, + ) ?: SparkExitRecord.BroadcastAttempt( + generation = record.generation, + txid = tx.txid, + attempts = 1, + rejections = rejection, + lastAttemptAt = nowMillis(), + lastOutcome = outcome.summary, + isAccepted = isAccepted, + isInputSpent = isInputSpent, + ) + val log = if (existing == null) { + record.broadcastLog + entry + } else { + record.broadcastLog.map { if (it === existing) entry else it } + } + return record.copy(broadcastLog = log) + } +} + +/** The rejection to show on the progress screen once a transaction was refused several times. */ +val SparkExitRecord.surfacedRejection: String? + get() = broadcastLog.firstOrNull { + it.generation == generation && it.rejections >= SparkExitDriver.REJECTIONS_TO_SURFACE && !it.isAccepted + }?.lastOutcome + +/** Transaction ids of the CPFP children, which the SDK returns as hex only. */ +object SparkExitTxids { + fun cpfpChildTxids(recovery: RecoverFundsResponse): List = + recovery.transactions.mapNotNull { tx -> + tx.cpfpTxHex?.let { runCatching { SignedTransactionId.fromHex(it) }.getOrNull() } + } +} + +/** A leaf the SDK refused to exit, read from its untyped `SparkError`: `Leaf {id} cannot be exited: {reason}`. */ +object SparkExitUnexitable { + const val NOT_RECOVERABLE = "Not recoverable at this fee rate" + + private val LEAF = Regex("""Leaf (\S+?) cannot be exited""") + private const val MARKER = "cannot be exited" + + /** [leafId] is empty when the message names no leaf that can be read. */ + data class Refusal(val leafId: String, val reason: String) + + /** The refusal [error] reports, or null for any other error. */ + fun parse(error: Throwable): Refusal? { + if (error !is SdkException.SparkException) return null + val message = error.v1 + if (MARKER !in message) return null + return Refusal(LEAF.find(message)?.groupValues?.get(1).orEmpty(), message) + } +} + +/** The inputs of a raw transaction, for relative timelocks: what each spends and its BIP 68 block lock. */ +object SparkExitTxInputs { + private const val DISABLE_FLAG = 1L shl 31 + private const val TYPE_FLAG = 1L shl 22 + private const val VALUE_MASK = 0xffffL + + data class Input(val prevTxid: String, val vout: UInt, val sequence: Long) { + /** The relative lock in blocks, 0 when the input has none or a time-based one. */ + val relativeLockBlocks: UInt + get() = if (sequence and DISABLE_FLAG != 0L || sequence and TYPE_FLAG != 0L) { + 0u + } else { + (sequence and VALUE_MASK).toUInt() + } + } + + /** The inputs, with no relative lock before version 2 (BIP 68), or null when [hex] is not a transaction. */ + fun decode(hex: String): List? = runCatching { + val bytes = hex.hexToByteArray() + var offset = 0 + fun take(length: Int): ByteArray { + require(length >= 0 && offset + length <= bytes.size) + return bytes.copyOfRange(offset, offset + length).also { offset += length } + } + fun le(length: Int): Long = take( + length + ).foldIndexed(0L) { i, sum, b -> sum or ((b.toLong() and 0xff) shl (8 * i)) } + fun compactSize(): Int = when (val prefix = le(1).toInt()) { + 0xfd -> le(2).toInt() + 0xfe -> le(4).toInt() + 0xff -> error("Too many items") + else -> prefix + } + val version = le(4) + if (bytes[offset] == 0.toByte()) take(2) + val count = compactSize() + require(count > 0) + List(count) { + val prevTxid = take(32).reversedArray().toHexString() + val vout = le(4).toUInt() + take(compactSize()) + val sequence = le(4) + Input(prevTxid, vout, if (version >= 2) sequence else DISABLE_FLAG) + } + }.getOrNull() +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt new file mode 100644 index 0000000000..8779121101 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -0,0 +1,347 @@ +package to.bitkit.repositories + +import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.PrepareRecoverFundsResponse +import breez_sdk_spark.RecoverFundsResponse +import breez_sdk_spark.RecoveryTransaction +import breez_sdk_spark.RecoveryTxKind +import org.lightningdevkit.ldknode.Network +import to.bitkit.models.safe +import to.bitkit.utils.AppError +import to.bitkit.utils.BlockTimeHelpers +import java.math.BigInteger +import java.security.MessageDigest +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +/** + * The key that pays a Spark exit's CPFP fees. It derives from the wallet seed on an account no wallet of Bitkit's + * derives, so ldk-node never spends the funding UTXO or the CPFP change chained back to it. + */ +object SparkExitFundingKey { + /** The BIP84 account of the funding key, outside every account ldk-node and the sweep tools derive. */ + const val ACCOUNT = 7797 + + private const val WIF_LENGTH = 38 + private const val PAYLOAD_LENGTH = 34 + private const val SECRET_LENGTH = 32 + private const val COMPRESSED_FLAG: Byte = 0x01 + private const val ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + + data class Derived( + val address: String, + /** Compressed public key, hex, as `CpfpInput.P2wpkh` takes it. */ + val pubkey: String, + val secretKey: ByteArray, + ) + + class InvalidWif : AppError("Invalid WIF private key") + + fun path(index: Int, network: Network): String { + val coin = if (network == Network.BITCOIN) 0 else 1 + return "m/84'/$coin'/$ACCOUNT'/0/$index" + } + + /** The 32-byte secret of a compressed-key WIF: base58check, version byte first, `0x01` compression flag last. */ + fun secretKey(wif: String): ByteArray { + val decoded = base58Decode(wif) ?: throw InvalidWif() + if (decoded.size != WIF_LENGTH) throw InvalidWif() + val payload = decoded.copyOfRange(0, PAYLOAD_LENGTH) + val sha256 = MessageDigest.getInstance("SHA-256") + val checksum = sha256.digest(sha256.digest(payload)).copyOfRange(0, 4) + if (!checksum.contentEquals(decoded.copyOfRange(PAYLOAD_LENGTH, WIF_LENGTH))) throw InvalidWif() + if (payload[PAYLOAD_LENGTH - 1] != COMPRESSED_FLAG) throw InvalidWif() + return payload.copyOfRange(1, 1 + SECRET_LENGTH) + } + + internal fun base58Decode(text: String): ByteArray? { + var value = BigInteger.ZERO + for (char in text) { + val digit = ALPHABET.indexOf(char).takeIf { it >= 0 } ?: return null + value = value.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(digit.toLong())) + } + val bytes = value.toByteArray().dropWhile { it == 0.toByte() }.toByteArray() + val leadingZeros = text.takeWhile { it == '1' }.length + return ByteArray(leadingZeros) + bytes + } +} + +/** + * What an exit costs and returns, from a `prepareRecoverFunds` quote, next to Spark's balance when it was taken + * ([sparkBalanceSats]), so value the quote cannot exit is named rather than silently left out. + */ +data class SparkExitQuote(val prepared: PrepareRecoverFundsResponse, val sparkBalanceSats: ULong? = null) { + /** The value of the leaves the exit takes on-chain. */ + val exitSats: ULong get() = prepared.recoverableValueSats + + val networkFeeSats: ULong get() = prepared.totalFeeSats + + /** What savings gains overall: the exited value less every fee, those paid from the fee funding included. */ + val receiveSats: ULong get() = exitSats.safe() - networkFeeSats.safe() + + /** The on-chain payment that funds the CPFP fees, or 0 when every leaf is recovered cooperatively. */ + val fundingSats: ULong get() = prepared.funding?.singleUtxoSats ?: 0uL + + /** + * What the sweep and the cooperative recoveries pay to savings: [receiveSats] plus the fee funding the exit did + * not spend, which the sweep returns. + */ + val incomingSats: ULong get() = receiveSats.safe() + fundingSats.safe() + + val leftBehindSats: ULong get() = prepared.skipped.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() } + + val leafIds: List get() = prepared.leaves.map { it.leafId } + + /** + * What the quote cannot exit now: the leaves it skips, and Spark's balance beyond every leaf it lists, such as a + * counter-swap still unclaimed. Null when nothing. + */ + val unexitableSats: ULong? get() = SparkExitMath.unexitableSats(sparkBalanceSats, this) + + /** Spark's balance beyond every leaf the quote lists, skipped ones included. */ + val beyondLeavesSats: ULong? + get() { + val leaves = prepared.leaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() } + return SparkExitMath.outsideExitSats(leaves.safe() + leftBehindSats.safe(), sparkBalanceSats) + } + + /** Breez's rule: only exit when the value is more than its fees. */ + val isWorthExiting: Boolean get() = prepared.leaves.isNotEmpty() && exitSats > networkFeeSats +} + +object SparkExitMath { + /** The block time of Spark's regtest, which mines one every ~30 seconds. */ + private val REGTEST_BLOCK_TIME = 30.seconds + + private val BLOCK_TIME = 10.minutes + + /** The countdown target: the latest block at which a timelocked step of the exit can confirm. */ + fun claimableAtHeight(recovery: RecoverFundsResponse): UInt? = recovery.transactions + .mapNotNull { (it.status as? ExitTransactionStatus.WaitingForTimelock)?.spendableAtHeight } + .maxOrNull() + + /** The next height above [tip] at which a timelocked step matures, for the reminder. */ + fun nextMaturityHeight(recovery: RecoverFundsResponse, tip: UInt): UInt? = recovery.transactions + .mapNotNull { (it.status as? ExitTransactionStatus.WaitingForTimelock)?.spendableAtHeight } + .filter { it > tip } + .minOrNull() + + /** Whether every refund's timelock is behind it: none still waits for its parents or its height. */ + fun areTimelocksMatured(transactions: List): Boolean { + val refunds = transactions.filter { it.kind == RecoveryTxKind.REFUND } + return refunds.isNotEmpty() && refunds.none { + it.status == ExitTransactionStatus.WaitingForDependencies || + it.status is ExitTransactionStatus.WaitingForTimelock + } + } + + /** + * The first block that can include [tx], as the SDK computes it: for each input with a BIP 68 block lock, the + * confirmation height of the transaction it spends plus the lock, the highest of them. [parentHeights] holds the + * heights read for the parents, null where unknown, which leaves the whole step unknown. A transaction that cannot + * be decoded counts [RecoveryTransaction.csvTimelockBlocks] from each of its `dependsOn`. Zero when nothing is + * locked. + */ + fun spendableAtHeight(tx: RecoveryTransaction, parentHeights: Map): UInt? { + val locks = SparkExitTxInputs.decode(tx.txHex) + ?.filter { it.relativeLockBlocks > 0u } + ?.map { it.prevTxid to it.relativeLockBlocks } + ?: tx.dependsOn.map { it to (tx.csvTimelockBlocks ?: 0u) } + var spendable = 0u + for ((parent, blocks) in locks) { + val height = parentHeights[parent] ?: return null + spendable = maxOf(spendable, height + blocks) + } + return spendable + } + + /** Nodes accept a transaction that would be valid in the next block. */ + fun isMature(spendableAtHeight: UInt, tip: UInt): Boolean = tip + 1u >= spendableAtHeight + + /** The steps already in a block, for progress. */ + fun confirmedCount(recovery: RecoverFundsResponse): Int = + recovery.transactions.count { it.status is ExitTransactionStatus.Confirmed } + + /** + * UTXOs at the funding address that are new funding: neither an adopted input nor change a CPFP child of this or + * an earlier generation chained there. + */ + fun newFunding(utxos: List, record: SparkExitRecord): List { + val adopted = record.funding.mapNotNull { f -> f.txid?.let { "$it:${f.vout ?: 0u}" } }.toSet() + val chained = (record.recovery?.let(SparkExitTxids::cpfpChildTxids).orEmpty() + record.earlierCpfpTxids).toSet() + return utxos.filter { "${it.txid}:${it.vout}" !in adopted && it.txid !in chained } + } + + /** The confirmed value at the funding address that is not new funding: unspent inputs and their CPFP change. */ + fun heldSats(utxos: List, record: SparkExitRecord): ULong { + val fresh = newFunding(utxos, record).toSet() + return utxos + .filter { it.status.confirmed && it !in fresh } + .fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + } + + /** + * The funding a rebuild needs in all, from the SDK's [requiredSats]: the total its inputs must hold, not the extra. + * What is still [held] at the address counts, so the shortfall is `requiredSats - held`, at least 1; without a + * reading of the address, `max(requiredSats, fundedSats)`, right for a first build where nothing is spent yet. + */ + fun neededFunding(requiredSats: ULong, fundedSats: ULong, held: ULong?): ULong { + if (held == null) return maxOf(requiredSats, fundedSats) + val missing = if (requiredSats > held) requiredSats - held else 0uL + return fundedSats.safe() + maxOf(missing, 1uL).safe() + } + + /** The skipped leaves of [quote] plus Spark's [balanceSats] beyond every leaf it lists, or null when nothing. */ + fun unexitableSats(balanceSats: ULong?, quote: SparkExitQuote): ULong? { + val beyond = quote.copy(sparkBalanceSats = balanceSats).beyondLeavesSats ?: 0uL + return (quote.leftBehindSats.safe() + beyond.safe()).takeIf { it > 0uL } + } + + /** Spark's balance beyond the exit's leaves while it still counts them, or null. */ + fun outsideExitSats(leafTotalSats: ULong?, balanceSats: ULong?): ULong? { + if (leafTotalSats == null || balanceSats == null || balanceSats <= leafTotalSats) return null + return balanceSats - leafTotalSats + } + + /** + * What progress shows while the exit still needs fee funding, or null when it does not. [utxos] is what the funding + * address holds, null when it could not be read. A payment from savings that has not confirmed, or new funding + * covering the shortfall that has not, is waited for; only what is still missing is asked for, at least dust. + */ + fun fundingState(record: SparkExitRecord, utxos: List?): SparkExitFundingState? { + val shortfall = record.fundingShortfallSats ?: return null + record.fundingPaymentTxid?.let { txid -> + val isAdopted = record.funding.any { it.txid == txid } + val isConfirmed = utxos?.any { it.txid == txid && it.status.confirmed } == true + if (!isAdopted && !isConfirmed) return SparkExitFundingState.Paid(txid) + } + val fresh = utxos?.let { newFunding(it, record) }.orEmpty() + val seen = fresh.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + if (fresh.isNotEmpty() && seen >= shortfall) { + // Covered: waiting for it to confirm, or for the next tick to take it once it has. + val txid = (fresh.firstOrNull { !it.status.confirmed } ?: fresh.first()).txid + return SparkExitFundingState.Seen(txid) + } + // Nodes refuse an output under its dust limit, so a smaller remainder is asked as the funding output's dust. + return SparkExitFundingState.Ask(maxOf(shortfall - seen, FUNDING_DUST_SATS), seen, shortfall) + } + + /** What reached the funding address against [requiredSats], once some but not all of it did; else null. */ + fun partialFunding(receivedSats: ULong, requiredSats: ULong): SparkExitPartialFunding? { + if (receivedSats == 0uL || receivedSats >= requiredSats) return null + return SparkExitPartialFunding( + receivedSats, + requiredSats, + maxOf(requiredSats - receivedSats, FUNDING_DUST_SATS) + ) + } + + /** Every confirmed UTXO of new funding, the largest first, once together they cover [requiredSats]. */ + fun fundingTopUp(utxos: List, requiredSats: ULong): List? { + val confirmed = utxos.filter { it.status.confirmed }.sortedByDescending { it.value } + if (confirmed.isEmpty()) return null + val total = confirmed.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + return confirmed.takeIf { total >= requiredSats } + } + + /** About how long until [height]. */ + fun timeUntil(height: UInt, tip: UInt, network: Network): Duration { + val blockTime = if (network == Network.REGTEST) REGTEST_BLOCK_TIME else BLOCK_TIME + return blockTime * BlockTimeHelpers.blocksRemaining(height, tip) + } + + /** The dust limit of the funding address's P2WPKH output, the least a top-up can pay. */ + const val FUNDING_DUST_SATS = 294uL + + /** About how many blocks after a step matures the operators may publish their own version of it. */ + private const val OPERATOR_WINDOW_BLOCKS = 50 + + /** + * How many blocks a matured refund leads an older state's refund of the same leaf by, the hard limit while the + * operators are down. + */ + private const val OLDER_STATE_LEAD_BLOCKS = 100 + + /** Blocks after a step matures before Bitkit warns that it was not published: 38 of the 50 are left to publish. */ + private const val WARN_GRACE_BLOCKS = 12 + + /** + * About how long until a step can be published: zero while one already can (its parents confirmed, and ready or + * its timelock behind [tip]) or when it is unknown, else until the next step matures. + */ + fun untilNextMaturity(recovery: RecoverFundsResponse?, tip: UInt?, network: Network): Duration { + if (recovery == null || tip == null) return Duration.ZERO + val height: UInt = tip + val confirmed = recovery.transactions.filter { it.status is ExitTransactionStatus.Confirmed }.map { it.txid } + val isPublishable = recovery.transactions.any { tx -> + val maturesAt = (tx.status as? ExitTransactionStatus.WaitingForTimelock)?.spendableAtHeight + val isDue = tx.status == ExitTransactionStatus.Ready || tx.status == ExitTransactionStatus.Unverified || + (maturesAt != null && maturesAt <= height) + isDue && tx.dependsOn.all { it in confirmed } + } + if (isPublishable) return Duration.ZERO + val maturity = nextMaturityHeight(recovery, height) ?: return Duration.ZERO + return timeUntil(maturity, height, network) + } + + /** + * How long a matured step is ours to publish: the smaller of the operators' window and an older state's lead, about + * 8 hours on mainnet, 25 minutes on Spark's regtest. + */ + fun operatorWindow(network: Network): Duration = + (if (network == Network.REGTEST) REGTEST_BLOCK_TIME else BLOCK_TIME) * + minOf(OPERATOR_WINDOW_BLOCKS, OLDER_STATE_LEAD_BLOCKS) + + /** + * When Bitkit warns that the background run fell behind, and the deadline it names: [untilMaturity] is how long + * until the next step matures, zero while steps already wait to be published. The deadline is the end of the + * window; the warning comes 12 blocks after maturity, well before the operators or an older state may publish. + */ + fun deadline(untilMaturity: Duration, network: Network): SparkExitDeadline { + val grace = blockTime(network) * WARN_GRACE_BLOCKS + return SparkExitDeadline(warnIn = untilMaturity + grace, deadlineIn = untilMaturity + operatorWindow(network)) + } + + private fun blockTime(network: Network) = if (network == Network.REGTEST) REGTEST_BLOCK_TIME else BLOCK_TIME + + /** + * The funding key index of the next exit: past the one the last exit took ([kept]), and past the [stored] record's, + * which covers exits started before the index was kept. + */ + fun nextFundingIndex(kept: Int?, stored: SparkExitRecord?): UInt { + val pastStored = stored?.funding?.maxOfOrNull { it.index + 1u } ?: 0u + return maxOf(kept?.toUInt() ?: 0u, pastStored) + } + + /** Savings can pay the fee funding when its spendable balance covers the funding and the payment's own fee. */ + fun canFundFromSavings(spendableSats: ULong, fundingSats: ULong, paymentFeeSats: ULong): Boolean = + fundingSats > 0uL && spendableSats >= fundingSats.safe() + paymentFeeSats.safe() +} + +/** The fee funding an exit still needs, as progress shows it. */ +sealed interface SparkExitFundingState { + /** Savings paid it in [txid], which has not confirmed yet. */ + data class Paid(val txid: String) : SparkExitFundingState + + /** A payment covering it, [txid] among them, was seen and waits to confirm. */ + data class Seen(val txid: String) : SparkExitFundingState + + /** + * [sats] are still missing at the funding address, at least dust, after [receivedSats] of new funding seen there + * against a shortfall of [requiredSats]. + */ + data class Ask( + val sats: ULong, + val receivedSats: ULong = 0uL, + val requiredSats: ULong = sats, + ) : SparkExitFundingState { + val partial: SparkExitPartialFunding? get() = SparkExitMath.partialFunding(receivedSats, requiredSats) + } +} + +/** A funding payment short of the need: [receivedSats] of [requiredSats] arrived, [missingSats] (at least dust) due. */ +data class SparkExitPartialFunding(val receivedSats: ULong, val requiredSats: ULong, val missingSats: ULong) + +/** When to warn that the exit fell behind, and when its next step's operator window closes, both from now. */ +data class SparkExitDeadline(val warnIn: Duration, val deadlineIn: Duration) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt new file mode 100644 index 0000000000..541f972963 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -0,0 +1,788 @@ +package to.bitkit.repositories + +import breez_sdk_spark.CooperativeRecoveryError +import breez_sdk_spark.CooperativeRecoveryFailure +import breez_sdk_spark.CpfpInput +import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.RecoverFundsLeaf +import breez_sdk_spark.RecoverFundsResponse +import breez_sdk_spark.RecoveryMethod +import breez_sdk_spark.RecoveryTransaction +import breez_sdk_spark.RecoveryTxKind +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import to.bitkit.models.safe +import to.bitkit.utils.AppError +import java.io.File +import java.nio.file.Files +import java.nio.file.StandardCopyOption + +/** + * Everything a Spark emergency exit needs to continue after a restart. The SDK keeps none of it: the signed + * recovery, the request it came from, how its fees were funded and what this device already broadcast. Times are + * epoch milliseconds. The JSON shape is shared with Bitkit iOS. + */ +data class SparkExitRecord( + val version: Int = CURRENT_VERSION, + val network: String, + val createdAt: Long, + val phase: Phase, + val feeRateSatPerVbyte: ULong, + val destination: String, + /** The leaves of the quote the user confirmed; every rebuild selects exactly these. */ + val leafIds: List, + val funding: List, + /** + * Bumped on every rebuild. Broadcasts are logged per generation and a rebuilt recovery replaces the old one + * entirely, so older hex is never sent again. + */ + val generation: Int = 0, + val recovery: RecoverFundsResponse? = null, + val broadcastLog: List = emptyList(), + val transferId: String? = null, + /** What reaches savings: the exited value less the fees paid out of it, plus the unspent fee funding. */ + val expectedSats: ULong, + val claimableAtHeight: UInt? = null, + val leftover: List = emptyList(), + val skippedLeafCount: Int = 0, + /** Cooperative leaves the last build could not recover. */ + val failedLeafCount: Int = 0, + /** Set and saved before a rebuild, so nothing of the diverged generation is broadcast while it is replaced. */ + val isRebuilding: Boolean = false, + val lastBuildAt: Long? = null, + /** The value of the quote's leaves, to show what Spark holds outside the exit. */ + val leafTotalSats: ULong? = null, + /** The CPFP child txids of replaced generations, whose change at the funding address is not new funding. */ + val earlierCpfpTxids: List = emptyList(), + /** The sweep of [leftover] to [destination] once the exit ended. */ + val leftoverSweep: LeftoverSweep? = null, + /** + * Per step txid, how many rebuilds in a row reproduced a step whose input was already spent. At two, an older + * state of this wallet claimed its leaf, which no rebuild can recover. + */ + val spentStepStrikes: Map = emptyMap(), + /** The payment from savings that funded the exit, kept so progress never asks for it again while it confirms. */ + val fundingPaymentTxid: String? = null, + /** Leaves an older state of this wallet claimed on-chain; builds leave them out. */ + val lostLeaves: List = emptyList(), + /** The user opened the result of an exit that failed or lost leaves, so Emergency exit may start a new one. */ + val isResultSeen: Boolean = false, + /** Leaves a rebuild could not exit, such as a fee-ladder leaf whose refund cannot pay its fee; left on Spark. */ + val leftBehindLeaves: List = emptyList(), +) { + companion object { + const val CURRENT_VERSION = 1 + + /** Rebuilds in a row that reproduce a spent step before its leaf counts as claimed by an older state. */ + const val LOST_AFTER_STRIKES = 2 + } + + sealed interface Phase { + /** Waiting for confirmed fee funding of [requiredSats] in all at the funding address before the first build. */ + data class AwaitingFunding(val requiredSats: ULong) : Phase + + /** Built and being driven to the chain. */ + data object Running : Phase + + /** A rebuild needs fee funding of [requiredSats] in all, more than the funding address received so far. */ + data class NeedsFunding(val requiredSats: ULong) : Phase + + data object Done : Phase + + data class Failed(val reason: String) : Phase + + val requiredFundingSats: ULong? + get() = when (this) { + is AwaitingFunding -> requiredSats + is NeedsFunding -> requiredSats + else -> null + } + } + + data class Funding( + /** The last path component under the funding key's account. */ + val index: UInt, + val address: String, + val pubkey: String, + val txid: String? = null, + val vout: UInt? = null, + val valueSats: ULong? = null, + ) { + val input: CpfpInput? + get() { + if (txid == null || vout == null || valueSats == null) return null + return CpfpInput.P2wpkh(txid, vout, valueSats, pubkey) + } + } + + data class BroadcastAttempt( + val generation: Int, + val txid: String, + val attempts: Int, + val rejections: Int, + val lastAttemptAt: Long, + val lastOutcome: String, + val isAccepted: Boolean, + /** Its parents confirmed but an input was already spent: the keyless pass stops sending it. */ + val isInputSpent: Boolean = false, + ) + + data class Leftover( + val txid: String, + val vout: UInt, + val valueSats: ULong, + ) + + data class LostLeaf(val leafId: String, val valueSats: ULong) + + data class LeftBehindLeaf(val leafId: String, val valueSats: ULong, val reason: String) + + /** A built sweep of the leftover, saved before it is sent; a null [txid] means it was dust and nothing went. */ + data class LeftoverSweep( + val txid: String?, + val txHex: String?, + val valueSats: ULong, + val isAccepted: Boolean = false, + val rejection: String? = null, + val isConfirmed: Boolean = false, + ) + + /** The leftover still has to be swept: not built yet, or built and neither confirmed nor rejected. */ + val isLeftoverSweepPending: Boolean + get() { + if (leftover.isEmpty()) return false + val sweep = leftoverSweep ?: return true + return sweep.txid != null && sweep.rejection == null && !sweep.isConfirmed + } + + /** + * Emergency exit opens progress, not a new exit, while this one runs and until its leftover fee funding is swept + * and confirmed, or kept as dust. A rejected sweep keeps it too: progress names the address the leftover is at. + * An exit that failed or lost leaves keeps it until the user opened it once. + */ + val showsResult: Boolean + get() = isActive || isLeftoverSweepPending || (leftover.isNotEmpty() && leftoverSweep?.rejection != null) || + hasUnseenResult + + /** The exit ended failed or with leaves lost, and the user has not opened its result yet. */ + val hasUnseenResult: Boolean + get() = !isActive && (phase is Phase.Failed || lostSats > 0uL) && !isResultSeen + + /** Background runs and the foreground loop keep going while the exit runs and until its leftover is swept. */ + val needsDriving: Boolean get() = isActive || isLeftoverSweepPending + + val isActive: Boolean + get() = when (phase) { + is Phase.AwaitingFunding, Phase.Running, is Phase.NeedsFunding -> true + Phase.Done, is Phase.Failed -> false + } + + val fundingInputs: List get() = funding.mapNotNull { it.input } + + /** The funding key index of this exit; records from before exits had their own index hold 0. */ + val fundingIndex: UInt get() = funding.firstOrNull()?.index ?: 0u + + /** The leaves builds select: the quote's, less those an older state claimed and those that cannot be exited. */ + val exitLeafIds: List + get() = leafIds - (lostLeaves.map { it.leafId } + leftBehindLeaves.map { it.leafId }).toSet() + + /** Every leaf of the exit was claimed by an older state, none left behind. */ + val isEveryLeafLost: Boolean + get() = lostLeaves.isNotEmpty() && lostLeaves.map { it.leafId }.containsAll(leafIds) + + val lostSats: ULong get() = lostLeaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() } + + val leftBehindLeafSats: ULong get() = leftBehindLeaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() } + + /** Leaves [leafId] on Spark for [reason], valued from the current recovery, else 0 before the first build. */ + fun leaveBehind(leafId: String, reason: String): SparkExitRecord = + copy(leftBehindLeaves = leftBehindLeaves + LeftBehindLeaf(leafId, leafValueSats(leafId), reason)) + + /** What the exit knows of [leafId]'s value, from its current recovery, else 0. */ + fun leafValueSats(leafId: String): ULong = recovery?.leaves?.firstOrNull { it.leafId == leafId }?.valueSats ?: 0uL + + val fundedSats: ULong get() = funding.fold(0uL) { sum, f -> sum.safe() + (f.valueSats ?: 0uL).safe() } + + /** What the funding address still has to receive before the exit can build, or null when nothing is missing. */ + val fundingShortfallSats: ULong? + get() { + val required = phase.requiredFundingSats ?: return null + val shortfall = required.safe() - fundedSats.safe() + return shortfall.takeIf { it > 0uL } + } + + /** Starts a new generation from a fresh build, forgetting what was broadcast for the previous one. */ + fun adopt(built: RecoverFundsResponse, atMillis: Long): SparkExitRecord = copy( + spentStepStrikes = spentStepStrikes(built), + earlierCpfpTxids = (earlierCpfpTxids + recovery?.let(SparkExitTxids::cpfpChildTxids).orEmpty()).distinct(), + generation = generation + 1, + recovery = built, + broadcastLog = emptyList(), + phase = Phase.Running, + isRebuilding = false, + lastBuildAt = atMillis, + failedLeafCount = built.failed.size, + ) + + /** + * The strikes after adopting [built]: a step of it that had its input spent in the generation it replaces gets one + * more; every other step drops out. + */ + fun spentStepStrikes(built: RecoverFundsResponse): Map { + val spent = broadcastLog.filter { it.generation == generation && it.isInputSpent }.map { it.txid }.toSet() + return built.transactions + .filter { it.txid in spent } + .associate { it.txid to (spentStepStrikes[it.txid] ?: 0) + 1 } + } + + /** The leaves [built] would lose again: a refund of an exiting leaf reproduced with its input spent twice. */ + fun lostLeaves(built: RecoverFundsResponse): List { + val strikes = spentStepStrikes(built) + val values = (recovery?.leaves.orEmpty() + built.leaves).associate { it.leafId to it.valueSats } + return built.transactions + .filter { it.kind == RecoveryTxKind.REFUND && (strikes[it.txid] ?: 0) >= LOST_AFTER_STRIKES } + .mapNotNull { it.nodeId?.takeIf { id -> id in exitLeafIds } } + .distinct() + .map { LostLeaf(it, values[it] ?: 0uL) } + } +} + +/** + * Reads and writes the exit record of one wallet. Writes go to a temporary file first and replace the record in one + * move, so a crash never leaves half a record. Files in the app's storage are readable after the first unlock, so + * the background worker can drive the exit while the device is locked. + */ +class SparkExitStore(private val file: File) { + fun load(): SparkExitRecord? { + if (!file.exists()) return null + return SparkExitJson.decode(file.readText()) + } + + /** Whether an exit runs, false when the record is missing or unreadable. */ + fun isActive(): Boolean = runCatching { load()?.isActive }.getOrNull() == true + + /** Moves an unreadable record out of the way, keeping it for support. */ + fun setAside(nowMillis: Long) { + val aside = File(file.parentFile, "${file.nameWithoutExtension}.unreadable-$nowMillis.json") + Files.move(file.toPath(), aside.toPath(), StandardCopyOption.REPLACE_EXISTING) + } + + fun save(record: SparkExitRecord) { + file.parentFile?.mkdirs() + val temp = File(file.parentFile, "${file.name}.tmp") + temp.writeText(SparkExitJson.encode(record)) + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } + + fun delete() { + file.delete() + } +} + +class SparkExitFormatError(message: String) : AppError(message) + +class SparkExitUnsupportedVersion(val version: Int) : AppError("Unsupported Spark exit record version '$version'") + +/** + * The exit record as JSON. The record's own fields follow Swift's synthesized `Codable` (camelCase, an enum case as + * `{"running":{}}`, absent optionals left out), and `recovery` follows spark-sdk 0.27.2's serde shape: snake_case + * fields, explicit nulls and externally tagged enums (`"Ready"`, `{"Confirmed":{"block_height":120}}`), so a stored + * recovery is readable by the Breez CLI's `check-recover-funds`. Built by hand so the app's `Json` settings cannot + * change it. + */ +object SparkExitJson { + private val json = Json { ignoreUnknownKeys = true } + + fun encode(record: SparkExitRecord): String = recordToJson(record).toString() + + fun decode(text: String): SparkExitRecord { + val root = json.parseToJsonElement(text).jsonObject + val version = root.int("version") + if (version != SparkExitRecord.CURRENT_VERSION) throw SparkExitUnsupportedVersion(version) + return recordFromJson(root) + } + + fun encodeRecovery(recovery: RecoverFundsResponse): String = recoveryToJson(recovery).toString() + + fun decodeRecovery(text: String): RecoverFundsResponse = + recoveryFromJson(json.parseToJsonElement(text).jsonObject) + + private fun recordToJson(r: SparkExitRecord) = buildJsonObject { + put("version", r.version) + put("network", r.network) + put("createdAt", r.createdAt) + put("phase", phaseToJson(r.phase)) + put("feeRateSatPerVbyte", r.feeRateSatPerVbyte.toLong()) + put("destination", r.destination) + put("leafIds", buildJsonArray { r.leafIds.forEach { add(JsonPrimitive(it)) } }) + put( + "funding", + buildJsonArray { + r.funding.forEach { + add( + buildJsonObject { + put("index", it.index.toLong()) + put("address", it.address) + put("pubkey", it.pubkey) + it.txid?.let { txid -> put("txid", txid) } + it.vout?.let { vout -> put("vout", vout.toLong()) } + it.valueSats?.let { value -> put("valueSats", value.toLong()) } + }, + ) + } + }, + ) + put("generation", r.generation) + r.recovery?.let { put("recovery", recoveryToJson(it)) } + put( + "broadcastLog", + buildJsonArray { + r.broadcastLog.forEach { + add( + buildJsonObject { + put("generation", it.generation) + put("txid", it.txid) + put("attempts", it.attempts) + put("rejections", it.rejections) + put("lastAttemptAt", it.lastAttemptAt) + put("lastOutcome", it.lastOutcome) + put("isAccepted", it.isAccepted) + if (it.isInputSpent) put("isInputSpent", true) + }, + ) + } + }, + ) + r.transferId?.let { put("transferId", it) } + put("expectedSats", r.expectedSats.toLong()) + r.claimableAtHeight?.let { put("claimableAtHeight", it.toLong()) } + put( + "leftover", + buildJsonArray { + r.leftover.forEach { + add( + buildJsonObject { + put("txid", it.txid) + put("vout", it.vout.toLong()) + put("valueSats", it.valueSats.toLong()) + }, + ) + } + }, + ) + put("skippedLeafCount", r.skippedLeafCount) + put("failedLeafCount", r.failedLeafCount) + put("isRebuilding", r.isRebuilding) + r.lastBuildAt?.let { put("lastBuildAt", it) } + r.leafTotalSats?.let { put("leafTotalSats", it.toLong()) } + if (r.earlierCpfpTxids.isNotEmpty()) { + put("earlierCpfpTxids", buildJsonArray { r.earlierCpfpTxids.forEach { add(JsonPrimitive(it)) } }) + } + r.leftoverSweep?.let { sweep -> + put( + "leftoverSweep", + buildJsonObject { + sweep.txid?.let { put("txid", it) } + sweep.txHex?.let { put("txHex", it) } + put("valueSats", sweep.valueSats.toLong()) + put("isAccepted", sweep.isAccepted) + sweep.rejection?.let { put("rejection", it) } + if (sweep.isConfirmed) put("isConfirmed", true) + }, + ) + } + r.fundingPaymentTxid?.let { put("fundingPaymentTxid", it) } + if (r.isResultSeen) put("isResultSeen", true) + if (r.spentStepStrikes.isNotEmpty()) { + put( + "spentStepStrikes", + buildJsonObject { r.spentStepStrikes.forEach { (txid, strikes) -> put(txid, strikes) } }, + ) + } + if (r.leftBehindLeaves.isNotEmpty()) { + put( + "leftBehindLeaves", + buildJsonArray { + r.leftBehindLeaves.forEach { + add( + buildJsonObject { + put("leafId", it.leafId) + put("valueSats", it.valueSats.toLong()) + put("reason", it.reason) + }, + ) + } + }, + ) + } + if (r.lostLeaves.isNotEmpty()) { + put( + "lostLeaves", + buildJsonArray { + r.lostLeaves.forEach { + add( + buildJsonObject { + put("leafId", it.leafId) + put("valueSats", it.valueSats.toLong()) + }, + ) + } + }, + ) + } + } + + private fun recordFromJson(o: JsonObject) = SparkExitRecord( + version = o.int("version"), + network = o.string("network"), + createdAt = o.millis("createdAt"), + phase = phaseFromJson(o.getValue("phase")), + feeRateSatPerVbyte = o.ulong("feeRateSatPerVbyte"), + destination = o.string("destination"), + leafIds = o.array("leafIds").map { it.jsonPrimitive.content }, + funding = o.array("funding").map { + val f = it.jsonObject + SparkExitRecord.Funding( + index = f.ulong("index").toUInt(), + address = f.string("address"), + pubkey = f.string("pubkey"), + txid = f.stringOrNull("txid"), + vout = f.ulongOrNull("vout")?.toUInt(), + valueSats = f.ulongOrNull("valueSats"), + ) + }, + generation = o.intOrNull("generation") ?: 0, + recovery = o.objectOrNull("recovery")?.let(::recoveryFromJson), + broadcastLog = o.arrayOrEmpty("broadcastLog").map { + val b = it.jsonObject + SparkExitRecord.BroadcastAttempt( + generation = b.int("generation"), + txid = b.string("txid"), + attempts = b.int("attempts"), + rejections = b.intOrNull("rejections") ?: 0, + lastAttemptAt = b.millis("lastAttemptAt"), + lastOutcome = b.string("lastOutcome"), + isAccepted = b.booleanOrNull("isAccepted") ?: false, + isInputSpent = b.booleanOrNull("isInputSpent") ?: false, + ) + }, + transferId = o.stringOrNull("transferId"), + expectedSats = o.ulong("expectedSats"), + claimableAtHeight = o.ulongOrNull("claimableAtHeight")?.toUInt(), + leftover = o.arrayOrEmpty("leftover").map { + val l = it.jsonObject + SparkExitRecord.Leftover(l.string("txid"), l.ulong("vout").toUInt(), l.ulong("valueSats")) + }, + skippedLeafCount = o.intOrNull("skippedLeafCount") ?: 0, + failedLeafCount = o.intOrNull("failedLeafCount") ?: 0, + isRebuilding = o.booleanOrNull("isRebuilding") ?: false, + lastBuildAt = o.millisOrNull("lastBuildAt"), + leafTotalSats = o.ulongOrNull("leafTotalSats"), + earlierCpfpTxids = o.arrayOrEmpty("earlierCpfpTxids").map { it.jsonPrimitive.content }, + leftoverSweep = o.objectOrNull("leftoverSweep")?.let { + SparkExitRecord.LeftoverSweep( + txid = it.stringOrNull("txid"), + txHex = it.stringOrNull("txHex"), + valueSats = it.ulong("valueSats"), + isAccepted = it.booleanOrNull("isAccepted") ?: false, + rejection = it.stringOrNull("rejection"), + isConfirmed = it.booleanOrNull("isConfirmed") ?: false, + ) + }, + fundingPaymentTxid = o.stringOrNull("fundingPaymentTxid"), + isResultSeen = o.booleanOrNull("isResultSeen") ?: false, + spentStepStrikes = o.objectOrNull("spentStepStrikes") + ?.mapValues { it.value.jsonPrimitive.content.toInt() } + .orEmpty(), + lostLeaves = o.arrayOrEmpty("lostLeaves").map { + val l = it.jsonObject + SparkExitRecord.LostLeaf(l.string("leafId"), l.ulong("valueSats")) + }, + leftBehindLeaves = o.arrayOrEmpty("leftBehindLeaves").map { + val l = it.jsonObject + SparkExitRecord.LeftBehindLeaf(l.string("leafId"), l.ulong("valueSats"), l.string("reason")) + }, + ) + + private fun phaseToJson(phase: SparkExitRecord.Phase): JsonObject = when (phase) { + is SparkExitRecord.Phase.AwaitingFunding -> + tagged("awaitingFunding", buildJsonObject { put("requiredSats", phase.requiredSats.toLong()) }) + SparkExitRecord.Phase.Running -> tagged("running", JsonObject(emptyMap())) + is SparkExitRecord.Phase.NeedsFunding -> + tagged("needsFunding", buildJsonObject { put("requiredSats", phase.requiredSats.toLong()) }) + SparkExitRecord.Phase.Done -> tagged("done", JsonObject(emptyMap())) + is SparkExitRecord.Phase.Failed -> tagged("failed", buildJsonObject { put("reason", phase.reason) }) + } + + private fun phaseFromJson(element: JsonElement): SparkExitRecord.Phase { + val (tag, fields) = variant(element) + return when (tag) { + "awaitingFunding" -> SparkExitRecord.Phase.AwaitingFunding(requireFields(fields).ulong("requiredSats")) + "running" -> SparkExitRecord.Phase.Running + "needsFunding" -> SparkExitRecord.Phase.NeedsFunding(requireFields(fields).ulong("requiredSats")) + "done" -> SparkExitRecord.Phase.Done + "failed" -> SparkExitRecord.Phase.Failed(requireFields(fields).string("reason")) + else -> throw unknown(tag) + } + } + + private fun recoveryToJson(r: RecoverFundsResponse) = buildJsonObject { + put("recoverable_value_sats", r.recoverableValueSats.toLong()) + put("total_fee_sats", r.totalFeeSats.toLong()) + put("cooperative_fee_sats", r.cooperativeFeeSats.toLong()) + put("cpfp_fee_sats", r.cpfpFeeSats.toLong()) + put("fanout_fee_sats", r.fanoutFeeSats.toLong()) + put("refund_fee_sats", r.refundFeeSats.toLong()) + put("sweep_fee_sats", r.sweepFeeSats.toLong()) + put("leaves", JsonArray(r.leaves.map(::leafToJson))) + put("failed", JsonArray(r.failed.map(::failureToJson))) + put("transactions", JsonArray(r.transactions.map(::transactionToJson))) + put("funding_inputs", JsonArray(r.fundingInputs.map(::cpfpInputToJson))) + put("fee_rate_sat_per_vbyte", r.feeRateSatPerVbyte.toLong()) + put("destination", r.destination) + } + + private fun recoveryFromJson(o: JsonObject) = RecoverFundsResponse( + recoverableValueSats = o.ulong("recoverable_value_sats"), + totalFeeSats = o.ulong("total_fee_sats"), + cooperativeFeeSats = o.ulong("cooperative_fee_sats"), + cpfpFeeSats = o.ulong("cpfp_fee_sats"), + fanoutFeeSats = o.ulong("fanout_fee_sats"), + refundFeeSats = o.ulong("refund_fee_sats"), + sweepFeeSats = o.ulong("sweep_fee_sats"), + leaves = o.array("leaves").map { leafFromJson(it.jsonObject) }, + failed = o.array("failed").map { failureFromJson(it.jsonObject) }, + transactions = o.array("transactions").map { transactionFromJson(it.jsonObject) }, + fundingInputs = o.array("funding_inputs").map(::cpfpInputFromJson), + feeRateSatPerVbyte = o.ulong("fee_rate_sat_per_vbyte"), + destination = o.string("destination"), + ) + + private val methods = mapOf(RecoveryMethod.COOPERATIVE to "Cooperative", RecoveryMethod.UNILATERAL to "Unilateral") + + private val kinds = mapOf( + RecoveryTxKind.COOPERATIVE to "Cooperative", + RecoveryTxKind.FAN_OUT to "FanOut", + RecoveryTxKind.NODE to "Node", + RecoveryTxKind.REFUND to "Refund", + RecoveryTxKind.SWEEP to "Sweep", + ) + + private fun leafToJson(leaf: RecoverFundsLeaf) = buildJsonObject { + put("leaf_id", leaf.leafId) + put("value_sats", leaf.valueSats.toLong()) + put("method", methods.getValue(leaf.method)) + } + + private fun leafFromJson(o: JsonObject): RecoverFundsLeaf { + val name = o.string("method") + val method = methods.entries.firstOrNull { it.value == name }?.key ?: throw unknown(name) + return RecoverFundsLeaf(o.string("leaf_id"), o.ulong("value_sats"), method) + } + + private fun failureToJson(failure: CooperativeRecoveryFailure) = buildJsonObject { + put("leaf_id", failure.leafId) + put("output_txid", failure.outputTxid) + put("output_vout", failure.outputVout.toLong()) + put( + "error", + when (val error = failure.error) { + is CooperativeRecoveryError.ReplacementFeeTooLow -> tagged( + "ReplacementFeeTooLow", + buildJsonObject { + put("required_fee_sats", error.requiredFeeSats.toLong()) + put("required_fee_rate_sat_per_vbyte", error.requiredFeeRateSatPerVbyte.toLong()) + }, + ) + is CooperativeRecoveryError.OperatorsUnavailable -> + tagged("OperatorsUnavailable", buildJsonObject { put("message", error.message) }) + is CooperativeRecoveryError.Generic -> + tagged("Generic", buildJsonObject { put("message", error.message) }) + }, + ) + } + + private fun failureFromJson(o: JsonObject): CooperativeRecoveryFailure { + val (tag, fields) = variant(o.getValue("error")) + val error = when (tag) { + "ReplacementFeeTooLow" -> requireFields(fields).let { + CooperativeRecoveryError.ReplacementFeeTooLow( + it.ulong("required_fee_sats"), + it.ulong("required_fee_rate_sat_per_vbyte"), + ) + } + "OperatorsUnavailable" -> CooperativeRecoveryError.OperatorsUnavailable( + requireFields(fields).string("message") + ) + "Generic" -> CooperativeRecoveryError.Generic(requireFields(fields).string("message")) + else -> throw unknown(tag) + } + return CooperativeRecoveryFailure( + o.string("leaf_id"), + o.string("output_txid"), + o.ulong("output_vout").toUInt(), + error + ) + } + + private fun transactionToJson(tx: RecoveryTransaction) = buildJsonObject { + put("kind", kinds.getValue(tx.kind)) + put("node_id", tx.nodeId?.let(::JsonPrimitive) ?: JsonNull) + put("txid", tx.txid) + put("tx_hex", tx.txHex) + put("cpfp_tx_hex", tx.cpfpTxHex?.let(::JsonPrimitive) ?: JsonNull) + put("csv_timelock_blocks", tx.csvTimelockBlocks?.let { JsonPrimitive(it.toLong()) } ?: JsonNull) + put("depends_on", JsonArray(tx.dependsOn.map(::JsonPrimitive))) + put("status", statusToJson(tx.status)) + } + + private fun transactionFromJson(o: JsonObject): RecoveryTransaction { + val kindName = o.string("kind") + return RecoveryTransaction( + kind = kinds.entries.firstOrNull { it.value == kindName }?.key ?: throw unknown(kindName), + nodeId = o.stringOrNull("node_id"), + txid = o.string("txid"), + txHex = o.string("tx_hex"), + cpfpTxHex = o.stringOrNull("cpfp_tx_hex"), + csvTimelockBlocks = o.ulongOrNull("csv_timelock_blocks")?.toUInt(), + dependsOn = o.array("depends_on").map { it.jsonPrimitive.content }, + status = statusFromJson(o.getValue("status")), + ) + } + + private fun statusToJson(status: ExitTransactionStatus): JsonElement = when (status) { + is ExitTransactionStatus.Confirmed -> tagged( + "Confirmed", + buildJsonObject { put("block_height", status.blockHeight?.let { JsonPrimitive(it.toLong()) } ?: JsonNull) }, + ) + ExitTransactionStatus.Ready -> JsonPrimitive("Ready") + ExitTransactionStatus.WaitingForDependencies -> JsonPrimitive("WaitingForDependencies") + is ExitTransactionStatus.WaitingForTimelock -> tagged( + "WaitingForTimelock", + buildJsonObject { + put("spendable_at_height", status.spendableAtHeight?.let { JsonPrimitive(it.toLong()) } ?: JsonNull) + }, + ) + ExitTransactionStatus.Unverified -> JsonPrimitive("Unverified") + } + + private fun statusFromJson(element: JsonElement): ExitTransactionStatus { + val (tag, fields) = variant(element) + return when (tag) { + "Confirmed" -> ExitTransactionStatus.Confirmed(requireFields(fields).ulongOrNull("block_height")?.toUInt()) + "Ready" -> ExitTransactionStatus.Ready + "WaitingForDependencies" -> ExitTransactionStatus.WaitingForDependencies + "WaitingForTimelock" -> ExitTransactionStatus.WaitingForTimelock( + requireFields(fields).ulongOrNull("spendable_at_height")?.toUInt(), + ) + "Unverified" -> ExitTransactionStatus.Unverified + else -> throw unknown(tag) + } + } + + private fun cpfpInputToJson(input: CpfpInput): JsonObject = when (input) { + is CpfpInput.P2wpkh -> tagged( + "P2wpkh", + buildJsonObject { + put("txid", input.txid) + put("vout", input.vout.toLong()) + put("value_sats", input.valueSats.toLong()) + put("pubkey", input.pubkey) + }, + ) + is CpfpInput.P2tr -> tagged( + "P2tr", + buildJsonObject { + put("txid", input.txid) + put("vout", input.vout.toLong()) + put("value_sats", input.valueSats.toLong()) + put("pubkey", input.pubkey) + }, + ) + is CpfpInput.Custom -> tagged( + "Custom", + buildJsonObject { + put("txid", input.txid) + put("vout", input.vout.toLong()) + put("value_sats", input.valueSats.toLong()) + put("script_pubkey_hex", input.scriptPubkeyHex) + put("signed_input_weight", input.signedInputWeight.toLong()) + }, + ) + } + + private fun cpfpInputFromJson(element: JsonElement): CpfpInput { + val (tag, fields) = variant(element) + val f = requireFields(fields) + val txid = f.string("txid") + val vout = f.ulong("vout").toUInt() + val value = f.ulong("value_sats") + return when (tag) { + "P2wpkh" -> CpfpInput.P2wpkh(txid, vout, value, f.string("pubkey")) + "P2tr" -> CpfpInput.P2tr(txid, vout, value, f.string("pubkey")) + "Custom" -> CpfpInput.Custom( + txid, + vout, + value, + f.string("script_pubkey_hex"), + f.ulong("signed_input_weight") + ) + else -> throw unknown(tag) + } + } + + /** serde's default enum shape: a unit variant is its name, a variant with fields an object keyed by its name. */ + private fun variant(element: JsonElement): Pair { + if (element is JsonPrimitive && element.isString) return element.content to null + val o = element.jsonObject + require(o.size == 1) { "Expected one variant key, got '${o.keys}'" } + val (tag, fields) = o.entries.first() + return tag to (fields as? JsonObject) + } + + private fun tagged(tag: String, fields: JsonObject) = JsonObject(mapOf(tag to fields)) + + private fun requireFields(fields: JsonObject?): JsonObject = requireNotNull( + fields + ) { "Variant is missing its fields" } + + private fun unknown(tag: String) = SparkExitFormatError("Unknown variant '$tag'") + + private fun JsonObject.value(key: String): JsonPrimitive? = + (this[key] as? JsonPrimitive)?.takeUnless { it is JsonNull } + + private fun JsonObject.string(key: String) = requireNotNull(value(key)) { "Missing '$key'" }.content + + private fun JsonObject.stringOrNull(key: String) = value(key)?.content + + private fun JsonObject.ulong(key: String) = string(key).toULong() + + private fun JsonObject.ulongOrNull(key: String) = value(key)?.content?.toULong() + + private fun JsonObject.int(key: String) = string(key).toInt() + + private fun JsonObject.intOrNull(key: String) = value(key)?.content?.toInt() + + private fun JsonObject.booleanOrNull(key: String) = value(key)?.content?.toBooleanStrictOrNull() + + /** Swift writes dates as a millisecond count that may carry a fraction. */ + private fun JsonObject.millis(key: String) = string(key).toBigDecimal().toLong() + + private fun JsonObject.millisOrNull(key: String) = value(key)?.content?.toBigDecimal()?.toLong() + + private fun JsonObject.array(key: String) = requireNotNull(this[key]) { "Missing '$key'" }.jsonArray + + private fun JsonObject.arrayOrEmpty(key: String) = (this[key] as? JsonArray).orEmpty() + + private fun JsonObject.objectOrNull(key: String) = this[key] as? JsonObject +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt new file mode 100644 index 0000000000..0c637a1b92 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -0,0 +1,566 @@ +package to.bitkit.repositories + +import breez_sdk_spark.CpfpFundingKind +import breez_sdk_spark.CpfpSigner +import breez_sdk_spark.ExitLeafSelection +import breez_sdk_spark.PrepareRecoverFundsRequest +import breez_sdk_spark.RecoveryTxKind +import breez_sdk_spark.singleKeyCpfpSigner +import com.synonym.bitkitcore.Activity +import io.ktor.client.HttpClient +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull +import to.bitkit.async.appScope +import to.bitkit.data.CacheStore +import to.bitkit.data.keychain.Keychain +import to.bitkit.di.BgDispatcher +import to.bitkit.env.Env +import to.bitkit.ext.nowMs +import to.bitkit.ext.runSuspendCatching +import to.bitkit.models.TransactionSpeed +import to.bitkit.models.TransferType +import to.bitkit.models.safe +import to.bitkit.services.CoreService +import to.bitkit.services.SparkError +import to.bitkit.services.SparkService +import to.bitkit.utils.AppError +import to.bitkit.utils.Logger +import to.bitkit.utils.ServiceError +import java.io.File +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Clock +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +/** + * Runs a Spark emergency exit: the quote, the fee funding, then the driver until every step is on-chain. The exit + * survives restarts through [SparkExitStore], and is driven while Bitkit is open, by WorkManager while it is closed, + * and after a notification brings the user back when a timelock matures. + */ +@Singleton +class SparkExitRepo @Inject constructor( + private val work: SparkExitWork, + @BgDispatcher private val bgDispatcher: CoroutineDispatcher, + private val sparkService: SparkService, + private val sparkRepo: SparkRepo, + private val lightningRepo: LightningRepo, + private val transferRepo: TransferRepo, + private val activityRepo: ActivityRepo, + private val coreService: CoreService, + private val keychain: Keychain, + private val httpClient: HttpClient, + private val clock: Clock, + private val sparkExitTip: SparkExitTip, + private val cacheStore: CacheStore, +) { + companion object { + private const val TAG = "SparkExitRepo" + + /** How often the exit is driven while Bitkit is in the foreground. */ + private val FOREGROUND_TICK_INTERVAL = 60.seconds + + /** How long a background run waits for Spark to connect before it gives up on the SDK steps. */ + private val BACKGROUND_CONNECT_TIMEOUT = 2.minutes + } + + private val scope = appScope(bgDispatcher, TAG) + private val tickMutex = Mutex() + private var foregroundJob: Job? = null + + @Volatile + private var walletIndex = 0 + + @Volatile + private var isLoaded = false + + private val _state = MutableStateFlow(SparkExitState()) + val state: StateFlow = _state.asStateFlow() + + init { + scope.launch { + sparkRepo.walletWiped.collect { + if (it != walletIndex) return@collect + work.cancelAll() + _state.update { SparkExitState() } + } + } + } + + private val store get() = SparkExitStore(File(Env.sparkExitRecordPath(walletIndex))) + + private val chain: SparkExitChain? + get() = EsploraSparkExitChain.defaultHosts(sparkService.networkName) + .takeIf { it.isNotEmpty() } + ?.let { EsploraSparkExitChain(it, httpClient) } + + // region lifecycle + + /** Loads the exit of [walletIndex] once, takes Spark off Lightning while it runs, and settles a finished one. */ + suspend fun load(walletIndex: Int = sparkRepo.walletIndex): Result = withContext(bgDispatcher) { + runSuspendCatching { + if (isLoaded && this@SparkExitRepo.walletIndex == walletIndex) return@runSuspendCatching _state.value.record + this@SparkExitRepo.walletIndex = walletIndex + val record = runSuspendCatching { store.load() }.getOrElse { + // Kept aside for support, so a new exit never overwrites it; a new exit prepares from chain state. + Logger.error("Failed to read the Spark exit record", it, context = TAG) + runSuspendCatching { store.setAside(clock.nowMs()) } + null + } + isLoaded = true + _state.update { it.copy(record = record) } + record?.let { settleIfFinished(it) } + settleOrphanedTransfers(record) + if (record?.needsDriving == true) work.schedulePeriodic() + record + } + } + + /** Drives the exit every minute while Bitkit is in the foreground. */ + fun onAppForegrounded() { + if (foregroundJob?.isActive == true) return + foregroundJob = scope.launch { + load().onFailure { Logger.error("Failed to load the Spark exit", it, context = TAG) } + while (isActive && _state.value.record?.needsDriving == true) { + tick() + delay(FOREGROUND_TICK_INTERVAL) + } + } + } + + fun onAppBackgrounded() { + foregroundJob?.cancel() + foregroundJob = null + } + + /** + * One background run: the steps the stored recovery allows without the SDK first, then, once Spark connects, the + * SDK check. It never starts the Lightning node. An ended exit only sweeps its leftover, which needs no SDK. + */ + suspend fun runInBackground(): Result = withContext(bgDispatcher) { + runSuspendCatching { + load().getOrThrow() + if (_state.value.record?.needsDriving != true) return@runSuspendCatching _state.value.record + tick() + if (_state.value.isExiting && !sparkService.isConnected) { + withTimeoutOrNull(BACKGROUND_CONNECT_TIMEOUT) { sparkRepo.start(walletIndex) } + if (sparkService.isConnected) tick() + } + _state.value.record + } + } + + // endregion + + // region tick + + /** Moves the exit one step forward; a tick already running makes this one a no-op. */ + suspend fun tick(): Result = withContext(bgDispatcher) { + if (!tickMutex.tryLock()) return@withContext Result.success(_state.value.record) + try { + runSuspendCatching { tickLocked() } + .onFailure { + Logger.error("Failed to drive the Spark exit", it, context = TAG) + _state.update { state -> state.copy(lastError = it.message) } + } + } finally { + tickMutex.unlock() + // Every tick keeps the background work queued, so one failed or skipped run never ends the chain. + if (_state.value.record?.needsDriving == true) work.schedulePeriodic() + } + } + + private suspend fun tickLocked(): SparkExitRecord? { + val current = _state.value.record?.takeIf { it.needsDriving } ?: return _state.value.record + val chain = chain ?: return current + Logger.debug("Driving Spark exit in phase '${current.phase}'", context = TAG) + val tip = runSuspendCatching { chain.tipHeight() }.getOrNull() + _state.update { it.copy(tipHeight = tip ?: it.tipHeight) } + tip?.let { height -> sparkExitTip.height.update { height } } + refreshFundingSeen(chain, current) + val store = store + val recovering = sparkService.exitRecovering() + val driver = SparkExitDriver( + chain = chain, + recovering = recovering, + // The record's own funding key, also for exits started before each exit had an index of its own. + makeSigner = { signer(current.fundingIndex) }, + save = store::save, + nowMillis = clock::nowMs, + ) + val updated = driver.tick(current) + _state.update { it.copy(record = updated, lastError = null) } + // Spark's balance next to the exit's leaves shows value outside the exit. + if (recovering != null) _state.update { it.copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) } + // A rebuild needs the SDK; every other running step can go out from the stored recovery without it. Steps + // refused again and again keep the exit from moving, however often it runs. + val canMove = recovering != null || !updated.isRebuilding + val isOnTrack = tip != null && canMove && updated.surfacedRejection == null + afterTick(updated, current, isOnTrack) + return updated + } + + private suspend fun afterTick(record: SparkExitRecord, previous: SparkExitRecord, isOnTrack: Boolean) { + record.transferId?.let { transferRepo.updateClaimableAtHeight(it, record.claimableAtHeight) } + settleIfFinished(record) + updateAlerts(record, previous, isOnTrack) + if (!record.isActive && previous.isActive) { + Logger.info("Ended Spark exit with phase '${record.phase}'", context = TAG) + sparkRepo.setExiting(false) + } + if (!record.needsDriving) work.cancelAll() + } + + /** + * Ends the exit's transfer once the sweep reaches savings, or once the exit ended, so its amount is never counted + * both as in transfer and in the on-chain balance. Runs on every tick and load until it holds. + */ + private suspend fun settleIfFinished(record: SparkExitRecord) { + val transferId = record.transferId ?: return + if (transferRepo.isSettled(transferId).getOrDefault(true)) return + var isFinished = !record.isActive + val sweep = record.recovery?.transactions?.firstOrNull { it.kind == RecoveryTxKind.SWEEP } + val sweepActivity = sweep?.let { activityRepo.getOnchainActivityByTxId(it.txid) } + if (sweepActivity != null) { + if (!sweepActivity.isTransfer) { + activityRepo.updateActivity(sweepActivity.id, Activity.Onchain(sweepActivity.copy(isTransfer = true))) + } + isFinished = true + } + if (isFinished) transferRepo.markSettled(transferId) + } + + /** + * Settles exit transfers no running exit owns: a record set aside as unreadable, or one written without its + * transfer id before a crash, would otherwise count its amount as in transfer to Savings for good. + */ + private suspend fun settleOrphanedTransfers(record: SparkExitRecord?) { + val owned = record?.takeIf { it.isActive }?.transferId + transferRepo.activeTransfers.first() + .filter { it.type == TransferType.SPARK_EXIT && it.id != owned } + .forEach { + Logger.warn("Settling Spark exit transfer '${it.id}' with no running exit", context = TAG) + transferRepo.markSettled(it.id) + } + } + + private suspend fun refreshFundingSeen(chain: SparkExitChain, record: SparkExitRecord) { + val address = record.funding.firstOrNull()?.address ?: return + _state.update { it.copy(fundingAddress = address) } + if (record.fundingShortfallSats == null) { + _state.update { it.copy(fundingState = null) } + return + } + val utxos = runSuspendCatching { chain.utxos(address) }.getOrNull() + // Only new funding counts as seen; adopted inputs and their CPFP change are already part of the exit. + val seen = utxos?.let { SparkExitMath.newFunding(it, record) }?.fold(0uL) { sum, utxo -> + sum.safe() + utxo.value.safe() + } + _state.update { + it.copy( + fundingSeenSats = seen ?: it.fundingSeenSats, + fundingState = SparkExitMath.fundingState(record, utxos), + ) + } + } + + /** + * Pushes back the warning that the exit fell behind, to 12 blocks into the operators' window of the next step to + * mature (about 50 blocks after it, when they may publish their own version), or of the steps already waiting to + * be published. Only a run that kept the exit on track pushes it; a stalled exit lets it fire. Needing more fee + * funding is notified once, at once. + */ + private fun updateAlerts(record: SparkExitRecord, previous: SparkExitRecord, isOnTrack: Boolean) { + SparkExitAlerts.losses(record, previous).forEach { + work.notify(it, amountSats = record.lostSats.takeIf { _ -> it == SparkExitAlert.Lost }) + } + when (record.phase) { + SparkExitRecord.Phase.Running -> { + if (!isOnTrack) return + val tip = _state.value.tipHeight + val untilMaturity = SparkExitMath.untilNextMaturity(record.recovery, tip, Env.network) + work.armDeadline( + SparkExitMath.deadline(untilMaturity, Env.network), + clock.nowMs(), + ) + } + is SparkExitRecord.Phase.NeedsFunding -> { + work.cancelDeadline() + if (previous.phase !is SparkExitRecord.Phase.NeedsFunding) work.notify(SparkExitAlert.Funding) + } + else -> work.cancelDeadline() + } + } + + /** What Android lets the exit do while Bitkit is closed, for the progress screen. */ + fun backgroundLimits(): SparkExitBackgroundLimits = work.backgroundLimits() + + // endregion + + // region quote and start + + /** Quotes an exit of every leaf to a fresh savings address at the SDK's fastest fee rate. */ + suspend fun loadQuote(): Result = withContext(bgDispatcher) { + runSuspendCatching { + val recovering = sparkService.exitRecovering() ?: throw SparkError.NotConnected() + if (sparkRepo.needsSettling()) _state.update { it.copy(isSettling = true) } + sparkRepo.settleForExit().also { _state.update { it.copy(isSettling = false) } }.getOrThrow() + val feeRate = maxOf(1uL, sparkService.fastestFeeRate()) + val destination = _state.value.pending?.destination ?: lightningRepo.newAddress().getOrThrow() + val prepared = recovering.prepare( + PrepareRecoverFundsRequest( + feeRateSatPerVbyte = feeRate, + fundingKind = CpfpFundingKind.P2wpkh, + destination = destination, + selection = ExitLeafSelection.All, + ), + ) + val quote = SparkExitQuote(prepared, sparkRepo.state.value.balanceSats) + // Chosen here, so the funding screen, the fee estimate and the record all use one address. + val fundingIndex = nextFundingIndex() + val fundingAddress = fundingKey(fundingIndex).address + _state.update { + it.copy( + pending = SparkExitPending(quote, destination, feeRate, fundingIndex), + fundingAddress = fundingAddress, + ) + } + quote + }.onFailure { + Logger.error("Failed to quote the Spark exit", it, context = TAG) + } + } + + /** The fee Savings pays to send the fee funding at the fast rate, or null when it cannot. */ + suspend fun savingsFundingFee(): Result = withContext(bgDispatcher) { + runSuspendCatching { + val pending = requireNotNull(_state.value.pending) { "No Spark exit quote" } + val address = requireNotNull(_state.value.fundingAddress) { "No Spark exit funding address" } + val fundingSats = pending.quote.fundingSats + val feeSats = lightningRepo.calculateTotalFee(fundingSats, address, TransactionSpeed.Fast).getOrThrow() + val spendable = lightningRepo.getBalancesAsync().getOrThrow().spendableOnchainBalanceSats + SparkExitSavingsFunding( + feeSats = feeSats, + canPay = SparkExitMath.canFundFromSavings(spendable, fundingSats, feeSats), + ) + } + } + + /** Reads what reached the funding address, for the funding screen while the user pays from another wallet. */ + suspend fun refreshFundingAddress(): Result = withContext(bgDispatcher) { + runSuspendCatching { + val chain = requireNotNull(chain) { "No chain host for this network" } + val address = requireNotNull(_state.value.fundingAddress) { "No Spark exit funding address" } + val seen = chain.utxos(address).fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + _state.update { it.copy(fundingSeenSats = seen) } + seen + } + } + + /** + * Starts the exit for the current quote: writes its record, moves the Spark balance into transfer to savings and, + * with [fundFromSavings], pays the fee funding from savings. + */ + suspend fun start(fundFromSavings: Boolean): Result = withContext(bgDispatcher) { + runSuspendCatching { + if (_state.value.isExiting) throw SparkExitError("A Spark exit is already running") + val pending = requireNotNull(_state.value.pending) { "No Spark exit quote" } + val network = requireNotNull(sparkService.networkName) { "Spark is not available on this network" } + val key = fundingKey(pending.fundingIndex) + val quote = pending.quote + var record = SparkExitRecord( + network = network, + createdAt = clock.nowMs(), + phase = SparkExitRecord.Phase.AwaitingFunding(quote.fundingSats), + feeRateSatPerVbyte = pending.feeRate, + destination = pending.destination, + leafIds = quote.leafIds, + funding = listOf( + SparkExitRecord.Funding(index = pending.fundingIndex, address = key.address, pubkey = key.pubkey), + ), + expectedSats = quote.incomingSats, + skippedLeafCount = quote.prepared.skipped.size, + leafTotalSats = quote.prepared.leaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() }, + ) + // Saved before the transfer exists, so a failed save never leaves a transfer counted with no exit behind. + store.save(record) + cacheStore.update { + val next = it.sparkExitNextFundingIndexes + (fundingIndexKey to pending.fundingIndex.toInt() + 1) + it.copy(sparkExitNextFundingIndexes = next) + } + val transferId = transferRepo.createTransfer( + TransferType.SPARK_EXIT, + quote.incomingSats.toLong() + ).getOrThrow() + record = record.copy(transferId = transferId) + store.save(record) + _state.update { it.copy(record = record, pending = null, fundingAddress = key.address) } + isLoaded = true + // Reconnecting for the exit disconnects Spark, which would cut a running leaf optimization short. + sparkRepo.awaitOptimizationIdle() + sparkRepo.setExiting(true) + work.schedulePeriodic() + Logger.info( + "Started Spark exit of '${quote.exitSats}' sats over '${quote.leafIds.size}' leaves", + context = TAG, + ) + // Driven before paying, so a failed payment from savings still leaves the exit watching its address. + scope.launch { tick() } + onAppForegrounded() + if (fundFromSavings && quote.fundingSats > 0uL) payFunding(key.address, quote.fundingSats) + }.onFailure { + Logger.error("Failed to start the Spark exit", it, context = TAG) + } + } + + /** Pays the fee funding from savings as an ordinary payment: it is a fee, not a transfer to spending. */ + private suspend fun payFunding(address: String, sats: ULong) { + val outcome = lightningRepo.sendOnChain( + address = address, + sats = sats, + speed = TransactionSpeed.Fast, + ).getOrThrow() + if (outcome !is OnchainSendOutcome.Accepted) { + throw SparkExitError( + "Spark exit funding was not accepted: '$outcome'" + ) + } + // After the tick in flight, so its save cannot drop the txid; progress then waits for it instead of asking. + tickMutex.withLock { + val record = _state.value.record ?: return@withLock + val paid = record.copy(fundingPaymentTxid = outcome.txid) + store.save(paid) + _state.update { + it.copy(record = paid, fundingState = SparkExitMath.fundingState(paid, utxos = null)) + } + } + runSuspendCatching { lightningRepo.completeAcceptedOrdinaryFollowup(outcome.txid) } + .onFailure { Logger.warn("Failed to finish the Spark exit funding locally", it, context = TAG) } + Logger.info("Funded the Spark exit with '$sats' sats in '${outcome.txid}'", context = TAG) + } + + /** + * Whether the exit can stop at no cost: nothing was built and its funding address received nothing, so Spark + * comes back as it was. + */ + val canCancel: Boolean + get() { + val exit = _state.value + val record = exit.record ?: return false + return record.phase is SparkExitRecord.Phase.AwaitingFunding && + record.recovery == null && + record.fundedSats == 0uL && + exit.fundingSeenSats == 0uL + } + + /** The user opened the result of an exit that failed or lost leaves: Emergency exit may start a new one now. */ + suspend fun markResultSeen(): Result = withContext(bgDispatcher) { + runSuspendCatching { + tickMutex.withLock { + val record = _state.value.record?.takeIf { it.hasUnseenResult } + ?: return@withLock + val seen = record.copy(isResultSeen = true) + store.save(seen) + _state.update { it.copy(record = seen) } + } + } + } + + suspend fun cancel(): Result = withContext(bgDispatcher) { + runSuspendCatching { + if (!canCancel) throw SparkExitError("The Spark exit can no longer be cancelled") + val record = requireNotNull(_state.value.record) + store.delete() + _state.update { it.copy(record = null) } + record.transferId?.let { transferRepo.markSettled(it) } + work.cancelAll() + sparkRepo.setExiting(false) + Logger.info("Cancelled the Spark exit before it was funded", context = TAG) + } + } + + // endregion + + // region keys + + private val fundingIndexKey get() = "${Env.network.name.lowercase()}/wallet$walletIndex" + + /** A funding key index no exit of this wallet used. */ + private suspend fun nextFundingIndex(): UInt = SparkExitMath.nextFundingIndex( + kept = cacheStore.data.first().sparkExitNextFundingIndexes[fundingIndexKey], + stored = runSuspendCatching { store.load() }.getOrNull(), + ) + + /** Every funding UTXO of one exit goes to its index: the SDK's single-key signer signs all inputs with one key. */ + private suspend fun fundingKey(index: UInt): SparkExitFundingKey.Derived { + val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() + val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) + val path = SparkExitFundingKey.path(index = index.toInt(), network = Env.network) + val address = coreService.onchain.deriveBitcoinAddress(mnemonic, path, Env.network, passphrase) + val wif = coreService.onchain.derivePrivateKey(mnemonic, path, Env.network, passphrase) + return SparkExitFundingKey.Derived(address.address, address.publicKey, SparkExitFundingKey.secretKey(wif)) + } + + private suspend fun signer(index: UInt): CpfpSigner = singleKeyCpfpSigner(fundingKey(index).secretKey) + + // endregion +} + +class SparkExitError(message: String) : AppError(message) + +/** A quote the user is looking at, with what the exit is built from once it starts. */ +data class SparkExitPending( + val quote: SparkExitQuote, + val destination: String, + val feeRate: ULong, + /** The funding key index this exit takes. */ + val fundingIndex: UInt, +) + +data class SparkExitSavingsFunding( + val feeSats: ULong, + val canPay: Boolean, +) + +data class SparkExitState( + val record: SparkExitRecord? = null, + val pending: SparkExitPending? = null, + val tipHeight: UInt? = null, + /** Confirmed or not, what reached the funding address. */ + val fundingSeenSats: ULong = 0uL, + /** What progress shows while the exit needs fee funding. */ + val fundingState: SparkExitFundingState? = null, + val fundingAddress: String? = null, + val lastError: String? = null, + /** Spark's balance as last seen while the SDK drove the exit. */ + val sparkBalanceSats: ULong? = null, + /** The quote waits for Spark to finish moving leaves, so value in flight is not left out of the exit. */ + val isSettling: Boolean = false, +) { + val isExiting: Boolean get() = record?.isActive == true + + /** Emergency exit opens progress rather than a new exit. */ + val showsResult: Boolean get() = record?.showsResult == true + + /** + * Spark's balance beyond the quote's leaves while the exit runs: value outside the exit, which stays on Spark. A + * signal only, exact while the exit's leaves still count in the balance; published leaves leave it. + */ + val outsideExitSats: ULong? + get() { + val active = record?.takeIf { it.isActive } ?: return null + return SparkExitMath.outsideExitSats(active.leafTotalSats, sparkBalanceSats) + } +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt new file mode 100644 index 0000000000..6dc251444a --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt @@ -0,0 +1,255 @@ +package to.bitkit.repositories + +import to.bitkit.models.safe +import to.bitkit.utils.AppError +import java.io.ByteArrayOutputStream +import java.security.MessageDigest + +/** + * Moves the fee funding an exit left at its funding address to savings once the exit is done: change from a branch + * whose refund the operators published, or funding a rebuild no longer needed. The SDK's single-key CPFP signer signs + * the P2WPKH inputs of the PSBT built here and finalizes them, so the funding key never leaves the signer. + */ +object SparkExitSweep { + private const val SEQUENCE_RBF = 0xfffffffdL + + /** Bitcoin Core's spend sizes for its dust rule: a witness program's input, and any other. */ + private const val WITNESS_SPEND_BYTES = 67uL + private const val LEGACY_SPEND_BYTES = 148uL + + data class Input(val txid: String, val vout: UInt, val valueSats: ULong) + + /** An unsigned sweep of [inputs] to [destination], or null when what it pays would be under the dust limit. */ + class Plan(val inputs: List, val destinationScript: ByteArray, val amountSats: ULong, val feeSats: ULong) + + fun plan(inputs: List, destination: String, feeRateSatPerVbyte: ULong): Plan? { + if (inputs.isEmpty()) return null + val script = AddressScript.of(destination) + val fee = vsize(inputs.size, script.size) * maxOf(1uL, feeRateSatPerVbyte) + val total = inputs.fold(0uL) { sum, input -> sum.safe() + input.valueSats.safe() } + if (total < fee.safe() + dustLimit(script).safe()) return null + return Plan(inputs, script, total - fee, fee) + } + + /** P2WPKH inputs sized for 72-byte signatures and one output: ceil((4 · base + witness) / 4). */ + fun vsize(inputCount: Int, outputScriptSize: Int): ULong { + val n = inputCount.toULong() + val base = 10uL + 41uL * n + 9uL + outputScriptSize.toULong() + val witness = 2uL + 108uL * n + return (4uL * base + witness + 3uL) / 4uL + } + + /** Bitcoin Core's dust limit of an output: 3 · (output size + spend size), 294 for P2WPKH, 330 for P2TR. */ + fun dustLimit(script: ByteArray): ULong { + val isWitness = script.size >= 4 && (script[0] == 0.toByte() || script[0] in 0x51.toByte()..0x60.toByte()) + val spend = if (isWitness) WITNESS_SPEND_BYTES else LEGACY_SPEND_BYTES + return 3uL * (9uL + script.size.toULong() + spend) + } + + /** A BIP 174 PSBT of [plan], each input carrying its P2WPKH `witness_utxo` at [fundingAddress] for the signer. */ + fun psbt(plan: Plan, fundingAddress: String): ByteArray { + val fundingScript = AddressScript.of(fundingAddress) + val out = ByteArrayOutputStream() + out.write(byteArrayOf(0x70, 0x73, 0x62, 0x74, 0xff.toByte())) + out.writeKeyValue(byteArrayOf(0x00), unsignedTx(plan)) + out.write(0x00) + plan.inputs.forEach { + out.writeKeyValue(byteArrayOf(0x01), le64(it.valueSats.toLong()) + varBytes(fundingScript)) + out.write(0x00) + } + out.write(0x00) + return out.toByteArray() + } + + /** The signed transaction hex from a PSBT whose every input the signer finalized. */ + fun signedTxHex(plan: Plan, signedPsbt: ByteArray): String { + val witnesses = PsbtReader(signedPsbt).finalWitnesses(plan.inputs.size) + val out = ByteArrayOutputStream() + out.write(le32(2)) + out.write(byteArrayOf(0x00, 0x01)) + out.write(txBody(plan)) + witnesses.forEach { out.write(it) } + out.write(le32(0)) + return out.toByteArray().toHexString() + } + + private fun unsignedTx(plan: Plan): ByteArray = le32(2) + txBody(plan) + le32(0) + + private fun txBody(plan: Plan): ByteArray { + val out = ByteArrayOutputStream() + out.write(compactSize(plan.inputs.size.toLong())) + plan.inputs.forEach { + out.write(it.txid.hexToByteArray().reversedArray()) + out.write(le32(it.vout.toLong())) + out.write(0x00) + out.write(le32(SEQUENCE_RBF)) + } + out.write(compactSize(1)) + out.write(le64(plan.amountSats.toLong())) + out.write(varBytes(plan.destinationScript)) + return out.toByteArray() + } + + private fun ByteArrayOutputStream.writeKeyValue(key: ByteArray, value: ByteArray) { + write(varBytes(key)) + write(varBytes(value)) + } + + private fun varBytes(bytes: ByteArray) = compactSize(bytes.size.toLong()) + bytes + + private fun compactSize(n: Long): ByteArray = when { + n < 0xfd -> byteArrayOf(n.toByte()) + n <= 0xffff -> byteArrayOf(0xfd.toByte()) + le(n, 2) + n <= 0xffffffffL -> byteArrayOf(0xfe.toByte()) + le(n, 4) + else -> byteArrayOf(0xff.toByte()) + le(n, 8) + } + + private fun le32(n: Long) = le(n, 4) + private fun le64(n: Long) = le(n, 8) + private fun le(n: Long, size: Int) = ByteArray(size) { ((n ushr (8 * it)) and 0xff).toByte() } + + /** Reads the `final_scriptwitness` of each input, already serialized as the transaction carries it. */ + private class PsbtReader(private val bytes: ByteArray) { + private var offset = 5 + + fun finalWitnesses(inputCount: Int): List { + if (!bytes.copyOfRange(0, 5).contentEquals(byteArrayOf(0x70, 0x73, 0x62, 0x74, 0xff.toByte()))) { + throw SparkExitSweepError("Not a PSBT") + } + skipMap() + return List(inputCount) { index -> + var witness: ByteArray? = null + while (true) { + val key = readVarBytes() + if (key.isEmpty()) break + val value = readVarBytes() + if (key[0] == FINAL_SCRIPTWITNESS) witness = value + } + witness ?: throw SparkExitSweepError("Input '$index' was not signed") + } + } + + private fun skipMap() { + while (true) { + if (readVarBytes().isEmpty()) return + readVarBytes() + } + } + + private fun readVarBytes(): ByteArray { + val length = readCompactSize() + if (length < 0 || length > bytes.size - offset) throw SparkExitSweepError("Truncated PSBT") + return bytes.copyOfRange(offset, offset + length).also { offset += length } + } + + private fun readCompactSize(): Int { + if (offset >= bytes.size) throw SparkExitSweepError("Truncated PSBT") + val prefix = bytes[offset++].toInt() and 0xff + val size = when (prefix) { + 0xfd -> 2 + 0xfe -> 4 + 0xff -> 8 + else -> return prefix + } + if (size > bytes.size - offset) throw SparkExitSweepError("Truncated PSBT") + var value = 0L + repeat(size) { value = value or ((bytes[offset++].toLong() and 0xff) shl (8 * it)) } + if (value > Int.MAX_VALUE) throw SparkExitSweepError("PSBT field too large") + return value.toInt() + } + + private companion object { + const val FINAL_SCRIPTWITNESS: Byte = 0x08 + } + } +} + +class SparkExitSweepError(message: String) : AppError(message) + +/** An address to the output script it pays: segwit (BIP 173 and 350), P2PKH or P2SH. */ +object AddressScript { + private val P2PKH_VERSIONS = setOf(0x00, 0x6f) + private val P2SH_VERSIONS = setOf(0x05, 0xc4) + private const val HASH_LENGTH = 20 + private const val CHECKSUM_LENGTH = 4 + + fun of(address: String): ByteArray { + val hrp = address.lowercase().substringBeforeLast('1', "") + if (hrp in setOf("bc", "tb", "bcrt")) return Bech32.scriptPubKey(address) + val decoded = SparkExitFundingKey.base58Decode(address) + ?.takeIf { it.size == 1 + HASH_LENGTH + CHECKSUM_LENGTH } + ?: throw SparkExitSweepError("Invalid address '$address'") + val payload = decoded.copyOfRange(0, 1 + HASH_LENGTH) + val sha256 = MessageDigest.getInstance("SHA-256") + val checksum = sha256.digest(sha256.digest(payload)).copyOfRange(0, CHECKSUM_LENGTH) + if (!checksum.contentEquals(decoded.copyOfRange(1 + HASH_LENGTH, decoded.size))) { + throw SparkExitSweepError("Invalid checksum in '$address'") + } + val hash = payload.copyOfRange(1, payload.size) + return when (payload[0].toInt() and 0xff) { + in P2PKH_VERSIONS -> { + byteArrayOf(0x76, 0xa9.toByte(), 0x14) + hash + byteArrayOf(0x88.toByte(), 0xac.toByte()) + } + in P2SH_VERSIONS -> byteArrayOf(0xa9.toByte(), 0x14) + hash + byteArrayOf(0x87.toByte()) + else -> throw SparkExitSweepError("Unsupported address '$address'") + } + } +} + +/** Segwit addresses (BIP 173 and BIP 350) to the output script they pay. */ +object Bech32 { + private const val CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" + private const val BECH32_CONST = 1 + private const val BECH32M_CONST = 0x2bc830a3 + private const val MIN_PROGRAM = 2 + private const val MAX_PROGRAM = 40 + + fun scriptPubKey(address: String): ByteArray { + val lower = address.lowercase() + val separator = lower.lastIndexOf('1') + if (separator < 1 || separator + 7 > lower.length) throw SparkExitSweepError("Invalid address '$address'") + val hrp = lower.substring(0, separator) + val data = lower.substring(separator + 1).map { + CHARSET.indexOf(it).takeIf { i -> i >= 0 } ?: throw SparkExitSweepError("Invalid address '$address'") + } + val version = data.first() + val checksum = polymod(expand(hrp) + data) + val expected = if (version == 0) BECH32_CONST else BECH32M_CONST + if (checksum != expected) throw SparkExitSweepError("Invalid checksum in '$address'") + val program = convertBits(data.subList(1, data.size - 6)) + if (program.size !in MIN_PROGRAM..MAX_PROGRAM || (version == 0 && program.size != 20 && program.size != 32)) { + throw SparkExitSweepError("Invalid program in '$address'") + } + val opVersion = if (version == 0) 0 else 0x50 + version + return byteArrayOf(opVersion.toByte(), program.size.toByte()) + program + } + + private fun expand(hrp: String): List = hrp.map { it.code shr 5 } + 0 + hrp.map { it.code and 31 } + + private fun polymod(values: List): Int { + val generators = intArrayOf(0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3) + var chk = 1 + values.forEach { value -> + val top = chk ushr 25 + chk = (chk and 0x1ffffff) shl 5 xor value + generators.forEachIndexed { i, g -> if ((top ushr i) and 1 == 1) chk = chk xor g } + } + return chk + } + + private fun convertBits(data: List): ByteArray { + var acc = 0 + var bits = 0 + val out = ByteArrayOutputStream() + data.forEach { + acc = (acc shl 5) or it + bits += 5 + while (bits >= 8) { + bits -= 8 + out.write((acc ushr bits) and 0xff) + } + } + if (bits >= 5 || ((acc shl (8 - bits)) and 0xff) != 0) throw SparkExitSweepError("Invalid padding") + return out.toByteArray() + } +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt new file mode 100644 index 0000000000..df2b540dc4 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -0,0 +1,347 @@ +package to.bitkit.repositories + +import android.app.AlarmManager +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.net.NetworkCapabilities +import android.text.format.DateFormat +import androidx.core.content.edit +import androidx.hilt.work.HiltWorker +import androidx.work.Constraints +import androidx.work.CoroutineWorker +import androidx.work.ExistingPeriodicWorkPolicy +import androidx.work.ExistingWorkPolicy +import androidx.work.NetworkType +import androidx.work.OneTimeWorkRequestBuilder +import androidx.work.PeriodicWorkRequestBuilder +import androidx.work.WorkManager +import androidx.work.WorkerParameters +import dagger.assisted.Assisted +import dagger.assisted.AssistedInject +import dagger.hilt.EntryPoint +import dagger.hilt.InstallIn +import dagger.hilt.android.EntryPointAccessors +import dagger.hilt.android.qualifiers.ApplicationContext +import dagger.hilt.components.SingletonComponent +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.launch +import to.bitkit.App +import to.bitkit.R +import to.bitkit.async.appScope +import to.bitkit.di.BgDispatcher +import to.bitkit.env.Env +import to.bitkit.ext.alarmManager +import to.bitkit.ext.connectivityManager +import to.bitkit.ext.nowMs +import to.bitkit.models.BITCOIN_SYMBOL +import to.bitkit.models.formatToModernDisplay +import to.bitkit.ui.areNotificationsEnabled +import to.bitkit.ui.pushNotification +import to.bitkit.utils.Logger +import to.bitkit.utils.batterySettingsSnapshot +import to.bitkit.utils.logBatterySettings +import java.io.File +import java.util.Date +import java.util.concurrent.TimeUnit +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.time.Clock +import kotlin.time.Duration +import kotlin.time.Duration.Companion.minutes + +/** + * Runs a Spark exit while Bitkit is closed, and tells the user when it cannot. + * + * A unique periodic work drives the exit every 15 minutes while it runs; WorkManager keeps it across app kills and + * reboots, and app start queues it again if it is missing. Each run that moves the exit forward re-arms a deadline + * alarm 12 blocks into the operators' window of the next step. The alarm fires only when no run made it in time + * (no network, battery settings, background restrictions, failures), and then posts a notification naming the + * deadline. Needing more fee funding is notified at once. + */ +@Singleton +class SparkExitWork @Inject constructor( + @ApplicationContext private val context: Context, + @BgDispatcher private val bgDispatcher: CoroutineDispatcher, + private val clock: Clock, +) { + companion object { + private const val TAG = "SparkExitWork" + private const val PERIODIC_WORK = "spark-exit-tick" + private const val CATCH_UP_WORK = "spark-exit-catch-up" + const val DEADLINE_ACTION = "to.bitkit.spark-exit.DEADLINE" + private const val PREFERENCES = "spark-exit-work" + private const val KEY_WARN_AT = "warn-at" + private const val KEY_DEADLINE_AT = "deadline-at" + private const val NOTIFICATION_ID = 7797 + + /** The shortest period WorkManager runs periodic work at. */ + val PERIOD = 15.minutes + + /** The exit of the wallet Bitkit runs, read before the wallet graph exists. */ + private fun store() = SparkExitStore(File(Env.sparkExitRecordPath(0))) + } + + private val scope = appScope(bgDispatcher, TAG) + private val preferences get() = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) + private val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build() + + fun schedulePeriodic() { + val request = PeriodicWorkRequestBuilder(PERIOD.inWholeMinutes, TimeUnit.MINUTES) + .setConstraints(constraints) + .build() + WorkManager.getInstance(context) + .enqueueUniquePeriodicWork(PERIODIC_WORK, ExistingPeriodicWorkPolicy.KEEP, request) + } + + /** + * At app start, boot and app update: queues the periodic work again when an exit runs, and re-arms its deadline + * alarm, which a reboot clears. + */ + fun ensureScheduled() { + scope.launch { + val record = runCatching { store().load() }.getOrNull() + if (record?.needsDriving != true) { + if (preferences.contains(KEY_WARN_AT)) cancelAll() + return@launch + } + schedulePeriodic() + val now = clock.nowMs() + val warnAt = preferences.getLong(KEY_WARN_AT, 0L) + val deadlineAt = preferences.getLong(KEY_DEADLINE_AT, 0L) + if (record.phase == SparkExitRecord.Phase.Running && (warnAt == 0L || !isDeadlineArmed())) { + if (warnAt == 0L) { + armDeadline(SparkExitMath.deadline(Duration.ZERO, Env.network), now) + } else { + setAlarm(maxOf(warnAt, now), deadlineAt) + } + } + Logger.debug("Ensured Spark exit background work (${context.logBatterySettings()})", context = TAG) + } + } + + /** Re-arms the warning that the exit fell behind; every run that moves the exit forward pushes it back. */ + fun armDeadline(deadline: SparkExitDeadline, nowMillis: Long = clock.nowMs()) { + setAlarm( + warnAt = nowMillis + deadline.warnIn.inWholeMilliseconds, + deadlineAt = nowMillis + deadline.deadlineIn.inWholeMilliseconds, + ) + } + + fun cancelDeadline() { + deadlinePendingIntent(PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE)?.let { + context.alarmManager.cancel(it) + it.cancel() + } + preferences.edit { + remove(KEY_WARN_AT) + remove(KEY_DEADLINE_AT) + } + } + + fun cancelAll() { + WorkManager.getInstance(context).run { + cancelUniqueWork(PERIODIC_WORK) + cancelUniqueWork(CATCH_UP_WORK) + } + cancelDeadline() + } + + /** + * The deadline alarm fired, so no run moved the exit forward in time: tells the user why and until when, tries a + * run now, and warns again later if it stays behind. + */ + suspend fun onDeadline() { + val record = runCatching { store().load() }.getOrNull() + val alert = SparkExitAlerts.reason(record, isOnline(), backgroundLimits()) + Logger.warn( + "Spark exit deadline alarm fired with alert '$alert' (${context.logBatterySettings()})", + context = TAG, + ) + if (alert == null || record?.phase != SparkExitRecord.Phase.Running) { + cancelDeadline() + return + } + val deadlineAt = preferences.getLong(KEY_DEADLINE_AT, 0L).takeIf { it > clock.nowMs() } + notify(alert, deadlineAt) + WorkManager.getInstance(context).enqueueUniqueWork( + CATCH_UP_WORK, + ExistingWorkPolicy.KEEP, + OneTimeWorkRequestBuilder().setConstraints(constraints).build(), + ) + armDeadline(SparkExitMath.deadline(Duration.ZERO, Env.network)) + } + + /** Posts the exit's notification, unless Bitkit is on screen, where the progress screen says the same. */ + fun notify(alert: SparkExitAlert, deadlineAtMillis: Long? = null, amountSats: ULong? = null) { + // Losses are posted on screen too: the user may be anywhere in the app when an exit fails or loses a leaf. + if (App.currentActivity?.value != null && alert !in ALWAYS_POSTED) return + val time = deadlineAtMillis?.let { DateFormat.getTimeFormat(context).format(Date(it)) } + val amount = amountSats?.let { "$BITCOIN_SYMBOL ${it.formatToModernDisplay()}" } + val text = context.getString(alert.textRes(hasDeadline = time != null)) + .replace("{time}", time.orEmpty()) + .replace("{amount}", amount.orEmpty()) + context.pushNotification( + title = context.getString(R.string.lightning__spark_exit__notification_title), + text = text, + bigText = text, + id = NOTIFICATION_ID, + ) + } + + fun backgroundLimits(): SparkExitBackgroundLimits { + val battery = context.batterySettingsSnapshot() + return SparkExitBackgroundLimits( + isRestricted = battery.isBackgroundRestricted == true, + isPowerSaveMode = battery.isPowerSaveMode == true, + isOptimized = battery.isIgnoringBatteryOptimizations == false, + areNotificationsEnabled = context.areNotificationsEnabled(), + ) + } + + private fun isOnline(): Boolean { + val connectivity = context.connectivityManager + val capabilities = connectivity.getNetworkCapabilities(connectivity.activeNetwork) ?: return false + return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + } + + private fun setAlarm(warnAt: Long, deadlineAt: Long) { + preferences.edit { + putLong(KEY_WARN_AT, warnAt) + putLong(KEY_DEADLINE_AT, deadlineAt) + } + val operation = checkNotNull( + deadlinePendingIntent(PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE), + ) { "Expected the Spark exit deadline PendingIntent" } + // Inexact but allowed in Doze, which needs no exact alarm permission; the window is hours on mainnet. + runCatching { context.alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, warnAt, operation) } + .onFailure { Logger.error("Failed to arm the Spark exit deadline alarm", it, context = TAG) } + } + + private fun isDeadlineArmed(): Boolean = + deadlinePendingIntent(PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE) != null + + private fun deadlinePendingIntent(flags: Int): PendingIntent? = PendingIntent.getBroadcast( + context, + 0, + Intent(context, SparkExitReceiver::class.java).setAction(DEADLINE_ACTION), + flags, + ) +} + +/** What Android lets Bitkit do in the background, for the notification and the progress screen. */ +data class SparkExitBackgroundLimits( + /** The user restricted Bitkit's background use: no work or alarm runs while it is closed. */ + val isRestricted: Boolean = false, + val isPowerSaveMode: Boolean = false, + /** Battery optimization is on, Android's default, so background runs wait for Doze's windows. */ + val isOptimized: Boolean = false, + val areNotificationsEnabled: Boolean = true, +) + +/** Why the user is asked to open Bitkit. */ +enum class SparkExitAlert { Funding, Lost, Failed, Rejected, Offline, Restricted, Battery, Behind } + +private val ALWAYS_POSTED = setOf(SparkExitAlert.Lost, SparkExitAlert.Failed) + +object SparkExitAlerts { + /** + * What a tick that moved the exit from [previous] to [record] lost, each posted once: leaves an older owner + * claimed, and the exit failing, unless it failed because every leaf was claimed, which the lost leaves say. + */ + fun losses(record: SparkExitRecord, previous: SparkExitRecord): List { + val phase = record.phase + return listOfNotNull( + SparkExitAlert.Lost.takeIf { record.lostLeaves.size > previous.lostLeaves.size }, + SparkExitAlert.Failed.takeIf { + phase is SparkExitRecord.Phase.Failed && !record.isEveryLeafLost && + previous.phase !is SparkExitRecord.Phase.Failed + }, + ) + } + + /** Why a running exit fell behind its deadline, or null when it needs nothing from the user. */ + fun reason(record: SparkExitRecord?, isOnline: Boolean, limits: SparkExitBackgroundLimits): SparkExitAlert? { + if (record?.isActive != true) return null + return when { + record.phase is SparkExitRecord.Phase.NeedsFunding -> SparkExitAlert.Funding + record.phase != SparkExitRecord.Phase.Running -> null + record.surfacedRejection != null -> SparkExitAlert.Rejected + !isOnline -> SparkExitAlert.Offline + limits.isRestricted -> SparkExitAlert.Restricted + // Battery optimization alone is Android's default for nearly every app, so it names no cause. + limits.isPowerSaveMode -> SparkExitAlert.Battery + else -> SparkExitAlert.Behind + } + } +} + +private fun SparkExitAlert.textRes(hasDeadline: Boolean): Int = when (this) { + SparkExitAlert.Funding -> R.string.lightning__spark_exit__notification_funding + SparkExitAlert.Lost -> R.string.lightning__spark_exit__notification_lost + SparkExitAlert.Failed -> R.string.lightning__spark_exit__notification_failed + SparkExitAlert.Rejected if hasDeadline -> R.string.lightning__spark_exit__notification_rejected + SparkExitAlert.Offline if hasDeadline -> R.string.lightning__spark_exit__notification_offline + SparkExitAlert.Restricted if hasDeadline -> R.string.lightning__spark_exit__notification_restricted + SparkExitAlert.Battery if hasDeadline -> R.string.lightning__spark_exit__notification_battery + SparkExitAlert.Behind if hasDeadline -> R.string.lightning__spark_exit__notification_behind + else -> R.string.lightning__spark_exit__notification_late +} + +@HiltWorker +class SparkExitWorker @AssistedInject constructor( + @Assisted appContext: Context, + @Assisted workerParams: WorkerParameters, + private val sparkExitRepo: SparkExitRepo, +) : CoroutineWorker(appContext, workerParams) { + companion object { + private const val TAG = "SparkExitWorker" + } + + override suspend fun doWork(): Result { + Logger.debug("Driving the Spark exit in background (${applicationContext.logBatterySettings()})", context = TAG) + sparkExitRepo.runInBackground().onFailure { + Logger.warn("Failed to drive the Spark exit in background", it, context = TAG) + return Result.retry() + } + return Result.success() + } +} + +/** The deadline alarm, and boot and app updates, which clear alarms. */ +class SparkExitReceiver : BroadcastReceiver() { + @EntryPoint + @InstallIn(SingletonComponent::class) + interface SparkExitReceiverEntryPoint { + fun sparkExitWork(): SparkExitWork + + @BgDispatcher + fun bgDispatcher(): CoroutineDispatcher + } + + override fun onReceive(context: Context, intent: Intent) { + val entryPoint = EntryPointAccessors.fromApplication( + context.applicationContext, + SparkExitReceiverEntryPoint::class.java, + ) + val work = entryPoint.sparkExitWork() + when (intent.action) { + SparkExitWork.DEADLINE_ACTION -> { + val pending = goAsync() + appScope(entryPoint.bgDispatcher(), TAG).launch { + try { + work.onDeadline() + } finally { + pending.finish() + } + } + } + Intent.ACTION_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED -> work.ensureScheduled() + } + } + + private companion object { + const val TAG = "SparkExitReceiver" + } +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 398d92f4b5..c630dd7dac 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1,5 +1,6 @@ package to.bitkit.repositories +import breez_sdk_spark.AutoOptimizationEvent import breez_sdk_spark.ClaimDeferredReason import breez_sdk_spark.ClaimDepositOutcome import breez_sdk_spark.FeePolicy @@ -33,6 +34,7 @@ import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull import org.lightningdevkit.ldknode.Event import org.lightningdevkit.ldknode.PaymentFailureReason import org.lightningdevkit.ldknode.PaymentId @@ -56,6 +58,7 @@ import javax.inject.Inject import javax.inject.Provider import javax.inject.Singleton import kotlin.time.Clock +import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant import breez_sdk_spark.PaymentType as SparkPaymentType @@ -87,6 +90,12 @@ class SparkRepo @Inject constructor( private val SEND_STATUS_PRIORITY = listOf(PaymentStatus.COMPLETED, PaymentStatus.PENDING, PaymentStatus.FAILED) + /** How long the SDK leaves the counter-swap of a leaf swap cut short unclaimed (its 300 s), plus a margin. */ + private val COUNTER_SWAP_GRACE = 330.seconds + + /** The longest an exit quote waits for a running leaf optimization to end. */ + private val OPTIMIZATION_WAIT = 2.minutes + /** Seconds a withdrawal quote must still hold to be reused, so it can't expire mid-send. */ private const val QUOTE_EXPIRY_MARGIN_SECS = 30uL } @@ -107,6 +116,9 @@ class SparkRepo @Inject constructor( private var eventsJob: Job? = null + /** The SDK is swapping leaves with the operators; their value is in flight until it ends. */ + private val isOptimizing = MutableStateFlow(false) + /** Watchers of the claims of deposits this app sent, by txid; they outlive the screens that start them. */ private val claimJobs = ConcurrentHashMap() @@ -126,11 +138,24 @@ class SparkRepo @Inject constructor( /** Fires once Spark connects and whenever its unilateral exit data changes, so the exit data backup is redone. */ val exitStateChanged: SharedFlow = _exitStateChanged.asSharedFlow() + /** The wallet Spark last started for. */ + @Volatile + var walletIndex: Int = 0 + private set + + private val _walletWiped = MutableSharedFlow(extraBufferCapacity = 1) + + /** Fires with the wallet index once its Spark wallet, and any emergency exit of it, was wiped. */ + val walletWiped: SharedFlow = _walletWiped.asSharedFlow() + suspend fun start(walletIndex: Int): Result = withContext(bgDispatcher) { if (!sparkService.isSupported) return@withContext Result.success(Unit) + this@SparkRepo.walletIndex = walletIndex runSuspendCatching { if (eventsJob == null) eventsJob = scope.launch { sparkService.events.collect { onSdkEvent(it) } } - sparkService.connect(walletIndex) + val isExiting = exitStore(walletIndex).isActive() + _state.update { it.copy(isExiting = isExiting) } + sparkService.connect(walletIndex, isExiting) importRestoredExitState(walletIndex) _exitStateChanged.emit(Unit) refresh() @@ -141,6 +166,7 @@ class SparkRepo @Inject constructor( } suspend fun stop() = withContext(bgDispatcher) { + onOptimizationCutShort() runSuspendCatching { sparkService.disconnect() } .onFailure { Logger.warn("Failed to stop Spark wallet", it, context = TAG) } _state.update { it.copy(isReady = false, hasSynced = false) } @@ -149,10 +175,89 @@ class SparkRepo @Inject constructor( suspend fun wipe(walletIndex: Int) = withContext(bgDispatcher) { runSuspendCatching { sparkService.wipeStorage(walletIndex) } .onFailure { Logger.error("Failed to wipe Spark wallet", it, context = TAG) } + runSuspendCatching { exitStore(walletIndex).delete() } + .onFailure { Logger.error("Failed to wipe Spark exit record", it, context = TAG) } _state.update { SparkState(isSupported = sparkService.isSupported) } + _walletWiped.emit(walletIndex) + } + + /** + * Takes Spark off the Lightning rail while an emergency exit runs, so no payment moves leaves the exit is + * spending, and connects Spark again so its leaf optimization follows: off while exiting, on once it ends. + */ + suspend fun setExiting(isExiting: Boolean): Result = withContext(bgDispatcher) { + if (_state.value.isExiting == isExiting && sparkService.isConnected) return@withContext Result.success(Unit) + _state.update { it.copy(isExiting = isExiting) } + runSuspendCatching { + onOptimizationCutShort() + sparkService.disconnect() + sparkService.connect(walletIndex, isExiting) + refresh() + }.onFailure { + Logger.error("Failed to reconnect Spark with exit '$isExiting'", it, context = TAG) + } + } + + /** Whether an exit quote has to wait first: a leaf optimization runs, or one ran or was cut short recently. */ + suspend fun needsSettling(): Boolean = + isOptimizing.value || cacheStore.data.first().sparkOptimizationActivityAt != null + + /** + * Settles the leaves for an emergency exit quote, which exits the leaves listed then. The balance leaves out an + * unclaimed counter-swap, and a leaf optimization cut short leaves its counter-swap unclaimed for the SDK's 300 s + * grace. So: wait for a running optimization, then until the last one is [COUNTER_SWAP_GRACE] old, then sync, + * which claims counter-swaps past the grace. + */ + suspend fun settleForExit(): Result = withContext(bgDispatcher) { + runSuspendCatching { + awaitOptimizationIdle() + cacheStore.data.first().sparkOptimizationActivityAt?.let { + delay(Instant.fromEpochMilliseconds(it) + COUNTER_SWAP_GRACE - clock.now()) + } + sparkService.syncWallet() + cacheStore.update { it.copy(sparkOptimizationActivityAt = null) } + refresh() + } + } + + /** Waits, up to [OPTIMIZATION_WAIT], for a running leaf optimization to end. */ + suspend fun awaitOptimizationIdle() { + if (withTimeoutOrNull(OPTIMIZATION_WAIT) { isOptimizing.first { !it } } == null) { + Logger.warn("Gave up waiting for a Spark leaf optimization to end", context = TAG) + } + } + + private suspend fun onOptimization(event: AutoOptimizationEvent) { + when (event) { + is AutoOptimizationEvent.Started, is AutoOptimizationEvent.RoundCompleted -> { + isOptimizing.update { true } + stampOptimizationActivity() + } + AutoOptimizationEvent.Cancelled, is AutoOptimizationEvent.Failed -> { + isOptimizing.update { false } + stampOptimizationActivity() + } + AutoOptimizationEvent.Completed, AutoOptimizationEvent.Skipped -> { + isOptimizing.update { false } + cacheStore.update { it.copy(sparkOptimizationActivityAt = null) } + } + } + } + + private suspend fun onOptimizationCutShort() { + if (!isOptimizing.value) return + isOptimizing.update { false } + stampOptimizationActivity() } - fun canReceive(): Boolean = _state.value.isReady + private suspend fun stampOptimizationActivity() { + val now = clock.now().toEpochMilliseconds() + cacheStore.update { it.copy(sparkOptimizationActivityAt = now) } + } + + private fun exitStore(walletIndex: Int) = SparkExitStore(File(Env.sparkExitRecordPath(walletIndex))) + + fun canReceive(): Boolean = _state.value.isReady && !_state.value.isExiting fun canSend(amountSats: ULong): Boolean = _state.value.isReady && _state.value.sendableSats >= amountSats @@ -187,6 +292,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { ensurePaymentDeadline(paymentDeadlineAt) if (!sparkService.isConnected) throw SparkError.SendRefused("Spark is not connected") + if (_state.value.isExiting) throw SparkError.SendRefused("Spark is in an emergency exit") val prepared = runSuspendCatching { sparkService.prepareSend(bolt11, amountSats) } .getOrElse { throw SparkError.SendRefused("Spark could not prepare the payment", it) } val method = prepared.paymentMethod as? SendPaymentMethod.Bolt11Invoice @@ -317,6 +423,7 @@ class SparkRepo @Inject constructor( /** Moves the whole Spark balance to the on-chain [address], fees included, for Spending to Savings. */ suspend fun withdrawAll(address: String): Result = withContext(bgDispatcher) { runSuspendCatching { + if (_state.value.isExiting) throw SparkError.SendRefused("Spark is in an emergency exit") val payment = sparkService.send(prepareWithdrawAll(address)) preparedWithdrawal = null (payment.details as? PaymentDetails.Withdraw)?.txId?.let { withdrawalTxids += it } @@ -576,6 +683,7 @@ class SparkRepo @Inject constructor( is SdkEvent.NewDeposits -> refresh() is SdkEvent.UnilateralExitStateChanged -> _exitStateChanged.emit(Unit) is SdkEvent.ClaimedDeposits -> refresh() + is SdkEvent.AutoOptimization -> onOptimization(event.optimizationEvent) else -> Unit } }.onFailure { @@ -670,9 +778,17 @@ data class SparkState( val deposits: ImmutableList = persistentListOf(), val withdrawals: ImmutableList = persistentListOf(), val recoverableFundsSats: ULong = 0uL, + /** An emergency exit is moving the balance on-chain: Spark then neither sends nor receives. */ + val isExiting: Boolean = false, ) { /** The most Spark can send once its service fee is paid, so a payment near the full balance isn't offered. */ - val sendableSats: ULong get() = SparkFees.sendableSats(balanceSats) + val sendableSats: ULong get() = if (isExiting) 0uL else SparkFees.sendableSats(balanceSats) + + /** Spark can take payments and transfers: connected, and no emergency exit runs. */ + val isUsable: Boolean get() = isReady && !isExiting + + /** The balance Spending counts; during an emergency exit it is in transfer to Savings instead. */ + val spendingSats: ULong get() = if (isExiting) 0uL else balanceSats } object SparkFees { diff --git a/app/src/main/java/to/bitkit/repositories/TransferRepo.kt b/app/src/main/java/to/bitkit/repositories/TransferRepo.kt index 041def1907..4e998dc4bd 100644 --- a/app/src/main/java/to/bitkit/repositories/TransferRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/TransferRepo.kt @@ -9,6 +9,7 @@ import com.synonym.bitkitcore.PaymentType import com.synonym.bitkitcore.SortDirection import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map @@ -44,19 +45,27 @@ class TransferRepo @Inject constructor( private val coreService: CoreService, private val transferDao: TransferDao, private val clock: Clock, + private val sparkExitTip: SparkExitTip = SparkExitTip(), ) { private val lastOrdersFetchMs = AtomicLong(0L) val activeTransfers: Flow> = transferDao.getActiveTransfers() + /** The countdown of a force close or, without one, a Spark exit, whose heights are read on Spark's chain. */ val forceCloseRemainingDuration: Flow = combine( activeTransfers, lightningRepo.lightningState, - ) { transfers, lightningState -> + sparkExitTip.height, + ) { transfers, lightningState, sparkExitHeight -> val forceClose = transfers.firstOrNull { it.type == TransferType.FORCE_CLOSE } - ?: return@combine null - val targetHeight = forceClose.claimableAtHeight?.toUInt() ?: return@combine null - val currentHeight = lightningState.block()?.height ?: return@combine null + val sparkExit = transfers.firstOrNull { it.type == TransferType.SPARK_EXIT } + val (transfer, currentHeight) = when { + forceClose != null -> forceClose to lightningState.block()?.height + sparkExit != null -> sparkExit to sparkExitHeight + else -> return@combine null + } + val targetHeight = transfer.claimableAtHeight?.toUInt() ?: return@combine null + currentHeight ?: return@combine null val remaining = BlockTimeHelpers.blocksRemaining(targetHeight, currentHeight) if (remaining <= 0) return@combine null BlockTimeHelpers.getDurationForBlocks(remaining) @@ -110,6 +119,18 @@ class TransferRepo @Inject constructor( } } + /** Moves a transfer's countdown target, as a Spark exit learns when its timelocks mature. */ + suspend fun updateClaimableAtHeight( + id: String, + claimableAtHeight: UInt? + ): Result = withContext(bgDispatcher) { + runSuspendCatching { transferDao.updateClaimableAtHeight(id, claimableAtHeight?.toInt()) } + } + + suspend fun isSettled(id: String): Result = withContext(bgDispatcher) { + runSuspendCatching { transferDao.getById(id)?.isSettled ?: true } + } + suspend fun findLspOrderIdByFundingTxId(fundingTxId: String): Result = withContext(bgDispatcher) { runSuspendCatching { transferDao.getByFundingTxId(fundingTxId)?.lspOrderId @@ -269,7 +290,8 @@ class TransferRepo @Inject constructor( channels: List, balances: BalanceDetails?, ) { - val toSavings = activeTransfers.filter { it.type.isToSavings() } + // A Spark exit has no channel; the exit settles its transfer once the sweep reaches savings. + val toSavings = activeTransfers.filter { it.type.isToSavings() && it.type != TransferType.SPARK_EXIT } if (toSavings.isEmpty()) return val balanceDetails = balances ?: run { @@ -407,6 +429,12 @@ class TransferRepo @Inject constructor( } } +/** The tip of the chain the Spark SDK reads, as a running Spark exit last saw it. */ +@Singleton +class SparkExitTip @Inject constructor() { + val height = MutableStateFlow(null) +} + private fun IBtOrder.hasClosedChannel(): Boolean { val channel = channel ?: return false return channel.state == BtOpenChannelState.CLOSED || channel.closingTxId != null || channel.close != null diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index d988881a95..ca628a434d 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -124,9 +124,9 @@ class WalletRepo @Inject constructor( } } repoScope.launch { - sparkRepo.state.map { it.balanceSats to it.pendingDepositSats }.distinctUntilChanged().collect { - if (walletExists()) syncBalances() - } + sparkRepo.state.map { Triple(it.balanceSats, it.pendingDepositSats, it.isExiting) } + .distinctUntilChanged() + .collect { if (walletExists()) syncBalances() } } } diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index e11294d0b8..4d6d5aae56 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -1,10 +1,13 @@ package to.bitkit.services import breez_sdk_spark.BreezSdk +import breez_sdk_spark.CheckRecoverFundsRequest +import breez_sdk_spark.CheckRecoverFundsResponse import breez_sdk_spark.ClaimDepositOutcome import breez_sdk_spark.ClaimDepositRequest import breez_sdk_spark.Config import breez_sdk_spark.ConnectRequest +import breez_sdk_spark.CpfpSigner import breez_sdk_spark.DepositInfo import breez_sdk_spark.EventListener import breez_sdk_spark.FeePolicy @@ -21,10 +24,14 @@ import breez_sdk_spark.MaxOnchainFee import breez_sdk_spark.OnchainConfirmationSpeed import breez_sdk_spark.Payment import breez_sdk_spark.PaymentRequest +import breez_sdk_spark.PrepareRecoverFundsRequest +import breez_sdk_spark.PrepareRecoverFundsResponse import breez_sdk_spark.PrepareSendPaymentRequest import breez_sdk_spark.PrepareSendPaymentResponse import breez_sdk_spark.ReceivePaymentMethod import breez_sdk_spark.ReceivePaymentRequest +import breez_sdk_spark.RecoverFundsRequest +import breez_sdk_spark.RecoverFundsResponse import breez_sdk_spark.SdkEvent import breez_sdk_spark.Seed import breez_sdk_spark.SendPaymentMethod @@ -42,6 +49,7 @@ import org.lightningdevkit.ldknode.Network import to.bitkit.data.keychain.Keychain import to.bitkit.env.Env import to.bitkit.models.safe +import to.bitkit.repositories.SparkExitRecovering import to.bitkit.utils.AppError import to.bitkit.utils.Logger import to.bitkit.utils.ServiceError @@ -66,7 +74,7 @@ class SparkService @Inject constructor( * Bitkit's settings over the SDK's [defaults]. Breez's real-time data sync server and its Lightning address * (LNURL) server stay off on every network. */ - internal fun configure(defaults: Config, apiKey: String?): Config = defaults.apply { + internal fun configure(defaults: Config, apiKey: String?, isExiting: Boolean): Config = defaults.apply { this.apiKey = apiKey realTimeSyncServerUrl = null lnurlDomain = null @@ -76,6 +84,7 @@ class SparkService @Inject constructor( onchain = MaxOnchainFee.NetworkRecommended(DEPOSIT_CLAIM_FEE_LEEWAY_SAT_PER_VB), proportionalPpm = null, ) + leafOptimizationConfig = leafOptimizationConfig.copy(autoEnabled = !isExiting) } /** Leeway in sat/vB over the recommended fee that an automatic deposit claim may pay. */ @@ -136,12 +145,16 @@ class SparkService @Inject constructor( */ val prefersSpark: Boolean get() = Env.network == Network.REGTEST - suspend fun connect(walletIndex: Int) = mutex.withLock { + /** + * Connects the Spark wallet. While [isExiting], leaf optimization stays off: it swaps leaves with the operators, + * which would hand the leaves an emergency exit is spending to someone else, whose refunds then confirm first. + */ + suspend fun connect(walletIndex: Int, isExiting: Boolean = false) = mutex.withLock { if (sdk != null) return@withLock val network = sparkNetwork() ?: throw SparkError.Unsupported() val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) - val config = configure(defaultConfig(network), Env.breezApiKey) + val config = configure(defaultConfig(network), Env.breezApiKey, isExiting) val storageDir = File(Env.sparkStoragePath(walletIndex)).apply { mkdirs() }.path val connected = connect(ConnectRequest(config, Seed.Mnemonic(mnemonic, passphrase), storageDir)) listenerId = connected.addEventListener( @@ -152,7 +165,7 @@ class SparkService @Inject constructor( }, ) sdk = connected - Logger.info("Connected Spark wallet on '$network'", context = TAG) + Logger.info("Connected Spark wallet on '$network' with exit '$isExiting'", context = TAG) } suspend fun disconnect() = mutex.withLock { @@ -242,6 +255,9 @@ class SparkService @Inject constructor( suspend fun importExitState(exitState: String): ImportUnilateralExitStateResponse = requireSdk().importUnilateralExitState(ImportUnilateralExitStateRequest(exitState)) + /** The SDK calls of an emergency exit, or null while Spark is not connected. */ + fun exitRecovering(): SparkExitRecovering? = sdk?.let(::BreezSparkExitRecovering) + /** The Spark network this build runs on, as exit data backups record it. */ val networkName: String? get() = sparkNetwork()?.name?.lowercase() @@ -254,6 +270,17 @@ class SparkService @Inject constructor( } } +class BreezSparkExitRecovering(private val sdk: BreezSdk) : SparkExitRecovering { + override suspend fun prepare(request: PrepareRecoverFundsRequest): PrepareRecoverFundsResponse = + sdk.prepareRecoverFunds(request) + + override suspend fun recover(request: RecoverFundsRequest, signer: CpfpSigner?): RecoverFundsResponse = + sdk.recoverFunds(request, signer) + + override suspend fun check(recovery: RecoverFundsResponse): CheckRecoverFundsResponse = + sdk.checkRecoverFunds(CheckRecoverFundsRequest(recovery)) +} + sealed class SparkError(message: String, cause: Throwable? = null) : AppError(message, cause) { class Unsupported : SparkError("Spark is not available on this network or build") class NotConnected : SparkError("Spark wallet is not connected") diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index c0789dd495..911d7c5071 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -38,6 +38,7 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.navigation.NavBackStackEntry import androidx.navigation.NavController import androidx.navigation.NavDestination.Companion.hasRoute import androidx.navigation.NavGraphBuilder @@ -205,6 +206,12 @@ import to.bitkit.ui.settings.lightning.CloseConnectionScreen import to.bitkit.ui.settings.lightning.LightningConnectionsScreen import to.bitkit.ui.settings.lightning.LightningConnectionsViewModel import to.bitkit.ui.settings.lightning.SparkDetailScreen +import to.bitkit.ui.settings.lightning.SparkExitConfirmScreen +import to.bitkit.ui.settings.lightning.SparkExitFundingScreen +import to.bitkit.ui.settings.lightning.SparkExitIntroScreen +import to.bitkit.ui.settings.lightning.SparkExitProgressScreen +import to.bitkit.ui.settings.lightning.SparkExitQuoteScreen +import to.bitkit.ui.settings.lightning.SparkExitViewModel import to.bitkit.ui.settings.pin.PinManagementScreen import to.bitkit.ui.settings.quickPay.QuickPayIntroScreen import to.bitkit.ui.settings.quickPay.QuickPaySettingsScreen @@ -330,10 +337,12 @@ fun ContentView( appViewModel.checkAdoptedPubkySource() appViewModel.refreshPrivatePaykitEndpoints() appViewModel.startPaykitPaymentRequestPolling() + appViewModel.startSparkExitDriving() } Lifecycle.Event.ON_STOP -> { appViewModel.stopPaykitPaymentRequestPolling() + appViewModel.stopSparkExitDriving() val keptAliveByService = notificationsGranted && keepActiveInBackground && appViewModel.isForegroundServiceRunning() @@ -1109,7 +1118,7 @@ private fun RootNavHost( val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() val hasSeenSpendingIntro by settingsViewModel.hasSeenSpendingIntro.collectAsStateWithLifecycle() FundingScreen( - canFundWithSpark = sparkState.isReady, + canFundWithSpark = sparkState.isUsable, onTransfer = { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) }, onFund = { scope.launch { @@ -1191,7 +1200,7 @@ private fun RootNavHost( val sparkState by walletViewModel.sparkState.collectAsStateWithLifecycle() TransferLearnMoreScreen( viewModel = hiltViewModel(parentEntry), - spendingBalanceSats = sparkState.balanceSats.toLong(), + spendingBalanceSats = sparkState.spendingSats.toLong(), onBackClick = { navController.popBackStack() }, onContinueClick = { navController.popBackStack() }, ) @@ -1346,7 +1355,7 @@ private fun NavGraphBuilder.home( onActivityItemClick = { navController.navToActivityDetail(it) }, onEmptyActivityRowClick = { appViewModel.showSheet(Sheet.Receive()) }, onTransferToSpendingClick = { - if (sparkState.isReady) { + if (sparkState.isUsable) { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) } else { appViewModel.showSheet(Sheet.TransferUnavailable) @@ -1365,7 +1374,7 @@ private fun NavGraphBuilder.home( SpendingWalletScreen( channels = lightningState.channels, - hasSparkBalance = sparkState.balanceSats > 0uL, + hasSparkBalance = sparkState.spendingSats > 0uL, lightningActivities = lightningActivities ?: persistentListOf(), onAllActivityButtonClick = { navController.navigateToAllActivity(activityListViewModel::clearFilters) }, onActivityItemClick = { navController.navToActivityDetail(it) }, @@ -1378,7 +1387,7 @@ private fun NavGraphBuilder.home( } }, onTransferFromSavingsClick = { - if (sparkState.isReady) { + if (sparkState.isUsable) { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) } else { appViewModel.showSheet(Sheet.TransferUnavailable) @@ -1395,7 +1404,7 @@ private fun NavGraphBuilder.home( walletId = walletId, onActivityItemClick = { navController.navToActivityDetail(it) }, onTransferToSpendingClick = { walletId -> - if (sparkState.isReady) { + if (sparkState.isUsable) { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro, walletId) } else { appViewModel.showSheet(Sheet.TransferUnavailable) @@ -2001,8 +2010,12 @@ private fun NavGraphBuilder.lightningConnections( navController.navigateToTransferSavingsIntro() } }, + onEmergencyExit = { showsResult -> + navController.navigateTo(if (showsResult) Routes.SparkExitProgress else Routes.SparkExitIntro) + }, ) } + sparkExit(navController) deepLinkableComposable { val route = it.toRoute() CloseConnectionScreen( @@ -2013,6 +2026,54 @@ private fun NavGraphBuilder.lightningConnections( } } +private fun NavGraphBuilder.sparkExit(navController: NavHostController) { + @Composable + fun exitViewModel(entry: NavBackStackEntry): SparkExitViewModel { + val parentEntry = remember(entry) { navController.getBackStackEntry(Routes.ConnectionsNav) } + return hiltViewModel(parentEntry) + } + val leaveExit = { navController.popBackStack(inclusive = false) } + composableWithDefaultTransitions { + SparkExitIntroScreen( + onBack = { navController.popBackStack() }, + onContinue = { navController.navigateTo(Routes.SparkExitQuote) }, + ) + } + composableWithDefaultTransitions { + SparkExitQuoteScreen( + viewModel = exitViewModel(it), + onBack = { navController.popBackStack() }, + onContinue = { needsFunding -> + navController.navigateTo(if (needsFunding) Routes.SparkExitFunding else Routes.SparkExitConfirm) + }, + ) + } + composableWithDefaultTransitions { + SparkExitFundingScreen( + viewModel = exitViewModel(it), + onBack = { navController.popBackStack() }, + onContinue = { navController.navigateTo(Routes.SparkExitConfirm) }, + ) + } + composableWithDefaultTransitions { + SparkExitConfirmScreen( + viewModel = exitViewModel(it), + onBack = { navController.popBackStack() }, + onStart = { + leaveExit() + navController.navigateTo(Routes.SparkExitProgress) + }, + ) + } + composableWithDefaultTransitions { + SparkExitProgressScreen( + viewModel = exitViewModel(it), + onBack = { navController.popBackStack() }, + onDone = { leaveExit() }, + ) + } +} + private fun NavGraphBuilder.activityItem( activityListViewModel: ActivityListViewModel, navController: NavHostController, @@ -2474,6 +2535,21 @@ sealed interface Routes { @Serializable data class CloseConnection(val channelId: String) : Routes.DeepLinkable + @Serializable + data object SparkExitIntro : Routes.InternalOnly + + @Serializable + data object SparkExitQuote : Routes.InternalOnly + + @Serializable + data object SparkExitFunding : Routes.InternalOnly + + @Serializable + data object SparkExitConfirm : Routes.InternalOnly + + @Serializable + data object SparkExitProgress : Routes.InternalOnly + @Serializable data object DevSettings : Routes.DeepLinkable diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAdvancedScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAdvancedScreen.kt index b2c7f99962..303f5eaf8c 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAdvancedScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsAdvancedScreen.kt @@ -63,7 +63,7 @@ fun SavingsAdvancedScreen( val openChannels = lightningState.channels.filterOpen() val sparkState by wallet.sparkState.collectAsStateWithLifecycle() - val sparkSats = sparkState.balanceSats + val sparkSats = sparkState.spendingSats var selectedChannelIds by remember { mutableStateOf(setOf()) } var isSparkSelected by remember { mutableStateOf(true) } diff --git a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt index 743cdc390a..85b9632e9b 100644 --- a/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/transfer/SavingsConfirmScreen.kt @@ -82,7 +82,7 @@ fun SavingsConfirmScreen( val openChannels = lightningState.channels.filterOpen() val sparkState by wallet.sparkState.collectAsStateWithLifecycle() - val sparkSats = sparkState.balanceSats + val sparkSats = sparkState.spendingSats // Spark counts as one more item: the selection list is offered once there are two to choose from. val hasMultiple = openChannels.size + (if (sparkSats > 0uL) 1 else 0) > 1 diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/HomeScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/HomeScreen.kt index 5f23a8830e..98b166b01f 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/HomeScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/HomeScreen.kt @@ -317,7 +317,7 @@ fun HomeScreen( } Suggestion.LIGHTNING -> when { - !sparkState.isReady -> appViewModel.showSheet(Sheet.TransferUnavailable) + !sparkState.isUsable -> appViewModel.showSheet(Sheet.TransferUnavailable) !hasSeenTransferIntro -> rootNavController.navigateToTransferIntro() else -> rootNavController.navigateToTransferFunding() } diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt index 11306c9312..f0feb93258 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/receive/ReceiveSheet.kt @@ -149,7 +149,7 @@ fun ReceiveSheet( onUsdtSelected = onUsdtSelected, walletState = walletState, lightningState = lightningState, - canReceiveWithSpark = sparkState.isReady, + canReceiveWithSpark = sparkState.isUsable, onClickReceiveCjit = { navController.navigateTo(ReceiveRoute.TransferUnavailable) }, onClickEditInvoice = { editInvoiceSourceTab = it diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt index 2687b39880..dda86e17ba 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt @@ -38,6 +38,8 @@ import to.bitkit.repositories.BlocktankRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LogsRepo import to.bitkit.repositories.SparkDeposit +import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SparkState import to.bitkit.repositories.SparkWithdrawal @@ -55,6 +57,7 @@ class LightningConnectionsViewModel @Inject constructor( private val logsRepo: LogsRepo, private val activityRepo: ActivityRepo, private val sparkRepo: SparkRepo, + private val sparkExitRepo: SparkExitRepo, ) : ViewModel() { companion object { @@ -101,9 +104,11 @@ class LightningConnectionsViewModel @Inject constructor( lightningRepo.lightningState, lightningRepo.lastKnownChannels, sparkRepo.state, - ) { lightningState, channels, sparkState -> - Triple(lightningState.nodeLifecycleState.isRunning(), channels, sparkState) - }.collect { (isNodeRunning, channels, sparkState) -> + sparkExitRepo.state, + ) { lightningState, channels, sparkState, exitState -> + ConnectionsSnapshot(lightningState.nodeLifecycleState.isRunning(), channels, sparkState, exitState) + }.collect { snapshot -> + val (isNodeRunning, channels, sparkState) = snapshot val connectionText = context.getString(R.string.lightning__connection) _uiState.update { @@ -115,10 +120,10 @@ class LightningConnectionsViewModel @Inject constructor( pendingConnections = channels.filterPending() .map { it.mapToUiModel(channels, connectionText) } .reversed().toImmutableList(), - localBalance = calculateLocalBalance(channels).safe() + sparkState.balanceSats.safe(), + localBalance = calculateLocalBalance(channels).safe() + sparkState.spendingSats.safe(), remoteBalance = channels.calculateRemoteBalance(), - spark = sparkState.toUi(lightningRepo), - isSparkReceiving = sparkState.isReady, + spark = sparkState.toUi(lightningRepo, snapshot.exitState.showsResult), + isSparkReceiving = sparkState.isUsable, ) } } @@ -238,7 +243,14 @@ data class SparkUi( val balanceSats: ULong, val deposits: ImmutableList = persistentListOf(), val withdrawals: ImmutableList = persistentListOf(), + val recoverableFundsSats: ULong = 0uL, + val isExiting: Boolean = false, + /** An exit runs, or ended with leftover fee funding not yet swept: Emergency exit opens its progress. */ + val showsExitResult: Boolean = false, ) { + /** The emergency exit is offered while Spark holds funds, and leads to its progress while it shows one. */ + val showsExit get() = balanceSats > 0uL || recoverableFundsSats > 0uL || showsExitResult + val pendingDeposits get() = deposits.filterNot { it.deposit.isClaimed } val claimedDeposits get() = deposits.filter { it.deposit.isClaimed } } @@ -249,19 +261,32 @@ data class SparkDepositUi( val confirmations: UInt? = null, ) -internal suspend fun SparkState.toUi(lightningRepo: LightningRepo): SparkUi? { - if (!isReady) return null +internal suspend fun SparkState.toUi(lightningRepo: LightningRepo, showsExitResult: Boolean = false): SparkUi? { + val showsExit = isExiting || showsExitResult + // An emergency exit keeps Spark listed, also while it cannot connect, so its progress stays reachable. + if (!isReady && !showsExit) return null // On regtest Spark always shows, so testers reach its deposit address to fund it from the faucet. - if (balanceSats == 0uL && deposits.isEmpty() && Env.network != Network.REGTEST) return null + val hasExit = showsExit || recoverableFundsSats > 0uL + if (balanceSats == 0uL && deposits.isEmpty() && !hasExit && Env.network != Network.REGTEST) return null return SparkUi( balanceSats = balanceSats, deposits = deposits.map { SparkDepositUi(it, if (it.isClaimed) null else lightningRepo.onchainConfirmations(it.txid)) }.toImmutableList(), withdrawals = withdrawals, + recoverableFundsSats = recoverableFundsSats, + isExiting = isExiting, + showsExitResult = showsExit, ) } +private data class ConnectionsSnapshot( + val isNodeRunning: Boolean, + val channels: List, + val sparkState: SparkState, + val exitState: SparkExitState, +) + data class ChannelUi( val name: String, val details: ChannelDetails, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt index e78fc3abaa..6adbdaceea 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt @@ -35,6 +35,7 @@ import to.bitkit.ui.components.ChannelStatusUi import to.bitkit.ui.components.LightningChannel import to.bitkit.ui.components.MoneyCaptionB import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.TertiaryButton import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.AppTopBar import to.bitkit.ui.scaffold.DrawerNavIcon @@ -47,6 +48,7 @@ import to.bitkit.ui.utils.getBlockExplorerUrl fun SparkDetailScreen( onBack: () -> Unit, onTransferToSavings: () -> Unit, + onEmergencyExit: (showsResult: Boolean) -> Unit, viewModel: SparkDetailViewModel = hiltViewModel(), ) { val context = LocalContext.current @@ -59,6 +61,7 @@ fun SparkDetailScreen( onOpenTx = { txId -> context.startActivity(Intent(Intent.ACTION_VIEW, getBlockExplorerUrl(txId).toUri())) }, onCopyText = { context.setClipboardText(it) }, onTransferToSavings = onTransferToSavings, + onEmergencyExit = { onEmergencyExit(uiState.spark?.showsExitResult == true) }, ) } @@ -71,6 +74,7 @@ private fun Content( onOpenTx: (String) -> Unit = {}, onCopyText: (String) -> Unit = {}, onTransferToSavings: () -> Unit = {}, + onEmergencyExit: () -> Unit = {}, ) { val spark = uiState.spark ?: SparkUi(balanceSats = 0uL) ScreenColumn { @@ -178,12 +182,19 @@ private fun Content( PrimaryButton( text = stringResource(R.string.wallet__transfer_to_savings), onClick = onTransferToSavings, - enabled = spark.balanceSats > 0uL, + enabled = spark.balanceSats > 0uL && !spark.isExiting, modifier = Modifier .fillMaxWidth() .testTag("SparkTransferToSavings") ) - + if (spark.showsExit) { + VerticalSpacer(8.dp) + TertiaryButton( + text = stringResource(R.string.lightning__spark_exit__button), + onClick = onEmergencyExit, + modifier = Modifier.testTag("SparkEmergencyExit") + ) + } VerticalSpacer(16.dp) } } diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt index ac14080045..dbea63b108 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt @@ -8,12 +8,14 @@ import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.lightningdevkit.ldknode.Network import to.bitkit.di.BgDispatcher import to.bitkit.env.Env import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkRepo import javax.inject.Inject import kotlin.time.Duration.Companion.milliseconds @@ -23,13 +25,17 @@ class SparkDetailViewModel @Inject constructor( @BgDispatcher private val bgDispatcher: CoroutineDispatcher, private val lightningRepo: LightningRepo, private val sparkRepo: SparkRepo, + private val sparkExitRepo: SparkExitRepo, ) : ViewModel() { private val _uiState = MutableStateFlow(SparkDetailUiState()) val uiState = _uiState.asStateFlow() init { viewModelScope.launch(bgDispatcher) { - sparkRepo.state.collect { state -> _uiState.update { it.copy(spark = state.toUi(lightningRepo)) } } + combine(sparkRepo.state, sparkExitRepo.state) { state, exit -> state to exit.showsResult } + .collect { (state, showsResult) -> + _uiState.update { it.copy(spark = state.toUi(lightningRepo, showsResult)) } + } } if (Env.network == Network.REGTEST) { viewModelScope.launch(bgDispatcher) { @@ -48,7 +54,8 @@ class SparkDetailViewModel @Inject constructor( viewModelScope.launch { _uiState.update { it.copy(isRefreshing = true) } sparkRepo.refreshState() - _uiState.update { it.copy(spark = sparkRepo.state.value.toUi(lightningRepo)) } + val showsResult = sparkExitRepo.state.value.showsResult + _uiState.update { it.copy(spark = sparkRepo.state.value.toUi(lightningRepo, showsResult)) } delay(500.milliseconds) _uiState.update { it.copy(isRefreshing = false) } } diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt new file mode 100644 index 0000000000..ef9d0932b2 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -0,0 +1,181 @@ +package to.bitkit.ui.settings.lightning + +import androidx.annotation.StringRes +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import breez_sdk_spark.RecoverFundsResponse +import to.bitkit.R +import to.bitkit.ext.setClipboardText +import to.bitkit.repositories.SparkExitMath +import to.bitkit.repositories.SparkExitPartialFunding +import to.bitkit.repositories.SparkExitQuote +import to.bitkit.repositories.SparkExitRecord +import to.bitkit.ui.components.BodyS +import to.bitkit.ui.components.CaptionB +import to.bitkit.ui.components.CaptionM +import to.bitkit.ui.components.MoneyCaptionB +import to.bitkit.ui.components.QrCodeImage +import to.bitkit.ui.components.rememberMoneyText +import to.bitkit.ui.shared.modifiers.clickableAlpha +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent +import to.bitkit.utils.BlockTimeHelpers + +/** An amount as plain text for copy that names it, in the user's primary unit. */ +@Composable +internal fun sparkExitAmountText(sats: ULong): String = + rememberMoneyText(sats.toLong(), showSymbol = true)?.replace(Regex(""), "") ?: sats.toString() + +@Composable +internal fun SparkExitQuoteRows(quote: SparkExitQuote) { + Column { + SparkExitAmountRow(stringResource(R.string.lightning__spark_exit__amount), quote.exitSats) + SparkExitAmountRow(stringResource(R.string.lightning__spark_exit__fees), quote.networkFeeSats) + SparkExitAmountRow(stringResource(R.string.lightning__spark_exit__receive), quote.receiveSats) + if (quote.fundingSats > 0uL) { + SparkExitAmountRow(stringResource(R.string.lightning__spark_exit__funding), quote.fundingSats) + } + if (quote.leftBehindSats > 0uL) { + SparkExitAmountRow(stringResource(R.string.lightning__spark_exit__left_behind), quote.leftBehindSats) + } + } +} + +@Composable +private fun SparkExitAmountRow(label: String, sats: ULong) { + SectionRow(name = label, valueContent = { MoneyCaptionB(sats = sats.toLong(), symbol = true) }) +} + +/** The funding address as QR and text, which copies it on tap, with what it must receive and what arrived so far. */ +@Composable +internal fun SparkExitFundingAddress( + address: String, + requiredSats: ULong, + seenSats: ULong, + modifier: Modifier = Modifier, + partial: SparkExitPartialFunding? = SparkExitMath.partialFunding(seenSats, requiredSats), +) { + val context = LocalContext.current + Column( + verticalArrangement = Arrangement.spacedBy(16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + modifier = modifier.fillMaxWidth() + ) { + QrCodeImage(content = address, size = 200.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__fund_external_text) + .replace("{amount}", sparkExitAmountText(requiredSats)), + color = Colors.White64, + modifier = Modifier.fillMaxWidth() + ) + CaptionB( + text = address, + maxLines = 2, + overflow = TextOverflow.MiddleEllipsis, + modifier = Modifier + .fillMaxWidth() + .clickableAlpha { context.setClipboardText(address) } + .testTag("SparkExitFundingAddress") + ) + partial?.let { + BodyS( + text = stringResource(R.string.lightning__spark_exit__fund_partial) + .replace("{received}", sparkExitAmountText(it.receivedSats)) + .replace("{required}", sparkExitAmountText(it.requiredSats)) + .replace("{missing}", sparkExitAmountText(it.missingSats)), + color = Colors.White64, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkExitFundingPartial") + ) + } + if (requiredSats > 0uL && seenSats >= requiredSats) { + CaptionM( + text = stringResource(R.string.lightning__spark_exit__fund_seen).withAccent(), + color = Colors.Green, + modifier = Modifier.fillMaxWidth() + ) + } + } +} + +/** A line of progress with the transaction it is about, whose id copies on tap. */ +@Composable +internal fun SparkExitTxNote(text: String, txid: String, @StringRes txidRes: Int, testTag: String) { + val context = LocalContext.current + Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { + BodyS(text = text, color = Colors.White64, modifier = Modifier.testTag(testTag)) + CaptionB( + text = stringResource(txidRes).replace("{txid}", txid), + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + modifier = Modifier + .fillMaxWidth() + .clickableAlpha { context.setClipboardText(txid) } + ) + } +} + +/** The exit's steps: funding, publishing, the timelock and the sweep. */ +@Composable +internal fun SparkExitSteps(record: SparkExitRecord, tipHeight: UInt?) { + val recovery: RecoverFundsResponse? = record.recovery + val transactions = recovery?.transactions.orEmpty() + val isFunded = record.phase !is SparkExitRecord.Phase.AwaitingFunding + val isDone = record.phase == SparkExitRecord.Phase.Done + val remaining = record.claimableAtHeight?.let { target -> + tipHeight?.let { BlockTimeHelpers.blocksRemaining(target, it) } + }?.takeIf { it > 0 }?.let(BlockTimeHelpers::getDurationForBlocks) + Column { + SparkExitStep(stringResource(R.string.lightning__spark_exit__step_funding), isDone = isFunded) + SparkExitStep( + title = stringResource(R.string.lightning__spark_exit__step_publish), + detail = recovery?.let { "${SparkExitMath.confirmedCount(it)}/${transactions.size}" }, + isDone = isDone, + ) + SparkExitStep( + title = stringResource(R.string.lightning__spark_exit__step_timelock), + detail = remaining?.let { + stringResource(R.string.lightning__spark_exit__ready_in).replace("{duration}", it) + }, + isDone = isDone || SparkExitMath.areTimelocksMatured(transactions), + ) + SparkExitStep(stringResource(R.string.lightning__spark_exit__step_sweep), isDone = isDone) + } +} + +@Composable +private fun SparkExitStep(title: String, isDone: Boolean, detail: String? = null) { + Row( + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .height(50.dp) + ) { + Icon( + painter = painterResource(if (isDone) R.drawable.ic_check else R.drawable.ic_hourglass_simple), + contentDescription = null, + tint = if (isDone) Colors.Green else Colors.White64, + modifier = Modifier.size(20.dp) + ) + CaptionB(text = title, modifier = Modifier.weight(1f)) + detail?.let { CaptionB(text = it, color = Colors.White64) } + } + HorizontalDivider() +} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt new file mode 100644 index 0000000000..e9f6c0bbf6 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt @@ -0,0 +1,100 @@ +package to.bitkit.ui.settings.lightning + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import to.bitkit.R +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.SwipeToConfirm +import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.ScreenColumn +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.rememberSubscriptionNotificationsRequest +import to.bitkit.ui.utils.withAccent +import to.bitkit.ui.utils.withAccentBoldBright + +/** The last look before the exit starts: what arrives and for how long the funds are out of reach. */ +@Composable +fun SparkExitConfirmScreen( + viewModel: SparkExitViewModel, + onBack: () -> Unit, + onStart: () -> Unit, +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + LaunchedEffect(Unit) { + viewModel.effects.collect { if (it == SparkExitEffect.Started) onStart() } + } + // Asked as the exit starts: the notifications are how a stalled background run reaches the user. + val requestNotifications = rememberSubscriptionNotificationsRequest() + Content( + uiState = uiState, + onBack = onBack, + onSwipe = { + requestNotifications() + viewModel.start() + }, + ) +} + +@Composable +private fun Content( + uiState: SparkExitUiState, + onBack: () -> Unit = {}, + onSwipe: () -> Unit = {}, +) { + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__spark_exit__nav_title), + onBackClick = onBack, + ) + Column( + modifier = Modifier + .weight(1f) + .padding(horizontal = 16.dp) + .verticalScroll(rememberScrollState()) + ) { + VerticalSpacer(32.dp) + Display(text = stringResource(R.string.lightning__spark_exit__confirm_title).withAccent()) + VerticalSpacer(8.dp) + BodyM( + text = stringResource(R.string.lightning__spark_exit__confirm_text).withAccentBoldBright(), + color = Colors.White64, + ) + VerticalSpacer(32.dp) + uiState.quote?.let { SparkExitQuoteRows(it) } + VerticalSpacer(32.dp) + } + Column(modifier = Modifier.padding(horizontal = 16.dp)) { + SwipeToConfirm( + text = stringResource(R.string.lightning__spark_exit__swipe), + color = Colors.Brand, + loading = uiState.isStarting, + enabled = uiState.quote != null && !uiState.isStarting, + onConfirm = onSwipe, + modifier = Modifier.testTag("SparkExitSwipe") + ) + VerticalSpacer(16.dp) + } + } +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + Content(uiState = SparkExitUiState()) + } +} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt new file mode 100644 index 0000000000..941a988aab --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt @@ -0,0 +1,143 @@ +package to.bitkit.ui.settings.lightning + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import to.bitkit.R +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.CaptionM +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.SecondaryButton +import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.ScreenColumn +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent +import to.bitkit.ui.utils.withAccentBoldBright + +/** Pays the CPFP fee funding from savings, or shows the funding address to pay from another wallet. */ +@Composable +fun SparkExitFundingScreen( + viewModel: SparkExitViewModel, + onBack: () -> Unit, + onContinue: () -> Unit, +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + LaunchedEffect(Unit) { + viewModel.onFundingShown() + viewModel.loadSavingsFunding() + } + DisposableEffect(Unit) { onDispose { viewModel.stopWatchingFundingAddress() } } + Content( + uiState = uiState, + onBack = onBack, + onFundFromSavings = { + viewModel.onFundFromSavings() + onContinue() + }, + onFundExternally = viewModel::onFundExternally, + onContinue = onContinue, + ) +} + +@Composable +private fun Content( + uiState: SparkExitUiState, + onBack: () -> Unit = {}, + onFundFromSavings: () -> Unit = {}, + onFundExternally: () -> Unit = {}, + onContinue: () -> Unit = {}, +) { + val fundingSats = uiState.fundingSats + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__spark_exit__nav_title), + onBackClick = onBack, + ) + Column( + modifier = Modifier + .weight(1f) + .padding(horizontal = 16.dp) + .verticalScroll(rememberScrollState()) + ) { + VerticalSpacer(32.dp) + Display(text = stringResource(R.string.lightning__spark_exit__funding_title).withAccent()) + VerticalSpacer(8.dp) + BodyM( + text = stringResource(R.string.lightning__spark_exit__funding_text) + .replace("{amount}", sparkExitAmountText(fundingSats)) + .withAccentBoldBright(), + color = Colors.White64, + ) + val address = uiState.fundingAddress + if (uiState.showsFundingAddress && address != null) { + VerticalSpacer(24.dp) + SparkExitFundingAddress( + address = address, + requiredSats = fundingSats, + seenSats = uiState.fundingSeenSats + ) + } + VerticalSpacer(32.dp) + } + Column(modifier = Modifier.padding(horizontal = 16.dp)) { + if (uiState.showsFundingAddress) { + PrimaryButton( + text = stringResource(R.string.common__continue), + onClick = onContinue, + enabled = uiState.canContinueFunding, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkExitFundingContinue") + ) + } else { + val isPricing = uiState.savingsFeeSats == null && !uiState.hasSavingsFeeFailed + if (!isPricing && !uiState.canFundFromSavings) { + CaptionM( + text = stringResource(R.string.lightning__spark_exit__fund_insufficient).withAccent(), + color = Colors.White64, + ) + VerticalSpacer(16.dp) + } + PrimaryButton( + text = stringResource(R.string.lightning__spark_exit__fund_savings), + onClick = onFundFromSavings, + isLoading = isPricing, + enabled = uiState.canFundFromSavings, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkExitFundSavings") + ) + VerticalSpacer(16.dp) + SecondaryButton( + text = stringResource(R.string.lightning__spark_exit__fund_external), + onClick = onFundExternally, + testTag = "SparkExitFundExternal", + ) + } + VerticalSpacer(16.dp) + } + } +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + Content(uiState = SparkExitUiState(hasSavingsFeeFailed = true)) + } +} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt new file mode 100644 index 0000000000..11078db7f2 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt @@ -0,0 +1,111 @@ +package to.bitkit.ui.settings.lightning + +import androidx.compose.foundation.Image +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import to.bitkit.R +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.FillHeight +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.SecondaryButton +import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.ScreenColumn +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent +import to.bitkit.ui.utils.withAccentBoldBright + +/** When to use an emergency exit, what it costs and how long it takes. */ +@Composable +fun SparkExitIntroScreen( + onBack: () -> Unit, + onContinue: () -> Unit, +) { + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__spark_exit__nav_title), + onBackClick = onBack, + ) + BoxWithConstraints( + modifier = Modifier + .weight(1f) + .fillMaxWidth() + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .heightIn(min = maxHeight) + .padding(horizontal = 16.dp) + ) { + VerticalSpacer(32.dp) + Display( + text = stringResource(R.string.lightning__spark_exit__intro_title).withAccent(), + modifier = Modifier.fillMaxWidth() + ) + VerticalSpacer(8.dp) + BodyM( + text = stringResource(R.string.lightning__spark_exit__intro_text).withAccentBoldBright(), + color = Colors.White64, + modifier = Modifier.fillMaxWidth() + ) + FillHeight() + Image( + painter = painterResource(R.drawable.exclamation_mark), + contentDescription = null, + contentScale = ContentScale.Fit, + modifier = Modifier.size(256.dp) + ) + FillHeight() + } + } + Column(modifier = Modifier.padding(horizontal = 16.dp)) { + Row( + horizontalArrangement = Arrangement.spacedBy(16.dp), + modifier = Modifier.fillMaxWidth(), + ) { + SecondaryButton( + text = stringResource(R.string.common__cancel), + onClick = onBack, + modifier = Modifier.weight(1f) + ) + PrimaryButton( + text = stringResource(R.string.common__continue), + onClick = onContinue, + modifier = Modifier + .weight(1f) + .testTag("SparkExitIntroContinue") + ) + } + VerticalSpacer(16.dp) + } + } +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + SparkExitIntroScreen(onBack = {}, onContinue = {}) + } +} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt new file mode 100644 index 0000000000..61c091e11a --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -0,0 +1,331 @@ +package to.bitkit.ui.settings.lightning + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.pulltorefresh.PullToRefreshBox +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import to.bitkit.R +import to.bitkit.repositories.SparkExitBackgroundLimits +import to.bitkit.repositories.SparkExitFundingState +import to.bitkit.repositories.SparkExitRecord +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.BodyS +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.SecondaryButton +import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.openNotificationSettings +import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.ScreenColumn +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent +import to.bitkit.ui.utils.withAccentBoldBright + +/** The running exit's steps and countdown, and its result once it ends. */ +@Composable +fun SparkExitProgressScreen( + viewModel: SparkExitViewModel, + onBack: () -> Unit, + onDone: () -> Unit, +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val context = LocalContext.current + LaunchedEffect(Unit) { + viewModel.refresh() + viewModel.effects.collect { if (it == SparkExitEffect.Cancelled) onDone() } + } + val isEnded = uiState.record?.isActive == false + LaunchedEffect(isEnded) { if (isEnded) viewModel.onResultShown() } + LifecycleResumeEffect(Unit) { + viewModel.refreshBackgroundLimits() + onPauseOrDispose {} + } + Content( + uiState = uiState, + onBack = onBack, + onRefresh = viewModel::refresh, + onCancel = viewModel::cancel, + onDone = onDone, + onNotificationSettings = context::openNotificationSettings, + ) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun Content( + uiState: SparkExitUiState, + onBack: () -> Unit = {}, + onRefresh: () -> Unit = {}, + onCancel: () -> Unit = {}, + onDone: () -> Unit = {}, + onNotificationSettings: () -> Unit = {}, +) { + val record = uiState.record + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__spark_exit__nav_title), + onBackClick = onBack, + ) + PullToRefreshBox( + isRefreshing = uiState.isRefreshing, + onRefresh = onRefresh, + modifier = Modifier.weight(1f) + ) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(horizontal = 16.dp) + .verticalScroll(rememberScrollState()) + .testTag("SparkExitProgress") + ) { + VerticalSpacer(32.dp) + Display(text = progressTitle(record?.phase).withAccent()) + VerticalSpacer(8.dp) + BodyM( + text = progressText( + record = record, + progressFunding = uiState.progressFunding, + outsideExitSats = uiState.outsideExitSats, + ).withAccentBoldBright(), + color = Colors.White64, + ) + VerticalSpacer(24.dp) + record?.let { ProgressDetails(it, uiState) } + if (record?.isActive == true) { + BackgroundNotes( + limits = uiState.backgroundLimits, + onNotificationSettings = onNotificationSettings, + ) + } + VerticalSpacer(32.dp) + } + } + Column(modifier = Modifier.padding(horizontal = 16.dp)) { + if (uiState.canCancel) { + SecondaryButton( + text = stringResource(R.string.lightning__spark_exit__cancel), + onClick = onCancel, + testTag = "SparkExitCancel", + ) + VerticalSpacer(16.dp) + } + PrimaryButton( + text = stringResource(R.string.common__ok), + onClick = onDone, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkExitProgressOk") + ) + VerticalSpacer(16.dp) + } + } +} + +@Composable +private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState) { + SparkExitSteps(record = record, tipHeight = uiState.tipHeight) + val address = record.funding.firstOrNull()?.address + val funding = uiState.progressFunding + if (funding != null && address != null) { + VerticalSpacer(24.dp) + when (funding) { + is SparkExitFundingState.Ask -> SparkExitFundingAddress( + address = address, + requiredSats = funding.sats, + seenSats = 0uL, + partial = funding.partial, + ) + is SparkExitFundingState.Paid -> SparkExitTxNote( + text = stringResource(R.string.lightning__spark_exit__fund_paid), + txid = funding.txid, + txidRes = R.string.lightning__spark_exit__funding_txid, + testTag = "SparkExitFundingPaid", + ) + is SparkExitFundingState.Seen -> SparkExitTxNote( + text = stringResource(R.string.lightning__spark_exit__fund_pending), + txid = funding.txid, + txidRes = R.string.lightning__spark_exit__funding_txid, + testTag = "SparkExitFundingSeen", + ) + } + } + uiState.rejection?.let { + VerticalSpacer(16.dp) + BodyS(text = stringResource(R.string.lightning__spark_exit__errors).replace("{error}", it), color = Colors.Red) + } + uiState.outsideExitSats?.let { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__outside_exit) + .replace("{amount}", sparkExitAmountText(it)), + color = Colors.White64, + ) + } + if (record.lostSats > 0uL) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__lost_leaves) + .replace("{amount}", sparkExitAmountText(record.lostSats)), + color = Colors.Red, + modifier = Modifier.testTag("SparkExitLostLeaves") + ) + } + if (record.leftBehindLeafSats > 0uL) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__left_behind_leaves) + .replace("{amount}", sparkExitAmountText(record.leftBehindLeafSats)), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitLeftBehindLeaves") + ) + } + if (!record.isActive && address != null) LeftoverNote(record, address) +} + +/** Where the leftover fee funding of an ended exit is: being sent, sent, kept as dust, or still at its address. */ +@Composable +private fun LeftoverNote(record: SparkExitRecord, address: String) { + if (record.leftover.isEmpty()) return + val total = record.leftover.fold(0uL) { sum, leftover -> sum + leftover.valueSats } + val sweep = record.leftoverSweep + VerticalSpacer(16.dp) + when { + sweep != null && sweep.txid == null -> BodyS( + text = stringResource(R.string.lightning__spark_exit__leftover_dust) + .replace("{amount}", sparkExitAmountText(total)) + .replace("{address}", address), + color = Colors.White64, + ) + sweep?.txid != null && sweep.isAccepted -> SparkExitTxNote( + text = stringResource(R.string.lightning__spark_exit__leftover_swept) + .replace("{amount}", sparkExitAmountText(sweep.valueSats)), + txid = sweep.txid, + txidRes = R.string.lightning__spark_exit__leftover_txid, + testTag = "SparkExitLeftoverSwept", + ) + sweep?.txid != null && sweep.rejection == null -> BodyS( + text = stringResource(R.string.lightning__spark_exit__leftover_sending) + .replace("{amount}", sparkExitAmountText(sweep.valueSats)), + color = Colors.White64, + ) + else -> BodyS( + text = stringResource(R.string.lightning__spark_exit__leftover) + .replace("{amount}", sparkExitAmountText(total)) + .replace("{address}", address), + color = Colors.White64, + ) + } +} + +@Composable +private fun BackgroundNotes( + limits: SparkExitBackgroundLimits, + onNotificationSettings: () -> Unit, +) { + val notes = listOfNotNull( + R.string.lightning__spark_exit__note_restricted.takeIf { limits.isRestricted }, + R.string.lightning__spark_exit__note_battery_saver.takeIf { limits.isPowerSaveMode }, + R.string.lightning__spark_exit__note_battery_optimized.takeIf { + limits.isOptimized && !limits.isRestricted && !limits.isPowerSaveMode + }, + R.string.lightning__spark_exit__note_notifications.takeIf { !limits.areNotificationsEnabled }, + ) + notes.forEach { + VerticalSpacer(16.dp) + BodyS(text = stringResource(it), color = Colors.White64) + } + if (!limits.areNotificationsEnabled) { + VerticalSpacer(16.dp) + SecondaryButton( + text = stringResource(R.string.lightning__spark_exit__note_notifications_button), + onClick = onNotificationSettings, + testTag = "SparkExitNotificationSettings", + ) + } +} + +@Composable +private fun progressTitle(phase: SparkExitRecord.Phase?): String = stringResource( + when (phase) { + SparkExitRecord.Phase.Done -> R.string.lightning__spark_exit__done_title + is SparkExitRecord.Phase.Failed -> R.string.lightning__spark_exit__failed_title + is SparkExitRecord.Phase.NeedsFunding -> R.string.lightning__spark_exit__needs_funding_title + else -> R.string.lightning__spark_exit__progress_title + }, +) + +@Composable +private fun progressText( + record: SparkExitRecord?, + progressFunding: SparkExitFundingState?, + outsideExitSats: ULong?, +): String = when (record?.phase) { + SparkExitRecord.Phase.Done -> listOfNotNull( + stringResource(R.string.lightning__spark_exit__done_text), + record.skippedLeafCount.takeIf { it > 0 }?.let { + stringResource(R.string.lightning__spark_exit__partial_text).replace("{count}", "$it") + }, + record.failedLeafCount.takeIf { it > 0 }?.let { + stringResource(R.string.lightning__spark_exit__failed_leaves).replace("{count}", "$it") + }, + ).joinToString(" ") + is SparkExitRecord.Phase.Failed -> sparkExitFailedText( + nothingText = stringResource(R.string.lightning__spark_exit__failed_text), + staysText = stringResource(R.string.lightning__spark_exit__failed_stays), + outsideAmount = outsideExitSats?.let { sparkExitAmountText(it) }, + ) + is SparkExitRecord.Phase.NeedsFunding -> when (val funding = progressFunding) { + // A payment that covers it waits to confirm: nothing to ask for. + is SparkExitFundingState.Ask -> stringResource(R.string.lightning__spark_exit__needs_funding_text) + .replace("{amount}", sparkExitAmountText(funding.sats)) + else -> stringResource(R.string.lightning__spark_exit__progress_text) + } + else -> stringResource(R.string.lightning__spark_exit__progress_text) +} + +/** + * The stopped exit's text: nothing was recovered, and what Spark still holds beyond the exit when it holds any. Lost + * leaves are gone, so they are not said to stay on Spark. + */ +internal fun sparkExitFailedText(nothingText: String, staysText: String, outsideAmount: String?): String = + listOfNotNull(nothingText, outsideAmount?.let { staysText.replace("{amount}", it) }).joinToString(" ") + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + Content( + uiState = SparkExitUiState( + record = SparkExitRecord( + network = "regtest", + createdAt = 0L, + phase = SparkExitRecord.Phase.Running, + feeRateSatPerVbyte = 2uL, + destination = "bcrt1q", + leafIds = listOf("leaf"), + funding = listOf(SparkExitRecord.Funding(0u, "bcrt1qfunding", "02ab")), + expectedSats = 91_000uL, + claimableAtHeight = 2_100u, + ), + tipHeight = 1_900u, + backgroundLimits = SparkExitBackgroundLimits(isOptimized = true, areNotificationsEnabled = false), + ), + ) + } +} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt new file mode 100644 index 0000000000..ccf7e7f921 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt @@ -0,0 +1,121 @@ +package to.bitkit.ui.settings.lightning + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import to.bitkit.R +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.BodyS +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.ScreenColumn +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent + +/** What the exit takes on-chain, what it costs, and what stays behind. */ +@Composable +fun SparkExitQuoteScreen( + viewModel: SparkExitViewModel, + onBack: () -> Unit, + onContinue: (needsFunding: Boolean) -> Unit, +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + LaunchedEffect(Unit) { viewModel.loadQuote() } + Content(uiState = uiState, onBack = onBack, onContinue = { onContinue(uiState.fundingSats > 0uL) }) +} + +@Composable +private fun Content( + uiState: SparkExitUiState, + onBack: () -> Unit = {}, + onContinue: () -> Unit = {}, +) { + val block = uiState.quoteBlock + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__spark_exit__nav_title), + onBackClick = onBack, + ) + Column( + modifier = Modifier + .weight(1f) + .padding(horizontal = 16.dp) + .verticalScroll(rememberScrollState()) + ) { + VerticalSpacer(32.dp) + Display(text = stringResource(R.string.lightning__spark_exit__quote_title).withAccent()) + VerticalSpacer(32.dp) + when { + uiState.quote != null -> { + SparkExitQuoteRows(uiState.quote) + uiState.quote.unexitableSats?.let { UnexitableNote(it) } + } + uiState.isQuoting && uiState.isSettling -> BodyM( + text = stringResource(R.string.lightning__spark_exit__quote_settling), + ) + uiState.isQuoting -> BodyM(text = stringResource(R.string.lightning__spark_exit__quote_loading)) + } + block?.let { + VerticalSpacer(16.dp) + BodyM( + text = stringResource( + when (it) { + SparkExitQuoteBlock.Error -> R.string.lightning__spark_exit__quote_error + SparkExitQuoteBlock.Nothing -> R.string.lightning__spark_exit__nothing + SparkExitQuoteBlock.Uneconomic -> R.string.lightning__spark_exit__uneconomic + }, + ), + color = Colors.Red, + modifier = Modifier.testTag("SparkExitQuoteBlocked") + ) + } + VerticalSpacer(32.dp) + } + Column(modifier = Modifier.padding(horizontal = 16.dp)) { + PrimaryButton( + text = stringResource(R.string.common__continue), + onClick = onContinue, + isLoading = uiState.isQuoting, + enabled = uiState.quote != null && block == null, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkExitQuoteContinue") + ) + VerticalSpacer(16.dp) + } + } +} + +/** What the quote cannot exit: skipped leaves, and value still moving inside Spark. */ +@Composable +private fun UnexitableNote(sats: ULong) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__quote_outside) + .replace("{amount}", sparkExitAmountText(sats)), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitQuoteOutside") + ) +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + Content(uiState = SparkExitUiState(isQuoting = true)) + } +} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt new file mode 100644 index 0000000000..02c8cf870a --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -0,0 +1,219 @@ +package to.bitkit.ui.settings.lightning + +import androidx.compose.runtime.Stable +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.isActive +import kotlinx.coroutines.launch +import to.bitkit.repositories.SparkExitBackgroundLimits +import to.bitkit.repositories.SparkExitFundingState +import to.bitkit.repositories.SparkExitQuote +import to.bitkit.repositories.SparkExitRecord +import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.surfacedRejection +import to.bitkit.ui.shared.toast.ToastEventBus +import javax.inject.Inject +import kotlin.time.Duration.Companion.seconds + +/** Drives the emergency exit screens, from the quote to the progress of a running exit. */ +@HiltViewModel +class SparkExitViewModel @Inject constructor( + private val sparkExitRepo: SparkExitRepo, +) : ViewModel() { + companion object { + /** How often the funding screen looks at the funding address while the user pays from another wallet. */ + private val FUNDING_POLL_INTERVAL = 15.seconds + } + + private val _uiState = MutableStateFlow(SparkExitUiState()) + val uiState = _uiState.asStateFlow() + + private val _effects = MutableSharedFlow(extraBufferCapacity = 1) + val effects = _effects.asSharedFlow() + + private var fundingWatch: Job? = null + + init { + viewModelScope.launch { + sparkExitRepo.state.collect { exit -> + _uiState.update { + it.copy( + record = exit.record, + tipHeight = exit.tipHeight, + fundingSeenSats = exit.fundingSeenSats, + fundingState = exit.fundingState, + fundingAddress = exit.fundingAddress, + canCancel = sparkExitRepo.canCancel, + outsideExitSats = exit.outsideExitSats, + isSettling = exit.isSettling, + ) + } + } + } + } + + fun loadQuote() { + viewModelScope.launch { + // A new quote starts the funding choice over. + stopWatchingFundingAddress() + _uiState.update { + it.copy(isQuoting = true, hasQuoteError = false, fundFromSavings = false, showsFundingAddress = false) + } + sparkExitRepo.loadQuote() + .onSuccess { quote -> _uiState.update { it.copy(quote = quote, isQuoting = false) } } + .onFailure { _uiState.update { it.copy(quote = null, isQuoting = false, hasQuoteError = true) } } + } + } + + fun loadSavingsFunding() { + viewModelScope.launch { + _uiState.update { it.copy(savingsFeeSats = null, hasSavingsFeeFailed = false) } + sparkExitRepo.savingsFundingFee() + .onSuccess { funding -> + _uiState.update { it.copy(savingsFeeSats = funding.feeSats, canFundFromSavings = funding.canPay) } + } + .onFailure { _uiState.update { it.copy(hasSavingsFeeFailed = true, canFundFromSavings = false) } } + } + } + + /** + * Entering the funding step offers both choices again, unless the funding address already received a payment: + * then it keeps showing the address and what reached it. + */ + fun onFundingShown() { + stopWatchingFundingAddress() + _uiState.update { it.copy(fundFromSavings = false, showsFundingAddress = false) } + viewModelScope.launch { + val seen = sparkExitRepo.refreshFundingAddress().getOrNull() ?: return@launch + if (seen > 0uL) onFundExternally() + } + } + + fun onFundFromSavings() { + _uiState.update { it.copy(fundFromSavings = true) } + } + + fun onFundExternally() { + _uiState.update { it.copy(fundFromSavings = false, showsFundingAddress = true) } + watchFundingAddress() + } + + fun watchFundingAddress() { + if (fundingWatch?.isActive == true) return + fundingWatch = viewModelScope.launch { + while (isActive) { + sparkExitRepo.refreshFundingAddress() + delay(FUNDING_POLL_INTERVAL) + } + } + } + + fun stopWatchingFundingAddress() { + fundingWatch?.cancel() + fundingWatch = null + } + + fun start() { + viewModelScope.launch { + _uiState.update { it.copy(isStarting = true) } + sparkExitRepo.start(_uiState.value.fundFromSavings) + .onSuccess { _effects.emit(SparkExitEffect.Started) } + .onFailure { + ToastEventBus.send(it) + // The exit started but paying its fee funding failed: progress shows where to fund it. + if (sparkExitRepo.state.value.isExiting) _effects.emit(SparkExitEffect.Started) + } + _uiState.update { it.copy(isStarting = false) } + } + } + + /** Progress showed the result of an ended exit, so a later Emergency exit can start a new one. */ + fun onResultShown() { + viewModelScope.launch { sparkExitRepo.markResultSeen() } + } + + fun refresh() { + viewModelScope.launch { + _uiState.update { it.copy(isRefreshing = true) } + sparkExitRepo.load() + sparkExitRepo.tick() + _uiState.update { it.copy(isRefreshing = false, canCancel = sparkExitRepo.canCancel) } + } + } + + fun refreshBackgroundLimits() { + _uiState.update { it.copy(backgroundLimits = sparkExitRepo.backgroundLimits()) } + } + + fun cancel() { + viewModelScope.launch { + sparkExitRepo.cancel() + .onSuccess { _effects.emit(SparkExitEffect.Cancelled) } + .onFailure { ToastEventBus.send(it) } + } + } +} + +sealed interface SparkExitEffect { + data object Started : SparkExitEffect + data object Cancelled : SparkExitEffect +} + +@Stable +data class SparkExitUiState( + val quote: SparkExitQuote? = null, + val isQuoting: Boolean = false, + val hasQuoteError: Boolean = false, + val savingsFeeSats: ULong? = null, + val hasSavingsFeeFailed: Boolean = false, + val canFundFromSavings: Boolean = false, + val fundFromSavings: Boolean = false, + val showsFundingAddress: Boolean = false, + val isStarting: Boolean = false, + val isRefreshing: Boolean = false, + val record: SparkExitRecord? = null, + val tipHeight: UInt? = null, + val fundingSeenSats: ULong = 0uL, + /** What progress shows while the exit needs fee funding. */ + val fundingState: SparkExitFundingState? = null, + val fundingAddress: String? = null, + val canCancel: Boolean = false, + val backgroundLimits: SparkExitBackgroundLimits = SparkExitBackgroundLimits(), + val outsideExitSats: ULong? = null, + /** The quote waits for Spark to finish moving leaves first. */ + val isSettling: Boolean = false, +) { + val fundingSats: ULong get() = quote?.fundingSats ?: 0uL + + /** Continue after funding from another wallet: once the funding address holds what the quote asks for. */ + val canContinueFunding: Boolean get() = fundingSats > 0uL && fundingSeenSats >= fundingSats + + /** Why the quote cannot continue, or null when it can. */ + val quoteBlock: SparkExitQuoteBlock? + get() { + if (hasQuoteError) return SparkExitQuoteBlock.Error + val quote = quote ?: return null + if (quote.prepared.leaves.isEmpty()) return SparkExitQuoteBlock.Nothing + if (!quote.isWorthExiting) return SparkExitQuoteBlock.Uneconomic + return null + } + + val rejection: String? get() = record?.surfacedRejection + + /** The fee funding progress shows, asking for the whole shortfall until the funding address was read. */ + val progressFunding: SparkExitFundingState? + get() { + val shortfall = record?.fundingShortfallSats ?: return null + return fundingState ?: SparkExitFundingState.Ask(shortfall) + } +} + +enum class SparkExitQuoteBlock { Error, Nothing, Uneconomic } diff --git a/app/src/main/java/to/bitkit/ui/utils/RequestNotificationPermissions.kt b/app/src/main/java/to/bitkit/ui/utils/RequestNotificationPermissions.kt index 53080db8ac..15a8445721 100644 --- a/app/src/main/java/to/bitkit/ui/utils/RequestNotificationPermissions.kt +++ b/app/src/main/java/to/bitkit/ui/utils/RequestNotificationPermissions.kt @@ -124,7 +124,7 @@ fun rememberNotificationToggleClick( } } -/** Asks for notification permission when a Paykit subscription starts, unless it is already granted. */ +/** Asks for notification permission when a Paykit subscription or a Spark emergency exit starts, unless granted. */ @Composable fun rememberSubscriptionNotificationsRequest( settingsViewModel: SettingsViewModel = hiltViewModel(), diff --git a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt index 56c740e63f..831c8d8d8c 100644 --- a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt @@ -52,7 +52,8 @@ class DeriveBalanceStateUseCase @Inject constructor( val channelFundableBalance = getMaxChannelFundableAmount(lightningRepo.getChannelFundableBalance()) val afterPendingChannels = balanceDetails.totalLightningBalanceSats.safe() - pendingChannelsSats.safe() val afterClosingChannels = afterPendingChannels.safe() - toSavingsAmount.safe() - val sparkSats = sparkRepo.state.value.balanceSats + val sparkSats = sparkRepo.state.value.spendingSats + val sparkExitSats = getSparkExitSats(activeTransfers) val afterLingeringCoopClose = afterClosingChannels.safe() - lingeringCoopCloseSats.safe() val totalLightningSats = afterLingeringCoopClose.safe() + sparkSats.safe() @@ -66,7 +67,8 @@ class DeriveBalanceStateUseCase @Inject constructor( sparkRepo.state.value.sendableSats, ), maxSendOnchainSats = getMaxSendAmount(balanceDetails), - balanceInTransferToSavings = toSavingsAmount.safe() - coopCloseSavingsSats.safe(), + balanceInTransferToSavings = (toSavingsAmount.safe() - coopCloseSavingsSats.safe()).safe() + + sparkExitSats.safe(), balanceInTransferToSpending = pendingChannelsSats.safe() + sparkRepo.state.value.pendingDepositSats.safe(), hardwareWallets = hwWalletRepo.wallets.value.map { it.toBalance() }, @@ -107,7 +109,7 @@ class DeriveBalanceStateUseCase @Inject constructor( balanceDetails: BalanceDetails, ): ULong { var toSavingsAmount = 0uL - val toSavings = transfers.filter { it.type.isToSavings() } + val toSavings = transfers.filter { it.type.isToSavings() && it.type != TransferType.SPARK_EXIT } for (transfer in toSavings) { val channelId = transferRepo.resolveChannelIdForTransfer(transfer, channels) @@ -118,6 +120,11 @@ class DeriveBalanceStateUseCase @Inject constructor( return toSavingsAmount } + /** A Spark emergency exit has no channel: its amount is in transfer until the exit settles it. */ + private fun getSparkExitSats(transfers: List): ULong = transfers + .filter { it.type == TransferType.SPARK_EXIT } + .fold(0uL) { sum, transfer -> sum.safe() + transfer.amountSats.toULong().safe() } + private suspend fun getMaxChannelFundableAmount(fundableBalance: ULong): ULong { if (fundableBalance == 0uL) return 0u diff --git a/app/src/main/java/to/bitkit/utils/BatterySettingsSnapshot.kt b/app/src/main/java/to/bitkit/utils/BatterySettingsSnapshot.kt index 8ab222a8dd..aa9bc50d1c 100644 --- a/app/src/main/java/to/bitkit/utils/BatterySettingsSnapshot.kt +++ b/app/src/main/java/to/bitkit/utils/BatterySettingsSnapshot.kt @@ -5,6 +5,7 @@ import android.content.Context import android.os.Build.VERSION import android.os.Build.VERSION_CODES import kotlinx.serialization.Serializable +import to.bitkit.ext.activityManager import to.bitkit.ext.powerManager import to.bitkit.ext.usageStatsManager @@ -17,6 +18,7 @@ data class BatterySettingsSnapshot( val isLowPowerStandbyEnabled: Boolean?, val isExemptFromLowPowerStandby: Boolean?, val appStandbyBucket: String?, + val isBackgroundRestricted: Boolean? = null, ) { val logSummary: String get() = listOf( @@ -27,6 +29,7 @@ data class BatterySettingsSnapshot( "lowPowerStandbyEnabled='${isLowPowerStandbyEnabled.logValue()}'", "exemptFromLowPowerStandby='${isExemptFromLowPowerStandby.logValue()}'", "appStandbyBucket='${appStandbyBucket.logValue()}'", + "backgroundRestricted='${isBackgroundRestricted.logValue()}'", ).joinToString() } @@ -54,6 +57,7 @@ fun Context.batterySettingsSnapshot(): BatterySettingsSnapshot { null }, appStandbyBucket = runCatching { usageStatsManager.appStandbyBucket.toAppStandbyBucketName() }.getOrNull(), + isBackgroundRestricted = runCatching { activityManager.isBackgroundRestricted }.getOrNull(), ) } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 6fabcf9943..0006a43f36 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -220,6 +220,7 @@ import to.bitkit.repositories.PublicPaykitRepo import to.bitkit.repositories.QuickPayPaymentFailedError import to.bitkit.repositories.QuickPayRepo import to.bitkit.repositories.SamRockRepo +import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.TransferRepo import to.bitkit.repositories.UsdtPreferencesRepo import to.bitkit.repositories.UsdtRepo @@ -331,6 +332,7 @@ class AppViewModel @Inject constructor( private val formatMoneyValue: FormatMoneyValue, private val widgetsRepo: WidgetsRepo, private val timeSource: TimeSource, + private val sparkExitRepo: SparkExitRepo, ) : ViewModel() { val healthState = healthRepo.healthState @@ -1409,6 +1411,11 @@ class AppViewModel @Inject constructor( private fun isAutomaticPaykitWorkPaused(): Boolean = isPaymentRequestPollingStopped.value || privatePaykitRepo.isProfileDeletionInProgress.value + /** Drives a Spark emergency exit every minute while Bitkit is in the foreground. */ + fun startSparkExitDriving() = sparkExitRepo.onAppForegrounded() + + fun stopSparkExitDriving() = sparkExitRepo.onAppBackgrounded() + fun startPaykitPaymentRequestPolling() { privatePaykitRepo.setContactPreparationActive(true) isPaymentRequestPollingStopped.update { false } diff --git a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt index b11f8cc82c..4b44013d1b 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -367,7 +367,7 @@ class TransferViewModel @Inject constructor( private suspend fun withdrawSparkToSavings() { sparkFeeJob?.join() - val balance = sparkRepo.state.value.balanceSats + val balance = sparkRepo.state.value.spendingSats if (balance == 0uL) return val address = sparkWithdrawAddress() if (address == null) { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 39227d7601..8c0f093dba 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -228,6 +228,77 @@ انتظر إيداعات تمت المطالبة بها إيداعات قيد التنفيذ + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. المزوّد Spark عبر Breez بلا حد diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index dac1da7456..9f7ac30481 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -235,6 +235,77 @@ Esperar Depósitos reclamados Depósitos en curso + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 334505505c..9fd7a3a182 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -232,6 +232,77 @@ Espera Dipòsits reclamats Dipòsits en curs + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Proveïdor Spark mitjançant Breez Sense límit diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 91f4805c90..aa0d4a6999 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -235,6 +235,77 @@ Počkat Připsané vklady Probíhající vklady + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Poskytovatel Spark přes Breez Bez limitu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 5cea87a889..cc1c538648 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -112,6 +112,77 @@ Warten Eingelöste Einzahlungen Laufende Einzahlungen + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Anbieter Spark über Breez Kein Limit diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 13bc6c27e3..8ba813824e 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -228,6 +228,77 @@ Αναμονή Εξαργυρωμένες καταθέσεις Καταθέσεις σε εξέλιξη + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Πάροχος Spark μέσω Breez Χωρίς όριο diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index e50e8de4c2..c657437678 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -234,6 +234,77 @@ Esperar Depósitos reclamados Depósitos en curso + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index fa41c6b382..5711a16930 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -176,6 +176,77 @@ Esperar Depósitos reclamados Depósitos en curso + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 205a538624..098cc2782d 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -111,6 +111,77 @@ Attendre Dépôts réclamés Dépôts en cours + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Fournisseur Spark via Breez Sans limite diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index f46eaf89c8..968c37e4be 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -233,6 +233,77 @@ Attendi Depositi riscattati Depositi in corso + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Fornitore Spark tramite Breez Nessun limite diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index fc7c27129e..41f2ed287b 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -232,6 +232,77 @@ Wachten Geclaimde stortingen Lopende stortingen + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Aanbieder Spark via Breez Geen limiet diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 61316f843c..0be5b1583f 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -113,6 +113,77 @@ Czekaj Odebrane wpłaty Wpłaty w toku + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Dostawca Spark przez Breez Bez limitu diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 3e7b7deb6b..ca5d45a471 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -236,6 +236,77 @@ Esperar Depósitos resgatados Depósitos em andamento + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Provedor Spark via Breez Sem limite diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 81321c2947..ff5a3de4c9 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -108,6 +108,77 @@ Esperar Depósitos resgatados Depósitos em curso + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Fornecedor Spark via Breez Sem limite diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 3f8d38a426..e0ad2ee1eb 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -244,6 +244,77 @@ Ждать Зачисленные депозиты Депозиты в обработке + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Провайдер Spark через Breez Без ограничений diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2fb23120cf..2b35ac1cd3 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -392,6 +392,77 @@ Wait Claimed deposits Deposits in progress + Amount to exit + Emergency exit + Cancel exit + You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. + Start\n<accent>exit?</accent> + Your funds are in savings. + Exit\n<accent>complete</accent> + Some transactions were rejected: {error} + {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} stays on Spark. + Nothing could be recovered. + Exit\n<accent>stopped</accent> + Network fees + Fund from another wallet + Send at least {amount} to this address. The exit starts once it confirms. + Your savings can\'t cover the fee funding. + Paid from savings, waiting for confirmation. + {received} of {required} received, send {missing} more. + Payment seen, waiting for confirmation. + Pay from savings + Payment seen. + Fee funding needed + The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. + Fund the\n<accent>fees</accent> + Transaction ID: {txid} + Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. + Leave Spark\n<accent>on-chain</accent> + Stays on Spark + {amount} can\'t be exited at this fee rate and stays on Spark. + {amount} of fee funding is still at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}. + Sending {amount} of leftover fee funding to savings. + {amount} of leftover fee funding was sent to savings. + Transaction ID: {txid} + {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. + Emergency Exit + The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. + More fees\n<accent>needed</accent> + Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. + Battery saver is on, so Android may hold back the exit while Bitkit is closed. + Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. + Turn on notifications + Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. + Nothing can be exited right now. + Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. + Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. + Your emergency exit stopped. Open Bitkit to see why. + Your emergency exit needs more fee funding. Open Bitkit to fund it. + Your emergency exit fell behind in the background. Open Bitkit to continue it. + {amount} of your exit can\'t be recovered. Open Bitkit to see why. + Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. + Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. + Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. + Emergency exit + {amount} on Spark is not part of this exit and stays on Spark. + {count} small amounts stayed on Spark. + The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. + Exit in\n<accent>progress</accent> + Could not get an exit quote. Try again. + Getting a quote… + {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. + Waiting for Spark to finish moving your balance. This can take up to 5 minutes. + Exit\n<accent>quote</accent> + Ready in {duration} + You receive about + Fee funding confirms + Publishing exit transactions + Sending to savings + Waiting for the timelock + Swipe To Exit + The fees are higher than what you would receive. Provider Spark via Breez No limit diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt new file mode 100644 index 0000000000..c1d32a8a0e --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt @@ -0,0 +1,80 @@ +package to.bitkit.repositories + +import org.junit.Test +import to.bitkit.repositories.SparkExitRecord.Phase +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class SparkExitAlertsTest { + private val running = SparkExitFixtures.record(Phase.Running) + private val unlimited = SparkExitBackgroundLimits() + + @Test + fun `names why a running exit fell behind, the most specific first`() { + val refused = running.copy( + broadcastLog = listOf( + SparkExitRecord.BroadcastAttempt( + generation = running.generation, + txid = "n1", + attempts = 3, + rejections = 3, + lastAttemptAt = 0L, + lastOutcome = "rejected: min relay fee not met", + isAccepted = false, + ), + ), + ) + assertEquals(SparkExitAlert.Rejected, SparkExitAlerts.reason(refused, isOnline = false, unlimited)) + assertEquals(SparkExitAlert.Offline, SparkExitAlerts.reason(running, isOnline = false, unlimited)) + assertEquals( + SparkExitAlert.Restricted, + SparkExitAlerts.reason(running, isOnline = true, unlimited.copy(isRestricted = true, isOptimized = true)), + ) + assertEquals( + SparkExitAlert.Battery, + SparkExitAlerts.reason(running, isOnline = true, unlimited.copy(isPowerSaveMode = true)), + ) + // Battery optimization is Android's default, so alone it is no cause to name. + assertEquals( + SparkExitAlert.Behind, + SparkExitAlerts.reason(running, isOnline = true, unlimited.copy(isOptimized = true)), + ) + assertEquals(SparkExitAlert.Behind, SparkExitAlerts.reason(running, isOnline = true, unlimited)) + } + + @Test + fun `asks for fee funding and stays quiet while nothing needs the user`() { + assertEquals( + SparkExitAlert.Funding, + SparkExitAlerts.reason(SparkExitFixtures.record(Phase.NeedsFunding(5_000uL)), isOnline = false, unlimited), + ) + assertNull(SparkExitAlerts.reason(SparkExitFixtures.record(), isOnline = false, unlimited)) + assertNull(SparkExitAlerts.reason(SparkExitFixtures.record(Phase.Done), isOnline = false, unlimited)) + assertNull(SparkExitAlerts.reason(null, isOnline = false, unlimited)) + } + + @Test + fun `posts each lost leaf event, and a failure unless every leaf was lost`() { + val lost = running.copy(lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 16_384uL))) + val claimed = lost.copy(phase = Phase.Failed(SparkExitDriver.LOST_REASON)) + val stopped = running.copy(phase = Phase.Failed(SparkExitDriver.NO_LEAF_REASON)) + + assertEquals(listOf(SparkExitAlert.Lost), SparkExitAlerts.losses(lost, running)) + assertEquals(listOf(SparkExitAlert.Lost), SparkExitAlerts.losses(claimed, running)) + assertEquals(emptyList(), SparkExitAlerts.losses(claimed, lost)) + assertEquals(listOf(SparkExitAlert.Failed), SparkExitAlerts.losses(stopped, running)) + // Every leaf lost says it alone, whatever the reason; a leaf left behind as well also fails the exit. + val stoppedLost = stopped.copy(lostLeaves = lost.lostLeaves) + assertEquals(listOf(SparkExitAlert.Lost), SparkExitAlerts.losses(stoppedLost, running)) + val leftBehind = SparkExitRecord.LeftBehindLeaf("leaf-2", 4_000uL, "Not recoverable at this fee rate") + assertEquals( + listOf(SparkExitAlert.Lost, SparkExitAlert.Failed), + SparkExitAlerts.losses( + stoppedLost.copy(leafIds = listOf("leaf-1", "leaf-2"), leftBehindLeaves = listOf(leftBehind)), + running, + ), + ) + assertEquals(emptyList(), SparkExitAlerts.losses(stopped, stopped)) + assertEquals(emptyList(), SparkExitAlerts.losses(SparkExitFixtures.record(Phase.Done), running)) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt new file mode 100644 index 0000000000..0613bb8b56 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -0,0 +1,198 @@ +package to.bitkit.repositories + +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.MockRequestHandleScope +import io.ktor.client.engine.mock.respond +import io.ktor.client.engine.mock.toByteArray +import io.ktor.client.plugins.defaultRequest +import io.ktor.client.request.HttpRequestData +import io.ktor.client.request.HttpResponseData +import io.ktor.http.ContentType +import io.ktor.http.HttpMethod +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import io.ktor.utils.io.errors.IOException +import org.junit.Test +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals +import kotlin.test.assertIs + +class SparkExitChainTest : BaseUnitTest() { + private val hostA = "https://a.example/api" + private val hostB = "https://b.example/api" + + private class Route(val url: String, val status: Int, val body: String) + + private val requests = mutableListOf() + private val bodies = mutableListOf() + + /** Answers each request with the first route whose URL it ends with; an unknown URL fails like a dead host. */ + private fun chain(vararg routes: Route, hosts: List = listOf(hostA)): EsploraSparkExitChain { + val pending = routes.toMutableList() + val engine = MockEngine { request -> answer(request, pending) } + // Like the app's shared client, which defaults every request to JSON. + val client = HttpClient(engine) { defaultRequest { contentType(ContentType.Application.Json) } } + return EsploraSparkExitChain(hosts, client) + } + + private suspend fun MockRequestHandleScope.answer( + request: HttpRequestData, + pending: MutableList, + ): HttpResponseData { + requests += request + bodies += String(request.body.toByteArray()) + val url = request.url.toString() + val route = pending.firstOrNull { url.endsWith(it.url) } ?: throw IOException("unreachable '$url'") + pending.remove(route) + return respond(route.body, HttpStatusCode.fromValue(route.status)) + } + + @Test + fun `sends a package as a raw json array of hex`() = test { + val sut = chain(Route("a.example/api/v1/txs/package", 200, """{"package_msg":"success","tx-results":{}}""")) + + val outcome = sut.broadcast(SparkExitFixtures.tx("n1", cpfp = "03child")) + + assertEquals(SparkExitBroadcastOutcome.Accepted, outcome) + assertEquals(HttpMethod.Post, requests.single().method) + assertEquals("""["02n1","03child"]""", bodies.single()) + assertEquals(ContentType.Application.Json, requests.single().body.contentType?.withoutParameters()) + } + + @Test + fun `sends a step without cpfp as plain hex`() = test { + val sut = chain(Route("a.example/api/tx", 200, "s1")) + + val outcome = sut.broadcast(SparkExitFixtures.tx("s1", kind = breez_sdk_spark.RecoveryTxKind.SWEEP)) + + assertEquals(SparkExitBroadcastOutcome.Accepted, outcome) + assertEquals("02s1", bodies.single()) + assertEquals(ContentType.Text.Plain, requests.single().body.contentType?.withoutParameters()) + assertEquals(null, requests.single().headers["Content-Type"]) + } + + @Test + fun `falls back to the unversioned package path then the next host`() = test { + val sut = chain( + Route("a.example/api/v1/txs/package", 404, "Not Found"), + Route("a.example/api/txs/package", 404, "Not Found"), + Route("b.example/api/v1/txs/package", 200, """{"package_msg":"success"}"""), + hosts = listOf(hostA, hostB), + ) + + val outcome = sut.broadcast(SparkExitFixtures.tx("n1", cpfp = "03c")) + + assertEquals(SparkExitBroadcastOutcome.Accepted, outcome) + assertEquals(listOf("a.example", "a.example", "b.example"), requests.map { it.url.host }) + } + + @Test + fun `tries the next host after a rejection or an unavailable host`() = test { + val rejected = chain( + Route( + "a.example/api/tx", + 400, + """sendrawtransaction RPC error: {"code":-26,"message":"min relay fee not met"}""" + ), + Route("b.example/api/tx", 200, "s1"), + hosts = listOf(hostA, hostB), + ) + assertEquals(SparkExitBroadcastOutcome.Accepted, rejected.broadcast(SparkExitFixtures.tx("s1"))) + + val limited = chain( + Route("a.example/api/tx", 429, "Too Many Requests"), + Route("b.example/api/tx", 200, "s1"), + hosts = listOf(hostA, hostB), + ) + assertEquals(SparkExitBroadcastOutcome.Accepted, limited.broadcast(SparkExitFixtures.tx("s1"))) + } + + @Test + fun `a node refusal wins over an unavailable or unreachable host`() = test { + val sut = chain( + Route( + "a.example/api/tx", + 400, + """sendrawtransaction RPC error: {"code":-26,"message":"min relay fee not met"}""" + ), + Route("b.example/api/tx", 503, ""), + hosts = listOf(hostA, hostB, "https://c.example/api"), + ) + + assertIs(sut.broadcast(SparkExitFixtures.tx("s1"))) + } + + @Test + fun `no reachable host is retried later`() = test { + val outcome = chain(hosts = listOf(hostA)).broadcast(SparkExitFixtures.tx("s1")) + + assertEquals(SparkExitBroadcastOutcome.RetryLater("no chain host reachable"), outcome) + } + + @Test + fun `reads the tip, funding utxos and a transaction status`() = test { + val sut = chain( + Route("a.example/api/blocks/tip/height", 200, "3681536\n"), + Route( + "a.example/api/address/bcrt1qf/utxo", + 200, + """[{"txid":"t","vout":1,"value":5000,""" + + """"status":{"confirmed":true,"block_height":7,"block_hash":"h"}}]""", + ), + Route("a.example/api/tx/t/status", 200, """{"confirmed":false}"""), + ) + + assertEquals(3_681_536u, sut.tipHeight()) + assertEquals(listOf(EsploraUtxo("t", 1u, 5_000uL, EsploraTxStatus(true, 7u))), sut.utxos("bcrt1qf")) + assertEquals(EsploraTxStatus(false, null), sut.txStatus("t")) + } + + @Test + fun `classifies node answers`() { + val failedPackage = """{"package_msg":"transaction failed","tx-results":""" + val classifier = SparkExitBroadcastClassifier + assertEquals( + SparkExitBroadcastOutcome.Accepted, + classifier.single(400, """sendrawtransaction RPC error: {"code":-27}"""), + ) + assertEquals( + SparkExitBroadcastOutcome.InputsMissing("""sendrawtransaction RPC error: {"code":-25}"""), + classifier.single(400, """sendrawtransaction RPC error: {"code":-25}"""), + ) + assertEquals(SparkExitBroadcastOutcome.RetryLater("HTTP 503"), classifier.single(503, "")) + assertIs( + classifier.single(400, """{"code":-26,"message":"min relay fee not met"}""") + ) + + val missing = failedPackage + """{"w1":{"txid":"a","error":"bad-txns-inputs-missingorspent"},""" + + """"w2":{"txid":"b","error":"bad-txns-inputs-missingorspent"}},"replaced-transactions":[]}""" + assertIs(classifier.pkg(200, missing)) + val known = failedPackage + """{"w1":{"txid":"a","error":"txn-already-in-mempool"},""" + + """"w2":{"txid":"b"}}}""" + assertEquals(SparkExitBroadcastOutcome.Accepted, classifier.pkg(200, known)) + val nonFinal = failedPackage + """{"w1":{"txid":"a","error":"non-BIP68-final"}}}""" + assertIs(classifier.pkg(200, nonFinal)) + // A child of an immature parent can fail with any error; the parent's timelock decides. + val nonFinalParent = failedPackage + """{"w1":{"txid":"a","error":"non-BIP68-final"},""" + + """"w2":{"txid":"b","error":"min relay fee not met"}}}""" + assertIs(classifier.pkg(200, nonFinalParent)) + val escaped = """{"error":"submitpackage RPC error: {\"code\":-25}"}""" + assertEquals(SparkExitBroadcastOutcome.InputsMissing(escaped), classifier.pkg(400, escaped)) + // Missing inputs on the CPFP child alone say nothing about the step. + val childMissing = failedPackage + """{"w1":{"txid":"parent"},""" + + """"w2":{"txid":"child","error":"bad-txns-inputs-missingorspent"}}}""" + assertIs(classifier.pkg(200, childMissing, parentTxid = "parent")) + val parentMissing = failedPackage + """{"w1":{"txid":"parent","error":"bad-txns-inputs-missingorspent"}}}""" + assertIs(classifier.pkg(200, parentMissing, parentTxid = "parent")) + // The step's own missing inputs decide over its child's error, in either order. + val parentFirst = failedPackage + """{"w1":{"txid":"parent","error":"bad-txns-inputs-missingorspent"},""" + + """"w2":{"txid":"child","error":"package-not-validated"}}}""" + assertIs(classifier.pkg(200, parentFirst, parentTxid = "parent")) + val childFirst = failedPackage + """{"w2":{"txid":"child","error":"package-not-validated"},""" + + """"w1":{"txid":"parent","error":"bad-txns-inputs-missingorspent"}}}""" + assertIs(classifier.pkg(200, childFirst, parentTxid = "parent")) + val lowFee = failedPackage + """{"w1":{"txid":"a","error":"min relay fee not met"}}}""" + assertIs(classifier.pkg(200, lowFee)) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt new file mode 100644 index 0000000000..93da862114 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -0,0 +1,843 @@ +package to.bitkit.repositories + +import breez_sdk_spark.CheckRecoverFundsResponse +import breez_sdk_spark.CooperativeRecoveryError +import breez_sdk_spark.CooperativeRecoveryFailure +import breez_sdk_spark.CpfpInput +import breez_sdk_spark.ExitLeafSelection +import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.RecoverFundsResponse +import breez_sdk_spark.RecoveryRedoReason +import breez_sdk_spark.RecoveryTxKind +import breez_sdk_spark.RecoveryVerdict +import breez_sdk_spark.SdkException +import breez_sdk_spark.SkippedLeaf +import breez_sdk_spark.SkippedLeafReason +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import to.bitkit.repositories.SparkExitRecord.Phase +import to.bitkit.test.BaseUnitTest +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Duration.Companion.seconds + +class SparkExitDriverTest : BaseUnitTest() { + private companion object { + const val SWEEP_DESTINATION = "bcrt1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqc8gma6" + const val SWEEP_FUNDING = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + } + + @get:Rule + val tempFolder = TemporaryFolder() + + private val chain = FakeSparkExitChain() + private val sdk = FakeSparkExitRecovering() + private val saved = mutableListOf() + private var now = 1_800_000_000_000L + + private fun driver(withSdk: Boolean = true, save: (SparkExitRecord) -> Unit = { saved += it }) = SparkExitDriver( + chain = chain, + recovering = sdk.takeIf { withSdk }, + makeSigner = { StubCpfpSigner() }, + save = save, + nowMillis = { now }, + ) + + private fun running(recovery: RecoverFundsResponse, builtAt: Long = now) = + SparkExitFixtures.record(Phase.Running).adopt(recovery, builtAt) + + private fun check(recovery: RecoverFundsResponse, verdict: RecoveryVerdict) = + CheckRecoverFundsResponse(recovery, verdict) + + private val redo = RecoveryVerdict.Redo(RecoveryRedoReason.ON_CHAIN_STATE_DIVERGED) + + @Test + fun `waits for a confirmed funding utxo`() = test { + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + listOf(SparkExitFixtures.utxo("f0", value = 20_000uL, confirmed = false)) + + val record = driver().tick(SparkExitFixtures.record()) + + assertEquals(Phase.AwaitingFunding(20_000uL), record.phase) + assertTrue(sdk.prepareRequests.isEmpty()) + } + + @Test + fun `builds once funded and saves before broadcasting`() = test { + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", 1u, 25_000uL)) + sdk.builds += SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", cpfp = "03c1"), + SparkExitFixtures.tx( + "n2", + dependsOn = listOf("n1"), + status = ExitTransactionStatus.WaitingForDependencies, + ), + ), + ) + var savesAtFirstBroadcast: Int? = null + chain.onBroadcast = { savesAtFirstBroadcast = savesAtFirstBroadcast ?: saved.size } + + val record = driver().tick(SparkExitFixtures.record()) + + assertEquals(Phase.Running, record.phase) + assertEquals(1, record.generation) + assertEquals(1, savesAtFirstBroadcast) + assertEquals(record.recovery, saved.first().recovery) + assertEquals( + listOf(CpfpInput.P2wpkh("f0", 1u, 25_000uL, "02ab")), + sdk.recoverRequests.first().fundingInputs + ) + assertEquals(listOf("leaf-1"), (sdk.prepareRequests.first().selection as ExitLeafSelection.Specific).leafIds) + assertEquals(listOf("n1"), chain.broadcasts.map { it.txid }) + assertEquals(listOf("n1"), record.broadcastLog.map { it.txid }) + assertEquals(record, saved.last()) + } + + @Test + fun `valid broadcasts ready steps once until they are due again`() = test { + var record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1")))) + val checked = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(10u)), + SparkExitFixtures.tx("n2", cpfp = "03c2", dependsOn = listOf("n1")), + SparkExitFixtures.tx( + "r1", + kind = RecoveryTxKind.REFUND, + dependsOn = listOf("n2"), + status = ExitTransactionStatus.WaitingForTimelock(3_000u), + ), + ), + ) + repeat(3) { sdk.checks += check(checked, RecoveryVerdict.Valid) } + + record = driver().tick(record) + record = driver().tick(record) + now += SparkExitDriver.REBROADCAST_INTERVAL.inWholeMilliseconds + record = driver().tick(record) + + assertEquals(listOf("n2", "n2"), chain.broadcasts.map { it.txid }) + assertEquals(2, record.broadcastLog.single().attempts) + assertEquals(3_000u, record.claimableAtHeight) + assertEquals(checked, record.recovery) + } + + @Test + fun `marks steps the chain host shows in a block before the sdk check`() = test { + val built = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("fan", kind = RecoveryTxKind.FAN_OUT), + SparkExitFixtures.tx( + "n1", + cpfp = "03c", + dependsOn = listOf("fan"), + status = ExitTransactionStatus.WaitingForDependencies, + ), + SparkExitFixtures.tx( + "n2", + cpfp = "03d", + dependsOn = listOf("n1"), + status = ExitTransactionStatus.WaitingForDependencies, + ), + ), + ) + chain.confirmedTxids = setOf("fan", "n1") + sdk.checks += check(built, RecoveryVerdict.Valid) + + driver().tick(running(built)) + + val sent = sdk.checkedRecoveries.single().transactions.map { it.status } + assertEquals( + listOf( + ExitTransactionStatus.Confirmed(900u), + ExitTransactionStatus.Confirmed(900u), + ExitTransactionStatus.WaitingForDependencies, + ), + sent, + ) + } + + @Test + fun `retries a rejected step and surfaces it after repeated rejections`() = test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1", cpfp = "03c"))) + var record = running(recovery) + chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met") + repeat(3) { sdk.checks += check(recovery, RecoveryVerdict.Valid) } + + record = driver().tick(record) + assertNull(record.surfacedRejection) + repeat(2) { record = driver().tick(record) } + + assertEquals(3, chain.broadcasts.size) + assertEquals("rejected: min relay fee not met", record.surfacedRejection) + } + + @Test + fun `done finishes and reads leftover funding`() = test { + var record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("s", kind = RecoveryTxKind.SWEEP)))) + val done = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("s", kind = RecoveryTxKind.SWEEP, status = ExitTransactionStatus.Confirmed(50u)) + ), + ) + sdk.checks += check(done, RecoveryVerdict.Done) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + listOf(SparkExitFixtures.utxo("change", value = 700uL)) + + record = driver().tick(record) + + assertEquals(Phase.Done, record.phase) + assertFalse(record.isActive) + assertEquals(listOf(SparkExitRecord.Leftover("change", 0u, 700uL)), record.leftover) + assertTrue(chain.broadcasts.isEmpty()) + assertEquals(record, saved.last()) + } + + @Test + fun `redo rebuilds as a new generation and never sends the old one`() = test { + val old = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))) + var record = running(old, builtAt = now - SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds).copy( + funding = listOf( + SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 20_000uL) + ), + broadcastLog = listOf(SparkExitRecord.BroadcastAttempt(1, "old", 1, 0, now, "accepted", true)), + ) + sdk.checks += check(old, redo) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("new", cpfp = "03n"))) + + record = driver().tick(record) + + assertEquals(2, record.generation) + assertFalse(record.isRebuilding) + assertEquals(listOf("new"), record.recovery?.transactions?.map { it.txid }) + assertEquals(listOf("new"), record.broadcastLog.map { it.txid }) + assertEquals(listOf("new"), chain.broadcasts.map { it.txid }) + assertEquals( + listOf(CpfpInput.P2wpkh("f0", 1u, 20_000uL, "02ab")), + sdk.recoverRequests.first().fundingInputs + ) + assertTrue(saved.first().isRebuilding) + } + + @Test + fun `redo is saved before rebuilding so the old generation is never sent without the sdk`() = test { + val old = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))) + var record = running(old) + sdk.checks += check(old, redo) + + // Built a minute ago: the rebuild waits, but the diverged state is already saved. + now += 60.seconds.inWholeMilliseconds + record = driver().tick(record) + assertTrue(record.isRebuilding) + assertTrue(saved.first().isRebuilding) + assertTrue(sdk.recoverRequests.isEmpty()) + + record = driver(withSdk = false).tick(record) + assertTrue(chain.broadcasts.isEmpty()) + + now += SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("new"))) + record = driver().tick(record) + assertFalse(record.isRebuilding) + assertEquals(2, record.generation) + assertEquals(listOf("new"), chain.broadcasts.map { it.txid }) + } + + @Test + fun `rebuild that needs more fees asks for funding`() = test { + val old = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))) + var record = running(old, builtAt = 0L) + sdk.checks += check(SparkExitFixtures.recovery(emptyList()), redo) + sdk.recoverError = SdkException.InsufficientCpfpFunds(3_000uL, "") + + record = driver().tick(record) + + assertEquals(Phase.NeedsFunding(3_000uL), record.phase) + assertTrue(record.isActive) + assertEquals(3_000uL, record.fundingShortfallSats) + } + + @Test + fun `asks only for what the sdk's total lacks and adopts small top ups together`() = test { + // A headless regtest run: the quote asked 8,541, five UTXOs held 9,035, and the SDK wanted 9,085 in total. + val funded = listOf(1_807uL, 1_807uL, 1_807uL, 1_807uL, 1_807uL).mapIndexed { i, value -> + SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f$i", 0u, value) + } + var record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) + .copy(funding = funded) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = funded.map { + SparkExitFixtures.utxo(requireNotNull(it.txid), value = requireNotNull(it.valueSats)) + } + sdk.checks += check(SparkExitFixtures.recovery(emptyList()), redo) + sdk.recoverError = SdkException.InsufficientCpfpFunds(9_085uL, "") + + record = driver().tick(record) + + assertEquals(Phase.NeedsFunding(9_085uL), record.phase) + assertEquals(50uL, record.fundingShortfallSats) + + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = funded.map { + SparkExitFixtures.utxo(requireNotNull(it.txid), value = requireNotNull(it.valueSats)) + } + listOf(SparkExitFixtures.utxo("t1", value = 30uL), SparkExitFixtures.utxo("t2", value = 20uL)) + sdk.recoverError = null + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + record = driver().tick(record) + + assertEquals(Phase.Running, record.phase) + assertEquals(7, sdk.recoverRequests.last().fundingInputs.size) + } + + @Test + fun `a redo whose spent input lives on as change asks only for what that change lacks`() = test { + val built = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1", cpfp = SparkExitFixtures.PARENT_HEX))) + var record = running(built, builtAt = 0L).copy( + funding = listOf( + SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 20_000uL), + ), + ) + // The input went into a CPFP child, whose 13,000 of change sits at the funding address. + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + listOf(SparkExitFixtures.utxo(SparkExitFixtures.PARENT_TXID, value = 13_000uL)) + sdk.checks += check(built, redo) + sdk.recoverError = SdkException.InsufficientCpfpFunds(15_000uL, "") + + record = driver().tick(record) + + assertEquals(2_000uL, record.fundingShortfallSats) + } + + @Test + fun `the tick that ends the exit sweeps its leftover to savings until a node accepts it`() = test { + val funding = "f0".repeat(32) + chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo(funding, 1u, 25_000uL)) + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = emptyList(), skipped = emptyList()) + chain.outcome = SparkExitBroadcastOutcome.RetryLater("unreachable") + val start = SparkExitFixtures.record().copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + ) + + var record = driver().tick(start) + + assertIs(record.phase) + assertEquals(listOf(SparkExitRecord.Leftover(funding, 1u, 25_000uL)), record.leftover) + val sweep = assertNotNull(record.leftoverSweep) + assertEquals(1, chain.rawBroadcasts.size) + assertTrue(record.isLeftoverSweepPending) + assertEquals(sweep, saved.first { it.leftoverSweep != null }.leftoverSweep) + + chain.outcome = SparkExitBroadcastOutcome.Accepted + record = driver().tick(record) + + assertEquals(listOf(sweep.txHex, sweep.txHex), chain.rawBroadcasts) + assertTrue(assertNotNull(record.leftoverSweep).isAccepted) + // Sent again until it confirms, and the result stays reachable until then. + assertTrue(record.needsDriving) + assertTrue(record.showsResult) + record = driver().tick(record) + assertEquals(3, chain.rawBroadcasts.size) + + chain.confirmedTxids = setOf(requireNotNull(sweep.txid)) + record = driver().tick(record) + + assertTrue(assertNotNull(record.leftoverSweep).isConfirmed) + assertFalse(record.needsDriving) + // A failed exit stays reachable until its result was seen. + assertTrue(record.showsResult) + assertFalse(record.copy(isResultSeen = true).showsResult) + record = driver().tick(record) + assertEquals(3, chain.rawBroadcasts.size) + } + + @Test + fun `a leftover under dust is not swept`() = test { + chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0", 1u, 400uL)) + val done = SparkExitFixtures.record(Phase.Done).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + leftover = listOf(SparkExitRecord.Leftover("f0", 1u, 400uL)), + ) + + val record = driver().tick(done) + + assertEquals(SparkExitRecord.LeftoverSweep(null, null, 400uL), record.leftoverSweep) + assertTrue(chain.rawBroadcasts.isEmpty()) + assertFalse(record.needsDriving) + } + + @Test + fun `top up ignores cpfp change chained to the funding address`() = test { + var record = SparkExitFixtures.record(Phase.NeedsFunding(23_000uL)).copy( + funding = listOf( + SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 20_000uL) + ), + recovery = SparkExitFixtures.recovery( + listOf(SparkExitFixtures.tx("n1", cpfp = SparkExitFixtures.PARENT_HEX)) + ), + ) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf( + SparkExitFixtures.utxo("f0", 1u, 20_000uL), + SparkExitFixtures.utxo(SparkExitFixtures.PARENT_TXID, value = 9_000uL), + ) + + record = driver().tick(record) + assertEquals(Phase.NeedsFunding(23_000uL), record.phase) + assertEquals(3_000uL, record.fundingShortfallSats) + assertTrue(sdk.prepareRequests.isEmpty()) + + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + chain.utxosByAddress.getValue(SparkExitFixtures.FUNDING_ADDRESS) + + SparkExitFixtures.utxo("topup", value = 3_000uL) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + record = driver().tick(record) + + assertEquals(Phase.Running, record.phase) + assertEquals(2, sdk.recoverRequests.first().fundingInputs.size) + } + + @Test + fun `cooperative leaves the operators could not sign are tried again`() = test { + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null) + sdk.builds += SparkExitFixtures.recovery( + emptyList(), + failed = listOf( + CooperativeRecoveryFailure("leaf-1", "o", 0u, CooperativeRecoveryError.OperatorsUnavailable("down")), + ), + ) + + val record = driver().tick(SparkExitFixtures.record(Phase.AwaitingFunding(0uL))) + + assertEquals(Phase.AwaitingFunding(0uL), record.phase) + assertEquals(1, record.failedLeafCount) + assertNull(record.recovery) + } + + @Test + fun `rebuild with nothing left ends the exit`() = test { + val record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) + .copy(isRebuilding = true) + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = emptyList()) + + assertEquals(Phase.Done, driver().tick(record).phase) + } + + @Test + fun `rebuild waits while a leaf is unverified`() = test { + val record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) + .copy(isRebuilding = true) + sdk.preparedResponse = SparkExitFixtures.prepared( + leaves = emptyList(), + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + + val ticked = driver().tick(record) + + assertEquals(Phase.Running, ticked.phase) + assertTrue(ticked.isRebuilding) + } + + @Test + fun `resumes after a restart mid-exit without repeating broadcasts`() = test { + val store = SparkExitStore(File(tempFolder.root, "spark-exit.json")) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", value = 20_000uL)) + val built = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1", cpfp = "03c"))) + sdk.builds += built + driver(save = store::save).tick(SparkExitFixtures.record()) + + // A new process: only the file is left, and a fresh driver picks up from it. + val reloaded = requireNotNull(store.load()) + sdk.checks += check(built, RecoveryVerdict.Valid) + driver(save = store::save).tick(reloaded) + + assertEquals(Phase.Running, reloaded.phase) + assertEquals(1, reloaded.generation) + assertEquals(listOf("n1"), chain.broadcasts.map { it.txid }) + assertEquals(1, sdk.recoverRequests.size) + assertEquals(1, requireNotNull(store.load()).broadcastLog.single().attempts) + } + + @Test + fun `without the sdk broadcasts steps whose parents confirmed and timelocks matured`() = test { + var record = running( + SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1"), + SparkExitFixtures.tx( + "n2", + cpfp = "03c", + dependsOn = listOf("n1"), + status = ExitTransactionStatus.WaitingForDependencies, + ), + SparkExitFixtures.tx( + "r1", + kind = RecoveryTxKind.REFUND, + dependsOn = listOf("n2"), + status = ExitTransactionStatus.WaitingForTimelock(990u), + ), + SparkExitFixtures.tx( + "r2", + kind = RecoveryTxKind.REFUND, + dependsOn = listOf("n1"), + status = ExitTransactionStatus.WaitingForTimelock(1_500u), + ), + ), + ), + ) + chain.tip = 1_000u + chain.confirmedTxids = setOf("n1") + + record = driver(withSdk = false).tick(record) + + assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }) + assertEquals(ExitTransactionStatus.Confirmed(900u), record.recovery?.transactions?.first()?.status) + assertEquals(Phase.Running, record.phase) + } + + @Test + fun `does nothing once finished`() = test { + val record = driver().tick(SparkExitFixtures.record(Phase.Done)) + + assertIs(record.phase) + assertTrue(saved.isEmpty()) + } + + @Test + fun `a run killed after a broadcast does not send it again on restart`() = test { + val store = SparkExitStore(File(tempFolder.root, "spark-exit.json")) + store.save(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"), SparkExitFixtures.tx("n2"))))) + // The process dies while it sends the second transaction, after the first went out. + chain.onBroadcast = { if (chain.broadcasts.size == 1) error("killed") } + + runCatching { driver(withSdk = false, save = store::save).tick(requireNotNull(store.load())) } + chain.onBroadcast = {} + val record = driver(withSdk = false, save = store::save).tick(requireNotNull(store.load())) + + assertEquals(listOf("n1", "n2"), chain.broadcasts.map { it.txid }) + assertEquals(listOf("n1", "n2"), record.broadcastLog.map { it.txid }) + assertEquals(record, store.load()) + } + + @Test + fun `done after a redo that needed no funding sweeps the earlier generation's change in one transaction`() = test { + val gen1 = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1", cpfp = "03c1"))) + var record = running(gen1).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab", "f0".repeat(32), 0u, 20_000uL)), + ) + sdk.checks += check(gen1, redo) + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null) + val gen2 = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + sdk.builds += gen2 + now += SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds + + record = driver().tick(record) + + assertEquals(2, record.generation) + assertTrue(sdk.recoverRequests.single().fundingInputs.isEmpty()) + + val change = (1..5).map { SparkExitFixtures.utxo("%064x".format(it), 1u, 700uL + it.toULong()) } + chain.utxosByAddress[SWEEP_FUNDING] = change + sdk.checks += check(gen2, RecoveryVerdict.Done) + record = driver().tick(record) + + assertEquals(Phase.Done, record.phase) + assertEquals(5, record.leftover.size) + val sent = chain.rawBroadcasts.single() + assertEquals(change.map { it.txid }, SparkExitTxInputs.decode(sent)?.map { it.prevTxid }) + assertTrue(assertNotNull(record.leftoverSweep).isAccepted) + assertTrue(record.showsResult) + } + + @Test + fun `an exit that ended while its funding address could not be read ends again once it can`() = test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + var record = running(recovery) + chain.utxosError = IllegalStateException("unreachable") + sdk.checks += check(recovery, RecoveryVerdict.Done) + + record = driver().tick(record) + + assertEquals(Phase.Running, record.phase) + assertTrue(record.needsDriving) + + chain.utxosError = null + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("c1", value = 900uL)) + sdk.checks += check(recovery, RecoveryVerdict.Done) + record = driver().tick(record) + + assertEquals(Phase.Done, record.phase) + assertEquals(listOf(SparkExitRecord.Leftover("c1", 0u, 900uL)), record.leftover) + } + + @Test + fun `adopted funding keeps the exit's own funding key index`() = test { + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", 1u, 25_000uL)) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + val start = SparkExitFixtures.record().let { it.copy(funding = it.funding.map { f -> f.copy(index = 3u) }) } + + val record = driver().tick(start) + + assertEquals(listOf(3u), record.funding.map { it.index }) + assertEquals(3u, record.fundingIndex) + } + + @Test + fun `without the sdk a refund waits for its csv to mature from its parent's confirmation`() = test { + val node = "aa".repeat(32) + val refund = SparkExitFixtures.tx( + "r1", + kind = RecoveryTxKind.REFUND, + dependsOn = listOf(node), + status = ExitTransactionStatus.WaitingForDependencies, + csv = 100u, + ).copy(txHex = SparkExitFixtures.csvTxHex(node, csv = 100)) + var record = running(SparkExitFixtures.recovery(listOf(refund))) + chain.confirmedTxids = setOf(node) + chain.heights[node] = 950u + chain.tip = 1_000u + + record = driver(withSdk = false).tick(record) + + assertTrue(chain.broadcasts.isEmpty()) + val waiting = record.recovery?.transactions?.single()?.status + assertEquals(ExitTransactionStatus.WaitingForTimelock(1_050u), waiting) + + // Nodes take it once it would be valid in the next block. + chain.tip = 1_049u + record = driver(withSdk = false).tick(record) + + assertEquals(listOf("r1"), chain.broadcasts.map { it.txid }) + assertEquals(0, record.broadcastLog.single().rejections) + } + + @Test + fun `without the sdk a step whose input someone else spent is not sent again`() = test { + val recovery = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1"), + SparkExitFixtures.tx( + "r1", + kind = RecoveryTxKind.REFUND, + dependsOn = listOf("n1"), + status = ExitTransactionStatus.WaitingForDependencies, + ), + ), + ) + var record = running(recovery) + chain.confirmedTxids = setOf("n1") + chain.outcome = SparkExitBroadcastOutcome.InputsMissing("bad-txns-inputs-missingorspent") + + record = driver(withSdk = false).tick(record) + now += SparkExitDriver.REBROADCAST_INTERVAL.inWholeMilliseconds + record = driver(withSdk = false).tick(record) + + assertEquals(listOf("r1"), chain.broadcasts.map { it.txid }) + val attempt = record.broadcastLog.single() + assertTrue(attempt.isInputSpent) + assertEquals(0, attempt.rejections) + assertNull(record.surfacedRejection) + } + + /** The qa-03 run: an older state's refund took the leaf, and every Redo rebuilt the same spent refund. */ + private fun lostLeafRecovery(leafId: String = "leaf-1") = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("node", status = ExitTransactionStatus.Confirmed(11_522u)), + SparkExitFixtures.tx("refund", kind = RecoveryTxKind.REFUND, cpfp = "03c", dependsOn = listOf("node")) + .copy(nodeId = leafId), + SparkExitFixtures.tx( + "sweep", + kind = RecoveryTxKind.SWEEP, + dependsOn = listOf("refund"), + status = ExitTransactionStatus.WaitingForDependencies, + ), + ), + ) + + @Test + fun `a refund an older state already spent ends the exit after two rebuilds reproduce it`() = test { + val recovery = lostLeafRecovery() + var record = running(recovery) + chain.outcome = SparkExitBroadcastOutcome.InputsMissing("""sendrawtransaction RPC error: {"code":-25}""") + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null) + sdk.checks += check(recovery, RecoveryVerdict.Valid) + repeat(2) { + sdk.checks += check(recovery, redo) + sdk.builds += recovery + } + + // Sent, refused as spent; then each Redo rebuilds the same refund. + record = driver().tick(record) + assertTrue(record.broadcastLog.single().isInputSpent) + now += SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds + record = driver().tick(record) + assertEquals(2, record.generation) + assertEquals(mapOf("refund" to 1), record.spentStepStrikes) + now += SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds + record = driver().tick(record) + + assertEquals(2, record.generation) + assertEquals(Phase.Failed(SparkExitDriver.LOST_REASON), record.phase) + assertEquals(listOf(SparkExitRecord.LostLeaf("leaf-1", 100_000uL)), record.lostLeaves) + assertEquals(100_000uL, record.lostSats) + assertFalse(record.isActive) + } + + @Test + fun `a single leaf lost while the funding address cannot be read ends lost through the no-leaf path`() = test { + val recovery = lostLeafRecovery() + var record = running(recovery) + chain.outcome = SparkExitBroadcastOutcome.InputsMissing("""sendrawtransaction RPC error: {"code":-25}""") + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null) + sdk.checks += check(recovery, RecoveryVerdict.Valid) + repeat(2) { + sdk.checks += check(recovery, redo) + sdk.builds += recovery + } + record = driver().tick(record) + now += SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds + record = driver().tick(record) + now += SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds + chain.utxosError = IllegalStateException("unreachable") + val lost = driver().tick(record) + assertEquals(Phase.Running, lost.phase) + assertEquals(listOf(SparkExitAlert.Lost), SparkExitAlerts.losses(lost, record)) + + chain.utxosError = null + val ended = driver().tick(lost) + + assertEquals(Phase.Failed(SparkExitDriver.LOST_REASON), ended.phase) + assertEquals(emptyList(), SparkExitAlerts.losses(ended, lost)) + val noLeaf = ended.copy(phase = Phase.Failed(SparkExitDriver.NO_LEAF_REASON)) + assertEquals(emptyList(), SparkExitAlerts.losses(noLeaf, lost)) + } + + @Test + fun `a lost leaf is left out and the rest of the exit rebuilds at once`() = test { + val recovery = lostLeafRecovery() + val start = running(recovery).copy(leafIds = listOf("leaf-1", "leaf-2")) + val strikes = start.copy( + spentStepStrikes = mapOf("refund" to 1), + broadcastLog = listOf( + SparkExitRecord.BroadcastAttempt(1, "refund", 1, 0, now, "inputs missing", false, isInputSpent = true), + ), + isRebuilding = true, + lastBuildAt = null, + ) + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null) + sdk.builds += recovery + + var record = driver().tick(strikes) + + assertEquals(Phase.Running, record.phase) + assertTrue(record.isRebuilding) + assertNull(record.lastBuildAt) + assertEquals(listOf("leaf-2"), record.exitLeafIds) + + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + record = driver().tick(record) + + val selection = sdk.prepareRequests.last().selection as ExitLeafSelection.Specific + assertEquals(listOf("leaf-2"), selection.leafIds) + assertEquals(2, record.generation) + } + + private fun ladderRefusal(leafId: String) = SdkException.SparkException( + "Leaf $leafId cannot be exited: its refund cannot pay its own fee at this fee rate", + ) + + @Test + fun `a rebuild drops a fee-ladder leaf that cannot pay its refund and prepares the rest`() = test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + val start = running( + recovery + ).copy(leafIds = listOf("leaf-1", "leaf-2"), isRebuilding = true, lastBuildAt = null) + sdk.prepareErrors += ladderRefusal("leaf-1") + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-2")) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + + val record = driver().tick(start) + + assertEquals( + listOf(listOf("leaf-1", "leaf-2"), listOf("leaf-2")), + sdk.prepareRequests.map { (it.selection as ExitLeafSelection.Specific).leafIds }, + ) + val dropped = record.leftBehindLeaves.single() + assertEquals("leaf-1", dropped.leafId) + assertEquals(100_000uL, dropped.valueSats) + assertEquals(ladderRefusal("leaf-1").v1, dropped.reason) + assertEquals(2, record.generation) + } + + @Test + fun `a rebuild whose every leaf cannot be exited fails`() = test { + val start = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1")))) + .copy(isRebuilding = true, lastBuildAt = null) + sdk.prepareErrors += ladderRefusal("leaf-1") + + val record = driver().tick(start) + + assertEquals(Phase.Failed(SparkExitDriver.NO_LEAF_REASON), record.phase) + assertEquals(listOf("leaf-1"), record.leftBehindLeaves.map { it.leafId }) + } + + @Test + fun `a refusal naming no leaf of the exit prepares what is still recoverable`() = test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + val start = running( + recovery + ).copy(leafIds = listOf("leaf-1", "leaf-2"), isRebuilding = true, lastBuildAt = null) + sdk.prepareErrors += SdkException.SparkException("Leaf cannot be exited") + sdk.preparedResponse = + SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-1"), skipped = emptyList()) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + + val record = driver().tick(start) + + assertEquals(ExitLeafSelection.RecoverableOnly, sdk.prepareRequests.last().selection) + assertEquals(listOf("leaf-2"), record.leftBehindLeaves.map { it.leafId }) + assertEquals(SparkExitUnexitable.NOT_RECOVERABLE, record.leftBehindLeaves.single().reason) + assertEquals(listOf("leaf-1"), record.exitLeafIds) + assertEquals(2, record.generation) + } + + @Test + fun `a leaf recoverFunds refuses is left behind and the rest rebuilt on the next tick`() = test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + val start = running( + recovery + ).copy(leafIds = listOf("leaf-1", "leaf-2"), isRebuilding = true, lastBuildAt = null) + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-1", "leaf-2")) + sdk.recoverError = ladderRefusal("leaf-1") + + var record = driver().tick(start) + + assertEquals(listOf("leaf-2"), record.exitLeafIds) + assertTrue(record.isRebuilding) + assertNull(record.lastBuildAt) + assertEquals(1, record.generation) + + sdk.recoverError = null + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + record = driver().tick(record) + + assertEquals(listOf("leaf-2"), (sdk.prepareRequests.last().selection as ExitLeafSelection.Specific).leafIds) + assertEquals(2, record.generation) + } + + @Test + fun `only a spark error saying a leaf cannot be exited is read as one`() { + assertNull(SparkExitUnexitable.parse(SdkException.SparkException("connection refused"))) + assertNull(SparkExitUnexitable.parse(IllegalStateException("Leaf a cannot be exited"))) + val message = "Leaf abc-1 cannot be exited: its refund cannot pay its own fee at this fee rate" + assertEquals( + SparkExitUnexitable.Refusal("abc-1", message), + SparkExitUnexitable.parse(SdkException.SparkException(message)), + ) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt new file mode 100644 index 0000000000..d2883d8a0d --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -0,0 +1,216 @@ +package to.bitkit.repositories + +import breez_sdk_spark.CheckRecoverFundsResponse +import breez_sdk_spark.CooperativeRecoveryFailure +import breez_sdk_spark.CpfpInput +import breez_sdk_spark.CpfpSigner +import breez_sdk_spark.ExitChainState +import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.PrepareRecoverFundsRequest +import breez_sdk_spark.PrepareRecoverFundsResponse +import breez_sdk_spark.RecoverFundsLeaf +import breez_sdk_spark.RecoverFundsRequest +import breez_sdk_spark.RecoverFundsResponse +import breez_sdk_spark.RecoveryFunding +import breez_sdk_spark.RecoveryMethod +import breez_sdk_spark.RecoveryTransaction +import breez_sdk_spark.RecoveryTxKind +import breez_sdk_spark.SkippedLeaf +import breez_sdk_spark.SkippedLeafReason + +/** The same fixtures as Bitkit iOS's `SparkExitTests.swift`, so both suites assert the same values. */ +object SparkExitFixtures { + const val PARENT_HEX = "020000000111111111111111111111111111111111111111111111111111111111111111110000000000" + + "ffffffff01e803000000000000160014222222222222222222222222222222222222222200000000" + + /** The id Spark's regtest node reported for [PARENT_HEX]. */ + const val PARENT_TXID = "b91b720103788b9ae50dbff918bc375d185df91025b9f6e861efe208909b6adf" + + const val FUNDING_ADDRESS = "bcrt1qfunding" + + fun tx( + txid: String, + kind: RecoveryTxKind = RecoveryTxKind.NODE, + cpfp: String? = null, + dependsOn: List = emptyList(), + status: ExitTransactionStatus = ExitTransactionStatus.Ready, + csv: UInt? = null, + ) = RecoveryTransaction( + kind = kind, + nodeId = if (kind == RecoveryTxKind.SWEEP) null else "node-$txid", + txid = txid, + txHex = "02$txid", + cpfpTxHex = cpfp, + csvTimelockBlocks = csv, + dependsOn = dependsOn, + status = status, + ) + + fun recovery( + transactions: List, + failed: List = emptyList(), + ) = RecoverFundsResponse( + recoverableValueSats = 100_000uL, + totalFeeSats = 9_000uL, + cooperativeFeeSats = 0uL, + cpfpFeeSats = 7_000uL, + fanoutFeeSats = 500uL, + refundFeeSats = 1_000uL, + sweepFeeSats = 500uL, + leaves = listOf(RecoverFundsLeaf("leaf-1", 100_000uL, RecoveryMethod.UNILATERAL)), + failed = failed, + transactions = transactions, + fundingInputs = listOf(CpfpInput.P2wpkh("f0", 1u, 20_000uL, "02ab")), + feeRateSatPerVbyte = 2uL, + destination = "bcrt1qdestination", + ) + + fun prepared( + funding: ULong? = 20_000uL, + leaves: List = listOf("leaf-1"), + skipped: List = listOf(SkippedLeaf("dust", 300uL, SkippedLeafReason.FeeExceedsValue)), + totalFeeSats: ULong = 9_000uL, + ) = PrepareRecoverFundsResponse( + leaves = leaves.map { RecoverFundsLeaf(it, 100_000uL, RecoveryMethod.UNILATERAL) }, + skipped = skipped, + recoverableValueSats = 100_000uL, + totalFeeSats = totalFeeSats, + cooperativeFeeSats = 0uL, + cpfpFeeSats = 7_000uL, + fanoutFeeSats = 500uL, + refundFeeSats = 1_000uL, + sweepFeeSats = 500uL, + funding = funding?.let { RecoveryFunding(it, emptyList()) }, + feeRateSatPerVbyte = 2uL, + destination = "bcrt1qdestination", + exitChainState = ExitChainState(emptyList(), emptyList(), emptyList(), emptyList(), emptyList()), + ) + + fun record(phase: SparkExitRecord.Phase = SparkExitRecord.Phase.AwaitingFunding(20_000uL)) = SparkExitRecord( + network = "regtest", + createdAt = 1_700_000_000_000L, + phase = phase, + feeRateSatPerVbyte = 2uL, + destination = "bcrt1qdestination", + leafIds = listOf("leaf-1"), + funding = listOf(SparkExitRecord.Funding(index = 0u, address = FUNDING_ADDRESS, pubkey = "02ab")), + transferId = "transfer-1", + expectedSats = 111_000uL, + ) + + /** + * A version 3 transaction spending output 0 of [parent] with [csv] blocks of relative timelock in its nSequence, + * as a refund spends its node. + */ + fun csvTxHex(parent: String, csv: Int): String { + fun le32(value: Long) = (0 until 4).joinToString("") { "%02x".format((value shr (8 * it)) and 0xff) } + val prevout = parent.chunked(2).reversed().joinToString("") + return "03000000" + "01" + prevout + le32(0) + "00" + le32(csv.toLong()) + + "01" + "e803000000000000" + "00" + le32(0) + } + + fun utxo(txid: String, vout: UInt = 0u, value: ULong, confirmed: Boolean = true) = + EsploraUtxo(txid, vout, value, EsploraTxStatus(confirmed, if (confirmed) 100u else null)) +} + +class FakeSparkExitChain : SparkExitChain { + var tip = 1_000u + val utxosByAddress = mutableMapOf>() + var utxosError: Throwable? = null + var confirmedTxids = setOf() + + /** Block heights of confirmed transactions; 900 for any other. */ + val heights = mutableMapOf() + var outcome: SparkExitBroadcastOutcome = SparkExitBroadcastOutcome.Accepted + val broadcasts = mutableListOf() + var onBroadcast: () -> Unit = {} + + override suspend fun tipHeight() = tip + + override suspend fun utxos(address: String): List { + utxosError?.let { throw it } + return utxosByAddress[address].orEmpty() + } + + override suspend fun txStatus(txid: String) = + EsploraTxStatus(txid in confirmedTxids, if (txid in confirmedTxids) heights[txid] ?: 900u else null) + + override suspend fun broadcast(tx: RecoveryTransaction): SparkExitBroadcastOutcome { + onBroadcast() + broadcasts += tx + return outcome + } + + override suspend fun broadcastHex(hex: String): SparkExitBroadcastOutcome { + rawBroadcasts += hex + return outcome + } + + val rawBroadcasts = mutableListOf() +} + +class FakeSparkExitRecovering : SparkExitRecovering { + var preparedResponse = SparkExitFixtures.prepared() + val builds = ArrayDeque() + val checks = ArrayDeque() + var recoverError: Throwable? = null + val prepareRequests = mutableListOf() + val recoverRequests = mutableListOf() + val checkedRecoveries = mutableListOf() + + /** Errors the next prepares throw, in order, before [preparedResponse] is returned. */ + val prepareErrors = ArrayDeque() + + override suspend fun prepare(request: PrepareRecoverFundsRequest): PrepareRecoverFundsResponse { + prepareRequests += request + prepareErrors.removeFirstOrNull()?.let { throw it } + return preparedResponse + } + + override suspend fun recover(request: RecoverFundsRequest, signer: CpfpSigner?): RecoverFundsResponse { + recoverRequests += request + recoverError?.let { throw it } + return builds.removeFirst() + } + + override suspend fun check(recovery: RecoverFundsResponse): CheckRecoverFundsResponse { + checkedRecoveries += recovery + return checks.removeFirst() + } +} + +/** Finalizes every input of a PSBT with [witness], as the SDK's single-key signer does with its signature. */ +class StubCpfpSigner(private val witness: String = P2WPKH_WITNESS) : CpfpSigner { + companion object { + /** A P2WPKH witness: two items, a 72-byte signature with its sighash flag and a 33-byte key. */ + val P2WPKH_WITNESS = "02" + "48" + "30".repeat(71) + "01" + "21" + "02".repeat(33) + } + + override suspend fun signPsbt(psbtBytes: ByteArray): ByteArray { + var offset = 5 + fun readCompactSize(): Int { + val prefix = psbtBytes[offset++].toInt() and 0xff + if (prefix < 0xfd) return prefix + check(prefix == 0xfd) + return (psbtBytes[offset++].toInt() and 0xff) or ((psbtBytes[offset++].toInt() and 0xff) shl 8) + } + var unsignedTx = ByteArray(0) + fun copyMap(extra: ByteArray): ByteArray { + val start = offset + while (true) { + val keyLength = readCompactSize() + if (keyLength == 0) return psbtBytes.copyOfRange(start, offset - 1) + extra + byteArrayOf(0x00) + val key = psbtBytes[offset] + offset += keyLength + val valueLength = readCompactSize() + if (start == 5 && key == 0x00.toByte()) unsignedTx = psbtBytes.copyOfRange(offset, offset + valueLength) + offset += valueLength + } + } + val witnessBytes = witness.hexToByteArray() + val finalWitness = byteArrayOf(0x01, 0x08, witnessBytes.size.toByte()) + witnessBytes + var signed = psbtBytes.copyOfRange(0, 5) + copyMap(ByteArray(0)) + repeat(unsignedTx[4].toInt()) { signed += copyMap(finalWitness) } + return signed + psbtBytes.copyOfRange(offset, psbtBytes.size) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt new file mode 100644 index 0000000000..707be6239b --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -0,0 +1,312 @@ +package to.bitkit.repositories + +import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.RecoveryTxKind +import org.junit.Test +import org.lightningdevkit.ldknode.Network +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes +import kotlin.time.Duration.Companion.seconds + +class SparkExitFundingTest { + @Test + fun `quote splits what arrives from what it costs`() { + val quote = SparkExitQuote(SparkExitFixtures.prepared(funding = 20_000uL)) + + assertEquals(100_000uL, quote.exitSats) + assertEquals(9_000uL, quote.networkFeeSats) + assertEquals(91_000uL, quote.receiveSats) + assertEquals(20_000uL, quote.fundingSats) + assertEquals(111_000uL, quote.incomingSats) + assertEquals(300uL, quote.leftBehindSats) + assertEquals(listOf("leaf-1"), quote.leafIds) + assertTrue(quote.isWorthExiting) + } + + @Test + fun `quote is not worth exiting when fees reach the value or nothing is left`() { + val expensive = SparkExitQuote(SparkExitFixtures.prepared(totalFeeSats = 100_000uL)) + + assertFalse(expensive.isWorthExiting) + assertEquals(0uL, expensive.receiveSats) + assertFalse(SparkExitQuote(SparkExitFixtures.prepared(leaves = emptyList())).isWorthExiting) + } + + @Test + fun `cooperative only quote needs no funding`() { + assertEquals(0uL, SparkExitQuote(SparkExitFixtures.prepared(funding = null)).fundingSats) + } + + @Test + fun `shortfall counts what the funding address already holds`() { + val record = SparkExitFixtures.record(SparkExitRecord.Phase.NeedsFunding(23_000uL)).copy( + funding = listOf( + SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 20_000uL) + ), + ) + + assertEquals(20_000uL, record.fundedSats) + assertEquals(3_000uL, record.fundingShortfallSats) + assertNull(record.copy(phase = SparkExitRecord.Phase.NeedsFunding(20_000uL)).fundingShortfallSats) + assertNull(record.copy(phase = SparkExitRecord.Phase.Running).fundingShortfallSats) + } + + @Test + fun `needed funding counts what the funding address still holds`() { + // The headless regtest run: 9,035 held, the SDK wants 9,085 in all. + assertEquals(9_085uL, SparkExitMath.neededFunding(9_085uL, fundedSats = 9_035uL, held = 9_035uL)) + // A Redo: a 20,000 input lives on as 13,000 of change, and the rebuild needs 15,000. + assertEquals(22_000uL, SparkExitMath.neededFunding(15_000uL, fundedSats = 20_000uL, held = 13_000uL)) + assertEquals(20_001uL, SparkExitMath.neededFunding(12_000uL, fundedSats = 20_000uL, held = 13_000uL)) + assertEquals(20_000uL, SparkExitMath.neededFunding(15_000uL, fundedSats = 20_000uL, held = null)) + } + + @Test + fun `spark's balance beyond the exit's leaves is outside the exit`() { + assertEquals(17_097uL, SparkExitMath.outsideExitSats(leafTotalSats = 32_768uL, balanceSats = 49_865uL)) + assertNull(SparkExitMath.outsideExitSats(leafTotalSats = 90_112uL, balanceSats = 9_789uL)) + assertNull(SparkExitMath.outsideExitSats(leafTotalSats = null, balanceSats = 9_789uL)) + } + + @Test + fun `claimable height is the latest timelock`() { + val recovery = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("a", status = ExitTransactionStatus.WaitingForTimelock(2_000u)), + SparkExitFixtures.tx("b", status = ExitTransactionStatus.WaitingForTimelock(2_400u)), + SparkExitFixtures.tx("c", status = ExitTransactionStatus.Confirmed(5u)), + ), + ) + + assertEquals(2_400u, SparkExitMath.claimableAtHeight(recovery)) + assertEquals(1, SparkExitMath.confirmedCount(recovery)) + assertNull(SparkExitMath.claimableAtHeight(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("d"))))) + } + + @Test + fun `timelocks are matured only once no refund waits`() { + val waiting = SparkExitFixtures.tx( + "r1", + kind = RecoveryTxKind.REFUND, + status = ExitTransactionStatus.WaitingForDependencies, + ) + val ready = waiting.copy(status = ExitTransactionStatus.Ready) + val timelocked = waiting.copy(status = ExitTransactionStatus.WaitingForTimelock(2_000u)) + + assertFalse(SparkExitMath.areTimelocksMatured(listOf(SparkExitFixtures.tx("n1"), waiting))) + assertFalse(SparkExitMath.areTimelocksMatured(listOf(timelocked))) + assertFalse(SparkExitMath.areTimelocksMatured(listOf(SparkExitFixtures.tx("n1")))) + assertTrue(SparkExitMath.areTimelocksMatured(listOf(ready))) + } + + @Test + fun `reminder targets the next timelock to mature`() { + val recovery = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("a", status = ExitTransactionStatus.WaitingForTimelock(900u)), + SparkExitFixtures.tx("b", status = ExitTransactionStatus.WaitingForTimelock(2_400u)), + SparkExitFixtures.tx("c", status = ExitTransactionStatus.WaitingForTimelock(2_000u)), + ), + ) + + assertEquals(2_000u, SparkExitMath.nextMaturityHeight(recovery, tip = 1_000u)) + assertNull(SparkExitMath.nextMaturityHeight(recovery, tip = 2_400u)) + } + + @Test + fun `funding utxos are the confirmed ones once together they cover the amount`() { + val utxos = listOf( + SparkExitFixtures.utxo("small", value = 999uL), + SparkExitFixtures.utxo("pending", value = 50_000uL, confirmed = false), + SparkExitFixtures.utxo("big", value = 2_000uL), + ) + + assertEquals(listOf("big", "small"), SparkExitMath.fundingTopUp(utxos, requiredSats = 2_999uL)?.map { it.txid }) + assertNull(SparkExitMath.fundingTopUp(utxos, requiredSats = 3_000uL)) + assertNull(SparkExitMath.fundingTopUp(emptyList(), requiredSats = 0uL)) + } + + @Test + fun `savings must cover the funding and its fee`() { + assertTrue(SparkExitMath.canFundFromSavings(10_500uL, 10_000uL, 500uL)) + assertFalse(SparkExitMath.canFundFromSavings(10_499uL, 10_000uL, 500uL)) + assertFalse(SparkExitMath.canFundFromSavings(10_000uL, 0uL, 0uL)) + } + + @Test + fun `eta uses the network's block time`() { + assertEquals(100.minutes, SparkExitMath.timeUntil(110u, 100u, Network.BITCOIN)) + assertEquals(5.minutes, SparkExitMath.timeUntil(110u, 100u, Network.REGTEST)) + assertEquals(Duration.ZERO, SparkExitMath.timeUntil(90u, 100u, Network.BITCOIN)) + } + + @Test + fun `deadline warns 12 blocks into the operators' window of the next step`() { + val mainnet = SparkExitMath.deadline(2.hours, Network.BITCOIN) + assertEquals(SparkExitDeadline(warnIn = 4.hours, deadlineIn = 10.hours + 20.minutes), mainnet) + val regtest = SparkExitMath.deadline(Duration.ZERO, Network.REGTEST) + assertEquals(SparkExitDeadline(warnIn = 6.minutes, deadlineIn = 25.minutes), regtest) + } + + @Test + fun `deadline warns under half of the smaller of the 50- and 100-block windows on every network`() { + listOf(Network.BITCOIN to 10.minutes, Network.REGTEST to 30.seconds).forEach { (network, block) -> + val maturity = 3.hours + val deadline = SparkExitMath.deadline(maturity, network) + assertTrue(deadline.warnIn - maturity < block * minOf(50, 100) / 2, "$network warns too late") + assertEquals(block * 50, deadline.deadlineIn - maturity) + } + } + + @Test + fun `a step that can be published now puts the deadline in the current window`() { + val far = SparkExitFixtures.tx("far", status = ExitTransactionStatus.WaitingForTimelock(1_100u)) + val waiting = SparkExitFixtures.recovery(listOf(far)) + assertEquals(100.minutes * 10, SparkExitMath.untilNextMaturity(waiting, tip = 1_000u, Network.BITCOIN)) + + val ready = SparkExitFixtures.recovery(listOf(far, SparkExitFixtures.tx("n1"))) + assertEquals(Duration.ZERO, SparkExitMath.untilNextMaturity(ready, tip = 1_000u, Network.BITCOIN)) + + val matured = SparkExitFixtures.tx("r1", status = ExitTransactionStatus.WaitingForTimelock(990u)) + val behindTip = SparkExitFixtures.recovery(listOf(far, matured)) + assertEquals(Duration.ZERO, SparkExitMath.untilNextMaturity(behindTip, tip = 1_000u, Network.BITCOIN)) + + val blocked = SparkExitFixtures.tx("n2", dependsOn = listOf("n1")) + val waitingForParent = SparkExitFixtures.recovery(listOf(far, blocked)) + assertEquals(100.minutes * 10, SparkExitMath.untilNextMaturity(waitingForParent, tip = 1_000u, Network.BITCOIN)) + } + + @Test + fun `funding key derives on its own account`() { + assertEquals("m/84'/1'/7797'/0/0", SparkExitFundingKey.path(0, Network.REGTEST)) + assertEquals("m/84'/0'/7797'/0/3", SparkExitFundingKey.path(3, Network.BITCOIN)) + } + + @Test + fun `decodes a compressed wif`() { + val key = SparkExitFundingKey.secretKey("KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn") + + assertContentEquals(ByteArray(31) + byteArrayOf(1), key) + } + + @Test + fun `rejects a wif with a bad checksum or an uncompressed key`() { + assertFailsWith { + SparkExitFundingKey.secretKey("KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWo") + } + assertFailsWith { + SparkExitFundingKey.secretKey("5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf") + } + assertFailsWith { SparkExitFundingKey.secretKey("0OIl") } + } + + @Test + fun `cpfp child txids ignore witness data`() { + val segwit = "0200000000010111111111111111111111111111111111111111111111111111111111111111110000000000" + + "ffffffff01e80300000000000016001422222222222222222222222222222222222222220202abcd0301020300000000" + val recovery = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("a", cpfp = SparkExitFixtures.PARENT_HEX), + SparkExitFixtures.tx("b", cpfp = segwit), + SparkExitFixtures.tx("c", cpfp = "02zz"), + SparkExitFixtures.tx("d"), + ), + ) + + assertEquals( + listOf(SparkExitFixtures.PARENT_TXID, SparkExitFixtures.PARENT_TXID), + SparkExitTxids.cpfpChildTxids(recovery), + ) + } + + @Test + fun `progress waits for a payment from savings and asks only for what is still missing`() { + val record = SparkExitFixtures.record().copy(fundingPaymentTxid = "paid") + val paidPending = listOf(SparkExitFixtures.utxo("paid", value = 20_000uL, confirmed = false)) + assertEquals(SparkExitFundingState.Paid("paid"), SparkExitMath.fundingState(record, paidPending)) + assertEquals(SparkExitFundingState.Paid("paid"), SparkExitMath.fundingState(record, utxos = null)) + // Confirmed but short: only the rest is asked for. + val paidShort = listOf(SparkExitFixtures.utxo("paid", value = 15_000uL)) + assertEquals( + SparkExitFundingState.Ask(5_000uL, 15_000uL, 20_000uL), + SparkExitMath.fundingState(record, paidShort) + ) + // Once adopted, a later shortfall no longer reads as paid. + val topUp = record.copy( + phase = SparkExitRecord.Phase.NeedsFunding(30_000uL), + funding = listOf(record.funding.single().copy(txid = "paid", vout = 0u, valueSats = 20_000uL)), + ) + assertEquals(SparkExitFundingState.Ask(10_000uL), SparkExitMath.fundingState(topUp, emptyList())) + } + + @Test + fun `progress waits for an external payment seen in the mempool`() { + val record = SparkExitFixtures.record() + val seen = listOf(SparkExitFixtures.utxo("ext", value = 20_000uL, confirmed = false)) + assertEquals(SparkExitFundingState.Seen("ext"), SparkExitMath.fundingState(record, seen)) + val partial = listOf(SparkExitFixtures.utxo("ext", value = 8_000uL, confirmed = false)) + assertEquals( + SparkExitFundingState.Ask(12_000uL, 8_000uL, 20_000uL), + SparkExitMath.fundingState(record, partial) + ) + assertNull(SparkExitMath.fundingState(record.copy(phase = SparkExitRecord.Phase.Running), seen)) + } + + @Test + fun `quote names what it skips and spark's balance beyond every leaf it lists`() { + val prepared = SparkExitFixtures.prepared() + val beyond = SparkExitQuote(prepared, sparkBalanceSats = 150_000uL) + assertEquals(50_000uL, beyond.unexitableSats) + assertEquals(49_700uL, beyond.beyondLeavesSats) + assertEquals(300uL, SparkExitQuote(prepared, sparkBalanceSats = 100_300uL).unexitableSats) + assertEquals(300uL, SparkExitQuote(prepared).unexitableSats) + assertNull(SparkExitQuote(SparkExitFixtures.prepared(skipped = emptyList())).unexitableSats) + } + + @Test + fun `each exit takes a funding key index no earlier exit used`() { + assertEquals(0u, SparkExitMath.nextFundingIndex(kept = null, stored = null)) + val old = SparkExitFixtures.record(SparkExitRecord.Phase.Done) + assertEquals(1u, SparkExitMath.nextFundingIndex(kept = null, stored = old)) + assertEquals(4u, SparkExitMath.nextFundingIndex(kept = 4, stored = old)) + val later = old.copy(funding = old.funding.map { it.copy(index = 6u) }) + assertEquals(7u, SparkExitMath.nextFundingIndex(kept = 4, stored = later)) + } + + @Test + fun `a partial payment shows what arrived and what is still due`() { + val partial = SparkExitPartialFunding(8_000uL, 20_000uL, 12_000uL) + assertEquals(partial, SparkExitMath.partialFunding(8_000uL, 20_000uL)) + assertNull(SparkExitMath.partialFunding(0uL, 20_000uL)) + assertNull(SparkExitMath.partialFunding(20_000uL, 20_000uL)) + + // On Progress the top-up counts only new funding, unconfirmed included, against the shortfall. + val record = SparkExitFixtures.record() + val seen = listOf(SparkExitFixtures.utxo("ext", value = 8_000uL, confirmed = false)) + val ask = assertIs(SparkExitMath.fundingState(record, seen)) + assertEquals(partial, ask.partial) + assertNull(SparkExitFundingState.Ask(20_000uL).partial) + } + + @Test + fun `a top up under dust is asked as the funding output's dust limit`() { + val record = SparkExitFixtures.record() + val almost = listOf(SparkExitFixtures.utxo("ext", value = 19_932uL)) + val ask = SparkExitFundingState.Ask(294uL, 19_932uL, 20_000uL) + assertEquals(ask, SparkExitMath.fundingState(record, almost)) + // The hint names the shortfall as it is and asks for dust at least. + assertEquals(SparkExitPartialFunding(19_932uL, 20_000uL, 294uL), ask.partial) + assertEquals( + SparkExitPartialFunding(19_932uL, 20_000uL, 294uL), + SparkExitMath.partialFunding(19_932uL, 20_000uL) + ) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt new file mode 100644 index 0000000000..96e4df4980 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -0,0 +1,248 @@ +package to.bitkit.repositories + +import breez_sdk_spark.CooperativeRecoveryError +import breez_sdk_spark.CooperativeRecoveryFailure +import breez_sdk_spark.CpfpInput +import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.RecoveryTxKind +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class SparkExitRecordTest { + @get:Rule + val tempFolder = TemporaryFolder() + + @Test + fun `record round trips with every phase and status`() { + val recovery = SparkExitFixtures.recovery( + transactions = listOf( + SparkExitFixtures.tx( + "fan", + kind = RecoveryTxKind.FAN_OUT, + status = ExitTransactionStatus.Confirmed(120u) + ), + SparkExitFixtures.tx("node", cpfp = "03cpfp", dependsOn = listOf("fan")), + SparkExitFixtures.tx( + "refund", + kind = RecoveryTxKind.REFUND, + cpfp = "03cpfp2", + dependsOn = listOf("node"), + status = ExitTransactionStatus.WaitingForTimelock(2_100u), + csv = 2_000u, + ), + SparkExitFixtures.tx( + "wait", + dependsOn = listOf("node"), + status = ExitTransactionStatus.WaitingForDependencies + ), + SparkExitFixtures.tx("unknown", status = ExitTransactionStatus.Unverified), + SparkExitFixtures.tx( + "sweep", + kind = RecoveryTxKind.SWEEP, + dependsOn = listOf("refund"), + status = ExitTransactionStatus.Confirmed(null), + ), + ), + failed = listOf( + CooperativeRecoveryFailure("a", "o1", 0u, CooperativeRecoveryError.ReplacementFeeTooLow(5uL, 6uL)), + CooperativeRecoveryFailure("b", "o2", 1u, CooperativeRecoveryError.OperatorsUnavailable("down")), + CooperativeRecoveryFailure("c", "o3", 2u, CooperativeRecoveryError.Generic("boom")), + ), + ) + val adopted = SparkExitFixtures.record(SparkExitRecord.Phase.Running).adopt(recovery, 1_700_000_050_000L) + val phases = listOf( + SparkExitRecord.Phase.AwaitingFunding(20_000uL), + SparkExitRecord.Phase.Running, + SparkExitRecord.Phase.NeedsFunding(4_321uL), + SparkExitRecord.Phase.Done, + SparkExitRecord.Phase.Failed("Nothing left to recover"), + ) + + phases.forEach { phase -> + val record = adopted.copy( + phase = phase, + broadcastLog = listOf( + SparkExitRecord.BroadcastAttempt(1, "node", 2, 1, 1_700_000_100_000L, "accepted", true), + SparkExitRecord.BroadcastAttempt( + 1, + "refund", + 1, + 0, + 1L, + "inputs missing", + false, + isInputSpent = true + ), + ), + claimableAtHeight = 2_100u, + leftover = listOf(SparkExitRecord.Leftover("change", 3u, 700uL)), + isRebuilding = true, + leafTotalSats = 90_112uL, + earlierCpfpTxids = listOf("child"), + leftoverSweep = SparkExitRecord.LeftoverSweep("sweep", "02sweep", 5_035uL, true, isConfirmed = true), + fundingPaymentTxid = "paid", + spentStepStrikes = mapOf("refund" to 1), + lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 16_384uL)), + leftBehindLeaves = listOf(SparkExitRecord.LeftBehindLeaf("leaf-2", 8_192uL, "its refund cannot pay")), + ) + + assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) + } + } + + @Test + fun `recovery uses the spark-sdk serde shape`() { + val recovery = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("a", cpfp = "03c", status = ExitTransactionStatus.Confirmed(7u)), + SparkExitFixtures.tx("b", kind = RecoveryTxKind.FAN_OUT), + SparkExitFixtures.tx("c", status = ExitTransactionStatus.WaitingForTimelock(null)), + ), + ) + + val json = Json.parseToJsonElement(SparkExitJson.encodeRecovery(recovery)).jsonObject + + assertEquals(2, json.getValue("fee_rate_sat_per_vbyte").jsonPrimitive.int) + val transactions = json.getValue("transactions").jsonArray.map { it.jsonObject } + assertEquals("Node", transactions[0].getValue("kind").jsonPrimitive.content) + assertEquals("03c", transactions[0].getValue("cpfp_tx_hex").jsonPrimitive.content) + val confirmed = transactions[0].getValue("status").jsonObject.getValue("Confirmed").jsonObject + assertEquals(7, confirmed.getValue("block_height").jsonPrimitive.int) + assertEquals("FanOut", transactions[1].getValue("kind").jsonPrimitive.content) + assertEquals(JsonPrimitive("Ready"), transactions[1].getValue("status")) + assertEquals(JsonNull, transactions[1].getValue("cpfp_tx_hex")) + val timelock = transactions[2].getValue("status").jsonObject.getValue("WaitingForTimelock") as JsonObject + assertEquals(JsonNull, timelock.getValue("spendable_at_height")) + val input = json.getValue("funding_inputs").jsonArray[0].jsonObject.getValue("P2wpkh").jsonObject + assertEquals(20_000, input.getValue("value_sats").jsonPrimitive.int) + } + + /** A recovery as the Breez CLI's `recover-funds --output-file` writes it (serde_json, spark-sdk 0.27.2). */ + @Test + fun `reads a recovery written by spark-sdk`() { + val json = """ + {"recoverable_value_sats":90112,"total_fee_sats":8832,"cooperative_fee_sats":0,"cpfp_fee_sats":8388, + "fanout_fee_sats":0,"refund_fee_sats":0,"sweep_fee_sats":444, + "leaves":[{"leaf_id":"l1","value_sats":90112,"method":"Unilateral"}], + "failed":[{"leaf_id":"l2","output_txid":"t","output_vout":3,"error":{"OperatorsUnavailable":{"message":"timeout"}}}], + "transactions":[ + {"kind":"Node","node_id":"n1","txid":"aa","tx_hex":"02aa","cpfp_tx_hex":"03bb","csv_timelock_blocks":null, + "depends_on":[],"status":"Ready"}, + {"kind":"Refund","node_id":"l1","txid":"cc","tx_hex":"02cc","cpfp_tx_hex":"03dd","csv_timelock_blocks":2000, + "depends_on":["aa"],"status":{"WaitingForTimelock":{"spendable_at_height":3100}}}, + {"kind":"Sweep","node_id":null,"txid":"ee","tx_hex":"02ee","cpfp_tx_hex":null,"csv_timelock_blocks":null, + "depends_on":["cc"],"status":"WaitingForDependencies"}], + "funding_inputs":[{"P2wpkh":{"txid":"ff","vout":0,"value_sats":10000,"pubkey":"02cd"}}], + "fee_rate_sat_per_vbyte":1,"destination":"bc1qexample"} + """.trimIndent() + + val recovery = SparkExitJson.decodeRecovery(json) + + assertEquals( + listOf(RecoveryTxKind.NODE, RecoveryTxKind.REFUND, RecoveryTxKind.SWEEP), + recovery.transactions.map { it.kind } + ) + assertEquals(ExitTransactionStatus.WaitingForTimelock(3_100u), recovery.transactions[1].status) + assertEquals(2_000u, recovery.transactions[1].csvTimelockBlocks) + assertNull(recovery.transactions[2].nodeId) + assertEquals(CooperativeRecoveryError.OperatorsUnavailable("timeout"), recovery.failed[0].error) + assertEquals(listOf(CpfpInput.P2wpkh("ff", 0u, 10_000uL, "02cd")), recovery.fundingInputs) + } + + /** A record as Bitkit iOS writes it: Swift's synthesized Codable, a fractional millisecond date. */ + @Test + fun `reads a record written by bitkit ios`() { + val text = requireNotNull(javaClass.classLoader?.getResource("spark-exit-record-ios.json")).readText() + + val record = SparkExitJson.decode(text) + + assertEquals(SparkExitRecord.Phase.Running, record.phase) + assertEquals(1_700_000_000_123L, record.createdAt) + assertEquals(1, record.generation) + assertEquals(listOf(CpfpInput.P2wpkh("f0", 1u, 20_000uL, "02ab")), record.fundingInputs) + assertEquals(3_100u, record.recovery?.let(SparkExitMath::claimableAtHeight)) + assertEquals("transfer-1", record.transferId) + assertNull(record.claimableAtHeight) + assertTrue(record.broadcastLog.single().isAccepted) + // Written before exits had their own funding key index: it signs with index 0. + assertEquals(0u, record.fundingIndex) + assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) + } + + @Test + fun `leaves absent optionals out of the record`() { + val json = Json.parseToJsonElement(SparkExitJson.encode(SparkExitFixtures.record())).jsonObject + + assertFalse("recovery" in json) + assertFalse("claimableAtHeight" in json) + assertFalse("fundingPaymentTxid" in json) + assertFalse("spentStepStrikes" in json) + assertFalse("lostLeaves" in json) + assertEquals( + JsonPrimitive(20_000), + json.getValue("phase").jsonObject.getValue("awaitingFunding").jsonObject["requiredSats"] + ) + assertFalse("txid" in json.getValue("funding").jsonArray[0].jsonObject) + } + + @Test + fun `refuses an unknown record version`() { + val text = SparkExitJson.encode(SparkExitFixtures.record()).replace("\"version\":1", "\"version\":2") + + val error = assertFailsWith { SparkExitJson.decode(text) } + + assertEquals(2, error.version) + } + + @Test + fun `store saves loads and sets an unreadable record aside`() { + val file = File(tempFolder.root, "regtest/wallet0/spark-exit.json") + val store = SparkExitStore(file) + assertNull(store.load()) + assertFalse(store.isActive()) + + store.save(SparkExitFixtures.record()) + + assertEquals(SparkExitFixtures.record(), store.load()) + assertTrue(store.isActive()) + assertFalse(File(file.parentFile, "spark-exit.json.tmp").exists()) + + file.writeText("{") + assertFalse(store.isActive()) + store.setAside(42L) + assertFalse(file.exists()) + assertTrue(File(file.parentFile, "spark-exit.unreadable-42.json").exists()) + } + + @Test + fun `a failed or lossy exit stays reachable until its result was seen`() { + val done = SparkExitFixtures.record(SparkExitRecord.Phase.Done) + assertFalse(done.showsResult) + + val failed = SparkExitFixtures.record(SparkExitRecord.Phase.Failed(SparkExitDriver.LOST_REASON)) + assertTrue(failed.showsResult) + assertFalse(failed.copy(isResultSeen = true).showsResult) + + val partial = done.copy(lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 16_384uL))) + assertTrue(partial.showsResult) + assertFalse(partial.copy(isResultSeen = true).showsResult) + + val seen = failed.copy(isResultSeen = true) + assertEquals(seen, SparkExitJson.decode(SparkExitJson.encode(seen))) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRegtestTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRegtestTest.kt new file mode 100644 index 0000000000..09343ca30a --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRegtestTest.kt @@ -0,0 +1,51 @@ +package to.bitkit.repositories + +import io.ktor.client.HttpClient +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertIs +import kotlin.test.assertTrue + +/** + * Runs the exit's chain client against Spark's hosted regtest mempool. It needs the network, so it only runs with + * `SPARK_EXIT_REGTEST=1` in the environment of `just test file SparkExitRegtestTest`. + */ +class SparkExitRegtestTest : BaseUnitTest() { + private val chain = EsploraSparkExitChain(EsploraSparkExitChain.defaultHosts("regtest"), HttpClient()) + + @Before + fun requireOptIn() { + assumeTrue( + "Set SPARK_EXIT_REGTEST=1 to run against Spark's regtest", + System.getenv("SPARK_EXIT_REGTEST") == "1" + ) + } + + @Test + fun `reads the tip and an unused funding address`() = test { + assertTrue(chain.tipHeight() > 0u) + assertTrue(chain.utxos("bcrt1qzyg3zyg3zyg3zyg3zyg3zyg3zyg3zyg3lgth6c").isEmpty()) + } + + /** + * A parent spending a missing input with its child, as a package: the live node reads the body and answers per + * transaction, which the classifier reads as retry later rather than a rejection. + */ + @Test + fun `live node answers a package the classifier retries`() = test { + val parentId = SparkExitFixtures.PARENT_TXID.chunked(2).reversed().joinToString("") + val child = "0200000001${parentId}0000000000ffffffff01e8030000000000001600142222222222222222222222222222" + + "22222222222200000000" + val tx = SparkExitFixtures.tx( + SparkExitFixtures.PARENT_TXID, + cpfp = child + ).copy(txHex = SparkExitFixtures.PARENT_HEX) + + val outcome = chain.broadcast(tx) + + assertIs(outcome) + assertTrue("missingorspent" in outcome.reason, outcome.reason) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt new file mode 100644 index 0000000000..304164ee64 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -0,0 +1,268 @@ +package to.bitkit.repositories + +import breez_sdk_spark.CheckRecoverFundsResponse +import breez_sdk_spark.RecoveryVerdict +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.client.engine.mock.toByteArray +import io.ktor.client.plugins.defaultRequest +import io.ktor.http.ContentType +import io.ktor.http.HttpMethod +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import io.ktor.utils.io.errors.IOException +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.flowOf +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.atLeastOnce +import org.mockito.kotlin.doAnswer +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.eq +import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.times +import org.mockito.kotlin.verify +import org.mockito.kotlin.whenever +import to.bitkit.data.AppCacheData +import to.bitkit.data.CacheStore +import to.bitkit.data.entities.TransferEntity +import to.bitkit.data.keychain.Keychain +import to.bitkit.env.Env +import to.bitkit.models.TransferType +import to.bitkit.repositories.SparkExitRecord.Phase +import to.bitkit.services.CoreService +import to.bitkit.services.OnchainService +import to.bitkit.services.SparkService +import to.bitkit.test.BaseUnitTest +import java.io.File +import kotlin.test.assertEquals +import kotlin.time.Clock +import kotlin.time.Instant + +class SparkExitRepoTest : BaseUnitTest() { + @get:Rule + val tempFolder = TemporaryFolder() + + private val transferRepo = mock() + private val sparkRepo = mock { + on { walletWiped } doReturn MutableSharedFlow() + on { walletIndex } doReturn 0 + on { state } doReturn MutableStateFlow(SparkState()) + } + private val work = mock() + + @Before + fun setUp() { + Env.initAppStoragePath(tempFolder.root.absolutePath) + } + + private fun createSut( + sparkService: SparkService = mock(), + httpClient: HttpClient = mock(), + keychain: Keychain = mock(), + coreService: CoreService = mock(), + ) = SparkExitRepo( + work = work, + bgDispatcher = testDispatcher, + sparkService = sparkService, + sparkRepo = sparkRepo, + lightningRepo = mock(), + transferRepo = transferRepo, + activityRepo = mock(), + coreService = coreService, + keychain = keychain, + httpClient = httpClient, + clock = object : Clock { + override fun now() = Instant.fromEpochSeconds(1_800_000_000) + }, + sparkExitTip = SparkExitTip(), + cacheStore = mock { on { data } doReturn flowOf(AppCacheData()) }, + ) + + private fun transfer(id: String, type: TransferType = TransferType.SPARK_EXIT) = + TransferEntity(id = id, type = type, amountSats = 111_000L, createdAt = 0L) + + @Test + fun `load settles exit transfers no running exit owns and resumes the running one`() = test { + SparkExitStore(File(Env.sparkExitRecordPath(0))).save(SparkExitFixtures.record()) + whenever(transferRepo.activeTransfers).thenReturn( + flowOf(listOf(transfer("transfer-1"), transfer("orphan"), transfer("close", TransferType.FORCE_CLOSE))), + ) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.markSettled(any())).thenReturn(Result.success(Unit)) + + val record = createSut().load(0).getOrThrow() + + assertEquals("transfer-1", record?.transferId) + verify(transferRepo).markSettled("orphan") + verify(transferRepo, never()).markSettled("transfer-1") + verify(transferRepo, never()).markSettled("close") + verify(work).schedulePeriodic() + } + + @Test + fun `load settles the transfer of an unreadable record it sets aside`() = test { + val file = File(Env.sparkExitRecordPath(0)).apply { + parentFile?.mkdirs() + writeText("{") + } + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.markSettled(any())).thenReturn(Result.success(Unit)) + + val record = createSut().load(0).getOrThrow() + + assertEquals(null, record) + verify(transferRepo).markSettled("transfer-1") + verify(work, never()).schedulePeriodic() + assertEquals(false, file.exists()) + } + + /** Spark's regtest mempool, where nothing is confirmed yet and every single transaction is accepted. */ + private fun regtestMempool(posts: MutableList, refusal: String? = null) = HttpClient( + MockEngine { request -> + val url = request.url.toString() + when { + request.method == HttpMethod.Post && url.endsWith("/api/tx") -> { + posts += String(request.body.toByteArray()) + if (refusal != null) return@MockEngine respond(refusal, HttpStatusCode.BadRequest) + respond(String(request.body.toByteArray()).removePrefix("02")) + } + url.endsWith("/blocks/tip/height") -> respond("1000") + url.endsWith("/status") -> respond("""{"confirmed":false}""") + else -> throw IOException("unreachable '$url'") + } + }, + ) { defaultRequest { contentType(ContentType.Application.Json) } } + + /** Spark in a process the worker woke: not connected until the run starts it, which never touches the node. */ + private suspend fun coldSpark(sdk: FakeSparkExitRecovering, connects: Boolean = true): SparkService { + var isConnected = false + whenever(sparkRepo.start(any())).thenAnswer { + isConnected = connects + Result.success(Unit) + } + return mock { + on { networkName } doReturn "regtest" + on { this.isConnected } doAnswer { isConnected } + on { exitRecovering() } doAnswer { sdk.takeIf { isConnected } } + } + } + + @Test + fun `a background run from a cold start drives the exit and a restart sends nothing twice`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + store.save(SparkExitFixtures.record(Phase.Running).adopt(recovery, 0L)) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) + val posts = mutableListOf() + + // First run: the keyless pass publishes from the stored recovery, then Spark connects and checks it. + val sdk = FakeSparkExitRecovering().apply { + checks += CheckRecoverFundsResponse(recovery, RecoveryVerdict.Valid) + } + createSut(coldSpark(sdk), regtestMempool(posts)).runInBackground().getOrThrow() + + assertEquals(listOf("02n1"), posts) + assertEquals(1, sdk.checkedRecoveries.size) + assertEquals(listOf("n1"), store.load()?.broadcastLog?.filter { it.isAccepted }?.map { it.txid }) + verify(work, atLeastOnce()).schedulePeriodic() + verify(work, atLeastOnce()).armDeadline(any(), any()) + + // The app was killed: a new process runs again within the rebroadcast interval. + val restarted = FakeSparkExitRecovering().apply { + checks += CheckRecoverFundsResponse(recovery, RecoveryVerdict.Valid) + } + createSut(coldSpark(restarted), regtestMempool(posts)).runInBackground().getOrThrow() + + assertEquals(listOf("02n1"), posts) + assertEquals(1, restarted.checkedRecoveries.size) + } + + @Test + fun `a background run whose steps keep being refused lets the deadline alarm fire`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + store.save(SparkExitFixtures.record(Phase.Running).adopt(recovery, 0L)) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) + val posts = mutableListOf() + val refusal = """sendrawtransaction RPC error: {"code":-26,"message":"min relay fee not met"}""" + + repeat(SparkExitDriver.REJECTIONS_TO_SURFACE) { + // The operators are down: Spark does not connect, and the keyless pass publishes alone. + val spark = coldSpark(FakeSparkExitRecovering(), connects = false) + createSut(spark, regtestMempool(posts, refusal)).runInBackground().getOrThrow() + } + + assertEquals(3, posts.size) + assertEquals(3, store.load()?.broadcastLog?.single()?.rejections) + // The first two refusals still count as runs that kept up; the third surfaces and stops pushing the alarm. + verify(work, times(2)).armDeadline(any(), any()) + } + + @Test + fun `a background run of an ended exit with leftover to sweep keeps going without starting spark`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save( + SparkExitFixtures.record(Phase.Done).copy(leftover = listOf(SparkExitRecord.Leftover("f0", 0u, 5_035uL))), + ) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(emptyList())) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(true)) + whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) + val spark = coldSpark(FakeSparkExitRecovering()) + + createSut(spark, regtestMempool(mutableListOf())).runInBackground().getOrThrow() + + verify(sparkRepo, never()).start(any()) + verify(work, atLeastOnce()).schedulePeriodic() + verify(work, never()).cancelAll() + } + + @Test + fun `a restarted exit signs with the funding key of its own record`() = test { + val address = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save( + SparkExitFixtures.record(Phase.Done).copy( + destination = "bcrt1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqc8gma6", + funding = listOf(SparkExitRecord.Funding(2u, address, "02ab")), + leftover = listOf(SparkExitRecord.Leftover("f0".repeat(32), 0u, 5_035uL)), + ), + ) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(emptyList())) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(true)) + val utxo = """[{"txid":"${"f0".repeat(32)}","vout":0,"value":5035,"status":{"confirmed":true}}]""" + val mempool = HttpClient( + MockEngine { request -> + val url = request.url.toString() + when { + url.endsWith("/address/$address/utxo") -> respond(utxo) + url.endsWith("/blocks/tip/height") -> respond("1000") + else -> throw IOException("unreachable '$url'") + } + }, + ) + val keychain = mock { on { loadString(any()) } doReturn "mnemonic" } + val onchain = mock() + whenever(onchain.deriveBitcoinAddress(any(), anyOrNull(), anyOrNull(), anyOrNull())) + .thenThrow(IllegalStateException("stub")) + val coreService = mock { on { this.onchain } doReturn onchain } + val spark = mock { on { networkName } doReturn "regtest" } + + createSut(spark, mempool, keychain, coreService).runInBackground().getOrThrow() + + verify( + onchain + ).deriveBitcoinAddress(any(), eq(SparkExitFundingKey.path(2, Env.network)), anyOrNull(), anyOrNull()) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitSweepTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitSweepTest.kt new file mode 100644 index 0000000000..f77451d55f --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitSweepTest.kt @@ -0,0 +1,90 @@ +package to.bitkit.repositories + +import org.junit.Test +import to.bitkit.test.BaseUnitTest +import to.bitkit.utils.SignedTransactionId +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class SparkExitSweepTest : BaseUnitTest() { + private val funding = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + private val savings = "bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0" + + @Test + fun `segwit addresses become the script they pay`() { + assertEquals( + "0014751e76e8199196d454941c45d1b3a323f1433bd6", + Bech32.scriptPubKey("BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4").toHexString(), + ) + assertEquals( + "512079be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + Bech32.scriptPubKey(savings).toHexString(), + ) + assertFailsWith { Bech32.scriptPubKey("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t5") } + assertEquals( + "76a91477bff20c60e522dfaa3350c39b030a5d004e839a88ac", + AddressScript.of("1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2").toHexString(), + ) + assertEquals( + "a914b472a266d0bd89c13706a4132ccfb16f7c3b9fcb87", + AddressScript.of("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy").toHexString(), + ) + assertFailsWith { AddressScript.of("1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN3") } + } + + @Test + fun `dust limits follow bitcoin core per output type`() { + assertEquals(294uL, SparkExitSweep.dustLimit(AddressScript.of("BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4"))) + assertEquals(330uL, SparkExitSweep.dustLimit(AddressScript.of(savings))) + assertEquals(540uL, SparkExitSweep.dustLimit(AddressScript.of("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy"))) + assertEquals(546uL, SparkExitSweep.dustLimit(AddressScript.of("1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2"))) + } + + @Test + fun `a sweep pays every input less its fee, and none that would leave dust`() { + val inputs = listOf(SparkExitSweep.Input("aa".repeat(32), 1u, 5_035uL)) + + val plan = assertNotNull(SparkExitSweep.plan(inputs, savings, feeRateSatPerVbyte = 2uL)) + + // 11 overhead + 68 for the input + 9 + 34 for the P2TR output, at 2 sat/vB. + assertEquals(244uL, plan.feeSats) + assertEquals(4_791uL, plan.amountSats) + // 500 less 244 of fee is under P2TR's dust limit of 330. + assertNull(SparkExitSweep.plan(listOf(inputs.first().copy(valueSats = 500uL)), savings, 2uL)) + assertNull(SparkExitSweep.plan(emptyList(), savings, 2uL)) + } + + @Test + fun `the signed transaction carries the signer's witness and keeps the unsigned txid`() = test { + val plan = assertNotNull( + SparkExitSweep.plan( + listOf( + SparkExitSweep.Input("11".repeat(32), 0u, 3_000uL), + SparkExitSweep.Input("22".repeat(32), 2u, 2_035uL), + ), + savings, + 1uL, + ), + ) + val psbt = SparkExitSweep.psbt(plan, funding) + val witness = StubCpfpSigner.P2WPKH_WITNESS + + val hex = SparkExitSweep.signedTxHex(plan, StubCpfpSigner().signPsbt(psbt)) + + assertTrue(hex.startsWith("02000000" + "0001" + "02" + "11".repeat(32) + "00000000" + "00" + "fdffffff")) + assertTrue(hex.endsWith(witness + witness + "00000000")) + val unsigned = "02000000" + hex.substring(12, hex.indexOf(witness)) + "00000000" + assertEquals(SignedTransactionId.fromHex(unsigned), SignedTransactionId.fromHex(hex)) + } + + @Test + fun `an input the signer left unsigned is refused`() { + val inputs = listOf(SparkExitSweep.Input("11".repeat(32), 0u, 3_000uL)) + val plan = assertNotNull(SparkExitSweep.plan(inputs, savings, 1uL)) + + assertFailsWith { SparkExitSweep.signedTxHex(plan, SparkExitSweep.psbt(plan, funding)) } + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index dc56da0703..da525bce67 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1,5 +1,6 @@ package to.bitkit.repositories +import breez_sdk_spark.AutoOptimizationEvent import breez_sdk_spark.BitcoinAddressDetails import breez_sdk_spark.Bolt11InvoiceDetails import breez_sdk_spark.ClaimDeferredReason @@ -26,9 +27,13 @@ import breez_sdk_spark.SparkHtlcStatus import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.OnchainActivity import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent import org.junit.Before import org.junit.Rule import org.junit.Test @@ -106,6 +111,10 @@ class SparkRepoTest : BaseUnitTest() { whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.success(Unit)) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.networkName).thenReturn("regtest") + whenever { cacheStore.update(any()) }.thenAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + cacheData.update(transform) + } } @Test @@ -124,6 +133,28 @@ class SparkRepoTest : BaseUnitTest() { assertFalse(File(Env.sparkExitRestorePath(0)).exists()) } + @Test + fun `an exit quote waits for a leaf optimization and the counter-swap of one cut short`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + sut.start(0).getOrThrow() + sparkEvents.emit(SdkEvent.AutoOptimization(AutoOptimizationEvent.Started(3u))) + + val settled = async { sut.settleForExit() } + runCurrent() + verify(sparkService, never()).syncWallet() + + // Cut short: the SDK claims its counter-swap on a sync only after a 300 s grace. + sparkEvents.emit(SdkEvent.AutoOptimization(AutoOptimizationEvent.Cancelled)) + advanceTimeBy(5.minutes) + runCurrent() + verify(sparkService, never()).syncWallet() + + advanceTimeBy(1.minutes) + settled.await().getOrThrow() + verify(sparkService).syncWallet() + } + @Test fun `records a send's fee once a sync reports it`() = test { whenever(sparkService.isConnected).thenReturn(true) diff --git a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt index cb005cedc8..871cf61f7c 100644 --- a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt @@ -63,7 +63,7 @@ class SparkServiceTest { @Test fun `config turns off breez data sync and the lightning address server on every network`() { Network.entries.forEach { network -> - val config = SparkService.configure(defaults(network), apiKey = "key") + val config = SparkService.configure(defaults(network), apiKey = "key", isExiting = false) assertNull(config.realTimeSyncServerUrl, "$network") assertNull(config.lnurlDomain, "$network") diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt index d5e0e15fd1..a594d2f6fe 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModelTest.kt @@ -9,6 +9,7 @@ import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.test.advanceUntilIdle import org.junit.Before import org.junit.Test +import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.R @@ -19,6 +20,8 @@ import to.bitkit.repositories.BlocktankRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState import to.bitkit.repositories.LogsRepo +import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SparkState import to.bitkit.test.BaseUnitTest @@ -79,5 +82,6 @@ class LightningConnectionsViewModelTest : BaseUnitTest() { logsRepo = logsRepo, activityRepo = activityRepo, sparkRepo = sparkRepo, + sparkExitRepo = mock { on { state } doReturn MutableStateFlow(SparkExitState()) }, ) } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt new file mode 100644 index 0000000000..8e4969ac71 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -0,0 +1,63 @@ +package to.bitkit.ui.settings.lightning + +import kotlinx.coroutines.flow.MutableStateFlow +import org.junit.Test +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.mock +import org.mockito.kotlin.whenever +import to.bitkit.repositories.SparkExitFixtures +import to.bitkit.repositories.SparkExitQuote +import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class SparkExitViewModelTest : BaseUnitTest() { + private val repo = mock { on { state } doReturn MutableStateFlow(SparkExitState()) } + + @Test + fun `entering the funding step again offers both choices while nothing was paid`() = test { + whenever(repo.refreshFundingAddress()).thenReturn(Result.success(0uL)) + val sut = SparkExitViewModel(repo) + sut.onFundExternally() + sut.stopWatchingFundingAddress() + + sut.onFundingShown() + + assertFalse(sut.uiState.value.showsFundingAddress) + assertFalse(sut.uiState.value.fundFromSavings) + } + + @Test + fun `entering the funding step keeps the address once a payment reached it`() = test { + whenever(repo.refreshFundingAddress()).thenReturn(Result.success(5_000uL)) + val sut = SparkExitViewModel(repo) + + sut.onFundingShown() + + assertTrue(sut.uiState.value.showsFundingAddress) + sut.stopWatchingFundingAddress() + } + + @Test + fun `funding from another wallet continues only once the address holds what the quote asks`() { + val quote = SparkExitQuote(SparkExitFixtures.prepared(funding = 20_000uL)) + assertFalse(SparkExitUiState().canContinueFunding) + assertFalse(SparkExitUiState(quote = quote, fundingSeenSats = 8_000uL).canContinueFunding) + assertTrue(SparkExitUiState(quote = quote, fundingSeenSats = 20_000uL).canContinueFunding) + } + + @Test + fun `a stopped exit says only what still stays on spark`() { + val nothing = "Nothing could be recovered." + val stays = "{amount} stays on Spark." + + assertEquals(nothing, sparkExitFailedText(nothing, stays, outsideAmount = null)) + assertEquals( + "Nothing could be recovered. ₿ 3 000 stays on Spark.", + sparkExitFailedText(nothing, stays, outsideAmount = "₿ 3 000"), + ) + } +} diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index ac1d2b580f..a19c89a289 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -971,6 +971,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { widgetsRepo = widgetsRepo, pubkyRepo = pubkyRepo, timeSource = testDispatcher.scheduler.timeSource, + sparkExitRepo = mock(), ) private suspend fun emitNodeEvent( diff --git a/app/src/test/resources/spark-exit-record-ios.json b/app/src/test/resources/spark-exit-record-ios.json new file mode 100644 index 0000000000..b349fb2e8d --- /dev/null +++ b/app/src/test/resources/spark-exit-record-ios.json @@ -0,0 +1 @@ +{"broadcastLog":[{"attempts":2,"generation":1,"isAccepted":true,"lastAttemptAt":1700000100000,"lastOutcome":"accepted","rejections":0,"txid":"aa"}],"createdAt":1700000000123.456,"destination":"bcrt1qdestination","expectedSats":111000,"failedLeafCount":0,"feeRateSatPerVbyte":2,"funding":[{"address":"bcrt1qfunding","index":0,"pubkey":"02ab","txid":"f0","valueSats":20000,"vout":1}],"generation":1,"isRebuilding":false,"lastBuildAt":1700000050000,"leafIds":["leaf-1"],"leftover":[],"network":"regtest","phase":{"running":{}},"recovery":{"cooperative_fee_sats":0,"cpfp_fee_sats":7000,"destination":"bcrt1qdestination","failed":[],"fanout_fee_sats":500,"fee_rate_sat_per_vbyte":2,"funding_inputs":[{"P2wpkh":{"pubkey":"02ab","txid":"f0","value_sats":20000,"vout":1}}],"leaves":[{"leaf_id":"leaf-1","method":"Unilateral","value_sats":100000}],"recoverable_value_sats":100000,"refund_fee_sats":1000,"sweep_fee_sats":500,"total_fee_sats":9000,"transactions":[{"cpfp_tx_hex":"03bb","csv_timelock_blocks":null,"depends_on":[],"kind":"Node","node_id":"n1","status":"Ready","tx_hex":"02aa","txid":"aa"},{"cpfp_tx_hex":"03dd","csv_timelock_blocks":2000,"depends_on":["aa"],"kind":"Refund","node_id":"leaf-1","status":{"WaitingForTimelock":{"spendable_at_height":3100}},"tx_hex":"02cc","txid":"cc"}]},"skippedLeafCount":1,"transferId":"transfer-1","version":1} diff --git a/changelog.d/next/1697.added.md b/changelog.d/next/1697.added.md index e1e6a1d79d..9c2f388681 100644 --- a/changelog.d/next/1697.added.md +++ b/changelog.d/next/1697.added.md @@ -1 +1 @@ -Spending keeps Lightning without channels: transfers from Savings now fund a Spark wallet that sends and receives Lightning payments. +Spending keeps Lightning without channels: transfers from Savings now fund a Spark wallet that sends and receives Lightning payments, with an emergency exit that moves its balance on-chain without the Spark operators. diff --git a/docs/screens-map.md b/docs/screens-map.md index b46984af02..58e64ae08b 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -317,6 +317,11 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | CloseConnectionScreen.kt | Settings > Advanced › Close connection | | LightningConnectionsScreen.kt | Settings > Advanced › Lightning Connections overview | | SparkDetailScreen.kt | `todo` | +| SparkExitConfirmScreen.kt | `todo` | +| SparkExitFundingScreen.kt | `todo` | +| SparkExitIntroScreen.kt | `todo` | +| SparkExitProgressScreen.kt | `todo` | +| SparkExitQuoteScreen.kt | `todo` | ## ui/settings/pin diff --git a/journeys/README.md b/journeys/README.md index 93e69007f4..21a47c4612 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -198,6 +198,7 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `backup/confirm-mnemonic-clear-wrong-word.xml` | not ported — `BackupConfirmMnemonic.swift` clears only the last word by its chip, with no red-word tap | | `coin-selection/manual-coin-selection-load.xml` | not ported — iOS has `SendUtxoSelectionView` but no load error, retry or identifiers to assert on | | `transfer/spending-confirm-amount-change.xml` | same file — both platforms show the same "Fees changed" info toast; closing the received sheet re-sizes iOS's Spending Confirm, so the lower amounts can show before the swipe | +| `transfer/spark-emergency-exit.xml` | not ported yet — iOS ships the same screens and identifiers in synonymdev/bitkit-ios#1128, without a journey | | `transfer/savings-select-funds.xml` | same file and steps — iOS runs it as J8 on synonymdev/bitkit-ios#1128 | | — | `hardware-wallet/transfer-to-spending-over-max.xml` exists only on iOS | diff --git a/journeys/transfer/spark-emergency-exit.xml b/journeys/transfer/spark-emergency-exit.xml new file mode 100644 index 0000000000..827922da94 --- /dev/null +++ b/journeys/transfer/spark-emergency-exit.xml @@ -0,0 +1,30 @@ + + + Verifies the Spark emergency exit up to the swipe. With a Spark balance, the Spark connection screen shows + "Emergency exit" (testTag "SparkEmergencyExit") under "Transfer to Savings". It opens the explainer, then the + quote, which asks the SDK's prepareRecoverFunds for every leaf and lists "Amount to exit", "Network fees", + "You receive about" and, when the exit needs CPFP fee funding, "Fee funding needed". Continue leads to the + funding screen, whose "Fund from another wallet" shows the funding address as a QR code. The journey stops before + the swipe: starting an exit takes the Spark balance out of Spending for days. The states after the swipe are + covered by SparkExitDriverTest, SparkExitRepoTest (a background run from a cold start) and the + SparkExitProgressScreen previews, which show the notes on battery and notification settings. + + Precondition: dev build with Spark connected on its regtest (no key needed) and a Spark balance, funded at the + deposit address the Spark connection screen shows (testTag "SparkDepositAddress") from Lightspark's regtest + faucet. Start on the wallet home screen. + + + Tap the menu icon (testTag "HeaderMenu") + Tap Settings (testTag "DrawerSettings") + Tap the Advanced tab (testTag "Tab-advanced") + Tap Lightning Connections (testTag "Channels") + Tap the Spark connection (testTag "SparkConnection") + Scroll down and verify "Transfer to Savings" (testTag "SparkTransferToSavings") is enabled and "Emergency exit" (testTag "SparkEmergencyExit") shows under it + Tap "Emergency exit" and verify the "Leave Spark on-chain" explainer says the exit takes up to 4 weeks, runs in the background and that Bitkit notifies you if it needs you + Tap "Continue" (testTag "SparkExitIntroContinue") and verify the "Exit quote" screen shows "Getting a quote…" and then "Amount to exit", "Network fees" and "You receive about" + Verify no reason shows in red (testTag "SparkExitQuoteBlocked") and "Continue" (testTag "SparkExitQuoteContinue") is enabled + Tap "Continue" and verify the "Fund the fees" screen names the fee funding amount, with "Pay from savings" (testTag "SparkExitFundSavings") and "Fund from another wallet" (testTag "SparkExitFundExternal") + Tap "Fund from another wallet" and verify a QR code and a bcrt1 address (testTag "SparkExitFundingAddress") show, and "Continue" (testTag "SparkExitFundingContinue") is disabled + Go back to the Spark connection screen and verify "Transfer to Savings" is still enabled: nothing started + + From 2ed467377ad530e876051d78bd7767f39bf82183 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 04:12:02 +0100 Subject: [PATCH 002/154] fix: rebuild a spark exit whose fee chain lost a race When another wallet's package confirms a shared tree node, our CPFP child for it is dropped and every later step that spends its change can never confirm, while the SDK check still answers Valid. Detect that child on a Valid check and rebuild from the same funding. As a safety net, a step unpaid or missing inputs 3 times in a row rebuilds once, and those sends count as no rejection until then. --- .../to/bitkit/repositories/SparkExitChain.kt | 33 ++++ .../to/bitkit/repositories/SparkExitDriver.kt | 116 ++++++++++++- .../to/bitkit/repositories/SparkExitRecord.kt | 10 ++ .../bitkit/repositories/SparkExitChainTest.kt | 28 ++++ .../repositories/SparkExitDriverTest.kt | 154 +++++++++++++++++- .../bitkit/repositories/SparkExitFixtures.kt | 17 ++ .../repositories/SparkExitRecordTest.kt | 5 +- 7 files changed, 351 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 4c3d4e4728..55a1678c4d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -65,6 +65,12 @@ interface SparkExitChain { suspend fun tipHeight(): UInt suspend fun utxos(address: String): List suspend fun txStatus(txid: String): EsploraTxStatus + + /** + * Whether a host has [txid] in a block or its mempool, from `/tx/{txid}/hex`: false only when every host answers + * 404. Throws when a host fails otherwise, since that host may know it. + */ + suspend fun isTxKnown(txid: String): Boolean suspend fun broadcast(tx: RecoveryTransaction): SparkExitBroadcastOutcome /** A transaction of the app's own, such as the sweep of leftover fee funding, as a single `/tx`. */ @@ -92,6 +98,8 @@ class EsploraSparkExitChain( } private val NOT_HERE = setOf(404, 405) + + private const val NOT_FOUND = 404 } override suspend fun tipHeight(): UInt = get("/blocks/tip/height").trim().toUInt() @@ -110,6 +118,22 @@ class EsploraSparkExitChain( override suspend fun txStatus(txid: String): EsploraTxStatus = status(json.parseToJsonElement(get("/tx/$txid/status")).jsonObject) + override suspend fun isTxKnown(txid: String): Boolean { + if (hosts.isEmpty()) throw SparkExitChainError("No chain host configured") + val path = "/tx/$txid/hex" + var lastError: Throwable? = null + for (host in hosts) { + val status = runSuspendCatching { client.get("$host$path").status } + .onFailure { lastError = it } + .getOrNull() + ?: continue + if (status.isSuccess()) return true + if (status.value != NOT_FOUND) lastError = SparkExitChainError("HTTP '${status.value}' for '$path'") + } + lastError?.let { throw it } + return false + } + /** Tries each host until one accepts. Otherwise a node's refusal wins over a host that was only unavailable. */ override suspend fun broadcast(tx: RecoveryTransaction): SparkExitBroadcastOutcome { val outcomes = mutableListOf() @@ -262,6 +286,15 @@ object SparkExitBroadcastClassifier { null } + private val unpaid = Regex("""min relay fee not met,\s*0\s*<""") + + /** + * A step refused for paying no fee at all, with no child paying for it: the child's chained change is gone, as + * when an earlier child of the exit lost a race. Read by the driver; a nonzero fee stays a plain rejection. + */ + fun isUnpaid(outcome: SparkExitBroadcastOutcome): Boolean = + outcome is SparkExitBroadcastOutcome.Rejected && unpaid.containsMatchIn(outcome.reason) + fun classify(text: String): SparkExitBroadcastOutcome = when { knownMessages.any { it in text } || hasRpcCode(-27, text) -> SparkExitBroadcastOutcome.Accepted notMatureMessages.any { it in text } -> SparkExitBroadcastOutcome.NotMature(text) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 99193a71eb..1f691b6f11 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -28,8 +28,9 @@ interface SparkExitRecovering { /** * Moves an exit one step forward each tick: builds it once its fee funding confirms, broadcasts what is ready, - * rebuilds when the chain diverged, and finishes when everything confirmed. Without the SDK (a background start, or - * operators down at connect) it still broadcasts the stored, already signed transactions whose parents confirmed. + * rebuilds when the chain diverged or its fee chain lost a race, and finishes when everything confirmed. Without the + * SDK (a background start, or operators down at connect) it still broadcasts the stored, already signed transactions + * whose parents confirmed. * Every built recovery is saved before anything of it is broadcast, and each broadcast as it happens, so a run killed * partway, as background runs can be, never sends the same transactions again before they are due. */ @@ -50,6 +51,9 @@ class SparkExitDriver( /** After this many rejections of one transaction the progress screen shows the error. */ const val REJECTIONS_TO_SURFACE = 3 + /** After this many unpaid sends in a row of a step whose parents confirmed, the exit rebuilds once for it. */ + const val FEE_CHAIN_FAILURES_TO_REBUILD = 3 + /** The least time between two builds, so a divergence that persists does not rebuild every tick. */ val REBUILD_INTERVAL = 10.minutes @@ -221,21 +225,78 @@ class SparkExitDriver( Logger.debug("Checked Spark exit generation '${record.generation}': '${checked.verdict}'", context = TAG) val updated = record.copy(recovery = checked.recovery) return when (checked.verdict) { - RecoveryVerdict.Valid -> broadcastReady(updated) + RecoveryVerdict.Valid -> { + val confirmed = checked.recovery.transactions + .filter { it.status is ExitTransactionStatus.Confirmed } + .map { it.txid } + .toSet() + val dead = deadChildren(stored) { it in confirmed } + if (dead.isNotEmpty()) { + // The SDK still calls it valid, but the steps that spend a dead child's change can never confirm. + Logger.warn("Rebuilding Spark exit whose CPFP children '$dead' lost a race", context = TAG) + return rebuild(updated, sdk) + } + val sent = broadcastReady(updated) + val stuck = stuckStep(sent) ?: return sent + Logger.warn("Rebuilding Spark exit once for step '$stuck' whose fee went unpaid", context = TAG) + rebuild(sent.copy(feeChainRebuildTxids = sent.feeChainRebuildTxids + stuck), sdk) + } RecoveryVerdict.Done -> end(updated.copy(phase = SparkExitRecord.Phase.Done), updated) is RecoveryVerdict.Redo -> { Logger.warn( "Rebuilding Spark exit diverged on-chain as generation '${record.generation + 1}'", context = TAG, ) - val rebuilding = updated.copy(isRebuilding = true) - save(rebuilding) - if (!isRebuildDue(rebuilding)) return rebuilding - build(rebuilding, sdk) + rebuild(updated, sdk) } } } + /** + * Saves the exit as rebuilding, so nothing of this generation goes out again, and rebuilds it once the last build + * is old enough, so a rebuild that reproduces the same problem cannot loop every tick. + */ + private suspend fun rebuild(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { + val rebuilding = record.copy(isRebuilding = true) + save(rebuilding) + if (!isRebuildDue(rebuilding)) return rebuilding + return build(rebuilding, sdk) + } + + /** A step of this generation whose fee went unpaid too many times in a row, and that has not rebuilt yet. */ + private fun stuckStep(record: SparkExitRecord): String? = record.broadcastLog.firstOrNull { + it.generation == record.generation && + it.feeChainFailures >= FEE_CHAIN_FAILURES_TO_REBUILD && + it.txid !in record.feeChainRebuildTxids + }?.txid + + /** + * Our CPFP children that can never confirm, and every child that spends their change. A wallet whose leaves share + * a node with ours broadcast its own package for it and won: the node is in a block, and our child for it is in + * neither a block nor the mempool. Only children whose change a pending step's child spends are looked up; a dead + * child nothing builds on harms nothing, and its funding ends up in the leftover sweep. + */ + private suspend fun deadChildren( + recovery: RecoverFundsResponse, + isConfirmed: (String) -> Boolean, + ): Set { + val children = SparkExitFeeChain.children(recovery) + val spends = SparkExitFeeChain.spends(recovery) + val stepOf = children.entries.associate { (step, child) -> child to step } + val suspects = children + .filterKeys { !isConfirmed(it) } + .values + .flatMap { spends[it].orEmpty() } + .filter { spent -> stepOf[spent]?.let(isConfirmed) == true } + .distinct() + val lost = suspects.filter { isUnknownToChain(it) }.toSet() + return SparkExitFeeChain.withDescendants(spends, lost) + } + + /** Every host answered it does not know [txid]; a host that failed otherwise leaves it alive for this tick. */ + private suspend fun isUnknownToChain(txid: String): Boolean = + runSuspendCatching { !chain.isTxKnown(txid) }.getOrDefault(false) + /** * Marks the next steps the chain host shows in a block as confirmed. The SDK asks the chain about a step only once * the caller saw it in a block; otherwise it looks for who spent its input, which an Electrum-backed mempool, @@ -352,7 +413,8 @@ class SparkExitDriver( /** * Without the SDK: each unconfirmed transaction whose parents are confirmed on the chain host and whose relative * timelock has matured, by the SDK's own rule. A stale one is refused by nodes as a conflict, and only the current - * generation is stored. A step whose input someone else spent is not sent again; the next SDK check rebuilds. + * generation is stored. A step whose input someone else spent is not sent again; the next SDK check rebuilds. A fee + * chain that lost a race is left to that check too, since only the SDK can rebuild it. */ private suspend fun broadcastWithoutSdk(record: SparkExitRecord): SparkExitRecord { val recovery = record.recovery ?: return record @@ -424,9 +486,14 @@ class SparkExitDriver( ): SparkExitRecord { val outcome = chain.broadcast(tx) val isInputSpent = parentsConfirmed && outcome is SparkExitBroadcastOutcome.InputsMissing + val isUnpaid = SparkExitBroadcastClassifier.isUnpaid(outcome) + val isStuck = parentsConfirmed && (isUnpaid || outcome is SparkExitBroadcastOutcome.InputsMissing) Logger.info("Broadcast Spark exit '${tx.kind}' '${tx.txid}': '${outcome.summary}'", context = TAG) val isAccepted = outcome == SparkExitBroadcastOutcome.Accepted - val rejection = if (outcome is SparkExitBroadcastOutcome.Rejected) 1 else 0 + // Unpaid counts as a rejection only once the step had its rebuild, so an underpriced exit still surfaces. + val isRejected = outcome is SparkExitBroadcastOutcome.Rejected && + (!isUnpaid || tx.txid in record.feeChainRebuildTxids) + val rejection = if (isRejected) 1 else 0 val existing = record.broadcastLog.firstOrNull { it.generation == record.generation && it.txid == tx.txid } val entry = existing?.copy( attempts = existing.attempts + 1, @@ -435,6 +502,7 @@ class SparkExitDriver( lastOutcome = outcome.summary, isAccepted = isAccepted, isInputSpent = existing.isInputSpent || isInputSpent, + feeChainFailures = if (isStuck) existing.feeChainFailures + 1 else 0, ) ?: SparkExitRecord.BroadcastAttempt( generation = record.generation, txid = tx.txid, @@ -444,6 +512,7 @@ class SparkExitDriver( lastOutcome = outcome.summary, isAccepted = isAccepted, isInputSpent = isInputSpent, + feeChainFailures = if (isStuck) 1 else 0, ) val log = if (existing == null) { record.broadcastLog + entry @@ -468,6 +537,35 @@ object SparkExitTxids { } } +/** How the exit's CPFP children chain: each spends its node's anchor and the change of the child before it. */ +object SparkExitFeeChain { + /** Each step's CPFP child txid, by the step's txid. */ + fun children(recovery: RecoverFundsResponse): Map = + recovery.transactions.mapNotNull { tx -> + val child = tx.cpfpTxHex?.let { runCatching { SignedTransactionId.fromHex(it) }.getOrNull() } + child?.let { tx.txid to it } + }.toMap() + + /** The txids each CPFP child spends outputs of, by the child's txid. */ + fun spends(recovery: RecoverFundsResponse): Map> = + recovery.transactions.mapNotNull { tx -> + val hex = tx.cpfpTxHex ?: return@mapNotNull null + val child = runCatching { SignedTransactionId.fromHex(hex) }.getOrNull() ?: return@mapNotNull null + val inputs = SparkExitTxInputs.decode(hex) ?: return@mapNotNull null + child to inputs.map { it.prevTxid }.toSet() + }.toMap() + + /** [dead] and every child that spends one of their outputs, directly or through other children. */ + fun withDescendants(spends: Map>, dead: Set): Set { + val all = dead.toMutableSet() + while (true) { + val added = spends.filter { (child, inputs) -> child !in all && inputs.any { it in all } }.keys + if (added.isEmpty()) return all + all += added + } + } +} + /** A leaf the SDK refused to exit, read from its untyped `SparkError`: `Leaf {id} cannot be exited: {reason}`. */ object SparkExitUnexitable { const val NOT_RECOVERABLE = "Not recoverable at this fee rate" diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 541f972963..90e7453329 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -79,6 +79,8 @@ data class SparkExitRecord( val isResultSeen: Boolean = false, /** Leaves a rebuild could not exit, such as a fee-ladder leaf whose refund cannot pay its fee; left on Spark. */ val leftBehindLeaves: List = emptyList(), + /** Steps that already started a rebuild after their fee went unpaid several times in a row; each starts one. */ + val feeChainRebuildTxids: List = emptyList(), ) { companion object { const val CURRENT_VERSION = 1 @@ -135,6 +137,8 @@ data class SparkExitRecord( val isAccepted: Boolean, /** Its parents confirmed but an input was already spent: the keyless pass stops sending it. */ val isInputSpent: Boolean = false, + /** Sends in a row, parents confirmed, that came back unpaid or with missing inputs; other outcomes reset it. */ + val feeChainFailures: Int = 0, ) data class Leftover( @@ -358,6 +362,7 @@ object SparkExitJson { put("lastOutcome", it.lastOutcome) put("isAccepted", it.isAccepted) if (it.isInputSpent) put("isInputSpent", true) + if (it.feeChainFailures > 0) put("feeChainFailures", it.feeChainFailures) }, ) } @@ -409,6 +414,9 @@ object SparkExitJson { buildJsonObject { r.spentStepStrikes.forEach { (txid, strikes) -> put(txid, strikes) } }, ) } + if (r.feeChainRebuildTxids.isNotEmpty()) { + put("feeChainRebuildTxids", buildJsonArray { r.feeChainRebuildTxids.forEach { add(JsonPrimitive(it)) } }) + } if (r.leftBehindLeaves.isNotEmpty()) { put( "leftBehindLeaves", @@ -474,6 +482,7 @@ object SparkExitJson { lastOutcome = b.string("lastOutcome"), isAccepted = b.booleanOrNull("isAccepted") ?: false, isInputSpent = b.booleanOrNull("isInputSpent") ?: false, + feeChainFailures = b.intOrNull("feeChainFailures") ?: 0, ) }, transferId = o.stringOrNull("transferId"), @@ -512,6 +521,7 @@ object SparkExitJson { val l = it.jsonObject SparkExitRecord.LeftBehindLeaf(l.string("leafId"), l.ulong("valueSats"), l.string("reason")) }, + feeChainRebuildTxids = o.arrayOrEmpty("feeChainRebuildTxids").map { it.jsonPrimitive.content }, ) private fun phaseToJson(phase: SparkExitRecord.Phase): JsonObject = when (phase) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt index 0613bb8b56..cc067ff19e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -16,7 +16,10 @@ import io.ktor.utils.io.errors.IOException import org.junit.Test import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertTrue class SparkExitChainTest : BaseUnitTest() { private val hostA = "https://a.example/api" @@ -195,4 +198,29 @@ class SparkExitChainTest : BaseUnitTest() { val lowFee = failedPackage + """{"w1":{"txid":"a","error":"min relay fee not met"}}}""" assertIs(classifier.pkg(200, lowFee)) } + + @Test + fun `only a step that paid no fee at all is unpaid`() { + val classifier = SparkExitBroadcastClassifier + // The qa-03 shared-ancestor race: the node pays nothing, and its child's chained change is gone. + val lostChain = """{"package_msg":"transaction failed","tx-results":""" + + """{"w1":{"txid":"parent","error":"min relay fee not met, 0 < 17"},""" + + """"w2":{"txid":"child","error":"bad-txns-inputs-missingorspent"}}}""" + assertTrue(classifier.isUnpaid(classifier.pkg(200, lostChain, parentTxid = "parent"))) + assertFalse(classifier.isUnpaid(SparkExitBroadcastOutcome.Rejected("min relay fee not met, 100 < 110"))) + assertFalse(classifier.isUnpaid(SparkExitBroadcastOutcome.RetryLater("min relay fee not met, 0 < 17"))) + } + + @Test + fun `a transaction is unknown only when every host says so`() = test { + val unknown = Route("a.example/api/tx/t/hex", 404, "Transaction not found") + assertFalse(chain(unknown).isTxKnown("t")) + + val known = Route("b.example/api/tx/t/hex", 200, "02aa") + assertTrue(chain(unknown, known, hosts = listOf(hostA, hostB)).isTxKnown("t")) + + val down = Route("b.example/api/tx/t/hex", 503, "") + assertFailsWith { chain(unknown, down, hosts = listOf(hostA, hostB)).isTxKnown("t") } + assertFailsWith { chain(hosts = listOf(hostA)).isTxKnown("t") } + } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 93da862114..013e5b254a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -18,6 +18,7 @@ import org.junit.Test import org.junit.rules.TemporaryFolder import to.bitkit.repositories.SparkExitRecord.Phase import to.bitkit.test.BaseUnitTest +import to.bitkit.utils.SignedTransactionId import java.io.File import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -31,6 +32,7 @@ class SparkExitDriverTest : BaseUnitTest() { private companion object { const val SWEEP_DESTINATION = "bcrt1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqc8gma6" const val SWEEP_FUNDING = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + val UNPAID = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 0 < 17") } @get:Rule @@ -167,7 +169,7 @@ class SparkExitDriverTest : BaseUnitTest() { fun `retries a rejected step and surfaces it after repeated rejections`() = test { val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1", cpfp = "03c"))) var record = running(recovery) - chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met") + chain.outcome = SparkExitBroadcastOutcome.Rejected("insufficient fee, rejecting replacement") repeat(3) { sdk.checks += check(recovery, RecoveryVerdict.Valid) } record = driver().tick(record) @@ -175,7 +177,7 @@ class SparkExitDriverTest : BaseUnitTest() { repeat(2) { record = driver().tick(record) } assertEquals(3, chain.broadcasts.size) - assertEquals("rejected: min relay fee not met", record.surfacedRejection) + assertEquals("rejected: insufficient fee, rejecting replacement", record.surfacedRejection) } @Test @@ -830,6 +832,154 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(2, record.generation) } + /** + * The qa-03 shared-ancestor race: our first node's package lost to another wallet's, so the node confirmed with + * their child and ours ([first] spends [FUNDING_TXID]) is gone; the next node's child spends its change. + */ + private object Race { + val NODE_1 = "a1".repeat(32) + val NODE_2 = "a2".repeat(32) + val FUNDING_TXID = "f0".repeat(32) + val first = SparkExitFixtures.childTxHex(NODE_1, FUNDING_TXID) + val firstTxid = SignedTransactionId.fromHex(first) + val second = SparkExitFixtures.childTxHex(NODE_2, firstTxid) + val rebuiltSecond = SparkExitFixtures.childTxHex(NODE_2, FUNDING_TXID) + + fun recovery(node1: ExitTransactionStatus = ExitTransactionStatus.Ready) = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx(NODE_1, cpfp = first, status = node1), + SparkExitFixtures.tx( + NODE_2, + cpfp = second, + dependsOn = listOf(NODE_1), + status = if (node1 is ExitTransactionStatus.Confirmed) { + ExitTransactionStatus.Ready + } else { + ExitTransactionStatus.WaitingForDependencies + }, + ), + ), + ) + + val rebuilt = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx(NODE_1, status = ExitTransactionStatus.Confirmed(11_600u)), + SparkExitFixtures.tx(NODE_2, cpfp = rebuiltSecond, dependsOn = listOf(NODE_1)), + ), + ) + } + + @Test + fun `a fee chain that lost a race to another wallet's package rebuilds without sending its dead txids`() = test { + var record = running(Race.recovery()).copy( + funding = listOf( + SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", Race.FUNDING_TXID, 0u, 20_000uL) + ), + ) + sdk.checks += check(Race.recovery(), RecoveryVerdict.Valid) + sdk.checks += check(Race.recovery(ExitTransactionStatus.Confirmed(11_600u)), RecoveryVerdict.Valid) + sdk.builds += Race.rebuilt + + // Both wallets sent a package for the shared node; ours was refused as a replacement. + chain.outcome = SparkExitBroadcastOutcome.Rejected("insufficient fee, rejecting replacement") + record = driver().tick(record) + // Theirs confirmed the node; our child is in neither a block nor the mempool. + chain.confirmedTxids = setOf(Race.NODE_1) + chain.unknownTxids = setOf(Race.firstTxid) + chain.outcome = SparkExitBroadcastOutcome.Accepted + now += SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds + record = driver().tick(record) + + assertEquals(2, record.generation) + assertEquals(listOf(Race.NODE_1, Race.NODE_2), chain.broadcasts.map { it.txid }) + assertEquals(listOf(Race.first, Race.rebuiltSecond), chain.broadcasts.map { it.cpfpTxHex }) + assertTrue(saved.any { it.isRebuilding && it.generation == 1 }) + assertEquals(record.fundingInputs, sdk.recoverRequests.single().fundingInputs) + assertEquals(listOf("leaf-1"), (sdk.prepareRequests.single().selection as ExitLeafSelection.Specific).leafIds) + assertTrue(record.lostLeaves.isEmpty()) + assertTrue(record.spentStepStrikes.isEmpty()) + assertNull(record.surfacedRejection) + } + + @Test + fun `a dead fee chain waits for the rebuild interval and sends nothing meanwhile`() = test { + val recovery = Race.recovery(ExitTransactionStatus.Confirmed(11_600u)) + var record = running(recovery) + chain.unknownTxids = setOf(Race.firstTxid) + sdk.checks += check(recovery, RecoveryVerdict.Valid) + + record = driver().tick(record) + record = driver().tick(record) + + assertTrue(record.isRebuilding) + assertEquals(1, record.generation) + assertTrue(chain.broadcasts.isEmpty()) + assertTrue(sdk.prepareRequests.isEmpty()) + } + + @Test + fun `a child still in the mempool of a confirmed node is not dead`() = test { + val recovery = Race.recovery(ExitTransactionStatus.Confirmed(11_600u)) + var record = running(recovery) + sdk.checks += check(recovery, RecoveryVerdict.Valid) + + record = driver().tick(record) + + assertEquals(listOf(Race.firstTxid), chain.knownLookups) + assertEquals(1, record.generation) + assertEquals(listOf(Race.NODE_2), chain.broadcasts.map { it.txid }) + } + + private val unpaidRecovery = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(11_600u)), + SparkExitFixtures.tx("n2", cpfp = "03c2", dependsOn = listOf("n1")), + ), + ) + + @Test + fun `a step unpaid three times in a row rebuilds once, then surfaces`() = test { + var record = running(unpaidRecovery, builtAt = now - SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds) + chain.outcome = UNPAID + repeat(5) { sdk.checks += check(unpaidRecovery, RecoveryVerdict.Valid) } + sdk.builds += unpaidRecovery + + repeat(2) { record = driver().tick(record) } + assertEquals(2, record.broadcastLog.single().feeChainFailures) + assertEquals(0, record.broadcastLog.single().rejections) + assertTrue(sdk.prepareRequests.isEmpty()) + record = driver().tick(record) + assertEquals(1, sdk.prepareRequests.size) + assertEquals(2, record.generation) + assertEquals(listOf("n2"), record.feeChainRebuildTxids) + // The rebuild reproduced the same step, which stays unpaid: it never rebuilds again, and now counts. + record = driver().tick(record) + assertNull(record.surfacedRejection) + record = driver().tick(record) + + assertEquals(1, sdk.prepareRequests.size) + assertEquals(2, record.generation) + assertEquals(3, record.broadcastLog.single().rejections) + assertEquals("rejected: min relay fee not met, 0 < 17", record.surfacedRejection) + assertTrue(record.lostLeaves.isEmpty()) + } + + @Test + fun `any other outcome resets the unpaid streak`() = test { + var record = running(unpaidRecovery) + repeat(4) { sdk.checks += check(unpaidRecovery, RecoveryVerdict.Valid) } + + chain.outcome = UNPAID + repeat(2) { record = driver().tick(record) } + chain.outcome = SparkExitBroadcastOutcome.RetryLater("HTTP 503") + record = driver().tick(record) + chain.outcome = UNPAID + record = driver().tick(record) + + assertEquals(1, record.broadcastLog.single().feeChainFailures) + assertTrue(sdk.prepareRequests.isEmpty()) + } + @Test fun `only a spark error saying a leaf cannot be exited is read as one`() { assertNull(SparkExitUnexitable.parse(SdkException.SparkException("connection refused"))) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt index d2883d8a0d..55eaeb9b42 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -109,6 +109,14 @@ object SparkExitFixtures { "01" + "e803000000000000" + "00" + le32(0) } + /** A version 3 CPFP child spending output 0 of each of [spends]: its node's anchor and the change it chains on. */ + fun childTxHex(vararg spends: String): String { + val inputs = spends.joinToString("") { parent -> + parent.chunked(2).reversed().joinToString("") + "00000000" + "00" + "ffffffff" + } + return "03000000" + "%02x".format(spends.size) + inputs + "01" + "e803000000000000" + "00" + "00000000" + } + fun utxo(txid: String, vout: UInt = 0u, value: ULong, confirmed: Boolean = true) = EsploraUtxo(txid, vout, value, EsploraTxStatus(confirmed, if (confirmed) 100u else null)) } @@ -119,6 +127,10 @@ class FakeSparkExitChain : SparkExitChain { var utxosError: Throwable? = null var confirmedTxids = setOf() + /** Txids no host knows: in neither a block nor the mempool. */ + var unknownTxids = setOf() + val knownLookups = mutableListOf() + /** Block heights of confirmed transactions; 900 for any other. */ val heights = mutableMapOf() var outcome: SparkExitBroadcastOutcome = SparkExitBroadcastOutcome.Accepted @@ -135,6 +147,11 @@ class FakeSparkExitChain : SparkExitChain { override suspend fun txStatus(txid: String) = EsploraTxStatus(txid in confirmedTxids, if (txid in confirmedTxids) heights[txid] ?: 900u else null) + override suspend fun isTxKnown(txid: String): Boolean { + knownLookups += txid + return txid !in unknownTxids + } + override suspend fun broadcast(tx: RecoveryTransaction): SparkExitBroadcastOutcome { onBroadcast() broadcasts += tx diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt index 96e4df4980..d7803d814a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -86,7 +86,8 @@ class SparkExitRecordTest { 1L, "inputs missing", false, - isInputSpent = true + isInputSpent = true, + feeChainFailures = 2, ), ), claimableAtHeight = 2_100u, @@ -99,6 +100,7 @@ class SparkExitRecordTest { spentStepStrikes = mapOf("refund" to 1), lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 16_384uL)), leftBehindLeaves = listOf(SparkExitRecord.LeftBehindLeaf("leaf-2", 8_192uL, "its refund cannot pay")), + feeChainRebuildTxids = listOf("refund"), ) assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) @@ -193,6 +195,7 @@ class SparkExitRecordTest { assertFalse("fundingPaymentTxid" in json) assertFalse("spentStepStrikes" in json) assertFalse("lostLeaves" in json) + assertFalse("feeChainRebuildTxids" in json) assertEquals( JsonPrimitive(20_000), json.getValue("phase").jsonObject.getValue("awaitingFunding").jsonObject["requiredSats"] From f541952b5dc652a82239ea42933a1cdc37317b99 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 04:20:11 +0100 Subject: [PATCH 003/154] fix: alarm a spark exit stuck on an unpaid step Unpaid sends no longer count as rejections, so without the SDK a step whose fee chain lost a race never surfaced and every background run looked on track. A step unpaid 3 times in a row now lets the deadline alarm fire. --- .../to/bitkit/repositories/SparkExitDriver.kt | 9 ++++++++ .../to/bitkit/repositories/SparkExitRepo.kt | 2 +- .../bitkit/repositories/SparkExitRepoTest.kt | 23 +++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 1f691b6f11..a3755fc0e7 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -529,6 +529,15 @@ val SparkExitRecord.surfacedRejection: String? it.generation == generation && it.rejections >= SparkExitDriver.REJECTIONS_TO_SURFACE && !it.isAccepted }?.lastOutcome +/** + * A step of this generation went unpaid too many times in a row. Without the SDK nothing rebuilds it and it counts no + * rejection, so the exit is not keeping up: the deadline alarm must be left to fire. + */ +val SparkExitRecord.isFeeChainStuck: Boolean + get() = broadcastLog.any { + it.generation == generation && it.feeChainFailures >= SparkExitDriver.FEE_CHAIN_FAILURES_TO_REBUILD + } + /** Transaction ids of the CPFP children, which the SDK returns as hex only. */ object SparkExitTxids { fun cpfpChildTxids(recovery: RecoverFundsResponse): List = diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 0c637a1b92..b9248597f6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -207,7 +207,7 @@ class SparkExitRepo @Inject constructor( // A rebuild needs the SDK; every other running step can go out from the stored recovery without it. Steps // refused again and again keep the exit from moving, however often it runs. val canMove = recovering != null || !updated.isRebuilding - val isOnTrack = tip != null && canMove && updated.surfacedRejection == null + val isOnTrack = tip != null && canMove && updated.surfacedRejection == null && !updated.isFeeChainStuck afterTick(updated, current, isOnTrack) return updated } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 304164ee64..2e539e95e0 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -210,6 +210,29 @@ class SparkExitRepoTest : BaseUnitTest() { verify(work, times(2)).armDeadline(any(), any()) } + @Test + fun `a background run whose step keeps going unpaid lets the deadline alarm fire`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + store.save(SparkExitFixtures.record(Phase.Running).adopt(recovery, 0L)) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) + val posts = mutableListOf() + val refusal = """sendrawtransaction RPC error: {"code":-26,"message":"min relay fee not met, 0 < 17"}""" + + repeat(SparkExitDriver.FEE_CHAIN_FAILURES_TO_REBUILD) { + // Only the SDK can rebuild the fee chain, and Spark does not connect. + val spark = coldSpark(FakeSparkExitRecovering(), connects = false) + createSut(spark, regtestMempool(posts, refusal)).runInBackground().getOrThrow() + } + + val attempt = store.load()?.broadcastLog?.single() + assertEquals(0, attempt?.rejections) + assertEquals(3, attempt?.feeChainFailures) + verify(work, times(2)).armDeadline(any(), any()) + } + @Test fun `a background run of an ended exit with leftover to sweep keeps going without starting spark`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) From 0baad3ff888f1b92b681e0b45bec65bbcc634334 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 04:33:27 +0100 Subject: [PATCH 004/154] fix: floor the spark exit funding ask at dust The funding state was read before the tick, so a tick that ended short of fees showed the raw shortfall (68 sats on qa-03) until the next tick. Read it again after a tick that changed the phase, and floor the fallback ask at the 294-sat dust limit. --- .../to/bitkit/repositories/SparkExitRepo.kt | 2 + .../settings/lightning/SparkExitViewModel.kt | 8 +++- .../bitkit/repositories/SparkExitRepoTest.kt | 47 +++++++++++++++++++ .../lightning/SparkExitViewModelTest.kt | 13 +++++ 4 files changed, 68 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index b9248597f6..73654e44c6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -202,6 +202,8 @@ class SparkExitRepo @Inject constructor( ) val updated = driver.tick(current) _state.update { it.copy(record = updated, lastError = null) } + // A tick that changed the phase, such as a build short of fees, needs the funding state of the new phase. + if (updated.phase != current.phase) refreshFundingSeen(chain, updated) // Spark's balance next to the exit's leaves shows value outside the exit. if (recovering != null) _state.update { it.copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) } // A rebuild needs the SDK; every other running step can go out from the stored recovery without it. Steps diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index 02c8cf870a..83cd128cff 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import to.bitkit.repositories.SparkExitBackgroundLimits import to.bitkit.repositories.SparkExitFundingState +import to.bitkit.repositories.SparkExitMath import to.bitkit.repositories.SparkExitQuote import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo @@ -208,11 +209,14 @@ data class SparkExitUiState( val rejection: String? get() = record?.surfacedRejection - /** The fee funding progress shows, asking for the whole shortfall until the funding address was read. */ + /** + * The fee funding progress shows, asking for the whole shortfall, at least the funding output's dust, until the + * funding address was read. + */ val progressFunding: SparkExitFundingState? get() { val shortfall = record?.fundingShortfallSats ?: return null - return fundingState ?: SparkExitFundingState.Ask(shortfall) + return fundingState ?: SparkExitFundingState.Ask(maxOf(shortfall, SparkExitMath.FUNDING_DUST_SATS)) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 2e539e95e0..cf786ff30c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1,7 +1,9 @@ package to.bitkit.repositories import breez_sdk_spark.CheckRecoverFundsResponse +import breez_sdk_spark.RecoveryRedoReason import breez_sdk_spark.RecoveryVerdict +import breez_sdk_spark.SdkException import io.ktor.client.HttpClient import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.respond @@ -43,6 +45,7 @@ import to.bitkit.services.SparkService import to.bitkit.test.BaseUnitTest import java.io.File import kotlin.test.assertEquals +import kotlin.test.assertIs import kotlin.time.Clock import kotlin.time.Instant @@ -233,6 +236,50 @@ class SparkExitRepoTest : BaseUnitTest() { verify(work, times(2)).armDeadline(any(), any()) } + @Test + fun `a tick that leaves the exit short of fees asks for at least dust at once`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + val funded = "f0".repeat(32) + store.save( + SparkExitFixtures.record(Phase.Running).adopt(recovery, 0L).copy( + funding = listOf( + SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", funded, 0u, 9_035uL) + ), + ), + ) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) + val utxo = """[{"txid":"$funded","vout":0,"value":9035,"status":{"confirmed":true,"block_height":900}}]""" + val mempool = HttpClient( + MockEngine { request -> + val url = request.url.toString() + when { + request.method == HttpMethod.Post && url.endsWith("/api/tx") -> respond("n1") + url.endsWith("/address/${SparkExitFixtures.FUNDING_ADDRESS}/utxo") -> respond(utxo) + url.endsWith("/blocks/tip/height") -> respond("1000") + url.endsWith("/status") -> respond("""{"confirmed":false}""") + else -> throw IOException("unreachable '$url'") + } + }, + ) { defaultRequest { contentType(ContentType.Application.Json) } } + // The qa-03 run: the rebuild needs 68 sats more than the address holds. + val sdk = FakeSparkExitRecovering().apply { + val redo = RecoveryVerdict.Redo(RecoveryRedoReason.ON_CHAIN_STATE_DIVERGED) + checks += CheckRecoverFundsResponse(recovery, redo) + preparedResponse = SparkExitFixtures.prepared(funding = null) + recoverError = SdkException.InsufficientCpfpFunds(9_103uL, "") + } + val sut = createSut(coldSpark(sdk), mempool) + + sut.runInBackground().getOrThrow() + + assertEquals(Phase.NeedsFunding(9_103uL), sut.state.value.record?.phase) + val ask = assertIs(sut.state.value.fundingState) + assertEquals(SparkExitMath.FUNDING_DUST_SATS, ask.sats) + } + @Test fun `a background run of an ended exit with leftover to sweep keeps going without starting spark`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 8e4969ac71..68daeeb642 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -6,7 +6,10 @@ import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.repositories.SparkExitFixtures +import to.bitkit.repositories.SparkExitFundingState +import to.bitkit.repositories.SparkExitMath import to.bitkit.repositories.SparkExitQuote +import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkExitState import to.bitkit.test.BaseUnitTest @@ -49,6 +52,16 @@ class SparkExitViewModelTest : BaseUnitTest() { assertTrue(SparkExitUiState(quote = quote, fundingSeenSats = 20_000uL).canContinueFunding) } + @Test + fun `progress asks for at least dust before the funding address was read`() { + val record = SparkExitFixtures.record(SparkExitRecord.Phase.NeedsFunding(68uL)) + + assertEquals( + SparkExitFundingState.Ask(SparkExitMath.FUNDING_DUST_SATS), + SparkExitUiState(record = record).progressFunding, + ) + } + @Test fun `a stopped exit says only what still stays on spark`() { val nothing = "Nothing could be recovered." From 4df5c75f4a031729b35a0436171fa76cdd9cdfb4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 05:21:16 +0100 Subject: [PATCH 005/154] fix: name what a stopped spark exit leaves on spark The stopped result read the amount outside the exit, which holds only while the exit runs, from a balance kept only during SDK ticks. It now reads Spark's live balance beyond the exit's leaves in any phase, as iOS does. --- .../bitkit/repositories/SparkExitFunding.kt | 7 ++++ .../lightning/SparkExitProgressScreen.kt | 6 +-- .../settings/lightning/SparkExitViewModel.kt | 39 ++++++++++++------- .../lightning/SparkExitViewModelTest.kt | 35 +++++++++++++++-- 4 files changed, 67 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 8779121101..f00fea449b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -198,6 +198,13 @@ object SparkExitMath { return (quote.leftBehindSats.safe() + beyond.safe()).takeIf { it > 0uL } } + /** + * What Spark's [balanceSats] holds beyond [record]'s leaves, in any phase: what a stopped exit leaves on Spark, + * such as value it could not exit. Lost leaves stay in the leaf total, so they are never claimed to stay. + */ + fun staysOnSparkSats(balanceSats: ULong?, record: SparkExitRecord?): ULong? = + record?.let { outsideExitSats(it.leafTotalSats, balanceSats) } + /** Spark's balance beyond the exit's leaves while it still counts them, or null. */ fun outsideExitSats(leafTotalSats: ULong?, balanceSats: ULong?): ULong? { if (leafTotalSats == null || balanceSats == null || balanceSats <= leafTotalSats) return null diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 61c091e11a..09c665b752 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -101,7 +101,7 @@ private fun Content( text = progressText( record = record, progressFunding = uiState.progressFunding, - outsideExitSats = uiState.outsideExitSats, + staysOnSparkSats = uiState.staysOnSparkSats, ).withAccentBoldBright(), color = Colors.White64, ) @@ -274,7 +274,7 @@ private fun progressTitle(phase: SparkExitRecord.Phase?): String = stringResourc private fun progressText( record: SparkExitRecord?, progressFunding: SparkExitFundingState?, - outsideExitSats: ULong?, + staysOnSparkSats: ULong?, ): String = when (record?.phase) { SparkExitRecord.Phase.Done -> listOfNotNull( stringResource(R.string.lightning__spark_exit__done_text), @@ -288,7 +288,7 @@ private fun progressText( is SparkExitRecord.Phase.Failed -> sparkExitFailedText( nothingText = stringResource(R.string.lightning__spark_exit__failed_text), staysText = stringResource(R.string.lightning__spark_exit__failed_stays), - outsideAmount = outsideExitSats?.let { sparkExitAmountText(it) }, + outsideAmount = staysOnSparkSats?.let { sparkExitAmountText(it) }, ) is SparkExitRecord.Phase.NeedsFunding -> when (val funding = progressFunding) { // A payment that covers it waits to confirm: nothing to ask for. diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index 83cd128cff..4a10af579a 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -10,6 +10,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch @@ -19,6 +20,8 @@ import to.bitkit.repositories.SparkExitMath import to.bitkit.repositories.SparkExitQuote import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState +import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.surfacedRejection import to.bitkit.ui.shared.toast.ToastEventBus import javax.inject.Inject @@ -28,6 +31,7 @@ import kotlin.time.Duration.Companion.seconds @HiltViewModel class SparkExitViewModel @Inject constructor( private val sparkExitRepo: SparkExitRepo, + private val sparkRepo: SparkRepo, ) : ViewModel() { companion object { /** How often the funding screen looks at the funding address while the user pays from another wallet. */ @@ -44,20 +48,25 @@ class SparkExitViewModel @Inject constructor( init { viewModelScope.launch { - sparkExitRepo.state.collect { exit -> - _uiState.update { - it.copy( - record = exit.record, - tipHeight = exit.tipHeight, - fundingSeenSats = exit.fundingSeenSats, - fundingState = exit.fundingState, - fundingAddress = exit.fundingAddress, - canCancel = sparkExitRepo.canCancel, - outsideExitSats = exit.outsideExitSats, - isSettling = exit.isSettling, - ) - } - } + // Spark's live balance, for what a stopped exit leaves on Spark after a relaunch too. + combine(sparkExitRepo.state, sparkRepo.state) { exit, spark -> exit to spark.balanceSats } + .collect { (exit, balanceSats) -> showExit(exit, balanceSats) } + } + } + + private fun showExit(exit: SparkExitState, balanceSats: ULong) { + _uiState.update { + it.copy( + record = exit.record, + tipHeight = exit.tipHeight, + fundingSeenSats = exit.fundingSeenSats, + fundingState = exit.fundingState, + fundingAddress = exit.fundingAddress, + canCancel = sparkExitRepo.canCancel, + outsideExitSats = exit.outsideExitSats, + staysOnSparkSats = SparkExitMath.staysOnSparkSats(balanceSats, exit.record), + isSettling = exit.isSettling, + ) } } @@ -189,6 +198,8 @@ data class SparkExitUiState( val canCancel: Boolean = false, val backgroundLimits: SparkExitBackgroundLimits = SparkExitBackgroundLimits(), val outsideExitSats: ULong? = null, + /** Spark's balance beyond the exit's leaves in any phase: what a stopped exit leaves on Spark. */ + val staysOnSparkSats: ULong? = null, /** The quote waits for Spark to finish moving leaves first. */ val isSettling: Boolean = false, ) { diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 68daeeb642..9a8489ac87 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -12,18 +12,24 @@ import to.bitkit.repositories.SparkExitQuote import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkExitState +import to.bitkit.repositories.SparkRepo +import to.bitkit.repositories.SparkState import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals import kotlin.test.assertFalse +import kotlin.test.assertNull import kotlin.test.assertTrue class SparkExitViewModelTest : BaseUnitTest() { - private val repo = mock { on { state } doReturn MutableStateFlow(SparkExitState()) } + private val exitState = MutableStateFlow(SparkExitState()) + private val sparkState = MutableStateFlow(SparkState()) + private val repo = mock { on { state } doReturn exitState } + private val sparkRepo = mock { on { state } doReturn sparkState } @Test fun `entering the funding step again offers both choices while nothing was paid`() = test { whenever(repo.refreshFundingAddress()).thenReturn(Result.success(0uL)) - val sut = SparkExitViewModel(repo) + val sut = SparkExitViewModel(repo, sparkRepo) sut.onFundExternally() sut.stopWatchingFundingAddress() @@ -36,7 +42,7 @@ class SparkExitViewModelTest : BaseUnitTest() { @Test fun `entering the funding step keeps the address once a payment reached it`() = test { whenever(repo.refreshFundingAddress()).thenReturn(Result.success(5_000uL)) - val sut = SparkExitViewModel(repo) + val sut = SparkExitViewModel(repo, sparkRepo) sut.onFundingShown() @@ -62,6 +68,29 @@ class SparkExitViewModelTest : BaseUnitTest() { ) } + /** The qa-03 rerun, case 5: one 32,768-sat leaf lost to an older owner, 1,696 sats Spark could not exit. */ + @Test + fun `a stopped exit names what spark's live balance holds beyond its leaves`() = test { + val stopped = SparkExitFixtures.record(SparkExitRecord.Phase.Failed("Claimed by an older state")).copy( + leafTotalSats = 32_768uL, + lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 32_768uL)), + ) + exitState.value = SparkExitState(record = stopped) + val sut = SparkExitViewModel(repo, sparkRepo) + + sparkState.value = SparkState(balanceSats = 34_464uL) + + assertEquals(1_696uL, sut.uiState.value.staysOnSparkSats) + assertNull(sut.uiState.value.outsideExitSats) + assertEquals( + "Nothing could be recovered. ₿ 1 696 stays on Spark.", + sparkExitFailedText("Nothing could be recovered.", "{amount} stays on Spark.", outsideAmount = "₿ 1 696"), + ) + // Only the lost leaf is left on Spark's books: nothing is claimed to stay. + sparkState.value = SparkState(balanceSats = 32_768uL) + assertNull(sut.uiState.value.staysOnSparkSats) + } + @Test fun `a stopped exit says only what still stays on spark`() { val nothing = "Nothing could be recovered." From 8eac6db67fb16733bede43fe1a9b214fdd9db419 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 11:07:52 +0100 Subject: [PATCH 006/154] fix: keep lost spark exit leaves out of later exits --- app/src/main/java/to/bitkit/env/Env.kt | 7 ++ .../to/bitkit/repositories/SparkExitDriver.kt | 42 +++++++++++- .../to/bitkit/repositories/SparkExitRecord.kt | 26 ++++++++ .../to/bitkit/repositories/SparkExitRepo.kt | 41 ++++++++++-- .../to/bitkit/repositories/SparkExitWorker.kt | 12 +++- .../java/to/bitkit/repositories/SparkRepo.kt | 2 + .../repositories/SparkExitAlertsTest.kt | 14 ++++ .../repositories/SparkExitDriverTest.kt | 65 +++++++++++++++++++ .../bitkit/repositories/SparkExitFixtures.kt | 14 +++- .../bitkit/repositories/SparkExitRepoTest.kt | 18 +++++ 10 files changed, 230 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index 53baea558e..234701f6e8 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -246,6 +246,13 @@ internal object Env { return Path(appStoragePath, network.name.lowercase(), "wallet$walletIndex", "spark-exit.json").toString() } + /** Leaves an older state of the wallet claimed on-chain, kept past the exit record that found them. */ + fun sparkExitLostLeavesPath(walletIndex: Int): String { + require(::appStoragePath.isInitialized) { "App storage path should be 'context.filesDir.absolutePath'." } + val wallet = "wallet$walletIndex" + return Path(appStoragePath, network.name.lowercase(), wallet, "spark-exit-lost-leaves.json").toString() + } + fun bitkitCoreStoragePath(walletIndex: Int): String { return storagePathOf(walletIndex, network.name.lowercase(), "core") } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index a3755fc0e7..eb691cc0c4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -26,6 +26,42 @@ interface SparkExitRecovering { suspend fun check(recovery: RecoverFundsResponse): CheckRecoverFundsResponse } +/** + * Prepares every leaf the operators list less [lost], the leaves an older state of this wallet claimed on-chain, which + * the operators keep listing. A quote that lists one is prepared again for the rest, so its amount, fees and funding + * leave it out, dropping a leaf the SDK refuses to exit; nothing is left to exit when every listed leaf is lost. + */ +suspend fun SparkExitRecovering.prepareAll( + request: PrepareRecoverFundsRequest, + lost: Set, +): PrepareRecoverFundsResponse { + val all = prepare(request.copy(selection = ExitLeafSelection.All)) + val skipped = all.skipped.filter { it.leafId !in lost } + if (all.leaves.none { it.leafId in lost }) return all.copy(skipped = skipped) + var ids = all.leaves.map { it.leafId }.filter { it !in lost } + while (ids.isNotEmpty()) { + val result = runSuspendCatching { prepare(request.copy(selection = ExitLeafSelection.Specific(ids))) } + result.getOrNull()?.let { prepared -> + return prepared.copy(skipped = (prepared.skipped + skipped).distinctBy { it.leafId }) + } + val error = requireNotNull(result.exceptionOrNull()) + val refusal = SparkExitUnexitable.parse(error)?.takeIf { it.leafId in ids } ?: throw error + ids = ids - refusal.leafId + } + return all.copy( + leaves = emptyList(), + skipped = skipped, + recoverableValueSats = 0uL, + totalFeeSats = 0uL, + cooperativeFeeSats = 0uL, + cpfpFeeSats = 0uL, + fanoutFeeSats = 0uL, + refundFeeSats = 0uL, + sweepFeeSats = 0uL, + funding = null, + ) +} + /** * Moves an exit one step forward each tick: builds it once its fee funding confirms, broadcasts what is ready, * rebuilds when the chain diverged or its fee chain lost a race, and finishes when everything confirmed. Without the @@ -204,7 +240,11 @@ class SparkExitDriver( ids.filter { it !in listed }.forEach { record = record.leaveBehind(it, SparkExitUnexitable.NOT_RECOVERABLE) } - return record to prepared + if (listed.all { it in ids }) return record to prepared + // It also lists leaves outside the exit, such as one an older state claimed: only the exit's are built. + val remaining = record.exitLeafIds + if (remaining.isEmpty()) return record to null + return record to sdk.prepare(prepareRequest(record, ExitLeafSelection.Specific(remaining))) } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 90e7453329..1703b17d12 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -293,6 +293,32 @@ class SparkExitStore(private val file: File) { } } +/** + * The ids of the leaves an older state of one wallet claimed on-chain. The operators keep listing such a leaf, so it + * outlives the exit record that found it: a later exit neither quotes nor builds it again. Not backed up; a restored + * wallet finds a lost leaf again in one rebuild. + */ +class SparkExitLostLeafStore(private val file: File) { + fun load(): Set { + if (!file.exists()) return emptySet() + return Json.parseToJsonElement(file.readText()).jsonArray.map { it.jsonPrimitive.content }.toSet() + } + + /** Adds [leafIds], writing only when one is new; an unreadable file is written anew. */ + fun add(leafIds: Collection) { + val known = runCatching { load() }.getOrDefault(emptySet()) + if (known.containsAll(leafIds)) return + file.parentFile?.mkdirs() + val temp = File(file.parentFile, "${file.name}.tmp") + temp.writeText(JsonArray((known + leafIds).sorted().map(::JsonPrimitive)).toString()) + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } + + fun delete() { + file.delete() + } +} + class SparkExitFormatError(message: String) : AppError(message) class SparkExitUnsupportedVersion(val version: Int) : AppError("Unsupported Spark exit record version '$version'") diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 73654e44c6..d8c2dfcc40 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -101,6 +101,8 @@ class SparkExitRepo @Inject constructor( private val store get() = SparkExitStore(File(Env.sparkExitRecordPath(walletIndex))) + private val lostLeafStore get() = SparkExitLostLeafStore(File(Env.sparkExitLostLeavesPath(walletIndex))) + private val chain: SparkExitChain? get() = EsploraSparkExitChain.defaultHosts(sparkService.networkName) .takeIf { it.isNotEmpty() } @@ -121,6 +123,7 @@ class SparkExitRepo @Inject constructor( } isLoaded = true _state.update { it.copy(record = record) } + rememberLostLeaves(record) record?.let { settleIfFinished(it) } settleOrphanedTransfers(record) if (record?.needsDriving == true) work.schedulePeriodic() @@ -200,7 +203,10 @@ class SparkExitRepo @Inject constructor( save = store::save, nowMillis = clock::nowMs, ) + // Read before this tick's losses are kept, so a leaf lost now is still reported once. + val reportedLost = reportedLostLeafIds() val updated = driver.tick(current) + rememberLostLeaves(updated) _state.update { it.copy(record = updated, lastError = null) } // A tick that changed the phase, such as a build short of fees, needs the funding state of the new phase. if (updated.phase != current.phase) refreshFundingSeen(chain, updated) @@ -210,14 +216,19 @@ class SparkExitRepo @Inject constructor( // refused again and again keep the exit from moving, however often it runs. val canMove = recovering != null || !updated.isRebuilding val isOnTrack = tip != null && canMove && updated.surfacedRejection == null && !updated.isFeeChainStuck - afterTick(updated, current, isOnTrack) + afterTick(updated, current, isOnTrack, reportedLost) return updated } - private suspend fun afterTick(record: SparkExitRecord, previous: SparkExitRecord, isOnTrack: Boolean) { + private suspend fun afterTick( + record: SparkExitRecord, + previous: SparkExitRecord, + isOnTrack: Boolean, + reportedLost: Set, + ) { record.transferId?.let { transferRepo.updateClaimableAtHeight(it, record.claimableAtHeight) } settleIfFinished(record) - updateAlerts(record, previous, isOnTrack) + updateAlerts(record, previous, isOnTrack, reportedLost) if (!record.isActive && previous.isActive) { Logger.info("Ended Spark exit with phase '${record.phase}'", context = TAG) sparkRepo.setExiting(false) @@ -284,8 +295,13 @@ class SparkExitRepo @Inject constructor( * be published. Only a run that kept the exit on track pushes it; a stalled exit lets it fire. Needing more fee * funding is notified once, at once. */ - private fun updateAlerts(record: SparkExitRecord, previous: SparkExitRecord, isOnTrack: Boolean) { - SparkExitAlerts.losses(record, previous).forEach { + private fun updateAlerts( + record: SparkExitRecord, + previous: SparkExitRecord, + isOnTrack: Boolean, + reportedLost: Set, + ) { + SparkExitAlerts.losses(record, previous, reportedLost).forEach { work.notify(it, amountSats = record.lostSats.takeIf { _ -> it == SparkExitAlert.Lost }) } when (record.phase) { @@ -306,6 +322,16 @@ class SparkExitRepo @Inject constructor( } } + private fun reportedLostLeafIds(): Set = runCatching { lostLeafStore.load() } + .onFailure { Logger.warn("Failed to read the lost Spark exit leaves", it, context = TAG) } + .getOrDefault(emptySet()) + + private fun rememberLostLeaves(record: SparkExitRecord?) { + val ids = record?.lostLeaves?.map { it.leafId }?.takeIf { it.isNotEmpty() } ?: return + runCatching { lostLeafStore.add(ids) } + .onFailure { Logger.warn("Failed to keep the lost Spark exit leaves '$ids'", it, context = TAG) } + } + /** What Android lets the exit do while Bitkit is closed, for the progress screen. */ fun backgroundLimits(): SparkExitBackgroundLimits = work.backgroundLimits() @@ -321,13 +347,16 @@ class SparkExitRepo @Inject constructor( sparkRepo.settleForExit().also { _state.update { it.copy(isSettling = false) } }.getOrThrow() val feeRate = maxOf(1uL, sparkService.fastestFeeRate()) val destination = _state.value.pending?.destination ?: lightningRepo.newAddress().getOrThrow() - val prepared = recovering.prepare( + // Leaves an earlier exit lost to an older state stay listed by the operators, but cannot be exited. + val lost = reportedLostLeafIds() + _state.value.record?.lostLeaves?.map { it.leafId }.orEmpty() + val prepared = recovering.prepareAll( PrepareRecoverFundsRequest( feeRateSatPerVbyte = feeRate, fundingKind = CpfpFundingKind.P2wpkh, destination = destination, selection = ExitLeafSelection.All, ), + lost, ) val quote = SparkExitQuote(prepared, sparkRepo.state.value.balanceSats) // Chosen here, so the funding screen, the fee estimate and the record all use one address. diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index df2b540dc4..cae829f698 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -248,12 +248,18 @@ private val ALWAYS_POSTED = setOf(SparkExitAlert.Lost, SparkExitAlert.Failed) object SparkExitAlerts { /** * What a tick that moved the exit from [previous] to [record] lost, each posted once: leaves an older owner - * claimed, and the exit failing, unless it failed because every leaf was claimed, which the lost leaves say. + * claimed, and the exit failing, unless it failed because every leaf was claimed, which the lost leaves say. A leaf + * in [reportedLost] was already reported by an earlier exit. */ - fun losses(record: SparkExitRecord, previous: SparkExitRecord): List { + fun losses( + record: SparkExitRecord, + previous: SparkExitRecord, + reportedLost: Set = emptySet(), + ): List { val phase = record.phase + val known = previous.lostLeaves.map { it.leafId }.toSet() + reportedLost return listOfNotNull( - SparkExitAlert.Lost.takeIf { record.lostLeaves.size > previous.lostLeaves.size }, + SparkExitAlert.Lost.takeIf { record.lostLeaves.any { it.leafId !in known } }, SparkExitAlert.Failed.takeIf { phase is SparkExitRecord.Phase.Failed && !record.isEveryLeafLost && previous.phase !is SparkExitRecord.Phase.Failed diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index c630dd7dac..a907433ce0 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -177,6 +177,8 @@ class SparkRepo @Inject constructor( .onFailure { Logger.error("Failed to wipe Spark wallet", it, context = TAG) } runSuspendCatching { exitStore(walletIndex).delete() } .onFailure { Logger.error("Failed to wipe Spark exit record", it, context = TAG) } + runSuspendCatching { SparkExitLostLeafStore(File(Env.sparkExitLostLeavesPath(walletIndex))).delete() } + .onFailure { Logger.error("Failed to wipe the lost Spark exit leaves", it, context = TAG) } _state.update { SparkState(isSupported = sparkService.isSupported) } _walletWiped.emit(walletIndex) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt index c1d32a8a0e..3420bb9229 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt @@ -77,4 +77,18 @@ class SparkExitAlertsTest { assertEquals(emptyList(), SparkExitAlerts.losses(stopped, stopped)) assertEquals(emptyList(), SparkExitAlerts.losses(SparkExitFixtures.record(Phase.Done), running)) } + + @Test + fun `posts no second loss for a leaf an earlier exit already reported`() { + val lost = running.copy(lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 65_536uL))) + val claimed = lost.copy(phase = Phase.Failed(SparkExitDriver.LOST_REASON)) + + assertEquals(emptyList(), SparkExitAlerts.losses(lost, running, reportedLost = setOf("leaf-1"))) + assertEquals(emptyList(), SparkExitAlerts.losses(claimed, running, reportedLost = setOf("leaf-1"))) + val another = lost.copy(lostLeaves = lost.lostLeaves + SparkExitRecord.LostLeaf("leaf-2", 4_000uL)) + assertEquals( + listOf(SparkExitAlert.Lost), + SparkExitAlerts.losses(another, running, reportedLost = setOf("leaf-1")), + ) + } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 013e5b254a..65b0285ef1 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -18,6 +18,8 @@ import org.junit.Test import org.junit.rules.TemporaryFolder import to.bitkit.repositories.SparkExitRecord.Phase import to.bitkit.test.BaseUnitTest +import to.bitkit.ui.settings.lightning.SparkExitQuoteBlock +import to.bitkit.ui.settings.lightning.SparkExitUiState import to.bitkit.utils.SignedTransactionId import java.io.File import kotlin.test.assertEquals @@ -808,6 +810,69 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(2, record.generation) } + @Test + fun `a refusal fallback that lists a leaf outside the exit prepares only the exit's leaves`() = test { + val start = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1")))) + .copy(leafIds = listOf("leaf-1", "leaf-2"), isRebuilding = true, lastBuildAt = null) + sdk.prepareErrors += SdkException.SparkException("Leaf cannot be exited") + // The operators still list a leaf an older state claimed, and recoverable-only picks it up. + sdk.preparedResponses += SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-1", "lost-1")) + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-1")) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + + val record = driver().tick(start) + + val selection = assertIs(sdk.prepareRequests.last().selection) + assertEquals(listOf("leaf-1"), selection.leafIds) + assertEquals(listOf("leaf-1"), sdk.recoverRequests.single().prepared.leaves.map { it.leafId }) + assertEquals(listOf("leaf-2"), record.leftBehindLeaves.map { it.leafId }) + } + + @Test + fun `a quote leaves out lost leaves the operators still list`() = test { + val lostSkip = SkippedLeaf("lost-2", 65_536uL, SkippedLeafReason.Unverified) + val dust = SkippedLeaf("dust", 300uL, SkippedLeafReason.FeeExceedsValue) + sdk.preparedResponses += SparkExitFixtures.prepared( + leaves = listOf("leaf-1", "lost-1"), + skipped = listOf(dust, lostSkip), + totalFeeSats = 18_000uL, + ) + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-1"), skipped = emptyList()) + + val prepared = sdk.prepareAll(SparkExitFixtures.prepareRequest(), lost = setOf("lost-1", "lost-2")) + + assertEquals(ExitLeafSelection.All, sdk.prepareRequests.first().selection) + val selection = assertIs(sdk.prepareRequests.last().selection) + assertEquals(listOf("leaf-1"), selection.leafIds) + assertEquals(listOf("leaf-1"), prepared.leaves.map { it.leafId }) + assertEquals(9_000uL, prepared.totalFeeSats) + assertEquals(listOf(dust), prepared.skipped) + } + + @Test + fun `a quote with no lost leaf listed is the operators' own`() = test { + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-1")) + + val prepared = sdk.prepareAll(SparkExitFixtures.prepareRequest(), lost = setOf("lost-1")) + + assertEquals(listOf(ExitLeafSelection.All), sdk.prepareRequests.map { it.selection }) + assertEquals(sdk.preparedResponse, prepared) + } + + @Test + fun `a quote whose every leaf is lost shows nothing to exit`() = test { + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("lost-1")) + + val prepared = sdk.prepareAll(SparkExitFixtures.prepareRequest(), lost = setOf("lost-1")) + + assertEquals(1, sdk.prepareRequests.size) + assertTrue(prepared.leaves.isEmpty()) + assertEquals(0uL, prepared.recoverableValueSats) + assertEquals(0uL, prepared.totalFeeSats) + assertNull(prepared.funding) + assertEquals(SparkExitQuoteBlock.Nothing, SparkExitUiState(quote = SparkExitQuote(prepared)).quoteBlock) + } + @Test fun `a leaf recoverFunds refuses is left behind and the rest rebuilt on the next tick`() = test { val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt index 55eaeb9b42..b657798247 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -2,9 +2,11 @@ package to.bitkit.repositories import breez_sdk_spark.CheckRecoverFundsResponse import breez_sdk_spark.CooperativeRecoveryFailure +import breez_sdk_spark.CpfpFundingKind import breez_sdk_spark.CpfpInput import breez_sdk_spark.CpfpSigner import breez_sdk_spark.ExitChainState +import breez_sdk_spark.ExitLeafSelection import breez_sdk_spark.ExitTransactionStatus import breez_sdk_spark.PrepareRecoverFundsRequest import breez_sdk_spark.PrepareRecoverFundsResponse @@ -86,6 +88,13 @@ object SparkExitFixtures { exitChainState = ExitChainState(emptyList(), emptyList(), emptyList(), emptyList(), emptyList()), ) + fun prepareRequest() = PrepareRecoverFundsRequest( + feeRateSatPerVbyte = 2uL, + fundingKind = CpfpFundingKind.P2wpkh, + destination = "bcrt1qdestination", + selection = ExitLeafSelection.All, + ) + fun record(phase: SparkExitRecord.Phase = SparkExitRecord.Phase.AwaitingFunding(20_000uL)) = SparkExitRecord( network = "regtest", createdAt = 1_700_000_000_000L, @@ -178,10 +187,13 @@ class FakeSparkExitRecovering : SparkExitRecovering { /** Errors the next prepares throw, in order, before [preparedResponse] is returned. */ val prepareErrors = ArrayDeque() + /** Responses the next prepares return, in order, before [preparedResponse]. */ + val preparedResponses = ArrayDeque() + override suspend fun prepare(request: PrepareRecoverFundsRequest): PrepareRecoverFundsResponse { prepareRequests += request prepareErrors.removeFirstOrNull()?.let { throw it } - return preparedResponse + return preparedResponses.removeFirstOrNull() ?: preparedResponse } override suspend fun recover(request: RecoverFundsRequest, signer: CpfpSigner?): RecoverFundsResponse { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index cf786ff30c..441bec38e2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -127,6 +127,24 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(false, file.exists()) } + @Test + fun `leaves lost to an older state outlive the exit record that found them`() = test { + val recordFile = File(Env.sparkExitRecordPath(0)) + val lost = SparkExitRecord.LostLeaf("leaf-1", 65_536uL) + SparkExitStore(recordFile).save( + SparkExitFixtures.record(Phase.Failed(SparkExitDriver.LOST_REASON)).copy(lostLeaves = listOf(lost)), + ) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(emptyList())) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(true)) + createSut().load(0).getOrThrow() + + // A new exit replaces the record. + SparkExitStore(recordFile).save(SparkExitFixtures.record().copy(leafIds = listOf("leaf-2"))) + createSut().load(0).getOrThrow() + + assertEquals(setOf("leaf-1"), SparkExitLostLeafStore(File(Env.sparkExitLostLeavesPath(0))).load()) + } + /** Spark's regtest mempool, where nothing is confirmed yet and every single transaction is accepted. */ private fun regtestMempool(posts: MutableList, refusal: String? = null) = HttpClient( MockEngine { request -> From 30f87e51f850e1dab2032d48818ce10dafddc016 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 12:41:21 +0100 Subject: [PATCH 007/154] feat: spark exit uses bitkit electrs on mainnet --- .../bitkit/services/SparkExitRegtestTest.kt | 2 +- .../to/bitkit/repositories/SparkExitChain.kt | 65 +++++++++----- .../to/bitkit/repositories/SparkExitRepo.kt | 1 - .../bitkit/repositories/SparkExitChainTest.kt | 87 ++++++++++++++++++- .../repositories/SparkExitRegtestTest.kt | 2 +- 5 files changed, 133 insertions(+), 24 deletions(-) diff --git a/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt b/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt index e6dffa1a13..73c54ef5ad 100644 --- a/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt +++ b/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt @@ -72,7 +72,7 @@ class SparkExitRegtestTest { assertTrue(prepared.leaves.isEmpty()) assertFalse(SparkExitQuote(prepared).isWorthExiting) - val chain = EsploraSparkExitChain(EsploraSparkExitChain.defaultHosts("regtest"), HttpClient()) + val chain = EsploraSparkExitChain(checkNotNull(EsploraSparkExitChain.defaultHosts("regtest")), HttpClient()) assertTrue(chain.tipHeight() > 0u) assertTrue(chain.utxos(address.address).isEmpty()) } finally { diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 55a1678c4d..4ac5a09373 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -21,6 +21,7 @@ import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.longOrNull +import to.bitkit.env.Env import to.bitkit.ext.runSuspendCatching import to.bitkit.utils.AppError @@ -67,8 +68,8 @@ interface SparkExitChain { suspend fun txStatus(txid: String): EsploraTxStatus /** - * Whether a host has [txid] in a block or its mempool, from `/tx/{txid}/hex`: false only when every host answers - * 404. Throws when a host fails otherwise, since that host may know it. + * Whether a read host has [txid] in a block or its mempool, from `/tx/{txid}/hex`: false only when every read host + * answers 404. Throws when a host fails otherwise, since that host may know it. */ suspend fun isTxKnown(txid: String): Boolean suspend fun broadcast(tx: RecoveryTransaction): SparkExitBroadcastOutcome @@ -79,22 +80,46 @@ interface SparkExitChain { class SparkExitChainError(message: String) : AppError(message) +/** A host an exit broadcasts through, with the paths it takes a package on, tried in order. */ +data class SparkExitBroadcastHost( + val url: String, + val packagePaths: List = listOf("/v1/txs/package", "/txs/package"), +) + +/** Where an exit reads the chain, and where it broadcasts, each tried in order. */ +data class SparkExitHosts(val reads: List, val broadcasts: List) { + companion object { + /** One set of hosts for reads and broadcasts alike. */ + fun of(vararg urls: String) = SparkExitHosts(urls.toList(), urls.map(::SparkExitBroadcastHost)) + } +} + /** - * esplora and mempool.space REST, on the hosts the Spark SDK uses by default: a transaction with a CPFP child goes - * out as a package through `/v1/txs/package` (a JSON array of hex), one without as a single `/tx`. + * esplora and mempool.space REST: a transaction with a CPFP child goes out as a package (a JSON array of hex), one + * without as a single `/tx`. */ class EsploraSparkExitChain( - private val hosts: List, + private val hosts: SparkExitHosts, private val client: HttpClient, ) : SparkExitChain { companion object { private val json = Json { ignoreUnknownKeys = true } - /** The Spark SDK's default chain service per network (breez spark-sdk `default_rest_chain_services`). */ - fun defaultHosts(sparkNetwork: String?): List = when (sparkNetwork) { - "mainnet" -> listOf("https://mempool.space/api", "https://blockstream.info/api") - "regtest" -> listOf("https://regtest-mempool.us-west-2.sparkinfra.net/api") - else -> emptyList() + /** + * The chain the Spark SDK reads per network. Mainnet reads Bitkit's own esplora alone, which takes a package + * on `/txs/package` only, and broadcasts there first, then through the SDK's former default hosts. + */ + fun defaultHosts(sparkNetwork: String?): SparkExitHosts? = when (sparkNetwork) { + "mainnet" -> SparkExitHosts( + reads = listOf(Env.bitkitEsploraUrl), + broadcasts = listOf( + SparkExitBroadcastHost(Env.bitkitEsploraUrl, packagePaths = listOf("/txs/package")), + SparkExitBroadcastHost("https://mempool.space/api"), + SparkExitBroadcastHost("https://blockstream.info/api"), + ), + ) + "regtest" -> SparkExitHosts.of("https://regtest-mempool.us-west-2.sparkinfra.net/api") + else -> null } private val NOT_HERE = setOf(404, 405) @@ -119,10 +144,10 @@ class EsploraSparkExitChain( status(json.parseToJsonElement(get("/tx/$txid/status")).jsonObject) override suspend fun isTxKnown(txid: String): Boolean { - if (hosts.isEmpty()) throw SparkExitChainError("No chain host configured") + if (hosts.reads.isEmpty()) throw SparkExitChainError("No chain host configured") val path = "/tx/$txid/hex" var lastError: Throwable? = null - for (host in hosts) { + for (host in hosts.reads) { val status = runSuspendCatching { client.get("$host$path").status } .onFailure { lastError = it } .getOrNull() @@ -137,12 +162,12 @@ class EsploraSparkExitChain( /** Tries each host until one accepts. Otherwise a node's refusal wins over a host that was only unavailable. */ override suspend fun broadcast(tx: RecoveryTransaction): SparkExitBroadcastOutcome { val outcomes = mutableListOf() - for (host in hosts) { + for (host in hosts.broadcasts) { val child = tx.cpfpTxHex val attempt = if (child != null) { submitPackage(host, listOf(tx.txHex, child), tx.txid) } else { - submitSingle(host, tx.txHex) + submitSingle(host.url, tx.txHex) } // null: this host cannot take it (no package endpoint, unreachable). if (attempt == SparkExitBroadcastOutcome.Accepted) return attempt @@ -154,8 +179,8 @@ class EsploraSparkExitChain( } override suspend fun broadcastHex(hex: String): SparkExitBroadcastOutcome { - val outcomes = hosts.mapNotNull { host -> - submitSingle(host, hex).also { if (it == SparkExitBroadcastOutcome.Accepted) return it } + val outcomes = hosts.broadcasts.mapNotNull { host -> + submitSingle(host.url, hex).also { if (it == SparkExitBroadcastOutcome.Accepted) return it } } return outcomes.firstOrNull { it is SparkExitBroadcastOutcome.Rejected } ?: outcomes.firstOrNull() @@ -163,13 +188,13 @@ class EsploraSparkExitChain( } private suspend fun submitPackage( - host: String, + host: SparkExitBroadcastHost, hexes: List, parentTxid: String, ): SparkExitBroadcastOutcome? { val body = JsonArray(hexes.map(::JsonPrimitive)).toString() - for (path in listOf("/v1/txs/package", "/txs/package")) { - val response = post("$host$path", TextContent(body, ContentType.Application.Json)) ?: return null + for (path in host.packagePaths) { + val response = post("${host.url}$path", TextContent(body, ContentType.Application.Json)) ?: return null if (response.status.value in NOT_HERE) continue return SparkExitBroadcastClassifier.pkg(response.status.value, response.bodyAsText(), parentTxid) } @@ -193,7 +218,7 @@ class EsploraSparkExitChain( private suspend fun get(path: String): String { var lastError: Throwable = SparkExitChainError("No chain host configured") - for (host in hosts) { + for (host in hosts.reads) { runSuspendCatching { val response = client.get("$host$path") if (!response.status.isSuccess()) { diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index d8c2dfcc40..96d6b33870 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -105,7 +105,6 @@ class SparkExitRepo @Inject constructor( private val chain: SparkExitChain? get() = EsploraSparkExitChain.defaultHosts(sparkService.networkName) - .takeIf { it.isNotEmpty() } ?.let { EsploraSparkExitChain(it, httpClient) } // region lifecycle diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt index cc067ff19e..8ba3047054 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -31,7 +31,10 @@ class SparkExitChainTest : BaseUnitTest() { private val bodies = mutableListOf() /** Answers each request with the first route whose URL it ends with; an unknown URL fails like a dead host. */ - private fun chain(vararg routes: Route, hosts: List = listOf(hostA)): EsploraSparkExitChain { + private fun chain(vararg routes: Route, hosts: List = listOf(hostA)): EsploraSparkExitChain = + chain(*routes, hosts = SparkExitHosts.of(*hosts.toTypedArray())) + + private fun chain(vararg routes: Route, hosts: SparkExitHosts): EsploraSparkExitChain { val pending = routes.toMutableList() val engine = MockEngine { request -> answer(request, pending) } // Like the app's shared client, which defaults every request to JSON. @@ -223,4 +226,86 @@ class SparkExitChainTest : BaseUnitTest() { assertFailsWith { chain(unknown, down, hosts = listOf(hostA, hostB)).isTxKnown("t") } assertFailsWith { chain(hosts = listOf(hostA)).isTxKnown("t") } } + + @Test + fun `a single read host decides whether a transaction is known`() = test { + assertFalse(chain(Route("a.example/api/tx/t/hex", 404, "Transaction not found")).isTxKnown("t")) + assertFailsWith { chain(Route("a.example/api/tx/t/hex", 503, "")).isTxKnown("t") } + assertFailsWith { chain().isTxKnown("t") } + } + + private val ownHosts = SparkExitHosts( + reads = listOf(hostA), + broadcasts = listOf( + SparkExitBroadcastHost(hostA, packagePaths = listOf("/txs/package")), + SparkExitBroadcastHost(hostB), + ), + ) + + @Test + fun `reads stay on the read hosts`() = test { + val sut = chain( + Route("a.example/api/blocks/tip/height", 503, ""), + Route("b.example/api/blocks/tip/height", 200, "1"), + Route("b.example/api/tx/t/hex", 200, "02aa"), + hosts = ownHosts, + ) + + assertFailsWith { sut.tipHeight() } + assertFailsWith { sut.isTxKnown("t") } + assertEquals(listOf("a.example", "a.example"), requests.map { it.url.host }) + } + + @Test + fun `a host with only the unversioned package path is asked once`() = test { + val sut = chain( + Route("a.example/api/txs/package", 200, """{"package_msg":"success"}"""), + hosts = ownHosts, + ) + + assertEquals(SparkExitBroadcastOutcome.Accepted, sut.broadcast(SparkExitFixtures.tx("n1", cpfp = "03c"))) + assertEquals("/api/txs/package", requests.single().url.encodedPath) + } + + @Test + fun `a broadcast falls back from the first host`() = test { + val sut = chain( + Route("a.example/api/txs/package", 503, ""), + Route("b.example/api/v1/txs/package", 200, """{"package_msg":"success"}"""), + Route("a.example/api/tx", 503, ""), + Route("b.example/api/tx", 200, "s1"), + hosts = ownHosts, + ) + + assertEquals(SparkExitBroadcastOutcome.Accepted, sut.broadcast(SparkExitFixtures.tx("n1", cpfp = "03c"))) + assertEquals(SparkExitBroadcastOutcome.Accepted, sut.broadcastHex("02s1")) + val paths = requests.map { "${it.url.host}${it.url.encodedPath}" } + assertEquals( + listOf("a.example/api/txs/package", "b.example/api/v1/txs/package", "a.example/api/tx", "b.example/api/tx"), + paths, + ) + } + + @Test + fun `mainnet reads bitkit electrs and broadcasts there first`() { + val hosts = checkNotNull(EsploraSparkExitChain.defaultHosts("mainnet")) + + assertEquals(listOf("https://bitkit.to/electrs"), hosts.reads) + assertEquals( + listOf( + SparkExitBroadcastHost("https://bitkit.to/electrs", listOf("/txs/package")), + SparkExitBroadcastHost("https://mempool.space/api", listOf("/v1/txs/package", "/txs/package")), + SparkExitBroadcastHost("https://blockstream.info/api", listOf("/v1/txs/package", "/txs/package")), + ), + hosts.broadcasts, + ) + } + + @Test + fun `regtest reads and broadcasts on the sdk host`() { + val regtest = "https://regtest-mempool.us-west-2.sparkinfra.net/api" + + assertEquals(SparkExitHosts.of(regtest), EsploraSparkExitChain.defaultHosts("regtest")) + assertEquals(null, EsploraSparkExitChain.defaultHosts("signet")) + } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRegtestTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRegtestTest.kt index 09343ca30a..77d3f1f62e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRegtestTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRegtestTest.kt @@ -13,7 +13,7 @@ import kotlin.test.assertTrue * `SPARK_EXIT_REGTEST=1` in the environment of `just test file SparkExitRegtestTest`. */ class SparkExitRegtestTest : BaseUnitTest() { - private val chain = EsploraSparkExitChain(EsploraSparkExitChain.defaultHosts("regtest"), HttpClient()) + private val chain = EsploraSparkExitChain(checkNotNull(EsploraSparkExitChain.defaultHosts("regtest")), HttpClient()) @Before fun requireOptIn() { From a443f006d1618a5bb9f7f32d02ba6cc21df8c92c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 13:27:04 +0100 Subject: [PATCH 008/154] fix: spark exit stays line after a lost leaf --- .../to/bitkit/repositories/SparkExitDriver.kt | 15 ++++++--- .../bitkit/repositories/SparkExitFunding.kt | 31 +++++++++++++---- .../to/bitkit/repositories/SparkExitRepo.kt | 5 ++- .../repositories/SparkExitDriverTest.kt | 15 ++++++--- .../repositories/SparkExitFundingTest.kt | 33 +++++++++++++++++++ 5 files changed, 79 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index eb691cc0c4..573bdd7bcc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -29,26 +29,30 @@ interface SparkExitRecovering { /** * Prepares every leaf the operators list less [lost], the leaves an older state of this wallet claimed on-chain, which * the operators keep listing. A quote that lists one is prepared again for the rest, so its amount, fees and funding - * leave it out, dropping a leaf the SDK refuses to exit; nothing is left to exit when every listed leaf is lost. + * leave it out, dropping a leaf the SDK refuses to exit; nothing is left to exit when every listed leaf is lost. The + * quote carries the values of the lost leaves the operators still list. */ suspend fun SparkExitRecovering.prepareAll( request: PrepareRecoverFundsRequest, lost: Set, -): PrepareRecoverFundsResponse { +): SparkExitQuote { val all = prepare(request.copy(selection = ExitLeafSelection.All)) + val lostLeafSats = all.leaves.filter { it.leafId in lost }.map { it.valueSats } + + all.skipped.filter { it.leafId in lost }.map { it.valueSats } val skipped = all.skipped.filter { it.leafId !in lost } - if (all.leaves.none { it.leafId in lost }) return all.copy(skipped = skipped) + if (all.leaves.none { it.leafId in lost }) return SparkExitQuote(all.copy(skipped = skipped), null, lostLeafSats) var ids = all.leaves.map { it.leafId }.filter { it !in lost } while (ids.isNotEmpty()) { val result = runSuspendCatching { prepare(request.copy(selection = ExitLeafSelection.Specific(ids))) } result.getOrNull()?.let { prepared -> - return prepared.copy(skipped = (prepared.skipped + skipped).distinctBy { it.leafId }) + val withSkipped = prepared.copy(skipped = (prepared.skipped + skipped).distinctBy { it.leafId }) + return SparkExitQuote(withSkipped, null, lostLeafSats) } val error = requireNotNull(result.exceptionOrNull()) val refusal = SparkExitUnexitable.parse(error)?.takeIf { it.leafId in ids } ?: throw error ids = ids - refusal.leafId } - return all.copy( + val nothing = all.copy( leaves = emptyList(), skipped = skipped, recoverableValueSats = 0uL, @@ -60,6 +64,7 @@ suspend fun SparkExitRecovering.prepareAll( sweepFeeSats = 0uL, funding = null, ) + return SparkExitQuote(nothing, null, lostLeafSats) } /** diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index f00fea449b..3a0347f052 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -69,9 +69,14 @@ object SparkExitFundingKey { /** * What an exit costs and returns, from a `prepareRecoverFunds` quote, next to Spark's balance when it was taken - * ([sparkBalanceSats]), so value the quote cannot exit is named rather than silently left out. + * ([sparkBalanceSats]), so value the quote cannot exit is named rather than silently left out. [lostLeafSats] are the + * values of the leaves an older state claimed that the operators still list, which the quote leaves out. */ -data class SparkExitQuote(val prepared: PrepareRecoverFundsResponse, val sparkBalanceSats: ULong? = null) { +data class SparkExitQuote( + val prepared: PrepareRecoverFundsResponse, + val sparkBalanceSats: ULong? = null, + val lostLeafSats: List = emptyList(), +) { /** The value of the leaves the exit takes on-chain. */ val exitSats: ULong get() = prepared.recoverableValueSats @@ -99,11 +104,12 @@ data class SparkExitQuote(val prepared: PrepareRecoverFundsResponse, val sparkBa */ val unexitableSats: ULong? get() = SparkExitMath.unexitableSats(sparkBalanceSats, this) - /** Spark's balance beyond every leaf the quote lists, skipped ones included. */ + /** Spark's balance beyond every leaf the quote lists, skipped ones included, less the lost leaves it holds. */ val beyondLeavesSats: ULong? get() { val leaves = prepared.leaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() } - return SparkExitMath.outsideExitSats(leaves.safe() + leftBehindSats.safe(), sparkBalanceSats) + val beyond = SparkExitMath.outsideExitSats(leaves.safe() + leftBehindSats.safe(), sparkBalanceSats) + return beyond?.let { SparkExitMath.beyondLostLeaves(it, lostLeafSats) }?.takeIf { it > 0uL } } /** Breez's rule: only exit when the value is more than its fees. */ @@ -200,10 +206,21 @@ object SparkExitMath { /** * What Spark's [balanceSats] holds beyond [record]'s leaves, in any phase: what a stopped exit leaves on Spark, - * such as value it could not exit. Lost leaves stay in the leaf total, so they are never claimed to stay. + * such as value it could not exit. Lost leaves count only while the balance still holds them ([beyondLostLeaves]). */ - fun staysOnSparkSats(balanceSats: ULong?, record: SparkExitRecord?): ULong? = - record?.let { outsideExitSats(it.leafTotalSats, balanceSats) } + fun staysOnSparkSats(balanceSats: ULong?, record: SparkExitRecord?): ULong? { + val leafTotal = record?.leafTotalSats ?: return null + val liveLeafTotal = if (leafTotal > record.lostSats) leafTotal - record.lostSats else 0uL + val beyond = outsideExitSats(liveLeafTotal, balanceSats) ?: return null + return beyondLostLeaves(beyond, record.lostLeaves.map { it.valueSats }).takeIf { it > 0uL } + } + + /** + * [sats] less the lost leaves it still holds. Spark's balance keeps a leaf an older state claimed until a later + * sync drops it, so each lost leaf, largest first, is taken out only while what is left still covers it. + */ + fun beyondLostLeaves(sats: ULong, lostLeafSats: List): ULong = + lostLeafSats.sortedDescending().fold(sats) { left, lost -> if (left >= lost) left - lost else left } /** Spark's balance beyond the exit's leaves while it still counts them, or null. */ fun outsideExitSats(leafTotalSats: ULong?, balanceSats: ULong?): ULong? { diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 96d6b33870..a492ceb758 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -348,7 +348,7 @@ class SparkExitRepo @Inject constructor( val destination = _state.value.pending?.destination ?: lightningRepo.newAddress().getOrThrow() // Leaves an earlier exit lost to an older state stay listed by the operators, but cannot be exited. val lost = reportedLostLeafIds() + _state.value.record?.lostLeaves?.map { it.leafId }.orEmpty() - val prepared = recovering.prepareAll( + val quote = recovering.prepareAll( PrepareRecoverFundsRequest( feeRateSatPerVbyte = feeRate, fundingKind = CpfpFundingKind.P2wpkh, @@ -356,8 +356,7 @@ class SparkExitRepo @Inject constructor( selection = ExitLeafSelection.All, ), lost, - ) - val quote = SparkExitQuote(prepared, sparkRepo.state.value.balanceSats) + ).copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) // Chosen here, so the funding screen, the fee estimate and the record all use one address. val fundingIndex = nextFundingIndex() val fundingAddress = fundingKey(fundingIndex).address diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 65b0285ef1..a4bc9fc717 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -839,7 +839,8 @@ class SparkExitDriverTest : BaseUnitTest() { ) sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-1"), skipped = emptyList()) - val prepared = sdk.prepareAll(SparkExitFixtures.prepareRequest(), lost = setOf("lost-1", "lost-2")) + val quote = sdk.prepareAll(SparkExitFixtures.prepareRequest(), lost = setOf("lost-1", "lost-2")) + val prepared = quote.prepared assertEquals(ExitLeafSelection.All, sdk.prepareRequests.first().selection) val selection = assertIs(sdk.prepareRequests.last().selection) @@ -847,30 +848,34 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("leaf-1"), prepared.leaves.map { it.leafId }) assertEquals(9_000uL, prepared.totalFeeSats) assertEquals(listOf(dust), prepared.skipped) + assertEquals(listOf(100_000uL, 65_536uL), quote.lostLeafSats) } @Test fun `a quote with no lost leaf listed is the operators' own`() = test { sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-1")) - val prepared = sdk.prepareAll(SparkExitFixtures.prepareRequest(), lost = setOf("lost-1")) + val quote = sdk.prepareAll(SparkExitFixtures.prepareRequest(), lost = setOf("lost-1")) assertEquals(listOf(ExitLeafSelection.All), sdk.prepareRequests.map { it.selection }) - assertEquals(sdk.preparedResponse, prepared) + assertEquals(sdk.preparedResponse, quote.prepared) + assertEquals(emptyList(), quote.lostLeafSats) } @Test fun `a quote whose every leaf is lost shows nothing to exit`() = test { sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("lost-1")) - val prepared = sdk.prepareAll(SparkExitFixtures.prepareRequest(), lost = setOf("lost-1")) + val quote = sdk.prepareAll(SparkExitFixtures.prepareRequest(), lost = setOf("lost-1")) + val prepared = quote.prepared assertEquals(1, sdk.prepareRequests.size) assertTrue(prepared.leaves.isEmpty()) assertEquals(0uL, prepared.recoverableValueSats) assertEquals(0uL, prepared.totalFeeSats) assertNull(prepared.funding) - assertEquals(SparkExitQuoteBlock.Nothing, SparkExitUiState(quote = SparkExitQuote(prepared)).quoteBlock) + assertEquals(SparkExitQuoteBlock.Nothing, SparkExitUiState(quote = quote).quoteBlock) + assertEquals(listOf(100_000uL), quote.lostLeafSats) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 707be6239b..8221675be2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -2,6 +2,8 @@ package to.bitkit.repositories import breez_sdk_spark.ExitTransactionStatus import breez_sdk_spark.RecoveryTxKind +import breez_sdk_spark.SkippedLeaf +import breez_sdk_spark.SkippedLeafReason import org.junit.Test import org.lightningdevkit.ldknode.Network import kotlin.test.assertContentEquals @@ -260,6 +262,37 @@ class SparkExitFundingTest { assertNull(SparkExitMath.fundingState(record.copy(phase = SparkExitRecord.Phase.Running), seen)) } + /** + * The qa-03 rerun: right after an exit lost a leaf, Spark's balance still counted it for about 10 minutes, and a + * record from before the lost-leaf list also held a leaf the balance had dropped already. + */ + @Test + fun `lost leaves stay out of what stays on spark whether the balance counts them or not`() { + val failed = SparkExitFixtures.record(SparkExitRecord.Phase.Failed("Claimed by an older state")) + val record = failed.copy( + leafTotalSats = 65_536uL, + lostLeaves = listOf(SparkExitRecord.LostLeaf("lost", 65_536uL)), + ) + assertEquals(3_392uL, SparkExitMath.staysOnSparkSats(68_928uL, record), "balance still counts it") + assertEquals(3_392uL, SparkExitMath.staysOnSparkSats(3_392uL, record), "balance synced") + + val older = failed.copy( + leafTotalSats = 131_072uL, + lostLeaves = listOf( + SparkExitRecord.LostLeaf("lost-before", 65_536uL), + SparkExitRecord.LostLeaf("lost", 65_536uL), + ), + ) + assertEquals(3_392uL, SparkExitMath.staysOnSparkSats(68_928uL, older)) + assertEquals(3_392uL, SparkExitMath.staysOnSparkSats(3_392uL, older)) + + val small = SkippedLeaf("small", 3_392uL, SkippedLeafReason.FeeExceedsValue) + val prepared = SparkExitFixtures.prepared(leaves = emptyList(), skipped = listOf(small)) + val quote = SparkExitQuote(prepared, lostLeafSats = listOf(65_536uL, 65_536uL)) + assertEquals(3_392uL, quote.copy(sparkBalanceSats = 68_928uL).unexitableSats) + assertEquals(3_392uL, quote.copy(sparkBalanceSats = 3_392uL).unexitableSats) + } + @Test fun `quote names what it skips and spark's balance beyond every leaf it lists`() { val prepared = SparkExitFixtures.prepared() From 3ca5e875ac039506bd62247e68007982e6b429e7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 16:49:39 +0100 Subject: [PATCH 009/154] fix: keep the spark exit backup from before an exit --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 9 ++++++++- .../java/to/bitkit/repositories/SparkRepoTest.kt | 12 ++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index a907433ce0..ce52fd5119 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -488,11 +488,18 @@ class SparkRepo @Inject constructor( ) } - /** The exit data backup, or null while Spark is not connected and there is nothing to back up. */ + /** + * The exit data backup, or null while Spark is not connected and there is nothing to back up. Also null while an + * emergency exit runs: the operators stop reporting the leaves it moves, so the backup from before it is kept. + */ suspend fun exitBackup(): Result = withContext(bgDispatcher) { runSuspendCatching { val network = sparkService.networkName if (!sparkService.isConnected || network == null) return@runSuspendCatching null + if (_state.value.isExiting || exitStore(walletIndex).isActive()) { + Logger.info("Skipped the Spark exit data backup while an exit runs", context = TAG) + return@runSuspendCatching null + } SparkExitBackupV1(createdAt = nowMillis(), network = network, exitState = sparkService.exportExitState()) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index da525bce67..e22e0f7dce 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -232,6 +232,18 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(listOf(SparkWithdrawal("withdrawal", 128uL, 1_470uL)), sut.state.value.withdrawals) } + @Test + fun `keeps the exit data backup from before an exit while it runs`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.exportExitState() }.thenReturn("state") + val sut = createSut() + assertEquals("state", sut.exitBackup().getOrThrow()?.exitState) + + SparkExitStore(File(Env.sparkExitRecordPath(0))).save(SparkExitFixtures.record()) + + assertNull(sut.exitBackup().getOrThrow()) + } + @Test fun `skips an exit backup from another network`() = test { val sut = createSut() From f2c6f1622e2be69ceb6858171fe81ec75a13af94 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 16:49:39 +0100 Subject: [PATCH 010/154] fix: open the spark exit from its notification --- app/src/main/java/to/bitkit/ui/ContentView.kt | 10 ++++++++++ app/src/main/java/to/bitkit/ui/MainActivity.kt | 4 ++++ app/src/main/java/to/bitkit/ui/Notifications.kt | 1 + .../main/java/to/bitkit/viewmodels/AppViewModel.kt | 14 ++++++++++++++ 4 files changed, 29 insertions(+) diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 911d7c5071..433e98811d 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -393,6 +393,16 @@ fun ContentView( } } + val isSparkExitRequested by appViewModel.isSparkExitRequested.collectAsStateWithLifecycle() + LaunchedEffect(isSparkExitRequested) { + if (!isSparkExitRequested) return@LaunchedEffect + // Waits for the navigation graph, which a cold start from the notification sets up only after this runs. + navController.currentBackStackEntryFlow.first() + val showsResult = appViewModel.onSparkExitOpened() + // Inside the connections graph, so the exit screens find their shared view model and Done goes back to Spark. + navController.navigateTo(Routes.SparkDetail) + if (showsResult) navController.navigateTo(Routes.SparkExitProgress) + } LaunchedEffect(appViewModel) { appViewModel.mainScreenEffect.collect { when (it) { diff --git a/app/src/main/java/to/bitkit/ui/MainActivity.kt b/app/src/main/java/to/bitkit/ui/MainActivity.kt index cf0fe8b3eb..34e6cb4632 100644 --- a/app/src/main/java/to/bitkit/ui/MainActivity.kt +++ b/app/src/main/java/to/bitkit/ui/MainActivity.kt @@ -288,6 +288,10 @@ class MainActivity : FragmentActivity() { } private fun handleLaunchIntent(intent: Intent) { + if (intent.getBooleanExtra(EXTRA_SPARK_EXIT, false)) { + intent.removeExtra(EXTRA_SPARK_EXIT) + appViewModel.onSparkExitNotificationTapped() + } if (intent.getBooleanExtra(EXTRA_PAYKIT_SUBSCRIPTION_PAYMENT_DUE, false)) { intent.removeExtra(EXTRA_PAYKIT_SUBSCRIPTION_PAYMENT_DUE) appViewModel.onPaykitSubscriptionNotificationTapped( diff --git a/app/src/main/java/to/bitkit/ui/Notifications.kt b/app/src/main/java/to/bitkit/ui/Notifications.kt index f04ae82195..1615e2638b 100644 --- a/app/src/main/java/to/bitkit/ui/Notifications.kt +++ b/app/src/main/java/to/bitkit/ui/Notifications.kt @@ -31,6 +31,7 @@ const val EXTRA_PAYKIT_PAYER_IDENTITY = "paykit_payer_identity" const val EXTRA_PAYKIT_PAYMENT_REQUEST_ID = "paykit_payment_request_id" const val EXTRA_PAYKIT_COUNTERPARTY = "paykit_counterparty" const val EXTRA_PAYKIT_BILLING_PERIOD_STARTS_AT = "paykit_billing_period_starts_at" +const val EXTRA_SPARK_EXIT = "spark_exit" val Context.CHANNEL_MAIN get() = getString(R.string.app_notifications_channel_id) diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 0006a43f36..8be9f44258 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -1412,6 +1412,20 @@ class AppViewModel @Inject constructor( isPaymentRequestPollingStopped.value || privatePaykitRepo.isProfileDeletionInProgress.value /** Drives a Spark emergency exit every minute while Bitkit is in the foreground. */ + private val _isSparkExitRequested = MutableStateFlow(false) + + /** An emergency exit notification was tapped; kept until the UI opens the exit, so a cold start keeps it. */ + val isSparkExitRequested = _isSparkExitRequested.asStateFlow() + + fun onSparkExitNotificationTapped() = _isSparkExitRequested.update { true } + + /** Clears the tapped notification and says whether the exit opens on its progress rather than a new exit. */ + suspend fun onSparkExitOpened(): Boolean { + _isSparkExitRequested.update { false } + sparkExitRepo.load() + return sparkExitRepo.state.value.showsResult + } + fun startSparkExitDriving() = sparkExitRepo.onAppForegrounded() fun stopSparkExitDriving() = sparkExitRepo.onAppBackgrounded() From 4f74ed11ca15e7a6ecebb4ea63880577e48019e2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 16:49:39 +0100 Subject: [PATCH 011/154] fix: spark exit rebuilds when it stops moving --- .../to/bitkit/repositories/SparkExitChain.kt | 9 + .../to/bitkit/repositories/SparkExitDriver.kt | 319 ++++++++++++-- .../bitkit/repositories/SparkExitFunding.kt | 125 +++++- .../to/bitkit/repositories/SparkExitRecord.kt | 271 ++++++++++-- .../to/bitkit/repositories/SparkExitRepo.kt | 27 +- .../to/bitkit/repositories/SparkExitWorker.kt | 44 +- .../java/to/bitkit/services/SparkService.kt | 6 + .../lightning/SparkExitProgressScreen.kt | 58 ++- .../settings/lightning/SparkExitViewModel.kt | 29 ++ app/src/main/res/values-ar/strings.xml | 8 +- app/src/main/res/values-b+es+419/strings.xml | 8 +- app/src/main/res/values-ca/strings.xml | 8 +- app/src/main/res/values-cs/strings.xml | 8 +- app/src/main/res/values-de/strings.xml | 8 +- app/src/main/res/values-el/strings.xml | 8 +- app/src/main/res/values-es-rES/strings.xml | 8 +- app/src/main/res/values-es/strings.xml | 8 +- app/src/main/res/values-fr/strings.xml | 8 +- app/src/main/res/values-it/strings.xml | 8 +- app/src/main/res/values-nl/strings.xml | 8 +- app/src/main/res/values-pl/strings.xml | 8 +- app/src/main/res/values-pt-rBR/strings.xml | 8 +- app/src/main/res/values-pt/strings.xml | 8 +- app/src/main/res/values-ru/strings.xml | 8 +- app/src/main/res/values/strings.xml | 8 +- .../repositories/SparkExitDriverTest.kt | 401 ++++++++++++++++-- .../bitkit/repositories/SparkExitFixtures.kt | 17 + .../repositories/SparkExitFundingTest.kt | 120 +++++- .../repositories/SparkExitRecordTest.kt | 88 +++- .../bitkit/repositories/SparkExitRepoTest.kt | 25 +- 30 files changed, 1508 insertions(+), 159 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 4ac5a09373..4b4bd7b726 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -24,6 +24,7 @@ import kotlinx.serialization.json.longOrNull import to.bitkit.env.Env import to.bitkit.ext.runSuspendCatching import to.bitkit.utils.AppError +import kotlin.math.ceil data class EsploraTxStatus(val confirmed: Boolean, val blockHeight: UInt? = null) @@ -76,6 +77,9 @@ interface SparkExitChain { /** A transaction of the app's own, such as the sweep of leftover fee funding, as a single `/tx`. */ suspend fun broadcastHex(hex: String): SparkExitBroadcastOutcome + + /** The rate for the next block, from `/fee-estimates`, rounded up. */ + suspend fun nextBlockFeeRate(): ULong } class SparkExitChainError(message: String) : AppError(message) @@ -143,6 +147,11 @@ class EsploraSparkExitChain( override suspend fun txStatus(txid: String): EsploraTxStatus = status(json.parseToJsonElement(get("/tx/$txid/status")).jsonObject) + override suspend fun nextBlockFeeRate(): ULong { + val rate = json.parseToJsonElement(get("/fee-estimates")).jsonObject.getValue("1").jsonPrimitive.content + return ceil(rate.toDouble()).toULong() + } + override suspend fun isTxKnown(txid: String): Boolean { if (hosts.reads.isEmpty()) throw SparkExitChainError("No chain host configured") val path = "/tx/$txid/hex" diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 573bdd7bcc..77af785355 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -10,8 +10,10 @@ import breez_sdk_spark.PrepareRecoverFundsResponse import breez_sdk_spark.RecoverFundsRequest import breez_sdk_spark.RecoverFundsResponse import breez_sdk_spark.RecoveryTransaction +import breez_sdk_spark.RecoveryTxKind import breez_sdk_spark.RecoveryVerdict import breez_sdk_spark.SdkException +import breez_sdk_spark.SkippedLeaf import breez_sdk_spark.SkippedLeafReason import to.bitkit.ext.runSuspendCatching import to.bitkit.models.safe @@ -24,6 +26,12 @@ interface SparkExitRecovering { suspend fun prepare(request: PrepareRecoverFundsRequest): PrepareRecoverFundsResponse suspend fun recover(request: RecoverFundsRequest, signer: CpfpSigner?): RecoverFundsResponse suspend fun check(recovery: RecoverFundsResponse): CheckRecoverFundsResponse + + /** The SDK's exit data, as `exportUnilateralExitState` gives it. */ + suspend fun exportExitState(): String + + /** Merges exit data from [exportExitState] back in; an older one never costs the wallet a leaf. */ + suspend fun importExitState(exitState: String) } /** @@ -82,6 +90,8 @@ class SparkExitDriver( private val makeSigner: suspend () -> CpfpSigner, private val save: (SparkExitRecord) -> Unit, private val nowMillis: () -> Long, + /** The chain tip this tick, null when it could not be read. */ + private val tip: UInt? = null, ) { companion object { private const val TAG = "SparkExitDriver" @@ -89,12 +99,18 @@ class SparkExitDriver( /** A ready transaction accepted in this generation is sent again after this long, in case a node dropped it. */ val REBROADCAST_INTERVAL = 10.minutes - /** After this many rejections of one transaction the progress screen shows the error. */ + /** After this many rejections of one transaction the exit rebuilds over it, as over a broken chain. */ const val REJECTIONS_TO_SURFACE = 3 - /** After this many unpaid sends in a row of a step whose parents confirmed, the exit rebuilds once for it. */ + /** After this many unpaid sends in a row of a step whose parents confirmed, the exit rebuilds over it. */ const val FEE_CHAIN_FAILURES_TO_REBUILD = 3 + /** Rebuilds over a broken chain with no step confirming in between, before the exit says it is not moving. */ + const val STALL_REBUILDS_TO_SURFACE = 3 + + /** Blocks an unconfirmed leftover sweep waits before it is replaced at a higher rate, about a day. */ + const val SWEEP_REPLACE_BLOCKS = 144u + /** The least time between two builds, so a divergence that persists does not rebuild every tick. */ val REBUILD_INTERVAL = 10.minutes @@ -129,7 +145,10 @@ class SparkExitDriver( record = recovering?.let { check(record, it) } ?: broadcastWithoutSdk(record) } } - record = record.copy(claimableAtHeight = record.recovery?.let(SparkExitMath::claimableAtHeight)) + // Without a tip the countdown keeps its last value rather than jump to another rule. + if (tip != null) { + record = record.copy(claimableAtHeight = record.recovery?.let { SparkExitMath.claimableAtHeight(it, tip) }) + } // The tick that ends the exit also sends its leftover fee funding to savings. if (record.isLeftoverSweepPending) record = sweepLeftover(record) save(record) @@ -143,14 +162,24 @@ class SparkExitDriver( private suspend fun adoptFunding(record: SparkExitRecord, requiredSats: ULong): SparkExitRecord? { val first = record.funding.firstOrNull() ?: return null val candidates = SparkExitMath.newFunding(chain.utxos(first.address), record) - val utxos = SparkExitMath.fundingTopUp(candidates, requiredSats) ?: return null + val inputFee = SparkExitMath.inputFeeSats(record.feeRateSatPerVbyte) + val utxos = SparkExitMath.fundingTopUp(candidates, requiredSats, inputFee) ?: return null val adopted = utxos.map { first.copy(txid = it.txid, vout = it.vout, valueSats = it.value) } val funding = if (record.funding.size == 1 && first.txid == null) adopted else record.funding + adopted return record.copy(funding = funding) } private suspend fun build(start: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { - val (record, prepared) = prepare(start, sdk) + // A build waiting for a leaf that may still move tries again only at its paced heights, or once its wait ends. + val since = start.retrySince + if (since != null && tip != null && !SparkExitMath.isRetryDue(since, start.retriedAt, tip) && + !SparkExitMath.isRetryReleased(since, tip) + ) { + return start + } + val (preparedRecord, prepared) = prepare(withExitState(start, sdk), sdk) + val stopped = prepared?.exitChainState?.stoppedLeafIds.orEmpty().toSet() + val record = preparedRecord.seeStopped(stopped) if (prepared == null) { // The last leaf lost on a tick that could not read the funding address ends here, still as lost. val reason = if (record.isEveryLeafLost) LOST_REASON else NO_LEAF_REASON @@ -158,8 +187,12 @@ class SparkExitDriver( return end(failed, record) } if (prepared.leaves.isEmpty()) { - // A leaf the chain could not be read for comes back on a later tick; finished leaves are not listed. - if (prepared.skipped.any { it.reason == SkippedLeafReason.Unverified }) return record + // A leaf that may still move, such as one the chain could not be read for, is waited for, about a week at + // most; finished leaves are not listed. + if (isWaiting(record, prepared.skipped, stopped)) { + Logger.info("Waiting for Spark exit leaves that may still move", context = TAG) + return record.copy(retrySince = record.retrySince ?: tip, retriedAt = tip ?: record.retriedAt) + } val ended = record.copy( skippedLeafCount = maxOf(record.skippedLeafCount, prepared.skipped.size), phase = if (record.recovery == null) { @@ -190,7 +223,8 @@ class SparkExitDriver( val held = record.funding.firstOrNull()?.address?.let { address -> runSuspendCatching { chain.utxos(address) }.getOrNull()?.let { SparkExitMath.heldSats(it, record) } } - val needed = SparkExitMath.neededFunding(it.requiredSats, record.fundedSats, held) + val inputFee = SparkExitMath.inputFeeSats(record.feeRateSatPerVbyte) + val needed = SparkExitMath.neededFunding(it.requiredSats, record.fundedSats, held, inputFee) return record.copy(phase = SparkExitRecord.Phase.NeedsFunding(needed)) } if (built.transactions.isEmpty()) { @@ -198,7 +232,8 @@ class SparkExitDriver( if (built.failed.isNotEmpty()) return record.copy(failedLeafCount = built.failed.size) return end(record.copy(phase = SparkExitRecord.Phase.Failed("Nothing to recover")), record) } - val lost = record.lostLeaves(built) + // A leaf the operators' watchtower stopped is waited for, not struck, until its wait is over. + val lost = record.lostLeaves(built).filter { !isStoppedWaiting(record, it.leafId, stopped) } if (lost.isNotEmpty()) return loseLeaves(record, lost) val adopted = record.adopt(built, nowMillis()) // Saved before any of it is broadcast, so a crash never leaves broadcast transactions without their record. @@ -210,6 +245,59 @@ class SparkExitDriver( return broadcastReady(adopted) } + /** + * Before the first build, keeps the SDK's exit data as it is now, which still holds every leaf of the exit; before + * every later build, imports it again, so a backup or sync since cannot have dropped a leaf the rebuild needs. + * A failure is logged and the build goes on. + */ + private suspend fun withExitState(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { + record.exitStateSnapshot?.let { snapshot -> + runSuspendCatching { sdk.importExitState(snapshot) } + .onFailure { Logger.warn("Failed to import the Spark exit data snapshot", it, context = TAG) } + return record + } + // A salvaged record rebuilds from what the SDK holds now; a fresh export would not hold more. + if (record.recovery != null || record.generation > 0 || record.isRebuiltFromChain) return record + val exported = runSuspendCatching { sdk.exportExitState() } + .onFailure { Logger.warn("Failed to export the Spark exit data snapshot", it, context = TAG) } + .getOrNull() + ?: return record + return record.copy(exitStateSnapshot = exported) + } + + /** Dates at this tip each of the exit's leaves the operators' watchtower stopped that was not seen stopped yet. */ + private fun SparkExitRecord.seeStopped(stopped: Set): SparkExitRecord { + val height = tip ?: return this + val fresh = stopped.filter { it in leafIds && it !in stoppedLeafSince } + if (fresh.isEmpty()) return this + return copy(stoppedLeafSince = stoppedLeafSince + fresh.associateWith { height }) + } + + /** [leafId] was stopped by the operators' watchtower fewer than six blocks ago, or its age is unknown. */ + private fun isStoppedWaiting(record: SparkExitRecord, leafId: String, stopped: Set): Boolean { + if (leafId !in stopped) return false + val since = record.stoppedLeafSince[leafId] ?: return true + val height = tip ?: return true + return height < since || height - since < SparkExitMath.STOPPED_BLOCKS + } + + /** + * An empty build waits while one of the exit's leaves was skipped for a reason that may yet change: the chain + * could not be read for it, its funds were not found yet, or the operators' watchtower stopped it a short while + * ago. Not after about a week of waiting. + */ + private fun isWaiting(record: SparkExitRecord, skipped: List, stopped: Set): Boolean { + val since = record.retrySince + if (since != null && tip != null && SparkExitMath.isRetryReleased(since, tip)) return false + return skipped.any { + it.leafId in record.exitLeafIds && when (it.reason) { + SkippedLeafReason.Unverified, SkippedLeafReason.FundsNotFound -> true + is SkippedLeafReason.NotRecoverable -> isStoppedWaiting(record, it.leafId, stopped) + SkippedLeafReason.FeeExceedsValue -> false + } + } + } + private fun prepareRequest(record: SparkExitRecord, selection: ExitLeafSelection) = PrepareRecoverFundsRequest( feeRateSatPerVbyte = record.feeRateSatPerVbyte, fundingKind = CpfpFundingKind.P2wpkh, @@ -268,23 +356,33 @@ class SparkExitDriver( val stored = record.recovery ?: return record.copy(phase = SparkExitRecord.Phase.AwaitingFunding(0uL)) val checked = sdk.check(withConfirmations(stored)) Logger.debug("Checked Spark exit generation '${record.generation}': '${checked.verdict}'", context = TAG) - val updated = record.copy(recovery = checked.recovery) + val updated = record.copy(recovery = checked.recovery).withProgress(checked.recovery) return when (checked.verdict) { RecoveryVerdict.Valid -> { val confirmed = checked.recovery.transactions .filter { it.status is ExitTransactionStatus.Confirmed } .map { it.txid } .toSet() - val dead = deadChildren(stored) { it in confirmed } - if (dead.isNotEmpty()) { - // The SDK still calls it valid, but the steps that spend a dead child's change can never confirm. - Logger.warn("Rebuilding Spark exit whose CPFP children '$dead' lost a race", context = TAG) - return rebuild(updated, sdk) + if (!updated.isStalled) { + val dead = deadChildren(stored) { it in confirmed } + if (dead.isNotEmpty()) { + // The SDK still calls it valid, but the steps that spend a dead child's change never confirm. + Logger.warn("Rebuilding Spark exit whose CPFP children '$dead' lost a race", context = TAG) + return stallRebuild(updated, sdk) + } } val sent = broadcastReady(updated) - val stuck = stuckStep(sent) ?: return sent - Logger.warn("Rebuilding Spark exit once for step '$stuck' whose fee went unpaid", context = TAG) - rebuild(sent.copy(feeChainRebuildTxids = sent.feeChainRebuildTxids + stuck), sdk) + val stuck = sent.stuckStep + if (stuck != null && !sent.isStalled) { + Logger.warn("Rebuilding Spark exit over step '${stuck.txid}' that keeps failing", context = TAG) + return stallRebuild(sent, sdk) + } + if (!needsUnverifiedRebuild(sent)) return sent + // A check cannot settle a step the SDK could not read; a fresh build reads the chain again. + Logger.info("Rebuilding Spark exit over steps the SDK could not read", context = TAG) + val rebuilding = sent.copy(isRebuilding = true, unverifiedRebuiltAtHeight = tip, isRedoRebuild = false) + save(rebuilding) + build(rebuilding, sdk) } RecoveryVerdict.Done -> end(updated.copy(phase = SparkExitRecord.Phase.Done), updated) is RecoveryVerdict.Redo -> { @@ -292,7 +390,8 @@ class SparkExitDriver( "Rebuilding Spark exit diverged on-chain as generation '${record.generation + 1}'", context = TAG, ) - rebuild(updated, sdk) + // Only a rebuild over a diverged chain can find a leaf an older state claimed. + rebuild(updated.copy(isRedoRebuild = true), sdk) } } } @@ -308,12 +407,38 @@ class SparkExitDriver( return build(rebuilding, sdk) } - /** A step of this generation whose fee went unpaid too many times in a row, and that has not rebuilt yet. */ - private fun stuckStep(record: SparkExitRecord): String? = record.broadcastLog.firstOrNull { - it.generation == record.generation && - it.feeChainFailures >= FEE_CHAIN_FAILURES_TO_REBUILD && - it.txid !in record.feeChainRebuildTxids - }?.txid + /** + * Rebuilds over a broken chain, counting the rebuild: one more with no step confirmed since the last, and at + * [STALL_REBUILDS_TO_SURFACE] the exit stops rebuilding and says it is not moving. + */ + private suspend fun stallRebuild(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { + val confirmed = record.recovery?.let(SparkExitMath::confirmedCount) ?: 0 + val counted = record.copy( + stallRebuilds = record.stallRebuilds + 1, + stallConfirmedCount = confirmed, + isRedoRebuild = false, + ) + return rebuild(counted, sdk) + } + + /** A step confirmed since the last rebuild over a broken chain: the exit moves, so the count starts over. */ + private fun SparkExitRecord.withProgress(checked: RecoverFundsResponse): SparkExitRecord { + val since = stallConfirmedCount ?: return this + if (SparkExitMath.confirmedCount(checked) <= since) return this + return copy(stallRebuilds = 0, stallConfirmedCount = null) + } + + /** + * A unilateral step the SDK could not read waits for a rebuild, once a block, and only once no unilateral step is + * ready: a rebuild then would conflict with what is in the mempool at the same rate. + */ + private fun needsUnverifiedRebuild(record: SparkExitRecord): Boolean { + val height = tip ?: return false + if (record.unverifiedRebuiltAtHeight == height) return false + val transactions = record.recovery?.transactions.orEmpty().filter { it.kind != RecoveryTxKind.COOPERATIVE } + return transactions.any { it.status == ExitTransactionStatus.Unverified } && + transactions.none { it.status == ExitTransactionStatus.Ready } + } /** * Our CPFP children that can never confirm, and every child that spends their change. A wallet whose leaves share @@ -365,14 +490,20 @@ class SparkExitDriver( /** * Sends what the ended exit left at its funding address to [SparkExitRecord.destination] in one transaction, once * every UTXO there confirmed, at the exit's fee rate. Built and saved before it is sent, then sent again each tick - * until a node accepts it; not after a rejection. Dust is not sent. + * until it confirms. A refusal for its fee builds it again at the next block's rate, as does a day unconfirmed, + * which replaces it; any other refusal is final. Dust is not sent. */ private suspend fun sweepLeftover(record: SparkExitRecord): SparkExitRecord { val built = record.leftoverSweep if (built?.txHex != null) { - if (built.isAccepted) { - val status = runSuspendCatching { chain.txStatus(requireNotNull(built.txid)) }.getOrNull() - if (status?.confirmed == true) return record.copy(leftoverSweep = built.copy(isConfirmed = true)) + // The sweep, or a version it replaced, confirmed. + val sent = listOfNotNull(built.txid.takeIf { built.isAccepted }) + built.replacedTxids + if (sent.any { isConfirmed(it) }) return record.copy(leftoverSweep = built.copy(isConfirmed = true)) + val sentAt = built.sentAtHeight + val isOverdue = built.isAccepted && sentAt != null && tip != null && tip >= sentAt + SWEEP_REPLACE_BLOCKS + if (isOverdue || built.isFeeRejection) { + val replaced = replaceSweep(record, built) + if (replaced != null || built.isFeeRejection) return replaced ?: record } // Sent again until it confirms; a node that already has it accepts it again. return sendSweep(record, built, built.txHex) @@ -382,17 +513,64 @@ class SparkExitDriver( if (utxos.isEmpty()) return record.copy(leftover = emptyList()) if (utxos.any { !it.status.confirmed }) return record val inputs = utxos.map { SparkExitSweep.Input(it.txid, it.vout, it.value) } - val total = utxos.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } - val plan = runSuspendCatching { SparkExitSweep.plan(inputs, record.destination, record.feeRateSatPerVbyte) } + val current = record.copy(leftover = utxos.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) }) + return buildSweep(current, inputs, record.feeRateSatPerVbyte) + } + + /** + * [old] built again from the same inputs at the next block's rate, at least one above its own so nodes take it + * as a replacement; null while the rate or the inputs cannot be read. + */ + private suspend fun replaceSweep(record: SparkExitRecord, old: SparkExitRecord.LeftoverSweep): SparkExitRecord? { + val hex = old.txHex ?: return null + val nextBlock = runSuspendCatching { chain.nextBlockFeeRate() } + .onFailure { Logger.warn("Failed to read the Spark exit leftover sweep fee rate", it, context = TAG) } + .getOrNull() + ?: return null + val rate = maxOf(nextBlock, (old.feeRateSatPerVbyte ?: record.feeRateSatPerVbyte) + 1uL) + val values = record.leftover.associate { "${it.txid}:${it.vout}" to it.valueSats } + val inputs = SparkExitTxInputs.decode(hex)?.map { + SparkExitSweep.Input(it.prevTxid, it.vout, values["${it.prevTxid}:${it.vout}"] ?: return null) + } ?: return null + Logger.info("Replacing Spark exit leftover sweep '${old.txid}' at '$rate' sat/vB", context = TAG) + // A sweep a node accepted may still confirm, so its txid is kept to look for. + val replaced = old.replacedTxids + listOfNotNull(old.txid.takeIf { old.isAccepted }) + return buildSweep(record, inputs, rate, replaced) + } + + private fun dustSweep(totalSats: ULong) = SparkExitRecord.LeftoverSweep(null, null, totalSats) + + private suspend fun isConfirmed(txid: String): Boolean = + runSuspendCatching { chain.txStatus(txid) }.getOrNull()?.confirmed == true + + /** + * Builds, saves and sends the sweep of [inputs] at [feeRate]. A replacement of a sweep a node accepted, the [replaced] + * txids given, that would be dust is not built: the earlier one stays. + */ + private suspend fun buildSweep( + record: SparkExitRecord, + inputs: List, + feeRate: ULong, + replaced: List? = null, + ): SparkExitRecord { + val address = record.funding.firstOrNull()?.address ?: return record + val total = inputs.fold(0uL) { sum, input -> sum.safe() + input.valueSats.safe() } + val plan = runSuspendCatching { SparkExitSweep.plan(inputs, record.destination, feeRate) } .getOrElse { Logger.error("Failed to plan the Spark exit leftover sweep", it, context = TAG) return record } - ?: return record.copy(leftoverSweep = SparkExitRecord.LeftoverSweep(null, null, total)) + ?: return if (!replaced.isNullOrEmpty()) record else record.copy(leftoverSweep = dustSweep(total)) val sweep = runSuspendCatching { val signed = makeSigner().signPsbt(SparkExitSweep.psbt(plan, address)) val hex = SparkExitSweep.signedTxHex(plan, signed) - SparkExitRecord.LeftoverSweep(SignedTransactionId.fromHex(hex), hex, plan.amountSats) + SparkExitRecord.LeftoverSweep( + txid = SignedTransactionId.fromHex(hex), + txHex = hex, + valueSats = plan.amountSats, + feeRateSatPerVbyte = feeRate.takeIf { it != record.feeRateSatPerVbyte }, + replacedTxids = replaced.orEmpty(), + ) }.getOrElse { Logger.error("Failed to build the Spark exit leftover sweep", it, context = TAG) return record @@ -411,11 +589,19 @@ class SparkExitDriver( val outcome = chain.broadcastHex(hex) Logger.info("Broadcast Spark exit leftover sweep '${sweep.txid}': '${outcome.summary}'", context = TAG) return when (outcome) { - SparkExitBroadcastOutcome.Accepted -> record.copy(leftoverSweep = sweep.copy(isAccepted = true)) - is SparkExitBroadcastOutcome.Rejected -> record.copy(leftoverSweep = sweep.copy(rejection = outcome.reason)) + SparkExitBroadcastOutcome.Accepted -> record.copy( + leftoverSweep = sweep.copy( + isAccepted = true, + rejection = null, + sentAtHeight = sweep.sentAtHeight ?: tip + ), + ) + is SparkExitBroadcastOutcome.Rejected -> record.copy( + leftoverSweep = sweep.copy(isAccepted = false, rejection = outcome.reason), + ) + is SparkExitBroadcastOutcome.InputsMissing, is SparkExitBroadcastOutcome.RetryLater, is SparkExitBroadcastOutcome.NotMature, - is SparkExitBroadcastOutcome.InputsMissing, -> record } } @@ -444,9 +630,10 @@ class SparkExitDriver( private suspend fun broadcastReady(record: SparkExitRecord): SparkExitRecord { var current = record val recovery = current.recovery ?: return current - // Unverified: the SDK could not read its parent from the chain; nodes refuse it harmlessly if it is not final. + // A cooperative step the SDK could not read goes out too: nodes refuse it if its funds already moved. A + // unilateral one waits for a rebuild. recovery.transactions - .filter { it.status == ExitTransactionStatus.Ready || it.status == ExitTransactionStatus.Unverified } + .filter { it.status == ExitTransactionStatus.Ready || it.isCooperativeUnverified } .filter { isDue(it.txid, current) } // A ready step's parents are confirmed, as the SDK saw them. .forEach { @@ -535,9 +722,8 @@ class SparkExitDriver( val isStuck = parentsConfirmed && (isUnpaid || outcome is SparkExitBroadcastOutcome.InputsMissing) Logger.info("Broadcast Spark exit '${tx.kind}' '${tx.txid}': '${outcome.summary}'", context = TAG) val isAccepted = outcome == SparkExitBroadcastOutcome.Accepted - // Unpaid counts as a rejection only once the step had its rebuild, so an underpriced exit still surfaces. - val isRejected = outcome is SparkExitBroadcastOutcome.Rejected && - (!isUnpaid || tx.txid in record.feeChainRebuildTxids) + // An unpaid step is a broken fee chain, never a rejection. + val isRejected = outcome is SparkExitBroadcastOutcome.Rejected && !isUnpaid val rejection = if (isRejected) 1 else 0 val existing = record.broadcastLog.firstOrNull { it.generation == record.generation && it.txid == tx.txid } val entry = existing?.copy( @@ -548,6 +734,7 @@ class SparkExitDriver( isAccepted = isAccepted, isInputSpent = existing.isInputSpent || isInputSpent, feeChainFailures = if (isStuck) existing.feeChainFailures + 1 else 0, + acceptedAtHeight = if (isAccepted) existing.acceptedAtHeight ?: tip else null, ) ?: SparkExitRecord.BroadcastAttempt( generation = record.generation, txid = tx.txid, @@ -558,6 +745,7 @@ class SparkExitDriver( isAccepted = isAccepted, isInputSpent = isInputSpent, feeChainFailures = if (isStuck) 1 else 0, + acceptedAtHeight = if (isAccepted) tip else null, ) val log = if (existing == null) { record.broadcastLog + entry @@ -568,11 +756,20 @@ class SparkExitDriver( } } -/** The rejection to show on the progress screen once a transaction was refused several times. */ +/** + * What the progress screen shows once rebuilding over a broken chain stopped moving the exit: the last answer of the + * step that keeps failing, else of any step of the generation, else empty. Null while the exit moves or still rebuilds. + */ val SparkExitRecord.surfacedRejection: String? - get() = broadcastLog.firstOrNull { - it.generation == generation && it.rejections >= SparkExitDriver.REJECTIONS_TO_SURFACE && !it.isAccepted - }?.lastOutcome + get() { + if (!isStalled) return null + val refused = broadcastLog.lastOrNull { it.generation == generation && !it.isAccepted } + val last = broadcastLog.lastOrNull { it.generation == generation } + return (stuckStep ?: refused ?: last)?.lastOutcome.orEmpty() + } + +private val RecoveryTransaction.isCooperativeUnverified: Boolean + get() = status == ExitTransactionStatus.Unverified && kind == RecoveryTxKind.COOPERATIVE /** * A step of this generation went unpaid too many times in a row. Without the SDK nothing rebuilds it and it counts no @@ -685,3 +882,35 @@ object SparkExitTxInputs { } }.getOrNull() } + +/** The outputs of a raw transaction, for what an exit paid to savings. */ +object SparkExitTxOutputs { + class Output(val valueSats: ULong, val script: ByteArray) + + /** The outputs, or null when [hex] is not a transaction. */ + fun decode(hex: String): List? = runCatching { + val bytes = hex.hexToByteArray() + var offset = 0 + fun take(length: Int): ByteArray { + require(length >= 0 && offset + length <= bytes.size) + return bytes.copyOfRange(offset, offset + length).also { offset += length } + } + fun le( + length: Int + ): Long = take(length).foldIndexed(0L) { i, sum, b -> sum or ((b.toLong() and 0xff) shl (8 * i)) } + fun compactSize(): Int = when (val prefix = le(1).toInt()) { + 0xfd -> le(2).toInt() + 0xfe -> le(4).toInt() + 0xff -> error("Too many items") + else -> prefix + } + take(4) + if (bytes[offset] == 0.toByte()) take(2) + repeat(compactSize()) { + take(36) + take(compactSize()) + take(4) + } + List(compactSize()) { Output(le(8).toULong(), take(compactSize())) } + }.getOrNull() +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 3a0347f052..f2d511f979 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -122,10 +122,80 @@ object SparkExitMath { private val BLOCK_TIME = 10.minutes - /** The countdown target: the latest block at which a timelocked step of the exit can confirm. */ - fun claimableAtHeight(recovery: RecoverFundsResponse): UInt? = recovery.transactions - .mapNotNull { (it.status as? ExitTransactionStatus.WaitingForTimelock)?.spendableAtHeight } - .maxOrNull() + /** + * The countdown target: [tip] plus [blocksToFinish], so it does not jump as steps confirm. Without a tip, the + * latest block at which a step already waiting for its timelock can confirm. + */ + fun claimableAtHeight(recovery: RecoverFundsResponse, tip: UInt? = null): UInt? { + if (tip != null) return blocksToFinish(recovery.transactions, tip)?.let { tip + it } + return recovery.transactions + .mapNotNull { (it.status as? ExitTransactionStatus.WaitingForTimelock)?.spendableAtHeight } + .maxOrNull() + } + + /** + * Blocks until the last step can confirm: the longest dependency path left, each step costing its remaining + * timelock plus a block to confirm in. A ready step's timelock is behind it; one waiting for its timelock counts + * down from the height the SDK gave; one not started yet waits its whole relative timelock after its parents. + * Null once every step confirmed. + */ + fun blocksToFinish(transactions: List, tip: UInt): UInt? { + val byTxid = transactions.associateBy { it.txid } + val memo = mutableMapOf() + fun after(tx: RecoveryTransaction, depth: Int): UInt = memo.getOrPut(tx.txid) { + val status = tx.status + if (status is ExitTransactionStatus.Confirmed || depth > transactions.size) return@getOrPut 0u + val timelock = when (status) { + ExitTransactionStatus.Ready -> 0u + is ExitTransactionStatus.WaitingForTimelock -> + status.spendableAtHeight?.let { if (it > tip) it - tip else 0u } ?: tx.csvTimelockBlocks ?: 0u + else -> tx.csvTimelockBlocks ?: 0u + } + val waits = tx.dependsOn.mapNotNull { byTxid[it] }.maxOfOrNull { after(it, depth + 1) } ?: 0u + waits + timelock + 1u + } + return transactions.filter { it.status !is ExitTransactionStatus.Confirmed }.maxOfOrNull { after(it, 0) } + } + + /** The fee one more P2WPKH funding input adds to a build at [feeRateSatPerVbyte]. */ + fun inputFeeSats(feeRateSatPerVbyte: ULong): ULong = P2WPKH_INPUT_VBYTES.safe() * feeRateSatPerVbyte.safe() + + /** + * What reached savings: what the SWEEP and COOPERATIVE steps of [record]'s recovery pay its destination, with + * those of replaced generations that had confirmed. Null when the destination cannot be read. + */ + fun receivedSats(record: SparkExitRecord): ULong? { + val script = runCatching { AddressScript.of(record.destination) }.getOrNull() ?: return null + val current = record.recovery?.let { paidTo(it.transactions, script) }.orEmpty() + return (record.earlierReceivedSats + current).values.fold(0uL) { sum, sats -> sum.safe() + sats.safe() } + } + + /** What the confirmed SWEEP and COOPERATIVE steps of [recovery] paid [destination], by txid. */ + fun confirmedReceived(recovery: RecoverFundsResponse, destination: String): Map { + val script = runCatching { AddressScript.of(destination) }.getOrNull() ?: return emptyMap() + return paidTo(recovery.transactions.filter { it.status is ExitTransactionStatus.Confirmed }, script) + } + + private fun paidTo(transactions: List, script: ByteArray): Map = transactions + .filter { it.kind == RecoveryTxKind.SWEEP || it.kind == RecoveryTxKind.COOPERATIVE } + .associate { tx -> + val outputs = SparkExitTxOutputs.decode(tx.txHex).orEmpty().filter { it.script.contentEquals(script) } + tx.txid to outputs.fold(0uL) { sum, output -> sum.safe() + output.valueSats.safe() } + } + .filterValues { it > 0uL } + + /** + * Whether a build that waits for a leaf that may still move tries again at [tip]: six blocks after it started + * waiting at [since], then at doubling gaps up to a day. + */ + fun isRetryDue(since: UInt, retriedAt: UInt?, tip: UInt): Boolean { + val last = maxOf(since, retriedAt ?: since) + val gap = (last - since).coerceIn(RETRY_BLOCKS, RETRY_MAX_BLOCKS) + return tip >= last && tip - last >= gap + } + + /** A wait that started at [since] has lasted about a week by [tip]: what is still stuck is let go. */ + fun isRetryReleased(since: UInt, tip: UInt): Boolean = tip >= since && tip - since >= RELEASE_BLOCKS /** The next height above [tip] at which a timelocked step matures, for the reminder. */ fun nextMaturityHeight(recovery: RecoverFundsResponse, tip: UInt): UInt? = recovery.transactions @@ -190,11 +260,14 @@ object SparkExitMath { /** * The funding a rebuild needs in all, from the SDK's [requiredSats]: the total its inputs must hold, not the extra. * What is still [held] at the address counts, so the shortfall is `requiredSats - held`, at least 1; without a - * reading of the address, `max(requiredSats, fundedSats)`, right for a first build where nothing is spent yet. + * reading of the address, `max(requiredSats, fundedSats)`, right for a first build where nothing is spent yet. The + * SDK sized [requiredSats] on the inputs it had, so a missing amount adds [inputFeeSats] for the coin that pays it. */ - fun neededFunding(requiredSats: ULong, fundedSats: ULong, held: ULong?): ULong { - if (held == null) return maxOf(requiredSats, fundedSats) - val missing = if (requiredSats > held) requiredSats - held else 0uL + fun neededFunding(requiredSats: ULong, fundedSats: ULong, held: ULong?, inputFeeSats: ULong = 0uL): ULong { + if (held == null) { + return if (requiredSats > fundedSats) requiredSats.safe() + inputFeeSats.safe() else fundedSats + } + val missing = if (requiredSats > held) (requiredSats - held).safe() + inputFeeSats.safe() else 0uL return fundedSats.safe() + maxOf(missing, 1uL).safe() } @@ -234,7 +307,7 @@ object SparkExitMath { * covering the shortfall that has not, is waited for; only what is still missing is asked for, at least dust. */ fun fundingState(record: SparkExitRecord, utxos: List?): SparkExitFundingState? { - val shortfall = record.fundingShortfallSats ?: return null + val needed = record.fundingShortfallSats ?: return null record.fundingPaymentTxid?.let { txid -> val isAdopted = record.funding.any { it.txid == txid } val isConfirmed = utxos?.any { it.txid == txid && it.status.confirmed } == true @@ -242,13 +315,18 @@ object SparkExitMath { } val fresh = utxos?.let { newFunding(it, record) }.orEmpty() val seen = fresh.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + // The shortfall counts the coin that pays it; each coin more adds its own input fee. + val inputFee = inputFeeSats(record.feeRateSatPerVbyte) + val shortfall = needed.safe() + (inputFee.safe() * maxOf(fresh.size - 1, 0).toULong().safe()).safe() if (fresh.isNotEmpty() && seen >= shortfall) { // Covered: waiting for it to confirm, or for the next tick to take it once it has. val txid = (fresh.firstOrNull { !it.status.confirmed } ?: fresh.first()).txid return SparkExitFundingState.Seen(txid) } - // Nodes refuse an output under its dust limit, so a smaller remainder is asked as the funding output's dust. - return SparkExitFundingState.Ask(maxOf(shortfall - seen, FUNDING_DUST_SATS), seen, shortfall) + // A partial payment leaves another coin to send, with its own input fee. Nodes refuse an output under its dust + // limit, so a smaller remainder is asked as the funding output's dust. + val required = if (fresh.isEmpty()) shortfall else shortfall.safe() + inputFee.safe() + return SparkExitFundingState.Ask(maxOf(required - seen, FUNDING_DUST_SATS), seen, required) } /** What reached the funding address against [requiredSats], once some but not all of it did; else null. */ @@ -261,12 +339,16 @@ object SparkExitMath { ) } - /** Every confirmed UTXO of new funding, the largest first, once together they cover [requiredSats]. */ - fun fundingTopUp(utxos: List, requiredSats: ULong): List? { + /** + * Every confirmed UTXO of new funding, the largest first, once together they cover [requiredSats] plus + * [inputFeeSats] for each coin beyond the first: the SDK spends every input it is given. + */ + fun fundingTopUp(utxos: List, requiredSats: ULong, inputFeeSats: ULong = 0uL): List? { val confirmed = utxos.filter { it.status.confirmed }.sortedByDescending { it.value } if (confirmed.isEmpty()) return null val total = confirmed.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } - return confirmed.takeIf { total >= requiredSats } + val needed = requiredSats.safe() + (inputFeeSats.safe() * (confirmed.size - 1).toULong().safe()).safe() + return confirmed.takeIf { total >= needed } } /** About how long until [height]. */ @@ -278,6 +360,21 @@ object SparkExitMath { /** The dust limit of the funding address's P2WPKH output, the least a top-up can pay. */ const val FUNDING_DUST_SATS = 294uL + /** A signed P2WPKH input's size: each funding coin adds this much to the CPFP children it pays for. */ + private const val P2WPKH_INPUT_VBYTES = 68uL + + /** Blocks before a build that waits for a leaf that may still move tries again; gaps double from here. */ + private const val RETRY_BLOCKS = 6u + + /** The longest gap between those tries, about a day. */ + private const val RETRY_MAX_BLOCKS = 144u + + /** About a week: what is still stuck after it is let go, so the exit can finish. */ + const val RELEASE_BLOCKS = 1_008u + + /** Blocks a leaf the operators' watchtower stopped may stay so before it is let go. */ + const val STOPPED_BLOCKS = 6u + /** About how many blocks after a step matures the operators may publish their own version of it. */ private const val OPERATOR_WINDOW_BLOCKS = 50 diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 1703b17d12..fb9a32eb44 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -14,6 +14,7 @@ import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.buildJsonObject @@ -79,14 +80,38 @@ data class SparkExitRecord( val isResultSeen: Boolean = false, /** Leaves a rebuild could not exit, such as a fee-ladder leaf whose refund cannot pay its fee; left on Spark. */ val leftBehindLeaves: List = emptyList(), - /** Steps that already started a rebuild after their fee went unpaid several times in a row; each starts one. */ - val feeChainRebuildTxids: List = emptyList(), + /** + * Rebuilds in a row over steps that keep being refused or a fee chain that lost a race, with no step confirming in + * between. At [SparkExitDriver.STALL_REBUILDS_TO_SURFACE] the exit stops rebuilding and says it is not moving. + */ + val stallRebuilds: Int = 0, + /** How many steps were confirmed when the last of those rebuilds started; more since then resets the count. */ + val stallConfirmedCount: Int? = null, + /** The tip of the last rebuild over a step the SDK could not read, so it rebuilds at most once a block. */ + val unverifiedRebuiltAtHeight: UInt? = null, + /** The tip at which each of the exit's leaves was first seen stopped by the operators' watchtower. */ + val stoppedLeafSince: Map = emptyMap(), + /** The tip at which a build first found nothing to build while a leaf may still move. */ + val retrySince: UInt? = null, + /** The tip of the last of those builds. */ + val retriedAt: UInt? = null, + /** The SDK's exit data from just before the first build, imported again before every rebuild. */ + val exitStateSnapshot: String? = null, + /** The stored record could not be read, so the exit rebuilds from the chain with the funding it kept. */ + val isRebuiltFromChain: Boolean = false, + /** The rebuild in progress started from a Redo verdict, the only one whose reproduced spent steps strike. */ + val isRedoRebuild: Boolean = false, + /** What confirmed SWEEP and COOPERATIVE steps of replaced generations paid to [destination], by txid. */ + val earlierReceivedSats: Map = emptyMap(), ) { companion object { const val CURRENT_VERSION = 1 /** Rebuilds in a row that reproduce a spent step before its leaf counts as claimed by an older state. */ const val LOST_AFTER_STRIKES = 2 + + /** Blocks a step a node accepted may go unconfirmed before the exit's fee rate counts as too low. */ + const val UNCONFIRMED_BLOCKS_TO_SURFACE = 6u } sealed interface Phase { @@ -139,6 +164,8 @@ data class SparkExitRecord( val isInputSpent: Boolean = false, /** Sends in a row, parents confirmed, that came back unpaid or with missing inputs; other outcomes reset it. */ val feeChainFailures: Int = 0, + /** The tip when a node first accepted it, kept while it stays accepted. */ + val acceptedAtHeight: UInt? = null, ) data class Leftover( @@ -159,14 +186,23 @@ data class SparkExitRecord( val isAccepted: Boolean = false, val rejection: String? = null, val isConfirmed: Boolean = false, - ) + /** The rate it was built at; null for the exit's own rate. */ + val feeRateSatPerVbyte: ULong? = null, + /** The tip when a node first accepted it, so one that does not confirm is replaced at a higher rate. */ + val sentAtHeight: UInt? = null, + /** Earlier versions a node accepted that this one replaced; any of them confirming ends the sweep. */ + val replacedTxids: List = emptyList(), + ) { + /** A refusal for its fee is not final: the sweep is built again at the network's current rate. */ + val isFeeRejection: Boolean get() = rejection?.contains("fee", ignoreCase = true) == true + } - /** The leftover still has to be swept: not built yet, or built and neither confirmed nor rejected. */ + /** The leftover still has to be swept: not built yet, or built and neither confirmed nor finally rejected. */ val isLeftoverSweepPending: Boolean get() { if (leftover.isEmpty()) return false val sweep = leftoverSweep ?: return true - return sweep.txid != null && sweep.rejection == null && !sweep.isConfirmed + return sweep.txid != null && (sweep.rejection == null || sweep.isFeeRejection) && !sweep.isConfirmed } /** @@ -227,7 +263,10 @@ data class SparkExitRecord( /** Starts a new generation from a fresh build, forgetting what was broadcast for the previous one. */ fun adopt(built: RecoverFundsResponse, atMillis: Long): SparkExitRecord = copy( - spentStepStrikes = spentStepStrikes(built), + spentStepStrikes = if (isRedoRebuild) spentStepStrikes(built) else spentStepStrikes, + isRedoRebuild = false, + earlierReceivedSats = earlierReceivedSats + recovery?.let { SparkExitMath.confirmedReceived(it, destination) } + .orEmpty(), earlierCpfpTxids = (earlierCpfpTxids + recovery?.let(SparkExitTxids::cpfpChildTxids).orEmpty()).distinct(), generation = generation + 1, recovery = built, @@ -236,8 +275,53 @@ data class SparkExitRecord( isRebuilding = false, lastBuildAt = atMillis, failedLeafCount = built.failed.size, + retrySince = null, + retriedAt = null, + isRebuiltFromChain = false, ) + /** A build found nothing to build while a leaf may still move, and waits for it. */ + val isWaitingForLeaves: Boolean get() = retrySince != null + + /** + * A step of this generation that keeps being refused, or whose fee chain keeps failing, and has not confirmed: + * the chain is broken, so the exit rebuilds over it. + */ + val stuckStep: BroadcastAttempt? + get() { + val confirmed = confirmedTxids + return broadcastLog.firstOrNull { + it.generation == generation && !it.isAccepted && it.txid !in confirmed && + ( + it.rejections >= SparkExitDriver.REJECTIONS_TO_SURFACE || + it.feeChainFailures >= SparkExitDriver.FEE_CHAIN_FAILURES_TO_REBUILD + ) + } + } + + /** Rebuilding over a broken chain failed to move the exit often enough to stop and say so. */ + val isStalled: Boolean get() = stallRebuilds >= SparkExitDriver.STALL_REBUILDS_TO_SURFACE + + /** + * A step a node accepted that has not confirmed for more blocks than a fair fee rate needs at [tip]: the network + * is busier than the exit's rate, which a rebuild at the same rate does not change. + */ + fun underpricedStep(tip: UInt?): BroadcastAttempt? { + tip ?: return null + val confirmed = confirmedTxids + return broadcastLog.firstOrNull { + val height = it.acceptedAtHeight ?: return@firstOrNull false + it.generation == generation && it.isAccepted && it.txid !in confirmed && + tip > height && tip - height > UNCONFIRMED_BLOCKS_TO_SURFACE + } + } + + private val confirmedTxids: Set + get() = recovery?.transactions.orEmpty() + .filter { it.status is ExitTransactionStatus.Confirmed } + .map { it.txid } + .toSet() + /** * The strikes after adopting [built]: a step of it that had its input spent in the generation it replaces gets one * more; every other step drops out. @@ -249,8 +333,12 @@ data class SparkExitRecord( .associate { it.txid to (spentStepStrikes[it.txid] ?: 0) + 1 } } - /** The leaves [built] would lose again: a refund of an exiting leaf reproduced with its input spent twice. */ + /** + * The leaves [built] would lose again: a refund of an exiting leaf that Redo rebuilds reproduced with its input + * spent twice. Other rebuilds never strike. + */ fun lostLeaves(built: RecoverFundsResponse): List { + if (!isRedoRebuild) return emptyList() val strikes = spentStepStrikes(built) val values = (recovery?.leaves.orEmpty() + built.leaves).associate { it.leafId to it.valueSats } return built.transactions @@ -272,8 +360,14 @@ class SparkExitStore(private val file: File) { return SparkExitJson.decode(file.readText()) } - /** Whether an exit runs, false when the record is missing or unreadable. */ - fun isActive(): Boolean = runCatching { load()?.isActive }.getOrNull() == true + /** + * Whether an exit runs, false when the record is missing. A record that cannot be read counts as running until it + * is salvaged, so an exit never disappears over it. + */ + fun isActive(): Boolean = runCatching { load()?.isActive == true }.getOrElse { file.exists() } + + /** The record's raw text, for salvaging one that cannot be read; null when there is none. */ + fun loadText(): String? = file.takeIf { it.exists() }?.readText() /** Moves an unreadable record out of the way, keeping it for support. */ fun setAside(nowMillis: Long) { @@ -321,6 +415,14 @@ class SparkExitLostLeafStore(private val file: File) { class SparkExitFormatError(message: String) : AppError(message) +/** + * Converters from older record versions, each to the next version up, applied in turn by [SparkExitJson.decode]. Add + * one here before raising [SparkExitRecord.CURRENT_VERSION], so an exit written by an earlier Bitkit keeps running. + */ +object SparkExitRecordMigration { + val converters: Map JsonObject> = emptyMap() +} + class SparkExitUnsupportedVersion(val version: Int) : AppError("Unsupported Spark exit record version '$version'") /** @@ -336,12 +438,81 @@ object SparkExitJson { fun encode(record: SparkExitRecord): String = recordToJson(record).toString() fun decode(text: String): SparkExitRecord { - val root = json.parseToJsonElement(text).jsonObject - val version = root.int("version") - if (version != SparkExitRecord.CURRENT_VERSION) throw SparkExitUnsupportedVersion(version) + var root = json.parseToJsonElement(text).jsonObject + var version = root.int("version") + while (version != SparkExitRecord.CURRENT_VERSION) { + val convert = SparkExitRecordMigration.converters[version] ?: throw SparkExitUnsupportedVersion(version) + root = convert(root) + version = root.int("version") + } return recordFromJson(root) } + /** + * What can be read of a record [decode] refused, as a record that rebuilds from the chain: the exit's leaves, rate, + * destination and the funding it kept, with no recovery or broadcasts. An exit that had ended stays ended. Null + * when not even the leaves, rate and destination can be read. + */ + fun salvage(text: String, nowMillis: Long): SparkExitRecord? { + val o = runCatching { json.parseToJsonElement(text).jsonObject }.getOrNull() ?: return null + fun read(block: () -> T): T? = runCatching(block).getOrNull() + val network = read { o.string("network") } ?: return null + val feeRate = read { o.ulong("feeRateSatPerVbyte") } ?: return null + val destination = read { o.string("destination") } ?: return null + val leafIds = read { o.array("leafIds").map { it.jsonPrimitive.content } }?.takeIf { it.isNotEmpty() } + ?: return null + val funding = read { o.array("funding") }.orEmpty().mapNotNull { + read { + val f = it.jsonObject + SparkExitRecord.Funding( + index = f.ulong("index").toUInt(), + address = f.string("address"), + pubkey = f.string("pubkey"), + txid = f.stringOrNull("txid"), + vout = f.ulongOrNull("vout")?.toUInt(), + valueSats = f.ulongOrNull("valueSats"), + ) + } + } + val stored = o["phase"]?.let { read { phaseFromJson(it) } } + val phase = when (stored) { + is SparkExitRecord.Phase.AwaitingFunding, + is SparkExitRecord.Phase.NeedsFunding, + SparkExitRecord.Phase.Done, + is SparkExitRecord.Phase.Failed, + -> stored + SparkExitRecord.Phase.Running, null -> SparkExitRecord.Phase.Running + } + val isActive = phase !is SparkExitRecord.Phase.Done && phase !is SparkExitRecord.Phase.Failed + return SparkExitRecord( + network = network, + createdAt = read { o.millis("createdAt") } ?: nowMillis, + phase = phase, + feeRateSatPerVbyte = feeRate, + destination = destination, + leafIds = leafIds, + funding = funding, + transferId = read { o.stringOrNull("transferId") }, + expectedSats = read { o.ulong("expectedSats") } ?: 0uL, + leafTotalSats = read { o.ulongOrNull("leafTotalSats") }, + lostLeaves = read { + o.arrayOrEmpty("lostLeaves").map { + val l = it.jsonObject + SparkExitRecord.LostLeaf(l.string("leafId"), l.ulong("valueSats")) + } + }.orEmpty(), + leftBehindLeaves = read { + o.arrayOrEmpty("leftBehindLeaves").map { + val l = it.jsonObject + SparkExitRecord.LeftBehindLeaf(l.string("leafId"), l.ulong("valueSats"), l.string("reason")) + } + }.orEmpty(), + isRebuilding = phase == SparkExitRecord.Phase.Running, + isRebuiltFromChain = isActive, + exitStateSnapshot = read { o.stringOrNull("exitStateSnapshot") }, + ) + } + fun encodeRecovery(recovery: RecoverFundsResponse): String = recoveryToJson(recovery).toString() fun decodeRecovery(text: String): RecoverFundsResponse = @@ -389,6 +560,7 @@ object SparkExitJson { put("isAccepted", it.isAccepted) if (it.isInputSpent) put("isInputSpent", true) if (it.feeChainFailures > 0) put("feeChainFailures", it.feeChainFailures) + it.acceptedAtHeight?.let { height -> put("acceptedAtHeight", height.toLong()) } }, ) } @@ -419,19 +591,7 @@ object SparkExitJson { if (r.earlierCpfpTxids.isNotEmpty()) { put("earlierCpfpTxids", buildJsonArray { r.earlierCpfpTxids.forEach { add(JsonPrimitive(it)) } }) } - r.leftoverSweep?.let { sweep -> - put( - "leftoverSweep", - buildJsonObject { - sweep.txid?.let { put("txid", it) } - sweep.txHex?.let { put("txHex", it) } - put("valueSats", sweep.valueSats.toLong()) - put("isAccepted", sweep.isAccepted) - sweep.rejection?.let { put("rejection", it) } - if (sweep.isConfirmed) put("isConfirmed", true) - }, - ) - } + r.leftoverSweep?.let { put("leftoverSweep", sweepToJson(it)) } r.fundingPaymentTxid?.let { put("fundingPaymentTxid", it) } if (r.isResultSeen) put("isResultSeen", true) if (r.spentStepStrikes.isNotEmpty()) { @@ -440,9 +600,7 @@ object SparkExitJson { buildJsonObject { r.spentStepStrikes.forEach { (txid, strikes) -> put(txid, strikes) } }, ) } - if (r.feeChainRebuildTxids.isNotEmpty()) { - put("feeChainRebuildTxids", buildJsonArray { r.feeChainRebuildTxids.forEach { add(JsonPrimitive(it)) } }) - } + putRebuildState(r) if (r.leftBehindLeaves.isNotEmpty()) { put( "leftBehindLeaves", @@ -476,6 +634,44 @@ object SparkExitJson { } } + private fun sweepToJson(sweep: SparkExitRecord.LeftoverSweep) = buildJsonObject { + sweep.txid?.let { put("txid", it) } + sweep.txHex?.let { put("txHex", it) } + put("valueSats", sweep.valueSats.toLong()) + put("isAccepted", sweep.isAccepted) + sweep.rejection?.let { put("rejection", it) } + if (sweep.isConfirmed) put("isConfirmed", true) + sweep.feeRateSatPerVbyte?.let { put("feeRateSatPerVbyte", it.toLong()) } + sweep.sentAtHeight?.let { put("sentAtHeight", it.toLong()) } + if (sweep.replacedTxids.isNotEmpty()) { + put("replacedTxids", buildJsonArray { sweep.replacedTxids.forEach { add(JsonPrimitive(it)) } }) + } + } + + /** What the exit keeps to pace and bound its rebuilds and waits, each left out at its default. */ + private fun JsonObjectBuilder.putRebuildState(r: SparkExitRecord) { + if (r.stallRebuilds > 0) put("stallRebuilds", r.stallRebuilds) + r.stallConfirmedCount?.let { put("stallConfirmedCount", it) } + r.unverifiedRebuiltAtHeight?.let { put("unverifiedRebuiltAtHeight", it.toLong()) } + if (r.stoppedLeafSince.isNotEmpty()) { + put( + "stoppedLeafSince", + buildJsonObject { r.stoppedLeafSince.forEach { (leafId, height) -> put(leafId, height.toLong()) } }, + ) + } + r.retrySince?.let { put("retrySince", it.toLong()) } + r.retriedAt?.let { put("retriedAt", it.toLong()) } + r.exitStateSnapshot?.let { put("exitStateSnapshot", it) } + if (r.isRebuiltFromChain) put("isRebuiltFromChain", true) + if (r.isRedoRebuild) put("isRedoRebuild", true) + if (r.earlierReceivedSats.isNotEmpty()) { + put( + "earlierReceivedSats", + buildJsonObject { r.earlierReceivedSats.forEach { (txid, sats) -> put(txid, sats.toLong()) } }, + ) + } + } + private fun recordFromJson(o: JsonObject) = SparkExitRecord( version = o.int("version"), network = o.string("network"), @@ -509,6 +705,7 @@ object SparkExitJson { isAccepted = b.booleanOrNull("isAccepted") ?: false, isInputSpent = b.booleanOrNull("isInputSpent") ?: false, feeChainFailures = b.intOrNull("feeChainFailures") ?: 0, + acceptedAtHeight = b.ulongOrNull("acceptedAtHeight")?.toUInt(), ) }, transferId = o.stringOrNull("transferId"), @@ -532,6 +729,9 @@ object SparkExitJson { isAccepted = it.booleanOrNull("isAccepted") ?: false, rejection = it.stringOrNull("rejection"), isConfirmed = it.booleanOrNull("isConfirmed") ?: false, + feeRateSatPerVbyte = it.ulongOrNull("feeRateSatPerVbyte"), + sentAtHeight = it.ulongOrNull("sentAtHeight")?.toUInt(), + replacedTxids = it.arrayOrEmpty("replacedTxids").map { txid -> txid.jsonPrimitive.content }, ) }, fundingPaymentTxid = o.stringOrNull("fundingPaymentTxid"), @@ -547,7 +747,20 @@ object SparkExitJson { val l = it.jsonObject SparkExitRecord.LeftBehindLeaf(l.string("leafId"), l.ulong("valueSats"), l.string("reason")) }, - feeChainRebuildTxids = o.arrayOrEmpty("feeChainRebuildTxids").map { it.jsonPrimitive.content }, + stallRebuilds = o.intOrNull("stallRebuilds") ?: 0, + stallConfirmedCount = o.intOrNull("stallConfirmedCount"), + unverifiedRebuiltAtHeight = o.ulongOrNull("unverifiedRebuiltAtHeight")?.toUInt(), + stoppedLeafSince = o.objectOrNull("stoppedLeafSince") + ?.mapValues { it.value.jsonPrimitive.content.toUInt() } + .orEmpty(), + retrySince = o.ulongOrNull("retrySince")?.toUInt(), + retriedAt = o.ulongOrNull("retriedAt")?.toUInt(), + exitStateSnapshot = o.stringOrNull("exitStateSnapshot"), + isRebuiltFromChain = o.booleanOrNull("isRebuiltFromChain") ?: false, + isRedoRebuild = o.booleanOrNull("isRedoRebuild") ?: false, + earlierReceivedSats = o.objectOrNull("earlierReceivedSats") + ?.mapValues { it.value.jsonPrimitive.content.toULong() } + .orEmpty(), ) private fun phaseToJson(phase: SparkExitRecord.Phase): JsonObject = when (phase) { diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index a492ceb758..4fd0dcbc3e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -115,10 +115,8 @@ class SparkExitRepo @Inject constructor( if (isLoaded && this@SparkExitRepo.walletIndex == walletIndex) return@runSuspendCatching _state.value.record this@SparkExitRepo.walletIndex = walletIndex val record = runSuspendCatching { store.load() }.getOrElse { - // Kept aside for support, so a new exit never overwrites it; a new exit prepares from chain state. Logger.error("Failed to read the Spark exit record", it, context = TAG) - runSuspendCatching { store.setAside(clock.nowMs()) } - null + salvage() } isLoaded = true _state.update { it.copy(record = record) } @@ -130,6 +128,22 @@ class SparkExitRepo @Inject constructor( } } + /** + * A record that cannot be read, such as one of an unknown version, is kept aside unchanged for support, and what + * can be read of it carries on as an exit that rebuilds from the chain, so a running exit never disappears. + */ + private fun salvage(): SparkExitRecord? { + val store = store + val text = runCatching { store.loadText() }.getOrNull() + runCatching { store.setAside(clock.nowMs()) } + .onFailure { Logger.warn("Failed to set the unreadable Spark exit record aside", it, context = TAG) } + val salvaged = text?.let { SparkExitJson.salvage(it, clock.nowMs()) } ?: return null + runCatching { store.save(salvaged) } + .onFailure { Logger.error("Failed to save the salvaged Spark exit record", it, context = TAG) } + Logger.warn("Salvaged the Spark exit record in phase '${salvaged.phase}' to rebuild from chain", context = TAG) + return salvaged + } + /** Drives the exit every minute while Bitkit is in the foreground. */ fun onAppForegrounded() { if (foregroundJob?.isActive == true) return @@ -201,6 +215,7 @@ class SparkExitRepo @Inject constructor( makeSigner = { signer(current.fundingIndex) }, save = store::save, nowMillis = clock::nowMs, + tip = tip, ) // Read before this tick's losses are kept, so a leaf lost now is still reported once. val reportedLost = reportedLostLeafIds() @@ -214,7 +229,11 @@ class SparkExitRepo @Inject constructor( // A rebuild needs the SDK; every other running step can go out from the stored recovery without it. Steps // refused again and again keep the exit from moving, however often it runs. val canMove = recovering != null || !updated.isRebuilding - val isOnTrack = tip != null && canMove && updated.surfacedRejection == null && !updated.isFeeChainStuck + // Without the SDK nothing rebuilds over a step that keeps failing. A step the network holds but does not + // confirm is underpriced, which no run changes. Either way the alarm may fire. + val isStuckWithoutSdk = recovering == null && updated.stuckStep != null + val isOnTrack = tip != null && canMove && updated.surfacedRejection == null && !updated.isFeeChainStuck && + !isStuckWithoutSdk && updated.underpricedStep(tip) == null afterTick(updated, current, isOnTrack, reportedLost) return updated } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index cae829f698..b7974ba63b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -8,6 +8,7 @@ import android.content.Intent import android.net.NetworkCapabilities import android.text.format.DateFormat import androidx.core.content.edit +import androidx.core.os.bundleOf import androidx.hilt.work.HiltWorker import androidx.work.Constraints import androidx.work.CoroutineWorker @@ -26,17 +27,21 @@ import dagger.hilt.android.EntryPointAccessors import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import to.bitkit.App import to.bitkit.R import to.bitkit.async.appScope +import to.bitkit.data.AppDb import to.bitkit.di.BgDispatcher import to.bitkit.env.Env import to.bitkit.ext.alarmManager import to.bitkit.ext.connectivityManager import to.bitkit.ext.nowMs +import to.bitkit.ext.runSuspendCatching import to.bitkit.models.BITCOIN_SYMBOL import to.bitkit.models.formatToModernDisplay +import to.bitkit.ui.EXTRA_SPARK_EXIT import to.bitkit.ui.areNotificationsEnabled import to.bitkit.ui.pushNotification import to.bitkit.utils.Logger @@ -65,6 +70,7 @@ class SparkExitWork @Inject constructor( @ApplicationContext private val context: Context, @BgDispatcher private val bgDispatcher: CoroutineDispatcher, private val clock: Clock, + private val db: AppDb, ) { companion object { private const val TAG = "SparkExitWork" @@ -78,9 +84,15 @@ class SparkExitWork @Inject constructor( /** The shortest period WorkManager runs periodic work at. */ val PERIOD = 15.minutes + } - /** The exit of the wallet Bitkit runs, read before the wallet graph exists. */ - private fun store() = SparkExitStore(File(Env.sparkExitRecordPath(0))) + /** The exit of the wallet Bitkit runs, read before the wallet graph exists. */ + private suspend fun store(): SparkExitStore { + val index = runSuspendCatching { db.configDao().getAll().first().firstOrNull()?.walletIndex } + .onFailure { Logger.warn("Failed to read the active wallet for the Spark exit", it, context = TAG) } + .getOrNull() + ?: 0L + return SparkExitStore(File(Env.sparkExitRecordPath(index.toInt()))) } private val scope = appScope(bgDispatcher, TAG) @@ -101,7 +113,14 @@ class SparkExitWork @Inject constructor( */ fun ensureScheduled() { scope.launch { - val record = runCatching { store().load() }.getOrNull() + val loaded = runCatching { store().load() } + // A record that cannot be read is salvaged by the next run, which the alarm and the work stay set for. + if (loaded.isFailure) { + Logger.warn("Failed to read the Spark exit record; keeping its background work", context = TAG) + schedulePeriodic() + return@launch + } + val record = loaded.getOrNull() if (record?.needsDriving != true) { if (preferences.contains(KEY_WARN_AT)) cancelAll() return@launch @@ -153,7 +172,14 @@ class SparkExitWork @Inject constructor( * run now, and warns again later if it stays behind. */ suspend fun onDeadline() { - val record = runCatching { store().load() }.getOrNull() + val loaded = runCatching { store().load() } + if (loaded.isFailure) { + Logger.warn("Failed to read the Spark exit record at its deadline; running it now", context = TAG) + enqueueCatchUp() + armDeadline(SparkExitMath.deadline(Duration.ZERO, Env.network)) + return + } + val record = loaded.getOrNull() val alert = SparkExitAlerts.reason(record, isOnline(), backgroundLimits()) Logger.warn( "Spark exit deadline alarm fired with alert '$alert' (${context.logBatterySettings()})", @@ -165,12 +191,16 @@ class SparkExitWork @Inject constructor( } val deadlineAt = preferences.getLong(KEY_DEADLINE_AT, 0L).takeIf { it > clock.nowMs() } notify(alert, deadlineAt) + enqueueCatchUp() + armDeadline(SparkExitMath.deadline(Duration.ZERO, Env.network)) + } + + private fun enqueueCatchUp() { WorkManager.getInstance(context).enqueueUniqueWork( CATCH_UP_WORK, ExistingWorkPolicy.KEEP, OneTimeWorkRequestBuilder().setConstraints(constraints).build(), ) - armDeadline(SparkExitMath.deadline(Duration.ZERO, Env.network)) } /** Posts the exit's notification, unless Bitkit is on screen, where the progress screen says the same. */ @@ -185,6 +215,7 @@ class SparkExitWork @Inject constructor( context.pushNotification( title = context.getString(R.string.lightning__spark_exit__notification_title), text = text, + extras = bundleOf(EXTRA_SPARK_EXIT to true), bigText = text, id = NOTIFICATION_ID, ) @@ -273,7 +304,8 @@ object SparkExitAlerts { return when { record.phase is SparkExitRecord.Phase.NeedsFunding -> SparkExitAlert.Funding record.phase != SparkExitRecord.Phase.Running -> null - record.surfacedRejection != null -> SparkExitAlert.Rejected + record.surfacedRejection != null || + (record.stuckStep?.rejections ?: 0) >= SparkExitDriver.REJECTIONS_TO_SURFACE -> SparkExitAlert.Rejected !isOnline -> SparkExitAlert.Offline limits.isRestricted -> SparkExitAlert.Restricted // Battery optimization alone is Android's default for nearly every app, so it names no cause. diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 92ba562abc..474f8022dd 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -285,6 +285,12 @@ class BreezSparkExitRecovering(private val sdk: BreezSdk) : SparkExitRecovering override suspend fun check(recovery: RecoverFundsResponse): CheckRecoverFundsResponse = sdk.checkRecoverFunds(CheckRecoverFundsRequest(recovery)) + + override suspend fun exportExitState(): String = sdk.exportUnilateralExitState().exitState + + override suspend fun importExitState(exitState: String) { + sdk.importUnilateralExitState(ImportUnilateralExitStateRequest(exitState)) + } } sealed class SparkError(message: String, cause: Throwable? = null) : AppError(message, cause) { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 09c665b752..f4ea96a92f 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -140,6 +140,19 @@ private fun Content( @Composable private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState) { SparkExitSteps(record = record, tipHeight = uiState.tipHeight) + uiState.receivedSats?.let { sats -> + VerticalSpacer(24.dp) + val text = stringResource(R.string.lightning__spark_exit__done_received) + .replace("{amount}", sparkExitAmountText(sats)) + uiState.sweepTxid?.let { + SparkExitTxNote( + text = text, + txid = it, + txidRes = R.string.lightning__spark_exit__sweep_txid, + testTag = "SparkExitReceived", + ) + } ?: BodyS(text = text, color = Colors.White64, modifier = Modifier.testTag("SparkExitReceived")) + } val address = record.funding.firstOrNull()?.address val funding = uiState.progressFunding if (funding != null && address != null) { @@ -165,9 +178,37 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState) ) } } + if (record.isRebuiltFromChain && record.isActive) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__rebuilt_from_chain), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitRebuiltFromChain") + ) + } + if (record.isWaitingForLeaves && record.isActive) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__waiting_leaves), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitWaitingLeaves") + ) + } uiState.rejection?.let { VerticalSpacer(16.dp) - BodyS(text = stringResource(R.string.lightning__spark_exit__errors).replace("{error}", it), color = Colors.Red) + BodyS( + text = stringResource(R.string.lightning__spark_exit__not_moving).replace("{error}", it), + color = Colors.Red, + modifier = Modifier.testTag("SparkExitNotMoving") + ) + } + uiState.lowFeeRate?.let { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__fee_low).replace("{rate}", "$it"), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitFeeLow") + ) } uiState.outsideExitSats?.let { VerticalSpacer(16.dp) @@ -195,12 +236,12 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState) modifier = Modifier.testTag("SparkExitLeftBehindLeaves") ) } - if (!record.isActive && address != null) LeftoverNote(record, address) + if (!record.isActive && address != null) LeftoverNote(record, address, uiState.fundingPath) } /** Where the leftover fee funding of an ended exit is: being sent, sent, kept as dust, or still at its address. */ @Composable -private fun LeftoverNote(record: SparkExitRecord, address: String) { +private fun LeftoverNote(record: SparkExitRecord, address: String, path: String?) { if (record.leftover.isEmpty()) return val total = record.leftover.fold(0uL) { sum, leftover -> sum + leftover.valueSats } val sweep = record.leftoverSweep @@ -219,11 +260,20 @@ private fun LeftoverNote(record: SparkExitRecord, address: String) { txidRes = R.string.lightning__spark_exit__leftover_txid, testTag = "SparkExitLeftoverSwept", ) - sweep?.txid != null && sweep.rejection == null -> BodyS( + sweep?.txid != null && (sweep.rejection == null || sweep.isFeeRejection) -> BodyS( text = stringResource(R.string.lightning__spark_exit__leftover_sending) .replace("{amount}", sparkExitAmountText(sweep.valueSats)), color = Colors.White64, ) + // Refused for good: where the leftover stays, with the path a wallet needs to find it. + sweep?.rejection != null && path != null -> BodyS( + text = stringResource(R.string.lightning__spark_exit__leftover_rejected) + .replace("{amount}", sparkExitAmountText(total)) + .replace("{address}", address) + .replace("{path}", path), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitLeftoverRejected") + ) else -> BodyS( text = stringResource(R.string.lightning__spark_exit__leftover) .replace("{amount}", sparkExitAmountText(total)) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index 4a10af579a..3042de9ec6 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -3,6 +3,7 @@ package to.bitkit.ui.settings.lightning import androidx.compose.runtime.Stable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import breez_sdk_spark.RecoveryTxKind import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.delay @@ -14,7 +15,9 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import to.bitkit.env.Env import to.bitkit.repositories.SparkExitBackgroundLimits +import to.bitkit.repositories.SparkExitFundingKey import to.bitkit.repositories.SparkExitFundingState import to.bitkit.repositories.SparkExitMath import to.bitkit.repositories.SparkExitQuote @@ -66,10 +69,20 @@ class SparkExitViewModel @Inject constructor( outsideExitSats = exit.outsideExitSats, staysOnSparkSats = SparkExitMath.staysOnSparkSats(balanceSats, exit.record), isSettling = exit.isSettling, + receivedSats = exit.record?.let(::receivedSats), + fundingPath = exit.record?.let { record -> + SparkExitFundingKey.path(record.fundingIndex.toInt(), Env.network) + }, ) } } + /** What the ended exit paid to savings, read from its sweep and cooperative transactions. */ + private fun receivedSats(record: SparkExitRecord): ULong? { + if (record.phase != SparkExitRecord.Phase.Done) return null + return SparkExitMath.receivedSats(record)?.takeIf { it > 0uL } + } + fun loadQuote() { viewModelScope.launch { // A new quote starts the funding choice over. @@ -202,6 +215,10 @@ data class SparkExitUiState( val staysOnSparkSats: ULong? = null, /** The quote waits for Spark to finish moving leaves first. */ val isSettling: Boolean = false, + /** What a finished exit paid to savings. */ + val receivedSats: ULong? = null, + /** The derivation path of the exit's funding key, where a leftover that could not be sent stays. */ + val fundingPath: String? = null, ) { val fundingSats: ULong get() = quote?.fundingSats ?: 0uL @@ -220,6 +237,18 @@ data class SparkExitUiState( val rejection: String? get() = record?.surfacedRejection + /** The exit's fee rate, while a step the network accepted does not confirm for longer than that rate needs. */ + val lowFeeRate: ULong? + get() { + val active = record?.takeIf { it.isActive } ?: return null + return active.feeRateSatPerVbyte.takeIf { active.underpricedStep(tipHeight) != null } + } + + /** The SWEEP transaction of a finished exit. */ + val sweepTxid: String? + get() = record?.takeIf { it.phase == SparkExitRecord.Phase.Done } + ?.recovery?.transactions?.firstOrNull { it.kind == RecoveryTxKind.SWEEP }?.txid + /** * The fee funding progress shows, asking for the whole shortfall, at least the funding output's dust, until the * funding address was read. diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 8c0f093dba..03745b6d42 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -233,13 +233,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -259,6 +260,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -266,6 +268,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -292,13 +295,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. المزوّد Spark عبر Breez بلا حد diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 9f7ac30481..61d1d56e3b 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -240,13 +240,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -266,6 +267,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -273,6 +275,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -299,13 +302,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 9fd7a3a182..2eca2da458 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -237,13 +237,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -263,6 +264,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -270,6 +272,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -296,13 +299,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Proveïdor Spark mitjançant Breez Sense límit diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index aa0d4a6999..e6c73fb139 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -240,13 +240,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -266,6 +267,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -273,6 +275,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -299,13 +302,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Poskytovatel Spark přes Breez Bez limitu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index cc1c538648..bd792589fb 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -117,13 +117,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -143,6 +144,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -150,6 +152,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -176,13 +179,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Anbieter Spark über Breez Kein Limit diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 8ba813824e..68cd180df1 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -233,13 +233,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -259,6 +260,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -266,6 +268,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -292,13 +295,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Πάροχος Spark μέσω Breez Χωρίς όριο diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index c657437678..fd07eb3153 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -239,13 +239,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -265,6 +266,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -272,6 +274,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -298,13 +301,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 5711a16930..b2f90a54f7 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -181,13 +181,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -207,6 +208,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -214,6 +216,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -240,13 +243,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 098cc2782d..fe35684990 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -116,13 +116,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -142,6 +143,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -149,6 +151,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -175,13 +178,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Fournisseur Spark via Breez Sans limite diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 968c37e4be..3e94de93d7 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -238,13 +238,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -264,6 +265,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -271,6 +273,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -297,13 +300,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Fornitore Spark tramite Breez Nessun limite diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 41f2ed287b..1951dc5755 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -237,13 +237,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -263,6 +264,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -270,6 +272,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -296,13 +299,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Aanbieder Spark via Breez Geen limiet diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 0be5b1583f..2868dcc353 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -118,13 +118,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -144,6 +145,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -151,6 +153,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -177,13 +180,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Dostawca Spark przez Breez Bez limitu diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index ca5d45a471..b02dbc8eba 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -241,13 +241,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -267,6 +268,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -274,6 +276,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -300,13 +303,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Provedor Spark via Breez Sem limite diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index ff5a3de4c9..ed67aaed33 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -113,13 +113,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -139,6 +140,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -146,6 +148,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -172,13 +175,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Fornecedor Spark via Breez Sem limite diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e0ad2ee1eb..3e9ba25d68 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -249,13 +249,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -275,6 +276,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -282,6 +284,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -308,13 +311,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Провайдер Spark через Breez Без ограничений diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2b35ac1cd3..462434dc3e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -397,13 +397,14 @@ Cancel exit You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> + {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - Some transactions were rejected: {error} {count} amounts the Spark operators could not sign for stayed on Spark. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. @@ -423,6 +424,7 @@ {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} @@ -430,6 +432,7 @@ Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. More fees\n<accent>needed</accent> + The exit is not moving: {error} Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. Battery saver is on, so Android may hold back the exit while Bitkit is closed. Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. @@ -456,13 +459,16 @@ Waiting for Spark to finish moving your balance. This can take up to 5 minutes. Exit\n<accent>quote</accent> Ready in {duration} + Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Fee funding confirms Publishing exit transactions Sending to savings Waiting for the timelock + Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. + Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. Provider Spark via Breez No limit diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index a4bc9fc717..b22c90f916 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -4,6 +4,7 @@ import breez_sdk_spark.CheckRecoverFundsResponse import breez_sdk_spark.CooperativeRecoveryError import breez_sdk_spark.CooperativeRecoveryFailure import breez_sdk_spark.CpfpInput +import breez_sdk_spark.ExitChainState import breez_sdk_spark.ExitLeafSelection import breez_sdk_spark.ExitTransactionStatus import breez_sdk_spark.RecoverFundsResponse @@ -45,14 +46,21 @@ class SparkExitDriverTest : BaseUnitTest() { private val saved = mutableListOf() private var now = 1_800_000_000_000L - private fun driver(withSdk: Boolean = true, save: (SparkExitRecord) -> Unit = { saved += it }) = SparkExitDriver( + private fun driver( + withSdk: Boolean = true, + tip: UInt? = null, + save: (SparkExitRecord) -> Unit = { saved += it }, + ) = SparkExitDriver( chain = chain, recovering = sdk.takeIf { withSdk }, makeSigner = { StubCpfpSigner() }, save = save, nowMillis = { now }, + tip = tip, ) + private val interval = SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds + private fun running(recovery: RecoverFundsResponse, builtAt: Long = now) = SparkExitFixtures.record(Phase.Running).adopt(recovery, builtAt) @@ -124,11 +132,12 @@ class SparkExitDriverTest : BaseUnitTest() { record = driver().tick(record) record = driver().tick(record) now += SparkExitDriver.REBROADCAST_INTERVAL.inWholeMilliseconds - record = driver().tick(record) + record = driver(tip = 2_000u).tick(record) assertEquals(listOf("n2", "n2"), chain.broadcasts.map { it.txid }) assertEquals(2, record.broadcastLog.single().attempts) - assertEquals(3_000u, record.claimableAtHeight) + // The longest path left: n2's block, then r1's 1,000 blocks of timelock and its own block. + assertEquals(3_002u, record.claimableAtHeight) assertEquals(checked, record.recovery) } @@ -168,20 +177,146 @@ class SparkExitDriverTest : BaseUnitTest() { } @Test - fun `retries a rejected step and surfaces it after repeated rejections`() = test { + fun `a refused step rebuilds until three rebuilds did not move the exit, then says it is not moving`() = test { val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1", cpfp = "03c"))) - var record = running(recovery) + var record = running(recovery, builtAt = now - interval) chain.outcome = SparkExitBroadcastOutcome.Rejected("insufficient fee, rejecting replacement") - repeat(3) { sdk.checks += check(recovery, RecoveryVerdict.Valid) } - - record = driver().tick(record) - assertNull(record.surfacedRejection) - repeat(2) { record = driver().tick(record) } + repeat(20) { sdk.checks += check(recovery, RecoveryVerdict.Valid) } + repeat(SparkExitDriver.STALL_REBUILDS_TO_SURFACE) { sdk.builds += recovery } + + var ticks = 0 + while (record.stallRebuilds < SparkExitDriver.STALL_REBUILDS_TO_SURFACE && ticks++ < 12) { + assertNull(record.surfacedRejection) + record = driver().tick(record) + now += interval + } + assertEquals(4, record.generation) + // Stalled: the step is still sent, but nothing rebuilds over it again. + repeat(3) { + record = driver().tick(record) + now += interval + } - assertEquals(3, chain.broadcasts.size) + assertEquals(4, record.generation) + assertEquals(SparkExitDriver.STALL_REBUILDS_TO_SURFACE, sdk.recoverRequests.size) assertEquals("rejected: insufficient fee, rejecting replacement", record.surfacedRejection) } + @Test + fun `a step confirming after a rebuild over a broken chain starts the count over`() = test { + val record = running(unpaidRecovery).copy(stallRebuilds = 3, stallConfirmedCount = 1) + assertTrue(record.isStalled) + val moved = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(11_600u)), + SparkExitFixtures.tx( + "n2", + cpfp = "03c2", + dependsOn = listOf("n1"), + status = ExitTransactionStatus.Confirmed(11_601u) + ), + ), + ) + sdk.checks += check(moved, RecoveryVerdict.Valid) + + val ticked = driver().tick(record) + + assertEquals(0, ticked.stallRebuilds) + assertNull(ticked.stallConfirmedCount) + assertNull(ticked.surfacedRejection) + } + + @Test + fun `a step accepted but not confirming for more than six blocks reads as underpriced and does not rebuild`() = + test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1", cpfp = "03c"))) + var record = running(recovery) + repeat(2) { sdk.checks += check(recovery, RecoveryVerdict.Valid) } + + record = driver(tip = 1_000u).tick(record) + assertEquals(1_000u, record.broadcastLog.single().acceptedAtHeight) + assertNull(record.underpricedStep(1_006u)) + now += SparkExitDriver.REBROADCAST_INTERVAL.inWholeMilliseconds + record = driver(tip = 1_007u).tick(record) + + assertEquals(2, chain.broadcasts.size) + assertEquals(1_000u, record.broadcastLog.single().acceptedAtHeight) + assertEquals("n1", record.underpricedStep(1_007u)?.txid) + assertEquals(1, record.generation) + assertTrue(sdk.prepareRequests.isEmpty()) + assertNull(record.surfacedRejection) + } + + @Test + fun `a unilateral step the sdk could not read is not sent and rebuilds once a block`() = test { + val unverified = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx( + "n2", + cpfp = "03c2", + dependsOn = listOf("n1"), + status = ExitTransactionStatus.Unverified, + ), + SparkExitFixtures.tx( + "co", + kind = RecoveryTxKind.COOPERATIVE, + status = ExitTransactionStatus.Unverified + ), + ), + ) + var record = running(unverified) + repeat(2) { sdk.checks += check(unverified, RecoveryVerdict.Valid) } + sdk.builds += unverified + + record = driver(tip = 1_000u).tick(record) + + assertTrue(chain.broadcasts.none { it.txid == "n2" }) + assertTrue(chain.broadcasts.any { it.txid == "co" }) + assertEquals(2, record.generation) + assertEquals(1_000u, record.unverifiedRebuiltAtHeight) + assertEquals(0, record.stallRebuilds) + assertEquals(record.fundingInputs, sdk.recoverRequests.single().fundingInputs) + assertEquals(2uL, sdk.prepareRequests.single().feeRateSatPerVbyte) + + record = driver(tip = 1_000u).tick(record) + + assertEquals(2, record.generation) + assertEquals(1, sdk.recoverRequests.size) + } + + @Test + fun `an unverified unilateral step waits while another unilateral step is ready`() = test { + val recovery = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Unverified), + SparkExitFixtures.tx("n2"), + ), + ) + sdk.checks += check(recovery, RecoveryVerdict.Valid) + + val record = driver(tip = 1_000u).tick(running(recovery)) + + assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }) + assertEquals(1, record.generation) + assertTrue(sdk.prepareRequests.isEmpty()) + } + + @Test + fun `without the sdk an unverified step whose parents confirmed is still sent`() = test { + val recovery = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + + driver(withSdk = false).tick(running(recovery)) + + // Only the SDK can rebuild over it; without it the step would never go out. + assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }) + } + @Test fun `done finishes and reads leftover funding`() = test { var record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("s", kind = RecoveryTxKind.SWEEP)))) @@ -262,9 +397,10 @@ class SparkExitDriverTest : BaseUnitTest() { record = driver().tick(record) - assertEquals(Phase.NeedsFunding(3_000uL), record.phase) + // The coin that pays it adds its own input fee, 68 vB at 2 sat/vB. + assertEquals(Phase.NeedsFunding(3_136uL), record.phase) assertTrue(record.isActive) - assertEquals(3_000uL, record.fundingShortfallSats) + assertEquals(3_136uL, record.fundingShortfallSats) } @Test @@ -283,12 +419,19 @@ class SparkExitDriverTest : BaseUnitTest() { record = driver().tick(record) - assertEquals(Phase.NeedsFunding(9_085uL), record.phase) - assertEquals(50uL, record.fundingShortfallSats) + // 50 short, plus the input fee of the coin that pays it. + assertEquals(Phase.NeedsFunding(9_221uL), record.phase) + assertEquals(186uL, record.fundingShortfallSats) + // Two coins: the second adds its own input fee too. + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = funded.map { + SparkExitFixtures.utxo(requireNotNull(it.txid), value = requireNotNull(it.valueSats)) + } + listOf(SparkExitFixtures.utxo("t1", value = 200uL), SparkExitFixtures.utxo("t2", value = 121uL)) + record = driver().tick(record) + assertEquals(Phase.NeedsFunding(9_221uL), record.phase) chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = funded.map { SparkExitFixtures.utxo(requireNotNull(it.txid), value = requireNotNull(it.valueSats)) - } + listOf(SparkExitFixtures.utxo("t1", value = 30uL), SparkExitFixtures.utxo("t2", value = 20uL)) + } + listOf(SparkExitFixtures.utxo("t1", value = 200uL), SparkExitFixtures.utxo("t2", value = 122uL)) sdk.recoverError = null sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) record = driver().tick(record) @@ -313,7 +456,7 @@ class SparkExitDriverTest : BaseUnitTest() { record = driver().tick(record) - assertEquals(2_000uL, record.fundingShortfallSats) + assertEquals(2_136uL, record.fundingShortfallSats) } @Test @@ -431,6 +574,64 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(Phase.Done, driver().tick(record).phase) } + private fun waiting(reason: SkippedLeafReason, stopped: List = emptyList()) = + SparkExitFixtures.prepared( + leaves = emptyList(), + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, reason)), + ).copy(exitChainState = ExitChainState(emptyList(), emptyList(), stopped, emptyList(), emptyList())) + + @Test + fun `an empty rebuild waits for a leaf whose funds were not found yet, at doubling gaps`() = test { + var record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) + .copy(isRebuilding = true) + sdk.preparedResponse = waiting(SkippedLeafReason.FundsNotFound) + val tries = mutableListOf() + for (tip in 1_000u..1_030u) { + val before = sdk.prepareRequests.size + record = driver(tip = tip).tick(record) + if (sdk.prepareRequests.size > before) tries += tip + } + + assertEquals(listOf(1_000u, 1_006u, 1_012u, 1_024u), tries) + assertEquals(Phase.Running, record.phase) + assertTrue(record.isWaitingForLeaves) + assertEquals(1_000u, record.retrySince) + assertEquals(1_024u, record.retriedAt) + } + + @Test + fun `a leaf still waited for after about a week is let go and the exit ends`() = test { + val record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) + .copy(isRebuilding = true, retrySince = 1_000u, retriedAt = 2_000u) + sdk.preparedResponse = waiting(SkippedLeafReason.Unverified) + + assertEquals(Phase.Running, driver(tip = 2_007u).tick(record).phase) + assertEquals(Phase.Done, driver(tip = 2_008u).tick(record).phase) + } + + @Test + fun `a leaf the operators' watchtower stopped is waited for six blocks, then let go`() = test { + var record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) + .copy(isRebuilding = true) + sdk.preparedResponse = waiting(SkippedLeafReason.NotRecoverable("stopped"), stopped = listOf("leaf-1")) + + record = driver(tip = 1_000u).tick(record) + assertEquals(mapOf("leaf-1" to 1_000u), record.stoppedLeafSince) + assertTrue(record.isWaitingForLeaves) + record = driver(tip = 1_006u).tick(record) + + assertEquals(Phase.Done, record.phase) + } + + @Test + fun `an unrecoverable leaf the watchtower did not stop ends the exit at once`() = test { + val record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) + .copy(isRebuilding = true) + sdk.preparedResponse = waiting(SkippedLeafReason.NotRecoverable("gone")) + + assertEquals(Phase.Done, driver(tip = 1_000u).tick(record).phase) + } + @Test fun `rebuild waits while a leaf is unverified`() = test { val record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) @@ -692,6 +893,153 @@ class SparkExitDriverTest : BaseUnitTest() { assertFalse(record.isActive) } + @Test + fun `a refund reproduced spent is not struck while the watchtower stopped its leaf a short while ago`() = test { + val recovery = lostLeafRecovery() + var record = running(recovery) + chain.outcome = SparkExitBroadcastOutcome.InputsMissing("""sendrawtransaction RPC error: {"code":-25}""") + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null) + .copy(exitChainState = ExitChainState(emptyList(), emptyList(), listOf("leaf-1"), emptyList(), emptyList())) + sdk.checks += check(recovery, RecoveryVerdict.Valid) + repeat(2) { + sdk.checks += check(recovery, redo) + sdk.builds += recovery + } + + record = driver(tip = 1_000u).tick(record) + now += interval + record = driver(tip = 1_001u).tick(record) + now += interval + record = driver(tip = 1_002u).tick(record) + + assertEquals(3, record.generation) + assertEquals(mapOf("refund" to 2), record.spentStepStrikes) + assertTrue(record.lostLeaves.isEmpty()) + assertEquals(Phase.Running, record.phase) + } + + @Test + fun `the first build keeps the sdk's exit data and every rebuild imports it first`() = test { + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", 1u, 25_000uL)) + val built = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + sdk.builds += built + sdk.builds += built + + var record = driver().tick(SparkExitFixtures.record()) + + assertEquals("exit-state-1", record.exitStateSnapshot) + assertEquals(1, sdk.exports) + assertTrue(sdk.imports.isEmpty()) + + sdk.exitState = "exit-state-2" + sdk.checks += check(built, redo) + now += interval + record = driver().tick(record) + + assertEquals(2, record.generation) + assertEquals(1, sdk.exports) + assertEquals(listOf("exit-state-1"), sdk.imports) + assertEquals("exit-state-1", record.exitStateSnapshot) + } + + private fun sweepDone(): SparkExitRecord { + chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0".repeat(32), 1u, 25_000uL)) + return SparkExitFixtures.record(Phase.Done).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + leftover = listOf(SparkExitRecord.Leftover("f0".repeat(32), 1u, 25_000uL)), + ) + } + + @Test + fun `a leftover sweep refused for its fee is built again at the next block's rate`() = test { + chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 300 < 400") + var record = driver(tip = 1_000u).tick(sweepDone()) + val refused = assertNotNull(record.leftoverSweep) + assertTrue(refused.isFeeRejection) + assertTrue(record.isLeftoverSweepPending) + + chain.nextBlockRate = 10uL + chain.outcome = SparkExitBroadcastOutcome.Accepted + record = driver(tip = 1_001u).tick(record) + + val rebuilt = assertNotNull(record.leftoverSweep) + assertTrue(rebuilt.txid != refused.txid) + assertEquals(10uL, rebuilt.feeRateSatPerVbyte) + assertTrue(rebuilt.valueSats < refused.valueSats) + assertTrue(rebuilt.isAccepted) + assertNull(rebuilt.rejection) + assertEquals(1_001u, rebuilt.sentAtHeight) + assertEquals(rebuilt.txHex, chain.rawBroadcasts.last()) + } + + @Test + fun `a leftover sweep refused for another reason is final`() = test { + chain.outcome = SparkExitBroadcastOutcome.Rejected("bad-txns-nonstandard-inputs") + var record = driver(tip = 1_000u).tick(sweepDone()) + assertFalse(record.isLeftoverSweepPending) + + record = driver(tip = 1_001u).tick(record) + + assertEquals(1, chain.rawBroadcasts.size) + assertFalse(record.needsDriving) + } + + @Test + fun `a leftover sweep a day unconfirmed is replaced at a higher rate`() = test { + var record = driver(tip = 1_000u).tick(sweepDone()) + val first = assertNotNull(record.leftoverSweep) + assertEquals(1_000u, first.sentAtHeight) + + record = driver(tip = 1_143u).tick(record) + assertEquals(first.txid, record.leftoverSweep?.txid) + record = driver(tip = 1_144u).tick(record) + + val replaced = assertNotNull(record.leftoverSweep) + assertTrue(replaced.txid != first.txid) + assertEquals(5uL, replaced.feeRateSatPerVbyte) + assertEquals(1_144u, replaced.sentAtHeight) + } + + @Test + fun `a sweep whose replaced version confirmed ends`() = test { + var record = driver(tip = 1_000u).tick(sweepDone()) + val first = requireNotNull(record.leftoverSweep?.txid) + record = driver(tip = 1_144u).tick(record) + assertEquals(listOf(first), record.leftoverSweep?.replacedTxids) + chain.outcome = SparkExitBroadcastOutcome.InputsMissing("missingorspent") + chain.confirmedTxids = setOf(first) + + record = driver(tip = 1_145u).tick(record) + + assertTrue(assertNotNull(record.leftoverSweep).isConfirmed) + assertFalse(record.needsDriving) + } + + @Test + fun `a sweep refused for its fee that only dust is left of at the next block's rate is kept as dust`() = test { + chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 300 < 400") + var record = driver(tip = 1_000u).tick(sweepDone()) + chain.nextBlockRate = 1_000uL + + record = driver(tip = 1_001u).tick(record) + + assertEquals(SparkExitRecord.LeftoverSweep(null, null, 25_000uL), record.leftoverSweep) + assertFalse(record.needsDriving) + } + + @Test + fun `a replacement that would be dust keeps the accepted sweep`() = test { + var record = driver(tip = 1_000u).tick(sweepDone()) + val first = assertNotNull(record.leftoverSweep) + chain.nextBlockRate = 1_000uL + + record = driver(tip = 1_144u).tick(record) + + assertEquals(first.txid, record.leftoverSweep?.txid) + assertTrue(assertNotNull(record.leftoverSweep).isAccepted) + } + @Test fun `a single leaf lost while the funding address cannot be read ends lost through the no-leaf path`() = test { val recovery = lostLeafRecovery() @@ -732,6 +1080,7 @@ class SparkExitDriverTest : BaseUnitTest() { ), isRebuilding = true, lastBuildAt = null, + isRedoRebuild = true, ) sdk.preparedResponse = SparkExitFixtures.prepared(funding = null) sdk.builds += recovery @@ -1008,10 +1357,10 @@ class SparkExitDriverTest : BaseUnitTest() { ) @Test - fun `a step unpaid three times in a row rebuilds once, then surfaces`() = test { - var record = running(unpaidRecovery, builtAt = now - SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds) + fun `a step unpaid three times in a row rebuilds and never counts as a rejection`() = test { + var record = running(unpaidRecovery, builtAt = now - interval) chain.outcome = UNPAID - repeat(5) { sdk.checks += check(unpaidRecovery, RecoveryVerdict.Valid) } + repeat(3) { sdk.checks += check(unpaidRecovery, RecoveryVerdict.Valid) } sdk.builds += unpaidRecovery repeat(2) { record = driver().tick(record) } @@ -1019,18 +1368,12 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(0, record.broadcastLog.single().rejections) assertTrue(sdk.prepareRequests.isEmpty()) record = driver().tick(record) - assertEquals(1, sdk.prepareRequests.size) - assertEquals(2, record.generation) - assertEquals(listOf("n2"), record.feeChainRebuildTxids) - // The rebuild reproduced the same step, which stays unpaid: it never rebuilds again, and now counts. - record = driver().tick(record) - assertNull(record.surfacedRejection) - record = driver().tick(record) assertEquals(1, sdk.prepareRequests.size) assertEquals(2, record.generation) - assertEquals(3, record.broadcastLog.single().rejections) - assertEquals("rejected: min relay fee not met, 0 < 17", record.surfacedRejection) + assertEquals(1, record.stallRebuilds) + assertEquals(0, record.broadcastLog.single().rejections) + assertNull(record.surfacedRejection) assertTrue(record.lostLeaves.isEmpty()) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt index b657798247..f14af6d785 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -173,6 +173,10 @@ class FakeSparkExitChain : SparkExitChain { } val rawBroadcasts = mutableListOf() + + var nextBlockRate: ULong? = 5uL + + override suspend fun nextBlockFeeRate(): ULong = nextBlockRate ?: throw SparkExitChainError("No fee estimates") } class FakeSparkExitRecovering : SparkExitRecovering { @@ -206,6 +210,19 @@ class FakeSparkExitRecovering : SparkExitRecovering { checkedRecoveries += recovery return checks.removeFirst() } + + var exitState = "exit-state-1" + var exports = 0 + val imports = mutableListOf() + + override suspend fun exportExitState(): String { + exports++ + return exitState + } + + override suspend fun importExitState(exitState: String) { + imports += exitState + } } /** Finalizes every input of a PSBT with [witness], as the SDK's single-key signer does with its signature. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 8221675be2..9c05c449c6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -71,6 +71,111 @@ class SparkExitFundingTest { assertEquals(20_000uL, SparkExitMath.neededFunding(15_000uL, fundedSats = 20_000uL, held = null)) } + @Test + fun `a top up adds the input fee of each coin beyond the ones the sdk sized it on`() { + val inputFee = SparkExitMath.inputFeeSats(2uL) + assertEquals(136uL, inputFee) + // The qa-03 run at 2 sat/vB: 9,035 held, the SDK wants 9,085, and the coin that pays the 50 adds its own input. + assertEquals(9_221uL, SparkExitMath.neededFunding(9_085uL, fundedSats = 9_035uL, held = 9_035uL, inputFee)) + assertEquals(15_136uL, SparkExitMath.neededFunding(15_000uL, fundedSats = 0uL, held = null, inputFee)) + val record = SparkExitFixtures.record(SparkExitRecord.Phase.NeedsFunding(9_221uL)).copy( + funding = listOf( + SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 9_035uL) + ), + ) + assertEquals(SparkExitFundingState.Ask(294uL, 0uL, 186uL), SparkExitMath.fundingState(record, emptyList())) + // Two coins of 1,000 cover a 1,999 shortfall only with the second coin's input fee on top. + val coins = listOf(SparkExitFixtures.utxo("a", value = 1_000uL), SparkExitFixtures.utxo("b", value = 1_000uL)) + assertNull(SparkExitMath.fundingTopUp(coins, requiredSats = 1_999uL, inputFeeSats = inputFee)) + assertEquals(2, SparkExitMath.fundingTopUp(coins, requiredSats = 1_864uL, inputFeeSats = inputFee)?.size) + } + + @Test + fun `the countdown follows the longest path of timelocks and blocks left`() { + val transactions = listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(990u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1")), + SparkExitFixtures.tx( + "r1", + kind = RecoveryTxKind.REFUND, + dependsOn = listOf("n2"), + status = ExitTransactionStatus.WaitingForDependencies, + csv = 100u, + ), + SparkExitFixtures.tx( + "r2", + kind = RecoveryTxKind.REFUND, + dependsOn = listOf("n1"), + status = ExitTransactionStatus.WaitingForTimelock(1_050u), + ), + SparkExitFixtures.tx("s", kind = RecoveryTxKind.SWEEP, dependsOn = listOf("r1", "r2")), + ) + + // n2 (1) then r1 (100 + 1) then the sweep (1); r2's path is shorter. + assertEquals(103u, SparkExitMath.blocksToFinish(transactions, tip = 1_000u)) + assertEquals(1_103u, SparkExitMath.claimableAtHeight(SparkExitFixtures.recovery(transactions), tip = 1_000u)) + // n2 confirmed: one block less, not a jump. + val moved = transactions.map { + if (it.txid == "n2") it.copy(status = ExitTransactionStatus.Confirmed(1_001u)) else it + } + assertEquals(1_103u, SparkExitMath.claimableAtHeight(SparkExitFixtures.recovery(moved), tip = 1_001u)) + assertNull(SparkExitMath.blocksToFinish(listOf(transactions.first()), tip = 1_000u)) + } + + @Test + fun `what reached savings is what the sweep and cooperative steps of every generation pay the destination`() { + val address = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + val destination = AddressScript.of(address) + val other = AddressScript.of("bcrt1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqc8gma6") + fun paying(vararg outputs: Pair): String { + fun le( + value: Long, + size: Int + ) = (0 until size).joinToString("") { "%02x".format((value shr (8 * it)) and 0xff) } + val body = outputs.joinToString("") { (value, script) -> + le(value, 8) + "%02x".format(script.size) + script.toHexString() + } + return "02000000" + "01" + "11".repeat(32) + le(0, 4) + "00" + "ffffffff" + + "%02x".format(outputs.size) + body + le(0, 4) + } + val cooperative = SparkExitFixtures.tx( + "c", + kind = RecoveryTxKind.COOPERATIVE, + status = ExitTransactionStatus.Confirmed(900u), + ).copy(txHex = paying(5_000L to destination, 700L to other)) + val first = SparkExitFixtures.recovery( + listOf( + cooperative, + SparkExitFixtures.tx("n", kind = RecoveryTxKind.NODE).copy(txHex = paying(1_000L to destination)), + ), + ) + // A Redo after the cooperative leaf landed: the new generation no longer lists it. + val rebuilt = SparkExitFixtures.recovery( + listOf(SparkExitFixtures.tx("s", kind = RecoveryTxKind.SWEEP).copy(txHex = paying(90_000L to destination))), + ) + val record = SparkExitFixtures.record(SparkExitRecord.Phase.Running).copy(destination = address) + .adopt(first, 1L) + .adopt(rebuilt, 2L) + + assertEquals(mapOf("c" to 5_000uL), record.earlierReceivedSats) + assertEquals(95_000uL, SparkExitMath.receivedSats(record)) + // Listed again, it counts once. + val relisted = SparkExitFixtures.recovery(listOf(cooperative) + rebuilt.transactions) + assertEquals(95_000uL, SparkExitMath.receivedSats(record.copy(recovery = relisted))) + } + + @Test + fun `a wait for a leaf that may still move tries again at doubling gaps up to a day and ends after a week`() { + assertFalse(SparkExitMath.isRetryDue(since = 1_000u, retriedAt = 1_000u, tip = 1_005u)) + assertTrue(SparkExitMath.isRetryDue(since = 1_000u, retriedAt = 1_000u, tip = 1_006u)) + assertFalse(SparkExitMath.isRetryDue(since = 1_000u, retriedAt = 1_024u, tip = 1_047u)) + assertTrue(SparkExitMath.isRetryDue(since = 1_000u, retriedAt = 1_024u, tip = 1_048u)) + assertFalse(SparkExitMath.isRetryDue(since = 1_000u, retriedAt = 1_500u, tip = 1_643u)) + assertTrue(SparkExitMath.isRetryDue(since = 1_000u, retriedAt = 1_500u, tip = 1_644u)) + assertFalse(SparkExitMath.isRetryReleased(since = 1_000u, tip = 2_007u)) + assertTrue(SparkExitMath.isRetryReleased(since = 1_000u, tip = 2_008u)) + } + @Test fun `spark's balance beyond the exit's leaves is outside the exit`() { assertEquals(17_097uL, SparkExitMath.outsideExitSats(leafTotalSats = 32_768uL, balanceSats = 49_865uL)) @@ -235,10 +340,10 @@ class SparkExitFundingTest { val paidPending = listOf(SparkExitFixtures.utxo("paid", value = 20_000uL, confirmed = false)) assertEquals(SparkExitFundingState.Paid("paid"), SparkExitMath.fundingState(record, paidPending)) assertEquals(SparkExitFundingState.Paid("paid"), SparkExitMath.fundingState(record, utxos = null)) - // Confirmed but short: only the rest is asked for. + // Confirmed but short: only the rest is asked for, with the input fee of the coin that pays it. val paidShort = listOf(SparkExitFixtures.utxo("paid", value = 15_000uL)) assertEquals( - SparkExitFundingState.Ask(5_000uL, 15_000uL, 20_000uL), + SparkExitFundingState.Ask(5_136uL, 15_000uL, 20_136uL), SparkExitMath.fundingState(record, paidShort) ) // Once adopted, a later shortfall no longer reads as paid. @@ -256,7 +361,7 @@ class SparkExitFundingTest { assertEquals(SparkExitFundingState.Seen("ext"), SparkExitMath.fundingState(record, seen)) val partial = listOf(SparkExitFixtures.utxo("ext", value = 8_000uL, confirmed = false)) assertEquals( - SparkExitFundingState.Ask(12_000uL, 8_000uL, 20_000uL), + SparkExitFundingState.Ask(12_136uL, 8_000uL, 20_136uL), SparkExitMath.fundingState(record, partial) ) assertNull(SparkExitMath.fundingState(record.copy(phase = SparkExitRecord.Phase.Running), seen)) @@ -321,11 +426,12 @@ class SparkExitFundingTest { assertNull(SparkExitMath.partialFunding(0uL, 20_000uL)) assertNull(SparkExitMath.partialFunding(20_000uL, 20_000uL)) - // On Progress the top-up counts only new funding, unconfirmed included, against the shortfall. + // On Progress the top-up counts only new funding, unconfirmed included, against the shortfall and the input + // fee of the coin still to send. val record = SparkExitFixtures.record() val seen = listOf(SparkExitFixtures.utxo("ext", value = 8_000uL, confirmed = false)) val ask = assertIs(SparkExitMath.fundingState(record, seen)) - assertEquals(partial, ask.partial) + assertEquals(SparkExitPartialFunding(8_000uL, 20_136uL, 12_136uL), ask.partial) assertNull(SparkExitFundingState.Ask(20_000uL).partial) } @@ -333,10 +439,10 @@ class SparkExitFundingTest { fun `a top up under dust is asked as the funding output's dust limit`() { val record = SparkExitFixtures.record() val almost = listOf(SparkExitFixtures.utxo("ext", value = 19_932uL)) - val ask = SparkExitFundingState.Ask(294uL, 19_932uL, 20_000uL) + val ask = SparkExitFundingState.Ask(294uL, 19_932uL, 20_136uL) assertEquals(ask, SparkExitMath.fundingState(record, almost)) // The hint names the shortfall as it is and asks for dust at least. - assertEquals(SparkExitPartialFunding(19_932uL, 20_000uL, 294uL), ask.partial) + assertEquals(SparkExitPartialFunding(19_932uL, 20_136uL, 294uL), ask.partial) assertEquals( SparkExitPartialFunding(19_932uL, 20_000uL, 294uL), SparkExitMath.partialFunding(19_932uL, 20_000uL) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt index d7803d814a..15c1028e6f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -20,6 +20,7 @@ import java.io.File import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse +import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue @@ -88,6 +89,7 @@ class SparkExitRecordTest { false, isInputSpent = true, feeChainFailures = 2, + acceptedAtHeight = 1_000u, ), ), claimableAtHeight = 2_100u, @@ -95,12 +97,30 @@ class SparkExitRecordTest { isRebuilding = true, leafTotalSats = 90_112uL, earlierCpfpTxids = listOf("child"), - leftoverSweep = SparkExitRecord.LeftoverSweep("sweep", "02sweep", 5_035uL, true, isConfirmed = true), + leftoverSweep = SparkExitRecord.LeftoverSweep( + "sweep", + "02sweep", + 5_035uL, + true, + isConfirmed = true, + feeRateSatPerVbyte = 7uL, + sentAtHeight = 1_010u, + replacedTxids = listOf("sweep-0"), + ), fundingPaymentTxid = "paid", spentStepStrikes = mapOf("refund" to 1), lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 16_384uL)), leftBehindLeaves = listOf(SparkExitRecord.LeftBehindLeaf("leaf-2", 8_192uL, "its refund cannot pay")), - feeChainRebuildTxids = listOf("refund"), + stallRebuilds = 2, + stallConfirmedCount = 3, + unverifiedRebuiltAtHeight = 1_001u, + stoppedLeafSince = mapOf("leaf-2" to 1_002u), + retrySince = 1_003u, + retriedAt = 1_009u, + exitStateSnapshot = "exit-state", + isRebuiltFromChain = true, + isRedoRebuild = true, + earlierReceivedSats = mapOf("sweep-0" to 90_000uL), ) assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) @@ -195,7 +215,18 @@ class SparkExitRecordTest { assertFalse("fundingPaymentTxid" in json) assertFalse("spentStepStrikes" in json) assertFalse("lostLeaves" in json) - assertFalse("feeChainRebuildTxids" in json) + listOf( + "stallRebuilds", + "stallConfirmedCount", + "unverifiedRebuiltAtHeight", + "stoppedLeafSince", + "retrySince", + "retriedAt", + "exitStateSnapshot", + "isRebuiltFromChain", + "isRedoRebuild", + "earlierReceivedSats", + ).forEach { assertFalse(it in json, it) } assertEquals( JsonPrimitive(20_000), json.getValue("phase").jsonObject.getValue("awaitingFunding").jsonObject["requiredSats"] @@ -212,6 +243,53 @@ class SparkExitRecordTest { assertEquals(2, error.version) } + @Test + fun `a record of an unknown version is salvaged to rebuild from chain with its funding`() { + val record = SparkExitFixtures.record(SparkExitRecord.Phase.Running).copy( + funding = listOf( + SparkExitRecord.Funding(3u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", "f0", 1u, 20_000uL) + ), + recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))), + leafTotalSats = 100_000uL, + exitStateSnapshot = "exit-state", + ) + val text = SparkExitJson.encode(record) + .replace("\"version\":1", "\"version\":2") + .replace("\"phase\":{\"running\":{}}", "\"phase\":{\"runningV2\":{}}") + assertFailsWith { SparkExitJson.decode(text) } + + val salvaged = assertNotNull(SparkExitJson.salvage(text, nowMillis = 42L)) + + assertEquals(SparkExitRecord.Phase.Running, salvaged.phase) + assertTrue(salvaged.isRebuilding) + assertTrue(salvaged.isRebuiltFromChain) + assertTrue(salvaged.isActive) + assertNull(salvaged.recovery) + assertNull(salvaged.lastBuildAt) + assertEquals(record.funding, salvaged.funding) + assertEquals(record.fundingInputs, salvaged.fundingInputs) + assertEquals(record.leafIds, salvaged.leafIds) + assertEquals(record.transferId, salvaged.transferId) + assertEquals(record.createdAt, salvaged.createdAt) + assertEquals(100_000uL, salvaged.leafTotalSats) + assertEquals("exit-state", salvaged.exitStateSnapshot) + assertEquals(salvaged, SparkExitJson.decode(SparkExitJson.encode(salvaged))) + assertFalse(salvaged.adopt(SparkExitFixtures.recovery(emptyList()), 1L).isRebuiltFromChain) + } + + @Test + fun `a salvaged record that had ended stays ended and one with nothing to rebuild from is not salvaged`() { + val done = SparkExitJson.encode(SparkExitFixtures.record(SparkExitRecord.Phase.Done)) + .replace("\"version\":1", "\"version\":9") + + val salvaged = assertNotNull(SparkExitJson.salvage(done, nowMillis = 42L)) + + assertEquals(SparkExitRecord.Phase.Done, salvaged.phase) + assertFalse(salvaged.isRebuiltFromChain) + assertNull(SparkExitJson.salvage("{", nowMillis = 42L)) + assertNull(SparkExitJson.salvage("""{"version":2,"network":"regtest"}""", nowMillis = 42L)) + } + @Test fun `store saves loads and sets an unreadable record aside`() { val file = File(tempFolder.root, "regtest/wallet0/spark-exit.json") @@ -225,8 +303,10 @@ class SparkExitRecordTest { assertTrue(store.isActive()) assertFalse(File(file.parentFile, "spark-exit.json.tmp").exists()) + // An unreadable record counts as running until the repo salvages it, so an exit never disappears over it. file.writeText("{") - assertFalse(store.isActive()) + assertTrue(store.isActive()) + assertEquals("{", store.loadText()) store.setAside(42L) assertFalse(file.exists()) assertTrue(File(file.parentFile, "spark-exit.unreadable-42.json").exists()) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 441bec38e2..a00f976628 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -46,6 +46,8 @@ import to.bitkit.test.BaseUnitTest import java.io.File import kotlin.test.assertEquals import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Instant @@ -127,6 +129,27 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(false, file.exists()) } + @Test + fun `load keeps a running exit whose record has an unknown version, to rebuild it from chain`() = test { + val file = File(Env.sparkExitRecordPath(0)) + SparkExitStore(file).save(SparkExitFixtures.record(Phase.Running)) + val original = file.readText().replace("\"version\":1", "\"version\":2") + file.writeText(original) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + + val record = assertNotNull(createSut().load(0).getOrThrow()) + + assertTrue(record.isActive) + assertTrue(record.isRebuiltFromChain) + assertTrue(record.isRebuilding) + assertEquals("transfer-1", record.transferId) + verify(transferRepo, never()).markSettled(any()) + verify(work).schedulePeriodic() + assertEquals(record, SparkExitStore(file).load()) + assertEquals(original, File(file.parentFile, "spark-exit.unreadable-1800000000000.json").readText()) + } + @Test fun `leaves lost to an older state outlive the exit record that found them`() = test { val recordFile = File(Env.sparkExitRecordPath(0)) @@ -293,7 +316,7 @@ class SparkExitRepoTest : BaseUnitTest() { sut.runInBackground().getOrThrow() - assertEquals(Phase.NeedsFunding(9_103uL), sut.state.value.record?.phase) + assertEquals(Phase.NeedsFunding(9_239uL), sut.state.value.record?.phase) val ask = assertIs(sut.state.value.fundingState) assertEquals(SparkExitMath.FUNDING_DUST_SATS, ask.sats) } From 145da4651cb6be8a8335f031aa1ea1c43a46e49a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 16:55:57 +0100 Subject: [PATCH 012/154] fix: spark exit shows a low fee rate when the mempool refuses it --- .../to/bitkit/repositories/SparkExitChain.kt | 11 +++++ .../to/bitkit/repositories/SparkExitDriver.kt | 6 ++- .../to/bitkit/repositories/SparkExitRecord.kt | 10 ++--- .../bitkit/repositories/SparkExitChainTest.kt | 13 ++++++ .../repositories/SparkExitDriverTest.kt | 40 +++++++++++++++++++ 5 files changed, 73 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 4b4bd7b726..76fac44e7f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -329,6 +329,17 @@ object SparkExitBroadcastClassifier { fun isUnpaid(outcome: SparkExitBroadcastOutcome): Boolean = outcome is SparkExitBroadcastOutcome.Rejected && unpaid.containsMatchIn(outcome.reason) + private val feeTooLow = Regex("""min relay fee not met,\s*[1-9]|mempool min fee not met""") + + /** + * A node refused a step whose fee it found too low: a nonzero fee under its relay floor, or under the mempool's + * floor. A rebuild at the same rate cannot help. An unpaid step and a lost replacement race are not this. + */ + fun isFeeTooLow(text: String): Boolean = feeTooLow.containsMatchIn(text) + + fun isFeeTooLow(outcome: SparkExitBroadcastOutcome): Boolean = + outcome is SparkExitBroadcastOutcome.Rejected && isFeeTooLow(outcome.reason) + fun classify(text: String): SparkExitBroadcastOutcome = when { knownMessages.any { it in text } || hasRpcCode(-27, text) -> SparkExitBroadcastOutcome.Accepted notMatureMessages.any { it in text } -> SparkExitBroadcastOutcome.NotMature(text) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 77af785355..5c82d5939c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -722,8 +722,10 @@ class SparkExitDriver( val isStuck = parentsConfirmed && (isUnpaid || outcome is SparkExitBroadcastOutcome.InputsMissing) Logger.info("Broadcast Spark exit '${tx.kind}' '${tx.txid}': '${outcome.summary}'", context = TAG) val isAccepted = outcome == SparkExitBroadcastOutcome.Accepted - // An unpaid step is a broken fee chain, never a rejection. - val isRejected = outcome is SparkExitBroadcastOutcome.Rejected && !isUnpaid + // An unpaid step is a broken fee chain, and a fee under the network's floor an underpriced exit: neither is a + // rejection a rebuild could fix. + val isRejected = outcome is SparkExitBroadcastOutcome.Rejected && !isUnpaid && + !SparkExitBroadcastClassifier.isFeeTooLow(outcome) val rejection = if (isRejected) 1 else 0 val existing = record.broadcastLog.firstOrNull { it.generation == record.generation && it.txid == tx.txid } val entry = existing?.copy( diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index fb9a32eb44..6de03325f4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -303,16 +303,16 @@ data class SparkExitRecord( val isStalled: Boolean get() = stallRebuilds >= SparkExitDriver.STALL_REBUILDS_TO_SURFACE /** - * A step a node accepted that has not confirmed for more blocks than a fair fee rate needs at [tip]: the network - * is busier than the exit's rate, which a rebuild at the same rate does not change. + * A step whose fee the network finds too low: a node refused it for its fee, or accepted it and it has not + * confirmed for more blocks than a fair fee rate needs at [tip]. A rebuild at the same rate does not change that. */ fun underpricedStep(tip: UInt?): BroadcastAttempt? { - tip ?: return null val confirmed = confirmedTxids return broadcastLog.firstOrNull { + if (it.generation != generation || it.txid in confirmed) return@firstOrNull false + if (!it.isAccepted) return@firstOrNull SparkExitBroadcastClassifier.isFeeTooLow(it.lastOutcome) val height = it.acceptedAtHeight ?: return@firstOrNull false - it.generation == generation && it.isAccepted && it.txid !in confirmed && - tip > height && tip - height > UNCONFIRMED_BLOCKS_TO_SURFACE + tip != null && tip > height && tip - height > UNCONFIRMED_BLOCKS_TO_SURFACE } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt index 8ba3047054..fd408b35e6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -214,6 +214,19 @@ class SparkExitChainTest : BaseUnitTest() { assertFalse(classifier.isUnpaid(SparkExitBroadcastOutcome.RetryLater("min relay fee not met, 0 < 17"))) } + @Test + fun `only a nonzero fee under a node's floor reads as a fee too low`() { + val classifier = SparkExitBroadcastClassifier + assertTrue(classifier.isFeeTooLow(SparkExitBroadcastOutcome.Rejected("min relay fee not met, 5 < 17"))) + assertTrue(classifier.isFeeTooLow(SparkExitBroadcastOutcome.Rejected("mempool min fee not met, 300 < 400"))) + // A dead parent or child, and the lost replacement race, stay on the broken-chain path. + assertFalse(classifier.isFeeTooLow(SparkExitBroadcastOutcome.Rejected("min relay fee not met, 0 < 17"))) + assertFalse( + classifier.isFeeTooLow(SparkExitBroadcastOutcome.Rejected("insufficient fee, rejecting replacement")), + ) + assertFalse(classifier.isFeeTooLow(SparkExitBroadcastOutcome.RetryLater("min relay fee not met, 5 < 17"))) + } + @Test fun `a transaction is unknown only when every host says so`() = test { val unknown = Route("a.example/api/tx/t/hex", 404, "Transaction not found") diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index b22c90f916..d2181a3814 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -247,6 +247,46 @@ class SparkExitDriverTest : BaseUnitTest() { assertNull(record.surfacedRejection) } + @Test + fun `a step refused for a fee under the network's floor reads as underpriced at once and never rebuilds`() = test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1", cpfp = "03c"))) + var record = running(recovery, builtAt = now - interval) + chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 5 < 17") + repeat(4) { sdk.checks += check(recovery, RecoveryVerdict.Valid) } + + record = driver(tip = 1_000u).tick(record) + assertEquals("n1", record.underpricedStep(null)?.txid) + repeat(3) { + now += interval + record = driver(tip = 1_001u).tick(record) + } + + assertEquals(0, record.broadcastLog.single().rejections) + assertNull(record.stuckStep) + assertEquals(1, record.generation) + assertTrue(sdk.prepareRequests.isEmpty()) + assertNull(record.surfacedRejection) + assertEquals("n1", record.underpricedStep(1_001u)?.txid) + assertEquals( + 2uL, + SparkExitUiState(record = record, tipHeight = 1_001u).lowFeeRate, + ) + } + + @Test + fun `a mempool floor refusal reads as underpriced and a lost replacement race does not`() = test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1", cpfp = "03c"))) + sdk.checks += check(recovery, RecoveryVerdict.Valid) + sdk.checks += check(recovery, RecoveryVerdict.Valid) + chain.outcome = SparkExitBroadcastOutcome.Rejected("mempool min fee not met, 300 < 400") + assertNotNull(driver(tip = 1_000u).tick(running(recovery)).underpricedStep(1_000u)) + + chain.outcome = SparkExitBroadcastOutcome.Rejected("insufficient fee, rejecting replacement") + val raced = driver(tip = 1_000u).tick(running(recovery)) + assertNull(raced.underpricedStep(1_000u)) + assertEquals(1, raced.broadcastLog.single().rejections) + } + @Test fun `a unilateral step the sdk could not read is not sent and rebuilds once a block`() = test { val unverified = SparkExitFixtures.recovery( From 25213f7c22c3ac0fc4b5d680ef306b5c99540a38 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 22:51:39 +0100 Subject: [PATCH 013/154] feat: spark exit funds each step separately --- .../to/bitkit/repositories/SparkExitDriver.kt | 7 ++- .../bitkit/repositories/SparkExitFunding.kt | 33 +++++++++- .../to/bitkit/repositories/SparkExitRecord.kt | 23 ++++++- .../to/bitkit/repositories/SparkExitRepo.kt | 12 +++- .../settings/lightning/SparkExitComponents.kt | 3 +- .../lightning/SparkExitFundingScreen.kt | 13 +++- .../settings/lightning/SparkExitViewModel.kt | 17 +++++- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../repositories/SparkExitDriverTest.kt | 14 +++++ .../repositories/SparkExitFundingTest.kt | 60 +++++++++++++++++++ .../lightning/SparkExitViewModelTest.kt | 7 ++- 26 files changed, 191 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index a5a7f5ce66..6ebebf18f9 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -304,6 +304,7 @@ class SparkExitDriver( private fun prepareRequest(record: SparkExitRecord, selection: ExitLeafSelection) = PrepareRecoverFundsRequest( feeRateSatPerVbyte = record.feeRateSatPerVbyte, fundingKind = CpfpFundingKind.P2wpkh, + fundingStrategy = record.cpfpFundingStrategy, destination = record.destination, selection = selection, ) @@ -785,12 +786,16 @@ val SparkExitRecord.isFeeChainStuck: Boolean it.generation == generation && it.feeChainFailures >= SparkExitDriver.FEE_CHAIN_FAILURES_TO_REBUILD } -/** Transaction ids of the CPFP children, which the SDK returns as hex only. */ +/** Transaction ids of what the exit's funding became, which the SDK returns as hex only for the CPFP children. */ object SparkExitTxids { fun cpfpChildTxids(recovery: RecoverFundsResponse): List = recovery.transactions.mapNotNull { tx -> tx.cpfpTxHex?.let { runCatching { SignedTransactionId.fromHex(it) }.getOrNull() } } + + /** The CPFP children and the fan-out: their outputs at the funding address are the exit's own, not new funding. */ + fun fundingTxids(recovery: RecoverFundsResponse): List = + cpfpChildTxids(recovery) + recovery.transactions.filter { it.kind == RecoveryTxKind.FAN_OUT }.map { it.txid } } /** How the exit's CPFP children chain: each spends its node's anchor and the change of the child before it. */ diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index f2d511f979..7fd1a9f35a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -112,6 +112,12 @@ data class SparkExitQuote( return beyond?.let { SparkExitMath.beyondLostLeaves(it, lostLeafSats) }?.takeIf { it > 0uL } } + /** + * How many UTXOs the SDK splits the fee funding into, one per transaction it fee-bumps under per-node funding: the + * funding screen names it when more than one. + */ + val fundedSteps: Int get() = prepared.funding?.perBranch?.size ?: 0 + /** Breez's rule: only exit when the value is more than its fees. */ val isWorthExiting: Boolean get() = prepared.leaves.isNotEmpty() && exitSats > networkFeeSats } @@ -240,12 +246,12 @@ object SparkExitMath { recovery.transactions.count { it.status is ExitTransactionStatus.Confirmed } /** - * UTXOs at the funding address that are new funding: neither an adopted input nor change a CPFP child of this or - * an earlier generation chained there. + * UTXOs at the funding address that are new funding: neither an adopted input nor an output a CPFP child or the + * fan-out of this or an earlier generation paid there. */ fun newFunding(utxos: List, record: SparkExitRecord): List { val adopted = record.funding.mapNotNull { f -> f.txid?.let { "$it:${f.vout ?: 0u}" } }.toSet() - val chained = (record.recovery?.let(SparkExitTxids::cpfpChildTxids).orEmpty() + record.earlierCpfpTxids).toSet() + val chained = (record.recovery?.let(SparkExitTxids::fundingTxids).orEmpty() + record.earlierCpfpTxids).toSet() return utxos.filter { "${it.txid}:${it.vout}" !in adopted && it.txid !in chained } } @@ -329,6 +335,24 @@ object SparkExitMath { return SparkExitFundingState.Ask(maxOf(required - seen, FUNDING_DUST_SATS), seen, required) } + /** + * The pre-start funding screen's reading of the funding address: [receivedSats] in [payments] UTXOs against the + * quote's [fundingSats] at [feeRateSatPerVbyte]. Each payment beyond the first adds its input's fee to what the + * exit needs, and a payment still to send adds one more, as the progress screen's ask does. + */ + fun prestartFunding( + fundingSats: ULong, + payments: Int, + receivedSats: ULong, + feeRateSatPerVbyte: ULong, + ): SparkExitPrestartFunding { + val inputFee = inputFeeSats(feeRateSatPerVbyte) + val covered = fundingSats.safe() + (inputFee.safe() * maxOf(payments - 1, 0).toULong().safe()).safe() + val isCovered = fundingSats > 0uL && payments > 0 && receivedSats >= covered + val partial = if (isCovered || receivedSats == 0uL) null else partialFunding(receivedSats, covered + inputFee) + return SparkExitPrestartFunding(isCovered, partial) + } + /** What reached the funding address against [requiredSats], once some but not all of it did; else null. */ fun partialFunding(receivedSats: ULong, requiredSats: ULong): SparkExitPartialFunding? { if (receivedSats == 0uL || receivedSats >= requiredSats) return null @@ -464,5 +488,8 @@ sealed interface SparkExitFundingState { /** A funding payment short of the need: [receivedSats] of [requiredSats] arrived, [missingSats] (at least dust) due. */ data class SparkExitPartialFunding(val receivedSats: ULong, val requiredSats: ULong, val missingSats: ULong) +/** Whether the funding address covers the quote before the exit starts, and the hint while it does not. */ +data class SparkExitPrestartFunding(val isCovered: Boolean, val partial: SparkExitPartialFunding?) + /** When to warn that the exit fell behind, and when its next step's operator window closes, both from now. */ data class SparkExitDeadline(val warnIn: Duration, val deadlineIn: Duration) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 6de03325f4..6d0f6180cf 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -2,6 +2,7 @@ package to.bitkit.repositories import breez_sdk_spark.CooperativeRecoveryError import breez_sdk_spark.CooperativeRecoveryFailure +import breez_sdk_spark.CpfpFundingStrategy import breez_sdk_spark.CpfpInput import breez_sdk_spark.ExitTransactionStatus import breez_sdk_spark.RecoverFundsLeaf @@ -63,7 +64,10 @@ data class SparkExitRecord( val lastBuildAt: Long? = null, /** The value of the quote's leaves, to show what Spark holds outside the exit. */ val leafTotalSats: ULong? = null, - /** The CPFP child txids of replaced generations, whose change at the funding address is not new funding. */ + /** + * The CPFP child and fan-out txids of replaced generations, whose outputs at the funding address are not new + * funding. The name predates the fan-out ids, kept so stored records read the same. + */ val earlierCpfpTxids: List = emptyList(), /** The sweep of [leftover] to [destination] once the exit ended. */ val leftoverSweep: LeftoverSweep? = null, @@ -103,6 +107,11 @@ data class SparkExitRecord( val isRedoRebuild: Boolean = false, /** What confirmed SWEEP and COOPERATIVE steps of replaced generations paid to [destination], by txid. */ val earlierReceivedSats: Map = emptyMap(), + /** + * How the funding pays the CPFP children, [PER_NODE] for exits started on SDK 0.28 and later; null funds one UTXO + * per branch, as exits started before did. Every prepare of the exit resumes with it. + */ + val fundingStrategy: String? = null, ) { companion object { const val CURRENT_VERSION = 1 @@ -112,6 +121,9 @@ data class SparkExitRecord( /** Blocks a step a node accepted may go unconfirmed before the exit's fee rate counts as too low. */ const val UNCONFIRMED_BLOCKS_TO_SURFACE = 6u + + /** [fundingStrategy] of an exit that funds each fee-bumped transaction from a UTXO of its own. */ + const val PER_NODE = "perNode" } sealed interface Phase { @@ -229,6 +241,10 @@ data class SparkExitRecord( val fundingInputs: List get() = funding.mapNotNull { it.input } + /** The strategy every prepare of this exit passes; null is the SDK's default, one UTXO per branch. */ + val cpfpFundingStrategy: CpfpFundingStrategy? + get() = CpfpFundingStrategy.PER_NODE.takeIf { fundingStrategy == PER_NODE } + /** The funding key index of this exit; records from before exits had their own index hold 0. */ val fundingIndex: UInt get() = funding.firstOrNull()?.index ?: 0u @@ -267,7 +283,7 @@ data class SparkExitRecord( isRedoRebuild = false, earlierReceivedSats = earlierReceivedSats + recovery?.let { SparkExitMath.confirmedReceived(it, destination) } .orEmpty(), - earlierCpfpTxids = (earlierCpfpTxids + recovery?.let(SparkExitTxids::cpfpChildTxids).orEmpty()).distinct(), + earlierCpfpTxids = (earlierCpfpTxids + recovery?.let(SparkExitTxids::fundingTxids).orEmpty()).distinct(), generation = generation + 1, recovery = built, broadcastLog = emptyList(), @@ -510,6 +526,7 @@ object SparkExitJson { isRebuilding = phase == SparkExitRecord.Phase.Running, isRebuiltFromChain = isActive, exitStateSnapshot = read { o.stringOrNull("exitStateSnapshot") }, + fundingStrategy = read { o.stringOrNull("fundingStrategy") }, ) } @@ -664,6 +681,7 @@ object SparkExitJson { r.exitStateSnapshot?.let { put("exitStateSnapshot", it) } if (r.isRebuiltFromChain) put("isRebuiltFromChain", true) if (r.isRedoRebuild) put("isRedoRebuild", true) + r.fundingStrategy?.let { put("fundingStrategy", it) } if (r.earlierReceivedSats.isNotEmpty()) { put( "earlierReceivedSats", @@ -758,6 +776,7 @@ object SparkExitJson { exitStateSnapshot = o.stringOrNull("exitStateSnapshot"), isRebuiltFromChain = o.booleanOrNull("isRebuiltFromChain") ?: false, isRedoRebuild = o.booleanOrNull("isRedoRebuild") ?: false, + fundingStrategy = o.stringOrNull("fundingStrategy"), earlierReceivedSats = o.objectOrNull("earlierReceivedSats") ?.mapValues { it.value.jsonPrimitive.content.toULong() } .orEmpty(), diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 4fd0dcbc3e..46a1b208b8 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -1,6 +1,7 @@ package to.bitkit.repositories import breez_sdk_spark.CpfpFundingKind +import breez_sdk_spark.CpfpFundingStrategy import breez_sdk_spark.CpfpSigner import breez_sdk_spark.ExitLeafSelection import breez_sdk_spark.PrepareRecoverFundsRequest @@ -371,6 +372,9 @@ class SparkExitRepo @Inject constructor( PrepareRecoverFundsRequest( feeRateSatPerVbyte = feeRate, fundingKind = CpfpFundingKind.P2wpkh, + // Each fee-bumped transaction gets a UTXO of its own, so one lost fee race strands one step's + // funding, not the chain after it. + fundingStrategy = CpfpFundingStrategy.PER_NODE, destination = destination, selection = ExitLeafSelection.All, ), @@ -411,8 +415,9 @@ class SparkExitRepo @Inject constructor( runSuspendCatching { val chain = requireNotNull(chain) { "No chain host for this network" } val address = requireNotNull(_state.value.fundingAddress) { "No Spark exit funding address" } - val seen = chain.utxos(address).fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } - _state.update { it.copy(fundingSeenSats = seen) } + val utxos = chain.utxos(address) + val seen = utxos.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + _state.update { it.copy(fundingSeenSats = seen, fundingSeenCount = utxos.size) } seen } } @@ -440,6 +445,7 @@ class SparkExitRepo @Inject constructor( ), expectedSats = quote.incomingSats, skippedLeafCount = quote.prepared.skipped.size, + fundingStrategy = SparkExitRecord.PER_NODE, leafTotalSats = quote.prepared.leaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() }, ) // Saved before the transfer exists, so a failed save never leaves a transfer counted with no exit behind. @@ -588,6 +594,8 @@ data class SparkExitState( val tipHeight: UInt? = null, /** Confirmed or not, what reached the funding address. */ val fundingSeenSats: ULong = 0uL, + /** How many payments make up [fundingSeenSats] before the exit starts: each adds its own input fee. */ + val fundingSeenCount: Int = 0, /** What progress shows while the exit needs fee funding. */ val fundingState: SparkExitFundingState? = null, val fundingAddress: String? = null, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt index ef9d0932b2..f694d5b37e 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -69,6 +69,7 @@ internal fun SparkExitFundingAddress( seenSats: ULong, modifier: Modifier = Modifier, partial: SparkExitPartialFunding? = SparkExitMath.partialFunding(seenSats, requiredSats), + isCovered: Boolean = requiredSats > 0uL && seenSats >= requiredSats, ) { val context = LocalContext.current Column( @@ -104,7 +105,7 @@ internal fun SparkExitFundingAddress( .testTag("SparkExitFundingPartial") ) } - if (requiredSats > 0uL && seenSats >= requiredSats) { + if (isCovered) { CaptionM( text = stringResource(R.string.lightning__spark_exit__fund_seen).withAccent(), color = Colors.Green, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt index 941a988aab..fd79bec998 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt @@ -17,6 +17,7 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import to.bitkit.R import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.BodyS import to.bitkit.ui.components.CaptionM import to.bitkit.ui.components.Display import to.bitkit.ui.components.PrimaryButton @@ -83,13 +84,23 @@ private fun Content( .withAccentBoldBright(), color = Colors.White64, ) + uiState.quote?.fundedSteps?.takeIf { it > 1 }?.let { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__funding_split).replace("{count}", "$it"), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitFundingSplit") + ) + } val address = uiState.fundingAddress if (uiState.showsFundingAddress && address != null) { VerticalSpacer(24.dp) SparkExitFundingAddress( address = address, requiredSats = fundingSats, - seenSats = uiState.fundingSeenSats + seenSats = uiState.fundingSeenSats, + partial = uiState.prestartFunding.partial, + isCovered = uiState.canContinueFunding, ) } VerticalSpacer(32.dp) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index 3042de9ec6..5fe076ec56 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -20,6 +20,7 @@ import to.bitkit.repositories.SparkExitBackgroundLimits import to.bitkit.repositories.SparkExitFundingKey import to.bitkit.repositories.SparkExitFundingState import to.bitkit.repositories.SparkExitMath +import to.bitkit.repositories.SparkExitPrestartFunding import to.bitkit.repositories.SparkExitQuote import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo @@ -63,6 +64,8 @@ class SparkExitViewModel @Inject constructor( record = exit.record, tipHeight = exit.tipHeight, fundingSeenSats = exit.fundingSeenSats, + fundingSeenCount = exit.fundingSeenCount, + fundingFeeRate = exit.pending?.feeRate, fundingState = exit.fundingState, fundingAddress = exit.fundingAddress, canCancel = sparkExitRepo.canCancel, @@ -205,6 +208,9 @@ data class SparkExitUiState( val record: SparkExitRecord? = null, val tipHeight: UInt? = null, val fundingSeenSats: ULong = 0uL, + val fundingSeenCount: Int = 0, + /** The quote's fee rate, which prices each extra payment to the funding address. */ + val fundingFeeRate: ULong? = null, /** What progress shows while the exit needs fee funding. */ val fundingState: SparkExitFundingState? = null, val fundingAddress: String? = null, @@ -222,8 +228,15 @@ data class SparkExitUiState( ) { val fundingSats: ULong get() = quote?.fundingSats ?: 0uL - /** Continue after funding from another wallet: once the funding address holds what the quote asks for. */ - val canContinueFunding: Boolean get() = fundingSats > 0uL && fundingSeenSats >= fundingSats + /** What the funding address holds against the quote before the exit starts. */ + val prestartFunding: SparkExitPrestartFunding + get() = SparkExitMath.prestartFunding(fundingSats, fundingSeenCount, fundingSeenSats, fundingFeeRate ?: 0uL) + + /** + * Continue after funding from another wallet: once the funding address holds what the quote asks for, plus the + * input fee of each payment beyond the first. + */ + val canContinueFunding: Boolean get() = prestartFunding.isCovered /** Why the quote cannot continue, or null when it can. */ val quoteBlock: SparkExitQuoteBlock? diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 03745b6d42..26dcc120b7 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -251,6 +251,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 61d1d56e3b..a24ff22486 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -258,6 +258,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 2eca2da458..a4a47e6e12 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -255,6 +255,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index e6c73fb139..123f85b428 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -258,6 +258,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index bd792589fb..9bc2140168 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -135,6 +135,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 68cd180df1..2fa7aa7a83 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -251,6 +251,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index fd07eb3153..494f1d57a3 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -257,6 +257,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index b2f90a54f7..bfe8f6f602 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -199,6 +199,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index fe35684990..1e78e915dd 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -134,6 +134,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 3e94de93d7..831e94a311 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -256,6 +256,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 1951dc5755..21ac9ff12e 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -255,6 +255,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 2868dcc353..3eae5469e4 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -136,6 +136,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index b02dbc8eba..ac0a6c1543 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -259,6 +259,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index ed67aaed33..2886cfd4f0 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -131,6 +131,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 3e9ba25d68..5827cfb2a4 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -267,6 +267,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 462434dc3e..279ceb218b 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -415,6 +415,7 @@ Pay from savings Payment seen. Fee funding needed + Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> Transaction ID: {txid} diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 4fb69f878d..355cd8cf0c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -3,6 +3,7 @@ package to.bitkit.repositories import breez_sdk_spark.CheckRecoverFundsResponse import breez_sdk_spark.CooperativeRecoveryError import breez_sdk_spark.CooperativeRecoveryFailure +import breez_sdk_spark.CpfpFundingStrategy import breez_sdk_spark.CpfpInput import breez_sdk_spark.ExitChainState import breez_sdk_spark.ExitLeafSelection @@ -687,6 +688,19 @@ class SparkExitDriverTest : BaseUnitTest() { assertTrue(ticked.isRebuilding) } + @Test + fun `every prepare resumes with the strategy the exit was quoted with`() = test { + val perBranch = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) + .copy(isRebuilding = true) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + + driver().tick(perBranch) + driver().tick(perBranch.copy(fundingStrategy = SparkExitRecord.PER_NODE)) + + assertEquals(listOf(null, CpfpFundingStrategy.PER_NODE), sdk.prepareRequests.map { it.fundingStrategy }) + } + @Test fun `rebuild waits while the operators could not be reached for a leaf`() = test { val record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 9c05c449c6..1f72d967bb 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -1,6 +1,9 @@ package to.bitkit.repositories +import breez_sdk_spark.CpfpFundingStrategy import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.PerBranchFunding +import breez_sdk_spark.RecoveryFunding import breez_sdk_spark.RecoveryTxKind import breez_sdk_spark.SkippedLeaf import breez_sdk_spark.SkippedLeafReason @@ -448,4 +451,61 @@ class SparkExitFundingTest { SparkExitMath.partialFunding(19_932uL, 20_000uL) ) } + + @Test + fun `before the start each payment beyond the first adds its input fee`() { + // 2 sat/vB: 136 sats per extra input. + val one = SparkExitMath.prestartFunding( + 20_000uL, + payments = 1, + receivedSats = 20_000uL, + feeRateSatPerVbyte = 2uL + ) + assertEquals(SparkExitPrestartFunding(isCovered = true, partial = null), one) + // Short after one payment: the hint names the funding plus the fee of the coin still to send. + val short = SparkExitMath.prestartFunding( + 20_000uL, + payments = 1, + receivedSats = 8_000uL, + feeRateSatPerVbyte = 2uL + ) + assertEquals(SparkExitPartialFunding(8_000uL, 20_136uL, 12_136uL), short.partial) + assertFalse(short.isCovered) + // Two payments that reach the funding still miss the second one's input fee. + val two = SparkExitMath.prestartFunding( + 20_000uL, + payments = 2, + receivedSats = 20_000uL, + feeRateSatPerVbyte = 2uL + ) + assertFalse(two.isCovered) + assertEquals(SparkExitPartialFunding(20_000uL, 20_272uL, 294uL), two.partial) + assertTrue(SparkExitMath.prestartFunding(20_000uL, 2, 20_136uL, 2uL).isCovered) + assertEquals(SparkExitPrestartFunding(false, null), SparkExitMath.prestartFunding(20_000uL, 0, 0uL, 2uL)) + } + + @Test + fun `the fan-out's outputs at the funding address are not new funding`() { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("fan", kind = RecoveryTxKind.FAN_OUT))) + val record = SparkExitFixtures.record(SparkExitRecord.Phase.NeedsFunding(30_000uL)).copy(recovery = recovery) + val utxos = listOf( + SparkExitFixtures.utxo("fan", value = 5_000uL), + SparkExitFixtures.utxo("ext", value = 9_000uL) + ) + + assertEquals(listOf("ext"), SparkExitMath.newFunding(utxos, record).map { it.txid }) + // Kept for the generations after it too. + val next = record.adopt(SparkExitFixtures.recovery(emptyList()), 1L) + assertEquals(listOf("ext"), SparkExitMath.newFunding(utxos, next).map { it.txid }) + } + + @Test + fun `a per-node quote names how many parts the funding is split into`() { + val entries = List(3) { PerBranchFunding("leaf-$it", 2_000uL) } + val prepared = SparkExitFixtures.prepared().let { + it.copy(funding = RecoveryFunding(7_000uL, entries, CpfpFundingStrategy.PER_NODE)) + } + assertEquals(3, SparkExitQuote(prepared).fundedSteps) + assertEquals(7_000uL, SparkExitQuote(prepared).fundingSats) + } } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 9a8489ac87..cf86071c87 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -54,8 +54,11 @@ class SparkExitViewModelTest : BaseUnitTest() { fun `funding from another wallet continues only once the address holds what the quote asks`() { val quote = SparkExitQuote(SparkExitFixtures.prepared(funding = 20_000uL)) assertFalse(SparkExitUiState().canContinueFunding) - assertFalse(SparkExitUiState(quote = quote, fundingSeenSats = 8_000uL).canContinueFunding) - assertTrue(SparkExitUiState(quote = quote, fundingSeenSats = 20_000uL).canContinueFunding) + val paid = SparkExitUiState(quote = quote, fundingSeenCount = 1, fundingFeeRate = 2uL) + assertFalse(paid.copy(fundingSeenSats = 8_000uL).canContinueFunding) + assertTrue(paid.copy(fundingSeenSats = 20_000uL).canContinueFunding) + // A second payment adds its input fee. + assertFalse(paid.copy(fundingSeenSats = 20_000uL, fundingSeenCount = 2).canContinueFunding) } @Test From 4ffbca905bc69826afc70a5f2a6ab1ec3d537e3a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 22:51:39 +0100 Subject: [PATCH 014/154] fix: spark exit alarm names a low fee and keeps an ended exit's leftover --- .../to/bitkit/repositories/SparkExitRecord.kt | 7 +++ .../to/bitkit/repositories/SparkExitRepo.kt | 3 +- .../to/bitkit/repositories/SparkExitWorker.kt | 45 ++++++++++++++++--- .../repositories/SparkExitAlertsTest.kt | 6 +++ .../repositories/SparkExitRecordTest.kt | 10 ++++- 5 files changed, 62 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 6d0f6180cf..06f599fe49 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -527,6 +527,13 @@ object SparkExitJson { isRebuiltFromChain = isActive, exitStateSnapshot = read { o.stringOrNull("exitStateSnapshot") }, fundingStrategy = read { o.stringOrNull("fundingStrategy") }, + // An exit that had ended still sweeps what it left at its funding address. + leftover = read { + o.arrayOrEmpty("leftover").map { + val l = it.jsonObject + SparkExitRecord.Leftover(l.string("txid"), l.ulong("vout").toUInt(), l.ulong("valueSats")) + } + }.orEmpty(), ) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 46a1b208b8..f5cf6cb7fd 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -325,8 +325,9 @@ class SparkExitRepo @Inject constructor( } when (record.phase) { SparkExitRecord.Phase.Running -> { - if (!isOnTrack) return val tip = _state.value.tipHeight + work.keepFeeLow(record.feeRateSatPerVbyte.takeIf { record.underpricedStep(tip) != null }) + if (!isOnTrack) return val untilMaturity = SparkExitMath.untilNextMaturity(record.recovery, tip, Env.network) work.armDeadline( SparkExitMath.deadline(untilMaturity, Env.network), diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index b7974ba63b..0a38846fd8 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -80,6 +80,7 @@ class SparkExitWork @Inject constructor( private const val PREFERENCES = "spark-exit-work" private const val KEY_WARN_AT = "warn-at" private const val KEY_DEADLINE_AT = "deadline-at" + private const val KEY_FEE_LOW_RATE = "fee-low-rate" private const val NOTIFICATION_ID = 7797 /** The shortest period WorkManager runs periodic work at. */ @@ -156,6 +157,21 @@ class SparkExitWork @Inject constructor( preferences.edit { remove(KEY_WARN_AT) remove(KEY_DEADLINE_AT) + remove(KEY_FEE_LOW_RATE) + } + } + + /** + * Keeps the exit's fee rate while the network finds it too low, or forgets it with null, so the deadline alarm + * names the fee even when the process that saw it is gone. + */ + fun keepFeeLow(feeRateSatPerVbyte: ULong?) { + preferences.edit { + if (feeRateSatPerVbyte == null) { + remove(KEY_FEE_LOW_RATE) + } else { + putLong(KEY_FEE_LOW_RATE, feeRateSatPerVbyte.toLong()) + } } } @@ -180,7 +196,8 @@ class SparkExitWork @Inject constructor( return } val record = loaded.getOrNull() - val alert = SparkExitAlerts.reason(record, isOnline(), backgroundLimits()) + val feeLowRate = preferences.getLong(KEY_FEE_LOW_RATE, 0L).takeIf { it > 0L }?.toULong() + val alert = SparkExitAlerts.reason(record, isOnline(), backgroundLimits(), feeLowRate) Logger.warn( "Spark exit deadline alarm fired with alert '$alert' (${context.logBatterySettings()})", context = TAG, @@ -190,7 +207,7 @@ class SparkExitWork @Inject constructor( return } val deadlineAt = preferences.getLong(KEY_DEADLINE_AT, 0L).takeIf { it > clock.nowMs() } - notify(alert, deadlineAt) + notify(alert, deadlineAt, feeRateSatPerVbyte = feeLowRate) enqueueCatchUp() armDeadline(SparkExitMath.deadline(Duration.ZERO, Env.network)) } @@ -204,7 +221,12 @@ class SparkExitWork @Inject constructor( } /** Posts the exit's notification, unless Bitkit is on screen, where the progress screen says the same. */ - fun notify(alert: SparkExitAlert, deadlineAtMillis: Long? = null, amountSats: ULong? = null) { + fun notify( + alert: SparkExitAlert, + deadlineAtMillis: Long? = null, + amountSats: ULong? = null, + feeRateSatPerVbyte: ULong? = null, + ) { // Losses are posted on screen too: the user may be anywhere in the app when an exit fails or loses a leaf. if (App.currentActivity?.value != null && alert !in ALWAYS_POSTED) return val time = deadlineAtMillis?.let { DateFormat.getTimeFormat(context).format(Date(it)) } @@ -212,6 +234,7 @@ class SparkExitWork @Inject constructor( val text = context.getString(alert.textRes(hasDeadline = time != null)) .replace("{time}", time.orEmpty()) .replace("{amount}", amount.orEmpty()) + .replace("{rate}", feeRateSatPerVbyte?.toString().orEmpty()) context.pushNotification( title = context.getString(R.string.lightning__spark_exit__notification_title), text = text, @@ -272,7 +295,7 @@ data class SparkExitBackgroundLimits( ) /** Why the user is asked to open Bitkit. */ -enum class SparkExitAlert { Funding, Lost, Failed, Rejected, Offline, Restricted, Battery, Behind } +enum class SparkExitAlert { Funding, Lost, Failed, Rejected, FeeLow, Offline, Restricted, Battery, Behind } private val ALWAYS_POSTED = setOf(SparkExitAlert.Lost, SparkExitAlert.Failed) @@ -298,14 +321,23 @@ object SparkExitAlerts { ) } - /** Why a running exit fell behind its deadline, or null when it needs nothing from the user. */ - fun reason(record: SparkExitRecord?, isOnline: Boolean, limits: SparkExitBackgroundLimits): SparkExitAlert? { + /** + * Why a running exit fell behind its deadline, or null when it needs nothing from the user. [feeLowRate] is the + * exit's rate while the network finds it too low, which no background run changes. + */ + fun reason( + record: SparkExitRecord?, + isOnline: Boolean, + limits: SparkExitBackgroundLimits, + feeLowRate: ULong? = null, + ): SparkExitAlert? { if (record?.isActive != true) return null return when { record.phase is SparkExitRecord.Phase.NeedsFunding -> SparkExitAlert.Funding record.phase != SparkExitRecord.Phase.Running -> null record.surfacedRejection != null || (record.stuckStep?.rejections ?: 0) >= SparkExitDriver.REJECTIONS_TO_SURFACE -> SparkExitAlert.Rejected + feeLowRate != null -> SparkExitAlert.FeeLow !isOnline -> SparkExitAlert.Offline limits.isRestricted -> SparkExitAlert.Restricted // Battery optimization alone is Android's default for nearly every app, so it names no cause. @@ -319,6 +351,7 @@ private fun SparkExitAlert.textRes(hasDeadline: Boolean): Int = when (this) { SparkExitAlert.Funding -> R.string.lightning__spark_exit__notification_funding SparkExitAlert.Lost -> R.string.lightning__spark_exit__notification_lost SparkExitAlert.Failed -> R.string.lightning__spark_exit__notification_failed + SparkExitAlert.FeeLow -> R.string.lightning__spark_exit__fee_low SparkExitAlert.Rejected if hasDeadline -> R.string.lightning__spark_exit__notification_rejected SparkExitAlert.Offline if hasDeadline -> R.string.lightning__spark_exit__notification_offline SparkExitAlert.Restricted if hasDeadline -> R.string.lightning__spark_exit__notification_restricted diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt index 3420bb9229..372ddb967c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt @@ -40,6 +40,12 @@ class SparkExitAlertsTest { SparkExitAlerts.reason(running, isOnline = true, unlimited.copy(isOptimized = true)), ) assertEquals(SparkExitAlert.Behind, SparkExitAlerts.reason(running, isOnline = true, unlimited)) + // An underpriced exit names its fee, which no background run fixes, before any cause of a missed run. + assertEquals( + SparkExitAlert.FeeLow, + SparkExitAlerts.reason(running, isOnline = false, unlimited.copy(isRestricted = true), feeLowRate = 2uL), + ) + assertEquals(SparkExitAlert.Rejected, SparkExitAlerts.reason(refused, isOnline = true, unlimited, 2uL)) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt index 15c1028e6f..2f501d2157 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -279,13 +279,19 @@ class SparkExitRecordTest { @Test fun `a salvaged record that had ended stays ended and one with nothing to rebuild from is not salvaged`() { - val done = SparkExitJson.encode(SparkExitFixtures.record(SparkExitRecord.Phase.Done)) - .replace("\"version\":1", "\"version\":9") + val leftover = listOf(SparkExitRecord.Leftover("change", 1u, 3_514uL)) + val ended = SparkExitFixtures.record(SparkExitRecord.Phase.Done) + .copy(leftover = leftover, fundingStrategy = SparkExitRecord.PER_NODE) + val done = SparkExitJson.encode(ended).replace("\"version\":1", "\"version\":9") val salvaged = assertNotNull(SparkExitJson.salvage(done, nowMillis = 42L)) assertEquals(SparkExitRecord.Phase.Done, salvaged.phase) assertFalse(salvaged.isRebuiltFromChain) + // It still sweeps what it left at its funding address. + assertEquals(leftover, salvaged.leftover) + assertTrue(salvaged.isLeftoverSweepPending) + assertEquals(SparkExitRecord.PER_NODE, salvaged.fundingStrategy) assertNull(SparkExitJson.salvage("{", nowMillis = 42L)) assertNull(SparkExitJson.salvage("""{"version":2,"network":"regtest"}""", nowMillis = 42L)) } From b9460dda9131681ae564ce4d62687ae55f5c02fb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 22:59:55 +0100 Subject: [PATCH 015/154] fix: spark exit regtest test names its prepare arguments --- .../java/to/bitkit/services/SparkExitRegtestTest.kt | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt b/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt index 73c54ef5ad..a77e2cd11d 100644 --- a/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt +++ b/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt @@ -4,6 +4,7 @@ import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import breez_sdk_spark.ConnectRequest import breez_sdk_spark.CpfpFundingKind +import breez_sdk_spark.CpfpFundingStrategy import breez_sdk_spark.ExitLeafSelection import breez_sdk_spark.PrepareRecoverFundsRequest import breez_sdk_spark.Seed @@ -67,7 +68,13 @@ class SparkExitRegtestTest { val feeRate = maxOf(1uL, sdk.recommendedFees().fastestFee) val prepared = BreezSparkExitRecovering(sdk).prepare( - PrepareRecoverFundsRequest(feeRate, CpfpFundingKind.P2wpkh, address.address, ExitLeafSelection.All), + PrepareRecoverFundsRequest( + feeRateSatPerVbyte = feeRate, + fundingKind = CpfpFundingKind.P2wpkh, + fundingStrategy = CpfpFundingStrategy.PER_NODE, + destination = address.address, + selection = ExitLeafSelection.All, + ), ) assertTrue(prepared.leaves.isEmpty()) assertFalse(SparkExitQuote(prepared).isWorthExiting) From baefdf2533744c1f8b009315717598e42ff1d5b3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 22:59:55 +0100 Subject: [PATCH 016/154] fix: spark exit retries leaves the operators moved on-chain --- .../to/bitkit/repositories/SparkExitDriver.kt | 53 +++++++++++++- .../to/bitkit/repositories/SparkExitRecord.kt | 48 +++++++++++++ .../to/bitkit/repositories/SparkExitRepo.kt | 5 ++ .../settings/lightning/SparkExitComponents.kt | 3 +- .../lightning/SparkExitProgressScreen.kt | 13 +++- app/src/main/res/values-ar/strings.xml | 3 +- app/src/main/res/values-b+es+419/strings.xml | 3 +- app/src/main/res/values-ca/strings.xml | 3 +- app/src/main/res/values-cs/strings.xml | 3 +- app/src/main/res/values-de/strings.xml | 3 +- app/src/main/res/values-el/strings.xml | 3 +- app/src/main/res/values-es-rES/strings.xml | 3 +- app/src/main/res/values-es/strings.xml | 3 +- app/src/main/res/values-fr/strings.xml | 3 +- app/src/main/res/values-it/strings.xml | 3 +- app/src/main/res/values-nl/strings.xml | 3 +- app/src/main/res/values-pl/strings.xml | 3 +- app/src/main/res/values-pt-rBR/strings.xml | 3 +- app/src/main/res/values-pt/strings.xml | 3 +- app/src/main/res/values-ru/strings.xml | 3 +- app/src/main/res/values/strings.xml | 3 +- .../repositories/SparkExitDriverTest.kt | 71 +++++++++++++++++++ 22 files changed, 221 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 6ebebf18f9..5a39705499 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -388,7 +388,13 @@ class SparkExitDriver( save(rebuilding) build(rebuilding, sdk) } - RecoveryVerdict.Done -> end(updated.copy(phase = SparkExitRecord.Phase.Done), updated) + RecoveryVerdict.Done -> { + // Leaves the operators moved on-chain but could not co-sign stay part of the exit, retried for a week. + if (checked.recovery.failed.isNotEmpty() && !updated.isFailedLeavesReleased) { + return retryFailedLeaves(updated, checked.recovery.failed.map { it.leafId }, sdk) + } + end(updated.copy(phase = SparkExitRecord.Phase.Done, failedLeaves = emptyList()), updated) + } is RecoveryVerdict.Redo -> { Logger.warn( "Rebuilding Spark exit diverged on-chain as generation '${record.generation + 1}'", @@ -400,6 +406,51 @@ class SparkExitDriver( } } + /** + * Builds a recovery of its own for [failedIds], the cooperative leaves a finished recovery could not get co-signed: + * at once, then at doubling gaps from 6 blocks to a day, as long-waiting leaves are. After about a week the exit + * is done without them. A recovery built for them is adopted as the next generation; what earlier ones landed + * still counts. + */ + private suspend fun retryFailedLeaves( + start: SparkExitRecord, + failedIds: List, + sdk: SparkExitRecovering, + ): SparkExitRecord { + val known = start.failedLeaves.associate { it.leafId to it.valueSats } + var record = start.copy(failedLeaves = failedIds.map { SparkExitRecord.FailedLeaf(it, known[it] ?: 0uL) }) + val height = tip ?: return record + val since = record.failedLeafRetrySince + if (since != null && SparkExitMath.isRetryReleased(since, height)) { + Logger.warn("Releasing Spark exit leaves '$failedIds' the operators did not co-sign", context = TAG) + val released = record.copy(phase = SparkExitRecord.Phase.Done, isFailedLeavesReleased = true) + return end(released, record) + } + if (since != null && !SparkExitMath.isRetryDue(since, record.failedLeafRetriedAt, height)) return record + record = record.copy(failedLeafRetrySince = since ?: height, failedLeafRetriedAt = height) + val retried = runSuspendCatching { + val prepared = sdk.prepare(prepareRequest(record, ExitLeafSelection.Specific(failedIds))) + val values = ( + prepared.leaves.map { it.leafId to it.valueSats } + + prepared.skipped.map { it.leafId to it.valueSats } + ).toMap() + record = record.copy( + failedLeaves = record.failedLeaves.map { it.copy(valueSats = values[it.leafId] ?: it.valueSats) }, + ) + if (prepared.leaves.isEmpty()) return@runSuspendCatching null + val needsFunding = prepared.funding != null + sdk.recover( + RecoverFundsRequest(prepared, if (needsFunding) record.fundingInputs else emptyList()), + if (needsFunding) makeSigner() else null, + ) + }.onFailure { Logger.warn("Failed to retry Spark exit leaves '$failedIds'", it, context = TAG) }.getOrNull() + if (retried == null || retried.transactions.isEmpty()) return record + val adopted = record.adopt(retried, nowMillis()) + save(adopted) + Logger.info("Built a recovery of Spark exit leaves '$failedIds' as '${adopted.generation}'", context = TAG) + return broadcastReady(adopted) + } + /** * Saves the exit as rebuilding, so nothing of this generation goes out again, and rebuilds it once the last build * is old enough, so a rebuild that reproduces the same problem cannot loop every tick. diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 06f599fe49..4beb68c666 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -112,6 +112,17 @@ data class SparkExitRecord( * per branch, as exits started before did. Every prepare of the exit resumes with it. */ val fundingStrategy: String? = null, + /** + * Cooperative leaves the operators moved on-chain but could not co-sign the recovery of, listed by a Done verdict. + * They stay part of the exit and are retried as their own recovery until [isFailedLeavesReleased]. + */ + val failedLeaves: List = emptyList(), + /** The tip at which a Done verdict first listed [failedLeaves]; they are let go about a week later. */ + val failedLeafRetrySince: UInt? = null, + /** The tip of the last retry of [failedLeaves]. */ + val failedLeafRetriedAt: UInt? = null, + /** The week of retries ended with [failedLeaves] still not recovered: the exit is done without them. */ + val isFailedLeavesReleased: Boolean = false, ) { companion object { const val CURRENT_VERSION = 1 @@ -190,6 +201,9 @@ data class SparkExitRecord( data class LeftBehindLeaf(val leafId: String, val valueSats: ULong, val reason: String) + /** A cooperative leaf the operators moved on-chain; [valueSats] is 0 until a retry's quote names it. */ + data class FailedLeaf(val leafId: String, val valueSats: ULong) + /** A built sweep of the leftover, saved before it is sent; a null [txid] means it was dust and nothing went. */ data class LeftoverSweep( val txid: String?, @@ -296,6 +310,15 @@ data class SparkExitRecord( isRebuiltFromChain = false, ) + /** The exit retries cooperative leaves the operators moved on-chain but could not co-sign. */ + val isRetryingFailedLeaves: Boolean get() = isActive && failedLeafRetrySince != null + + /** While retrying, the current recovery still lists leaves the operators have not co-signed. */ + val isWaitingForOperators: Boolean + get() = isRetryingFailedLeaves && recovery?.failed?.isNotEmpty() == true + + val failedLeafSats: ULong get() = failedLeaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() } + /** A build found nothing to build while a leaf may still move, and waits for it. */ val isWaitingForLeaves: Boolean get() = retrySince != null @@ -689,6 +712,24 @@ object SparkExitJson { if (r.isRebuiltFromChain) put("isRebuiltFromChain", true) if (r.isRedoRebuild) put("isRedoRebuild", true) r.fundingStrategy?.let { put("fundingStrategy", it) } + if (r.failedLeaves.isNotEmpty()) { + put( + "failedLeaves", + buildJsonArray { + r.failedLeaves.forEach { + add( + buildJsonObject { + put("leafId", it.leafId) + put("valueSats", it.valueSats.toLong()) + }, + ) + } + }, + ) + } + r.failedLeafRetrySince?.let { put("failedLeafRetrySince", it.toLong()) } + r.failedLeafRetriedAt?.let { put("failedLeafRetriedAt", it.toLong()) } + if (r.isFailedLeavesReleased) put("isFailedLeavesReleased", true) if (r.earlierReceivedSats.isNotEmpty()) { put( "earlierReceivedSats", @@ -784,6 +825,13 @@ object SparkExitJson { isRebuiltFromChain = o.booleanOrNull("isRebuiltFromChain") ?: false, isRedoRebuild = o.booleanOrNull("isRedoRebuild") ?: false, fundingStrategy = o.stringOrNull("fundingStrategy"), + failedLeaves = o.arrayOrEmpty("failedLeaves").map { + val l = it.jsonObject + SparkExitRecord.FailedLeaf(l.string("leafId"), l.ulong("valueSats")) + }, + failedLeafRetrySince = o.ulongOrNull("failedLeafRetrySince")?.toUInt(), + failedLeafRetriedAt = o.ulongOrNull("failedLeafRetriedAt")?.toUInt(), + isFailedLeavesReleased = o.booleanOrNull("isFailedLeavesReleased") ?: false, earlierReceivedSats = o.objectOrNull("earlierReceivedSats") ?.mapValues { it.value.jsonPrimitive.content.toULong() } .orEmpty(), diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index f5cf6cb7fd..16f59e36f5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -324,6 +324,11 @@ class SparkExitRepo @Inject constructor( work.notify(it, amountSats = record.lostSats.takeIf { _ -> it == SparkExitAlert.Lost }) } when (record.phase) { + // Waiting on the operators for a week needs nothing from the user, so nothing reminds them. + SparkExitRecord.Phase.Running if record.isWaitingForOperators -> { + work.keepFeeLow(null) + work.cancelDeadline() + } SparkExitRecord.Phase.Running -> { val tip = _state.value.tipHeight work.keepFeeLow(record.feeRateSatPerVbyte.takeIf { record.underpricedStep(tip) != null }) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt index f694d5b37e..2dbb5c45a8 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -138,7 +138,8 @@ internal fun SparkExitSteps(record: SparkExitRecord, tipHeight: UInt?) { val recovery: RecoverFundsResponse? = record.recovery val transactions = recovery?.transactions.orEmpty() val isFunded = record.phase !is SparkExitRecord.Phase.AwaitingFunding - val isDone = record.phase == SparkExitRecord.Phase.Done + // Retrying leaves the operators moved on-chain, every step of the exit itself is done. + val isDone = record.phase == SparkExitRecord.Phase.Done || record.isRetryingFailedLeaves val remaining = record.claimableAtHeight?.let { target -> tipHeight?.let { BlockTimeHelpers.blocksRemaining(target, it) } }?.takeIf { it > 0 }?.let(BlockTimeHelpers::getDurationForBlocks) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index f4ea96a92f..4e2b762841 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -186,6 +186,15 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState) modifier = Modifier.testTag("SparkExitRebuiltFromChain") ) } + if (record.isWaitingForOperators) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__waiting_operators) + .replace("{amount}", sparkExitAmountText(record.failedLeafSats)), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitWaitingOperators") + ) + } if (record.isWaitingForLeaves && record.isActive) { VerticalSpacer(16.dp) BodyS( @@ -331,8 +340,8 @@ private fun progressText( record.skippedLeafCount.takeIf { it > 0 }?.let { stringResource(R.string.lightning__spark_exit__partial_text).replace("{count}", "$it") }, - record.failedLeafCount.takeIf { it > 0 }?.let { - stringResource(R.string.lightning__spark_exit__failed_leaves).replace("{count}", "$it") + record.failedLeafSats.takeIf { record.isFailedLeavesReleased && it > 0uL }?.let { + stringResource(R.string.lightning__spark_exit__failed_leaves).replace("{amount}", sparkExitAmountText(it)) }, ).joinToString(" ") is SparkExitRecord.Phase.Failed -> sparkExitFailedText( diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 26dcc120b7..d99209ab77 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -236,7 +236,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -306,6 +306,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. المزوّد Spark عبر Breez بلا حد diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index a24ff22486..8c07696e87 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -243,7 +243,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -313,6 +313,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index a4a47e6e12..b4345f22cd 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -240,7 +240,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -310,6 +310,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Proveïdor Spark mitjançant Breez Sense límit diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 123f85b428..bceb452deb 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -243,7 +243,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -313,6 +313,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Poskytovatel Spark přes Breez Bez limitu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 9bc2140168..b6365ab905 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -120,7 +120,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -190,6 +190,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Anbieter Spark über Breez Kein Limit diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 2fa7aa7a83..1e1cfa47df 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -236,7 +236,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -306,6 +306,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Πάροχος Spark μέσω Breez Χωρίς όριο diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 494f1d57a3..68ef0bf3f5 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -242,7 +242,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -312,6 +312,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index bfe8f6f602..d27d415941 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -184,7 +184,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -254,6 +254,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 1e78e915dd..6f35b37111 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -119,7 +119,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -189,6 +189,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Fournisseur Spark via Breez Sans limite diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 831e94a311..993d5e833f 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -241,7 +241,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -311,6 +311,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Fornitore Spark tramite Breez Nessun limite diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 21ac9ff12e..91c8b8e58a 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -240,7 +240,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -310,6 +310,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Aanbieder Spark via Breez Geen limiet diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 3eae5469e4..e9bb764544 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -121,7 +121,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -191,6 +191,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Dostawca Spark przez Breez Bez limitu diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index ac0a6c1543..786756c6c5 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -244,7 +244,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -314,6 +314,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Provedor Spark via Breez Sem limite diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 2886cfd4f0..6279368cc4 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -116,7 +116,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -186,6 +186,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Fornecedor Spark via Breez Sem limite diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 5827cfb2a4..9d872d796a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -252,7 +252,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -322,6 +322,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Провайдер Spark через Breez Без ограничений diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 279ceb218b..bf14fa3719 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -400,7 +400,7 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {count} amounts the Spark operators could not sign for stayed on Spark. + {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> @@ -470,6 +470,7 @@ Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. + {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. Provider Spark via Breez No limit diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 355cd8cf0c..6894738d2b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -8,7 +8,9 @@ import breez_sdk_spark.CpfpInput import breez_sdk_spark.ExitChainState import breez_sdk_spark.ExitLeafSelection import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.RecoverFundsLeaf import breez_sdk_spark.RecoverFundsResponse +import breez_sdk_spark.RecoveryMethod import breez_sdk_spark.RecoveryRedoReason import breez_sdk_spark.RecoveryTxKind import breez_sdk_spark.RecoveryVerdict @@ -606,6 +608,75 @@ class SparkExitDriverTest : BaseUnitTest() { assertNull(record.recovery) } + private val operatorsDown = CooperativeRecoveryFailure( + "coop-1", + "o", + 0u, + CooperativeRecoveryError.OperatorsUnavailable("down"), + ) + + private fun coopLeaf(valueSats: ULong) = SparkExitFixtures.prepared(funding = null, leaves = emptyList()).copy( + leaves = listOf(RecoverFundsLeaf("coop-1", valueSats, RecoveryMethod.COOPERATIVE)), + ) + + @Test + fun `leaves the operators moved on-chain are retried at doubling gaps, then let go after a week`() = test { + val done = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("s", kind = RecoveryTxKind.SWEEP, status = ExitTransactionStatus.Confirmed(9u)) + ), + failed = listOf(operatorsDown), + ) + var record = running(done) + repeat(6) { sdk.checks += check(done, RecoveryVerdict.Done) } + sdk.preparedResponse = coopLeaf(16_384uL) + // The operators still cannot co-sign: the retry builds nothing. + repeat(3) { sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = listOf(operatorsDown)) } + + record = driver(tip = 1_000u).tick(record) + assertEquals(Phase.Running, record.phase) + assertTrue(record.isWaitingForOperators) + assertEquals(listOf(SparkExitRecord.FailedLeaf("coop-1", 16_384uL)), record.failedLeaves) + assertEquals(16_384uL, record.failedLeafSats) + assertEquals(listOf("coop-1"), (sdk.prepareRequests.single().selection as ExitLeafSelection.Specific).leafIds) + + record = driver(tip = 1_005u).tick(record) + assertEquals(1, sdk.prepareRequests.size) + record = driver(tip = 1_006u).tick(record) + assertEquals(2, sdk.prepareRequests.size) + assertEquals(1_006u, record.failedLeafRetriedAt) + + record = driver(tip = 2_007u).tick(record) + assertEquals(Phase.Running, record.phase) + record = driver(tip = 2_008u).tick(record) + assertEquals(Phase.Done, record.phase) + assertTrue(record.isFailedLeavesReleased) + assertEquals(16_384uL, record.failedLeafSats) + assertFalse(record.isWaitingForOperators) + } + + @Test + fun `a retry the operators co-sign becomes the next generation and the exit ends once it confirms`() = test { + val done = SparkExitFixtures.recovery(emptyList(), failed = listOf(operatorsDown)) + var record = running(done) + sdk.checks += check(done, RecoveryVerdict.Done) + sdk.preparedResponse = coopLeaf(16_384uL) + val coop = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("coop", kind = RecoveryTxKind.COOPERATIVE))) + sdk.builds += coop + + record = driver(tip = 1_000u).tick(record) + assertEquals(2, record.generation) + assertEquals(listOf("coop"), chain.broadcasts.map { it.txid }) + assertFalse(record.isWaitingForOperators) + assertTrue(record.isRetryingFailedLeaves) + + sdk.checks += check(coop, RecoveryVerdict.Done) + record = driver(tip = 1_001u).tick(record) + assertEquals(Phase.Done, record.phase) + assertTrue(record.failedLeaves.isEmpty()) + assertFalse(record.isFailedLeavesReleased) + } + @Test fun `rebuild with nothing left ends the exit`() = test { val record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) From fe94c07e6dc3701ca56dabbbb566079a57999796 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 23:16:44 +0100 Subject: [PATCH 017/154] feat: spark exit can pay a higher fee --- .../to/bitkit/repositories/SparkExitChain.kt | 12 ++ .../to/bitkit/repositories/SparkExitDriver.kt | 22 +++ .../bitkit/repositories/SparkExitFunding.kt | 25 +++ .../to/bitkit/repositories/SparkExitRecord.kt | 35 ++++ .../to/bitkit/repositories/SparkExitRepo.kt | 127 ++++++++++-- app/src/main/java/to/bitkit/ui/ContentView.kt | 12 ++ .../screens/wallets/send/SendFeeRateScreen.kt | 6 +- .../settings/lightning/SparkExitComponents.kt | 11 +- .../lightning/SparkExitFeeBumpScreen.kt | 181 ++++++++++++++++++ .../lightning/SparkExitProgressScreen.kt | 59 ++++-- .../settings/lightning/SparkExitViewModel.kt | 75 +++++++- app/src/main/res/values-ar/strings.xml | 11 +- app/src/main/res/values-b+es+419/strings.xml | 11 +- app/src/main/res/values-ca/strings.xml | 11 +- app/src/main/res/values-cs/strings.xml | 11 +- app/src/main/res/values-de/strings.xml | 11 +- app/src/main/res/values-el/strings.xml | 11 +- app/src/main/res/values-es-rES/strings.xml | 11 +- app/src/main/res/values-es/strings.xml | 11 +- app/src/main/res/values-fr/strings.xml | 11 +- app/src/main/res/values-it/strings.xml | 11 +- app/src/main/res/values-nl/strings.xml | 11 +- app/src/main/res/values-pl/strings.xml | 11 +- app/src/main/res/values-pt-rBR/strings.xml | 11 +- app/src/main/res/values-pt/strings.xml | 11 +- app/src/main/res/values-ru/strings.xml | 11 +- app/src/main/res/values/strings.xml | 11 +- .../repositories/SparkExitDriverTest.kt | 72 +++++++ .../bitkit/repositories/SparkExitFixtures.kt | 4 + .../repositories/SparkExitFundingTest.kt | 53 +++++ .../lightning/SparkExitViewModelTest.kt | 29 +++ docs/screens-map.md | 1 + 32 files changed, 824 insertions(+), 76 deletions(-) create mode 100644 app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 76fac44e7f..483c0ff282 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -80,8 +80,14 @@ interface SparkExitChain { /** The rate for the next block, from `/fee-estimates`, rounded up. */ suspend fun nextBlockFeeRate(): ULong + + /** The rates for the next block and about half an hour, from `/fee-estimates` targets 1 and 3, rounded up. */ + suspend fun networkFees(): SparkExitNetworkFees } +/** What the network asks now, in sat/vB: for the next block, and for about half an hour. */ +data class SparkExitNetworkFees(val fastest: ULong, val halfHour: ULong) + class SparkExitChainError(message: String) : AppError(message) /** A host an exit broadcasts through, with the paths it takes a package on, tried in order. */ @@ -152,6 +158,12 @@ class EsploraSparkExitChain( return ceil(rate.toDouble()).toULong() } + override suspend fun networkFees(): SparkExitNetworkFees { + val estimates = json.parseToJsonElement(get("/fee-estimates")).jsonObject + fun rate(target: String) = ceil(estimates.getValue(target).jsonPrimitive.content.toDouble()).toULong() + return SparkExitNetworkFees(fastest = rate("1"), halfHour = rate("3")) + } + override suspend fun isTxKnown(txid: String): Boolean { if (hosts.reads.isEmpty()) throw SparkExitChainError("No chain host configured") val path = "/tx/$txid/hex" diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 5a39705499..3f8a645260 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -406,6 +406,28 @@ class SparkExitDriver( } } + /** + * What the exit's funding address must still receive to rebuild at [rate]: a build of the exit's leaves with the + * funding it holds, nothing broadcast. Zero when that funding covers it; otherwise the SDK's shortfall less what + * the address still holds, with one more input's fee for the payment, at least dust. + */ + suspend fun feeBumpShortfall(record: SparkExitRecord, rate: ULong): ULong { + val sdk = checkNotNull(recovering) { "Spark is not connected" } + val atRate = record.copy(feeRateSatPerVbyte = rate) + val prepared = sdk.prepare(prepareRequest(atRate, ExitLeafSelection.Specific(atRate.exitLeafIds))) + if (prepared.funding == null) return 0uL + val built = + runSuspendCatching { sdk.recover(RecoverFundsRequest(prepared, atRate.fundingInputs), makeSigner()) } + val error = built.exceptionOrNull() ?: return 0uL + val required = (error as? SdkException.InsufficientCpfpFunds ?: throw error).requiredSats + val held = atRate.funding.firstOrNull()?.address?.let { address -> + runSuspendCatching { chain.utxos(address) }.getOrNull()?.let { SparkExitMath.heldSats(it, atRate) } + } + val needed = SparkExitMath.neededFunding(required, atRate.fundedSats, held, SparkExitMath.inputFeeSats(rate)) + val extra = if (needed > atRate.fundedSats) needed - atRate.fundedSats else 0uL + return maxOf(extra, SparkExitMath.FUNDING_DUST_SATS) + } + /** * Builds a recovery of its own for [failedIds], the cooperative leaves a finished recovery could not get co-signed: * at once, then at doubling gaps from 6 blocks to a day, as long-waiting leaves are. After about a week the exit diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 7fd1a9f35a..e679280501 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -6,6 +6,7 @@ import breez_sdk_spark.RecoverFundsResponse import breez_sdk_spark.RecoveryTransaction import breez_sdk_spark.RecoveryTxKind import org.lightningdevkit.ldknode.Network +import to.bitkit.models.FeeRate import to.bitkit.models.safe import to.bitkit.utils.AppError import to.bitkit.utils.BlockTimeHelpers @@ -488,6 +489,30 @@ sealed interface SparkExitFundingState { /** A funding payment short of the need: [receivedSats] of [requiredSats] arrived, [missingSats] (at least dust) due. */ data class SparkExitPartialFunding(val receivedSats: ULong, val requiredSats: ULong, val missingSats: ULong) +/** + * A higher rate a running exit can move to, at the send flow's [speed], with [extraSats] its funding address must + * still receive and [totalSats] what that costs from savings, the payment's own fee included. + */ +data class SparkExitFeeBumpOption( + val speed: FeeRate, + val rateSatPerVbyte: ULong, + val extraSats: ULong, + val totalSats: ULong, +) { + companion object { + /** + * The rates to offer above [exitRate], each strictly above it so the rebuild replaces what is in the mempool: + * Fast at the next block's rate, or one above the exit's when the network asks no more; Normal at the half-hour + * rate, only between the two. + */ + fun rates(exitRate: ULong, fees: SparkExitNetworkFees): List> { + val fast = maxOf(fees.fastest, exitRate + 1uL) + val normal = fees.halfHour.takeIf { it > exitRate && it < fast } + return listOfNotNull(FeeRate.FAST to fast, normal?.let { FeeRate.NORMAL to it }) + } + } +} + /** Whether the funding address covers the quote before the exit starts, and the hint while it does not. */ data class SparkExitPrestartFunding(val isCovered: Boolean, val partial: SparkExitPartialFunding?) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 4beb68c666..5e20e9e9be 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -123,6 +123,8 @@ data class SparkExitRecord( val failedLeafRetriedAt: UInt? = null, /** The week of retries ended with [failedLeaves] still not recovered: the exit is done without them. */ val isFailedLeavesReleased: Boolean = false, + /** The confirmed sweep of a replaced generation, so Done still names it after a retry of leaves replaced it. */ + val landedSweepTxid: String? = null, ) { companion object { const val CURRENT_VERSION = 1 @@ -298,6 +300,10 @@ data class SparkExitRecord( earlierReceivedSats = earlierReceivedSats + recovery?.let { SparkExitMath.confirmedReceived(it, destination) } .orEmpty(), earlierCpfpTxids = (earlierCpfpTxids + recovery?.let(SparkExitTxids::fundingTxids).orEmpty()).distinct(), + landedSweepTxid = recovery?.transactions + ?.firstOrNull { it.kind == RecoveryTxKind.SWEEP && it.status is ExitTransactionStatus.Confirmed } + ?.txid + ?: landedSweepTxid, generation = generation + 1, recovery = built, broadcastLog = emptyList(), @@ -310,6 +316,33 @@ data class SparkExitRecord( isRebuiltFromChain = false, ) + /** + * Whether the user may raise the exit's fee rate: it runs on a built recovery, is not rebuilding or retrying leaves + * the operators moved, and the network finds its rate too low ([underpricedStep]) or asks more for the next block + * ([fees]). + */ + fun canPayHigherFee(tip: UInt?, fees: SparkExitNetworkFees?): Boolean { + if (phase != Phase.Running || isRebuilding || recovery == null || isRetryingFailedLeaves) return false + return underpricedStep(tip) != null || isBelowNetwork(fees) + } + + /** The network asks more for the next block than the exit's rate. */ + fun isBelowNetwork(fees: SparkExitNetworkFees?): Boolean = fees != null && fees.fastest > feeRateSatPerVbyte + + /** + * The exit at [rate]: with [extraSats] of funding paid in [paymentTxid], it waits for that payment as a top-up + * and then rebuilds; with nothing to pay, it rebuilds on the next tick. Either way what has not confirmed goes + * out again at the new rate and replaces what is in the mempool. Not a Redo, so it strikes nothing. + */ + fun applyFeeBump(rate: ULong, extraSats: ULong, paymentTxid: String?): SparkExitRecord { + val bumped = copy(feeRateSatPerVbyte = rate, isRedoRebuild = false) + if (extraSats == 0uL) return bumped.copy(isRebuilding = true, lastBuildAt = null) + return bumped.copy( + phase = Phase.NeedsFunding(fundedSats.safe() + extraSats.safe()), + fundingPaymentTxid = paymentTxid, + ) + } + /** The exit retries cooperative leaves the operators moved on-chain but could not co-sign. */ val isRetryingFailedLeaves: Boolean get() = isActive && failedLeafRetrySince != null @@ -730,6 +763,7 @@ object SparkExitJson { r.failedLeafRetrySince?.let { put("failedLeafRetrySince", it.toLong()) } r.failedLeafRetriedAt?.let { put("failedLeafRetriedAt", it.toLong()) } if (r.isFailedLeavesReleased) put("isFailedLeavesReleased", true) + r.landedSweepTxid?.let { put("landedSweepTxid", it) } if (r.earlierReceivedSats.isNotEmpty()) { put( "earlierReceivedSats", @@ -832,6 +866,7 @@ object SparkExitJson { failedLeafRetrySince = o.ulongOrNull("failedLeafRetrySince")?.toUInt(), failedLeafRetriedAt = o.ulongOrNull("failedLeafRetriedAt")?.toUInt(), isFailedLeavesReleased = o.booleanOrNull("isFailedLeavesReleased") ?: false, + landedSweepTxid = o.stringOrNull("landedSweepTxid"), earlierReceivedSats = o.objectOrNull("earlierReceivedSats") ?.mapValues { it.value.jsonPrimitive.content.toULong() } .orEmpty(), diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 16f59e36f5..d90a79e023 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -206,18 +206,11 @@ class SparkExitRepo @Inject constructor( val tip = runSuspendCatching { chain.tipHeight() }.getOrNull() _state.update { it.copy(tipHeight = tip ?: it.tipHeight) } tip?.let { height -> sparkExitTip.height.update { height } } + refreshNetworkFees(chain) refreshFundingSeen(chain, current) val store = store val recovering = sparkService.exitRecovering() - val driver = SparkExitDriver( - chain = chain, - recovering = recovering, - // The record's own funding key, also for exits started before each exit had an index of its own. - makeSigner = { signer(current.fundingIndex) }, - save = store::save, - nowMillis = clock::nowMs, - tip = tip, - ) + val driver = driver(chain, recovering, current, tip) // Read before this tick's losses are kept, so a leaf lost now is still reported once. val reportedLost = reportedLostLeafIds() val updated = driver.tick(current) @@ -239,6 +232,21 @@ class SparkExitRepo @Inject constructor( return updated } + private fun driver( + chain: SparkExitChain, + recovering: SparkExitRecovering?, + record: SparkExitRecord, + tip: UInt?, + ) = SparkExitDriver( + chain = chain, + recovering = recovering, + // The record's own funding key, also for exits started before each exit had an index of its own. + makeSigner = { signer(record.fundingIndex) }, + save = store::save, + nowMillis = clock::nowMs, + tip = tip, + ) + private suspend fun afterTick( record: SparkExitRecord, previous: SparkExitRecord, @@ -288,6 +296,19 @@ class SparkExitRepo @Inject constructor( } } + /** The network's rates for the fee bump and its hint: the SDK's when Spark is connected, else the chain host's. */ + private suspend fun refreshNetworkFees(chain: SparkExitChain) { + val fees = runSuspendCatching { + if (sparkService.isConnected) { + SparkExitNetworkFees(sparkService.fastestFeeRate(), sparkService.halfHourFeeRate()) + } else { + chain.networkFees() + } + }.onFailure { Logger.warn("Failed to read the network fee rates for the Spark exit", it, context = TAG) } + .getOrNull() + _state.update { it.copy(networkFees = fees ?: it.networkFees) } + } + private suspend fun refreshFundingSeen(chain: SparkExitChain, record: SparkExitRecord) { val address = record.funding.firstOrNull()?.address ?: return _state.update { it.copy(fundingAddress = address) } @@ -401,6 +422,66 @@ class SparkExitRepo @Inject constructor( } } + /** + * The higher rates the running exit can move to, each with what its funding address must still receive and what + * that costs from savings, found by building the exit at each rate without broadcasting. Needs Spark connected. + */ + suspend fun feeBumpOptions(): Result> = withContext(bgDispatcher) { + runSuspendCatching { + val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } + val chain = requireNotNull(chain) { "No chain host for this network" } + val recovering = sparkService.exitRecovering() ?: throw SparkError.NotConnected() + refreshNetworkFees(chain) + val fees = requireNotNull(_state.value.networkFees) { "No network fee rates" } + val driver = driver(chain, recovering, record, _state.value.tipHeight) + val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } + SparkExitFeeBumpOption.rates(record.feeRateSatPerVbyte, fees).map { (speed, rate) -> + val extra = driver.feeBumpShortfall(record, rate) + val paymentFee = if (extra == 0uL) { + 0uL + } else { + lightningRepo.calculateTotalFee(extra, address, TransactionSpeed.Fast).getOrThrow() + } + SparkExitFeeBumpOption(speed, rate, extra, extra.safe() + paymentFee.safe()) + } + }.onFailure { + Logger.error("Failed to price a higher Spark exit fee", it, context = TAG) + } + } + + /** What savings can spend now, for the fee bump's rows. */ + suspend fun spendableSavingsSats(): Result = withContext(bgDispatcher) { + runSuspendCatching { lightningRepo.getBalancesAsync().getOrThrow().spendableOnchainBalanceSats } + } + + /** + * Moves the running exit to [option]'s rate: pays what its funding address still needs from savings, like the + * first funding, then rebuilds what has not confirmed at that rate, which replaces it in the mempool. + */ + suspend fun payHigherFee(option: SparkExitFeeBumpOption): Result = withContext(bgDispatcher) { + runSuspendCatching { + val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } + val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } + val txid = if (option.extraSats > 0uL) sendFunding(address, option.extraSats) else null + tickMutex.withLock { + val current = _state.value.record ?: return@withLock + val bumped = current.applyFeeBump(option.rateSatPerVbyte, option.extraSats, txid) + store.save(bumped) + _state.update { + it.copy(record = bumped, fundingState = SparkExitMath.fundingState(bumped, utxos = null)) + } + } + Logger.info( + "Raised the Spark exit fee to '${option.rateSatPerVbyte}' sat/vB, paying '${option.extraSats}' sats", + context = TAG, + ) + scope.launch { tick() } + Unit + }.onFailure { + Logger.error("Failed to raise the Spark exit fee", it, context = TAG) + } + } + /** The fee Savings pays to send the fee funding at the fast rate, or null when it cannot. */ suspend fun savingsFundingFee(): Result = withContext(bgDispatcher) { runSuspendCatching { @@ -485,8 +566,22 @@ class SparkExitRepo @Inject constructor( } } - /** Pays the fee funding from savings as an ordinary payment: it is a fee, not a transfer to spending. */ + /** Pays the fee funding from savings and keeps its txid, so progress waits for it instead of asking again. */ private suspend fun payFunding(address: String, sats: ULong) { + val txid = sendFunding(address, sats) + // After the tick in flight, so its save cannot drop the txid. + tickMutex.withLock { + val record = _state.value.record ?: return@withLock + val paid = record.copy(fundingPaymentTxid = txid) + store.save(paid) + _state.update { + it.copy(record = paid, fundingState = SparkExitMath.fundingState(paid, utxos = null)) + } + } + } + + /** Sends [sats] from savings to the funding address as an ordinary payment: a fee, not a transfer to spending. */ + private suspend fun sendFunding(address: String, sats: ULong): String { val outcome = lightningRepo.sendOnChain( address = address, sats = sats, @@ -497,18 +592,10 @@ class SparkExitRepo @Inject constructor( "Spark exit funding was not accepted: '$outcome'" ) } - // After the tick in flight, so its save cannot drop the txid; progress then waits for it instead of asking. - tickMutex.withLock { - val record = _state.value.record ?: return@withLock - val paid = record.copy(fundingPaymentTxid = outcome.txid) - store.save(paid) - _state.update { - it.copy(record = paid, fundingState = SparkExitMath.fundingState(paid, utxos = null)) - } - } runSuspendCatching { lightningRepo.completeAcceptedOrdinaryFollowup(outcome.txid) } .onFailure { Logger.warn("Failed to finish the Spark exit funding locally", it, context = TAG) } Logger.info("Funded the Spark exit with '$sats' sats in '${outcome.txid}'", context = TAG) + return outcome.txid } /** @@ -610,6 +697,8 @@ data class SparkExitState( val sparkBalanceSats: ULong? = null, /** The quote waits for Spark to finish moving leaves, so value in flight is not left out of the exit. */ val isSettling: Boolean = false, + /** What the network asks now, for the fee bump and its hint. */ + val networkFees: SparkExitNetworkFees? = null, ) { val isExiting: Boolean get() = record?.isActive == true diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 433e98811d..b77b10abea 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -207,6 +207,7 @@ import to.bitkit.ui.settings.lightning.LightningConnectionsScreen import to.bitkit.ui.settings.lightning.LightningConnectionsViewModel import to.bitkit.ui.settings.lightning.SparkDetailScreen import to.bitkit.ui.settings.lightning.SparkExitConfirmScreen +import to.bitkit.ui.settings.lightning.SparkExitFeeBumpScreen import to.bitkit.ui.settings.lightning.SparkExitFundingScreen import to.bitkit.ui.settings.lightning.SparkExitIntroScreen import to.bitkit.ui.settings.lightning.SparkExitProgressScreen @@ -2080,6 +2081,14 @@ private fun NavGraphBuilder.sparkExit(navController: NavHostController) { viewModel = exitViewModel(it), onBack = { navController.popBackStack() }, onDone = { leaveExit() }, + onPayHigherFee = { navController.navigateTo(Routes.SparkExitFeeBump) }, + ) + } + composableWithDefaultTransitions { + SparkExitFeeBumpScreen( + viewModel = exitViewModel(it), + onBack = { navController.popBackStack() }, + onDone = { navController.popBackStack() }, ) } } @@ -2560,6 +2569,9 @@ sealed interface Routes { @Serializable data object SparkExitProgress : Routes.InternalOnly + @Serializable + data object SparkExitFeeBump : Routes.InternalOnly + @Serializable data object DevSettings : Routes.DeepLinkable diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendFeeRateScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendFeeRateScreen.kt index 6f7e31fd7d..3c19fcb831 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendFeeRateScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendFeeRateScreen.kt @@ -148,12 +148,14 @@ private fun Content( } } +/** A speed row of the fee picker, also used by the Spark emergency exit's fee bump; [description] under its title. */ @Composable -private fun FeeItem( +internal fun FeeItem( feeRate: FeeRate, sats: Long, onClick: () -> Unit, modifier: Modifier = Modifier, + description: String = stringResource(feeRate.description), isSelected: Boolean = false, isDisabled: Boolean = false, unit: PrimaryDisplay = LocalCurrencies.current.primaryDisplay, @@ -186,7 +188,7 @@ private fun FeeItem( HorizontalSpacer(16.dp) Column { BodyMSB(stringResource(feeRate.title), color = color) - BodySSB(stringResource(feeRate.description), color = accent) + BodySSB(description, color = accent) } FillWidth() if (sats != 0L) { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt index 2dbb5c45a8..97dd02fdc8 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -117,10 +117,15 @@ internal fun SparkExitFundingAddress( /** A line of progress with the transaction it is about, whose id copies on tap. */ @Composable -internal fun SparkExitTxNote(text: String, txid: String, @StringRes txidRes: Int, testTag: String) { +internal fun SparkExitTxNote(text: String?, txid: String, @StringRes txidRes: Int, testTag: String) { val context = LocalContext.current - Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { - BodyS(text = text, color = Colors.White64, modifier = Modifier.testTag(testTag)) + Column( + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier + .fillMaxWidth() + .testTag(testTag) + ) { + text?.let { BodyS(text = it, color = Colors.White64) } CaptionB( text = stringResource(txidRes).replace("{txid}", txid), maxLines = 1, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt new file mode 100644 index 0000000000..a8b2ab6d54 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt @@ -0,0 +1,181 @@ +package to.bitkit.ui.settings.lightning + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import kotlinx.collections.immutable.persistentListOf +import to.bitkit.R +import to.bitkit.models.FeeRate +import to.bitkit.repositories.SparkExitFeeBumpOption +import to.bitkit.ui.components.BodyM +import to.bitkit.ui.components.CaptionM +import to.bitkit.ui.components.Display +import to.bitkit.ui.components.PrimaryButton +import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.ScreenColumn +import to.bitkit.ui.screens.wallets.send.FeeItem +import to.bitkit.ui.theme.AppThemeSurface +import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.withAccent +import to.bitkit.ui.utils.withAccentBoldBright + +/** + * Raises a running exit's fee rate: the network's rates above it, each with what it costs from savings, then the + * payment, after which the exit rebuilds what has not confirmed at the new rate. + */ +@Composable +fun SparkExitFeeBumpScreen( + viewModel: SparkExitViewModel, + onBack: () -> Unit, + onDone: () -> Unit, +) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + LaunchedEffect(Unit) { + viewModel.loadFeeBump() + viewModel.effects.collect { if (it == SparkExitEffect.FeeBumped) onDone() } + } + Content( + uiState = uiState, + onBack = onBack, + onSelect = viewModel::selectFeeBump, + onRetry = viewModel::loadFeeBump, + onPay = viewModel::payHigherFee, + ) +} + +@Composable +private fun Content( + uiState: SparkExitUiState, + onBack: () -> Unit = {}, + onSelect: (FeeRate) -> Unit = {}, + onRetry: () -> Unit = {}, + onPay: () -> Unit = {}, +) { + val bump = uiState.feeBump + val selected = bump.selectedOption + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__spark_exit__nav_title), + onBackClick = onBack, + ) + Column( + modifier = Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + ) { + Column(modifier = Modifier.padding(horizontal = 16.dp)) { + VerticalSpacer(32.dp) + Display(text = stringResource(R.string.lightning__spark_exit__fee_bump_title).withAccent()) + VerticalSpacer(8.dp) + BodyM( + text = stringResource(R.string.lightning__spark_exit__fee_bump_text) + .replace("{rate}", "${uiState.record?.feeRateSatPerVbyte ?: 0uL}") + .withAccentBoldBright(), + color = Colors.White64, + ) + VerticalSpacer(24.dp) + } + when { + bump.isLoading -> Box( + contentAlignment = Alignment.Center, + modifier = Modifier.fillMaxWidth() + ) { + CircularProgressIndicator(strokeWidth = 2.dp, color = Colors.White32) + } + bump.hasError -> BodyM( + text = stringResource(R.string.lightning__spark_exit__fee_bump_error), + color = Colors.White64, + modifier = Modifier + .padding(horizontal = 16.dp) + .testTag("SparkExitFeeBumpError") + ) + else -> { + bump.options.forEach { option -> + FeeItem( + feeRate = option.speed, + sats = option.totalSats.toLong(), + description = "${stringResource(option.speed.description)} · " + + stringResource(R.string.lightning__spark_exit__fee_bump_rate) + .replace("{rate}", "${option.rateSatPerVbyte}"), + isSelected = option == selected, + isDisabled = !bump.canPay(option), + onClick = { if (bump.canPay(option)) onSelect(option.speed) }, + modifier = Modifier.testTag("SparkExitFeeBump${option.speed.name}") + ) + } + } + } + VerticalSpacer(32.dp) + } + Column(modifier = Modifier.padding(horizontal = 16.dp)) { + if (selected != null && !bump.canPay(selected)) { + CaptionM( + text = stringResource(R.string.lightning__spark_exit__fund_insufficient).withAccent(), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitFeeBumpInsufficient") + ) + VerticalSpacer(16.dp) + } + if (bump.hasError) { + PrimaryButton( + text = stringResource(R.string.common__try_again), + onClick = onRetry, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkExitFeeBumpRetry") + ) + } else { + PrimaryButton( + text = stringResource( + if (selected?.extraSats == 0uL) { + R.string.lightning__spark_exit__fee_bump_confirm + } else { + R.string.lightning__spark_exit__fund_savings + }, + ), + onClick = onPay, + enabled = selected != null && bump.canPay(selected) && !bump.isPaying, + isLoading = bump.isLoading || bump.isPaying, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkExitFeeBumpPay") + ) + } + VerticalSpacer(16.dp) + } + } +} + +@Preview(showSystemUi = true) +@Composable +private fun Preview() { + AppThemeSurface { + Content( + uiState = SparkExitUiState( + feeBump = SparkExitFeeBumpUiState( + options = persistentListOf( + SparkExitFeeBumpOption(FeeRate.FAST, 12uL, 4_200uL, 4_620uL), + SparkExitFeeBumpOption(FeeRate.NORMAL, 8uL, 2_400uL, 2_820uL), + ), + selected = FeeRate.FAST, + spendableSats = 100_000uL, + ), + ), + ) + } +} diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 4e2b762841..abb420d66b 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -32,6 +32,7 @@ import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.openNotificationSettings import to.bitkit.ui.scaffold.AppTopBar import to.bitkit.ui.scaffold.ScreenColumn +import to.bitkit.ui.shared.modifiers.clickableAlpha import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.withAccent @@ -43,6 +44,7 @@ fun SparkExitProgressScreen( viewModel: SparkExitViewModel, onBack: () -> Unit, onDone: () -> Unit, + onPayHigherFee: () -> Unit, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() val context = LocalContext.current @@ -63,6 +65,7 @@ fun SparkExitProgressScreen( onCancel = viewModel::cancel, onDone = onDone, onNotificationSettings = context::openNotificationSettings, + onPayHigherFee = onPayHigherFee, ) } @@ -75,6 +78,7 @@ private fun Content( onCancel: () -> Unit = {}, onDone: () -> Unit = {}, onNotificationSettings: () -> Unit = {}, + onPayHigherFee: () -> Unit = {}, ) { val record = uiState.record ScreenColumn { @@ -95,18 +99,19 @@ private fun Content( .testTag("SparkExitProgress") ) { VerticalSpacer(32.dp) - Display(text = progressTitle(record?.phase).withAccent()) + Display(text = progressTitle(record?.phase, uiState.progressFunding).withAccent()) VerticalSpacer(8.dp) BodyM( text = progressText( record = record, + receivedSats = uiState.receivedSats, progressFunding = uiState.progressFunding, staysOnSparkSats = uiState.staysOnSparkSats, ).withAccentBoldBright(), color = Colors.White64, ) VerticalSpacer(24.dp) - record?.let { ProgressDetails(it, uiState) } + record?.let { ProgressDetails(it, uiState, onPayHigherFee) } if (record?.isActive == true) { BackgroundNotes( limits = uiState.backgroundLimits, @@ -117,6 +122,14 @@ private fun Content( } } Column(modifier = Modifier.padding(horizontal = 16.dp)) { + if (uiState.canPayHigherFee) { + SecondaryButton( + text = stringResource(R.string.lightning__spark_exit__fee_bump_button), + onClick = onPayHigherFee, + testTag = "SparkExitPayHigherFee", + ) + VerticalSpacer(16.dp) + } if (uiState.canCancel) { SecondaryButton( text = stringResource(R.string.lightning__spark_exit__cancel), @@ -138,20 +151,16 @@ private fun Content( } @Composable -private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState) { +private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, onPayHigherFee: () -> Unit) { SparkExitSteps(record = record, tipHeight = uiState.tipHeight) - uiState.receivedSats?.let { sats -> + uiState.sweepTxid?.let { VerticalSpacer(24.dp) - val text = stringResource(R.string.lightning__spark_exit__done_received) - .replace("{amount}", sparkExitAmountText(sats)) - uiState.sweepTxid?.let { - SparkExitTxNote( - text = text, - txid = it, - txidRes = R.string.lightning__spark_exit__sweep_txid, - testTag = "SparkExitReceived", - ) - } ?: BodyS(text = text, color = Colors.White64, modifier = Modifier.testTag("SparkExitReceived")) + SparkExitTxNote( + text = null, + txid = it, + txidRes = R.string.lightning__spark_exit__sweep_txid, + testTag = "SparkExitSweepTxid", + ) } val address = record.funding.firstOrNull()?.address val funding = uiState.progressFunding @@ -219,6 +228,16 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState) modifier = Modifier.testTag("SparkExitFeeLow") ) } + if (uiState.showsFeeRose) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__fee_rose), + color = Colors.Yellow, + modifier = Modifier + .clickableAlpha(onClick = onPayHigherFee) + .testTag("SparkExitFeeRose") + ) + } uiState.outsideExitSats?.let { VerticalSpacer(16.dp) BodyS( @@ -320,11 +339,13 @@ private fun BackgroundNotes( } @Composable -private fun progressTitle(phase: SparkExitRecord.Phase?): String = stringResource( +private fun progressTitle(phase: SparkExitRecord.Phase?, funding: SparkExitFundingState?): String = stringResource( when (phase) { SparkExitRecord.Phase.Done -> R.string.lightning__spark_exit__done_title is SparkExitRecord.Phase.Failed -> R.string.lightning__spark_exit__failed_title - is SparkExitRecord.Phase.NeedsFunding -> R.string.lightning__spark_exit__needs_funding_title + // A payment that covers it, such as a higher fee paid from savings, only waits to confirm. + is SparkExitRecord.Phase.NeedsFunding if funding is SparkExitFundingState.Ask -> + R.string.lightning__spark_exit__needs_funding_title else -> R.string.lightning__spark_exit__progress_title }, ) @@ -332,11 +353,15 @@ private fun progressTitle(phase: SparkExitRecord.Phase?): String = stringResourc @Composable private fun progressText( record: SparkExitRecord?, + receivedSats: ULong?, progressFunding: SparkExitFundingState?, staysOnSparkSats: ULong?, ): String = when (record?.phase) { SparkExitRecord.Phase.Done -> listOfNotNull( - stringResource(R.string.lightning__spark_exit__done_text), + // What reached savings when it is known, else only that it did. + receivedSats?.let { + stringResource(R.string.lightning__spark_exit__done_received).replace("{amount}", sparkExitAmountText(it)) + } ?: stringResource(R.string.lightning__spark_exit__done_text), record.skippedLeafCount.takeIf { it > 0 }?.let { stringResource(R.string.lightning__spark_exit__partial_text).replace("{count}", "$it") }, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index 5fe076ec56..c3837d71ee 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -5,6 +5,9 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import breez_sdk_spark.RecoveryTxKind import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow @@ -16,10 +19,13 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import to.bitkit.env.Env +import to.bitkit.models.FeeRate import to.bitkit.repositories.SparkExitBackgroundLimits +import to.bitkit.repositories.SparkExitFeeBumpOption import to.bitkit.repositories.SparkExitFundingKey import to.bitkit.repositories.SparkExitFundingState import to.bitkit.repositories.SparkExitMath +import to.bitkit.repositories.SparkExitNetworkFees import to.bitkit.repositories.SparkExitPrestartFunding import to.bitkit.repositories.SparkExitQuote import to.bitkit.repositories.SparkExitRecord @@ -72,6 +78,7 @@ class SparkExitViewModel @Inject constructor( outsideExitSats = exit.outsideExitSats, staysOnSparkSats = SparkExitMath.staysOnSparkSats(balanceSats, exit.record), isSettling = exit.isSettling, + networkFees = exit.networkFees, receivedSats = exit.record?.let(::receivedSats), fundingPath = exit.record?.let { record -> SparkExitFundingKey.path(record.fundingIndex.toInt(), Env.network) @@ -161,6 +168,37 @@ class SparkExitViewModel @Inject constructor( } } + /** Prices the higher rates the running exit can move to, selecting the fastest. */ + fun loadFeeBump() { + viewModelScope.launch { + _uiState.update { it.copy(feeBump = SparkExitFeeBumpUiState(isLoading = true)) } + val spendable = sparkExitRepo.spendableSavingsSats().getOrNull() + sparkExitRepo.feeBumpOptions() + .onSuccess { options -> + val bump = SparkExitFeeBumpUiState(options = options.toImmutableList(), spendableSats = spendable) + // The fastest rate savings can pay for. + val selected = (options.firstOrNull(bump::canPay) ?: options.firstOrNull())?.speed + _uiState.update { it.copy(feeBump = bump.copy(selected = selected)) } + } + .onFailure { _uiState.update { it.copy(feeBump = SparkExitFeeBumpUiState(hasError = true)) } } + } + } + + fun selectFeeBump(speed: FeeRate) { + _uiState.update { it.copy(feeBump = it.feeBump.copy(selected = speed)) } + } + + fun payHigherFee() { + val option = _uiState.value.feeBump.selectedOption ?: return + viewModelScope.launch { + _uiState.update { it.copy(feeBump = it.feeBump.copy(isPaying = true)) } + sparkExitRepo.payHigherFee(option) + .onSuccess { _effects.emit(SparkExitEffect.FeeBumped) } + .onFailure { ToastEventBus.send(it) } + _uiState.update { it.copy(feeBump = it.feeBump.copy(isPaying = false)) } + } + } + /** Progress showed the result of an ended exit, so a later Emergency exit can start a new one. */ fun onResultShown() { viewModelScope.launch { sparkExitRepo.markResultSeen() } @@ -191,6 +229,7 @@ class SparkExitViewModel @Inject constructor( sealed interface SparkExitEffect { data object Started : SparkExitEffect data object Cancelled : SparkExitEffect + data object FeeBumped : SparkExitEffect } @Stable @@ -225,7 +264,17 @@ data class SparkExitUiState( val receivedSats: ULong? = null, /** The derivation path of the exit's funding key, where a leftover that could not be sent stays. */ val fundingPath: String? = null, + /** What the network asks now, for the fee bump and its hint. */ + val networkFees: SparkExitNetworkFees? = null, + val feeBump: SparkExitFeeBumpUiState = SparkExitFeeBumpUiState(), ) { + /** Progress offers Pay a higher fee. */ + val canPayHigherFee: Boolean get() = record?.canPayHigherFee(tipHeight, networkFees) == true + + /** Progress hints that the network asks more than the exit pays, while it does not show the fee as too low. */ + val showsFeeRose: Boolean + get() = canPayHigherFee && lowFeeRate == null && record?.isBelowNetwork(networkFees) == true + val fundingSats: ULong get() = quote?.fundingSats ?: 0uL /** What the funding address holds against the quote before the exit starts. */ @@ -257,10 +306,13 @@ data class SparkExitUiState( return active.feeRateSatPerVbyte.takeIf { active.underpricedStep(tipHeight) != null } } - /** The SWEEP transaction of a finished exit. */ + /** The SWEEP transaction of a finished exit, or the one that landed before a retry of leaves replaced it. */ val sweepTxid: String? - get() = record?.takeIf { it.phase == SparkExitRecord.Phase.Done } - ?.recovery?.transactions?.firstOrNull { it.kind == RecoveryTxKind.SWEEP }?.txid + get() { + val done = record?.takeIf { it.phase == SparkExitRecord.Phase.Done } ?: return null + return done.recovery?.transactions?.firstOrNull { it.kind == RecoveryTxKind.SWEEP }?.txid + ?: done.landedSweepTxid + } /** * The fee funding progress shows, asking for the whole shortfall, at least the funding output's dust, until the @@ -274,3 +326,20 @@ data class SparkExitUiState( } enum class SparkExitQuoteBlock { Error, Nothing, Uneconomic } + +/** The fee bump screen: the rates it offers, the one picked, and what savings can spend. */ +@Stable +data class SparkExitFeeBumpUiState( + val isLoading: Boolean = false, + val hasError: Boolean = false, + val options: ImmutableList = persistentListOf(), + val selected: FeeRate? = null, + val spendableSats: ULong? = null, + val isPaying: Boolean = false, +) { + val selectedOption: SparkExitFeeBumpOption? get() = options.firstOrNull { it.speed == selected } + + /** Savings covers [option]'s cost, or there is nothing to pay. */ + fun canPay(option: SparkExitFeeBumpOption): Boolean = + option.totalSats == 0uL || (spendableSats ?: 0uL) >= option.totalSats +} diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index d99209ab77..8f8ae6c8e5 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -236,11 +236,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 8c07696e87..2606c148cf 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -243,11 +243,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index b4345f22cd..13523519e2 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -240,11 +240,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index bceb452deb..c9df9fb51b 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -243,11 +243,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index b6365ab905..4b05c6aa3e 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -120,11 +120,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 1e1cfa47df..ee4b0356a3 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -236,11 +236,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 68ef0bf3f5..a326f8ba5b 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -242,11 +242,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index d27d415941..571a121c45 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -184,11 +184,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 6f35b37111..94a964b676 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -119,11 +119,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 993d5e833f..013be9d713 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -241,11 +241,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 91c8b8e58a..433e5422dd 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -240,11 +240,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index e9bb764544..b398fc8c4d 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -121,11 +121,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 786756c6c5..eae5667802 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -244,11 +244,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 6279368cc4..d5d52cd2df 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -116,11 +116,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 9d872d796a..749793f067 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -252,11 +252,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index bf14fa3719..c4bc4dd179 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -400,11 +400,18 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. They can still be asked to release it. + {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. Exit\n<accent>stopped</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. It confirms once fees drop. + Pay a higher fee + Use this fee + Could not price a higher fee. Try again. + {rate} sat/vB + This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. + Pay a\n<accent>higher fee</accent> + The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. + Network fees rose above this exit\'s fee. It may slow down. Network fees Fund from another wallet Send at least {amount} to this address. The exit starts once it confirms. diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 6894738d2b..a619f69d02 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -677,6 +677,78 @@ class SparkExitDriverTest : BaseUnitTest() { assertFalse(record.isFailedLeavesReleased) } + private fun funded(record: SparkExitRecord) = record.copy( + funding = listOf(record.funding.single().copy(txid = "f0", vout = 0u, valueSats = 20_000uL)), + ) + + @Test + fun `a higher fee the funding covers needs nothing more`() = test { + val record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1b"))) + + assertEquals(0uL, driver().feeBumpShortfall(record, 9uL)) + + val request = sdk.prepareRequests.single() + assertEquals(9uL, request.feeRateSatPerVbyte) + assertEquals(listOf("leaf-1"), (request.selection as ExitLeafSelection.Specific).leafIds) + assertEquals(record.fundingInputs, sdk.recoverRequests.single().fundingInputs) + // Priced, not built: nothing is sent or saved. + assertTrue(chain.broadcasts.isEmpty()) + assertTrue(saved.isEmpty()) + } + + @Test + fun `a higher fee asks for the sdk's shortfall less what the funding address holds, with one input's fee`() = test { + val record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) + sdk.recoverError = SdkException.InsufficientCpfpFunds(26_000uL, "") + // Still at the address: the adopted input, unspent. + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", value = 20_000uL)) + + // 26,000 needed, 20,000 held: 6,000, plus 68 vB at 9 sat/vB for the coin that pays it. + assertEquals(6_612uL, driver().feeBumpShortfall(record, 9uL)) + + sdk.recoverError = SdkException.InsufficientCpfpFunds(20_000uL, "") + assertEquals(SparkExitMath.FUNDING_DUST_SATS, driver().feeBumpShortfall(record, 9uL)) + } + + @Test + fun `a paid higher fee rebuilds at the new rate once its payment confirms`() = test { + var record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) + .applyFeeBump(rate = 9uL, extraSats = 6_612uL, paymentTxid = "bump") + assertEquals(Phase.NeedsFunding(26_612uL), record.phase) + assertEquals(SparkExitFundingState.Paid("bump"), SparkExitMath.fundingState(record, utxos = null)) + + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf( + SparkExitFixtures.utxo("f0", value = 20_000uL), + SparkExitFixtures.utxo("bump", value = 6_612uL), + ) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1b"))) + record = driver().tick(record) + + assertEquals(Phase.Running, record.phase) + assertEquals(9uL, sdk.prepareRequests.single().feeRateSatPerVbyte) + assertEquals( + listOf("f0", "bump"), + sdk.recoverRequests.single().fundingInputs.map { (it as CpfpInput.P2wpkh).txid } + ) + assertEquals(listOf("n1b"), chain.broadcasts.map { it.txid }) + } + + @Test + fun `a higher fee with nothing to pay rebuilds on the next tick`() = test { + val record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) + .applyFeeBump(rate = 9uL, extraSats = 0uL, paymentTxid = null) + assertTrue(record.isRebuilding) + assertEquals(Phase.Running, record.phase) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1b"))) + + val rebuilt = driver().tick(record) + + assertEquals(9uL, sdk.prepareRequests.single().feeRateSatPerVbyte) + assertEquals(record.generation + 1, rebuilt.generation) + assertEquals(listOf("n1b"), chain.broadcasts.map { it.txid }) + } + @Test fun `rebuild with nothing left ends the exit`() = test { val record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt index 2892da8572..18cf41a0e5 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -178,6 +178,10 @@ class FakeSparkExitChain : SparkExitChain { var nextBlockRate: ULong? = 5uL override suspend fun nextBlockFeeRate(): ULong = nextBlockRate ?: throw SparkExitChainError("No fee estimates") + + var fees = SparkExitNetworkFees(fastest = 5uL, halfHour = 3uL) + + override suspend fun networkFees(): SparkExitNetworkFees = fees } class FakeSparkExitRecovering : SparkExitRecovering { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 1f72d967bb..0cb2e26f58 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -9,6 +9,7 @@ import breez_sdk_spark.SkippedLeaf import breez_sdk_spark.SkippedLeafReason import org.junit.Test import org.lightningdevkit.ldknode.Network +import to.bitkit.models.FeeRate import kotlin.test.assertContentEquals import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -508,4 +509,56 @@ class SparkExitFundingTest { assertEquals(3, SparkExitQuote(prepared).fundedSteps) assertEquals(7_000uL, SparkExitQuote(prepared).fundingSats) } + + @Test + fun `a fee bump offers rates strictly above the exit's, normal only between it and fast`() { + val fees = SparkExitNetworkFees(fastest = 9uL, halfHour = 6uL) + assertEquals(listOf(FeeRate.FAST to 9uL, FeeRate.NORMAL to 6uL), SparkExitFeeBumpOption.rates(2uL, fees)) + assertEquals(listOf(FeeRate.FAST to 9uL), SparkExitFeeBumpOption.rates(6uL, fees)) + // The network asks no more than the exit pays, yet the mempool refuses it: one above, to replace it. + assertEquals(listOf(FeeRate.FAST to 10uL), SparkExitFeeBumpOption.rates(9uL, fees)) + } + + @Test + fun `pay a higher fee is offered while the exit runs underpriced or below the network`() { + val record = SparkExitFixtures.record(SparkExitRecord.Phase.Running) + .adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))), 0L) + val rising = SparkExitNetworkFees(fastest = 9uL, halfHour = 6uL) + val calm = SparkExitNetworkFees(fastest = 2uL, halfHour = 1uL) + assertTrue(record.canPayHigherFee(1_000u, rising)) + assertFalse(record.canPayHigherFee(1_000u, calm)) + // Accepted, but unconfirmed for more than 6 blocks. + val slow = record.copy( + broadcastLog = listOf( + SparkExitRecord.BroadcastAttempt( + record.generation, + "n1", + 1, + 0, + 0L, + "accepted", + true, + acceptedAtHeight = 990u + ), + ), + ) + assertTrue(slow.canPayHigherFee(1_000u, calm)) + assertFalse(slow.copy(isRebuilding = true).canPayHigherFee(1_000u, rising)) + assertFalse(slow.copy(failedLeafRetrySince = 1_000u).canPayHigherFee(1_000u, rising)) + assertFalse(SparkExitFixtures.record().canPayHigherFee(1_000u, rising)) + } + + @Test + fun `a new generation keeps the sweep that landed before it`() { + val swept = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("s", kind = RecoveryTxKind.SWEEP, status = ExitTransactionStatus.Confirmed(9u)) + ), + ) + val record = SparkExitFixtures.record(SparkExitRecord.Phase.Running).adopt(swept, 0L) + val retried = record.adopt(SparkExitFixtures.recovery(emptyList()), 1L) + assertEquals("s", retried.landedSweepTxid) + assertEquals("s", retried.adopt(SparkExitFixtures.recovery(emptyList()), 2L).landedSweepTxid) + assertEquals(retried, SparkExitJson.decode(SparkExitJson.encode(retried))) + } } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index cf86071c87..890dd9536a 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -5,9 +5,12 @@ import org.junit.Test import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever +import to.bitkit.models.FeeRate +import to.bitkit.repositories.SparkExitFeeBumpOption import to.bitkit.repositories.SparkExitFixtures import to.bitkit.repositories.SparkExitFundingState import to.bitkit.repositories.SparkExitMath +import to.bitkit.repositories.SparkExitNetworkFees import to.bitkit.repositories.SparkExitQuote import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo @@ -61,6 +64,32 @@ class SparkExitViewModelTest : BaseUnitTest() { assertFalse(paid.copy(fundingSeenSats = 20_000uL, fundingSeenCount = 2).canContinueFunding) } + @Test + fun `progress hints at rising fees and offers a higher fee savings can pay for`() { + val running = SparkExitFixtures.record(SparkExitRecord.Phase.Running) + .adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))), 0L) + val rising = SparkExitUiState( + record = running, + tipHeight = 1_000u, + networkFees = SparkExitNetworkFees(9uL, 6uL) + ) + assertTrue(rising.canPayHigherFee) + assertTrue(rising.showsFeeRose) + assertFalse(rising.copy(networkFees = SparkExitNetworkFees(2uL, 1uL)).canPayHigherFee) + + val fast = SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 4_200uL, 4_620uL) + assertTrue(SparkExitFeeBumpUiState(spendableSats = 4_620uL).canPay(fast)) + assertFalse(SparkExitFeeBumpUiState(spendableSats = 4_619uL).canPay(fast)) + assertTrue(SparkExitFeeBumpUiState(spendableSats = 0uL).canPay(fast.copy(extraSats = 0uL, totalSats = 0uL))) + } + + @Test + fun `done names the sweep that landed before a retry of leaves replaced it`() { + val done = SparkExitFixtures.record(SparkExitRecord.Phase.Done) + .copy(recovery = SparkExitFixtures.recovery(emptyList()), landedSweepTxid = "sweep") + assertEquals("sweep", SparkExitUiState(record = done).sweepTxid) + } + @Test fun `progress asks for at least dust before the funding address was read`() { val record = SparkExitFixtures.record(SparkExitRecord.Phase.NeedsFunding(68uL)) diff --git a/docs/screens-map.md b/docs/screens-map.md index 58e64ae08b..abec99dd48 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -318,6 +318,7 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | LightningConnectionsScreen.kt | Settings > Advanced › Lightning Connections overview | | SparkDetailScreen.kt | `todo` | | SparkExitConfirmScreen.kt | `todo` | +| SparkExitFeeBumpScreen.kt | `todo` | | SparkExitFundingScreen.kt | `todo` | | SparkExitIntroScreen.kt | `todo` | | SparkExitProgressScreen.kt | `todo` | From e515b735e5f96e071f72255d1edbb1689aa38e6d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 23:33:49 +0100 Subject: [PATCH 018/154] fix: spark exit fee bump shows units and selects only what savings covers --- .../ui/screens/wallets/send/SendFeeRateScreen.kt | 15 ++++++++++++--- .../settings/lightning/SparkExitFeeBumpScreen.kt | 3 ++- .../ui/settings/lightning/SparkExitViewModel.kt | 7 +++++-- .../settings/lightning/SparkExitViewModelTest.kt | 3 +++ 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendFeeRateScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendFeeRateScreen.kt index 3c19fcb831..54448ee164 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendFeeRateScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendFeeRateScreen.kt @@ -148,7 +148,10 @@ private fun Content( } } -/** A speed row of the fee picker, also used by the Spark emergency exit's fee bump; [description] under its title. */ +/** + * A speed row of the fee picker, also used by the Spark emergency exit's fee bump: [description] under its title, and + * with [showsSymbols] each amount with its unit. + */ @Composable internal fun FeeItem( feeRate: FeeRate, @@ -158,6 +161,7 @@ internal fun FeeItem( description: String = stringResource(feeRate.description), isSelected: Boolean = false, isDisabled: Boolean = false, + showsSymbols: Boolean = false, unit: PrimaryDisplay = LocalCurrencies.current.primaryDisplay, ) { val color = if (isDisabled) Colors.Gray3 else MaterialTheme.colorScheme.primary @@ -195,8 +199,13 @@ internal fun FeeItem( Column( horizontalAlignment = Alignment.End, ) { - MoneyMSB(sats, color = color, accent = accent) - MoneySSB(sats, unit = unit.not(), color = accent, accent = accent) + if (showsSymbols) { + MoneyMSB(sats, color = color, accent = accent, showSymbol = true) + MoneySSB(sats, unit = unit.not(), color = accent, accent = accent, showSymbol = true) + } else { + MoneyMSB(sats, color = color, accent = accent) + MoneySSB(sats, unit = unit.not(), color = accent, accent = accent) + } } } } diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt index a8b2ab6d54..dab31b4e39 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt @@ -114,6 +114,7 @@ private fun Content( .replace("{rate}", "${option.rateSatPerVbyte}"), isSelected = option == selected, isDisabled = !bump.canPay(option), + showsSymbols = true, onClick = { if (bump.canPay(option)) onSelect(option.speed) }, modifier = Modifier.testTag("SparkExitFeeBump${option.speed.name}") ) @@ -123,7 +124,7 @@ private fun Content( VerticalSpacer(32.dp) } Column(modifier = Modifier.padding(horizontal = 16.dp)) { - if (selected != null && !bump.canPay(selected)) { + if (bump.isSavingsShort) { CaptionM( text = stringResource(R.string.lightning__spark_exit__fund_insufficient).withAccent(), color = Colors.White64, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index c3837d71ee..608ce31a37 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -176,8 +176,8 @@ class SparkExitViewModel @Inject constructor( sparkExitRepo.feeBumpOptions() .onSuccess { options -> val bump = SparkExitFeeBumpUiState(options = options.toImmutableList(), spendableSats = spendable) - // The fastest rate savings can pay for. - val selected = (options.firstOrNull(bump::canPay) ?: options.firstOrNull())?.speed + // The fastest rate savings can pay for, or none when it covers no rate. + val selected = options.firstOrNull(bump::canPay)?.speed _uiState.update { it.copy(feeBump = bump.copy(selected = selected)) } } .onFailure { _uiState.update { it.copy(feeBump = SparkExitFeeBumpUiState(hasError = true)) } } @@ -339,6 +339,9 @@ data class SparkExitFeeBumpUiState( ) { val selectedOption: SparkExitFeeBumpOption? get() = options.firstOrNull { it.speed == selected } + /** Savings covers none of the rates offered. */ + val isSavingsShort: Boolean get() = options.isNotEmpty() && options.none(::canPay) + /** Savings covers [option]'s cost, or there is nothing to pay. */ fun canPay(option: SparkExitFeeBumpOption): Boolean = option.totalSats == 0uL || (spendableSats ?: 0uL) >= option.totalSats diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 890dd9536a..61b85e8ced 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -1,5 +1,6 @@ package to.bitkit.ui.settings.lightning +import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.flow.MutableStateFlow import org.junit.Test import org.mockito.kotlin.doReturn @@ -81,6 +82,8 @@ class SparkExitViewModelTest : BaseUnitTest() { assertTrue(SparkExitFeeBumpUiState(spendableSats = 4_620uL).canPay(fast)) assertFalse(SparkExitFeeBumpUiState(spendableSats = 4_619uL).canPay(fast)) assertTrue(SparkExitFeeBumpUiState(spendableSats = 0uL).canPay(fast.copy(extraSats = 0uL, totalSats = 0uL))) + assertTrue(SparkExitFeeBumpUiState(options = persistentListOf(fast), spendableSats = 1_000uL).isSavingsShort) + assertFalse(SparkExitFeeBumpUiState(options = persistentListOf(fast), spendableSats = 5_000uL).isSavingsShort) } @Test From 7ce4419bf085ad455dc3238def1812e6329b72d9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 23:57:20 +0100 Subject: [PATCH 019/154] fix: spark exit sweeps fee change when network fees drop --- .../to/bitkit/repositories/SparkExitChain.kt | 10 +++ .../to/bitkit/repositories/SparkExitDriver.kt | 56 ++++++++++-- .../bitkit/repositories/SparkExitFunding.kt | 6 ++ .../to/bitkit/repositories/SparkExitRecord.kt | 19 ++++ .../to/bitkit/repositories/SparkExitSweep.kt | 6 ++ .../lightning/SparkExitProgressScreen.kt | 9 +- app/src/main/res/values-ar/strings.xml | 3 +- app/src/main/res/values-b+es+419/strings.xml | 3 +- app/src/main/res/values-ca/strings.xml | 3 +- app/src/main/res/values-cs/strings.xml | 3 +- app/src/main/res/values-de/strings.xml | 3 +- app/src/main/res/values-el/strings.xml | 3 +- app/src/main/res/values-es-rES/strings.xml | 3 +- app/src/main/res/values-es/strings.xml | 3 +- app/src/main/res/values-fr/strings.xml | 3 +- app/src/main/res/values-it/strings.xml | 3 +- app/src/main/res/values-nl/strings.xml | 3 +- app/src/main/res/values-pl/strings.xml | 3 +- app/src/main/res/values-pt-rBR/strings.xml | 3 +- app/src/main/res/values-pt/strings.xml | 3 +- app/src/main/res/values-ru/strings.xml | 3 +- app/src/main/res/values/strings.xml | 3 +- .../repositories/SparkExitDriverTest.kt | 88 ++++++++++++++++--- .../bitkit/repositories/SparkExitFixtures.kt | 4 + .../repositories/SparkExitFundingTest.kt | 20 +++++ 25 files changed, 231 insertions(+), 35 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 483c0ff282..3f89b9ed78 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -83,6 +83,9 @@ interface SparkExitChain { /** The rates for the next block and about half an hour, from `/fee-estimates` targets 1 and 3, rounded up. */ suspend fun networkFees(): SparkExitNetworkFees + + /** The network's cheapest rate, `/fee-estimates` at its farthest target, rounded up and at least 1 sat/vB. */ + suspend fun economyFeeRate(): ULong } /** What the network asks now, in sat/vB: for the next block, and for about half an hour. */ @@ -158,6 +161,13 @@ class EsploraSparkExitChain( return ceil(rate.toDouble()).toULong() } + override suspend fun economyFeeRate(): ULong { + val estimates = json.parseToJsonElement(get("/fee-estimates")).jsonObject + val farthest = estimates.keys.maxByOrNull { it.toIntOrNull() ?: 0 } + ?: throw SparkExitChainError("No fee estimates") + return maxOf(1uL, ceil(estimates.getValue(farthest).jsonPrimitive.content.toDouble()).toULong()) + } + override suspend fun networkFees(): SparkExitNetworkFees { val estimates = json.parseToJsonElement(get("/fee-estimates")).jsonObject fun rate(target: String) = ceil(estimates.getValue(target).jsonPrimitive.content.toDouble()).toULong() diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 3f8a645260..976a44e611 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -111,6 +111,12 @@ class SparkExitDriver( /** Blocks an unconfirmed leftover sweep waits before it is replaced at a higher rate, about a day. */ const val SWEEP_REPLACE_BLOCKS = 144u + /** Blocks between two reads of the rate while the leftover waits for cheaper fees, about a day. */ + const val SWEEP_RECHECK_BLOCKS = 144u + + /** Blocks the leftover waits for cheaper fees before it is kept as dust, about four weeks. */ + const val SWEEP_RELEASE_BLOCKS = 4_032u + /** The least time between two builds, so a divergence that persists does not rebuild every tick. */ val REBUILD_INTERVAL = 10.minutes @@ -585,13 +591,51 @@ class SparkExitDriver( // Sent again until it confirms; a node that already has it accepts it again. return sendSweep(record, built, built.txHex) } + if (built?.isWaitingForFees == true) { + val height = tip ?: return record + val since = requireNotNull(built.waitingSince) + if (height >= since + SWEEP_RELEASE_BLOCKS) { + Logger.info("Keeping the Spark exit leftover as dust after waiting for cheaper fees", context = TAG) + return record.copy(leftoverSweep = built.copy(isDustKept = true)) + } + if (height < (built.checkedAtHeight ?: since) + SWEEP_RECHECK_BLOCKS) return record + } val address = record.funding.firstOrNull()?.address ?: return record val utxos = runSuspendCatching { chain.utxos(address) }.getOrNull() ?: return record if (utxos.isEmpty()) return record.copy(leftover = emptyList()) if (utxos.any { !it.status.confirmed }) return record - val inputs = utxos.map { SparkExitSweep.Input(it.txid, it.vout, it.value) } val current = record.copy(leftover = utxos.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) }) - return buildSweep(current, inputs, record.feeRateSatPerVbyte) + val rate = SparkExitMath.sweepFeeRate(economyRate(), record.feeRateSatPerVbyte) + val inputs = SparkExitSweep.worthSweeping( + utxos.map { SparkExitSweep.Input(it.txid, it.vout, it.value) }, + rate, + ) + return buildSweep(current, inputs, rate) + } + + /** The network's cheapest rate, null when it cannot be read. */ + private suspend fun economyRate(): ULong? = runSuspendCatching { chain.economyFeeRate() } + .onFailure { Logger.warn("Failed to read the economy fee rate for the leftover sweep", it, context = TAG) } + .getOrNull() + + /** + * The leftover waits for fees to drop, from [tip] or from when it started waiting; while the tip is unknown it + * stays as it is and the next tick tries again. + */ + private fun waitForFees(record: SparkExitRecord): SparkExitRecord { + val totalSats = record.leftover.fold(0uL) { sum, leftover -> sum.safe() + leftover.valueSats.safe() } + val height = tip ?: return record + Logger.info("Waiting for cheaper fees to sweep the Spark exit leftover", context = TAG) + val since = record.leftoverSweep?.takeIf { it.isWaitingForFees }?.waitingSince ?: height + return record.copy( + leftoverSweep = SparkExitRecord.LeftoverSweep( + null, + null, + totalSats, + waitingSince = since, + checkedAtHeight = height, + ), + ) } /** @@ -608,15 +652,13 @@ class SparkExitDriver( val values = record.leftover.associate { "${it.txid}:${it.vout}" to it.valueSats } val inputs = SparkExitTxInputs.decode(hex)?.map { SparkExitSweep.Input(it.prevTxid, it.vout, values["${it.prevTxid}:${it.vout}"] ?: return null) - } ?: return null + }?.let { SparkExitSweep.worthSweeping(it, rate) } ?: return null Logger.info("Replacing Spark exit leftover sweep '${old.txid}' at '$rate' sat/vB", context = TAG) // A sweep a node accepted may still confirm, so its txid is kept to look for. val replaced = old.replacedTxids + listOfNotNull(old.txid.takeIf { old.isAccepted }) return buildSweep(record, inputs, rate, replaced) } - private fun dustSweep(totalSats: ULong) = SparkExitRecord.LeftoverSweep(null, null, totalSats) - private suspend fun isConfirmed(txid: String): Boolean = runSuspendCatching { chain.txStatus(txid) }.getOrNull()?.confirmed == true @@ -631,13 +673,13 @@ class SparkExitDriver( replaced: List? = null, ): SparkExitRecord { val address = record.funding.firstOrNull()?.address ?: return record - val total = inputs.fold(0uL) { sum, input -> sum.safe() + input.valueSats.safe() } val plan = runSuspendCatching { SparkExitSweep.plan(inputs, record.destination, feeRate) } .getOrElse { Logger.error("Failed to plan the Spark exit leftover sweep", it, context = TAG) return record } - ?: return if (!replaced.isNullOrEmpty()) record else record.copy(leftoverSweep = dustSweep(total)) + // A replacement of an accepted sweep keeps that one; otherwise the leftover waits for cheaper fees. + ?: return if (!replaced.isNullOrEmpty()) record else waitForFees(record) val sweep = runSuspendCatching { val signed = makeSigner().signPsbt(SparkExitSweep.psbt(plan, address)) val hex = SparkExitSweep.signedTxHex(plan, signed) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index e679280501..6db6b2747d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -164,6 +164,12 @@ object SparkExitMath { return transactions.filter { it.status !is ExitTransactionStatus.Confirmed }.maxOfOrNull { after(it, 0) } } + /** + * The rate the leftover is swept at: the network's cheapest ([economy]), so as little of it as possible goes to + * fees, never above the exit's own rate, at least 1 sat/vB. The exit's rate when the network's cannot be read. + */ + fun sweepFeeRate(economy: ULong?, exitRate: ULong): ULong = maxOf(1uL, minOf(economy ?: exitRate, exitRate)) + /** The fee one more P2WPKH funding input adds to a build at [feeRateSatPerVbyte]. */ fun inputFeeSats(feeRateSatPerVbyte: ULong): ULong = P2WPKH_INPUT_VBYTES.safe() * feeRateSatPerVbyte.safe() diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 5e20e9e9be..394c4f13e1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -206,6 +206,9 @@ data class SparkExitRecord( /** A cooperative leaf the operators moved on-chain; [valueSats] is 0 until a retry's quote names it. */ data class FailedLeaf(val leafId: String, val valueSats: ULong) + /** The leftover waits for network fees to drop before it is worth sweeping. */ + val isLeftoverWaitingForFees: Boolean get() = leftover.isNotEmpty() && leftoverSweep?.isWaitingForFees == true + /** A built sweep of the leftover, saved before it is sent; a null [txid] means it was dust and nothing went. */ data class LeftoverSweep( val txid: String?, @@ -220,7 +223,16 @@ data class SparkExitRecord( val sentAtHeight: UInt? = null, /** Earlier versions a node accepted that this one replaced; any of them confirming ends the sweep. */ val replacedTxids: List = emptyList(), + /** With no [txid]: the tip from which the leftover waits for fees low enough to make it worth sending. */ + val waitingSince: UInt? = null, + /** The tip at which the waiting leftover's rate was last read. */ + val checkedAtHeight: UInt? = null, + /** The wait ran out: the leftover stays at its funding address as dust. */ + val isDustKept: Boolean = false, ) { + /** Not built, waiting for fees to drop. A sweep with no [txid] and no wait is dust kept, as before waits. */ + val isWaitingForFees: Boolean get() = txid == null && waitingSince != null && !isDustKept + /** A refusal for its fee is not final: the sweep is built again at the network's current rate. */ val isFeeRejection: Boolean get() = rejection?.contains("fee", ignoreCase = true) == true } @@ -230,6 +242,7 @@ data class SparkExitRecord( get() { if (leftover.isEmpty()) return false val sweep = leftoverSweep ?: return true + if (sweep.isWaitingForFees) return true return sweep.txid != null && (sweep.rejection == null || sweep.isFeeRejection) && !sweep.isConfirmed } @@ -726,6 +739,9 @@ object SparkExitJson { if (sweep.replacedTxids.isNotEmpty()) { put("replacedTxids", buildJsonArray { sweep.replacedTxids.forEach { add(JsonPrimitive(it)) } }) } + sweep.waitingSince?.let { put("waitingSince", it.toLong()) } + sweep.checkedAtHeight?.let { put("checkedAtHeight", it.toLong()) } + if (sweep.isDustKept) put("isDustKept", true) } /** What the exit keeps to pace and bound its rebuilds and waits, each left out at its default. */ @@ -832,6 +848,9 @@ object SparkExitJson { feeRateSatPerVbyte = it.ulongOrNull("feeRateSatPerVbyte"), sentAtHeight = it.ulongOrNull("sentAtHeight")?.toUInt(), replacedTxids = it.arrayOrEmpty("replacedTxids").map { txid -> txid.jsonPrimitive.content }, + waitingSince = it.ulongOrNull("waitingSince")?.toUInt(), + checkedAtHeight = it.ulongOrNull("checkedAtHeight")?.toUInt(), + isDustKept = it.booleanOrNull("isDustKept") ?: false, ) }, fundingPaymentTxid = o.stringOrNull("fundingPaymentTxid"), diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt index 6dc251444a..8dd4cf8268 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt @@ -22,6 +22,12 @@ object SparkExitSweep { /** An unsigned sweep of [inputs] to [destination], or null when what it pays would be under the dust limit. */ class Plan(val inputs: List, val destinationScript: ByteArray, val amountSats: ULong, val feeSats: ULong) + /** The inputs worth more than the fee each adds to a sweep at [feeRateSatPerVbyte]: the rest cost more to send. */ + fun worthSweeping(inputs: List, feeRateSatPerVbyte: ULong): List { + val inputFee = SparkExitMath.inputFeeSats(maxOf(1uL, feeRateSatPerVbyte)) + return inputs.filter { it.valueSats > inputFee } + } + fun plan(inputs: List, destination: String, feeRateSatPerVbyte: ULong): Plan? { if (inputs.isEmpty()) return null val script = AddressScript.of(destination) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index abb420d66b..cfcd6df7e1 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -275,10 +275,17 @@ private fun LeftoverNote(record: SparkExitRecord, address: String, path: String? val sweep = record.leftoverSweep VerticalSpacer(16.dp) when { + record.isLeftoverWaitingForFees -> BodyS( + text = stringResource(R.string.lightning__spark_exit__leftover_waiting) + .replace("{amount}", sparkExitAmountText(total)), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitLeftoverWaiting") + ) sweep != null && sweep.txid == null -> BodyS( text = stringResource(R.string.lightning__spark_exit__leftover_dust) .replace("{amount}", sparkExitAmountText(total)) - .replace("{address}", address), + .replace("{address}", address) + .replace("{path}", path.orEmpty()), color = Colors.White64, ) sweep?.txid != null && sweep.isAccepted -> SparkExitTxNote( diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 8f8ae6c8e5..63f3b948bf 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -267,11 +267,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 2606c148cf..36b2cc6234 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -274,11 +274,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 13523519e2..af94630562 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -271,11 +271,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index c9df9fb51b..6c23cb96b9 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -274,11 +274,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 4b05c6aa3e..96783dcea9 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -151,11 +151,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index ee4b0356a3..179c42b786 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -267,11 +267,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index a326f8ba5b..0d7a3ae244 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -273,11 +273,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 571a121c45..b7cf0b356a 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -215,11 +215,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 94a964b676..6798cfb0d3 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -150,11 +150,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 013be9d713..5e55494db6 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -272,11 +272,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 433e5422dd..cae74f1de2 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -271,11 +271,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index b398fc8c4d..856e98fc71 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -152,11 +152,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index eae5667802..00d84d6048 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -275,11 +275,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index d5d52cd2df..0bfc610000 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -147,11 +147,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 749793f067..eb6b498634 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -283,11 +283,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c4bc4dd179..9d9bf10792 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -431,11 +431,12 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}. + {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. Transaction ID: {txid} + {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index a619f69d02..2ce70f0ec5 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -546,7 +546,7 @@ class SparkExitDriverTest : BaseUnitTest() { } @Test - fun `a leftover under dust is not swept`() = test { + fun `a leftover worth less than its fees waits for cheaper fees, then is kept as dust after four weeks`() = test { chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0", 1u, 400uL)) val done = SparkExitFixtures.record(Phase.Done).copy( destination = SWEEP_DESTINATION, @@ -554,13 +554,77 @@ class SparkExitDriverTest : BaseUnitTest() { leftover = listOf(SparkExitRecord.Leftover("f0", 1u, 400uL)), ) - val record = driver().tick(done) + // At 1 sat/vB the sweep's fee leaves less than dust: it waits, and the exit is still driven. + var record = driver(tip = 1_000u).tick(done) + assertTrue(record.isLeftoverWaitingForFees) + assertTrue(record.needsDriving) + assertEquals(1_000u, assertNotNull(record.leftoverSweep).waitingSince) + + // The rate is read again about once a day. + chain.utxosByAddress[SWEEP_FUNDING] = emptyList() + record = driver(tip = 1_143u).tick(record) + assertTrue(record.isLeftoverWaitingForFees) + chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0", 1u, 400uL)) + record = driver(tip = 1_144u).tick(record) + assertEquals(1_144u, assertNotNull(record.leftoverSweep).checkedAtHeight) + assertEquals(1_000u, assertNotNull(record.leftoverSweep).waitingSince) - assertEquals(SparkExitRecord.LeftoverSweep(null, null, 400uL), record.leftoverSweep) + record = driver(tip = 5_032u).tick(record) + assertTrue(assertNotNull(record.leftoverSweep).isDustKept) + assertFalse(record.isLeftoverWaitingForFees) + assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) assertTrue(chain.rawBroadcasts.isEmpty()) assertFalse(record.needsDriving) } + @Test + fun `a waiting leftover is swept once fees drop`() = test { + chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0".repeat(32), 1u, 25_000uL)) + chain.outcome = SparkExitBroadcastOutcome.Accepted + val waiting = SparkExitFixtures.record(Phase.Done).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + leftover = listOf(SparkExitRecord.Leftover("f0".repeat(32), 1u, 25_000uL)), + leftoverSweep = SparkExitRecord.LeftoverSweep( + null, + null, + 25_000uL, + waitingSince = 1_000u, + checkedAtHeight = 1_000u + ), + ) + + val record = driver(tip = 1_144u).tick(waiting) + + assertTrue(assertNotNull(record.leftoverSweep).isAccepted) + assertFalse(record.isLeftoverWaitingForFees) + } + + @Test + fun `the leftover sweeps at the cheapest rate up to the exit's, leaving coins not worth their fee`() = + test { + val coin = "f0".repeat(32) + chain.utxosByAddress[SWEEP_FUNDING] = listOf( + SparkExitFixtures.utxo(coin, 1u, 25_000uL), + SparkExitFixtures.utxo("f1".repeat(32), 0u, 60uL), + ) + chain.outcome = SparkExitBroadcastOutcome.Accepted + val done = SparkExitFixtures.record(Phase.Done).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + feeRateSatPerVbyte = 5uL, + leftover = listOf(SparkExitRecord.Leftover(coin, 1u, 25_000uL)), + ) + + val cheap = assertNotNull(driver(tip = 1_000u).tick(done).leftoverSweep) + assertEquals(1uL, cheap.feeRateSatPerVbyte) + // The 60-sat coin costs 68 sats to add: only the other one is swept. + assertEquals(listOf(coin), SparkExitTxInputs.decode(requireNotNull(cheap.txHex))?.map { it.prevTxid }) + + chain.economyRate = 9uL + assertNull(assertNotNull(driver(tip = 1_000u).tick(done).leftoverSweep).feeRateSatPerVbyte) + } + @Test fun `top up ignores cpfp change chained to the funding address`() = test { var record = SparkExitFixtures.record(Phase.NeedsFunding(23_000uL)).copy( @@ -1226,16 +1290,18 @@ class SparkExitDriverTest : BaseUnitTest() { } @Test - fun `a sweep refused for its fee that only dust is left of at the next block's rate is kept as dust`() = test { - chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 300 < 400") - var record = driver(tip = 1_000u).tick(sweepDone()) - chain.nextBlockRate = 1_000uL + fun `a sweep refused for its fee that only dust is left of at the next block's rate waits for cheaper fees`() = + test { + chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 300 < 400") + var record = driver(tip = 1_000u).tick(sweepDone()) + chain.nextBlockRate = 1_000uL - record = driver(tip = 1_001u).tick(record) + record = driver(tip = 1_001u).tick(record) - assertEquals(SparkExitRecord.LeftoverSweep(null, null, 25_000uL), record.leftoverSweep) - assertFalse(record.needsDriving) - } + assertTrue(record.isLeftoverWaitingForFees) + assertEquals(1_001u, assertNotNull(record.leftoverSweep).waitingSince) + assertTrue(record.needsDriving) + } @Test fun `a replacement that would be dust keeps the accepted sweep`() = test { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt index 18cf41a0e5..e4c399fa03 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -182,6 +182,10 @@ class FakeSparkExitChain : SparkExitChain { var fees = SparkExitNetworkFees(fastest = 5uL, halfHour = 3uL) override suspend fun networkFees(): SparkExitNetworkFees = fees + + var economyRate: ULong? = 1uL + + override suspend fun economyFeeRate(): ULong = economyRate ?: throw SparkExitChainError("No fee estimates") } class FakeSparkExitRecovering : SparkExitRecovering { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 0cb2e26f58..762681d6e6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -561,4 +561,24 @@ class SparkExitFundingTest { assertEquals("s", retried.adopt(SparkExitFixtures.recovery(emptyList()), 2L).landedSweepTxid) assertEquals(retried, SparkExitJson.decode(SparkExitJson.encode(retried))) } + + @Test + fun `the leftover sweeps at the network's cheapest rate, never above the exit's, at least 1 sat per vbyte`() { + assertEquals(2uL, SparkExitMath.sweepFeeRate(economy = 2uL, exitRate = 9uL)) + assertEquals(9uL, SparkExitMath.sweepFeeRate(economy = 20uL, exitRate = 9uL)) + assertEquals(9uL, SparkExitMath.sweepFeeRate(economy = null, exitRate = 9uL)) + assertEquals(1uL, SparkExitMath.sweepFeeRate(economy = 0uL, exitRate = 9uL)) + } + + @Test + fun `a leftover sweep takes only coins worth more than their input fee`() { + val coins = listOf( + SparkExitSweep.Input("a", 0u, 294uL), + SparkExitSweep.Input("b", 0u, 340uL), + SparkExitSweep.Input("c", 0u, 341uL), + ) + // 68 vB at 5 sat/vB is 340 sats. + assertEquals(listOf("c"), SparkExitSweep.worthSweeping(coins, 5uL).map { it.txid }) + assertEquals(listOf("a", "b", "c"), SparkExitSweep.worthSweeping(coins, 4uL).map { it.txid }) + } } From 012c6cb920c2f8fbecd5a66fdb491196ba489ea6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 5 Nov 2026 23:57:21 +0100 Subject: [PATCH 020/154] fix: spark exit asks nothing while a higher fee confirms --- .../to/bitkit/repositories/SparkExitRecord.kt | 5 ++++ .../to/bitkit/repositories/SparkExitRepo.kt | 5 +++- .../settings/lightning/SparkExitViewModel.kt | 6 +++-- .../repositories/SparkExitDriverTest.kt | 3 +++ .../lightning/SparkExitViewModelTest.kt | 23 +++++++++++++++++++ 5 files changed, 39 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 394c4f13e1..b91c49488e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -209,6 +209,11 @@ data class SparkExitRecord( /** The leftover waits for network fees to drop before it is worth sweeping. */ val isLeftoverWaitingForFees: Boolean get() = leftover.isNotEmpty() && leftoverSweep?.isWaitingForFees == true + /** Savings paid funding the exit has not taken yet, such as a higher fee: nothing is asked while it confirms. */ + val isAwaitingOwnPayment: Boolean + get() = fundingPaymentTxid != null && fundingShortfallSats != null && + funding.none { it.txid == fundingPaymentTxid } + /** A built sweep of the leftover, saved before it is sent; a null [txid] means it was dust and nothing went. */ data class LeftoverSweep( val txid: String?, diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index d90a79e023..825d0a1090 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -362,7 +362,10 @@ class SparkExitRepo @Inject constructor( } is SparkExitRecord.Phase.NeedsFunding -> { work.cancelDeadline() - if (previous.phase !is SparkExitRecord.Phase.NeedsFunding) work.notify(SparkExitAlert.Funding) + // A payment from savings, such as a higher fee, is on its way: nothing to ask the user for. + if (previous.phase !is SparkExitRecord.Phase.NeedsFunding && !record.isAwaitingOwnPayment) { + work.notify(SparkExitAlert.Funding) + } } else -> work.cancelDeadline() } diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index 608ce31a37..db11586f34 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -302,8 +302,10 @@ data class SparkExitUiState( /** The exit's fee rate, while a step the network accepted does not confirm for longer than that rate needs. */ val lowFeeRate: ULong? get() { - val active = record?.takeIf { it.isActive } ?: return null - return active.feeRateSatPerVbyte.takeIf { active.underpricedStep(tipHeight) != null } + // Not while a higher fee is paid and the exit waits to rebuild at it. + val running = record?.takeIf { it.phase == SparkExitRecord.Phase.Running && !it.isRebuilding } + ?: return null + return running.feeRateSatPerVbyte.takeIf { running.underpricedStep(tipHeight) != null } } /** The SWEEP transaction of a finished exit, or the one that landed before a retry of leaves replaced it. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 2ce70f0ec5..164097d6d4 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -781,6 +781,8 @@ class SparkExitDriverTest : BaseUnitTest() { .applyFeeBump(rate = 9uL, extraSats = 6_612uL, paymentTxid = "bump") assertEquals(Phase.NeedsFunding(26_612uL), record.phase) assertEquals(SparkExitFundingState.Paid("bump"), SparkExitMath.fundingState(record, utxos = null)) + // Savings' payment is on its way: nothing is asked for while it confirms. + assertTrue(record.isAwaitingOwnPayment) chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf( SparkExitFixtures.utxo("f0", value = 20_000uL), @@ -791,6 +793,7 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(Phase.Running, record.phase) assertEquals(9uL, sdk.prepareRequests.single().feeRateSatPerVbyte) + assertFalse(record.isAwaitingOwnPayment) assertEquals( listOf("f0", "bump"), sdk.recoverRequests.single().fundingInputs.map { (it as CpfpInput.P2wpkh).txid } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 61b85e8ced..1ba830a3c2 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -86,6 +86,29 @@ class SparkExitViewModelTest : BaseUnitTest() { assertFalse(SparkExitFeeBumpUiState(options = persistentListOf(fast), spendableSats = 5_000uL).isSavingsShort) } + @Test + fun `a paid higher fee no longer shows the fee as too low`() { + val running = SparkExitFixtures.record(SparkExitRecord.Phase.Running) + .adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))), 0L) + val slow = running.copy( + broadcastLog = listOf( + SparkExitRecord.BroadcastAttempt( + running.generation, + "n1", + 1, + 0, + 0L, + "ok", + true, + acceptedAtHeight = 990u + ), + ), + ) + assertEquals(2uL, SparkExitUiState(record = slow, tipHeight = 1_000u).lowFeeRate) + val paid = slow.applyFeeBump(rate = 9uL, extraSats = 5_000uL, paymentTxid = "bump") + assertNull(SparkExitUiState(record = paid, tipHeight = 1_000u).lowFeeRate) + } + @Test fun `done names the sweep that landed before a retry of leaves replaced it`() { val done = SparkExitFixtures.record(SparkExitRecord.Phase.Done) From 0a41ffb2444f6205a50c2f45f9e3f0d769cf0142 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 00:25:10 +0100 Subject: [PATCH 021/154] fix: spark exit rerun findings --- .../to/bitkit/repositories/SparkExitDriver.kt | 22 +++++++++++++++++-- .../to/bitkit/repositories/SparkExitRecord.kt | 11 +++++++++- .../to/bitkit/repositories/SparkExitRepo.kt | 9 ++++++++ .../to/bitkit/repositories/SparkExitWorker.kt | 4 ++++ .../java/to/bitkit/services/SparkService.kt | 3 +-- .../repositories/SparkExitAlertsTest.kt | 10 +++++++++ .../repositories/SparkExitDriverTest.kt | 18 +++++++++++++++ .../bitkit/repositories/SparkExitFixtures.kt | 4 +++- .../repositories/SparkExitFundingTest.kt | 18 +++++++++++++++ .../repositories/SparkExitRecordTest.kt | 6 ++++- 10 files changed, 98 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 976a44e611..89884187cb 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -5,6 +5,7 @@ import breez_sdk_spark.CpfpFundingKind import breez_sdk_spark.CpfpSigner import breez_sdk_spark.ExitLeafSelection import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.ImportUnilateralExitStateResponse import breez_sdk_spark.PrepareRecoverFundsRequest import breez_sdk_spark.PrepareRecoverFundsResponse import breez_sdk_spark.RecoverFundsRequest @@ -31,7 +32,7 @@ interface SparkExitRecovering { suspend fun exportExitState(): String /** Merges exit data from [exportExitState] back in; an older one never costs the wallet a leaf. */ - suspend fun importExitState(exitState: String) + suspend fun importExitState(exitState: String): ImportUnilateralExitStateResponse } /** @@ -259,6 +260,14 @@ class SparkExitDriver( private suspend fun withExitState(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { record.exitStateSnapshot?.let { snapshot -> runSuspendCatching { sdk.importExitState(snapshot) } + .onSuccess { + Logger.info( + "Imported the Spark exit's own exit data: '${it.importedLeaves}' leaves imported, " + + "'${it.skippedChains}' already held, '${it.skippedForeignLeaves}' foreign, " + + "'${it.skippedConflictingLeaves}' conflicting", + context = TAG, + ) + } .onFailure { Logger.warn("Failed to import the Spark exit data snapshot", it, context = TAG) } return record } @@ -366,7 +375,9 @@ class SparkExitDriver( val stored = record.recovery ?: return record.copy(phase = SparkExitRecord.Phase.AwaitingFunding(0uL)) val checked = sdk.check(withConfirmations(stored)) Logger.debug("Checked Spark exit generation '${record.generation}': '${checked.verdict}'", context = TAG) - val updated = record.copy(recovery = checked.recovery).withProgress(checked.recovery) + val updated = record.copy( + recovery = checked.recovery + ).withProgress(checked.recovery).withRebuildLanded(checked.recovery) return when (checked.verdict) { RecoveryVerdict.Valid -> { val confirmed = checked.recovery.transactions @@ -504,6 +515,13 @@ class SparkExitDriver( return rebuild(counted, sdk) } + /** A step of the rebuild from the chain confirmed: the note that the record could not be read has served. */ + private fun SparkExitRecord.withRebuildLanded(checked: RecoverFundsResponse): SparkExitRecord { + val since = rebuiltFromChainConfirmedCount ?: return this + if (SparkExitMath.confirmedCount(checked) <= since) return this + return copy(isRebuiltFromChain = false, rebuiltFromChainConfirmedCount = null) + } + /** A step confirmed since the last rebuild over a broken chain: the exit moves, so the count starts over. */ private fun SparkExitRecord.withProgress(checked: RecoverFundsResponse): SparkExitRecord { val since = stallConfirmedCount ?: return this diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index b91c49488e..a1e25881fd 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -125,6 +125,8 @@ data class SparkExitRecord( val isFailedLeavesReleased: Boolean = false, /** The confirmed sweep of a replaced generation, so Done still names it after a retry of leaves replaced it. */ val landedSweepTxid: String? = null, + /** Steps confirmed when the rebuild from the chain was adopted; one more clears [isRebuiltFromChain]. */ + val rebuiltFromChainConfirmedCount: Int? = null, ) { companion object { const val CURRENT_VERSION = 1 @@ -331,7 +333,12 @@ data class SparkExitRecord( failedLeafCount = built.failed.size, retrySince = null, retriedAt = null, - isRebuiltFromChain = false, + // A rebuild from the chain keeps saying so until one of its steps confirms. + rebuiltFromChainConfirmedCount = if (isRebuiltFromChain) { + rebuiltFromChainConfirmedCount ?: SparkExitMath.confirmedCount(built) + } else { + null + }, ) /** @@ -785,6 +792,7 @@ object SparkExitJson { r.failedLeafRetriedAt?.let { put("failedLeafRetriedAt", it.toLong()) } if (r.isFailedLeavesReleased) put("isFailedLeavesReleased", true) r.landedSweepTxid?.let { put("landedSweepTxid", it) } + r.rebuiltFromChainConfirmedCount?.let { put("rebuiltFromChainConfirmedCount", it) } if (r.earlierReceivedSats.isNotEmpty()) { put( "earlierReceivedSats", @@ -891,6 +899,7 @@ object SparkExitJson { failedLeafRetriedAt = o.ulongOrNull("failedLeafRetriedAt")?.toUInt(), isFailedLeavesReleased = o.booleanOrNull("isFailedLeavesReleased") ?: false, landedSweepTxid = o.stringOrNull("landedSweepTxid"), + rebuiltFromChainConfirmedCount = o.intOrNull("rebuiltFromChainConfirmedCount"), earlierReceivedSats = o.objectOrNull("earlierReceivedSats") ?.mapValues { it.value.jsonPrimitive.content.toULong() } .orEmpty(), diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 825d0a1090..cf759009f4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -344,6 +344,15 @@ class SparkExitRepo @Inject constructor( SparkExitAlerts.losses(record, previous, reportedLost).forEach { work.notify(it, amountSats = record.lostSats.takeIf { _ -> it == SparkExitAlert.Lost }) } + // The exit stopped rebuilding and says it is not moving: no later run fixes that, so the user hears now. + if (SparkExitAlerts.isNewlyStalled(record, previous)) { + val untilMaturity = SparkExitMath.untilNextMaturity(record.recovery, _state.value.tipHeight, Env.network) + val deadline = SparkExitMath.deadline(untilMaturity, Env.network) + work.notify( + SparkExitAlert.Rejected, + deadlineAtMillis = clock.nowMs() + deadline.deadlineIn.inWholeMilliseconds + ) + } when (record.phase) { // Waiting on the operators for a week needs nothing from the user, so nothing reminds them. SparkExitRecord.Phase.Running if record.isWaitingForOperators -> { diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index 0a38846fd8..6298809e11 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -321,6 +321,10 @@ object SparkExitAlerts { ) } + /** [record] started saying it is not moving on the tick from [previous]. */ + fun isNewlyStalled(record: SparkExitRecord, previous: SparkExitRecord): Boolean = + record.isActive && record.isStalled && !previous.isStalled + /** * Why a running exit fell behind its deadline, or null when it needs nothing from the user. [feeLowRate] is the * exit's rate while the network finds it too low, which no background run changes. diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index d01d3ac416..b77b53b777 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -295,9 +295,8 @@ class BreezSparkExitRecovering(private val sdk: BreezSdk) : SparkExitRecovering override suspend fun exportExitState(): String = sdk.exportUnilateralExitState().exitState - override suspend fun importExitState(exitState: String) { + override suspend fun importExitState(exitState: String): ImportUnilateralExitStateResponse = sdk.importUnilateralExitState(ImportUnilateralExitStateRequest(exitState)) - } } sealed class SparkError(message: String, cause: Throwable? = null) : AppError(message, cause) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt index 372ddb967c..3b385c4356 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt @@ -3,7 +3,9 @@ package to.bitkit.repositories import org.junit.Test import to.bitkit.repositories.SparkExitRecord.Phase import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertNull +import kotlin.test.assertTrue class SparkExitAlertsTest { private val running = SparkExitFixtures.record(Phase.Running) @@ -97,4 +99,12 @@ class SparkExitAlertsTest { SparkExitAlerts.losses(another, running, reportedLost = setOf("leaf-1")), ) } + + @Test + fun `an exit that starts saying it is not moving is posted at once`() { + val stalled = running.copy(stallRebuilds = SparkExitDriver.STALL_REBUILDS_TO_SURFACE) + assertTrue(SparkExitAlerts.isNewlyStalled(stalled, running)) + assertFalse(SparkExitAlerts.isNewlyStalled(stalled, stalled)) + assertFalse(SparkExitAlerts.isNewlyStalled(running, running)) + } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 164097d6d4..1616f9bff5 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -816,6 +816,24 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("n1b"), chain.broadcasts.map { it.txid }) } + @Test + fun `a rebuild from the chain keeps its note until one of its steps confirms`() = test { + val built = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + val record = SparkExitFixtures.record(Phase.Running) + .copy(isRebuilding = true, isRebuiltFromChain = true) + .adopt(built, 0L) + sdk.checks += check(built, RecoveryVerdict.Valid) + assertTrue(driver(tip = 1_000u).tick(record).isRebuiltFromChain) + + val landed = SparkExitFixtures.recovery( + listOf(SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(1_000u))) + ) + sdk.checks += check(landed, RecoveryVerdict.Valid) + val ticked = driver(tip = 1_001u).tick(record) + assertFalse(ticked.isRebuiltFromChain) + assertNull(ticked.rebuiltFromChainConfirmedCount) + } + @Test fun `rebuild with nothing left ends the exit`() = test { val record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt index e4c399fa03..6fecdad179 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -9,6 +9,7 @@ import breez_sdk_spark.CpfpSigner import breez_sdk_spark.ExitChainState import breez_sdk_spark.ExitLeafSelection import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.ImportUnilateralExitStateResponse import breez_sdk_spark.PrepareRecoverFundsRequest import breez_sdk_spark.PrepareRecoverFundsResponse import breez_sdk_spark.RecoverFundsLeaf @@ -229,8 +230,9 @@ class FakeSparkExitRecovering : SparkExitRecovering { return exitState } - override suspend fun importExitState(exitState: String) { + override suspend fun importExitState(exitState: String): ImportUnilateralExitStateResponse { imports += exitState + return ImportUnilateralExitStateResponse(0u, 0u, 0u, 17u) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 762681d6e6..7dbcf322ef 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -581,4 +581,22 @@ class SparkExitFundingTest { assertEquals(listOf("c"), SparkExitSweep.worthSweeping(coins, 5uL).map { it.txid }) assertEquals(listOf("a", "b", "c"), SparkExitSweep.worthSweeping(coins, 4uL).map { it.txid }) } + + /** The local regtest rerun's case 4: an exit asking for 2,283 at 2 sat/vB, so 136 sats per extra input. */ + @Test + fun `the pre-start hint and the progress top-up name the same total with every extra input's fee`() { + val one = SparkExitMath.prestartFunding(2_283uL, payments = 1, receivedSats = 1_283uL, feeRateSatPerVbyte = 2uL) + assertEquals(SparkExitPartialFunding(1_283uL, 2_419uL, 1_136uL), one.partial) + val two = SparkExitMath.prestartFunding(2_283uL, payments = 2, receivedSats = 2_283uL, feeRateSatPerVbyte = 2uL) + assertEquals(SparkExitPartialFunding(2_283uL, 2_555uL, 294uL), two.partial) + assertTrue(SparkExitMath.prestartFunding(2_283uL, 2, 2_419uL, 2uL).isCovered) + + val topUp = SparkExitFixtures.record(SparkExitRecord.Phase.NeedsFunding(2_283uL)) + val first = listOf(SparkExitFixtures.utxo("a", value = 1_283uL)) + val ask = assertIs(SparkExitMath.fundingState(topUp, first)) + assertEquals(SparkExitPartialFunding(1_283uL, 2_419uL, 1_136uL), ask.partial) + val second = first + SparkExitFixtures.utxo("b", value = 1_000uL) + val again = assertIs(SparkExitMath.fundingState(topUp, second)) + assertEquals(SparkExitPartialFunding(2_283uL, 2_555uL, 294uL), again.partial) + } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt index 2f501d2157..bdb4932873 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -274,7 +274,11 @@ class SparkExitRecordTest { assertEquals(100_000uL, salvaged.leafTotalSats) assertEquals("exit-state", salvaged.exitStateSnapshot) assertEquals(salvaged, SparkExitJson.decode(SparkExitJson.encode(salvaged))) - assertFalse(salvaged.adopt(SparkExitFixtures.recovery(emptyList()), 1L).isRebuiltFromChain) + // The note stays until a step of the rebuild confirms. + val rebuilt = salvaged.adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))), 1L) + assertTrue(rebuilt.isRebuiltFromChain) + assertEquals(0, rebuilt.rebuiltFromChainConfirmedCount) + assertEquals(rebuilt, SparkExitJson.decode(SparkExitJson.encode(rebuilt))) } @Test From 2a75eea45cd417f7c1bd8f49853ce036bacdc6ee Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 00:32:19 +0100 Subject: [PATCH 022/154] chore: resync this branch with its pull request From 623e6f0aa6239205316c06308c9a274b33d2c69a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 00:53:14 +0100 Subject: [PATCH 023/154] fix: spark exit sends lone transactions as a package when the host refuses them --- .../to/bitkit/repositories/SparkExitChain.kt | 34 ++++++++++---- .../bitkit/repositories/SparkExitChainTest.kt | 47 +++++++++++++++++++ 2 files changed, 73 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 3f89b9ed78..2327aa9ac6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -24,6 +24,7 @@ import kotlinx.serialization.json.longOrNull import to.bitkit.env.Env import to.bitkit.ext.runSuspendCatching import to.bitkit.utils.AppError +import to.bitkit.utils.SignedTransactionId import kotlin.math.ceil data class EsploraTxStatus(val confirmed: Boolean, val blockHeight: UInt? = null) @@ -75,7 +76,10 @@ interface SparkExitChain { suspend fun isTxKnown(txid: String): Boolean suspend fun broadcast(tx: RecoveryTransaction): SparkExitBroadcastOutcome - /** A transaction of the app's own, such as the sweep of leftover fee funding, as a single `/tx`. */ + /** + * A transaction of the app's own, such as the sweep of leftover fee funding, as a single `/tx`, or as a one-item + * package on a host that refuses it there with a bare RPC error. + */ suspend fun broadcastHex(hex: String): SparkExitBroadcastOutcome /** The rate for the next block, from `/fee-estimates`, rounded up. */ @@ -109,7 +113,8 @@ data class SparkExitHosts(val reads: List, val broadcasts: List - submitSingle(host.url, hex).also { if (it == SparkExitBroadcastOutcome.Accepted) return it } + submitSingle(host, hex).also { if (it == SparkExitBroadcastOutcome.Accepted) return it } } return outcomes.firstOrNull { it is SparkExitBroadcastOutcome.Rejected } ?: outcomes.firstOrNull() @@ -221,7 +226,7 @@ class EsploraSparkExitChain( private suspend fun submitPackage( host: SparkExitBroadcastHost, hexes: List, - parentTxid: String, + parentTxid: String?, ): SparkExitBroadcastOutcome? { val body = JsonArray(hexes.map(::JsonPrimitive)).toString() for (path in host.packagePaths) { @@ -232,10 +237,13 @@ class EsploraSparkExitChain( return null } - private suspend fun submitSingle(host: String, hex: String): SparkExitBroadcastOutcome? { - val response = post("$host/tx", TextContent(hex, ContentType.Text.Plain)) ?: return null + private suspend fun submitSingle(host: SparkExitBroadcastHost, hex: String): SparkExitBroadcastOutcome? { + val response = post("${host.url}/tx", TextContent(hex, ContentType.Text.Plain)) ?: return null if (response.status.value in NOT_HERE) return null - return SparkExitBroadcastClassifier.single(response.status.value, response.bodyAsText()) + val outcome = SparkExitBroadcastClassifier.single(response.status.value, response.bodyAsText()) + if (!SparkExitBroadcastClassifier.isUnplaceable(outcome)) return outcome + val txid = runCatching { SignedTransactionId.fromHex(hex) }.getOrNull() + return submitPackage(host, listOf(hex), txid) ?: outcome } private suspend fun post(url: String, content: TextContent): HttpResponse? = @@ -362,6 +370,16 @@ object SparkExitBroadcastClassifier { fun isFeeTooLow(outcome: SparkExitBroadcastOutcome): Boolean = outcome is SparkExitBroadcastOutcome.Rejected && isFeeTooLow(outcome.reason) + private val bareRpcError = Regex("code\\\\?\"\\s*:\\s*-1\\b") + + /** + * A refusal that names only RPC code -1, with no reason a node gives: Spark's hosted regtest answers every lone + * `/tx` that way, while the same hex as a package gets a real answer. + */ + fun isUnplaceable(outcome: SparkExitBroadcastOutcome): Boolean = + outcome is SparkExitBroadcastOutcome.Rejected && bareRpcError.containsMatchIn(outcome.reason) && + !outcome.reason.contains("message", ignoreCase = true) + fun classify(text: String): SparkExitBroadcastOutcome = when { knownMessages.any { it in text } || hasRpcCode(-27, text) -> SparkExitBroadcastOutcome.Accepted notMatureMessages.any { it in text } -> SparkExitBroadcastOutcome.NotMature(text) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt index fd408b35e6..8cdd0e976b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -78,6 +78,53 @@ class SparkExitChainTest : BaseUnitTest() { assertEquals(null, requests.single().headers["Content-Type"]) } + private val bareRefusal = """{"error":"sendrawtransaction RPC error: {\"code\":-1}"}""" + + @Test + fun `a lone transaction refused with a bare rpc error is sent again as a one-item package`() = test { + val sut = chain( + Route("a.example/api/tx", 400, bareRefusal), + Route("a.example/api/v1/txs/package", 200, """{"package_msg":"success","tx-results":{}}"""), + ) + + assertEquals(SparkExitBroadcastOutcome.Accepted, sut.broadcastHex("02sweep")) + assertEquals(listOf("02sweep", """["02sweep"]"""), bodies) + } + + @Test + fun `a one-item package's own error is classified`() = test { + val sut = chain( + Route("a.example/api/tx", 400, bareRefusal), + Route( + "a.example/api/v1/txs/package", + 200, + """{"package_msg":"transaction failed","tx-results":{"w":{"txid":"x","error":"non-BIP68-final"}}}""", + ), + ) + + val outcome = sut.broadcast(SparkExitFixtures.tx("s1", kind = breez_sdk_spark.RecoveryTxKind.SWEEP)) + + assertIs(outcome) + } + + @Test + fun `a lone transaction a host takes or refuses with a reason never goes out as a package`() = test { + assertEquals( + SparkExitBroadcastOutcome.Accepted, + chain(Route("a.example/api/tx", 200, "s1")).broadcastHex("02s1") + ) + assertEquals(1, requests.size) + val refused = chain( + Route("a.example/api/tx", 400, "sendrawtransaction RPC error: min relay fee not met, 1 < 2") + ) + assertIs(refused.broadcastHex("02s1")) + assertEquals(2, requests.size) + assertFalse( + SparkExitBroadcastClassifier.isUnplaceable(SparkExitBroadcastOutcome.Rejected("min relay fee not met")) + ) + assertTrue(SparkExitBroadcastClassifier.isUnplaceable(SparkExitBroadcastClassifier.classify(bareRefusal))) + } + @Test fun `falls back to the unversioned package path then the next host`() = test { val sut = chain( From 41dbb0d3b1d70bd4e48fbb2974e0fd8dfe91edaf Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 15:31:12 +0100 Subject: [PATCH 024/154] fix: spark exit retries a refused fee change sweep --- .../to/bitkit/repositories/SparkExitChain.kt | 58 ++++++++++---- .../to/bitkit/repositories/SparkExitDriver.kt | 39 +++++++--- .../to/bitkit/repositories/SparkExitRecord.kt | 18 ++++- .../to/bitkit/repositories/SparkExitSweep.kt | 16 ++++ .../lightning/SparkExitProgressScreen.kt | 2 +- .../bitkit/repositories/SparkExitChainTest.kt | 17 +++++ .../repositories/SparkExitDriverTest.kt | 76 ++++++++++++------- 7 files changed, 170 insertions(+), 56 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 2327aa9ac6..31cad50722 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -88,10 +88,42 @@ interface SparkExitChain { /** The rates for the next block and about half an hour, from `/fee-estimates` targets 1 and 3, rounded up. */ suspend fun networkFees(): SparkExitNetworkFees - /** The network's cheapest rate, `/fee-estimates` at its farthest target, rounded up and at least 1 sat/vB. */ + /** The network's cheapest rate, `/fee-estimates` at its farthest target, rounded up; 1 sat/vB with none. */ suspend fun economyFeeRate(): ULong } +/** The least rate nodes relay, used when the chain host gives no estimate at all. */ +private const val MIN_RELAY_RATE = 1uL + +/** + * `/fee-estimates`, a map from confirmation target in blocks to sat/vB. A host can leave targets out, or answer `{}` + * as a fresh mempool does, so each read falls back to the next target it has. + */ +object SparkExitFeeEstimates { + private val json = Json { ignoreUnknownKeys = true } + + fun parse(body: String): Map = runCatching { + json.parseToJsonElement(body).jsonObject.mapNotNull { (key, value) -> + val target = key.toIntOrNull() ?: return@mapNotNull null + val rate = (value as? JsonPrimitive)?.content?.toDoubleOrNull() ?: return@mapNotNull null + target to rate + }.toMap() + }.getOrDefault(emptyMap()) + + /** The rate for [target] blocks, else for the next target after it, else the closest before it; at least 1. */ + fun at(estimates: Map, target: Int): ULong? { + val key = estimates.keys.filter { it >= target }.minOrNull() ?: estimates.keys.maxOrNull() ?: return null + return round(estimates.getValue(key)) + } + + /** The rate at the farthest target, the cheapest the host knows; at least 1. */ + fun farthest( + estimates: Map + ): ULong? = estimates.keys.maxOrNull()?.let { round(estimates.getValue(it)) } + + private fun round(rate: Double): ULong = maxOf(1uL, ceil(rate).toULong()) +} + /** What the network asks now, in sat/vB: for the next block, and for about half an hour. */ data class SparkExitNetworkFees(val fastest: ULong, val halfHour: ULong) @@ -161,24 +193,20 @@ class EsploraSparkExitChain( override suspend fun txStatus(txid: String): EsploraTxStatus = status(json.parseToJsonElement(get("/tx/$txid/status")).jsonObject) - override suspend fun nextBlockFeeRate(): ULong { - val rate = json.parseToJsonElement(get("/fee-estimates")).jsonObject.getValue("1").jsonPrimitive.content - return ceil(rate.toDouble()).toULong() - } - - override suspend fun economyFeeRate(): ULong { - val estimates = json.parseToJsonElement(get("/fee-estimates")).jsonObject - val farthest = estimates.keys.maxByOrNull { it.toIntOrNull() ?: 0 } - ?: throw SparkExitChainError("No fee estimates") - return maxOf(1uL, ceil(estimates.getValue(farthest).jsonPrimitive.content.toDouble()).toULong()) - } + override suspend fun nextBlockFeeRate(): ULong = SparkExitFeeEstimates.at(feeEstimates(), 1) ?: MIN_RELAY_RATE override suspend fun networkFees(): SparkExitNetworkFees { - val estimates = json.parseToJsonElement(get("/fee-estimates")).jsonObject - fun rate(target: String) = ceil(estimates.getValue(target).jsonPrimitive.content.toDouble()).toULong() - return SparkExitNetworkFees(fastest = rate("1"), halfHour = rate("3")) + val estimates = feeEstimates() + return SparkExitNetworkFees( + fastest = SparkExitFeeEstimates.at(estimates, 1) ?: MIN_RELAY_RATE, + halfHour = SparkExitFeeEstimates.at(estimates, 3) ?: MIN_RELAY_RATE, + ) } + override suspend fun economyFeeRate(): ULong = SparkExitFeeEstimates.farthest(feeEstimates()) ?: MIN_RELAY_RATE + + private suspend fun feeEstimates(): Map = SparkExitFeeEstimates.parse(get("/fee-estimates")) + override suspend fun isTxKnown(txid: String): Boolean { if (hosts.reads.isEmpty()) throw SparkExitChainError("No chain host configured") val path = "/tx/$txid/hex" diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 89884187cb..f916342f0b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -600,35 +600,40 @@ class SparkExitDriver( // The sweep, or a version it replaced, confirmed. val sent = listOfNotNull(built.txid.takeIf { built.isAccepted }) + built.replacedTxids if (sent.any { isConfirmed(it) }) return record.copy(leftoverSweep = built.copy(isConfirmed = true)) + // Refused for its fee: wait for the next block and try again at a rate nodes take. + if (built.isFeeRejection) return waitForFees(record, built) val sentAt = built.sentAtHeight val isOverdue = built.isAccepted && sentAt != null && tip != null && tip >= sentAt + SWEEP_REPLACE_BLOCKS - if (isOverdue || built.isFeeRejection) { - val replaced = replaceSweep(record, built) - if (replaced != null || built.isFeeRejection) return replaced ?: record - } + if (isOverdue) replaceSweep(record, built)?.let { return it } // Sent again until it confirms; a node that already has it accepts it again. return sendSweep(record, built, built.txHex) } if (built?.isWaitingForFees == true) { + // A version a node accepted before a later refusal may still confirm. + if (built.replacedTxids.any { isConfirmed(it) }) { + return record.copy(leftoverSweep = built.copy(isConfirmed = true)) + } val height = tip ?: return record val since = requireNotNull(built.waitingSince) if (height >= since + SWEEP_RELEASE_BLOCKS) { Logger.info("Keeping the Spark exit leftover as dust after waiting for cheaper fees", context = TAG) return record.copy(leftoverSweep = built.copy(isDustKept = true)) } - if (height < (built.checkedAtHeight ?: since) + SWEEP_RECHECK_BLOCKS) return record + val next = built.retryAtHeight ?: ((built.checkedAtHeight ?: since) + SWEEP_RECHECK_BLOCKS) + if (height < next) return record } val address = record.funding.firstOrNull()?.address ?: return record val utxos = runSuspendCatching { chain.utxos(address) }.getOrNull() ?: return record if (utxos.isEmpty()) return record.copy(leftover = emptyList()) if (utxos.any { !it.status.confirmed }) return record val current = record.copy(leftover = utxos.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) }) - val rate = SparkExitMath.sweepFeeRate(economyRate(), record.feeRateSatPerVbyte) + val floor = built?.takeIf { it.isWaitingForFees }?.refusedFeeRate ?: 0uL + val rate = maxOf(SparkExitMath.sweepFeeRate(economyRate(), record.feeRateSatPerVbyte), floor) val inputs = SparkExitSweep.worthSweeping( utxos.map { SparkExitSweep.Input(it.txid, it.vout, it.value) }, rate, ) - return buildSweep(current, inputs, rate) + return buildSweep(current, inputs, rate, built?.replacedTxids?.takeIf { it.isNotEmpty() }) } /** The network's cheapest rate, null when it cannot be read. */ @@ -640,18 +645,28 @@ class SparkExitDriver( * The leftover waits for fees to drop, from [tip] or from when it started waiting; while the tip is unknown it * stays as it is and the next tick tries again. */ - private fun waitForFees(record: SparkExitRecord): SparkExitRecord { + private fun waitForFees( + record: SparkExitRecord, + refused: SparkExitRecord.LeftoverSweep? = null, + ): SparkExitRecord { val totalSats = record.leftover.fold(0uL) { sum, leftover -> sum.safe() + leftover.valueSats.safe() } val height = tip ?: return record Logger.info("Waiting for cheaper fees to sweep the Spark exit leftover", context = TAG) - val since = record.leftoverSweep?.takeIf { it.isWaitingForFees }?.waitingSince ?: height + val earlier = record.leftoverSweep + val since = earlier?.takeIf { it.isWaitingForFees }?.waitingSince ?: earlier?.waitingSince ?: height + val floor = refused?.let { + SparkExitSweep.refusedFeeRate(it.rejection, it.feeRateSatPerVbyte ?: record.feeRateSatPerVbyte) + } return record.copy( leftoverSweep = SparkExitRecord.LeftoverSweep( null, null, totalSats, + replacedTxids = refused?.replacedTxids.orEmpty(), waitingSince = since, checkedAtHeight = height, + refusedFeeRate = floor, + retryAtHeight = floor?.let { height + 1u }, ), ) } @@ -697,7 +712,11 @@ class SparkExitDriver( return record } // A replacement of an accepted sweep keeps that one; otherwise the leftover waits for cheaper fees. - ?: return if (!replaced.isNullOrEmpty()) record else waitForFees(record) + ?: return if (!replaced.isNullOrEmpty() && record.leftoverSweep?.txHex != null) { + record + } else { + waitForFees(record) + } val sweep = runSuspendCatching { val signed = makeSigner().signPsbt(SparkExitSweep.psbt(plan, address)) val hex = SparkExitSweep.signedTxHex(plan, signed) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index a1e25881fd..5818ef3567 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -209,7 +209,12 @@ data class SparkExitRecord( data class FailedLeaf(val leafId: String, val valueSats: ULong) /** The leftover waits for network fees to drop before it is worth sweeping. */ - val isLeftoverWaitingForFees: Boolean get() = leftover.isNotEmpty() && leftoverSweep?.isWaitingForFees == true + val isLeftoverWaitingForFees: Boolean + get() { + val sweep = leftoverSweep ?: return false + // A sweep refused for its fee goes back to waiting on the next tick; until then it reads the same. + return leftover.isNotEmpty() && (sweep.isWaitingForFees || (sweep.isFeeRejection && !sweep.isAccepted)) + } /** Savings paid funding the exit has not taken yet, such as a higher fee: nothing is asked while it confirms. */ val isAwaitingOwnPayment: Boolean @@ -236,6 +241,13 @@ data class SparkExitRecord( val checkedAtHeight: UInt? = null, /** The wait ran out: the leftover stays at its funding address as dust. */ val isDustKept: Boolean = false, + /** + * While waiting: the least rate a node takes, read from the refusal of an earlier version. The next build pays + * this or the network's cheapest rate, whichever is higher, even past the exit's own rate. + */ + val refusedFeeRate: ULong? = null, + /** While waiting after a refusal: the tip from which the next build may go out, the block after it. */ + val retryAtHeight: UInt? = null, ) { /** Not built, waiting for fees to drop. A sweep with no [txid] and no wait is dust kept, as before waits. */ val isWaitingForFees: Boolean get() = txid == null && waitingSince != null && !isDustKept @@ -754,6 +766,8 @@ object SparkExitJson { sweep.waitingSince?.let { put("waitingSince", it.toLong()) } sweep.checkedAtHeight?.let { put("checkedAtHeight", it.toLong()) } if (sweep.isDustKept) put("isDustKept", true) + sweep.refusedFeeRate?.let { put("refusedFeeRate", it.toLong()) } + sweep.retryAtHeight?.let { put("retryAtHeight", it.toLong()) } } /** What the exit keeps to pace and bound its rebuilds and waits, each left out at its default. */ @@ -864,6 +878,8 @@ object SparkExitJson { waitingSince = it.ulongOrNull("waitingSince")?.toUInt(), checkedAtHeight = it.ulongOrNull("checkedAtHeight")?.toUInt(), isDustKept = it.booleanOrNull("isDustKept") ?: false, + refusedFeeRate = it.ulongOrNull("refusedFeeRate"), + retryAtHeight = it.ulongOrNull("retryAtHeight")?.toUInt(), ) }, fundingPaymentTxid = o.stringOrNull("fundingPaymentTxid"), diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt index 8dd4cf8268..0d4d084ccc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt @@ -22,6 +22,22 @@ object SparkExitSweep { /** An unsigned sweep of [inputs] to [destination], or null when what it pays would be under the dust limit. */ class Plan(val inputs: List, val destinationScript: ByteArray, val amountSats: ULong, val feeSats: ULong) + private val feeNotMet = Regex("""fee not met,\s*(\d+)\s*<\s*(\d+)""") + + /** + * The least rate a node takes after it refused a sweep built at [feeRateSatPerVbyte] with [rejection], such as + * `min relay fee not met, 450 < 674` (fees in sats): that rate scaled to the fee asked for, rounded up, and at + * least one more than the refused rate. + */ + fun refusedFeeRate(rejection: String?, feeRateSatPerVbyte: ULong): ULong { + val rate = maxOf(1uL, feeRateSatPerVbyte) + val match = rejection?.let { feeNotMet.find(it) } + val paid = match?.groupValues?.get(1)?.toULongOrNull()?.takeIf { it > 0uL } + val asked = match?.groupValues?.get(2)?.toULongOrNull() + val scaled = if (paid != null && asked != null) (rate * asked + paid - 1uL) / paid else 0uL + return maxOf(scaled, rate + 1uL) + } + /** The inputs worth more than the fee each adds to a sweep at [feeRateSatPerVbyte]: the rest cost more to send. */ fun worthSweeping(inputs: List, feeRateSatPerVbyte: ULong): List { val inputFee = SparkExitMath.inputFeeSats(maxOf(1uL, feeRateSatPerVbyte)) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index cfcd6df7e1..4980638421 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -295,7 +295,7 @@ private fun LeftoverNote(record: SparkExitRecord, address: String, path: String? txidRes = R.string.lightning__spark_exit__leftover_txid, testTag = "SparkExitLeftoverSwept", ) - sweep?.txid != null && (sweep.rejection == null || sweep.isFeeRejection) -> BodyS( + sweep?.txid != null && sweep.rejection == null -> BodyS( text = stringResource(R.string.lightning__spark_exit__leftover_sending) .replace("{amount}", sparkExitAmountText(sweep.valueSats)), color = Colors.White64, diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt index 8cdd0e976b..41b20f53a2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -125,6 +125,23 @@ class SparkExitChainTest : BaseUnitTest() { assertTrue(SparkExitBroadcastClassifier.isUnplaceable(SparkExitBroadcastClassifier.classify(bareRefusal))) } + @Test + fun `fee estimates fall back to the next target, then to the min relay rate, and never fail`() = test { + val empty = chain( + Route("a.example/api/fee-estimates", 200, "{}"), + Route("a.example/api/fee-estimates", 200, "{}") + ) + assertEquals(1uL, empty.nextBlockFeeRate()) + assertEquals(SparkExitNetworkFees(fastest = 1uL, halfHour = 1uL), empty.networkFees()) + assertEquals(1uL, chain(Route("a.example/api/fee-estimates", 200, "{}")).economyFeeRate()) + + val sparse = mapOf(6 to 3.2, 144 to 1.1) + assertEquals(4uL, SparkExitFeeEstimates.at(sparse, 1)) + assertEquals(2uL, SparkExitFeeEstimates.at(sparse, 1_008)) + assertEquals(2uL, SparkExitFeeEstimates.farthest(sparse)) + assertEquals(sparse, SparkExitFeeEstimates.parse("""{"6":3.2,"144":1.1,"x":2}""")) + } + @Test fun `falls back to the unversioned package path then the next host`() = test { val sut = chain( diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 1616f9bff5..1025c16f83 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1245,26 +1245,58 @@ class SparkExitDriverTest : BaseUnitTest() { ) } + /** + * The 0.28 rerun's case 6 (Run E): six 294-sat coins of per-node change swept at 1 sat/vB, which the mempool + * refused with "min relay fee not met, 450 < 674". + */ @Test - fun `a leftover sweep refused for its fee is built again at the next block's rate`() = test { - chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 300 < 400") - var record = driver(tip = 1_000u).tick(sweepDone()) - val refused = assertNotNull(record.leftoverSweep) - assertTrue(refused.isFeeRejection) - assertTrue(record.isLeftoverSweepPending) + fun `a fee change sweep refused for its fee waits a block and tries again at a rate nodes take`() = test { + val coins = List(6) { SparkExitFixtures.utxo("%064x".format(it), 0u, 294uL) } + chain.utxosByAddress[SWEEP_FUNDING] = coins + chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 450 < 674") + val done = SparkExitFixtures.record(Phase.Done).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + feeRateSatPerVbyte = 1uL, + leftover = coins.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) }, + ) - chain.nextBlockRate = 10uL + var record = driver(tip = 1_000u).tick(done) + // Refused, as a stored record from before this rule would be: it already reads as waiting for fees. + assertTrue(assertNotNull(record.leftoverSweep).isFeeRejection) + assertTrue(record.isLeftoverWaitingForFees) + record = driver(tip = 1_000u).tick(record) + + // Back to waiting, with the rate the refusal asks for, still driven, and Done says the change waits. + val waiting = assertNotNull(record.leftoverSweep) + assertTrue(record.isLeftoverWaitingForFees) + assertEquals(2uL, waiting.refusedFeeRate) + assertEquals(1_001u, waiting.retryAtHeight) + assertEquals(1_000u, waiting.waitingSince) + assertTrue(record.needsDriving) + assertEquals(1, chain.rawBroadcasts.size) + assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) + + // Not again in the same block; the next one builds at max(economy, 2). + record = driver(tip = 1_000u).tick(record) + assertEquals(1, chain.rawBroadcasts.size) chain.outcome = SparkExitBroadcastOutcome.Accepted record = driver(tip = 1_001u).tick(record) + val sent = assertNotNull(record.leftoverSweep) + assertEquals(2uL, sent.feeRateSatPerVbyte) + assertTrue(sent.isAccepted) + assertEquals(6, SparkExitTxInputs.decode(requireNotNull(sent.txHex))?.size) + assertFalse(record.isLeftoverWaitingForFees) + } - val rebuilt = assertNotNull(record.leftoverSweep) - assertTrue(rebuilt.txid != refused.txid) - assertEquals(10uL, rebuilt.feeRateSatPerVbyte) - assertTrue(rebuilt.valueSats < refused.valueSats) - assertTrue(rebuilt.isAccepted) - assertNull(rebuilt.rejection) - assertEquals(1_001u, rebuilt.sentAtHeight) - assertEquals(rebuilt.txHex, chain.rawBroadcasts.last()) + @Test + fun `a refused minimum is the refused rate scaled to the fee asked for, and at least one more`() { + assertEquals(2uL, SparkExitSweep.refusedFeeRate("min relay fee not met, 450 < 674", 1uL)) + assertEquals( + 4uL, + SparkExitSweep.refusedFeeRate("mempool min fee not met, 450 < 1_400".replace("_", ""), 1uL) + ) + assertEquals(3uL, SparkExitSweep.refusedFeeRate("insufficient fee", 2uL)) } @Test @@ -1310,20 +1342,6 @@ class SparkExitDriverTest : BaseUnitTest() { assertFalse(record.needsDriving) } - @Test - fun `a sweep refused for its fee that only dust is left of at the next block's rate waits for cheaper fees`() = - test { - chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 300 < 400") - var record = driver(tip = 1_000u).tick(sweepDone()) - chain.nextBlockRate = 1_000uL - - record = driver(tip = 1_001u).tick(record) - - assertTrue(record.isLeftoverWaitingForFees) - assertEquals(1_001u, assertNotNull(record.leftoverSweep).waitingSince) - assertTrue(record.needsDriving) - } - @Test fun `a replacement that would be dust keeps the accepted sweep`() = test { var record = driver(tip = 1_000u).tick(sweepDone()) From d9d3c873defac03672ad5815d9d41954d8ef4d94 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 6 Nov 2026 18:45:06 +0100 Subject: [PATCH 025/154] fix: spark exit notifies when it stops moving --- .../to/bitkit/repositories/SparkExitRepo.kt | 2 +- .../to/bitkit/repositories/SparkExitWorker.kt | 16 ++++++---- .../repositories/SparkExitAlertsTest.kt | 4 +++ .../bitkit/repositories/SparkExitRepoTest.kt | 30 +++++++++++++++++++ 4 files changed, 46 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index cf759009f4..e9316cc6ee 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -349,7 +349,7 @@ class SparkExitRepo @Inject constructor( val untilMaturity = SparkExitMath.untilNextMaturity(record.recovery, _state.value.tipHeight, Env.network) val deadline = SparkExitMath.deadline(untilMaturity, Env.network) work.notify( - SparkExitAlert.Rejected, + SparkExitAlert.NotMoving, deadlineAtMillis = clock.nowMs() + deadline.deadlineIn.inWholeMilliseconds ) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index 6298809e11..cc5091fabb 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -227,8 +227,8 @@ class SparkExitWork @Inject constructor( amountSats: ULong? = null, feeRateSatPerVbyte: ULong? = null, ) { - // Losses are posted on screen too: the user may be anywhere in the app when an exit fails or loses a leaf. - if (App.currentActivity?.value != null && alert !in ALWAYS_POSTED) return + // Losses and a stopped exit are posted on screen too. + if (App.currentActivity?.value != null && !alert.isPostedOnScreen) return val time = deadlineAtMillis?.let { DateFormat.getTimeFormat(context).format(Date(it)) } val amount = amountSats?.let { "$BITCOIN_SYMBOL ${it.formatToModernDisplay()}" } val text = context.getString(alert.textRes(hasDeadline = time != null)) @@ -294,10 +294,15 @@ data class SparkExitBackgroundLimits( val areNotificationsEnabled: Boolean = true, ) -/** Why the user is asked to open Bitkit. */ -enum class SparkExitAlert { Funding, Lost, Failed, Rejected, FeeLow, Offline, Restricted, Battery, Behind } +/** + * Why the user is asked to open Bitkit. [NotMoving] is the exit stopping its rebuilds over a broken chain, posted once + * on the tick it happens, with the refused-steps text. + */ +enum class SparkExitAlert { Funding, Lost, Failed, NotMoving, Rejected, FeeLow, Offline, Restricted, Battery, Behind } -private val ALWAYS_POSTED = setOf(SparkExitAlert.Lost, SparkExitAlert.Failed) +/** Posted while Bitkit is on screen too: the user may be anywhere in the app, and no later run changes them. */ +val SparkExitAlert.isPostedOnScreen: Boolean + get() = this == SparkExitAlert.Lost || this == SparkExitAlert.Failed || this == SparkExitAlert.NotMoving object SparkExitAlerts { /** @@ -357,6 +362,7 @@ private fun SparkExitAlert.textRes(hasDeadline: Boolean): Int = when (this) { SparkExitAlert.Failed -> R.string.lightning__spark_exit__notification_failed SparkExitAlert.FeeLow -> R.string.lightning__spark_exit__fee_low SparkExitAlert.Rejected if hasDeadline -> R.string.lightning__spark_exit__notification_rejected + SparkExitAlert.NotMoving if hasDeadline -> R.string.lightning__spark_exit__notification_rejected SparkExitAlert.Offline if hasDeadline -> R.string.lightning__spark_exit__notification_offline SparkExitAlert.Restricted if hasDeadline -> R.string.lightning__spark_exit__notification_restricted SparkExitAlert.Battery if hasDeadline -> R.string.lightning__spark_exit__notification_battery diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt index 3b385c4356..e2375749f9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt @@ -106,5 +106,9 @@ class SparkExitAlertsTest { assertTrue(SparkExitAlerts.isNewlyStalled(stalled, running)) assertFalse(SparkExitAlerts.isNewlyStalled(stalled, stalled)) assertFalse(SparkExitAlerts.isNewlyStalled(running, running)) + // Posted while Bitkit is on screen too, as losses are; a missed run's reminder is not. + assertTrue(SparkExitAlert.NotMoving.isPostedOnScreen) + assertTrue(SparkExitAlert.Lost.isPostedOnScreen) + assertFalse(SparkExitAlert.Rejected.isPostedOnScreen) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index a00f976628..b48772b5b7 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -254,6 +254,36 @@ class SparkExitRepoTest : BaseUnitTest() { verify(work, times(2)).armDeadline(any(), any()) } + @Test + fun `an exit that stops moving after three stall rebuilds notifies once, at once`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + store.save(SparkExitFixtures.record(Phase.Running).adopt(recovery, 0L)) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) + val posts = mutableListOf() + val refusal = """sendrawtransaction RPC error: {"code":-26,"message":"insufficient fee"}""" + + repeat(SparkExitDriver.STALL_REBUILDS_TO_SURFACE + 1) { run -> + // A rival keeps winning the step: it was refused twice already in this generation, and rebuilds are due. + val stored = requireNotNull(store.load()) + val refused = SparkExitRecord.BroadcastAttempt(stored.generation, "n1", 2, 2, 0L, "rejected", false) + store.save(stored.copy(broadcastLog = listOf(refused), lastBuildAt = null)) + val sdk = FakeSparkExitRecovering().apply { + preparedResponse = SparkExitFixtures.prepared(funding = null) + checks += CheckRecoverFundsResponse(recovery, RecoveryVerdict.Valid) + builds += recovery + } + createSut(coldSpark(sdk), regtestMempool(posts, refusal)).runInBackground().getOrThrow() + + val record = requireNotNull(store.load()) + val expected = if (run + 1 >= SparkExitDriver.STALL_REBUILDS_TO_SURFACE) 1 else 0 + assertEquals(minOf(run + 1, SparkExitDriver.STALL_REBUILDS_TO_SURFACE), record.stallRebuilds) + verify(work, times(expected)).notify(eq(SparkExitAlert.NotMoving), anyOrNull(), anyOrNull(), anyOrNull()) + } + } + @Test fun `a background run whose step keeps going unpaid lets the deadline alarm fire`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) From 64004d7ed272170fe95442db8cb3797873037fd5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 00:26:58 +0100 Subject: [PATCH 026/154] fix: spark exit cancel, fee bump and sweep findings from review --- .../to/bitkit/repositories/SparkExitChain.kt | 42 ++- .../to/bitkit/repositories/SparkExitDriver.kt | 197 +++++----- .../bitkit/repositories/SparkExitFunding.kt | 3 + .../to/bitkit/repositories/SparkExitRecord.kt | 130 +++++-- .../to/bitkit/repositories/SparkExitRepo.kt | 343 ++++++++++++------ .../to/bitkit/repositories/SparkExitWorker.kt | 16 +- .../java/to/bitkit/repositories/SparkRepo.kt | 11 +- .../lightning/SparkExitProgressScreen.kt | 24 +- .../settings/lightning/SparkExitViewModel.kt | 18 +- app/src/main/res/values-ar/strings.xml | 5 + app/src/main/res/values-b+es+419/strings.xml | 5 + app/src/main/res/values-ca/strings.xml | 5 + app/src/main/res/values-cs/strings.xml | 5 + app/src/main/res/values-de/strings.xml | 5 + app/src/main/res/values-el/strings.xml | 5 + app/src/main/res/values-es-rES/strings.xml | 5 + app/src/main/res/values-es/strings.xml | 5 + app/src/main/res/values-fr/strings.xml | 5 + app/src/main/res/values-it/strings.xml | 5 + app/src/main/res/values-nl/strings.xml | 5 + app/src/main/res/values-pl/strings.xml | 5 + app/src/main/res/values-pt-rBR/strings.xml | 5 + app/src/main/res/values-pt/strings.xml | 5 + app/src/main/res/values-ru/strings.xml | 5 + app/src/main/res/values/strings.xml | 5 + .../bitkit/repositories/SparkExitChainTest.kt | 27 +- .../repositories/SparkExitDriverTest.kt | 77 +++- .../repositories/SparkExitRecordTest.kt | 3 +- .../bitkit/repositories/SparkExitRepoTest.kt | 250 ++++++++++++- .../lightning/SparkExitViewModelTest.kt | 7 +- 30 files changed, 938 insertions(+), 290 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 31cad50722..6a1bb63cdf 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -268,8 +268,11 @@ class EsploraSparkExitChain( private suspend fun submitSingle(host: SparkExitBroadcastHost, hex: String): SparkExitBroadcastOutcome? { val response = post("${host.url}/tx", TextContent(hex, ContentType.Text.Plain)) ?: return null if (response.status.value in NOT_HERE) return null - val outcome = SparkExitBroadcastClassifier.single(response.status.value, response.bodyAsText()) - if (!SparkExitBroadcastClassifier.isUnplaceable(outcome)) return outcome + val body = response.bodyAsText() + val outcome = SparkExitBroadcastClassifier.single(response.status.value, body) + if (outcome !is SparkExitBroadcastOutcome.Rejected || !SparkExitBroadcastClassifier.isUnplaceable(body)) { + return outcome + } val txid = runCatching { SignedTransactionId.fromHex(hex) }.getOrNull() return submitPackage(host, listOf(hex), txid) ?: outcome } @@ -354,9 +357,7 @@ object SparkExitBroadcastClassifier { } if (outcomes.isEmpty()) { return if (results.isEmpty()) { - SparkExitBroadcastOutcome.RetryLater( - body - ) + SparkExitBroadcastOutcome.RetryLater(shortReason(body)) } else { SparkExitBroadcastOutcome.Accepted } @@ -404,19 +405,38 @@ object SparkExitBroadcastClassifier { * A refusal that names only RPC code -1, with no reason a node gives: Spark's hosted regtest answers every lone * `/tx` that way, while the same hex as a package gets a real answer. */ - fun isUnplaceable(outcome: SparkExitBroadcastOutcome): Boolean = - outcome is SparkExitBroadcastOutcome.Rejected && bareRpcError.containsMatchIn(outcome.reason) && - !outcome.reason.contains("message", ignoreCase = true) + fun isUnplaceable(text: String): Boolean = + bareRpcError.containsMatchIn(text) && !text.contains("message", ignoreCase = true) + /** + * Classifies a node's answer from its whole [text]; the outcome carries only a short reason, the node's message + * or RPC code, so a host's error page is never kept or shown. + */ fun classify(text: String): SparkExitBroadcastOutcome = when { knownMessages.any { it in text } || hasRpcCode(-27, text) -> SparkExitBroadcastOutcome.Accepted - notMatureMessages.any { it in text } -> SparkExitBroadcastOutcome.NotMature(text) + notMatureMessages.any { it in text } -> SparkExitBroadcastOutcome.NotMature(shortReason(text)) inputsMissingMessages.any { it in text } || hasRpcCode(-25, text) -> SparkExitBroadcastOutcome.InputsMissing( - text + shortReason(text) ) - else -> SparkExitBroadcastOutcome.Rejected(text) + else -> SparkExitBroadcastOutcome.Rejected(shortReason(text)) } + private val messageField = Regex("""message\\?"\s*:\s*\\?"((?:[^"\\]|\\[^"])*)""") + private val rpcCodeField = Regex("""code\\?"\s*:\s*(-?\d+)""") + private val markup = Regex("<[^>]*>") + private val whitespace = Regex("\\s+") + + /** A node's message, else its RPC code, else the answer without markup, in one line of at most 200 characters. */ + fun shortReason(text: String): String { + val message = messageField.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() } + val reason = message + ?: rpcCodeField.find(text)?.groupValues?.get(1)?.let { "RPC error $it" } + ?: text.replace(markup, " ") + return reason.replace(whitespace, " ").trim().take(MAX_REASON_LENGTH) + } + + private const val MAX_REASON_LENGTH = 200 + /** The RPC code, also when the node's error sits JSON-escaped inside mempool's own error object. */ private fun hasRpcCode(code: Int, text: String) = Regex("""code\\?"\s*:\s*$code\b""").containsMatchIn(text) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index f916342f0b..84d3080304 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -136,11 +136,16 @@ class SparkExitDriver( return record } is SparkExitRecord.Phase.AwaitingFunding, is SparkExitRecord.Phase.NeedsFunding -> { - val sdk = recovering ?: return record - val shortfall = record.fundingShortfallSats - // Nothing to fund when every leaf is recovered cooperatively. - if (shortfall != null) record = adoptFunding(record, shortfall) ?: return record - record = build(record, sdk) + // A higher fee paid from savings: the generation out there keeps going while that payment confirms. + if (record.isDrivingWhileFunding) record = driveWhileFunding(record) + record = lookForOwnPayment(record) + val sdk = recovering + if (sdk != null && record.phase.requiredFundingSats != null) { + val shortfall = record.fundingShortfallSats + // Nothing to fund when every leaf is recovered cooperatively. + val funded = if (shortfall != null) adoptFunding(record, shortfall) else record + if (funded != null) record = build(funded, sdk) + } } SparkExitRecord.Phase.Running if record.isRebuilding -> { // The diverged generation is never broadcast again; only a rebuild moves on from here. @@ -162,10 +167,6 @@ class SparkExitDriver( return record } - /** - * Adds every confirmed UTXO of new funding at the funding address once together they cover [requiredSats]; null - * while they do not. Several small payments count: the SDK spends every funding input it is given. - */ private suspend fun adoptFunding(record: SparkExitRecord, requiredSats: ULong): SparkExitRecord? { val first = record.funding.firstOrNull() ?: return null val candidates = SparkExitMath.newFunding(chain.utxos(first.address), record) @@ -230,6 +231,8 @@ class SparkExitDriver( val held = record.funding.firstOrNull()?.address?.let { address -> runSuspendCatching { chain.utxos(address) }.getOrNull()?.let { SparkExitMath.heldSats(it, record) } } + // Without a reading of the address the shortfall is unknown; the next tick builds again. + if (held == null && record.fundedSats > 0uL) return record val inputFee = SparkExitMath.inputFeeSats(record.feeRateSatPerVbyte) val needed = SparkExitMath.neededFunding(it.requiredSats, record.fundedSats, held, inputFee) return record.copy(phase = SparkExitRecord.Phase.NeedsFunding(needed)) @@ -252,11 +255,6 @@ class SparkExitDriver( return broadcastReady(adopted) } - /** - * Before the first build, keeps the SDK's exit data as it is now, which still holds every leaf of the exit; before - * every later build, imports it again, so a backup or sync since cannot have dropped a leaf the rebuild needs. - * A failure is logged and the build goes on. - */ private suspend fun withExitState(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { record.exitStateSnapshot?.let { snapshot -> runSuspendCatching { sdk.importExitState(snapshot) } @@ -280,7 +278,6 @@ class SparkExitDriver( return record.copy(exitStateSnapshot = exported) } - /** Dates at this tip each of the exit's leaves the operators' watchtower stopped that was not seen stopped yet. */ private fun SparkExitRecord.seeStopped(stopped: Set): SparkExitRecord { val height = tip ?: return this val fresh = stopped.filter { it in leafIds && it !in stoppedLeafSince } @@ -288,7 +285,6 @@ class SparkExitDriver( return copy(stoppedLeafSince = stoppedLeafSince + fresh.associateWith { height }) } - /** [leafId] was stopped by the operators' watchtower fewer than six blocks ago, or its age is unknown. */ private fun isStoppedWaiting(record: SparkExitRecord, leafId: String, stopped: Set): Boolean { if (leafId !in stopped) return false val since = record.stoppedLeafSince[leafId] ?: return true @@ -296,11 +292,6 @@ class SparkExitDriver( return height < since || height - since < SparkExitMath.STOPPED_BLOCKS } - /** - * An empty build waits while one of the exit's leaves was skipped for a reason that may yet change: the chain - * could not be read for it, its funds were not found yet, the operators could not be reached to find them, or the - * operators' watchtower stopped it a short while ago. Not after about a week of waiting. - */ private fun isWaiting(record: SparkExitRecord, skipped: List, stopped: Set): Boolean { val since = record.retrySince if (since != null && tip != null && SparkExitMath.isRetryReleased(since, tip)) return false @@ -324,12 +315,6 @@ class SparkExitDriver( selection = selection, ) - /** - * Prepares the exit's leaves. A leaf the SDK refuses to exit, such as a fee-ladder leaf whose refund cannot pay its - * own fee at this rate, fails the whole prepare: it is dropped and the rest prepared again. When the refused leaf - * cannot be told, the leaves still recoverable are prepared instead, and the exit's leaves left out are dropped. - * The prepared response is null once no leaves remain. - */ private suspend fun prepare( start: SparkExitRecord, sdk: SparkExitRecovering, @@ -360,10 +345,6 @@ class SparkExitDriver( } } - /** - * Leaves the rebuild unadopted and drops [lost] from the exit: an older state of this wallet claimed them, and - * every rebuild would reproduce the same spent refund. The next tick rebuilds at once without them. - */ private suspend fun loseLeaves(record: SparkExitRecord, lost: List): SparkExitRecord { Logger.warn("Dropping Spark exit leaves '${lost.map { it.leafId }}' claimed by an older state", context = TAG) val updated = record.copy(lostLeaves = record.lostLeaves + lost, isRebuilding = true, lastBuildAt = null) @@ -371,9 +352,38 @@ class SparkExitDriver( return end(updated.copy(phase = SparkExitRecord.Phase.Failed(LOST_REASON), isRebuilding = false), updated) } + private suspend fun lookForOwnPayment(record: SparkExitRecord): SparkExitRecord { + val txid = record.fundingPaymentTxid?.takeIf { record.isAwaitingOwnPayment } ?: return record + val height = tip ?: return record + val isKnown = runSuspendCatching { chain.isTxKnown(txid) }.getOrDefault(true) + return record.withOwnPaymentLooked(height, isKnown) + } + + private suspend fun driveWhileFunding(record: SparkExitRecord): SparkExitRecord { + val sdk = recovering ?: return broadcastWithoutSdk(record) + val stored = requireNotNull(record.recovery) + val checked = runSuspendCatching { sdk.check(withConfirmations(stored)) } + .onFailure { Logger.warn("Failed to check the Spark exit, sending without the SDK", it, context = TAG) } + .getOrNull() + ?: return broadcastWithoutSdk(record) + val updated = record.copy(recovery = checked.recovery) + return when (checked.verdict) { + RecoveryVerdict.Valid -> broadcastReady(updated) + // Finished before the higher fee was needed: running again, the next check ends it and the payment goes + // back with the leftover. + RecoveryVerdict.Done -> updated.copy(phase = SparkExitRecord.Phase.Running) + // A rebuild waits for the funding it was paid for. + is RecoveryVerdict.Redo -> updated + } + } + private suspend fun check(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { val stored = record.recovery ?: return record.copy(phase = SparkExitRecord.Phase.AwaitingFunding(0uL)) - val checked = sdk.check(withConfirmations(stored)) + // An SDK that cannot check this tick still leaves the stored, signed steps to send. + val checked = runSuspendCatching { sdk.check(withConfirmations(stored)) } + .onFailure { Logger.warn("Failed to check the Spark exit, sending without the SDK", it, context = TAG) } + .getOrNull() + ?: return broadcastWithoutSdk(record) Logger.debug("Checked Spark exit generation '${record.generation}': '${checked.verdict}'", context = TAG) val updated = record.copy( recovery = checked.recovery @@ -430,7 +440,7 @@ class SparkExitDriver( */ suspend fun feeBumpShortfall(record: SparkExitRecord, rate: ULong): ULong { val sdk = checkNotNull(recovering) { "Spark is not connected" } - val atRate = record.copy(feeRateSatPerVbyte = rate) + val atRate = withExitState(record, sdk).copy(feeRateSatPerVbyte = rate) val prepared = sdk.prepare(prepareRequest(atRate, ExitLeafSelection.Specific(atRate.exitLeafIds))) if (prepared.funding == null) return 0uL val built = @@ -445,12 +455,6 @@ class SparkExitDriver( return maxOf(extra, SparkExitMath.FUNDING_DUST_SATS) } - /** - * Builds a recovery of its own for [failedIds], the cooperative leaves a finished recovery could not get co-signed: - * at once, then at doubling gaps from 6 blocks to a day, as long-waiting leaves are. After about a week the exit - * is done without them. A recovery built for them is adopted as the next generation; what earlier ones landed - * still counts. - */ private suspend fun retryFailedLeaves( start: SparkExitRecord, failedIds: List, @@ -468,6 +472,7 @@ class SparkExitDriver( if (since != null && !SparkExitMath.isRetryDue(since, record.failedLeafRetriedAt, height)) return record record = record.copy(failedLeafRetrySince = since ?: height, failedLeafRetriedAt = height) val retried = runSuspendCatching { + record = withExitState(record, sdk) val prepared = sdk.prepare(prepareRequest(record, ExitLeafSelection.Specific(failedIds))) val values = ( prepared.leaves.map { it.leafId to it.valueSats } + @@ -490,10 +495,6 @@ class SparkExitDriver( return broadcastReady(adopted) } - /** - * Saves the exit as rebuilding, so nothing of this generation goes out again, and rebuilds it once the last build - * is old enough, so a rebuild that reproduces the same problem cannot loop every tick. - */ private suspend fun rebuild(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { val rebuilding = record.copy(isRebuilding = true) save(rebuilding) @@ -501,10 +502,6 @@ class SparkExitDriver( return build(rebuilding, sdk) } - /** - * Rebuilds over a broken chain, counting the rebuild: one more with no step confirmed since the last, and at - * [STALL_REBUILDS_TO_SURFACE] the exit stops rebuilding and says it is not moving. - */ private suspend fun stallRebuild(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { val confirmed = record.recovery?.let(SparkExitMath::confirmedCount) ?: 0 val counted = record.copy( @@ -515,24 +512,18 @@ class SparkExitDriver( return rebuild(counted, sdk) } - /** A step of the rebuild from the chain confirmed: the note that the record could not be read has served. */ private fun SparkExitRecord.withRebuildLanded(checked: RecoverFundsResponse): SparkExitRecord { val since = rebuiltFromChainConfirmedCount ?: return this if (SparkExitMath.confirmedCount(checked) <= since) return this return copy(isRebuiltFromChain = false, rebuiltFromChainConfirmedCount = null) } - /** A step confirmed since the last rebuild over a broken chain: the exit moves, so the count starts over. */ private fun SparkExitRecord.withProgress(checked: RecoverFundsResponse): SparkExitRecord { val since = stallConfirmedCount ?: return this if (SparkExitMath.confirmedCount(checked) <= since) return this return copy(stallRebuilds = 0, stallConfirmedCount = null) } - /** - * A unilateral step the SDK could not read waits for a rebuild, once a block, and only once no unilateral step is - * ready: a rebuild then would conflict with what is in the mempool at the same rate. - */ private fun needsUnverifiedRebuild(record: SparkExitRecord): Boolean { val height = tip ?: return false if (record.unverifiedRebuiltAtHeight == height) return false @@ -541,12 +532,6 @@ class SparkExitDriver( transactions.none { it.status == ExitTransactionStatus.Ready } } - /** - * Our CPFP children that can never confirm, and every child that spends their change. A wallet whose leaves share - * a node with ours broadcast its own package for it and won: the node is in a block, and our child for it is in - * neither a block nor the mempool. Only children whose change a pending step's child spends are looked up; a dead - * child nothing builds on harms nothing, and its funding ends up in the leftover sweep. - */ private suspend fun deadChildren( recovery: RecoverFundsResponse, isConfirmed: (String) -> Boolean, @@ -564,15 +549,9 @@ class SparkExitDriver( return SparkExitFeeChain.withDescendants(spends, lost) } - /** Every host answered it does not know [txid]; a host that failed otherwise leaves it alive for this tick. */ private suspend fun isUnknownToChain(txid: String): Boolean = runSuspendCatching { !chain.isTxKnown(txid) }.getOrDefault(false) - /** - * Marks the next steps the chain host shows in a block as confirmed. The SDK asks the chain about a step only once - * the caller saw it in a block; otherwise it looks for who spent its input, which an Electrum-backed mempool, - * such as Spark's regtest, does not report. - */ private suspend fun withConfirmations(recovery: RecoverFundsResponse): RecoverFundsResponse { val confirmed = recovery.transactions .filter { it.status is ExitTransactionStatus.Confirmed } @@ -588,12 +567,6 @@ class SparkExitDriver( return recovery.copy(transactions = transactions) } - /** - * Sends what the ended exit left at its funding address to [SparkExitRecord.destination] in one transaction, once - * every UTXO there confirmed, at the exit's fee rate. Built and saved before it is sent, then sent again each tick - * until it confirms. A refusal for its fee builds it again at the next block's rate, as does a day unconfirmed, - * which replaces it; any other refusal is final. Dust is not sent. - */ private suspend fun sweepLeftover(record: SparkExitRecord): SparkExitRecord { val built = record.leftoverSweep if (built?.txHex != null) { @@ -602,6 +575,11 @@ class SparkExitDriver( if (sent.any { isConfirmed(it) }) return record.copy(leftoverSweep = built.copy(isConfirmed = true)) // Refused for its fee: wait for the next block and try again at a rate nodes take. if (built.isFeeRejection) return waitForFees(record, built) + // No node took it in a day: built again from what the address holds. + val builtAt = built.builtAtHeight + if (!built.isAccepted && builtAt != null && tip != null && tip >= builtAt + SWEEP_RECHECK_BLOCKS) { + return record.copy(leftoverSweep = null) + } val sentAt = built.sentAtHeight val isOverdue = built.isAccepted && sentAt != null && tip != null && tip >= sentAt + SWEEP_REPLACE_BLOCKS if (isOverdue) replaceSweep(record, built)?.let { return it } @@ -625,8 +603,39 @@ class SparkExitDriver( val address = record.funding.firstOrNull()?.address ?: return record val utxos = runSuspendCatching { chain.utxos(address) }.getOrNull() ?: return record if (utxos.isEmpty()) return record.copy(leftover = emptyList()) - if (utxos.any { !it.status.confirmed }) return record - val current = record.copy(leftover = utxos.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) }) + // Unconfirmed outputs hold the sweep block by block, for a day at most; then the confirmed ones go. + val confirmed = utxos.filter { it.status.confirmed } + if (confirmed.size < utxos.size) { + val height = tip ?: return record + val since = built?.takeIf { it.isWaitingForFees }?.waitingSince ?: height + if (confirmed.isEmpty() || height < since + SWEEP_RECHECK_BLOCKS) { + val total = utxos.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + val waiting = SparkExitRecord.LeftoverSweep( + null, + null, + total, + replacedTxids = built?.replacedTxids.orEmpty(), + waitingSince = since, + checkedAtHeight = height, + refusedFeeRate = built?.refusedFeeRate, + retryAtHeight = height + 1u, + ) + return record.copy( + leftover = utxos.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) }, + leftoverSweep = waiting, + ) + } + } + val current = record.copy(leftover = confirmed.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) }) + // What not even the lowest relay rate can send stays as dust at once: no wait for fees would change it. + val all = confirmed.map { SparkExitSweep.Input(it.txid, it.vout, it.value) } + val isEverSweepable = runCatching { + SparkExitSweep.plan(SparkExitSweep.worthSweeping(all, 1uL), record.destination, 1uL) != null + }.getOrDefault(true) + if (!isEverSweepable) { + val total = all.fold(0uL) { sum, input -> sum.safe() + input.valueSats.safe() } + return current.copy(leftoverSweep = SparkExitRecord.LeftoverSweep(null, null, total, isDustKept = true)) + } val floor = built?.takeIf { it.isWaitingForFees }?.refusedFeeRate ?: 0uL val rate = maxOf(SparkExitMath.sweepFeeRate(economyRate(), record.feeRateSatPerVbyte), floor) val inputs = SparkExitSweep.worthSweeping( @@ -636,15 +645,10 @@ class SparkExitDriver( return buildSweep(current, inputs, rate, built?.replacedTxids?.takeIf { it.isNotEmpty() }) } - /** The network's cheapest rate, null when it cannot be read. */ private suspend fun economyRate(): ULong? = runSuspendCatching { chain.economyFeeRate() } .onFailure { Logger.warn("Failed to read the economy fee rate for the leftover sweep", it, context = TAG) } .getOrNull() - /** - * The leftover waits for fees to drop, from [tip] or from when it started waiting; while the tip is unknown it - * stays as it is and the next tick tries again. - */ private fun waitForFees( record: SparkExitRecord, refused: SparkExitRecord.LeftoverSweep? = null, @@ -671,10 +675,6 @@ class SparkExitDriver( ) } - /** - * [old] built again from the same inputs at the next block's rate, at least one above its own so nodes take it - * as a replacement; null while the rate or the inputs cannot be read. - */ private suspend fun replaceSweep(record: SparkExitRecord, old: SparkExitRecord.LeftoverSweep): SparkExitRecord? { val hex = old.txHex ?: return null val nextBlock = runSuspendCatching { chain.nextBlockFeeRate() } @@ -685,7 +685,8 @@ class SparkExitDriver( val values = record.leftover.associate { "${it.txid}:${it.vout}" to it.valueSats } val inputs = SparkExitTxInputs.decode(hex)?.map { SparkExitSweep.Input(it.prevTxid, it.vout, values["${it.prevTxid}:${it.vout}"] ?: return null) - }?.let { SparkExitSweep.worthSweeping(it, rate) } ?: return null + } ?: return null + // Every input kept: a replacement must pay more in all than the sweep it replaces. Logger.info("Replacing Spark exit leftover sweep '${old.txid}' at '$rate' sat/vB", context = TAG) // A sweep a node accepted may still confirm, so its txid is kept to look for. val replaced = old.replacedTxids + listOfNotNull(old.txid.takeIf { old.isAccepted }) @@ -695,10 +696,6 @@ class SparkExitDriver( private suspend fun isConfirmed(txid: String): Boolean = runSuspendCatching { chain.txStatus(txid) }.getOrNull()?.confirmed == true - /** - * Builds, saves and sends the sweep of [inputs] at [feeRate]. A replacement of a sweep a node accepted, the [replaced] - * txids given, that would be dust is not built: the earlier one stays. - */ private suspend fun buildSweep( record: SparkExitRecord, inputs: List, @@ -726,6 +723,7 @@ class SparkExitDriver( valueSats = plan.amountSats, feeRateSatPerVbyte = feeRate.takeIf { it != record.feeRateSatPerVbyte }, replacedTxids = replaced.orEmpty(), + builtAtHeight = tip, ) }.getOrElse { Logger.error("Failed to build the Spark exit leftover sweep", it, context = TAG) @@ -752,10 +750,17 @@ class SparkExitDriver( sentAtHeight = sweep.sentAtHeight ?: tip ), ) + // A replacement refused for another reason while the version it replaced may still confirm waits again. + is SparkExitBroadcastOutcome.Rejected if sweep.replacedTxids.isNotEmpty() && tip != null && + !outcome.reason.contains("fee", ignoreCase = true) -> + waitForFees( + record + ).let { it.copy(leftoverSweep = it.leftoverSweep?.copy(replacedTxids = sweep.replacedTxids)) } is SparkExitBroadcastOutcome.Rejected -> record.copy( leftoverSweep = sweep.copy(isAccepted = false, rejection = outcome.reason), ) - is SparkExitBroadcastOutcome.InputsMissing, + // Its inputs went elsewhere: what is still at the address is read and swept again. + is SparkExitBroadcastOutcome.InputsMissing -> record.copy(leftoverSweep = null) is SparkExitBroadcastOutcome.RetryLater, is SparkExitBroadcastOutcome.NotMature, -> record @@ -767,17 +772,12 @@ class SparkExitDriver( return nowMillis() - last >= REBUILD_INTERVAL.inWholeMilliseconds } - /** What is left at the funding address, null when it could not be read. */ private suspend fun leftover(record: SparkExitRecord): List? { val address = record.funding.firstOrNull()?.address ?: return emptyList() return runSuspendCatching { chain.utxos(address) }.getOrNull() ?.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) } } - /** - * [ended] with the leftover at its funding address, or [unchanged] while the address cannot be read: an exit that - * ended without its leftover read would never sweep it. - */ private suspend fun end(ended: SparkExitRecord, unchanged: SparkExitRecord): SparkExitRecord { val leftover = leftover(ended) ?: return unchanged return ended.copy(leftover = leftover) @@ -798,12 +798,6 @@ class SparkExitDriver( return current } - /** - * Without the SDK: each unconfirmed transaction whose parents are confirmed on the chain host and whose relative - * timelock has matured, by the SDK's own rule. A stale one is refused by nodes as a conflict, and only the current - * generation is stored. A step whose input someone else spent is not sent again; the next SDK check rebuilds. A fee - * chain that lost a race is left to that check too, since only the SDK can rebuild it. - */ private suspend fun broadcastWithoutSdk(record: SparkExitRecord): SparkExitRecord { val recovery = record.recovery ?: return record val tip = chain.tipHeight() @@ -841,7 +835,6 @@ class SparkExitDriver( return current.copy(recovery = recovery.copy(transactions = transactions)) } - /** A confirmed parent's height, read from the chain host when the stored confirmation carries none. */ private suspend fun parentHeight(txid: String, known: EsploraTxStatus?): UInt? { if (known?.confirmed != true) return null return known.blockHeight ?: runSuspendCatching { chain.txStatus(txid) }.getOrNull()?.blockHeight @@ -863,10 +856,6 @@ class SparkExitDriver( parentsConfirmed: Boolean, ): SparkExitRecord = broadcast(tx, record, parentsConfirmed).also(save) - /** - * Sends [tx] and logs the outcome. With every parent confirmed, missing inputs mean someone else spent one first: - * the operators, which a rebuild recovers, or an older state of this wallet, which rebuilds keep reproducing. - */ private suspend fun broadcast( tx: RecoveryTransaction, record: SparkExitRecord, diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 6db6b2747d..01c5f4d002 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -99,6 +99,9 @@ data class SparkExitQuote( val leafIds: List get() = prepared.leaves.map { it.leafId } + /** The value of the leaves the quote lists, which the exit takes on-chain. */ + val leafTotalSats: ULong get() = prepared.leaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() } + /** * What the quote cannot exit now: the leaves it skips, and Spark's balance beyond every leaf it lists, such as a * counter-swap still unclaimed. Null when nothing. diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 5818ef3567..4ee06f3a7a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -26,6 +26,7 @@ import kotlinx.serialization.json.put import to.bitkit.models.safe import to.bitkit.utils.AppError import java.io.File +import java.io.FileOutputStream import java.nio.file.Files import java.nio.file.StandardCopyOption @@ -127,6 +128,12 @@ data class SparkExitRecord( val landedSweepTxid: String? = null, /** Steps confirmed when the rebuild from the chain was adopted; one more clears [isRebuiltFromChain]. */ val rebuiltFromChainConfirmedCount: Int? = null, + /** The tip of the first funding-wait tick that looked for [fundingPaymentTxid]. */ + val fundingPaymentSeenAtHeight: UInt? = null, + /** The first tip at which no host knew [fundingPaymentTxid]; cleared once one does. */ + val fundingPaymentMissingSince: UInt? = null, + /** The user cancelled the exit after funding had reached its address; the leftover sweep sends it back. */ + val isCancelled: Boolean = false, ) { companion object { const val CURRENT_VERSION = 1 @@ -137,6 +144,12 @@ data class SparkExitRecord( /** Blocks a step a node accepted may go unconfirmed before the exit's fee rate counts as too low. */ const val UNCONFIRMED_BLOCKS_TO_SURFACE = 6u + /** Blocks a payment from savings may be unknown to every host before the exit forgets it and asks again. */ + const val OWN_PAYMENT_MISSING_BLOCKS = 1u + + /** Blocks after the first look a payment from savings may stay unadopted before the exit asks again. */ + const val OWN_PAYMENT_TIMEOUT_BLOCKS = 144u + /** [fundingStrategy] of an exit that funds each fee-bumped transaction from a UTXO of its own. */ const val PER_NODE = "perNode" } @@ -221,6 +234,26 @@ data class SparkExitRecord( get() = fundingPaymentTxid != null && fundingShortfallSats != null && funding.none { it.txid == fundingPaymentTxid } + /** A higher fee's top-up, not a diverged rebuild: the generation out there is still driven while it confirms. */ + val isDrivingWhileFunding: Boolean + get() = phase is Phase.NeedsFunding && recovery != null && !isRebuilding + + /** + * [fundingPaymentTxid] at [tip], when [isKnown] says whether a host knows it: forgotten once missing for a block, + * or 144 blocks after the first look without being adopted, so the ask and its reminder come back. + */ + fun withOwnPaymentLooked(tip: UInt, isKnown: Boolean): SparkExitRecord { + if (!isAwaitingOwnPayment) return this + val seenAt = fundingPaymentSeenAtHeight ?: tip + val missingSince = if (isKnown) null else fundingPaymentMissingSince ?: tip + val isMissing = missingSince != null && tip >= missingSince + OWN_PAYMENT_MISSING_BLOCKS + val isTimedOut = tip >= seenAt + OWN_PAYMENT_TIMEOUT_BLOCKS + if (isMissing || isTimedOut) { + return copy(fundingPaymentTxid = null, fundingPaymentSeenAtHeight = null, fundingPaymentMissingSince = null) + } + return copy(fundingPaymentSeenAtHeight = seenAt, fundingPaymentMissingSince = missingSince) + } + /** A built sweep of the leftover, saved before it is sent; a null [txid] means it was dust and nothing went. */ data class LeftoverSweep( val txid: String?, @@ -248,6 +281,8 @@ data class SparkExitRecord( val refusedFeeRate: ULong? = null, /** While waiting after a refusal: the tip from which the next build may go out, the block after it. */ val retryAtHeight: UInt? = null, + /** The tip it was built at, so one no node ever takes is built again from the address. */ + val builtAtHeight: UInt? = null, ) { /** Not built, waiting for fees to drop. A sweep with no [txid] and no wait is dust kept, as before waits. */ val isWaitingForFees: Boolean get() = txid == null && waitingSince != null && !isDustKept @@ -371,12 +406,18 @@ data class SparkExitRecord( * and then rebuilds; with nothing to pay, it rebuilds on the next tick. Either way what has not confirmed goes * out again at the new rate and replaces what is in the mempool. Not a Redo, so it strikes nothing. */ - fun applyFeeBump(rate: ULong, extraSats: ULong, paymentTxid: String?): SparkExitRecord { + fun applyFeeBump( + rate: ULong, + extraSats: ULong, + paymentTxid: String?, + ): SparkExitRecord { val bumped = copy(feeRateSatPerVbyte = rate, isRedoRebuild = false) if (extraSats == 0uL) return bumped.copy(isRebuilding = true, lastBuildAt = null) return bumped.copy( phase = Phase.NeedsFunding(fundedSats.safe() + extraSats.safe()), fundingPaymentTxid = paymentTxid, + fundingPaymentSeenAtHeight = null, + fundingPaymentMissingSince = null, ) } @@ -478,16 +519,16 @@ class SparkExitStore(private val file: File) { /** The record's raw text, for salvaging one that cannot be read; null when there is none. */ fun loadText(): String? = file.takeIf { it.exists() }?.readText() - /** Moves an unreadable record out of the way, keeping it for support. */ + /** Copies an unreadable record aside for support; the salvaged record then replaces it in one atomic write. */ fun setAside(nowMillis: Long) { val aside = File(file.parentFile, "${file.nameWithoutExtension}.unreadable-$nowMillis.json") - Files.move(file.toPath(), aside.toPath(), StandardCopyOption.REPLACE_EXISTING) + Files.copy(file.toPath(), aside.toPath(), StandardCopyOption.REPLACE_EXISTING) } fun save(record: SparkExitRecord) { file.parentFile?.mkdirs() val temp = File(file.parentFile, "${file.name}.tmp") - temp.writeText(SparkExitJson.encode(record)) + writeDurably(temp, SparkExitJson.encode(record)) Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) } @@ -513,7 +554,7 @@ class SparkExitLostLeafStore(private val file: File) { if (known.containsAll(leafIds)) return file.parentFile?.mkdirs() val temp = File(file.parentFile, "${file.name}.tmp") - temp.writeText(JsonArray((known + leafIds).sorted().map(::JsonPrimitive)).toString()) + writeDurably(temp, JsonArray((known + leafIds).sorted().map(::JsonPrimitive)).toString()) Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) } @@ -522,6 +563,14 @@ class SparkExitLostLeafStore(private val file: File) { } } +/** Writes [text] to [file] and syncs it to disk, so the atomic move after it never lands an empty file. */ +internal fun writeDurably(file: File, text: String) { + FileOutputStream(file).use { + it.write(text.toByteArray()) + it.fd.sync() + } +} + class SparkExitFormatError(message: String) : AppError(message) /** @@ -620,13 +669,19 @@ object SparkExitJson { isRebuiltFromChain = isActive, exitStateSnapshot = read { o.stringOrNull("exitStateSnapshot") }, fundingStrategy = read { o.stringOrNull("fundingStrategy") }, - // An exit that had ended still sweeps what it left at its funding address. - leftover = read { - o.arrayOrEmpty("leftover").map { - val l = it.jsonObject - SparkExitRecord.Leftover(l.string("txid"), l.ulong("vout").toUInt(), l.ulong("valueSats")) - } + // An exit that had ended still sweeps what it left at its funding address, and keeps what it landed. + leftover = read { o.arrayOrEmpty("leftover").map { leftoverFromJson(it.jsonObject) } }.orEmpty(), + leftoverSweep = read { o.objectOrNull("leftoverSweep")?.let(::sweepFromJson) }, + // The stored recovery's children and fan-out too, when it still reads: their outputs aren't new funding. + earlierCpfpTxids = ( + read { o.arrayOrEmpty("earlierCpfpTxids").map { it.jsonPrimitive.content } }.orEmpty() + + read { o.objectOrNull("recovery")?.let { SparkExitTxids.fundingTxids(recoveryFromJson(it)) } } + .orEmpty() + ).distinct(), + earlierReceivedSats = read { + o.objectOrNull("earlierReceivedSats")?.mapValues { it.value.jsonPrimitive.content.toULong() } }.orEmpty(), + landedSweepTxid = read { o.stringOrNull("landedSweepTxid") }, ) } @@ -768,6 +823,7 @@ object SparkExitJson { if (sweep.isDustKept) put("isDustKept", true) sweep.refusedFeeRate?.let { put("refusedFeeRate", it.toLong()) } sweep.retryAtHeight?.let { put("retryAtHeight", it.toLong()) } + sweep.builtAtHeight?.let { put("builtAtHeight", it.toLong()) } } /** What the exit keeps to pace and bound its rebuilds and waits, each left out at its default. */ @@ -807,6 +863,9 @@ object SparkExitJson { if (r.isFailedLeavesReleased) put("isFailedLeavesReleased", true) r.landedSweepTxid?.let { put("landedSweepTxid", it) } r.rebuiltFromChainConfirmedCount?.let { put("rebuiltFromChainConfirmedCount", it) } + r.fundingPaymentSeenAtHeight?.let { put("fundingPaymentSeenAtHeight", it.toLong()) } + r.fundingPaymentMissingSince?.let { put("fundingPaymentMissingSince", it.toLong()) } + if (r.isCancelled) put("isCancelled", true) if (r.earlierReceivedSats.isNotEmpty()) { put( "earlierReceivedSats", @@ -854,34 +913,14 @@ object SparkExitJson { transferId = o.stringOrNull("transferId"), expectedSats = o.ulong("expectedSats"), claimableAtHeight = o.ulongOrNull("claimableAtHeight")?.toUInt(), - leftover = o.arrayOrEmpty("leftover").map { - val l = it.jsonObject - SparkExitRecord.Leftover(l.string("txid"), l.ulong("vout").toUInt(), l.ulong("valueSats")) - }, + leftover = o.arrayOrEmpty("leftover").map { leftoverFromJson(it.jsonObject) }, skippedLeafCount = o.intOrNull("skippedLeafCount") ?: 0, failedLeafCount = o.intOrNull("failedLeafCount") ?: 0, isRebuilding = o.booleanOrNull("isRebuilding") ?: false, lastBuildAt = o.millisOrNull("lastBuildAt"), leafTotalSats = o.ulongOrNull("leafTotalSats"), earlierCpfpTxids = o.arrayOrEmpty("earlierCpfpTxids").map { it.jsonPrimitive.content }, - leftoverSweep = o.objectOrNull("leftoverSweep")?.let { - SparkExitRecord.LeftoverSweep( - txid = it.stringOrNull("txid"), - txHex = it.stringOrNull("txHex"), - valueSats = it.ulong("valueSats"), - isAccepted = it.booleanOrNull("isAccepted") ?: false, - rejection = it.stringOrNull("rejection"), - isConfirmed = it.booleanOrNull("isConfirmed") ?: false, - feeRateSatPerVbyte = it.ulongOrNull("feeRateSatPerVbyte"), - sentAtHeight = it.ulongOrNull("sentAtHeight")?.toUInt(), - replacedTxids = it.arrayOrEmpty("replacedTxids").map { txid -> txid.jsonPrimitive.content }, - waitingSince = it.ulongOrNull("waitingSince")?.toUInt(), - checkedAtHeight = it.ulongOrNull("checkedAtHeight")?.toUInt(), - isDustKept = it.booleanOrNull("isDustKept") ?: false, - refusedFeeRate = it.ulongOrNull("refusedFeeRate"), - retryAtHeight = it.ulongOrNull("retryAtHeight")?.toUInt(), - ) - }, + leftoverSweep = o.objectOrNull("leftoverSweep")?.let(::sweepFromJson), fundingPaymentTxid = o.stringOrNull("fundingPaymentTxid"), isResultSeen = o.booleanOrNull("isResultSeen") ?: false, spentStepStrikes = o.objectOrNull("spentStepStrikes") @@ -916,11 +955,36 @@ object SparkExitJson { isFailedLeavesReleased = o.booleanOrNull("isFailedLeavesReleased") ?: false, landedSweepTxid = o.stringOrNull("landedSweepTxid"), rebuiltFromChainConfirmedCount = o.intOrNull("rebuiltFromChainConfirmedCount"), + fundingPaymentSeenAtHeight = o.ulongOrNull("fundingPaymentSeenAtHeight")?.toUInt(), + fundingPaymentMissingSince = o.ulongOrNull("fundingPaymentMissingSince")?.toUInt(), + isCancelled = o.booleanOrNull("isCancelled") ?: false, earlierReceivedSats = o.objectOrNull("earlierReceivedSats") ?.mapValues { it.value.jsonPrimitive.content.toULong() } .orEmpty(), ) + private fun leftoverFromJson(l: JsonObject) = + SparkExitRecord.Leftover(l.string("txid"), l.ulong("vout").toUInt(), l.ulong("valueSats")) + + private fun sweepFromJson(it: JsonObject) = + SparkExitRecord.LeftoverSweep( + txid = it.stringOrNull("txid"), + txHex = it.stringOrNull("txHex"), + valueSats = it.ulong("valueSats"), + isAccepted = it.booleanOrNull("isAccepted") ?: false, + rejection = it.stringOrNull("rejection"), + isConfirmed = it.booleanOrNull("isConfirmed") ?: false, + feeRateSatPerVbyte = it.ulongOrNull("feeRateSatPerVbyte"), + sentAtHeight = it.ulongOrNull("sentAtHeight")?.toUInt(), + replacedTxids = it.arrayOrEmpty("replacedTxids").map { txid -> txid.jsonPrimitive.content }, + waitingSince = it.ulongOrNull("waitingSince")?.toUInt(), + checkedAtHeight = it.ulongOrNull("checkedAtHeight")?.toUInt(), + isDustKept = it.booleanOrNull("isDustKept") ?: false, + refusedFeeRate = it.ulongOrNull("refusedFeeRate"), + retryAtHeight = it.ulongOrNull("retryAtHeight")?.toUInt(), + builtAtHeight = it.ulongOrNull("builtAtHeight")?.toUInt(), + ) + private fun phaseToJson(phase: SparkExitRecord.Phase): JsonObject = when (phase) { is SparkExitRecord.Phase.AwaitingFunding -> tagged("awaitingFunding", buildJsonObject { put("requiredSats", phase.requiredSats.toLong()) }) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index e9316cc6ee..4ecd48182e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -79,6 +79,9 @@ class SparkExitRepo @Inject constructor( private val scope = appScope(bgDispatcher, TAG) private val tickMutex = Mutex() + + /** One start or fee payment at a time: a second tap never pays or creates twice. */ + private val paymentMutex = Mutex() private var foregroundJob: Job? = null @Volatile @@ -129,16 +132,17 @@ class SparkExitRepo @Inject constructor( } } - /** - * A record that cannot be read, such as one of an unknown version, is kept aside unchanged for support, and what - * can be read of it carries on as an exit that rebuilds from the chain, so a running exit never disappears. - */ private fun salvage(): SparkExitRecord? { val store = store val text = runCatching { store.loadText() }.getOrNull() runCatching { store.setAside(clock.nowMs()) } .onFailure { Logger.warn("Failed to set the unreadable Spark exit record aside", it, context = TAG) } - val salvaged = text?.let { SparkExitJson.salvage(it, clock.nowMs()) } ?: return null + val salvaged = text?.let { SparkExitJson.salvage(it, clock.nowMs()) } + if (salvaged == null) { + // Nothing to rebuild from: only the copy set aside stays. + runCatching { store.delete() } + return null + } runCatching { store.save(salvaged) } .onFailure { Logger.error("Failed to save the salvaged Spark exit record", it, context = TAG) } Logger.warn("Salvaged the Spark exit record in phase '${salvaged.phase}' to rebuild from chain", context = TAG) @@ -168,7 +172,8 @@ class SparkExitRepo @Inject constructor( */ suspend fun runInBackground(): Result = withContext(bgDispatcher) { runSuspendCatching { - load().getOrThrow() + // Spark has not started in a cold background run, so its wallet index is not known yet. + load(work.activeWalletIndex()).getOrThrow() if (_state.value.record?.needsDriving != true) return@runSuspendCatching _state.value.record tick() if (_state.value.isExiting && !sparkService.isConnected) { @@ -191,6 +196,11 @@ class SparkExitRepo @Inject constructor( .onFailure { Logger.error("Failed to drive the Spark exit", it, context = TAG) _state.update { state -> state.copy(lastError = it.message) } + // A run that failed did not keep the exit on track: the alerts still run and the alarm may fire. + _state.value.record?.takeIf { record -> record.needsDriving }?.let { record -> + runSuspendCatching { afterTick(record, record, isOnTrack = false, reportedLostLeafIds()) } + .onFailure { e -> Logger.warn("Failed to update Spark exit alerts", e, context = TAG) } + } } } finally { tickMutex.unlock() @@ -263,10 +273,6 @@ class SparkExitRepo @Inject constructor( if (!record.needsDriving) work.cancelAll() } - /** - * Ends the exit's transfer once the sweep reaches savings, or once the exit ended, so its amount is never counted - * both as in transfer and in the on-chain balance. Runs on every tick and load until it holds. - */ private suspend fun settleIfFinished(record: SparkExitRecord) { val transferId = record.transferId ?: return if (transferRepo.isSettled(transferId).getOrDefault(true)) return @@ -282,10 +288,6 @@ class SparkExitRepo @Inject constructor( if (isFinished) transferRepo.markSettled(transferId) } - /** - * Settles exit transfers no running exit owns: a record set aside as unreadable, or one written without its - * transfer id before a crash, would otherwise count its amount as in transfer to Savings for good. - */ private suspend fun settleOrphanedTransfers(record: SparkExitRecord?) { val owned = record?.takeIf { it.isActive }?.transferId transferRepo.activeTransfers.first() @@ -296,7 +298,6 @@ class SparkExitRepo @Inject constructor( } } - /** The network's rates for the fee bump and its hint: the SDK's when Spark is connected, else the chain host's. */ private suspend fun refreshNetworkFees(chain: SparkExitChain) { val fees = runSuspendCatching { if (sparkService.isConnected) { @@ -329,12 +330,6 @@ class SparkExitRepo @Inject constructor( } } - /** - * Pushes back the warning that the exit fell behind, to 12 blocks into the operators' window of the next step to - * mature (about 50 blocks after it, when they may publish their own version), or of the steps already waiting to - * be published. Only a run that kept the exit on track pushes it; a stalled exit lets it fire. Needing more fee - * funding is notified once, at once. - */ private fun updateAlerts( record: SparkExitRecord, previous: SparkExitRecord, @@ -353,6 +348,12 @@ class SparkExitRepo @Inject constructor( deadlineAtMillis = clock.nowMs() + deadline.deadlineIn.inWholeMilliseconds ) } + // A payment from savings the exit forgot, as no host knew it or it never confirmed: the ask is back. + if (previous.isAwaitingOwnPayment && !record.isAwaitingOwnPayment && record.fundingShortfallSats != null && + record.fundingPaymentTxid == null + ) { + work.notify(SparkExitAlert.Funding) + } when (record.phase) { // Waiting on the operators for a week needs nothing from the user, so nothing reminds them. SparkExitRecord.Phase.Running if record.isWaitingForOperators -> { @@ -369,6 +370,19 @@ class SparkExitRepo @Inject constructor( clock.nowMs(), ) } + // While a higher fee confirms, the generation out there is still driven, and its deadline stands. + is SparkExitRecord.Phase.NeedsFunding if record.isDrivingWhileFunding -> { + if (previous.phase !is SparkExitRecord.Phase.NeedsFunding && !record.isAwaitingOwnPayment) { + work.notify(SparkExitAlert.Funding) + } + if (!isOnTrack) return + val untilMaturity = SparkExitMath.untilNextMaturity( + record.recovery, + _state.value.tipHeight, + Env.network + ) + work.armDeadline(SparkExitMath.deadline(untilMaturity, Env.network), clock.nowMs()) + } is SparkExitRecord.Phase.NeedsFunding -> { work.cancelDeadline() // A payment from savings, such as a higher fee, is on its way: nothing to ask the user for. @@ -407,18 +421,8 @@ class SparkExitRepo @Inject constructor( val destination = _state.value.pending?.destination ?: lightningRepo.newAddress().getOrThrow() // Leaves an earlier exit lost to an older state stay listed by the operators, but cannot be exited. val lost = reportedLostLeafIds() + _state.value.record?.lostLeaves?.map { it.leafId }.orEmpty() - val quote = recovering.prepareAll( - PrepareRecoverFundsRequest( - feeRateSatPerVbyte = feeRate, - fundingKind = CpfpFundingKind.P2wpkh, - // Each fee-bumped transaction gets a UTXO of its own, so one lost fee race strands one step's - // funding, not the chain after it. - fundingStrategy = CpfpFundingStrategy.PER_NODE, - destination = destination, - selection = ExitLeafSelection.All, - ), - lost, - ).copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) + val quote = recovering.prepareAll(quoteRequest(feeRate, destination), lost) + .copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) // Chosen here, so the funding screen, the fee estimate and the record all use one address. val fundingIndex = nextFundingIndex() val fundingAddress = fundingKey(fundingIndex).address @@ -447,14 +451,20 @@ class SparkExitRepo @Inject constructor( val fees = requireNotNull(_state.value.networkFees) { "No network fee rates" } val driver = driver(chain, recovering, record, _state.value.tipHeight) val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } - SparkExitFeeBumpOption.rates(record.feeRateSatPerVbyte, fees).map { (speed, rate) -> - val extra = driver.feeBumpShortfall(record, rate) - val paymentFee = if (extra == 0uL) { - 0uL - } else { - lightningRepo.calculateTotalFee(extra, address, TransactionSpeed.Fast).getOrThrow() + val priced = SparkExitFeeBumpOption.rates(record.feeRateSatPerVbyte, fees).map { (speed, rate) -> + runSuspendCatching { + val extra = driver.feeBumpShortfall(record, rate) + val paymentFee = if (extra == 0uL) { + 0uL + } else { + lightningRepo.calculateTotalFee(extra, address, TransactionSpeed.Fast).getOrThrow() + } + SparkExitFeeBumpOption(speed, rate, extra, extra.safe() + paymentFee.safe()) } - SparkExitFeeBumpOption(speed, rate, extra, extra.safe() + paymentFee.safe()) + } + // A rate at which the SDK refuses one of the exit's leaves would leave that leaf behind: not offered. + priced.mapNotNull { it.getOrNull() }.ifEmpty { + throw priced.firstNotNullOfOrNull { it.exceptionOrNull() } ?: SparkExitError("No rate to offer") } }.onFailure { Logger.error("Failed to price a higher Spark exit fee", it, context = TAG) @@ -472,28 +482,61 @@ class SparkExitRepo @Inject constructor( */ suspend fun payHigherFee(option: SparkExitFeeBumpOption): Result = withContext(bgDispatcher) { runSuspendCatching { - val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } - val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } - val txid = if (option.extraSats > 0uL) sendFunding(address, option.extraSats) else null - tickMutex.withLock { - val current = _state.value.record ?: return@withLock - val bumped = current.applyFeeBump(option.rateSatPerVbyte, option.extraSats, txid) - store.save(bumped) - _state.update { - it.copy(record = bumped, fundingState = SparkExitMath.fundingState(bumped, utxos = null)) - } + if (!paymentMutex.tryLock()) throw SparkExitError("A Spark exit payment is already being made") + try { + payHigherFeeLocked(option) + } finally { + paymentMutex.unlock() } - Logger.info( - "Raised the Spark exit fee to '${option.rateSatPerVbyte}' sat/vB, paying '${option.extraSats}' sats", - context = TAG, - ) - scope.launch { tick() } - Unit }.onFailure { Logger.error("Failed to raise the Spark exit fee", it, context = TAG) } } + private suspend fun payHigherFeeLocked(option: SparkExitFeeBumpOption) { + val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } + val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } + val txid = if (option.extraSats > 0uL) sendFunding(address, option.extraSats) else null + tickMutex.withLock { + val current = _state.value.record ?: return@withLock + if (current.isRebuilding && current.isActive) { + // It started rebuilding meanwhile: the rebuild adopts or the leftover sweep returns the payment. + Logger.warn("Not applying a higher fee to a Spark exit that started rebuilding", context = TAG) + return@withLock + } + if (!current.isActive) { + // The exit ended while savings paid: the payment is leftover the sweep sends back to savings. + Logger.warn("Sweeping a higher fee paid after the Spark exit ended", context = TAG) + val pending = txid?.let { listOf(SparkExitRecord.Leftover(it, 0u, option.extraSats)) }.orEmpty() + val swept = current.copy(leftover = current.leftover + pending, leftoverSweep = null) + store.save(swept) + _state.update { it.copy(record = swept) } + return@withLock + } + val bumped = current.applyFeeBump(option.rateSatPerVbyte, option.extraSats, txid) + store.save(bumped) + _state.update { + it.copy(record = bumped, fundingState = SparkExitMath.fundingState(bumped, utxos = null)) + } + } + if (_state.value.record?.needsDriving == true) work.schedulePeriodic() + Logger.info( + "Raised the Spark exit fee to '${option.rateSatPerVbyte}' sat/vB, paying '${option.extraSats}' sats", + context = TAG, + ) + scope.launch { tick() } + } + + // Each fee-bumped transaction gets a UTXO of its own, so one lost fee race strands one step's funding, not the + // chain after it. + private fun quoteRequest(feeRate: ULong, destination: String) = PrepareRecoverFundsRequest( + feeRateSatPerVbyte = feeRate, + fundingKind = CpfpFundingKind.P2wpkh, + fundingStrategy = CpfpFundingStrategy.PER_NODE, + destination = destination, + selection = ExitLeafSelection.All, + ) + /** The fee Savings pays to send the fee funding at the fast rate, or null when it cannot. */ suspend fun savingsFundingFee(): Result = withContext(bgDispatcher) { runSuspendCatching { @@ -527,58 +570,97 @@ class SparkExitRepo @Inject constructor( */ suspend fun start(fundFromSavings: Boolean): Result = withContext(bgDispatcher) { runSuspendCatching { - if (_state.value.isExiting) throw SparkExitError("A Spark exit is already running") - val pending = requireNotNull(_state.value.pending) { "No Spark exit quote" } - val network = requireNotNull(sparkService.networkName) { "Spark is not available on this network" } - val key = fundingKey(pending.fundingIndex) - val quote = pending.quote - var record = SparkExitRecord( - network = network, - createdAt = clock.nowMs(), - phase = SparkExitRecord.Phase.AwaitingFunding(quote.fundingSats), - feeRateSatPerVbyte = pending.feeRate, - destination = pending.destination, - leafIds = quote.leafIds, - funding = listOf( - SparkExitRecord.Funding(index = pending.fundingIndex, address = key.address, pubkey = key.pubkey), - ), - expectedSats = quote.incomingSats, - skippedLeafCount = quote.prepared.skipped.size, - fundingStrategy = SparkExitRecord.PER_NODE, - leafTotalSats = quote.prepared.leaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() }, - ) - // Saved before the transfer exists, so a failed save never leaves a transfer counted with no exit behind. - store.save(record) - cacheStore.update { - val next = it.sparkExitNextFundingIndexes + (fundingIndexKey to pending.fundingIndex.toInt() + 1) - it.copy(sparkExitNextFundingIndexes = next) + if (!paymentMutex.tryLock()) throw SparkExitError("A Spark exit is already starting") + try { + startLocked(fundFromSavings) + } finally { + paymentMutex.unlock() } - val transferId = transferRepo.createTransfer( - TransferType.SPARK_EXIT, - quote.incomingSats.toLong() - ).getOrThrow() - record = record.copy(transferId = transferId) - store.save(record) - _state.update { it.copy(record = record, pending = null, fundingAddress = key.address) } - isLoaded = true - // Reconnecting for the exit disconnects Spark, which would cut a running leaf optimization short. - sparkRepo.awaitOptimizationIdle() - sparkRepo.setExiting(true) - work.schedulePeriodic() - Logger.info( - "Started Spark exit of '${quote.exitSats}' sats over '${quote.leafIds.size}' leaves", - context = TAG, - ) - // Driven before paying, so a failed payment from savings still leaves the exit watching its address. - scope.launch { tick() } - onAppForegrounded() - if (fundFromSavings && quote.fundingSats > 0uL) payFunding(key.address, quote.fundingSats) }.onFailure { Logger.error("Failed to start the Spark exit", it, context = TAG) } } - /** Pays the fee funding from savings and keeps its txid, so progress waits for it instead of asking again. */ + private suspend fun startLocked(fundFromSavings: Boolean) { + if (_state.value.isExiting) throw SparkExitError("A Spark exit is already running") + val pending = requireNotNull(_state.value.pending) { "No Spark exit quote" } + val network = requireNotNull(sparkService.networkName) { "Spark is not available on this network" } + val key = fundingKey(pending.fundingIndex) + var quote = pending.quote + var record = SparkExitRecord( + network = network, + createdAt = clock.nowMs(), + phase = SparkExitRecord.Phase.AwaitingFunding(quote.fundingSats), + feeRateSatPerVbyte = pending.feeRate, + destination = pending.destination, + leafIds = quote.leafIds, + funding = listOf( + SparkExitRecord.Funding(index = pending.fundingIndex, address = key.address, pubkey = key.pubkey), + ), + expectedSats = quote.incomingSats, + skippedLeafCount = quote.prepared.skipped.size, + fundingStrategy = SparkExitRecord.PER_NODE, + leafTotalSats = quote.leafTotalSats, + ) + // Saved before the transfer exists, so a failed save never leaves a transfer counted with no exit behind. + store.save(record) + cacheStore.update { + val next = it.sparkExitNextFundingIndexes + (fundingIndexKey to pending.fundingIndex.toInt() + 1) + it.copy(sparkExitNextFundingIndexes = next) + } + // Spark stops paying and receiving in the same step the transfer counts its balance, before any wait. + sparkRepo.holdForExit() + val transferId = transferRepo.createTransfer(TransferType.SPARK_EXIT, quote.incomingSats.toLong()).getOrThrow() + record = record.copy(transferId = transferId) + store.save(record) + _state.update { it.copy(record = record, pending = null, fundingAddress = key.address) } + isLoaded = true + // Reconnecting for the exit disconnects Spark, which would cut a running leaf optimization short. + sparkRepo.awaitOptimizationIdle() + // An optimization since the quote swapped leaves: the exit is quoted again over the leaves Spark holds now. + requote(pending)?.let { fresh -> + quote = fresh + tickMutex.withLock { + val current = requireNotNull(_state.value.record) + transferRepo.markSettled(transferId) + val freshTransfer = transferRepo.createTransfer( + TransferType.SPARK_EXIT, + fresh.incomingSats.toLong(), + ).getOrThrow() + record = current.copy( + phase = SparkExitRecord.Phase.AwaitingFunding(fresh.fundingSats), + leafIds = fresh.leafIds, + expectedSats = fresh.incomingSats, + skippedLeafCount = fresh.prepared.skipped.size, + leafTotalSats = fresh.leafTotalSats, + transferId = freshTransfer, + ) + store.save(record) + _state.update { it.copy(record = record) } + } + } + sparkRepo.setExiting(true, reconnect = true) + work.schedulePeriodic() + Logger.info("Started Spark exit of '${quote.exitSats}' sats over '${quote.leafIds.size}' leaves", context = TAG) + // Driven before paying, so a failed payment from savings still leaves the exit watching its address. + scope.launch { tick() } + onAppForegrounded() + if (fundFromSavings && quote.fundingSats > 0uL) payFunding(key.address, quote.fundingSats) + } + + private suspend fun requote(pending: SparkExitPending): SparkExitQuote? { + val recovering = sparkService.exitRecovering() ?: return null + val lost = reportedLostLeafIds() + _state.value.record?.lostLeaves?.map { it.leafId }.orEmpty() + val request = quoteRequest(pending.feeRate, pending.destination) + val fresh = runSuspendCatching { recovering.prepareAll(request, lost) } + .onFailure { Logger.warn("Failed to quote the Spark exit again at its start", it, context = TAG) } + .getOrNull() + ?: return null + if (fresh.leafIds.toSet() == pending.quote.leafIds.toSet() || fresh.prepared.leaves.isEmpty()) return null + Logger.warn("Quoting the Spark exit again: its leaves changed since the quote", context = TAG) + return fresh.copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) + } + private suspend fun payFunding(address: String, sats: ULong) { val txid = sendFunding(address, sats) // After the tick in flight, so its save cannot drop the txid. @@ -592,7 +674,6 @@ class SparkExitRepo @Inject constructor( } } - /** Sends [sats] from savings to the funding address as an ordinary payment: a fee, not a transfer to spending. */ private suspend fun sendFunding(address: String, sats: ULong): String { val outcome = lightningRepo.sendOnChain( address = address, @@ -621,6 +702,7 @@ class SparkExitRepo @Inject constructor( return record.phase is SparkExitRecord.Phase.AwaitingFunding && record.recovery == null && record.fundedSats == 0uL && + record.fundingPaymentTxid == null && exit.fundingSeenSats == 0uL } @@ -637,16 +719,42 @@ class SparkExitRepo @Inject constructor( } } - suspend fun cancel(): Result = withContext(bgDispatcher) { + /** + * Stops an exit that nothing was paid into. The funding address is read again first: anything that reached it + * keeps the record, as an ended exit whose leftover sweep sends it to savings; an address that cannot be read + * refuses the cancel. Under the tick lock, so a tick in flight cannot save the record back. + */ + suspend fun cancel(): Result = withContext(bgDispatcher) { runSuspendCatching { - if (!canCancel) throw SparkExitError("The Spark exit can no longer be cancelled") - val record = requireNotNull(_state.value.record) - store.delete() - _state.update { it.copy(record = null) } - record.transferId?.let { transferRepo.markSettled(it) } - work.cancelAll() - sparkRepo.setExiting(false) - Logger.info("Cancelled the Spark exit before it was funded", context = TAG) + tickMutex.withLock { + if (!canCancel) throw SparkExitError("The Spark exit can no longer be cancelled") + val record = requireNotNull(_state.value.record) + val chain = requireNotNull(chain) { "No chain host for this network" } + val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } + val utxos = runSuspendCatching { chain.utxos(address) }.getOrElse { throw SparkExitCancelUnreadable() } + record.transferId?.let { transferRepo.markSettled(it) } + val outcome = if (utxos.isEmpty()) { + store.delete() + _state.update { it.copy(record = null) } + work.cancelAll() + SparkExitCancel.Cancelled + } else { + val leftover = utxos.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) } + val ended = record.copy( + phase = SparkExitRecord.Phase.Failed(CANCELLED_REASON), + leftover = leftover, + isResultSeen = true, + isCancelled = true, + ) + store.save(ended) + _state.update { it.copy(record = ended) } + work.schedulePeriodic() + SparkExitCancel.Sweeping + } + sparkRepo.setExiting(false) + Logger.info("Cancelled the Spark exit with outcome '$outcome'", context = TAG) + outcome + } } } @@ -656,13 +764,11 @@ class SparkExitRepo @Inject constructor( private val fundingIndexKey get() = "${Env.network.name.lowercase()}/wallet$walletIndex" - /** A funding key index no exit of this wallet used. */ private suspend fun nextFundingIndex(): UInt = SparkExitMath.nextFundingIndex( kept = cacheStore.data.first().sparkExitNextFundingIndexes[fundingIndexKey], stored = runSuspendCatching { store.load() }.getOrNull(), ) - /** Every funding UTXO of one exit goes to its index: the SDK's single-key signer signs all inputs with one key. */ private suspend fun fundingKey(index: UInt): SparkExitFundingKey.Derived { val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) @@ -679,6 +785,15 @@ class SparkExitRepo @Inject constructor( class SparkExitError(message: String) : AppError(message) +/** The funding address could not be read, so a cancel could not tell whether money reached it. */ +class SparkExitCancelUnreadable : AppError("Could not read the Spark exit funding address") + +/** The record's failed reason for an exit the user cancelled after funding reached its address. */ +const val CANCELLED_REASON = "Cancelled" + +/** What cancelling did: the exit is gone, or funding had reached its address and is being sent to savings. */ +enum class SparkExitCancel { Cancelled, Sweeping } + /** A quote the user is looking at, with what the exit is built from once it starts. */ data class SparkExitPending( val quote: SparkExitQuote, diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index cc5091fabb..112afbaf11 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -88,13 +88,15 @@ class SparkExitWork @Inject constructor( } /** The exit of the wallet Bitkit runs, read before the wallet graph exists. */ - private suspend fun store(): SparkExitStore { - val index = runSuspendCatching { db.configDao().getAll().first().firstOrNull()?.walletIndex } + private suspend fun store(): SparkExitStore = SparkExitStore(File(Env.sparkExitRecordPath(activeWalletIndex()))) + + /** The wallet Bitkit runs, read from its config before the wallet graph or Spark has started. */ + suspend fun activeWalletIndex(): Int = + runSuspendCatching { db.configDao().getAll().first().firstOrNull()?.walletIndex } .onFailure { Logger.warn("Failed to read the active wallet for the Spark exit", it, context = TAG) } .getOrNull() - ?: 0L - return SparkExitStore(File(Env.sparkExitRecordPath(index.toInt()))) - } + ?.toInt() + ?: 0 private val scope = appScope(bgDispatcher, TAG) private val preferences get() = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) @@ -114,7 +116,7 @@ class SparkExitWork @Inject constructor( */ fun ensureScheduled() { scope.launch { - val loaded = runCatching { store().load() } + val loaded = runSuspendCatching { store().load() } // A record that cannot be read is salvaged by the next run, which the alarm and the work stay set for. if (loaded.isFailure) { Logger.warn("Failed to read the Spark exit record; keeping its background work", context = TAG) @@ -188,7 +190,7 @@ class SparkExitWork @Inject constructor( * run now, and warns again later if it stays behind. */ suspend fun onDeadline() { - val loaded = runCatching { store().load() } + val loaded = runSuspendCatching { store().load() } if (loaded.isFailure) { Logger.warn("Failed to read the Spark exit record at its deadline; running it now", context = TAG) enqueueCatchUp() diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 9f7154edf1..765f4a8c44 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -224,8 +224,9 @@ class SparkRepo @Inject constructor( * Takes Spark off the Lightning rail while an emergency exit runs, so no payment moves leaves the exit is * spending, and connects Spark again so its leaf optimization follows: off while exiting, on once it ends. */ - suspend fun setExiting(isExiting: Boolean): Result = withContext(bgDispatcher) { - if (_state.value.isExiting == isExiting && sparkService.isConnected) return@withContext Result.success(Unit) + suspend fun setExiting(isExiting: Boolean, reconnect: Boolean = false): Result = withContext(bgDispatcher) { + val isCurrent = _state.value.isExiting == isExiting && sparkService.isConnected + if (isCurrent && !reconnect) return@withContext Result.success(Unit) _state.update { it.copy(isExiting = isExiting) } runSuspendCatching { onOptimizationCutShort() @@ -237,6 +238,12 @@ class SparkRepo @Inject constructor( } } + /** + * Holds Spark for an exit about to start: no sends, receives or spending balance, in the same step the exit's + * transfer starts counting it. [setExiting] reconnects it for the exit afterwards. + */ + fun holdForExit() = _state.update { it.copy(isExiting = true) } + /** Whether an exit quote has to wait first: a leaf optimization runs, or one ran or was cut short recently. */ suspend fun needsSettling(): Boolean = isOptimizing.value || cacheStore.data.first().sparkOptimizationActivityAt != null diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 4980638421..c439b77598 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -11,6 +11,9 @@ import androidx.compose.material3.pulltorefresh.PullToRefreshBox import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag @@ -20,6 +23,7 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import to.bitkit.R +import to.bitkit.repositories.CANCELLED_REASON import to.bitkit.repositories.SparkExitBackgroundLimits import to.bitkit.repositories.SparkExitFundingState import to.bitkit.repositories.SparkExitRecord @@ -30,6 +34,7 @@ import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.openNotificationSettings +import to.bitkit.ui.scaffold.AppAlertDialog import to.bitkit.ui.scaffold.AppTopBar import to.bitkit.ui.scaffold.ScreenColumn import to.bitkit.ui.shared.modifiers.clickableAlpha @@ -131,12 +136,26 @@ private fun Content( VerticalSpacer(16.dp) } if (uiState.canCancel) { + var isConfirming by remember { mutableStateOf(false) } SecondaryButton( text = stringResource(R.string.lightning__spark_exit__cancel), - onClick = onCancel, + onClick = { isConfirming = true }, testTag = "SparkExitCancel", ) VerticalSpacer(16.dp) + if (isConfirming) { + AppAlertDialog( + title = stringResource(R.string.lightning__spark_exit__cancel_title), + text = stringResource(R.string.lightning__spark_exit__cancel_text), + confirmText = stringResource(R.string.lightning__spark_exit__cancel), + onConfirm = { + isConfirming = false + onCancel() + }, + onDismiss = { isConfirming = false }, + confirmTestTag = "SparkExitCancelConfirm", + ) + } } PrimaryButton( text = stringResource(R.string.common__ok), @@ -349,6 +368,7 @@ private fun BackgroundNotes( private fun progressTitle(phase: SparkExitRecord.Phase?, funding: SparkExitFundingState?): String = stringResource( when (phase) { SparkExitRecord.Phase.Done -> R.string.lightning__spark_exit__done_title + SparkExitRecord.Phase.Failed(CANCELLED_REASON) -> R.string.lightning__spark_exit__cancelled_title is SparkExitRecord.Phase.Failed -> R.string.lightning__spark_exit__failed_title // A payment that covers it, such as a higher fee paid from savings, only waits to confirm. is SparkExitRecord.Phase.NeedsFunding if funding is SparkExitFundingState.Ask -> @@ -376,6 +396,8 @@ private fun progressText( stringResource(R.string.lightning__spark_exit__failed_leaves).replace("{amount}", sparkExitAmountText(it)) }, ).joinToString(" ") + SparkExitRecord.Phase.Failed(CANCELLED_REASON) -> + stringResource(R.string.lightning__spark_exit__cancelled_text) is SparkExitRecord.Phase.Failed -> sparkExitFailedText( nothingText = stringResource(R.string.lightning__spark_exit__failed_text), staysText = stringResource(R.string.lightning__spark_exit__failed_stays), diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index db11586f34..a16abfa1f2 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -1,10 +1,12 @@ package to.bitkit.ui.settings.lightning +import android.content.Context import androidx.compose.runtime.Stable import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import breez_sdk_spark.RecoveryTxKind import dagger.hilt.android.lifecycle.HiltViewModel +import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList @@ -18,9 +20,13 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import to.bitkit.R import to.bitkit.env.Env import to.bitkit.models.FeeRate +import to.bitkit.models.Toast import to.bitkit.repositories.SparkExitBackgroundLimits +import to.bitkit.repositories.SparkExitCancel +import to.bitkit.repositories.SparkExitCancelUnreadable import to.bitkit.repositories.SparkExitFeeBumpOption import to.bitkit.repositories.SparkExitFundingKey import to.bitkit.repositories.SparkExitFundingState @@ -40,6 +46,7 @@ import kotlin.time.Duration.Companion.seconds /** Drives the emergency exit screens, from the quote to the progress of a running exit. */ @HiltViewModel class SparkExitViewModel @Inject constructor( + @ApplicationContext private val context: Context, private val sparkExitRepo: SparkExitRepo, private val sparkRepo: SparkRepo, ) : ViewModel() { @@ -220,8 +227,15 @@ class SparkExitViewModel @Inject constructor( fun cancel() { viewModelScope.launch { sparkExitRepo.cancel() - .onSuccess { _effects.emit(SparkExitEffect.Cancelled) } - .onFailure { ToastEventBus.send(it) } + // Funding that reached the address keeps the exit on screen while it is sent back to savings. + .onSuccess { if (it == SparkExitCancel.Cancelled) _effects.emit(SparkExitEffect.Cancelled) } + .onFailure { + if (it !is SparkExitCancelUnreadable) return@onFailure ToastEventBus.send(it) + ToastEventBus.send( + Toast.ToastType.ERROR, + context.getString(R.string.lightning__spark_exit__cancel_failed) + ) + } } } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 2abe6f9f05..59445afbae 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -231,6 +231,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index c709392b6c..d166792033 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -238,6 +238,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 14eeb49f89..3b85b001cc 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -235,6 +235,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 337faaa06a..691e09325f 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -238,6 +238,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 939c69f60e..3de9867d63 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -115,6 +115,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 2f33551d41..3641c7db63 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -231,6 +231,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 1929c32581..cd4cf22e41 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -237,6 +237,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 9c302554e3..1799189c2c 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -179,6 +179,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index abfb127cc0..777fd2a96a 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -114,6 +114,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 41ec04cb02..d76a2ea495 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -236,6 +236,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index fc17992fd8..7f6f289996 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -235,6 +235,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 3fe430edef..296b03d8dd 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -116,6 +116,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 85d13dd384..0ad012fe22 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -239,6 +239,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 56866d0a11..d9cea4c7a5 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -111,6 +111,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 23425fd578..c32579f4a3 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -247,6 +247,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 33b01e8728..d1be4eb13c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -396,6 +396,11 @@ Amount to exit Emergency exit Cancel exit + Couldn\'t check the funding address. Try again. + Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. + Cancel exit? + You cancelled the exit. The fee funding that arrived goes back to savings. + Exit\n<accent>cancelled</accent> You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. Start\n<accent>exit?</accent> {amount} reached your savings. diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt index 41b20f53a2..d179c733d3 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -119,10 +119,8 @@ class SparkExitChainTest : BaseUnitTest() { ) assertIs(refused.broadcastHex("02s1")) assertEquals(2, requests.size) - assertFalse( - SparkExitBroadcastClassifier.isUnplaceable(SparkExitBroadcastOutcome.Rejected("min relay fee not met")) - ) - assertTrue(SparkExitBroadcastClassifier.isUnplaceable(SparkExitBroadcastClassifier.classify(bareRefusal))) + assertFalse(SparkExitBroadcastClassifier.isUnplaceable("min relay fee not met")) + assertTrue(SparkExitBroadcastClassifier.isUnplaceable(bareRefusal)) } @Test @@ -218,6 +216,23 @@ class SparkExitChainTest : BaseUnitTest() { assertEquals(EsploraTxStatus(false, null), sut.txStatus("t")) } + @Test + fun `a refusal keeps only a short reason, never a host's page`() { + val classifier = SparkExitBroadcastClassifier + assertEquals( + SparkExitBroadcastOutcome.Rejected("min relay fee not met, 0 < 17"), + classifier.single( + 400, + """{"error":"sendrawtransaction RPC error: """ + + """{\"code\":-26,\"message\":\"min relay fee not met, 0 < 17\"}"}""" + ), + ) + val page = "

502 Bad Gateway

" + "x".repeat(500) + "" + val reason = (classifier.single(400, page) as SparkExitBroadcastOutcome.Rejected).reason + assertFalse("<" in reason) + assertTrue(reason.length <= 200) + } + @Test fun `classifies node answers`() { val failedPackage = """{"package_msg":"transaction failed","tx-results":""" @@ -227,7 +242,7 @@ class SparkExitChainTest : BaseUnitTest() { classifier.single(400, """sendrawtransaction RPC error: {"code":-27}"""), ) assertEquals( - SparkExitBroadcastOutcome.InputsMissing("""sendrawtransaction RPC error: {"code":-25}"""), + SparkExitBroadcastOutcome.InputsMissing("RPC error -25"), classifier.single(400, """sendrawtransaction RPC error: {"code":-25}"""), ) assertEquals(SparkExitBroadcastOutcome.RetryLater("HTTP 503"), classifier.single(503, "")) @@ -248,7 +263,7 @@ class SparkExitChainTest : BaseUnitTest() { """"w2":{"txid":"b","error":"min relay fee not met"}}}""" assertIs(classifier.pkg(200, nonFinalParent)) val escaped = """{"error":"submitpackage RPC error: {\"code\":-25}"}""" - assertEquals(SparkExitBroadcastOutcome.InputsMissing(escaped), classifier.pkg(400, escaped)) + assertEquals(SparkExitBroadcastOutcome.InputsMissing("RPC error -25"), classifier.pkg(400, escaped)) // Missing inputs on the CPFP child alone say nothing about the step. val childMissing = failedPackage + """{"w1":{"txid":"parent"},""" + """"w2":{"txid":"child","error":"bad-txns-inputs-missingorspent"}}}""" diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 1025c16f83..ea59374c83 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -547,14 +547,16 @@ class SparkExitDriverTest : BaseUnitTest() { @Test fun `a leftover worth less than its fees waits for cheaper fees, then is kept as dust after four weeks`() = test { - chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0", 1u, 400uL)) + chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0", 1u, 1_000uL)) + chain.economyRate = 9uL val done = SparkExitFixtures.record(Phase.Done).copy( destination = SWEEP_DESTINATION, funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), - leftover = listOf(SparkExitRecord.Leftover("f0", 1u, 400uL)), + leftover = listOf(SparkExitRecord.Leftover("f0", 1u, 1_000uL)), + feeRateSatPerVbyte = 9uL, ) - // At 1 sat/vB the sweep's fee leaves less than dust: it waits, and the exit is still driven. + // At 9 sat/vB the sweep's fee leaves less than dust: it waits, and the exit is still driven. var record = driver(tip = 1_000u).tick(done) assertTrue(record.isLeftoverWaitingForFees) assertTrue(record.needsDriving) @@ -564,7 +566,7 @@ class SparkExitDriverTest : BaseUnitTest() { chain.utxosByAddress[SWEEP_FUNDING] = emptyList() record = driver(tip = 1_143u).tick(record) assertTrue(record.isLeftoverWaitingForFees) - chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0", 1u, 400uL)) + chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0", 1u, 1_000uL)) record = driver(tip = 1_144u).tick(record) assertEquals(1_144u, assertNotNull(record.leftoverSweep).checkedAtHeight) assertEquals(1_000u, assertNotNull(record.leftoverSweep).waitingSince) @@ -577,6 +579,70 @@ class SparkExitDriverTest : BaseUnitTest() { assertFalse(record.needsDriving) } + @Test + fun `a leftover not even the lowest rate can send is kept as dust at once`() = test { + chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0", 1u, 400uL)) + val done = SparkExitFixtures.record(Phase.Done).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + leftover = listOf(SparkExitRecord.Leftover("f0", 1u, 400uL)), + ) + + val record = driver(tip = 1_000u).tick(done) + + assertTrue(assertNotNull(record.leftoverSweep).isDustKept) + assertFalse(record.needsDriving) + } + + @Test + fun `a leftover sweep whose inputs went elsewhere reads the address again`() = test { + var record = driver(tip = 1_000u).tick(sweepDone()) + assertNotNull(assertNotNull(record.leftoverSweep).txHex) + chain.outcome = SparkExitBroadcastOutcome.InputsMissing("missing-inputs") + record = driver(tip = 1_001u).tick(record) + assertNull(record.leftoverSweep) + + chain.utxosByAddress[SWEEP_FUNDING] = emptyList() + record = driver(tip = 1_002u).tick(record) + assertTrue(record.leftover.isEmpty()) + assertFalse(record.needsDriving) + } + + @Test + fun `a higher fee waiting on its payment still sends the steps due and checks with the sdk`() = test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + val bumped = running(recovery).copy( + funding = listOf( + SparkExitFixtures.record().funding.single().copy(txid = "f0", vout = 0u, valueSats = 20_000uL) + ), + ).applyFeeBump(rate = 9uL, extraSats = 6_000uL, paymentTxid = "bump") + sdk.checks += check(recovery, RecoveryVerdict.Valid) + + var record = driver(tip = 1_001u).tick(bumped) + + assertEquals(listOf("n1"), chain.broadcasts.map { it.txid }) + assertIs(record.phase) + assertTrue(record.isAwaitingOwnPayment) + assertEquals(1_001u, record.fundingPaymentSeenAtHeight) + // No host knows the payment for a block: the exit forgets it and asks again. + chain.unknownTxids = setOf("bump") + sdk.checks += check(recovery, RecoveryVerdict.Valid) + record = driver(tip = 1_002u).tick(record) + assertEquals(1_002u, record.fundingPaymentMissingSince) + sdk.checks += check(recovery, RecoveryVerdict.Valid) + record = driver(tip = 1_003u).tick(record) + assertFalse(record.isAwaitingOwnPayment) + assertNull(record.fundingPaymentTxid) + } + + @Test + fun `a payment from savings never adopted is forgotten 144 blocks after the first look`() { + val waiting = SparkExitFixtures.record(Phase.NeedsFunding(30_000uL)).copy(fundingPaymentTxid = "bump") + val looked = waiting.withOwnPaymentLooked(1_000u, isKnown = true) + assertTrue(looked.withOwnPaymentLooked(1_143u, isKnown = true).isAwaitingOwnPayment) + assertFalse(looked.withOwnPaymentLooked(1_144u, isKnown = true).isAwaitingOwnPayment) + } + @Test fun `a waiting leftover is swept once fees drop`() = test { chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0".repeat(32), 1u, 25_000uL)) @@ -798,7 +864,8 @@ class SparkExitDriverTest : BaseUnitTest() { listOf("f0", "bump"), sdk.recoverRequests.single().fundingInputs.map { (it as CpfpInput.P2wpkh).txid } ) - assertEquals(listOf("n1b"), chain.broadcasts.map { it.txid }) + // The generation out there kept going while the payment confirmed. + assertEquals(listOf("n1", "n1b"), chain.broadcasts.map { it.txid }) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt index bdb4932873..2c9b64f479 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -318,7 +318,8 @@ class SparkExitRecordTest { assertTrue(store.isActive()) assertEquals("{", store.loadText()) store.setAside(42L) - assertFalse(file.exists()) + // Copied aside: the salvaged record replaces the original in one atomic write. + assertTrue(file.exists()) assertTrue(File(file.parentFile, "spark-exit.unreadable-42.json").exists()) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index b48772b5b7..624885a115 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1,9 +1,11 @@ package to.bitkit.repositories import breez_sdk_spark.CheckRecoverFundsResponse +import breez_sdk_spark.CpfpFundingStrategy import breez_sdk_spark.RecoveryRedoReason import breez_sdk_spark.RecoveryVerdict import breez_sdk_spark.SdkException +import com.synonym.bitkitcore.GetAddressResponse import io.ktor.client.HttpClient import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.respond @@ -14,9 +16,13 @@ import io.ktor.http.HttpMethod import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import io.ktor.utils.io.errors.IOException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOf +import kotlinx.coroutines.test.advanceUntilIdle import org.junit.Before import org.junit.Rule import org.junit.Test @@ -26,7 +32,9 @@ import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn +import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.eq +import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.times @@ -37,6 +45,7 @@ import to.bitkit.data.CacheStore import to.bitkit.data.entities.TransferEntity import to.bitkit.data.keychain.Keychain import to.bitkit.env.Env +import to.bitkit.models.FeeRate import to.bitkit.models.TransferType import to.bitkit.repositories.SparkExitRecord.Phase import to.bitkit.services.CoreService @@ -45,8 +54,10 @@ import to.bitkit.services.SparkService import to.bitkit.test.BaseUnitTest import java.io.File import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotNull +import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock import kotlin.time.Instant @@ -66,6 +77,7 @@ class SparkExitRepoTest : BaseUnitTest() { @Before fun setUp() { Env.initAppStoragePath(tempFolder.root.absolutePath) + whenever { work.activeWalletIndex() }.thenReturn(0) } private fun createSut( @@ -73,12 +85,13 @@ class SparkExitRepoTest : BaseUnitTest() { httpClient: HttpClient = mock(), keychain: Keychain = mock(), coreService: CoreService = mock(), + lightningRepo: LightningRepo = mock(), ) = SparkExitRepo( work = work, bgDispatcher = testDispatcher, sparkService = sparkService, sparkRepo = sparkRepo, - lightningRepo = mock(), + lightningRepo = lightningRepo, transferRepo = transferRepo, activityRepo = mock(), coreService = coreService, @@ -406,4 +419,239 @@ class SparkExitRepoTest : BaseUnitTest() { onchain ).deriveBitcoinAddress(any(), eq(SparkExitFundingKey.path(2, Env.network)), anyOrNull(), anyOrNull()) } + + private val lightning = mock() + + private val funding = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + + /** A compressed regtest WIF of a 32-byte secret of 0x01s. */ + private val wif = "cMceqPhHedrhbcR9eXgzmfWy7kRqLyAxMYwFT6ABDWsiwUp9Nsq9" + + private suspend fun keyed(): Pair { + val keychain = mock { on { loadString(any()) } doReturn "mnemonic" } + val onchain = mock() + whenever(onchain.deriveBitcoinAddress(any(), anyOrNull(), anyOrNull(), anyOrNull())) + .thenReturn(GetAddressResponse(funding, "m/84'/1'/7797'/0/0", "02ab")) + whenever(onchain.derivePrivateKey(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn(wif) + return keychain to mock { on { this.onchain } doReturn onchain } + } + + private suspend fun connectedSpark(sdk: FakeSparkExitRecovering) = mock { + on { networkName } doReturn "regtest" + on { isConnected } doReturn true + on { exitRecovering() } doReturn sdk + }.also { + whenever(it.fastestFeeRate()).thenReturn(9uL) + whenever(it.halfHourFeeRate()).thenReturn(6uL) + } + + private fun fundingChain(utxos: String? = "[]") = HttpClient( + MockEngine { request -> + val url = request.url.toString() + when { + url.endsWith("/address/$funding/utxo") && utxos != null -> respond(utxos) + url.endsWith("/blocks/tip/height") -> respond("1000") + url.endsWith("/fee-estimates") -> respond("""{"1":9,"3":6,"144":1}""") + else -> throw IOException("unreachable '$url'") + } + }, + ) { defaultRequest { contentType(ContentType.Application.Json) } } + + private suspend fun quotedSut(sdk: FakeSparkExitRecovering, http: HttpClient = fundingChain()): SparkExitRepo { + whenever(sparkRepo.needsSettling()).thenReturn(false) + whenever(sparkRepo.settleForExit()).thenReturn(Result.success(Unit)) + whenever(lightning.newAddress()).thenReturn(Result.success("bcrt1qdestination")) + whenever( + transferRepo.createTransfer( + any(), + any(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull() + ) + ) + .thenReturn(Result.success("transfer-1"), Result.success("transfer-2")) + whenever(transferRepo.markSettled(any())).thenReturn(Result.success(Unit)) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(emptyList())) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) + val (keychain, core) = keyed() + return createSut(connectedSpark(sdk), http, keychain, core, lightning) + } + + @Test + fun `a quote prepares every leaf per node at the fastest rate to a fresh savings address`() = test { + val sdk = FakeSparkExitRecovering() + val sut = quotedSut(sdk) + + val quote = sut.loadQuote().getOrThrow() + + assertEquals(listOf("leaf-1"), quote.leafIds) + val request = sdk.prepareRequests.single() + assertEquals(CpfpFundingStrategy.PER_NODE, request.fundingStrategy) + assertEquals(9uL, request.feeRateSatPerVbyte) + assertEquals("bcrt1qdestination", request.destination) + assertEquals(funding, sut.state.value.fundingAddress) + } + + @Test + fun `starting holds spark with the transfer, then reconnects it, and a second start is refused`() = test { + val sdk = FakeSparkExitRecovering() + val sut = quotedSut(sdk) + sut.loadQuote().getOrThrow() + + sut.start(fundFromSavings = false).getOrThrow() + + val order = inOrder(sparkRepo, transferRepo) + order.verify(sparkRepo).holdForExit() + order.verify( + transferRepo + ).createTransfer(any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) + order.verify(sparkRepo).awaitOptimizationIdle() + order.verify(sparkRepo).setExiting(true, true) + val record = assertNotNull(sut.state.value.record) + assertEquals(SparkExitRecord.PER_NODE, record.fundingStrategy) + assertEquals("transfer-1", record.transferId) + assertIs(record.phase) + assertTrue(sut.start(fundFromSavings = false).isFailure) + sut.onAppBackgrounded() + } + + @Test + fun `a leaf swap between the quote and the start quotes the exit again`() = test { + val sdk = FakeSparkExitRecovering() + val sut = quotedSut(sdk) + sut.loadQuote().getOrThrow() + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-2")) + + sut.start(fundFromSavings = false).getOrThrow() + + val record = assertNotNull(sut.state.value.record) + assertEquals(listOf("leaf-2"), record.leafIds) + assertEquals("transfer-2", record.transferId) + verify(transferRepo).markSettled("transfer-1") + sut.onAppBackgrounded() + } + + private fun awaitingRecord(paidTxid: String? = null) = SparkExitFixtures.record().copy( + funding = listOf(SparkExitRecord.Funding(0u, funding, "02ab")), + fundingPaymentTxid = paidTxid, + ) + + @Test + fun `cancel forgets an exit nothing reached, and never one savings paid`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord(paidTxid = "paid")) + val paid = quotedSut(FakeSparkExitRecovering()) + paid.load().getOrThrow() + assertFalse(paid.canCancel) + assertTrue(paid.cancel().isFailure) + assertNotNull(store.load()) + + store.save(awaitingRecord()) + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + assertTrue(sut.canCancel) + assertEquals(SparkExitCancel.Cancelled, sut.cancel().getOrThrow()) + assertNull(store.load()) + verify(sparkRepo).setExiting(false, false) + } + + @Test + fun `cancel keeps funding that reached the address and sends it back to savings`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord()) + val utxo = """[{"txid":"${"f0".repeat(32)}","vout":0,"value":5000,"status":{"confirmed":false}}]""" + val sut = quotedSut(FakeSparkExitRecovering(), fundingChain(utxo)) + sut.load().getOrThrow() + + assertEquals(SparkExitCancel.Sweeping, sut.cancel().getOrThrow()) + + val record = assertNotNull(store.load()) + assertTrue(record.isCancelled) + assertEquals(Phase.Failed(CANCELLED_REASON), record.phase) + assertEquals(5_000uL, record.leftover.single().valueSats) + assertTrue(record.needsDriving) + } + + @Test + fun `cancel refuses while the funding address cannot be read`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord()) + val sut = quotedSut(FakeSparkExitRecovering(), fundingChain(utxos = null)) + sut.load().getOrThrow() + + assertIs(sut.cancel().exceptionOrNull()) + assertNotNull(store.load()) + } + + private suspend fun stubFunding(answer: suspend () -> Result) { + whenever { + lightning.sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + }.doSuspendableAnswer { answer() } + whenever(lightning.completeAcceptedOrdinaryFollowup(any())).thenReturn(Unit) + } + + private fun runningRecord() = SparkExitFixtures.record(Phase.Running) + .copy(funding = listOf(SparkExitRecord.Funding(0u, funding, "02ab", "f0", 0u, 20_000uL))) + .adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))), 0L) + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a higher fee pays once, even when tapped twice, and never for an ended exit`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(runningRecord()) + val gate = CompletableDeferred() + stubFunding { + gate.await() + Result.success(OnchainSendOutcome.Accepted("bump")) + } + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + val option = SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 6_000uL, 6_400uL) + + val first = async { sut.payHigherFee(option) } + advanceUntilIdle() + assertTrue(sut.payHigherFee(option).isFailure) + gate.complete(Unit) + first.await().getOrThrow() + // The tick the payment starts runs before the record is changed under it. + advanceUntilIdle() + + val record = assertNotNull(store.load()) + assertEquals("bump", record.fundingPaymentTxid) + assertEquals(9uL, record.feeRateSatPerVbyte) + assertTrue(record.isDrivingWhileFunding) + + store.save(runningRecord().copy(phase = Phase.Done)) + val ended = quotedSut(FakeSparkExitRecovering()) + ended.load().getOrThrow() + assertTrue(ended.payHigherFee(option).isFailure) + } + + @Test + fun `fee bump rates are priced without broadcasting, leaving out a rate the sdk refuses a leaf at`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(runningRecord()) + val sdk = FakeSparkExitRecovering().apply { + preparedResponse = SparkExitFixtures.prepared(funding = null) + prepareErrors += SdkException.SparkException("Leaf leaf-1 cannot be exited: its refund cannot pay its fee") + } + val sut = quotedSut(sdk) + sut.load().getOrThrow() + + val options = sut.feeBumpOptions().getOrThrow() + + assertEquals(listOf(FeeRate.NORMAL to 6uL), options.map { it.speed to it.rateSatPerVbyte }) + assertEquals(0uL, options.single().totalSats) + assertTrue(sdk.recoverRequests.isEmpty()) + } } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 1ba830a3c2..0da74c1de2 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -1,5 +1,6 @@ package to.bitkit.ui.settings.lightning +import android.content.Context import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.flow.MutableStateFlow import org.junit.Test @@ -33,7 +34,7 @@ class SparkExitViewModelTest : BaseUnitTest() { @Test fun `entering the funding step again offers both choices while nothing was paid`() = test { whenever(repo.refreshFundingAddress()).thenReturn(Result.success(0uL)) - val sut = SparkExitViewModel(repo, sparkRepo) + val sut = SparkExitViewModel(mock(), repo, sparkRepo) sut.onFundExternally() sut.stopWatchingFundingAddress() @@ -46,7 +47,7 @@ class SparkExitViewModelTest : BaseUnitTest() { @Test fun `entering the funding step keeps the address once a payment reached it`() = test { whenever(repo.refreshFundingAddress()).thenReturn(Result.success(5_000uL)) - val sut = SparkExitViewModel(repo, sparkRepo) + val sut = SparkExitViewModel(mock(), repo, sparkRepo) sut.onFundingShown() @@ -134,7 +135,7 @@ class SparkExitViewModelTest : BaseUnitTest() { lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 32_768uL)), ) exitState.value = SparkExitState(record = stopped) - val sut = SparkExitViewModel(repo, sparkRepo) + val sut = SparkExitViewModel(mock(), repo, sparkRepo) sparkState.value = SparkState(balanceSats = 34_464uL) From b0affb23a6f749986f3f2ab2dbfa54441447496c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 00:50:20 +0100 Subject: [PATCH 027/154] fix: remind about an unfunded spark exit --- .../to/bitkit/repositories/SparkExitRepo.kt | 13 ++++ .../to/bitkit/repositories/SparkExitWorker.kt | 68 +++++++++++++++++++ .../repositories/SparkExitAlertsTest.kt | 20 ++++++ .../bitkit/repositories/SparkExitRepoTest.kt | 23 +++++-- 4 files changed, 117 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 4ecd48182e..e0811b1224 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -336,6 +336,19 @@ class SparkExitRepo @Inject constructor( isOnTrack: Boolean, reportedLost: Set, ) { + // A started exit nothing reached yet is reminded about once, 4 hours in; funds seen or paid, or another phase, + // call the reminder off. + val remindIn = SparkExitAlerts.fundingReminderIn( + record, + _state.value.fundingSeenSats, + clock.nowMs(), + Env.network + ) + if (remindIn != null) { + work.scheduleFundingReminder(record.createdAt, remindIn) + } else { + work.cancelFundingReminder(record.createdAt) + } SparkExitAlerts.losses(record, previous, reportedLost).forEach { work.notify(it, amountSats = record.lostSats.takeIf { _ -> it == SparkExitAlert.Lost }) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index 112afbaf11..4e16096d22 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -19,6 +19,7 @@ import androidx.work.OneTimeWorkRequestBuilder import androidx.work.PeriodicWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters +import androidx.work.workDataOf import dagger.assisted.Assisted import dagger.assisted.AssistedInject import dagger.hilt.EntryPoint @@ -29,6 +30,7 @@ import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch +import org.lightningdevkit.ldknode.Network import to.bitkit.App import to.bitkit.R import to.bitkit.async.appScope @@ -54,6 +56,8 @@ import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Clock import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes /** @@ -76,6 +80,8 @@ class SparkExitWork @Inject constructor( private const val TAG = "SparkExitWork" private const val PERIODIC_WORK = "spark-exit-tick" private const val CATCH_UP_WORK = "spark-exit-catch-up" + private const val FUNDING_REMINDER_WORK = "spark-exit-funding-reminder" + const val KEY_EXIT_CREATED_AT = "exit-created-at" const val DEADLINE_ACTION = "to.bitkit.spark-exit.DEADLINE" private const val PREFERENCES = "spark-exit-work" private const val KEY_WARN_AT = "warn-at" @@ -181,10 +187,38 @@ class SparkExitWork @Inject constructor( WorkManager.getInstance(context).run { cancelUniqueWork(PERIODIC_WORK) cancelUniqueWork(CATCH_UP_WORK) + cancelAllWorkByTag(FUNDING_REMINDER_WORK) } cancelDeadline() } + /** + * Reminds once, after [delay], that the exit created at [exitCreatedAt] waits for its fee funding. Unique per + * exit and kept as first scheduled, so later ticks do not push it back. + */ + fun scheduleFundingReminder(exitCreatedAt: Long, delay: Duration) { + val request = OneTimeWorkRequestBuilder() + .setInitialDelay(delay.inWholeMilliseconds, TimeUnit.MILLISECONDS) + .setInputData(workDataOf(KEY_EXIT_CREATED_AT to exitCreatedAt)) + .addTag(FUNDING_REMINDER_WORK) + .build() + WorkManager.getInstance(context) + .enqueueUniqueWork(fundingReminderName(exitCreatedAt), ExistingWorkPolicy.KEEP, request) + } + + fun cancelFundingReminder(exitCreatedAt: Long) { + WorkManager.getInstance(context).cancelUniqueWork(fundingReminderName(exitCreatedAt)) + } + + private fun fundingReminderName(exitCreatedAt: Long) = "$FUNDING_REMINDER_WORK-$exitCreatedAt" + + /** The reminder fired: posts the funding notification while the exit it was for still waits for funding. */ + suspend fun onFundingReminder(exitCreatedAt: Long) { + val record = runSuspendCatching { store().load() }.getOrNull() ?: return + if (record.createdAt != exitCreatedAt || !SparkExitAlerts.isAwaitingFirstFunding(record)) return + notify(SparkExitAlert.Funding) + } + /** * The deadline alarm fired, so no run moved the exit forward in time: tells the user why and until when, tries a * run now, and warns again later if it stays behind. @@ -328,6 +362,26 @@ object SparkExitAlerts { ) } + /** How long after its start an unfunded exit is reminded about: 4 hours, 10 minutes on regtest, as on iOS. */ + private val fundingReminderDelay = 4.hours + private val regtestFundingReminderDelay = 10.minutes + + /** A started exit nothing was paid into: no adopted funding, no payment from savings. */ + fun isAwaitingFirstFunding(record: SparkExitRecord): Boolean = + record.phase is SparkExitRecord.Phase.AwaitingFunding && record.fundingShortfallSats != null && + record.fundedSats == 0uL && record.fundingPaymentTxid == null + + /** + * How long from [nowMillis] until the one reminder about [record] waiting for its first funding, or null when no + * reminder is due: funding was paid or [seenSats] reached the address, or the exit is past that phase. + */ + fun fundingReminderIn(record: SparkExitRecord, seenSats: ULong, nowMillis: Long, network: Network): Duration? { + if (!isAwaitingFirstFunding(record) || seenSats > 0uL) return null + val delay = if (network == Network.REGTEST) regtestFundingReminderDelay else fundingReminderDelay + val at = record.createdAt + delay.inWholeMilliseconds + return maxOf(at - nowMillis, 0L).milliseconds + } + /** [record] started saying it is not moving on the tick from [previous]. */ fun isNewlyStalled(record: SparkExitRecord, previous: SparkExitRecord): Boolean = record.isActive && record.isStalled && !previous.isStalled @@ -372,6 +426,20 @@ private fun SparkExitAlert.textRes(hasDeadline: Boolean): Int = when (this) { else -> R.string.lightning__spark_exit__notification_late } +/** The one reminder that a started exit still waits for its fee funding. */ +@HiltWorker +class SparkExitFundingReminderWorker @AssistedInject constructor( + @Assisted appContext: Context, + @Assisted workerParams: WorkerParameters, + private val work: SparkExitWork, +) : CoroutineWorker(appContext, workerParams) { + override suspend fun doWork(): Result { + val createdAt = inputData.getLong(SparkExitWork.KEY_EXIT_CREATED_AT, 0L) + work.onFundingReminder(createdAt) + return Result.success() + } +} + @HiltWorker class SparkExitWorker @AssistedInject constructor( @Assisted appContext: Context, diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt index e2375749f9..c963b111ef 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt @@ -1,11 +1,15 @@ package to.bitkit.repositories import org.junit.Test +import org.lightningdevkit.ldknode.Network import to.bitkit.repositories.SparkExitRecord.Phase import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlin.time.Duration +import kotlin.time.Duration.Companion.hours +import kotlin.time.Duration.Companion.minutes class SparkExitAlertsTest { private val running = SparkExitFixtures.record(Phase.Running) @@ -111,4 +115,20 @@ class SparkExitAlertsTest { assertTrue(SparkExitAlert.Lost.isPostedOnScreen) assertFalse(SparkExitAlert.Rejected.isPostedOnScreen) } + + @Test + fun `an exit nothing was paid into is reminded about once, 4 hours after it started`() { + val unfunded = SparkExitFixtures.record(Phase.AwaitingFunding(20_000uL)).copy(createdAt = 0L) + val hour = 3_600_000L + assertEquals(4.hours, SparkExitAlerts.fundingReminderIn(unfunded, 0uL, 0L, Network.BITCOIN)) + assertEquals(1.hours, SparkExitAlerts.fundingReminderIn(unfunded, 0uL, 3 * hour, Network.BITCOIN)) + assertEquals(Duration.ZERO, SparkExitAlerts.fundingReminderIn(unfunded, 0uL, 5 * hour, Network.BITCOIN)) + assertEquals(10.minutes, SparkExitAlerts.fundingReminderIn(unfunded, 0uL, 0L, Network.REGTEST)) + // Funds seen or paid, or another phase: no reminder. + assertNull(SparkExitAlerts.fundingReminderIn(unfunded, 5_000uL, 0L, Network.BITCOIN)) + assertNull( + SparkExitAlerts.fundingReminderIn(unfunded.copy(fundingPaymentTxid = "paid"), 0uL, 0L, Network.BITCOIN) + ) + assertNull(SparkExitAlerts.fundingReminderIn(unfunded.copy(phase = Phase.Running), 0uL, 0L, Network.BITCOIN)) + } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 624885a115..8c80d74be1 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -23,6 +23,7 @@ import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent import org.junit.Before import org.junit.Rule import org.junit.Test @@ -445,14 +446,18 @@ class SparkExitRepoTest : BaseUnitTest() { whenever(it.halfHourFeeRate()).thenReturn(6uL) } + // On the test's own dispatcher, so no tick a start or payment launches runs on after the test. private fun fundingChain(utxos: String? = "[]") = HttpClient( - MockEngine { request -> - val url = request.url.toString() - when { - url.endsWith("/address/$funding/utxo") && utxos != null -> respond(utxos) - url.endsWith("/blocks/tip/height") -> respond("1000") - url.endsWith("/fee-estimates") -> respond("""{"1":9,"3":6,"144":1}""") - else -> throw IOException("unreachable '$url'") + MockEngine.create { + dispatcher = testDispatcher + addHandler { request -> + val url = request.url.toString() + when { + url.endsWith("/address/$funding/utxo") && utxos != null -> respond(utxos) + url.endsWith("/blocks/tip/height") -> respond("1000") + url.endsWith("/fee-estimates") -> respond("""{"1":9,"3":6,"144":1}""") + else -> throw IOException("unreachable '$url'") + } } }, ) { defaultRequest { contentType(ContentType.Application.Json) } } @@ -497,6 +502,7 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(funding, sut.state.value.fundingAddress) } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `starting holds spark with the transfer, then reconnects it, and a second start is refused`() = test { val sdk = FakeSparkExitRecovering() @@ -517,6 +523,9 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals("transfer-1", record.transferId) assertIs(record.phase) assertTrue(sut.start(fundFromSavings = false).isFailure) + // Nothing paid in yet: the one reminder is scheduled for 4 hours (10 minutes on regtest) after the start. + runCurrent() + verify(work, atLeastOnce()).scheduleFundingReminder(eq(record.createdAt), any()) sut.onAppBackgrounded() } From 9ec930731cc5b8b7b30c4934b7daec7e6356a34f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 01:20:26 +0100 Subject: [PATCH 028/154] fix: spark exit bot review findings --- .../to/bitkit/repositories/SparkExitDriver.kt | 122 +++++++++++---- .../to/bitkit/repositories/SparkExitRecord.kt | 29 ++++ .../to/bitkit/repositories/SparkExitRepo.kt | 40 ++++- .../lightning/SparkExitProgressScreen.kt | 11 ++ .../repositories/SparkExitDriverTest.kt | 91 +++++++++-- .../bitkit/repositories/SparkExitFixtures.kt | 4 + .../bitkit/repositories/SparkExitRepoTest.kt | 147 +++++++++++++++--- 7 files changed, 379 insertions(+), 65 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 84d3080304..5eb93de8d4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -238,7 +238,14 @@ class SparkExitDriver( return record.copy(phase = SparkExitRecord.Phase.NeedsFunding(needed)) } if (built.transactions.isEmpty()) { - // Cooperative leaves the operators could not co-sign now are tried again on the next tick. + // A first build of only cooperative leaves the operators could not co-sign is kept: they are retried for a + // week like any failed leaf. A rebuild like it keeps the recovery it has and tries again on the next tick. + if (built.failed.isNotEmpty() && record.recovery == null) { + val adopted = record.adopt(built, nowMillis()) + save(adopted) + Logger.info("Built Spark exit of only '${built.failed.size}' failed cooperative leaves", context = TAG) + return adopted + } if (built.failed.isNotEmpty()) return record.copy(failedLeafCount = built.failed.size) return end(record.copy(phase = SparkExitRecord.Phase.Failed("Nothing to recover")), record) } @@ -379,6 +386,10 @@ class SparkExitDriver( private suspend fun check(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { val stored = record.recovery ?: return record.copy(phase = SparkExitRecord.Phase.AwaitingFunding(0uL)) + // Nothing to check or send: only the failed cooperative leaves are left, and their retry decides the end. + if (stored.transactions.isEmpty() && stored.failed.isNotEmpty()) { + return retryFailedLeaves(record, stored.failed.map { it.leafId }, sdk) + } // An SDK that cannot check this tick still leaves the stored, signed steps to send. val checked = runSuspendCatching { sdk.check(withConfirmations(stored)) } .onFailure { Logger.warn("Failed to check the Spark exit, sending without the SDK", it, context = TAG) } @@ -435,24 +446,35 @@ class SparkExitDriver( /** * What the exit's funding address must still receive to rebuild at [rate]: a build of the exit's leaves with the - * funding it holds, nothing broadcast. Zero when that funding covers it; otherwise the SDK's shortfall less what - * the address still holds, with one more input's fee for the payment, at least dust. + * funding it holds, nothing broadcast. Priced on a copy: a leaf the SDK refuses is left behind on the copy and + * the rest priced again, as a rebuild would, so the live exit's leaves never change. Zero when that funding covers + * it; otherwise the SDK's shortfall less what the address still holds, with one more input's fee for the payment, + * at least dust. */ suspend fun feeBumpShortfall(record: SparkExitRecord, rate: ULong): ULong { val sdk = checkNotNull(recovering) { "Spark is not connected" } - val atRate = withExitState(record, sdk).copy(feeRateSatPerVbyte = rate) - val prepared = sdk.prepare(prepareRequest(atRate, ExitLeafSelection.Specific(atRate.exitLeafIds))) - if (prepared.funding == null) return 0uL - val built = - runSuspendCatching { sdk.recover(RecoverFundsRequest(prepared, atRate.fundingInputs), makeSigner()) } - val error = built.exceptionOrNull() ?: return 0uL - val required = (error as? SdkException.InsufficientCpfpFunds ?: throw error).requiredSats - val held = atRate.funding.firstOrNull()?.address?.let { address -> - runSuspendCatching { chain.utxos(address) }.getOrNull()?.let { SparkExitMath.heldSats(it, atRate) } + var atRate = withExitState(record, sdk).copy(feeRateSatPerVbyte = rate) + while (true) { + val (priced, prepared) = prepare(atRate, sdk) + atRate = priced + if (prepared == null || prepared.funding == null) return 0uL + val built = + runSuspendCatching { sdk.recover(RecoverFundsRequest(prepared, atRate.fundingInputs), makeSigner()) } + val error = built.exceptionOrNull() ?: return 0uL + val refusal = SparkExitUnexitable.parse(error)?.takeIf { it.leafId in atRate.exitLeafIds } + if (refusal != null) { + atRate = atRate.leaveBehind(refusal.leafId, refusal.reason) + continue + } + val required = (error as? SdkException.InsufficientCpfpFunds ?: throw error).requiredSats + val held = atRate.funding.firstOrNull()?.address?.let { address -> + runSuspendCatching { chain.utxos(address) }.getOrNull()?.let { SparkExitMath.heldSats(it, atRate) } + } + val needed = + SparkExitMath.neededFunding(required, atRate.fundedSats, held, SparkExitMath.inputFeeSats(rate)) + val extra = if (needed > atRate.fundedSats) needed - atRate.fundedSats else 0uL + return maxOf(extra, SparkExitMath.FUNDING_DUST_SATS) } - val needed = SparkExitMath.neededFunding(required, atRate.fundedSats, held, SparkExitMath.inputFeeSats(rate)) - val extra = if (needed > atRate.fundedSats) needed - atRate.fundedSats else 0uL - return maxOf(extra, SparkExitMath.FUNDING_DUST_SATS) } private suspend fun retryFailedLeaves( @@ -571,14 +593,13 @@ class SparkExitDriver( val built = record.leftoverSweep if (built?.txHex != null) { // The sweep, or a version it replaced, confirmed. - val sent = listOfNotNull(built.txid.takeIf { built.isAccepted }) + built.replacedTxids - if (sent.any { isConfirmed(it) }) return record.copy(leftoverSweep = built.copy(isConfirmed = true)) + built.sentTxids.firstOrNull { isConfirmed(it) }?.let { return sweepLanded(record, built, it) } // Refused for its fee: wait for the next block and try again at a rate nodes take. if (built.isFeeRejection) return waitForFees(record, built) // No node took it in a day: built again from what the address holds. val builtAt = built.builtAtHeight if (!built.isAccepted && builtAt != null && tip != null && tip >= builtAt + SWEEP_RECHECK_BLOCKS) { - return record.copy(leftoverSweep = null) + return readAddressAgain(record, built) } val sentAt = built.sentAtHeight val isOverdue = built.isAccepted && sentAt != null && tip != null && tip >= sentAt + SWEEP_REPLACE_BLOCKS @@ -588,9 +609,7 @@ class SparkExitDriver( } if (built?.isWaitingForFees == true) { // A version a node accepted before a later refusal may still confirm. - if (built.replacedTxids.any { isConfirmed(it) }) { - return record.copy(leftoverSweep = built.copy(isConfirmed = true)) - } + built.replacedTxids.firstOrNull { isConfirmed(it) }?.let { return sweepLanded(record, built, it) } val height = tip ?: return record val since = requireNotNull(built.waitingSince) if (height >= since + SWEEP_RELEASE_BLOCKS) { @@ -645,6 +664,59 @@ class SparkExitDriver( return buildSweep(current, inputs, rate, built?.replacedTxids?.takeIf { it.isNotEmpty() }) } + /** + * The sweep confirmed. Funding that reached the address after it was built is still there: it waits and goes out + * in a sweep of its own, and the confirmed one is kept to show. + */ + private suspend fun sweepLanded( + record: SparkExitRecord, + sweep: SparkExitRecord.LeftoverSweep, + txid: String, + ): SparkExitRecord { + val landed = record.copy(leftoverSweep = sweep.copy(isConfirmed = true)) + val address = record.funding.firstOrNull()?.address ?: return landed + // Read again on the next tick: what is left at the address decides how the sweep ends. + // A host behind the block that confirmed it may still list what it spent. + val spent = sweep.txHex?.let { hex -> SparkExitTxInputs.decode(hex)?.map { "${it.prevTxid}:${it.vout}" } } + ?: record.leftover.map { "${it.txid}:${it.vout}" } + val utxos = runSuspendCatching { chain.utxos(address) }.getOrNull() + ?.filter { "${it.txid}:${it.vout}" !in spent } + ?: return record + if (utxos.isEmpty()) return landed + val height = tip ?: return record + Logger.info("Spark exit leftover sweep '$txid' confirmed with more funding left to sweep", context = TAG) + val total = utxos.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + return record.copy( + sweptLeftover = record.sweptLeftover + SparkExitRecord.SweptLeftover(txid, sweep.valueSats), + leftover = utxos.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) }, + leftoverSweep = SparkExitRecord.LeftoverSweep( + null, + null, + total, + waitingSince = height, + checkedAtHeight = height, + retryAtHeight = height, + ), + ) + } + + /** What the address holds is read again on the next tick, still looking for the versions a node accepted. */ + private fun readAddressAgain(record: SparkExitRecord, sweep: SparkExitRecord.LeftoverSweep): SparkExitRecord { + val height = tip ?: return record.copy(leftoverSweep = null) + val total = record.leftover.fold(0uL) { sum, leftover -> sum.safe() + leftover.valueSats.safe() } + return record.copy( + leftoverSweep = SparkExitRecord.LeftoverSweep( + null, + null, + total, + replacedTxids = sweep.sentTxids, + waitingSince = record.leftoverSweep?.waitingSince ?: height, + checkedAtHeight = height, + retryAtHeight = height, + ), + ) + } + private suspend fun economyRate(): ULong? = runSuspendCatching { chain.economyFeeRate() } .onFailure { Logger.warn("Failed to read the economy fee rate for the leftover sweep", it, context = TAG) } .getOrNull() @@ -666,7 +738,7 @@ class SparkExitDriver( null, null, totalSats, - replacedTxids = refused?.replacedTxids.orEmpty(), + replacedTxids = (refused ?: earlier)?.sentTxids.orEmpty(), waitingSince = since, checkedAtHeight = height, refusedFeeRate = floor, @@ -753,14 +825,12 @@ class SparkExitDriver( // A replacement refused for another reason while the version it replaced may still confirm waits again. is SparkExitBroadcastOutcome.Rejected if sweep.replacedTxids.isNotEmpty() && tip != null && !outcome.reason.contains("fee", ignoreCase = true) -> - waitForFees( - record - ).let { it.copy(leftoverSweep = it.leftoverSweep?.copy(replacedTxids = sweep.replacedTxids)) } + waitForFees(record.copy(leftoverSweep = sweep)) is SparkExitBroadcastOutcome.Rejected -> record.copy( leftoverSweep = sweep.copy(isAccepted = false, rejection = outcome.reason), ) // Its inputs went elsewhere: what is still at the address is read and swept again. - is SparkExitBroadcastOutcome.InputsMissing -> record.copy(leftoverSweep = null) + is SparkExitBroadcastOutcome.InputsMissing -> readAddressAgain(record, sweep) is SparkExitBroadcastOutcome.RetryLater, is SparkExitBroadcastOutcome.NotMature, -> record diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 4ee06f3a7a..dadb7ea667 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -126,6 +126,8 @@ data class SparkExitRecord( val isFailedLeavesReleased: Boolean = false, /** The confirmed sweep of a replaced generation, so Done still names it after a retry of leaves replaced it. */ val landedSweepTxid: String? = null, + /** Leftover sweeps that confirmed while more funding was still at the address, earliest first. */ + val sweptLeftover: List = emptyList(), /** Steps confirmed when the rebuild from the chain was adopted; one more clears [isRebuiltFromChain]. */ val rebuiltFromChainConfirmedCount: Int? = null, /** The tip of the first funding-wait tick that looked for [fundingPaymentTxid]. */ @@ -216,6 +218,8 @@ data class SparkExitRecord( data class LostLeaf(val leafId: String, val valueSats: ULong) + data class SweptLeftover(val txid: String, val valueSats: ULong) + data class LeftBehindLeaf(val leafId: String, val valueSats: ULong, val reason: String) /** A cooperative leaf the operators moved on-chain; [valueSats] is 0 until a retry's quote names it. */ @@ -287,6 +291,9 @@ data class SparkExitRecord( /** Not built, waiting for fees to drop. A sweep with no [txid] and no wait is dust kept, as before waits. */ val isWaitingForFees: Boolean get() = txid == null && waitingSince != null && !isDustKept + /** This version, once a node accepted it, and the earlier ones it replaced: any of them may still confirm. */ + val sentTxids: List get() = listOfNotNull(txid.takeIf { isAccepted }) + replacedTxids + /** A refusal for its fee is not final: the sweep is built again at the network's current rate. */ val isFeeRejection: Boolean get() = rejection?.contains("fee", ignoreCase = true) == true } @@ -682,6 +689,7 @@ object SparkExitJson { o.objectOrNull("earlierReceivedSats")?.mapValues { it.value.jsonPrimitive.content.toULong() } }.orEmpty(), landedSweepTxid = read { o.stringOrNull("landedSweepTxid") }, + sweptLeftover = read { sweptLeftoverFromJson(o) }.orEmpty(), ) } @@ -862,6 +870,21 @@ object SparkExitJson { r.failedLeafRetriedAt?.let { put("failedLeafRetriedAt", it.toLong()) } if (r.isFailedLeavesReleased) put("isFailedLeavesReleased", true) r.landedSweepTxid?.let { put("landedSweepTxid", it) } + if (r.sweptLeftover.isNotEmpty()) { + put( + "sweptLeftover", + buildJsonArray { + r.sweptLeftover.forEach { + add( + buildJsonObject { + put("txid", it.txid) + put("valueSats", it.valueSats.toLong()) + }, + ) + } + }, + ) + } r.rebuiltFromChainConfirmedCount?.let { put("rebuiltFromChainConfirmedCount", it) } r.fundingPaymentSeenAtHeight?.let { put("fundingPaymentSeenAtHeight", it.toLong()) } r.fundingPaymentMissingSince?.let { put("fundingPaymentMissingSince", it.toLong()) } @@ -954,6 +977,7 @@ object SparkExitJson { failedLeafRetriedAt = o.ulongOrNull("failedLeafRetriedAt")?.toUInt(), isFailedLeavesReleased = o.booleanOrNull("isFailedLeavesReleased") ?: false, landedSweepTxid = o.stringOrNull("landedSweepTxid"), + sweptLeftover = sweptLeftoverFromJson(o), rebuiltFromChainConfirmedCount = o.intOrNull("rebuiltFromChainConfirmedCount"), fundingPaymentSeenAtHeight = o.ulongOrNull("fundingPaymentSeenAtHeight")?.toUInt(), fundingPaymentMissingSince = o.ulongOrNull("fundingPaymentMissingSince")?.toUInt(), @@ -963,6 +987,11 @@ object SparkExitJson { .orEmpty(), ) + private fun sweptLeftoverFromJson(o: JsonObject) = o.arrayOrEmpty("sweptLeftover").map { + val l = it.jsonObject + SparkExitRecord.SweptLeftover(l.string("txid"), l.ulong("valueSats")) + } + private fun leftoverFromJson(l: JsonObject) = SparkExitRecord.Leftover(l.string("txid"), l.ulong("vout").toUInt(), l.ulong("valueSats")) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index e0811b1224..e18611dae2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -11,6 +11,7 @@ import com.synonym.bitkitcore.Activity import io.ktor.client.HttpClient import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job +import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -177,7 +178,9 @@ class SparkExitRepo @Inject constructor( if (_state.value.record?.needsDriving != true) return@runSuspendCatching _state.value.record tick() if (_state.value.isExiting && !sparkService.isConnected) { - withTimeoutOrNull(BACKGROUND_CONNECT_TIMEOUT) { sparkRepo.start(walletIndex) } + // The connect keeps going past the timeout, so the next run finds Spark connecting or connected. + val connect = scope.async { sparkRepo.start(walletIndex) } + withTimeoutOrNull(BACKGROUND_CONNECT_TIMEOUT) { connect.await() } if (sparkService.isConnected) tick() } _state.value.record @@ -196,6 +199,10 @@ class SparkExitRepo @Inject constructor( .onFailure { Logger.error("Failed to drive the Spark exit", it, context = TAG) _state.update { state -> state.copy(lastError = it.message) } + // Steps the run saved before it failed are on disk, newer than the record it started from. + runSuspendCatching { store.load() }.getOrNull()?.let { saved -> + _state.update { state -> state.copy(record = saved) } + } // A run that failed did not keep the exit on track: the alerts still run and the alarm may fire. _state.value.record?.takeIf { record -> record.needsDriving }?.let { record -> runSuspendCatching { afterTick(record, record, isOnTrack = false, reportedLostLeafIds()) } @@ -218,6 +225,7 @@ class SparkExitRepo @Inject constructor( tip?.let { height -> sparkExitTip.height.update { height } } refreshNetworkFees(chain) refreshFundingSeen(chain, current) + if (current.isActive) _state.update { it.copy(isSavingsSendUnresolved = isSavingsSending(current)) } val store = store val recovering = sparkService.exitRecovering() val driver = driver(chain, recovering, current, tip) @@ -687,16 +695,26 @@ class SparkExitRepo @Inject constructor( } } + private suspend fun isSavingsSending(record: SparkExitRecord): Boolean { + val address = record.funding.firstOrNull()?.address ?: return false + val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() + return attempt?.address == address && attempt.isUnresolved + } + private suspend fun sendFunding(address: String, sats: ULong): String { val outcome = lightningRepo.sendOnChain( address = address, sats = sats, speed = TransactionSpeed.Fast, ).getOrThrow() - if (outcome !is OnchainSendOutcome.Accepted) { - throw SparkExitError( - "Spark exit funding was not accepted: '$outcome'" - ) + if (outcome is OnchainSendOutcome.Rejected) { + throw SparkExitError("Spark exit funding was not accepted: '$outcome'") + } + // A send no host confirmed may still go out: it counts as paid, so the exit keeps watching its address and + // cannot be cancelled. The own-payment wait forgets it if no host ever sees it. + if (outcome is OnchainSendOutcome.Unknown) { + Logger.warn("Spark exit funding '${outcome.txid}' went out with an unknown result", context = TAG) + return outcome.txid } runSuspendCatching { lightningRepo.completeAcceptedOrdinaryFollowup(outcome.txid) } .onFailure { Logger.warn("Failed to finish the Spark exit funding locally", it, context = TAG) } @@ -716,6 +734,7 @@ class SparkExitRepo @Inject constructor( record.recovery == null && record.fundedSats == 0uL && record.fundingPaymentTxid == null && + !exit.isSavingsSendUnresolved && exit.fundingSeenSats == 0uL } @@ -740,10 +759,15 @@ class SparkExitRepo @Inject constructor( suspend fun cancel(): Result = withContext(bgDispatcher) { runSuspendCatching { tickMutex.withLock { + val record = _state.value.record ?: throw SparkExitError("No Spark exit to cancel") + val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } + // A savings send to the address still unresolved may be retried later: the exit keeps watching it. + val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() } + .getOrElse { throw SparkExitCancelUnreadable() } + val isSending = attempt?.address == address && attempt.isUnresolved + _state.update { it.copy(isSavingsSendUnresolved = isSending) } if (!canCancel) throw SparkExitError("The Spark exit can no longer be cancelled") - val record = requireNotNull(_state.value.record) val chain = requireNotNull(chain) { "No chain host for this network" } - val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } val utxos = runSuspendCatching { chain.utxos(address) }.getOrElse { throw SparkExitCancelUnreadable() } record.transferId?.let { transferRepo.markSettled(it) } val outcome = if (utxos.isEmpty()) { @@ -827,6 +851,8 @@ data class SparkExitState( val tipHeight: UInt? = null, /** Confirmed or not, what reached the funding address. */ val fundingSeenSats: ULong = 0uL, + /** A savings send to the funding address is unresolved and may be retried: cancel stays off. */ + val isSavingsSendUnresolved: Boolean = false, /** How many payments make up [fundingSeenSats] before the exit starts: each adds its own input fee. */ val fundingSeenCount: Int = 0, /** What progress shows while the exit needs fee funding. */ diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index c439b77598..8a1a46a6e6 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -289,6 +289,17 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, /** Where the leftover fee funding of an ended exit is: being sent, sent, kept as dust, or still at its address. */ @Composable private fun LeftoverNote(record: SparkExitRecord, address: String, path: String?) { + // Sweeps that already confirmed come first; funding that arrived after them has a note of its own below. + record.sweptLeftover.forEach { + VerticalSpacer(16.dp) + SparkExitTxNote( + text = stringResource(R.string.lightning__spark_exit__leftover_swept) + .replace("{amount}", sparkExitAmountText(it.valueSats)), + txid = it.txid, + txidRes = R.string.lightning__spark_exit__leftover_txid, + testTag = "SparkExitLeftoverSweptEarlier", + ) + } if (record.leftover.isEmpty()) return val total = record.leftover.fold(0uL) { sum, leftover -> sum + leftover.valueSats } val sweep = record.leftoverSweep diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index ea59374c83..54a9528ffd 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -598,9 +598,12 @@ class SparkExitDriverTest : BaseUnitTest() { fun `a leftover sweep whose inputs went elsewhere reads the address again`() = test { var record = driver(tip = 1_000u).tick(sweepDone()) assertNotNull(assertNotNull(record.leftoverSweep).txHex) + val first = assertNotNull(record.leftoverSweep.txid) chain.outcome = SparkExitBroadcastOutcome.InputsMissing("missing-inputs") record = driver(tip = 1_001u).tick(record) - assertNull(record.leftoverSweep) + // The accepted sweep may still confirm: it is looked for while the address is read again. + assertEquals(listOf(first), assertNotNull(record.leftoverSweep).replacedTxids) + assertNull(record.leftoverSweep.txid) chain.utxosByAddress[SWEEP_FUNDING] = emptyList() record = driver(tip = 1_002u).tick(record) @@ -722,20 +725,31 @@ class SparkExitDriverTest : BaseUnitTest() { } @Test - fun `cooperative leaves the operators could not sign are tried again`() = test { + fun `a first build of only cooperative leaves the operators could not sign is kept and retried`() = test { sdk.preparedResponse = SparkExitFixtures.prepared(funding = null) - sdk.builds += SparkExitFixtures.recovery( - emptyList(), - failed = listOf( - CooperativeRecoveryFailure("leaf-1", "o", 0u, CooperativeRecoveryError.OperatorsUnavailable("down")), - ), + val failed = listOf( + CooperativeRecoveryFailure("leaf-1", "o", 0u, CooperativeRecoveryError.OperatorsUnavailable("down")), ) + sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = failed) - val record = driver().tick(SparkExitFixtures.record(Phase.AwaitingFunding(0uL))) + var record = driver(tip = 1_000u).tick(SparkExitFixtures.record(Phase.AwaitingFunding(0uL))) - assertEquals(Phase.AwaitingFunding(0uL), record.phase) + assertEquals(Phase.Running, record.phase) assertEquals(1, record.failedLeafCount) - assertNull(record.recovery) + assertEquals(failed, assertNotNull(record.recovery).failed) + assertEquals(record, saved.last()) + + // No check of a recovery with nothing in it: the failed leaves are retried at once, then let go. + sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = failed) + record = driver(tip = 1_001u).tick(record) + assertTrue(sdk.checkedRecoveries.isEmpty()) + assertEquals(listOf("leaf-1"), (sdk.prepareRequests.last().selection as ExitLeafSelection.Specific).leafIds) + assertEquals(listOf("leaf-1"), record.failedLeaves.map { it.leafId }) + assertEquals(Phase.Running, record.phase) + + record = driver(tip = 2_009u).tick(record) + assertEquals(Phase.Done, record.phase) + assertTrue(record.isFailedLeavesReleased) } private val operatorsDown = CooperativeRecoveryFailure( @@ -789,7 +803,6 @@ class SparkExitDriverTest : BaseUnitTest() { fun `a retry the operators co-sign becomes the next generation and the exit ends once it confirms`() = test { val done = SparkExitFixtures.recovery(emptyList(), failed = listOf(operatorsDown)) var record = running(done) - sdk.checks += check(done, RecoveryVerdict.Done) sdk.preparedResponse = coopLeaf(16_384uL) val coop = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("coop", kind = RecoveryTxKind.COOPERATIVE))) sdk.builds += coop @@ -841,6 +854,25 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(SparkExitMath.FUNDING_DUST_SATS, driver().feeBumpShortfall(record, 9uL)) } + @Test + fun `a higher fee leaves a leaf the build refuses behind on a copy and prices the rest`() = test { + val record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) + .copy(leafIds = listOf("leaf-1", "leaf-2")) + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-1", "leaf-2")) + sdk.preparedResponses += SparkExitFixtures.prepared(leaves = listOf("leaf-1", "leaf-2")) + sdk.preparedResponses += SparkExitFixtures.prepared(leaves = listOf("leaf-2")) + sdk.recoverErrors += ladderRefusal("leaf-1") + sdk.recoverError = SdkException.InsufficientCpfpFunds(26_000uL, "") + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", value = 20_000uL)) + + assertEquals(6_612uL, driver().feeBumpShortfall(record, 9uL)) + + assertEquals(listOf("leaf-2"), (sdk.prepareRequests.last().selection as ExitLeafSelection.Specific).leafIds) + // The live exit keeps its leaves. + assertEquals(listOf("leaf-1", "leaf-2"), record.exitLeafIds) + assertTrue(saved.isEmpty()) + } + @Test fun `a paid higher fee rebuilds at the new rate once its payment confirms`() = test { var record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) @@ -1394,6 +1426,43 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(1_144u, replaced.sentAtHeight) } + @Test + fun `a sweep that confirmed with more funding at the address is kept and the rest swept on its own`() = test { + var record = driver(tip = 1_000u).tick(sweepDone()) + val first = assertNotNull(record.leftoverSweep) + chain.confirmedTxids = setOf(assertNotNull(first.txid)) + val late = SparkExitFixtures.utxo("e1".repeat(32), 0u, 30_000uL) + chain.utxosByAddress[SWEEP_FUNDING] = listOf(late) + + record = driver(tip = 1_001u).tick(record) + + assertEquals(listOf(SparkExitRecord.SweptLeftover(first.txid, first.valueSats)), record.sweptLeftover) + assertEquals(listOf(SparkExitRecord.Leftover(late.txid, late.vout, late.value)), record.leftover) + val swept = SparkExitJson.decode(SparkExitJson.encode(record)) + assertEquals(record.sweptLeftover, swept.sweptLeftover) + + record = driver(tip = 1_001u).tick(record) + val second = assertNotNull(record.leftoverSweep) + assertTrue(second.isAccepted) + assertEquals(late.txid, SparkExitTxInputs.decode(second.txHex!!)!!.single().prevTxid) + assertTrue(record.needsDriving) + } + + @Test + fun `a sweep no node took is built again still looking for the version a node accepted`() = test { + var record = driver(tip = 1_000u).tick(sweepDone()) + val first = requireNotNull(record.leftoverSweep?.txid) + record = driver(tip = 1_144u).tick(record) + assertEquals(listOf(first), record.leftoverSweep?.replacedTxids) + val replacement = assertNotNull(record.leftoverSweep) + // No node takes the replacement for a day: the address is read again, still looking for the first. + chain.outcome = SparkExitBroadcastOutcome.RetryLater("timeout") + record = driver(tip = 1_145u).tick(record.copy(leftoverSweep = replacement.copy(isAccepted = false))) + record = driver(tip = 1_288u).tick(record) + assertNull(record.leftoverSweep?.txid) + assertEquals(listOf(first), record.leftoverSweep?.replacedTxids) + } + @Test fun `a sweep whose replaced version confirmed ends`() = test { var record = driver(tip = 1_000u).tick(sweepDone()) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt index 6fecdad179..743bfd1592 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -198,6 +198,9 @@ class FakeSparkExitRecovering : SparkExitRecovering { val recoverRequests = mutableListOf() val checkedRecoveries = mutableListOf() + /** Errors the next recovers throw, in order, before [recoverError]. */ + val recoverErrors = ArrayDeque() + /** Errors the next prepares throw, in order, before [preparedResponse] is returned. */ val prepareErrors = ArrayDeque() @@ -212,6 +215,7 @@ class FakeSparkExitRecovering : SparkExitRecovering { override suspend fun recover(request: RecoverFundsRequest, signer: CpfpSigner?): RecoverFundsResponse { recoverRequests += request + recoverErrors.removeFirstOrNull()?.let { throw it } recoverError?.let { throw it } return builds.removeFirst() } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 8c80d74be1..09fe895c06 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -184,17 +184,20 @@ class SparkExitRepoTest : BaseUnitTest() { /** Spark's regtest mempool, where nothing is confirmed yet and every single transaction is accepted. */ private fun regtestMempool(posts: MutableList, refusal: String? = null) = HttpClient( - MockEngine { request -> - val url = request.url.toString() - when { - request.method == HttpMethod.Post && url.endsWith("/api/tx") -> { - posts += String(request.body.toByteArray()) - if (refusal != null) return@MockEngine respond(refusal, HttpStatusCode.BadRequest) - respond(String(request.body.toByteArray()).removePrefix("02")) + MockEngine.create { + dispatcher = testDispatcher + addHandler { request -> + val url = request.url.toString() + when { + request.method == HttpMethod.Post && url.endsWith("/api/tx") -> { + posts += String(request.body.toByteArray()) + if (refusal != null) return@addHandler respond(refusal, HttpStatusCode.BadRequest) + respond(String(request.body.toByteArray()).removePrefix("02")) + } + url.endsWith("/blocks/tip/height") -> respond("1000") + url.endsWith("/status") -> respond("""{"confirmed":false}""") + else -> throw IOException("unreachable '$url'") } - url.endsWith("/blocks/tip/height") -> respond("1000") - url.endsWith("/status") -> respond("""{"confirmed":false}""") - else -> throw IOException("unreachable '$url'") } }, ) { defaultRequest { contentType(ContentType.Application.Json) } } @@ -245,6 +248,51 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(1, restarted.checkedRecoveries.size) } + @Test + fun `a background run gives up on a hanging connect at the timeout and leaves it running`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + store.save(SparkExitFixtures.record(Phase.Running).adopt(recovery, 0L)) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) + val spark = coldSpark(FakeSparkExitRecovering(), connects = false) + val gate = CompletableDeferred() + var isCancelled = false + whenever(sparkRepo.start(any())).doSuspendableAnswer { + runCatching { gate.await() }.onFailure { isCancelled = true }.getOrThrow() + Result.success(Unit) + } + + createSut(spark, regtestMempool(mutableListOf())).runInBackground().getOrThrow() + + assertFalse(gate.isCompleted) + assertFalse(isCancelled) + gate.complete(Unit) + } + + @Test + fun `a tick that fails after saving a step keeps the saved record`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val running = runningRecord() + store.save(running) + val sdk = FakeSparkExitRecovering().apply { + checks += CheckRecoverFundsResponse( + running.recovery!!, + RecoveryVerdict.Redo(RecoveryRedoReason.ON_CHAIN_STATE_DIVERGED), + ) + // The rebuild is saved, then its prepare fails. + prepareErrors += SdkException.SparkException("connection reset") + } + val sut = quotedSut(sdk) + sut.load().getOrThrow() + + assertTrue(sut.tick().isFailure) + + assertTrue(assertNotNull(sut.state.value.record).isRebuilding) + assertEquals(store.load(), sut.state.value.record) + } + @Test fun `a background run whose steps keep being refused lets the deadline alarm fire`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) @@ -338,14 +386,17 @@ class SparkExitRepoTest : BaseUnitTest() { whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) val utxo = """[{"txid":"$funded","vout":0,"value":9035,"status":{"confirmed":true,"block_height":900}}]""" val mempool = HttpClient( - MockEngine { request -> - val url = request.url.toString() - when { - request.method == HttpMethod.Post && url.endsWith("/api/tx") -> respond("n1") - url.endsWith("/address/${SparkExitFixtures.FUNDING_ADDRESS}/utxo") -> respond(utxo) - url.endsWith("/blocks/tip/height") -> respond("1000") - url.endsWith("/status") -> respond("""{"confirmed":false}""") - else -> throw IOException("unreachable '$url'") + MockEngine.create { + dispatcher = testDispatcher + addHandler { request -> + val url = request.url.toString() + when { + request.method == HttpMethod.Post && url.endsWith("/api/tx") -> respond("n1") + url.endsWith("/address/${SparkExitFixtures.FUNDING_ADDRESS}/utxo") -> respond(utxo) + url.endsWith("/blocks/tip/height") -> respond("1000") + url.endsWith("/status") -> respond("""{"confirmed":false}""") + else -> throw IOException("unreachable '$url'") + } } }, ) { defaultRequest { contentType(ContentType.Application.Json) } } @@ -569,6 +620,60 @@ class SparkExitRepoTest : BaseUnitTest() { verify(sparkRepo).setExiting(false, false) } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a savings payment with an unknown result counts as paid and keeps the exit`() = test { + stubFunding { Result.success(OnchainSendOutcome.Unknown("maybe")) } + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + + sut.start(fundFromSavings = true).getOrThrow() + runCurrent() + + val record = assertNotNull(sut.state.value.record) + assertEquals("maybe", record.fundingPaymentTxid) + assertTrue(record.isAwaitingOwnPayment) + assertFalse(sut.canCancel) + assertTrue(sut.cancel().isFailure) + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + assertEquals("maybe", store.load()?.fundingPaymentTxid) + verify(lightning, never()).completeAcceptedOrdinaryFollowup(any()) + sut.onAppBackgrounded() + } + + @Test + fun `cancel keeps an exit savings may still pay, while its send to the address is unresolved`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord()) + val attempt = OnchainSendAttempt( + walletId = "wallet", + attemptId = "attempt", + requestId = null, + orderId = null, + address = funding, + amountSats = 9_000uL, + isMaxAmount = false, + feeRateSatsPerVByte = 9uL, + isTransfer = false, + channelId = null, + tags = emptyList(), + evidence = OnchainSendEvidence.Unknown, + txid = "maybe", + ) + whenever(lightning.currentOnchainSendAttempt()).thenReturn(attempt) + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + + assertTrue(sut.cancel().isFailure) + assertFalse(sut.canCancel) + assertNotNull(store.load()) + + // Once savings let the send go, the exit nothing reached can go too. + whenever(lightning.currentOnchainSendAttempt()).thenReturn(null) + assertEquals(SparkExitCancel.Cancelled, sut.cancel().getOrThrow()) + assertNull(store.load()) + } + @Test fun `cancel keeps funding that reached the address and sends it back to savings`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) @@ -647,7 +752,7 @@ class SparkExitRepoTest : BaseUnitTest() { } @Test - fun `fee bump rates are priced without broadcasting, leaving out a rate the sdk refuses a leaf at`() = test { + fun `fee bump rates are priced without broadcasting, leaving a leaf the sdk refuses behind`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) store.save(runningRecord()) val sdk = FakeSparkExitRecovering().apply { @@ -659,8 +764,8 @@ class SparkExitRepoTest : BaseUnitTest() { val options = sut.feeBumpOptions().getOrThrow() - assertEquals(listOf(FeeRate.NORMAL to 6uL), options.map { it.speed to it.rateSatPerVbyte }) - assertEquals(0uL, options.single().totalSats) + assertEquals(listOf(FeeRate.FAST to 9uL, FeeRate.NORMAL to 6uL), options.map { it.speed to it.rateSatPerVbyte }) + assertTrue(options.all { it.totalSats == 0uL }) assertTrue(sdk.recoverRequests.isEmpty()) } } From ee4393cf174c9ad10d68d3e7db5711d91877417d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 02:16:50 +0100 Subject: [PATCH 029/154] fix: spark exit second round of review findings --- .../to/bitkit/repositories/SparkExitChain.kt | 6 +- .../to/bitkit/repositories/SparkExitDriver.kt | 110 +++++++++++---- .../bitkit/repositories/SparkExitFunding.kt | 19 ++- .../to/bitkit/repositories/SparkExitRecord.kt | 28 +++- .../to/bitkit/repositories/SparkExitRepo.kt | 132 +++++++++++++----- .../to/bitkit/repositories/SparkExitWorker.kt | 12 +- .../lightning/SparkExitFeeBumpScreen.kt | 9 +- .../settings/lightning/SparkExitViewModel.kt | 16 ++- .../usecases/DeriveBalanceStateUseCase.kt | 24 +++- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../repositories/SparkExitAlertsTest.kt | 7 + .../repositories/SparkExitDriverTest.kt | 94 +++++++++++-- .../repositories/SparkExitFundingTest.kt | 11 ++ .../bitkit/repositories/SparkExitRepoTest.kt | 112 ++++++++++++++- .../usecases/DeriveBalanceStateUseCaseTest.kt | 33 +++++ 30 files changed, 530 insertions(+), 99 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 6a1bb63cdf..a849ed10a0 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -41,7 +41,11 @@ sealed interface SparkExitBroadcastOutcome { /** The host or node could not take it now: the next tick tries again. */ data class RetryLater(val reason: String) : SparkExitBroadcastOutcome { - override val summary get() = "retry: $reason" + override val summary get() = "$PREFIX$reason" + + companion object { + const val PREFIX = "retry: " + } } /** Its relative timelock has not matured (`non-BIP68-final`): sent again once it has, never a rejection. */ diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 5eb93de8d4..180e493959 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -130,8 +130,9 @@ class SparkExitDriver( var record = start when (record.phase) { SparkExitRecord.Phase.Done, is SparkExitRecord.Phase.Failed -> { - if (!record.isLeftoverSweepPending) return record - record = sweepLeftover(record) + if (!record.isLeftoverSweepPending && !record.isEndedPaymentPending) return record + record = watchEndedPayment(record) + if (record.isLeftoverSweepPending) record = sweepLeftover(record) save(record) return record } @@ -162,6 +163,7 @@ class SparkExitDriver( record = record.copy(claimableAtHeight = record.recovery?.let { SparkExitMath.claimableAtHeight(it, tip) }) } // The tick that ends the exit also sends its leftover fee funding to savings. + if (!record.isActive) record = watchEndedPayment(record) if (record.isLeftoverSweepPending) record = sweepLeftover(record) save(record) return record @@ -446,37 +448,36 @@ class SparkExitDriver( /** * What the exit's funding address must still receive to rebuild at [rate]: a build of the exit's leaves with the - * funding it holds, nothing broadcast. Priced on a copy: a leaf the SDK refuses is left behind on the copy and - * the rest priced again, as a rebuild would, so the live exit's leaves never change. Zero when that funding covers - * it; otherwise the SDK's shortfall less what the address still holds, with one more input's fee for the payment, - * at least dust. + * funding it holds, nothing broadcast, on a copy with the rebuild's drop-and-retry. A leaf the prepare or the build + * refuses at that rate throws [SparkExitFeeBumpLeavesBehind]. Zero when that funding covers it; otherwise the + * SDK's shortfall less what the address still holds, with one more input's fee for the payment, at least dust. */ suspend fun feeBumpShortfall(record: SparkExitRecord, rate: ULong): ULong { val sdk = checkNotNull(recovering) { "Spark is not connected" } - var atRate = withExitState(record, sdk).copy(feeRateSatPerVbyte = rate) - while (true) { - val (priced, prepared) = prepare(atRate, sdk) - atRate = priced - if (prepared == null || prepared.funding == null) return 0uL - val built = - runSuspendCatching { sdk.recover(RecoverFundsRequest(prepared, atRate.fundingInputs), makeSigner()) } - val error = built.exceptionOrNull() ?: return 0uL - val refusal = SparkExitUnexitable.parse(error)?.takeIf { it.leafId in atRate.exitLeafIds } - if (refusal != null) { - atRate = atRate.leaveBehind(refusal.leafId, refusal.reason) - continue - } - val required = (error as? SdkException.InsufficientCpfpFunds ?: throw error).requiredSats - val held = atRate.funding.firstOrNull()?.address?.let { address -> - runSuspendCatching { chain.utxos(address) }.getOrNull()?.let { SparkExitMath.heldSats(it, atRate) } - } - val needed = - SparkExitMath.neededFunding(required, atRate.fundedSats, held, SparkExitMath.inputFeeSats(rate)) - val extra = if (needed > atRate.fundedSats) needed - atRate.fundedSats else 0uL - return maxOf(extra, SparkExitMath.FUNDING_DUST_SATS) + val atRate = withExitState(record, sdk).copy(feeRateSatPerVbyte = rate) + val (priced, prepared) = prepare(atRate, sdk) + // A rate at which a leaf can't pay its own exit would leave that leaf on Spark: never offered. + val dropped = priced.leftBehindLeaves.drop(record.leftBehindLeaves.size) + if (dropped.isNotEmpty() || prepared == null) throw SparkExitFeeBumpLeavesBehind(leavesSats(record, dropped)) + if (prepared.funding == null) return 0uL + val built = + runSuspendCatching { sdk.recover(RecoverFundsRequest(prepared, priced.fundingInputs), makeSigner()) } + val error = built.exceptionOrNull() ?: return 0uL + SparkExitUnexitable.parse(error)?.takeIf { it.leafId in priced.exitLeafIds }?.let { + throw SparkExitFeeBumpLeavesBehind(record.leafValueSats(it.leafId)) + } + val required = (error as? SdkException.InsufficientCpfpFunds ?: throw error).requiredSats + val held = priced.funding.firstOrNull()?.address?.let { address -> + runSuspendCatching { chain.utxos(address) }.getOrNull()?.let { SparkExitMath.heldSats(it, priced) } } + val needed = SparkExitMath.neededFunding(required, priced.fundedSats, held, SparkExitMath.inputFeeSats(rate)) + val extra = if (needed > priced.fundedSats) needed - priced.fundedSats else 0uL + return maxOf(extra, SparkExitMath.FUNDING_DUST_SATS) } + private fun leavesSats(record: SparkExitRecord, leaves: List): ULong = + leaves.fold(0uL) { sum, leaf -> sum.safe() + record.leafValueSats(leaf.leafId).safe() } + private suspend fun retryFailedLeaves( start: SparkExitRecord, failedIds: List, @@ -658,7 +659,7 @@ class SparkExitDriver( val floor = built?.takeIf { it.isWaitingForFees }?.refusedFeeRate ?: 0uL val rate = maxOf(SparkExitMath.sweepFeeRate(economyRate(), record.feeRateSatPerVbyte), floor) val inputs = SparkExitSweep.worthSweeping( - utxos.map { SparkExitSweep.Input(it.txid, it.vout, it.value) }, + confirmed.map { SparkExitSweep.Input(it.txid, it.vout, it.value) }, rate, ) return buildSweep(current, inputs, rate, built?.replacedTxids?.takeIf { it.isNotEmpty() }) @@ -902,7 +903,58 @@ class SparkExitDriver( if (isDue(tx.txid, current)) current = broadcastAndSave(tx, current, parentsConfirmed = true) tx } - return current.copy(recovery = recovery.copy(transactions = transactions)) + val checked = current.copy(recovery = recovery.copy(transactions = transactions)) + // Every step confirmed and no leaf failed: the exit is done without an SDK verdict. + val isAllConfirmed = transactions.isNotEmpty() && + transactions.all { it.status is ExitTransactionStatus.Confirmed } + if (!isAllConfirmed || recovery.failed.isNotEmpty() || checked.phase != SparkExitRecord.Phase.Running) { + return checked + } + Logger.info("Every Spark exit step confirmed; ending the exit without the SDK", context = TAG) + return end(checked.copy(phase = SparkExitRecord.Phase.Done, failedLeaves = emptyList()), checked) + } + + /** + * A payment from savings still unresolved when the exit ended, such as a higher fee sent with an unknown result: + * its outputs join the leftover once they reach the address, and the own-payment wait forgets one no host sees. + */ + private suspend fun watchEndedPayment(record: SparkExitRecord): SparkExitRecord { + val txid = record.fundingPaymentTxid ?: return record + // Already in the leftover: the sweep takes it, and nothing more is watched. + if (!record.isActive && record.leftover.any { it.txid == txid }) { + return record.copy( + fundingPaymentTxid = null, + fundingPaymentSeenAtHeight = null, + fundingPaymentMissingSince = null, + ) + } + if (!record.isEndedPaymentPending) return record + val height = tip ?: return record + val address = record.funding.firstOrNull()?.address ?: return record + val arrived = runSuspendCatching { chain.utxos(address) }.getOrNull()?.filter { it.txid == txid } + ?: return record + if (arrived.isEmpty()) { + val isKnown = runSuspendCatching { chain.isTxKnown(txid) }.getOrDefault(true) + return record.withOwnPaymentLooked(height, isKnown) + } + val sweep = record.leftoverSweep + // A sweep still out there settles first; then the payment goes in a sweep of its own. + if (sweep?.txHex != null && !sweep.isConfirmed && sweep.rejection == null) return record + Logger.info( + "Adding Spark exit payment '$txid' that arrived after the exit ended to its leftover", + context = TAG + ) + val swept = sweep?.takeIf { it.isConfirmed && it.txid != null } + ?.let { record.sweptLeftover + SparkExitRecord.SweptLeftover(requireNotNull(it.txid), it.valueSats) } + val payment = arrived.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) } + return record.copy( + leftover = if (swept != null) payment else (record.leftover + payment).distinct(), + sweptLeftover = swept ?: record.sweptLeftover, + leftoverSweep = null, + fundingPaymentTxid = null, + fundingPaymentSeenAtHeight = null, + fundingPaymentMissingSince = null, + ) } private suspend fun parentHeight(txid: String, known: EsploraTxStatus?): UInt? { diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 01c5f4d002..d6ef8212e3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -374,15 +374,22 @@ object SparkExitMath { } /** - * Every confirmed UTXO of new funding, the largest first, once together they cover [requiredSats] plus - * [inputFeeSats] for each coin beyond the first: the SDK spends every input it is given. + * The fewest confirmed UTXOs of new funding, the largest first, that cover [requiredSats] plus [inputFeeSats] for + * each coin beyond the first; a coin worth no more than its input's fee is never taken. The SDK spends every input + * it is given, so the rest stays for the leftover sweep. */ fun fundingTopUp(utxos: List, requiredSats: ULong, inputFeeSats: ULong = 0uL): List? { val confirmed = utxos.filter { it.status.confirmed }.sortedByDescending { it.value } - if (confirmed.isEmpty()) return null - val total = confirmed.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } - val needed = requiredSats.safe() + (inputFeeSats.safe() * (confirmed.size - 1).toULong().safe()).safe() - return confirmed.takeIf { total >= needed } + val taken = mutableListOf() + var total = 0uL + for (utxo in confirmed) { + if (taken.isNotEmpty() && utxo.value <= inputFeeSats) return null + taken += utxo + total = total.safe() + utxo.value.safe() + val needed = requiredSats.safe() + (inputFeeSats.safe() * (taken.size - 1).toULong().safe()).safe() + if (total >= needed) return taken + } + return null } /** About how long until [height]. */ diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index dadb7ea667..5f89a76db1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -238,6 +238,14 @@ data class SparkExitRecord( get() = fundingPaymentTxid != null && fundingShortfallSats != null && funding.none { it.txid == fundingPaymentTxid } + /** The exit ended while a payment from savings to its address was unresolved: it is watched until it is. */ + val isEndedPaymentPending: Boolean + get() = !isActive && fundingPaymentTxid != null && funding.none { it.txid == fundingPaymentTxid } && + leftover.none { it.txid == fundingPaymentTxid } + + /** Steps still go out: the exit runs, or drives its generation while a higher fee's payment confirms. */ + val isSendingSteps: Boolean get() = phase == Phase.Running || isDrivingWhileFunding + /** A higher fee's top-up, not a diverged rebuild: the generation out there is still driven while it confirms. */ val isDrivingWhileFunding: Boolean get() = phase is Phase.NeedsFunding && recovery != null && !isRebuilding @@ -247,7 +255,7 @@ data class SparkExitRecord( * or 144 blocks after the first look without being adopted, so the ask and its reminder come back. */ fun withOwnPaymentLooked(tip: UInt, isKnown: Boolean): SparkExitRecord { - if (!isAwaitingOwnPayment) return this + if (!isAwaitingOwnPayment && !isEndedPaymentPending) return this val seenAt = fundingPaymentSeenAtHeight ?: tip val missingSince = if (isKnown) null else fundingPaymentMissingSince ?: tip val isMissing = missingSince != null && tip >= missingSince + OWN_PAYMENT_MISSING_BLOCKS @@ -313,7 +321,8 @@ data class SparkExitRecord( * An exit that failed or lost leaves keeps it until the user opened it once. */ val showsResult: Boolean - get() = isActive || isLeftoverSweepPending || (leftover.isNotEmpty() && leftoverSweep?.rejection != null) || + get() = isActive || isLeftoverSweepPending || isEndedPaymentPending || + (leftover.isNotEmpty() && leftoverSweep?.rejection != null) || hasUnseenResult /** The exit ended failed or with leaves lost, and the user has not opened its result yet. */ @@ -321,7 +330,7 @@ data class SparkExitRecord( get() = !isActive && (phase is Phase.Failed || lostSats > 0uL) && !isResultSeen /** Background runs and the foreground loop keep going while the exit runs and until its leftover is swept. */ - val needsDriving: Boolean get() = isActive || isLeftoverSweepPending + val needsDriving: Boolean get() = isActive || isLeftoverSweepPending || isEndedPaymentPending val isActive: Boolean get() = when (phase) { @@ -444,6 +453,19 @@ data class SparkExitRecord( * A step of this generation that keeps being refused, or whose fee chain keeps failing, and has not confirmed: * the chain is broken, so the exit rebuilds over it. */ + /** + * A step of this generation whose last send reached no node, such as a host timing out: the exit is not on track + * while it waits, so the deadline is not pushed back. + */ + val unpublishedStep: BroadcastAttempt? + get() { + val confirmed = confirmedTxids + return broadcastLog.firstOrNull { + it.generation == generation && !it.isAccepted && it.txid !in confirmed && + it.lastOutcome.startsWith(SparkExitBroadcastOutcome.RetryLater.PREFIX) + } + } + val stuckStep: BroadcastAttempt? get() { val confirmed = confirmedTxids diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index e18611dae2..175a1c17ba 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -98,14 +98,41 @@ class SparkExitRepo @Inject constructor( scope.launch { sparkRepo.walletWiped.collect { if (it != walletIndex) return@collect - work.cancelAll() - _state.update { SparkExitState() } + // Closed first: a tick or background run still going writes nothing more of the wiped exit. + isWriteClosed = true + foregroundJob?.cancel() + foregroundJob = null + tickMutex.withLock { + runCatching { store.delete() } + .onFailure { e -> + Logger.warn( + "Failed to delete the wiped Spark exit record", + e, + context = TAG + ) + } + runCatching { lostLeafStore.delete() } + work.cancelAll() + _state.update { SparkExitState() } + isLoaded = false + // A later exit, of a new or restored wallet, writes again. + isWriteClosed = false + } } } } private val store get() = SparkExitStore(File(Env.sparkExitRecordPath(walletIndex))) + /** Closed while a wipe of the wallet runs: a save then throws and writes nothing. */ + @Volatile + private var isWriteClosed = false + + private fun saveRecord(record: SparkExitRecord) { + if (isWriteClosed) throw SparkExitError("The Spark exit's wallet was wiped") + store.save(record) + } + private val lostLeafStore get() = SparkExitLostLeafStore(File(Env.sparkExitLostLeavesPath(walletIndex))) private val chain: SparkExitChain? @@ -144,7 +171,7 @@ class SparkExitRepo @Inject constructor( runCatching { store.delete() } return null } - runCatching { store.save(salvaged) } + runCatching { saveRecord(salvaged) } .onFailure { Logger.error("Failed to save the salvaged Spark exit record", it, context = TAG) } Logger.warn("Salvaged the Spark exit record in phase '${salvaged.phase}' to rebuild from chain", context = TAG) return salvaged @@ -245,6 +272,7 @@ class SparkExitRepo @Inject constructor( // confirm is underpriced, which no run changes. Either way the alarm may fire. val isStuckWithoutSdk = recovering == null && updated.stuckStep != null val isOnTrack = tip != null && canMove && updated.surfacedRejection == null && !updated.isFeeChainStuck && + updated.unpublishedStep == null && !isStuckWithoutSdk && updated.underpricedStep(tip) == null afterTick(updated, current, isOnTrack, reportedLost) return updated @@ -260,7 +288,7 @@ class SparkExitRepo @Inject constructor( recovering = recovering, // The record's own funding key, also for exits started before each exit had an index of its own. makeSigner = { signer(record.fundingIndex) }, - save = store::save, + save = ::saveRecord, nowMillis = clock::nowMs, tip = tip, ) @@ -282,18 +310,17 @@ class SparkExitRepo @Inject constructor( } private suspend fun settleIfFinished(record: SparkExitRecord) { + // The sweep's activity is marked as a transfer whenever the wallet has it, also after the transfer settled: + // a cold background run can end the exit before the wallet synced the sweep. + val sweepTxid = record.recovery?.transactions?.firstOrNull { it.kind == RecoveryTxKind.SWEEP }?.txid + ?: record.landedSweepTxid + val sweepActivity = sweepTxid?.let { activityRepo.getOnchainActivityByTxId(it) } + if (sweepActivity != null && !sweepActivity.isTransfer) { + activityRepo.updateActivity(sweepActivity.id, Activity.Onchain(sweepActivity.copy(isTransfer = true))) + } val transferId = record.transferId ?: return if (transferRepo.isSettled(transferId).getOrDefault(true)) return - var isFinished = !record.isActive - val sweep = record.recovery?.transactions?.firstOrNull { it.kind == RecoveryTxKind.SWEEP } - val sweepActivity = sweep?.let { activityRepo.getOnchainActivityByTxId(it.txid) } - if (sweepActivity != null) { - if (!sweepActivity.isTransfer) { - activityRepo.updateActivity(sweepActivity.id, Activity.Onchain(sweepActivity.copy(isTransfer = true))) - } - isFinished = true - } - if (isFinished) transferRepo.markSettled(transferId) + if (!record.isActive || sweepActivity != null) transferRepo.markSettled(transferId) } private suspend fun settleOrphanedTransfers(record: SparkExitRecord?) { @@ -483,9 +510,12 @@ class SparkExitRepo @Inject constructor( SparkExitFeeBumpOption(speed, rate, extra, extra.safe() + paymentFee.safe()) } } - // A rate at which the SDK refuses one of the exit's leaves would leave that leaf behind: not offered. + // A rate at which a leaf can't pay its own exit is not offered. With no rate left only for that reason, + // that is the error the screen names. priced.mapNotNull { it.getOrNull() }.ifEmpty { - throw priced.firstNotNullOfOrNull { it.exceptionOrNull() } ?: SparkExitError("No rate to offer") + val errors = priced.mapNotNull { it.exceptionOrNull() } + throw errors.firstOrNull { it !is SparkExitFeeBumpLeavesBehind } ?: errors.firstOrNull() + ?: SparkExitError("No rate to offer") } }.onFailure { Logger.error("Failed to price a higher Spark exit fee", it, context = TAG) @@ -530,12 +560,12 @@ class SparkExitRepo @Inject constructor( Logger.warn("Sweeping a higher fee paid after the Spark exit ended", context = TAG) val pending = txid?.let { listOf(SparkExitRecord.Leftover(it, 0u, option.extraSats)) }.orEmpty() val swept = current.copy(leftover = current.leftover + pending, leftoverSweep = null) - store.save(swept) + saveRecord(swept) _state.update { it.copy(record = swept) } return@withLock } val bumped = current.applyFeeBump(option.rateSatPerVbyte, option.extraSats, txid) - store.save(bumped) + saveRecord(bumped) _state.update { it.copy(record = bumped, fundingState = SparkExitMath.fundingState(bumped, utxos = null)) } @@ -624,7 +654,7 @@ class SparkExitRepo @Inject constructor( leafTotalSats = quote.leafTotalSats, ) // Saved before the transfer exists, so a failed save never leaves a transfer counted with no exit behind. - store.save(record) + saveRecord(record) cacheStore.update { val next = it.sparkExitNextFundingIndexes + (fundingIndexKey to pending.fundingIndex.toInt() + 1) it.copy(sparkExitNextFundingIndexes = next) @@ -633,15 +663,18 @@ class SparkExitRepo @Inject constructor( sparkRepo.holdForExit() val transferId = transferRepo.createTransfer(TransferType.SPARK_EXIT, quote.incomingSats.toLong()).getOrThrow() record = record.copy(transferId = transferId) - store.save(record) + saveRecord(record) _state.update { it.copy(record = record, pending = null, fundingAddress = key.address) } isLoaded = true // Reconnecting for the exit disconnects Spark, which would cut a running leaf optimization short. sparkRepo.awaitOptimizationIdle() - // An optimization since the quote swapped leaves: the exit is quoted again over the leaves Spark holds now. - requote(pending)?.let { fresh -> - quote = fresh - tickMutex.withLock { + val createdAt = record.createdAt + // A cancel during the wait ended this exit: nothing more of the start runs, and nothing is paid. + val isCurrent = tickMutex.withLock { + if (!isStarting(createdAt)) return@withLock false + // An optimization since the quote swapped leaves: the exit is quoted again over the leaves Spark holds now. + requote(pending)?.let { fresh -> + quote = fresh val current = requireNotNull(_state.value.record) transferRepo.markSettled(transferId) val freshTransfer = transferRepo.createTransfer( @@ -656,19 +689,26 @@ class SparkExitRepo @Inject constructor( leafTotalSats = fresh.leafTotalSats, transferId = freshTransfer, ) - store.save(record) + saveRecord(record) _state.update { it.copy(record = record) } } + // Under the lock, so a cancel can't release Spark between the check and taking it off Lightning. + sparkRepo.setExiting(true, reconnect = true) + true } - sparkRepo.setExiting(true, reconnect = true) + if (!isCurrent) throw SparkExitStartCancelled() work.schedulePeriodic() Logger.info("Started Spark exit of '${quote.exitSats}' sats over '${quote.leafIds.size}' leaves", context = TAG) // Driven before paying, so a failed payment from savings still leaves the exit watching its address. scope.launch { tick() } onAppForegrounded() - if (fundFromSavings && quote.fundingSats > 0uL) payFunding(key.address, quote.fundingSats) + if (fundFromSavings && quote.fundingSats > 0uL) payFunding(createdAt, key.address, quote.fundingSats) } + /** The exit created at [createdAt] is still the one on record and running: no cancel or wipe ended it. */ + private fun isStarting(createdAt: Long): Boolean = + _state.value.record?.let { it.createdAt == createdAt && it.isActive } == true + private suspend fun requote(pending: SparkExitPending): SparkExitQuote? { val recovering = sparkService.exitRecovering() ?: return null val lost = reportedLostLeafIds() + _state.value.record?.lostLeaves?.map { it.leafId }.orEmpty() @@ -682,13 +722,18 @@ class SparkExitRepo @Inject constructor( return fresh.copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) } - private suspend fun payFunding(address: String, sats: ULong) { - val txid = sendFunding(address, sats) - // After the tick in flight, so its save cannot drop the txid. + private suspend fun payFunding(createdAt: Long, address: String, sats: ULong) { + // Under the tick lock from the check to the saved txid: a cancel either ends the exit before anything is paid + // or finds the payment and refuses. After the tick in flight, so its save cannot drop the txid. tickMutex.withLock { + if (!isStarting(createdAt)) { + Logger.info("Spark exit ended before savings paid its funding; nothing is paid", context = TAG) + return@withLock + } + val txid = sendFunding(address, sats) val record = _state.value.record ?: return@withLock val paid = record.copy(fundingPaymentTxid = txid) - store.save(paid) + saveRecord(paid) _state.update { it.copy(record = paid, fundingState = SparkExitMath.fundingState(paid, utxos = null)) } @@ -745,7 +790,7 @@ class SparkExitRepo @Inject constructor( val record = _state.value.record?.takeIf { it.hasUnseenResult } ?: return@withLock val seen = record.copy(isResultSeen = true) - store.save(seen) + saveRecord(seen) _state.update { it.copy(record = seen) } } } @@ -783,7 +828,7 @@ class SparkExitRepo @Inject constructor( isResultSeen = true, isCancelled = true, ) - store.save(ended) + saveRecord(ended) _state.update { it.copy(record = ended) } work.schedulePeriodic() SparkExitCancel.Sweeping @@ -825,6 +870,12 @@ class SparkExitError(message: String) : AppError(message) /** The funding address could not be read, so a cancel could not tell whether money reached it. */ class SparkExitCancelUnreadable : AppError("Could not read the Spark exit funding address") +/** The exit was cancelled while it started, before anything was paid: nothing more of the start ran. */ +class SparkExitStartCancelled : AppError("The Spark exit was cancelled while it started") + +/** A higher fee rate would leave [sats] of the exit's leaves on Spark, so it is not offered. */ +class SparkExitFeeBumpLeavesBehind(val sats: ULong) : AppError("A higher fee would leave part of the exit on Spark") + /** The record's failed reason for an exit the user cancelled after funding reached its address. */ const val CANCELLED_REASON = "Cancelled" @@ -880,4 +931,19 @@ data class SparkExitState( val active = record?.takeIf { it.isActive } ?: return null return SparkExitMath.outsideExitSats(active.leafTotalSats, sparkBalanceSats) } + + /** + * What the exit still brings to savings: what it expects less what reached savings already, and less the first + * fee funding nobody paid yet, which the expected amount counts as returned. Null without an exit. + */ + val inTransferSats: ULong? + get() { + val exit = record ?: return null + val received = SparkExitMath.receivedSats(exit) ?: 0uL + val unpaid = (exit.phase as? SparkExitRecord.Phase.AwaitingFunding) + ?.takeIf { exit.fundingPaymentTxid == null } + ?.let { it.requiredSats.safe() - maxOf(exit.fundedSats, fundingSeenSats).safe() } + ?: 0uL + return (exit.expectedSats.safe() - received.safe()).safe() - unpaid.safe() + } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index 4e16096d22..8c2f6472a9 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -87,6 +87,7 @@ class SparkExitWork @Inject constructor( private const val KEY_WARN_AT = "warn-at" private const val KEY_DEADLINE_AT = "deadline-at" private const val KEY_FEE_LOW_RATE = "fee-low-rate" + private const val KEY_FUNDING_REMINDED = "funding-reminded-exit" private const val NOTIFICATION_ID = 7797 /** The shortest period WorkManager runs periodic work at. */ @@ -197,6 +198,8 @@ class SparkExitWork @Inject constructor( * exit and kept as first scheduled, so later ticks do not push it back. */ fun scheduleFundingReminder(exitCreatedAt: Long, delay: Duration) { + // One reminder per exit: once it fired, later ticks of the same exit schedule none. + if (preferences.getLong(KEY_FUNDING_REMINDED, 0L) == exitCreatedAt) return val request = OneTimeWorkRequestBuilder() .setInitialDelay(delay.inWholeMilliseconds, TimeUnit.MILLISECONDS) .setInputData(workDataOf(KEY_EXIT_CREATED_AT to exitCreatedAt)) @@ -214,6 +217,7 @@ class SparkExitWork @Inject constructor( /** The reminder fired: posts the funding notification while the exit it was for still waits for funding. */ suspend fun onFundingReminder(exitCreatedAt: Long) { + preferences.edit { putLong(KEY_FUNDING_REMINDED, exitCreatedAt) } val record = runSuspendCatching { store().load() }.getOrNull() ?: return if (record.createdAt != exitCreatedAt || !SparkExitAlerts.isAwaitingFirstFunding(record)) return notify(SparkExitAlert.Funding) @@ -238,7 +242,8 @@ class SparkExitWork @Inject constructor( "Spark exit deadline alarm fired with alert '$alert' (${context.logBatterySettings()})", context = TAG, ) - if (alert == null || record?.phase != SparkExitRecord.Phase.Running) { + // A generation driven while a higher fee's payment confirms keeps the alarm, as a running one does. + if (alert == null || record?.isSendingSteps != true) { cancelDeadline() return } @@ -398,8 +403,9 @@ object SparkExitAlerts { ): SparkExitAlert? { if (record?.isActive != true) return null return when { - record.phase is SparkExitRecord.Phase.NeedsFunding -> SparkExitAlert.Funding - record.phase != SparkExitRecord.Phase.Running -> null + record.phase is SparkExitRecord.Phase.NeedsFunding && !record.isDrivingWhileFunding -> + SparkExitAlert.Funding + !record.isSendingSteps -> null record.surfacedRejection != null || (record.stuckStep?.rejections ?: 0) >= SparkExitDriver.REJECTIONS_TO_SURFACE -> SparkExitAlert.Rejected feeLowRate != null -> SparkExitAlert.FeeLow diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt index dab31b4e39..23a29118e7 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt @@ -97,6 +97,13 @@ private fun Content( ) { CircularProgressIndicator(strokeWidth = 2.dp, color = Colors.White32) } + bump.isLeavingLeaves -> BodyM( + text = stringResource(R.string.lightning__spark_exit__fee_bump_leaves_behind), + color = Colors.White64, + modifier = Modifier + .padding(horizontal = 16.dp) + .testTag("SparkExitFeeBumpLeavesBehind") + ) bump.hasError -> BodyM( text = stringResource(R.string.lightning__spark_exit__fee_bump_error), color = Colors.White64, @@ -140,7 +147,7 @@ private fun Content( .fillMaxWidth() .testTag("SparkExitFeeBumpRetry") ) - } else { + } else if (!bump.isLeavingLeaves) { PrimaryButton( text = stringResource( if (selected?.extraSats == 0uL) { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index a16abfa1f2..37db1acf69 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -27,6 +27,7 @@ import to.bitkit.models.Toast import to.bitkit.repositories.SparkExitBackgroundLimits import to.bitkit.repositories.SparkExitCancel import to.bitkit.repositories.SparkExitCancelUnreadable +import to.bitkit.repositories.SparkExitFeeBumpLeavesBehind import to.bitkit.repositories.SparkExitFeeBumpOption import to.bitkit.repositories.SparkExitFundingKey import to.bitkit.repositories.SparkExitFundingState @@ -36,6 +37,7 @@ import to.bitkit.repositories.SparkExitPrestartFunding import to.bitkit.repositories.SparkExitQuote import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitStartCancelled import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.surfacedRejection @@ -167,7 +169,8 @@ class SparkExitViewModel @Inject constructor( sparkExitRepo.start(_uiState.value.fundFromSavings) .onSuccess { _effects.emit(SparkExitEffect.Started) } .onFailure { - ToastEventBus.send(it) + // A cancel during the start already said so on progress. + if (it !is SparkExitStartCancelled) ToastEventBus.send(it) // The exit started but paying its fee funding failed: progress shows where to fund it. if (sparkExitRepo.state.value.isExiting) _effects.emit(SparkExitEffect.Started) } @@ -187,7 +190,14 @@ class SparkExitViewModel @Inject constructor( val selected = options.firstOrNull(bump::canPay)?.speed _uiState.update { it.copy(feeBump = bump.copy(selected = selected)) } } - .onFailure { _uiState.update { it.copy(feeBump = SparkExitFeeBumpUiState(hasError = true)) } } + .onFailure { error -> + val bump = if (error is SparkExitFeeBumpLeavesBehind) { + SparkExitFeeBumpUiState(isLeavingLeaves = true) + } else { + SparkExitFeeBumpUiState(hasError = true) + } + _uiState.update { it.copy(feeBump = bump) } + } } } @@ -348,6 +358,8 @@ enum class SparkExitQuoteBlock { Error, Nothing, Uneconomic } data class SparkExitFeeBumpUiState( val isLoading: Boolean = false, val hasError: Boolean = false, + /** Every higher rate would leave part of the exit on Spark, so none is offered. */ + val isLeavingLeaves: Boolean = false, val options: ImmutableList = persistentListOf(), val selected: FeeRate? = null, val spendableSats: ULong? = null, diff --git a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt index 831c8d8d8c..526d9fa147 100644 --- a/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt +++ b/app/src/main/java/to/bitkit/usecases/DeriveBalanceStateUseCase.kt @@ -20,6 +20,7 @@ import to.bitkit.models.safe import to.bitkit.models.toBalance import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.TransferRepo import to.bitkit.utils.Logger @@ -35,6 +36,7 @@ class DeriveBalanceStateUseCase @Inject constructor( private val settingsStore: SettingsStore, private val hwWalletRepo: HwWalletRepo, private val sparkRepo: SparkRepo, + private val sparkExitRepo: SparkExitRepo, ) { suspend operator fun invoke(): Result = withContext(bgDispatcher) { runCatching { @@ -52,7 +54,9 @@ class DeriveBalanceStateUseCase @Inject constructor( val channelFundableBalance = getMaxChannelFundableAmount(lightningRepo.getChannelFundableBalance()) val afterPendingChannels = balanceDetails.totalLightningBalanceSats.safe() - pendingChannelsSats.safe() val afterClosingChannels = afterPendingChannels.safe() - toSavingsAmount.safe() - val sparkSats = sparkRepo.state.value.spendingSats + // During an exit, Spark's value outside it stays on Spark. + val sparkSats = sparkRepo.state.value.spendingSats.safe() + + (sparkExitRepo.state.value.outsideExitSats ?: 0uL).safe() val sparkExitSats = getSparkExitSats(activeTransfers) val afterLingeringCoopClose = afterClosingChannels.safe() - lingeringCoopCloseSats.safe() val totalLightningSats = afterLingeringCoopClose.safe() + sparkSats.safe() @@ -120,10 +124,20 @@ class DeriveBalanceStateUseCase @Inject constructor( return toSavingsAmount } - /** A Spark emergency exit has no channel: its amount is in transfer until the exit settles it. */ - private fun getSparkExitSats(transfers: List): ULong = transfers - .filter { it.type == TransferType.SPARK_EXIT } - .fold(0uL) { sum, transfer -> sum.safe() + transfer.amountSats.toULong().safe() } + /** + * A Spark emergency exit has no channel: what it still brings to savings is in transfer until the exit settles + * it. The running exit's own transfer counts only that, not funding nobody paid or value savings already has. + */ + private fun getSparkExitSats(transfers: List): ULong { + val exit = sparkExitRepo.state.value + return transfers + .filter { it.type == TransferType.SPARK_EXIT } + .fold(0uL) { sum, transfer -> + val sats = exit.inTransferSats?.takeIf { exit.record?.transferId == transfer.id } + ?: transfer.amountSats.toULong() + sum.safe() + sats.safe() + } + } private suspend fun getMaxChannelFundableAmount(fundableBalance: ULong): ULong { if (fundableBalance == 0uL) return 0u diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 59445afbae..c500381009 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -248,6 +248,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index d166792033..58802a012a 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -255,6 +255,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 3b85b001cc..a4824e6de7 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -252,6 +252,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 691e09325f..bdb5514515 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -255,6 +255,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3de9867d63..59d4852a27 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -132,6 +132,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 3641c7db63..c9482786cc 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -248,6 +248,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index cd4cf22e41..cb5b6f0079 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -254,6 +254,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 1799189c2c..12cf7ca8c8 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -196,6 +196,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 777fd2a96a..dd7cf82594 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -131,6 +131,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index d76a2ea495..1c99eee7d6 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -253,6 +253,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 7f6f289996..3d6e924598 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -252,6 +252,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 296b03d8dd..e66269ce5b 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -133,6 +133,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 0ad012fe22..e293996295 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -256,6 +256,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index d9cea4c7a5..675ed4136e 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -128,6 +128,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index c32579f4a3..eb7f6dbe8e 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -264,6 +264,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index d1be4eb13c..9a7836bd51 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -413,6 +413,7 @@ Pay a higher fee Use this fee Could not price a higher fee. Try again. + A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. {rate} sat/vB This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. Pay a\n<accent>higher fee</accent> diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt index c963b111ef..06528162f6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt @@ -32,6 +32,13 @@ class SparkExitAlertsTest { ) assertEquals(SparkExitAlert.Rejected, SparkExitAlerts.reason(refused, isOnline = false, unlimited)) assertEquals(SparkExitAlert.Offline, SparkExitAlerts.reason(running, isOnline = false, unlimited)) + // A generation driven while a higher fee's payment confirms falls behind like a running one. + val bumped = running.adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))), 0L) + .applyFeeBump(rate = 9uL, extraSats = 6_000uL, paymentTxid = "bump") + assertTrue(bumped.isDrivingWhileFunding && bumped.isSendingSteps) + assertEquals(SparkExitAlert.Offline, SparkExitAlerts.reason(bumped, isOnline = false, unlimited)) + val awaiting = SparkExitFixtures.record(SparkExitRecord.Phase.NeedsFunding(9_000uL)) + assertEquals(SparkExitAlert.Funding, SparkExitAlerts.reason(awaiting, isOnline = false, unlimited)) assertEquals( SparkExitAlert.Restricted, SparkExitAlerts.reason(running, isOnline = true, unlimited.copy(isRestricted = true, isOptimized = true)), diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 54a9528ffd..aec2021eea 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -27,6 +27,7 @@ import to.bitkit.ui.settings.lightning.SparkExitUiState import to.bitkit.utils.SignedTransactionId import java.io.File import kotlin.test.assertEquals +import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotNull @@ -38,6 +39,7 @@ class SparkExitDriverTest : BaseUnitTest() { private companion object { const val SWEEP_DESTINATION = "bcrt1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqc8gma6" const val SWEEP_FUNDING = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + val BUMP = "be".repeat(32) val UNPAID = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 0 < 17") } @@ -469,12 +471,12 @@ class SparkExitDriverTest : BaseUnitTest() { // Two coins: the second adds its own input fee too. chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = funded.map { SparkExitFixtures.utxo(requireNotNull(it.txid), value = requireNotNull(it.valueSats)) - } + listOf(SparkExitFixtures.utxo("t1", value = 200uL), SparkExitFixtures.utxo("t2", value = 121uL)) + } + listOf(SparkExitFixtures.utxo("t1", value = 150uL), SparkExitFixtures.utxo("t2", value = 121uL)) record = driver().tick(record) assertEquals(Phase.NeedsFunding(9_221uL), record.phase) chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = funded.map { SparkExitFixtures.utxo(requireNotNull(it.txid), value = requireNotNull(it.valueSats)) - } + listOf(SparkExitFixtures.utxo("t1", value = 200uL), SparkExitFixtures.utxo("t2", value = 122uL)) + } + listOf(SparkExitFixtures.utxo("t1", value = 150uL), SparkExitFixtures.utxo("t2", value = 172uL)) sdk.recoverError = null sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) record = driver().tick(record) @@ -855,20 +857,22 @@ class SparkExitDriverTest : BaseUnitTest() { } @Test - fun `a higher fee leaves a leaf the build refuses behind on a copy and prices the rest`() = test { + fun `a higher fee at which a leaf can't pay its own exit is refused, the live exit unchanged`() = test { val record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) .copy(leafIds = listOf("leaf-1", "leaf-2")) sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-1", "leaf-2")) - sdk.preparedResponses += SparkExitFixtures.prepared(leaves = listOf("leaf-1", "leaf-2")) - sdk.preparedResponses += SparkExitFixtures.prepared(leaves = listOf("leaf-2")) - sdk.recoverErrors += ladderRefusal("leaf-1") - sdk.recoverError = SdkException.InsufficientCpfpFunds(26_000uL, "") + // Refused by the build at this rate. + sdk.recoverError = ladderRefusal("leaf-1") chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", value = 20_000uL)) - assertEquals(6_612uL, driver().feeBumpShortfall(record, 9uL)) + val refused = assertFailsWith { driver().feeBumpShortfall(record, 9uL) } + assertEquals(100_000uL, refused.sats) + + // Refused by the prepare at this rate. + sdk.recoverError = null + sdk.prepareErrors += ladderRefusal("leaf-2") + assertFailsWith { driver().feeBumpShortfall(record, 9uL) } - assertEquals(listOf("leaf-2"), (sdk.prepareRequests.last().selection as ExitLeafSelection.Specific).leafIds) - // The live exit keeps its leaves. assertEquals(listOf("leaf-1", "leaf-2"), record.exitLeafIds) assertTrue(saved.isEmpty()) } @@ -1060,6 +1064,76 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(1, requireNotNull(store.load()).broadcastLog.single().attempts) } + @Test + fun `without the sdk an exit whose every step confirmed ends done`() = test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + chain.confirmedTxids = setOf("n1") + + val record = driver(withSdk = false, tip = 1_000u).tick(running(recovery)) + + assertEquals(Phase.Done, record.phase) + assertTrue(chain.broadcasts.isEmpty()) + } + + @Test + fun `without the sdk an exit whose steps confirmed with failed leaves keeps running for their retry`() = test { + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1")), failed = listOf(operatorsDown)) + chain.confirmedTxids = setOf("n1") + + val record = driver(withSdk = false, tip = 1_000u).tick(running(recovery)) + + assertEquals(Phase.Running, record.phase) + } + + @Test + fun `an exit that ended with a savings payment unresolved watches it and sweeps it once it arrives`() = test { + chain.utxosByAddress[SWEEP_FUNDING] = emptyList() + val ended = SparkExitFixtures.record(Phase.Done).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + fundingPaymentTxid = BUMP, + ) + assertTrue(ended.needsDriving) + + var record = driver(tip = 1_000u).tick(ended) + assertEquals(1_000u, record.fundingPaymentSeenAtHeight) + assertTrue(record.needsDriving) + + val payment = SparkExitFixtures.utxo(BUMP, 0u, 6_000uL) + chain.utxosByAddress[SWEEP_FUNDING] = listOf(payment) + record = driver(tip = 1_001u).tick(record) + + assertEquals(listOf(SparkExitRecord.Leftover(BUMP, 0u, 6_000uL)), record.leftover) + assertNull(record.fundingPaymentTxid) + assertNotNull(assertNotNull(record.leftoverSweep).txHex) + + // One no host ever sees is forgotten after a block, and the exit stops. + chain.unknownTxids = setOf("gone") + var forgotten = driver(tip = 1_000u).tick(ended.copy(fundingPaymentTxid = "gone")) + forgotten = driver(tip = 1_001u).tick(forgotten) + assertNull(forgotten.fundingPaymentTxid) + assertFalse(forgotten.needsDriving) + } + + @Test + fun `a sweep past the day's wait for unconfirmed funding spends only the confirmed outputs`() = test { + val confirmed = SparkExitFixtures.utxo("c1".repeat(32), 0u, 25_000uL) + val unconfirmed = SparkExitFixtures.utxo("d1".repeat(32), 0u, 10_000uL, confirmed = false) + chain.utxosByAddress[SWEEP_FUNDING] = listOf(confirmed, unconfirmed) + val done = SparkExitFixtures.record(Phase.Done).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + leftover = listOf(SparkExitRecord.Leftover(confirmed.txid, 0u, 25_000uL)), + ) + + var record = driver(tip = 1_000u).tick(done) + assertTrue(record.isLeftoverWaitingForFees) + record = driver(tip = 1_144u).tick(record) + + val sweep = assertNotNull(record.leftoverSweep) + assertEquals(listOf(confirmed.txid), SparkExitTxInputs.decode(assertNotNull(sweep.txHex))?.map { it.prevTxid }) + } + @Test fun `without the sdk broadcasts steps whose parents confirmed and timelocks matured`() = test { var record = running( diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 7dbcf322ef..fea2782fa4 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -243,6 +243,17 @@ class SparkExitFundingTest { assertEquals(listOf("big", "small"), SparkExitMath.fundingTopUp(utxos, requiredSats = 2_999uL)?.map { it.txid }) assertNull(SparkExitMath.fundingTopUp(utxos, requiredSats = 3_000uL)) assertNull(SparkExitMath.fundingTopUp(emptyList(), requiredSats = 0uL)) + // At 20 sat/vB a 294-sat coin costs more than it adds: the 10,000-sat coin alone funds 10,000. + val withDust = listOf( + SparkExitFixtures.utxo("dust", value = 294uL), + SparkExitFixtures.utxo("coin", value = 10_000uL) + ) + val inputFee = SparkExitMath.inputFeeSats(20uL) + assertEquals( + listOf("coin"), + SparkExitMath.fundingTopUp(withDust, requiredSats = 10_000uL, inputFeeSats = inputFee)?.map { it.txid }, + ) + assertNull(SparkExitMath.fundingTopUp(withDust, requiredSats = 10_001uL, inputFeeSats = inputFee)) } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 09fe895c06..3094406144 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -68,8 +68,9 @@ class SparkExitRepoTest : BaseUnitTest() { val tempFolder = TemporaryFolder() private val transferRepo = mock() + private val wiped = MutableSharedFlow(extraBufferCapacity = 1) private val sparkRepo = mock { - on { walletWiped } doReturn MutableSharedFlow() + on { walletWiped } doReturn wiped on { walletIndex } doReturn 0 on { state } doReturn MutableStateFlow(SparkState()) } @@ -183,7 +184,11 @@ class SparkExitRepoTest : BaseUnitTest() { } /** Spark's regtest mempool, where nothing is confirmed yet and every single transaction is accepted. */ - private fun regtestMempool(posts: MutableList, refusal: String? = null) = HttpClient( + private fun regtestMempool( + posts: MutableList, + refusal: String? = null, + refusalStatus: HttpStatusCode = HttpStatusCode.BadRequest, + ) = HttpClient( MockEngine.create { dispatcher = testDispatcher addHandler { request -> @@ -191,7 +196,7 @@ class SparkExitRepoTest : BaseUnitTest() { when { request.method == HttpMethod.Post && url.endsWith("/api/tx") -> { posts += String(request.body.toByteArray()) - if (refusal != null) return@addHandler respond(refusal, HttpStatusCode.BadRequest) + if (refusal != null) return@addHandler respond(refusal, refusalStatus) respond(String(request.body.toByteArray()).removePrefix("02")) } url.endsWith("/blocks/tip/height") -> respond("1000") @@ -293,6 +298,68 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(store.load(), sut.state.value.record) } + @Test + fun `a background run whose steps no host takes for now never pushes the deadline back`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + val recovery = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + store.save(SparkExitFixtures.record(Phase.Running).adopt(recovery, 0L)) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) + val posts = mutableListOf() + + repeat(2) { + val spark = coldSpark(FakeSparkExitRecovering(), connects = false) + val mempool = regtestMempool(posts, "busy", HttpStatusCode.ServiceUnavailable) + createSut(spark, mempool).runInBackground().getOrThrow() + } + + assertTrue(posts.isNotEmpty()) + assertNotNull(store.load()?.unpublishedStep) + verify(work, never()).armDeadline(any(), any()) + } + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a wipe waits for the tick in flight and deletes what it saved`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(runningRecord()) + val gate = CompletableDeferred() + val chain = HttpClient( + MockEngine.create { + dispatcher = testDispatcher + addHandler { request -> + val url = request.url.toString() + when { + url.endsWith("/blocks/tip/height") -> { + gate.await() + respond("1000") + } + url.endsWith("/address/$funding/utxo") -> respond("[]") + url.endsWith("/fee-estimates") -> respond("""{"1":9,"3":6,"144":1}""") + else -> throw IOException("unreachable '$url'") + } + } + }, + ) { defaultRequest { contentType(ContentType.Application.Json) } } + val sdk = FakeSparkExitRecovering().apply { + checks += CheckRecoverFundsResponse(runningRecord().recovery!!, RecoveryVerdict.Valid) + } + val sut = quotedSut(sdk, chain) + sut.load().getOrThrow() + + val tick = async { sut.tick() } + runCurrent() + wiped.emit(0) + gate.complete(Unit) + tick.await() + runCurrent() + + assertNull(store.load()) + assertNull(sut.state.value.record) + verify(work, atLeastOnce()).cancelAll() + } + @Test fun `a background run whose steps keep being refused lets the deadline alarm fire`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) @@ -580,6 +647,34 @@ class SparkExitRepoTest : BaseUnitTest() { sut.onAppBackgrounded() } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a cancel during the start's optimization wait ends the exit before anything is paid`() = test { + stubFunding { Result.success(OnchainSendOutcome.Accepted("paid")) } + val gate = CompletableDeferred() + whenever(sparkRepo.awaitOptimizationIdle()).doSuspendableAnswer { gate.await() } + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + + val start = async { sut.start(fundFromSavings = true) } + runCurrent() + assertTrue(sut.canCancel) + assertEquals(SparkExitCancel.Cancelled, sut.cancel().getOrThrow()) + gate.complete(Unit) + + assertIs(start.await().exceptionOrNull()) + assertNull(SparkExitStore(File(Env.sparkExitRecordPath(0))).load()) + assertNull(sut.state.value.record) + verify(transferRepo).markSettled("transfer-1") + verify(lightning, never()).sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + verify(sparkRepo, never()).setExiting(true, true) + } + @Test fun `a leaf swap between the quote and the start quotes the exit again`() = test { val sdk = FakeSparkExitRecovering() @@ -752,7 +847,7 @@ class SparkExitRepoTest : BaseUnitTest() { } @Test - fun `fee bump rates are priced without broadcasting, leaving a leaf the sdk refuses behind`() = test { + fun `fee bump rates are priced without broadcasting, leaving out a rate the sdk refuses a leaf at`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) store.save(runningRecord()) val sdk = FakeSparkExitRecovering().apply { @@ -764,8 +859,13 @@ class SparkExitRepoTest : BaseUnitTest() { val options = sut.feeBumpOptions().getOrThrow() - assertEquals(listOf(FeeRate.FAST to 9uL, FeeRate.NORMAL to 6uL), options.map { it.speed to it.rateSatPerVbyte }) - assertTrue(options.all { it.totalSats == 0uL }) + assertEquals(listOf(FeeRate.NORMAL to 6uL), options.map { it.speed to it.rateSatPerVbyte }) + assertEquals(0uL, options.single().totalSats) + + // No rate left that every leaf can pay its exit at: that is the error. + val refusal = "Leaf leaf-1 cannot be exited: its refund cannot pay its fee" + repeat(2) { sdk.prepareErrors += SdkException.SparkException(refusal) } + assertIs(sut.feeBumpOptions().exceptionOrNull()) assertTrue(sdk.recoverRequests.isEmpty()) } } diff --git a/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt index 800be7030a..438a4794e6 100644 --- a/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt @@ -23,6 +23,9 @@ import to.bitkit.models.TransferType import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState +import to.bitkit.repositories.SparkExitFixtures +import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SparkState import to.bitkit.repositories.TransferRepo @@ -38,6 +41,8 @@ class DeriveBalanceStateUseCaseTest : BaseUnitTest() { private val settingsStore: SettingsStore = mock() private val hwWalletRepo: HwWalletRepo = mock() private val sparkRepo: SparkRepo = idleSparkRepo() + private val sparkExitState = MutableStateFlow(SparkExitState()) + private val sparkExitRepo = mock { on { state } doReturn sparkExitState } private lateinit var sut: DeriveBalanceStateUseCase @@ -65,6 +70,7 @@ class DeriveBalanceStateUseCaseTest : BaseUnitTest() { settingsStore = settingsStore, hwWalletRepo = hwWalletRepo, sparkRepo = sparkRepo, + sparkExitRepo = sparkExitRepo, ) } @@ -84,6 +90,33 @@ class DeriveBalanceStateUseCaseTest : BaseUnitTest() { assertEquals(20_000uL, balanceState.balanceInTransferToSpending) } + @Test + fun `should count a spark exit's value still on its way and spark's value outside it`() = test { + newBalanceDetails() + whenever(lightningRepo.getChannels()).thenReturn(emptyList()) + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isReady = true, balanceSats = 130_000uL, isExiting = true)), + ) + val transfer = newTransferEntity(type = TransferType.SPARK_EXIT, amountSats = 120_000L).copy(id = "exit-1") + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer))) + // Expects 120,000 back, 20,000 of it the first fee funding, of which 5,000 reached the address so far. + sparkExitState.value = SparkExitState( + record = SparkExitFixtures.record().copy( + transferId = "exit-1", + expectedSats = 120_000uL, + leafTotalSats = 100_000uL, + ), + fundingSeenSats = 5_000uL, + sparkBalanceSats = 130_000uL, + ) + + val balanceState = sut().getOrThrow() + + assertEquals(105_000uL, balanceState.balanceInTransferToSavings) + // Lightning's 50,000 plus the 30,000 Spark holds beyond the exit's leaves. + assertEquals(80_000uL, balanceState.totalLightningSats) + } + @Test fun `should subtract estimated fee from channelFundableBalance`() = test { val fundableBalance = 75_000uL From 3425c85af197d37ca48b505e0b574b394700a43f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 7 Nov 2026 02:53:58 +0100 Subject: [PATCH 030/154] fix: count spark exit payouts only once confirmed --- .../to/bitkit/repositories/SparkExitRepo.kt | 5 +++- .../repositories/SparkExitFundingTest.kt | 23 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 175a1c17ba..424516b643 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -939,7 +939,10 @@ data class SparkExitState( val inTransferSats: ULong? get() { val exit = record ?: return null - val received = SparkExitMath.receivedSats(exit) ?: 0uL + // Reached only once its sweep or cooperative step confirmed: the plan lists the sweep from the first build. + val confirmed = exit.recovery?.let { SparkExitMath.confirmedReceived(it, exit.destination) }.orEmpty() + val received = (exit.earlierReceivedSats + confirmed).values + .fold(0uL) { sum, sats -> sum.safe() + sats.safe() } val unpaid = (exit.phase as? SparkExitRecord.Phase.AwaitingFunding) ?.takeIf { exit.fundingPaymentTxid == null } ?.let { it.requiredSats.safe() - maxOf(exit.fundedSats, fundingSeenSats).safe() } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index fea2782fa4..14c6bcf488 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -168,6 +168,29 @@ class SparkExitFundingTest { assertEquals(95_000uL, SparkExitMath.receivedSats(record.copy(recovery = relisted))) } + @Test + fun `an exit's value is in transfer until its sweep confirms, from the first build on`() { + val address = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + val script = AddressScript.of(address) + // One output of 90,000 to the destination. + val hex = "02000000" + "01" + "11".repeat(32) + "00000000" + "00" + "ffffffff" + "01" + + "905f010000000000" + "%02x".format(script.size) + script.toHexString() + "00000000" + val sweep = SparkExitFixtures.tx("s", kind = RecoveryTxKind.SWEEP).copy(txHex = hex) + val built = SparkExitFixtures.record(SparkExitRecord.Phase.Running) + .copy(destination = address, expectedSats = 95_000uL) + .adopt(SparkExitFixtures.recovery(listOf(sweep)), 1L) + + // The plan lists the sweep from the first build: nothing reached savings yet. + assertEquals(95_000uL, SparkExitState(record = built).inTransferSats) + + val landed = built.copy( + recovery = built.recovery?.copy( + transactions = listOf(sweep.copy(status = ExitTransactionStatus.Confirmed(900u))), + ), + ) + assertEquals(5_000uL, SparkExitState(record = landed).inTransferSats) + } + @Test fun `a wait for a leaf that may still move tries again at doubling gaps up to a day and ends after a week`() { assertFalse(SparkExitMath.isRetryDue(since = 1_000u, retriedAt = 1_000u, tip = 1_005u)) From 4d19f456165683894d51f45dbde5351ab635a6c1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 11:49:36 +0100 Subject: [PATCH 031/154] fix: pay at most the confirmed exit funding from savings --- .../to/bitkit/repositories/SparkExitRepo.kt | 4 +++- .../bitkit/repositories/SparkExitRepoTest.kt | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 424516b643..b5c586deab 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -702,7 +702,9 @@ class SparkExitRepo @Inject constructor( // Driven before paying, so a failed payment from savings still leaves the exit watching its address. scope.launch { tick() } onAppForegrounded() - if (fundFromSavings && quote.fundingSats > 0uL) payFunding(createdAt, key.address, quote.fundingSats) + // Savings pays at most what the user confirmed: Progress asks for the rest of a higher fresh amount. + val savingsSats = minOf(quote.fundingSats, pending.quote.fundingSats) + if (fundFromSavings && savingsSats > 0uL) payFunding(createdAt, key.address, savingsSats) } /** The exit created at [createdAt] is still the one on record and running: no cancel or wipe ended it. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 3094406144..361c75125e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -691,6 +691,27 @@ class SparkExitRepoTest : BaseUnitTest() { sut.onAppBackgrounded() } + @Test + fun `savings never pays more than the confirmed funding when the start quotes again`() = test { + stubFunding { Result.success(OnchainSendOutcome.Accepted("paid")) } + val sdk = FakeSparkExitRecovering() + val sut = quotedSut(sdk) + val shown = sut.loadQuote().getOrThrow().fundingSats + sdk.preparedResponse = SparkExitFixtures.prepared(funding = 35_000uL, leaves = listOf("leaf-1", "leaf-2")) + + sut.start(fundFromSavings = true).getOrThrow() + // Stops the foreground loop even when the check fails, or runTest drives it forever. + sut.onAppBackgrounded() + + assertEquals(20_000uL, shown) + verify(lightning).sendOnChain( + eq(funding), eq(shown), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + } + private fun awaitingRecord(paidTxid: String? = null) = SparkExitFixtures.record().copy( funding = listOf(SparkExitRecord.Funding(0u, funding, "02ab")), fundingPaymentTxid = paidTxid, From ba3ed06c2036e9611677a89d5762a36457cddaeb Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 11:49:40 +0100 Subject: [PATCH 032/154] fix: cap the refused leftover sweep rate at the next block's --- .../to/bitkit/repositories/SparkExitDriver.kt | 10 +++++++++- .../bitkit/repositories/SparkExitDriverTest.kt | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 180e493959..383defe52a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -656,7 +656,11 @@ class SparkExitDriver( val total = all.fold(0uL) { sum, input -> sum.safe() + input.valueSats.safe() } return current.copy(leftoverSweep = SparkExitRecord.LeftoverSweep(null, null, total, isDustKept = true)) } - val floor = built?.takeIf { it.isWaitingForFees }?.refusedFeeRate ?: 0uL + val refused = built?.takeIf { it.isWaitingForFees }?.refusedFeeRate ?: 0uL + // A refusal raises the rate up to the next block's or the exit's, never above: a node asking more is refused + // again, and the sweep waits a block for fees to drop. + val cap = if (refused > 0uL) maxOf(nextBlockRate() ?: 0uL, record.feeRateSatPerVbyte) else 0uL + val floor = minOf(refused, cap) val rate = maxOf(SparkExitMath.sweepFeeRate(economyRate(), record.feeRateSatPerVbyte), floor) val inputs = SparkExitSweep.worthSweeping( confirmed.map { SparkExitSweep.Input(it.txid, it.vout, it.value) }, @@ -718,6 +722,10 @@ class SparkExitDriver( ) } + private suspend fun nextBlockRate(): ULong? = runSuspendCatching { chain.nextBlockFeeRate() } + .onFailure { Logger.warn("Failed to read the next-block fee rate for the leftover sweep", it, context = TAG) } + .getOrNull() + private suspend fun economyRate(): ULong? = runSuspendCatching { chain.economyFeeRate() } .onFailure { Logger.warn("Failed to read the economy fee rate for the leftover sweep", it, context = TAG) } .getOrNull() diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index aec2021eea..0266891dd6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1472,6 +1472,23 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(3uL, SparkExitSweep.refusedFeeRate("insufficient fee", 2uL)) } + @Test + fun `a host's refusal cannot push the leftover sweep above the network's next-block rate`() = test { + // A host answers a 1 sat/vB sweep with an absurd ask: 22,000 sats for a ~110 vB transaction. + chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 110 < 22000") + var record = driver(tip = 1_000u).tick(sweepDone()) + record = driver(tip = 1_000u).tick(record) + chain.outcome = SparkExitBroadcastOutcome.Accepted + record = driver(tip = 1_001u).tick(record) + + val sent = assertNotNull(record.leftoverSweep) + assertTrue( + (sent.feeRateSatPerVbyte ?: 0uL) <= chain.nextBlockRate!!, + "sweep rate '${sent.feeRateSatPerVbyte}' sat/vB, next block '${chain.nextBlockRate}', " + + "leftover 25000 sats, swept '${sent.valueSats}' sats", + ) + } + @Test fun `a leftover sweep refused for another reason is final`() = test { chain.outcome = SparkExitBroadcastOutcome.Rejected("bad-txns-nonstandard-inputs") From c554a0185c73e416e831afe415a5358b99584e48 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 11:49:44 +0100 Subject: [PATCH 033/154] feat: show the savings payment fee and total on exit confirm --- .../ui/settings/lightning/SparkExitComponents.kt | 9 +++++++++ .../ui/settings/lightning/SparkExitConfirmScreen.kt | 3 +++ .../bitkit/ui/settings/lightning/SparkExitViewModel.kt | 9 +++++++++ app/src/main/res/values/strings.xml | 2 ++ .../ui/settings/lightning/SparkExitViewModelTest.kt | 10 ++++++++++ 5 files changed, 33 insertions(+) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt index 97dd02fdc8..62d58dceeb 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -56,6 +56,15 @@ internal fun SparkExitQuoteRows(quote: SparkExitQuote) { } } +/** What paying the fee funding from savings costs: the fee of that payment and all that leaves savings. */ +@Composable +internal fun SparkExitSavingsRows(feeSats: ULong, totalSats: ULong) { + Column { + SparkExitAmountRow(stringResource(R.string.lightning__spark_exit__savings_fee), feeSats) + SparkExitAmountRow(stringResource(R.string.lightning__spark_exit__savings_total), totalSats) + } +} + @Composable private fun SparkExitAmountRow(label: String, sats: ULong) { SectionRow(name = label, valueContent = { MoneyCaptionB(sats = sats.toLong(), symbol = true) }) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt index e9f6c0bbf6..a70e45cc0d 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt @@ -75,6 +75,9 @@ private fun Content( ) VerticalSpacer(32.dp) uiState.quote?.let { SparkExitQuoteRows(it) } + uiState.savingsTotalSats?.let { total -> + uiState.savingsFeeSats?.let { fee -> SparkExitSavingsRows(fee, total) } + } VerticalSpacer(32.dp) } Column(modifier = Modifier.padding(horizontal = 16.dp)) { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index 37db1acf69..4c4c1c6af8 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -24,6 +24,7 @@ import to.bitkit.R import to.bitkit.env.Env import to.bitkit.models.FeeRate import to.bitkit.models.Toast +import to.bitkit.models.safe import to.bitkit.repositories.SparkExitBackgroundLimits import to.bitkit.repositories.SparkExitCancel import to.bitkit.repositories.SparkExitCancelUnreadable @@ -292,6 +293,14 @@ data class SparkExitUiState( val networkFees: SparkExitNetworkFees? = null, val feeBump: SparkExitFeeBumpUiState = SparkExitFeeBumpUiState(), ) { + /** What leaves savings when it pays the fee funding: the funding and the fee of the payment that sends it. */ + val savingsTotalSats: ULong? + get() { + val fundingSats = quote?.fundingSats?.takeIf { fundFromSavings && it > 0uL } ?: return null + val feeSats = savingsFeeSats ?: return null + return fundingSats.safe() + feeSats.safe() + } + /** Progress offers Pay a higher fee. */ val canPayHigherFee: Boolean get() = record?.canPayHigherFee(tipHeight, networkFees) == true diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 9a7836bd51..5e3d04c849 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -477,6 +477,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 0da74c1de2..9e8a255f82 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -117,6 +117,16 @@ class SparkExitViewModelTest : BaseUnitTest() { assertEquals("sweep", SparkExitUiState(record = done).sweepTxid) } + @Test + fun `confirm shows what leaves savings only when savings pays the fee funding`() { + val quote = SparkExitQuote(SparkExitFixtures.prepared(funding = 20_000uL)) + val state = SparkExitUiState(quote = quote, savingsFeeSats = 300uL, fundFromSavings = true) + + assertEquals(20_300uL, state.savingsTotalSats) + assertNull(state.copy(fundFromSavings = false).savingsTotalSats) + assertNull(state.copy(savingsFeeSats = null).savingsTotalSats) + } + @Test fun `progress asks for at least dust before the funding address was read`() { val record = SparkExitFixtures.record(SparkExitRecord.Phase.NeedsFunding(68uL)) From ea47b000a668cacbcab15174e760a0e32f550826 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 13:11:18 +0100 Subject: [PATCH 034/154] fix: watch a higher fee paid after the spark exit ended --- .../to/bitkit/repositories/SparkExitRepo.kt | 17 +++--- .../bitkit/repositories/SparkExitRepoTest.kt | 54 +++++++++++++++++++ 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index b5c586deab..68430ac59b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -556,12 +556,17 @@ class SparkExitRepo @Inject constructor( return@withLock } if (!current.isActive) { - // The exit ended while savings paid: the payment is leftover the sweep sends back to savings. - Logger.warn("Sweeping a higher fee paid after the Spark exit ended", context = TAG) - val pending = txid?.let { listOf(SparkExitRecord.Leftover(it, 0u, option.extraSats)) }.orEmpty() - val swept = current.copy(leftover = current.leftover + pending, leftoverSweep = null) - saveRecord(swept) - _state.update { it.copy(record = swept) } + // The exit ended while savings paid: the payment is watched until its outputs reach the address, then + // joins the leftover the sweep sends back to savings. + val paid = txid ?: return@withLock + Logger.warn("Watching higher fee '$paid' paid after the Spark exit ended", context = TAG) + val watched = current.copy( + fundingPaymentTxid = paid, + fundingPaymentSeenAtHeight = null, + fundingPaymentMissingSince = null, + ) + saveRecord(watched) + _state.update { it.copy(record = watched) } return@withLock } val bumped = current.applyFeeBump(option.rateSatPerVbyte, option.extraSats, txid) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 361c75125e..0adccd0f02 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -867,6 +867,60 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(ended.payHigherFee(option).isFailure) } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a higher fee paid while the exit ends is watched until its outputs reach the address`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(runningRecord()) + val gate = CompletableDeferred() + stubFunding { + gate.await() + Result.success(OnchainSendOutcome.Accepted("bump")) + } + var utxos = "[]" + val http = HttpClient( + MockEngine.create { + dispatcher = testDispatcher + addHandler { request -> + val url = request.url.toString() + when { + url.endsWith("/address/$funding/utxo") -> respond(utxos) + url.endsWith("/blocks/tip/height") -> respond("1000") + url.endsWith("/fee-estimates") -> respond("""{"1":9,"3":6,"144":1}""") + url.endsWith("/tx/bump/hex") -> respond("02bump") + else -> throw IOException("unreachable '$url'") + } + } + }, + ) { defaultRequest { contentType(ContentType.Application.Json) } } + val sdk = FakeSparkExitRecovering().apply { + checks += CheckRecoverFundsResponse(runningRecord().recovery!!, RecoveryVerdict.Done) + } + val sut = quotedSut(sdk, http) + sut.load().getOrThrow() + + val payment = async { sut.payHigherFee(SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 6_000uL, 6_400uL)) } + advanceUntilIdle() + // A tick ends the exit while savings sends, before any of the payment reached the address. + sut.tick().getOrThrow() + assertEquals(Phase.Done, sut.state.value.record?.phase) + gate.complete(Unit) + payment.await().getOrThrow() + advanceUntilIdle() + + val watching = assertNotNull(store.load()) + assertTrue(watching.needsDriving) + assertEquals("bump", watching.fundingPaymentTxid) + assertTrue(watching.leftover.isEmpty()) + + utxos = """[{"txid":"bump","vout":1,"value":6000,"status":{"confirmed":true}}]""" + sut.tick().getOrThrow() + + val record = assertNotNull(store.load()) + assertEquals(listOf(SparkExitRecord.Leftover("bump", 1u, 6_000uL)), record.leftover) + assertTrue(record.needsDriving) + } + @Test fun `fee bump rates are priced without broadcasting, leaving out a rate the sdk refuses a leaf at`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) From 3e16b69945f1f825280c8b49b09697cf10092b49 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 13:11:19 +0100 Subject: [PATCH 035/154] fix: keep the spark exit transfer while failed leaves retry --- .../to/bitkit/repositories/SparkExitRepo.kt | 6 ++- .../bitkit/repositories/SparkExitRepoTest.kt | 48 ++++++++++++++++++- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 68430ac59b..ddcaef31d8 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -320,7 +320,11 @@ class SparkExitRepo @Inject constructor( } val transferId = record.transferId ?: return if (transferRepo.isSettled(transferId).getOrDefault(true)) return - if (!record.isActive || sweepActivity != null) transferRepo.markSettled(transferId) + // Leaves the operators could not co-sign are still on their way to savings while retried: the transfer keeps + // counting them, less what already confirmed. + if (!record.isActive || (sweepActivity != null && !record.isRetryingFailedLeaves)) { + transferRepo.markSettled(transferId) + } } private suspend fun settleOrphanedTransfers(record: SparkExitRecord?) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 0adccd0f02..4aa25c8d8f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -2,10 +2,14 @@ package to.bitkit.repositories import breez_sdk_spark.CheckRecoverFundsResponse import breez_sdk_spark.CpfpFundingStrategy +import breez_sdk_spark.ExitTransactionStatus import breez_sdk_spark.RecoveryRedoReason +import breez_sdk_spark.RecoveryTxKind import breez_sdk_spark.RecoveryVerdict import breez_sdk_spark.SdkException import com.synonym.bitkitcore.GetAddressResponse +import com.synonym.bitkitcore.OnchainActivity +import com.synonym.bitkitcore.PaymentType import io.ktor.client.HttpClient import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.respond @@ -46,6 +50,7 @@ import to.bitkit.data.CacheStore import to.bitkit.data.entities.TransferEntity import to.bitkit.data.keychain.Keychain import to.bitkit.env.Env +import to.bitkit.ext.create import to.bitkit.models.FeeRate import to.bitkit.models.TransferType import to.bitkit.repositories.SparkExitRecord.Phase @@ -88,6 +93,7 @@ class SparkExitRepoTest : BaseUnitTest() { keychain: Keychain = mock(), coreService: CoreService = mock(), lightningRepo: LightningRepo = mock(), + activityRepo: ActivityRepo = mock(), ) = SparkExitRepo( work = work, bgDispatcher = testDispatcher, @@ -95,7 +101,7 @@ class SparkExitRepoTest : BaseUnitTest() { sparkRepo = sparkRepo, lightningRepo = lightningRepo, transferRepo = transferRepo, - activityRepo = mock(), + activityRepo = activityRepo, coreService = coreService, keychain = keychain, httpClient = httpClient, @@ -165,6 +171,46 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(original, File(file.parentFile, "spark-exit.unreadable-1800000000000.json").readText()) } + @Test + fun `a confirmed sweep settles the transfer, but not while failed cooperative leaves are retried`() = test { + val sweep = SparkExitFixtures.tx( + "s", + kind = RecoveryTxKind.SWEEP, + status = ExitTransactionStatus.Confirmed(50u), + ) + val running = SparkExitFixtures.record(Phase.Running).adopt(SparkExitFixtures.recovery(listOf(sweep)), 0L) + val activity = OnchainActivity.create( + walletId = "wallet0", + id = "sweep", + txType = PaymentType.RECEIVED, + txId = "s", + value = 90_000uL, + fee = 0uL, + address = "bcrt1qdestination", + timestamp = 0uL, + feeRate = 1uL, + ).copy(isTransfer = true) + val activityRepo = mock() + whenever(activityRepo.getOnchainActivityByTxId(any(), any())).thenReturn(activity) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.markSettled(any())).thenReturn(Result.success(Unit)) + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + + // Leaves the operators could not co-sign are still on their way: the transfer keeps counting them. + // Before and after the retry's own build, which no longer lists the landed sweep. + val retry = running.copy(failedLeafRetrySince = 900u) + listOf(retry, retry.adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))), 0L)).forEach { + store.save(it) + createSut(activityRepo = activityRepo).load().getOrThrow() + } + verify(transferRepo, never()).markSettled(any()) + + store.save(running) + createSut(activityRepo = activityRepo).load().getOrThrow() + verify(transferRepo).markSettled("transfer-1") + } + @Test fun `leaves lost to an older state outlive the exit record that found them`() = test { val recordFile = File(Env.sparkExitRecordPath(0)) From 18d3a8281bd724fee16e6aa3a9599cfb5f12daa0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 13:17:51 +0100 Subject: [PATCH 036/154] fix: watch a higher fee paid while the spark exit rebuilds --- .../to/bitkit/repositories/SparkExitRepo.kt | 22 +++++++----- .../bitkit/repositories/SparkExitRepoTest.kt | 35 +++++++++++++++++++ 2 files changed, 49 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index ddcaef31d8..d2506bc64b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -555,8 +555,10 @@ class SparkExitRepo @Inject constructor( tickMutex.withLock { val current = _state.value.record ?: return@withLock if (current.isRebuilding && current.isActive) { - // It started rebuilding meanwhile: the rebuild adopts or the leftover sweep returns the payment. + // It started rebuilding meanwhile: the rebuild adopts the payment, and an exit that ends before it + // does keeps watching it until its outputs join the leftover. Logger.warn("Not applying a higher fee to a Spark exit that started rebuilding", context = TAG) + txid?.let { watchPayment(current, it) } return@withLock } if (!current.isActive) { @@ -564,13 +566,7 @@ class SparkExitRepo @Inject constructor( // joins the leftover the sweep sends back to savings. val paid = txid ?: return@withLock Logger.warn("Watching higher fee '$paid' paid after the Spark exit ended", context = TAG) - val watched = current.copy( - fundingPaymentTxid = paid, - fundingPaymentSeenAtHeight = null, - fundingPaymentMissingSince = null, - ) - saveRecord(watched) - _state.update { it.copy(record = watched) } + watchPayment(current, paid) return@withLock } val bumped = current.applyFeeBump(option.rateSatPerVbyte, option.extraSats, txid) @@ -587,6 +583,16 @@ class SparkExitRepo @Inject constructor( scope.launch { tick() } } + private fun watchPayment(record: SparkExitRecord, txid: String) { + val watched = record.copy( + fundingPaymentTxid = txid, + fundingPaymentSeenAtHeight = null, + fundingPaymentMissingSince = null, + ) + saveRecord(watched) + _state.update { it.copy(record = watched) } + } + // Each fee-bumped transaction gets a UTXO of its own, so one lost fee race strands one step's funding, not the // chain after it. private fun quoteRequest(feeRate: ULong, destination: String) = PrepareRecoverFundsRequest( diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 4aa25c8d8f..ac296bfbf3 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -967,6 +967,41 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(record.needsDriving) } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a higher fee paid while the exit starts rebuilding stays watched`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(runningRecord()) + val gate = CompletableDeferred() + stubFunding { + gate.await() + Result.success(OnchainSendOutcome.Unknown("bump")) + } + val sdk = FakeSparkExitRecovering().apply { + checks += CheckRecoverFundsResponse( + runningRecord().recovery!!, + RecoveryVerdict.Redo(RecoveryRedoReason.ON_CHAIN_STATE_DIVERGED), + ) + prepareErrors += SdkException.SparkException("connection reset") + } + val sut = quotedSut(sdk) + sut.load().getOrThrow() + + val payment = async { sut.payHigherFee(SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 6_000uL, 6_400uL)) } + advanceUntilIdle() + // A tick starts a rebuild while savings sends. + sut.tick() + assertTrue(assertNotNull(sut.state.value.record).isRebuilding) + gate.complete(Unit) + payment.await().getOrThrow() + advanceUntilIdle() + + val record = assertNotNull(store.load()) + assertEquals("bump", record.fundingPaymentTxid) + // Should the exit end before the payment is adopted, the ended exit keeps watching it. + assertTrue(record.copy(phase = Phase.Done).isEndedPaymentPending) + } + @Test fun `fee bump rates are priced without broadcasting, leaving out a rate the sdk refuses a leaf at`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) From 4babc07a8cd8e092f3e882a99545e294f8601b88 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:12:06 +0100 Subject: [PATCH 037/154] fix: keep the spark exit transfer while failed leaves await retry --- .../to/bitkit/repositories/SparkExitRecord.kt | 7 ++++ .../to/bitkit/repositories/SparkExitRepo.kt | 6 +-- .../bitkit/repositories/SparkExitRepoTest.kt | 37 +++++++++++++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 5f89a76db1..3dd19aae79 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -440,6 +440,13 @@ data class SparkExitRecord( /** The exit retries cooperative leaves the operators moved on-chain but could not co-sign. */ val isRetryingFailedLeaves: Boolean get() = isActive && failedLeafRetrySince != null + /** + * Cooperative leaves the operators could not co-sign are still on their way to savings: the running recovery lists + * them, or their retry runs. + */ + val hasFailedLeavesOutstanding: Boolean + get() = isRetryingFailedLeaves || (isActive && recovery?.failed?.isNotEmpty() == true) + /** While retrying, the current recovery still lists leaves the operators have not co-signed. */ val isWaitingForOperators: Boolean get() = isRetryingFailedLeaves && recovery?.failed?.isNotEmpty() == true diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index d2506bc64b..e6c549b938 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -320,9 +320,9 @@ class SparkExitRepo @Inject constructor( } val transferId = record.transferId ?: return if (transferRepo.isSettled(transferId).getOrDefault(true)) return - // Leaves the operators could not co-sign are still on their way to savings while retried: the transfer keeps - // counting them, less what already confirmed. - if (!record.isActive || (sweepActivity != null && !record.isRetryingFailedLeaves)) { + // Leaves the operators could not co-sign are still on their way to savings, before and while they are retried: + // the transfer keeps counting them, less what already confirmed. + if (!record.isActive || (sweepActivity != null && !record.hasFailedLeavesOutstanding)) { transferRepo.markSettled(transferId) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index ac296bfbf3..07dd5534ae 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1,6 +1,8 @@ package to.bitkit.repositories import breez_sdk_spark.CheckRecoverFundsResponse +import breez_sdk_spark.CooperativeRecoveryError +import breez_sdk_spark.CooperativeRecoveryFailure import breez_sdk_spark.CpfpFundingStrategy import breez_sdk_spark.ExitTransactionStatus import breez_sdk_spark.RecoveryRedoReason @@ -211,6 +213,41 @@ class SparkExitRepoTest : BaseUnitTest() { verify(transferRepo).markSettled("transfer-1") } + @Test + fun `a sweep seen before failed leaves are retried keeps the transfer`() = test { + val sweep = SparkExitFixtures.tx("s", kind = RecoveryTxKind.SWEEP) + val failed = CooperativeRecoveryFailure( + "coop-1", + "o", + 0u, + CooperativeRecoveryError.OperatorsUnavailable("down"), + ) + val running = SparkExitFixtures.record(Phase.Running) + .adopt(SparkExitFixtures.recovery(listOf(sweep), failed = listOf(failed)), 0L) + val activity = OnchainActivity.create( + walletId = "wallet0", + id = "sweep", + txType = PaymentType.RECEIVED, + txId = "s", + value = 90_000uL, + fee = 0uL, + address = "bcrt1qdestination", + timestamp = 0uL, + feeRate = 1uL, + ).copy(isTransfer = true) + val activityRepo = mock() + whenever(activityRepo.getOnchainActivityByTxId(any(), any())).thenReturn(activity) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.markSettled(any())).thenReturn(Result.success(Unit)) + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + + assertNull(running.failedLeafRetrySince) + store.save(running) + createSut(activityRepo = activityRepo).load().getOrThrow() + verify(transferRepo, never()).markSettled(any()) + } + @Test fun `leaves lost to an older state outlive the exit record that found them`() = test { val recordFile = File(Env.sparkExitRecordPath(0)) From ff79f740f7899dc01b3a1bebc5e33b289c3b9ce9 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:33:19 +0100 Subject: [PATCH 038/154] fix: translate the spark exit savings payment rows --- app/src/main/res/values-ar/strings.xml | 2 ++ app/src/main/res/values-b+es+419/strings.xml | 2 ++ app/src/main/res/values-ca/strings.xml | 2 ++ app/src/main/res/values-cs/strings.xml | 2 ++ app/src/main/res/values-de/strings.xml | 2 ++ app/src/main/res/values-el/strings.xml | 2 ++ app/src/main/res/values-es-rES/strings.xml | 2 ++ app/src/main/res/values-es/strings.xml | 2 ++ app/src/main/res/values-fr/strings.xml | 2 ++ app/src/main/res/values-it/strings.xml | 2 ++ app/src/main/res/values-nl/strings.xml | 2 ++ app/src/main/res/values-pl/strings.xml | 2 ++ app/src/main/res/values-pt-rBR/strings.xml | 2 ++ app/src/main/res/values-pt/strings.xml | 2 ++ app/src/main/res/values-ru/strings.xml | 2 ++ 15 files changed, 30 insertions(+) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 359400f3ab..f61063cb9f 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -313,6 +313,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 9a6f21b8b3..f29a7a5ab1 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -320,6 +320,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 31a9b7e820..2141d6f922 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -317,6 +317,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 6783686fae..655250310d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -320,6 +320,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 19111cf297..310712feeb 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -196,6 +196,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index ea1e1a8bd0..eb1c5ce199 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -313,6 +313,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index a71551e7ba..64790a34ce 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -319,6 +319,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 2e2168c4e7..e7e7df03f1 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -261,6 +261,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 0690ce226e..8d900ee081 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -195,6 +195,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index e00d31e610..2c7f28cdd7 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -318,6 +318,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 18fef616ab..8e58ae6c45 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -317,6 +317,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index a854c30654..b035bf84fc 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -197,6 +197,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index c4580ee1d2..7ab7bf540e 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -321,6 +321,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 3376c2d36c..ee4f6e79b6 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -192,6 +192,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 114187952f..08e89458d0 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -329,6 +329,8 @@ Ready in {duration} Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about + Savings payment fee + Total from savings Fee funding confirms Publishing exit transactions Sending to savings From a8e1462c0dba8e8cccf8102d44af9789f70d88ad Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 14:33:23 +0100 Subject: [PATCH 039/154] fix: remind about the rest of a short spark exit savings payment --- .../to/bitkit/repositories/SparkExitDriver.kt | 19 +++++++++++++++++- .../to/bitkit/repositories/SparkExitRepo.kt | 7 +------ .../to/bitkit/repositories/SparkExitWorker.kt | 8 ++++++++ .../repositories/SparkExitDriverTest.kt | 20 +++++++++++++++++++ 4 files changed, 47 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 383defe52a..e69495e556 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -145,7 +145,7 @@ class SparkExitDriver( val shortfall = record.fundingShortfallSats // Nothing to fund when every leaf is recovered cooperatively. val funded = if (shortfall != null) adoptFunding(record, shortfall) else record - if (funded != null) record = build(funded, sdk) + record = if (funded != null) build(funded, sdk) else countShortOwnPayment(record) } } SparkExitRecord.Phase.Running if record.isRebuilding -> { @@ -361,6 +361,23 @@ class SparkExitDriver( return end(updated.copy(phase = SparkExitRecord.Phase.Failed(LOST_REASON), isRebuilding = false), updated) } + /** + * A payment from savings that confirmed at the address without covering the funding is no longer waited for: it + * counts as funding seen there, and the rest is asked for and reminded about at once. + */ + private suspend fun countShortOwnPayment(record: SparkExitRecord): SparkExitRecord { + val txid = record.fundingPaymentTxid?.takeIf { record.isAwaitingOwnPayment } ?: return record + val address = record.funding.firstOrNull()?.address ?: return record + val utxos = runSuspendCatching { chain.utxos(address) }.getOrNull() ?: return record + if (utxos.none { it.txid == txid && it.status.confirmed }) return record + Logger.info("Spark exit savings payment '$txid' confirmed short, asking for the rest", context = TAG) + return record.copy( + fundingPaymentTxid = null, + fundingPaymentSeenAtHeight = null, + fundingPaymentMissingSince = null, + ) + } + private suspend fun lookForOwnPayment(record: SparkExitRecord): SparkExitRecord { val txid = record.fundingPaymentTxid?.takeIf { record.isAwaitingOwnPayment } ?: return record val height = tip ?: return record diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index e6c549b938..6dca80fa3d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -400,12 +400,7 @@ class SparkExitRepo @Inject constructor( deadlineAtMillis = clock.nowMs() + deadline.deadlineIn.inWholeMilliseconds ) } - // A payment from savings the exit forgot, as no host knew it or it never confirmed: the ask is back. - if (previous.isAwaitingOwnPayment && !record.isAwaitingOwnPayment && record.fundingShortfallSats != null && - record.fundingPaymentTxid == null - ) { - work.notify(SparkExitAlert.Funding) - } + if (SparkExitAlerts.isFundingAskBack(record, previous)) work.notify(SparkExitAlert.Funding) when (record.phase) { // Waiting on the operators for a week needs nothing from the user, so nothing reminds them. SparkExitRecord.Phase.Running if record.isWaitingForOperators -> { diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index 8c2f6472a9..dfb315735f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -371,6 +371,14 @@ object SparkExitAlerts { private val fundingReminderDelay = 4.hours private val regtestFundingReminderDelay = 10.minutes + /** + * A payment from savings the exit stopped waiting for on the tick from [previous]: no host knew it, it never + * confirmed, or it confirmed short of the funding. The ask is back. + */ + fun isFundingAskBack(record: SparkExitRecord, previous: SparkExitRecord): Boolean = + previous.isAwaitingOwnPayment && !record.isAwaitingOwnPayment && record.fundingShortfallSats != null && + record.fundingPaymentTxid == null + /** A started exit nothing was paid into: no adopted funding, no payment from savings. */ fun isAwaitingFirstFunding(record: SparkExitRecord): Boolean = record.phase is SparkExitRecord.Phase.AwaitingFunding && record.fundingShortfallSats != null && diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 0266891dd6..71130c8071 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -640,6 +640,26 @@ class SparkExitDriverTest : BaseUnitTest() { assertNull(record.fundingPaymentTxid) } + @Test + fun `a savings payment that confirms short of the funding asks for the rest at once`() = test { + val paid = "d0".repeat(32) + val waiting = SparkExitFixtures.record(Phase.AwaitingFunding(35_000uL)).copy(fundingPaymentTxid = paid) + val address = SparkExitFixtures.FUNDING_ADDRESS + chain.utxosByAddress[address] = listOf(SparkExitFixtures.utxo(paid, 0u, 20_000uL, confirmed = false)) + + val sent = driver(tip = 1_000u).tick(waiting) + assertTrue(sent.isAwaitingOwnPayment, "still confirming") + assertFalse(SparkExitAlerts.isFundingAskBack(sent, waiting)) + + chain.utxosByAddress[address] = listOf(SparkExitFixtures.utxo(paid, 0u, 20_000uL)) + val short = driver(tip = 1_001u).tick(sent) + + assertFalse(short.isAwaitingOwnPayment) + assertTrue(SparkExitAlerts.isFundingAskBack(short, sent)) + val ask = assertIs(SparkExitMath.fundingState(short, chain.utxosByAddress[address])) + assertEquals(20_000uL, ask.receivedSats) + } + @Test fun `a payment from savings never adopted is forgotten 144 blocks after the first look`() { val waiting = SparkExitFixtures.record(Phase.NeedsFunding(30_000uL)).copy(fundingPaymentTxid = "bump") From efa22be058210af0a6269fef122dc15f7130e84e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:28:02 +0100 Subject: [PATCH 040/154] fix: retry spark exit leaves a partial build skipped --- .../to/bitkit/repositories/SparkExitDriver.kt | 84 ++++++++++++++++--- .../to/bitkit/repositories/SparkExitRecord.kt | 18 +++- .../to/bitkit/repositories/SparkExitRepo.kt | 2 +- .../repositories/SparkExitDriverTest.kt | 52 ++++++++++++ 4 files changed, 141 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index e69495e556..c50dc6e7ea 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -254,7 +254,9 @@ class SparkExitDriver( // A leaf the operators' watchtower stopped is waited for, not struck, until its wait is over. val lost = record.lostLeaves(built).filter { !isStoppedWaiting(record, it.leafId, stopped) } if (lost.isNotEmpty()) return loseLeaves(record, lost) + // A leaf that may still move is kept apart and tried again before the exit ends. val adopted = record.adopt(built, nowMillis()) + .copy(waitingLeafIds = waitingLeafIds(record, prepared.skipped, stopped)) // Saved before any of it is broadcast, so a crash never leaves broadcast transactions without their record. save(adopted) Logger.info( @@ -301,10 +303,17 @@ class SparkExitDriver( return height < since || height - since < SparkExitMath.STOPPED_BLOCKS } - private fun isWaiting(record: SparkExitRecord, skipped: List, stopped: Set): Boolean { + private fun isWaiting(record: SparkExitRecord, skipped: List, stopped: Set): Boolean = + waitingLeafIds(record, skipped, stopped).isNotEmpty() + + private fun waitingLeafIds( + record: SparkExitRecord, + skipped: List, + stopped: Set, + ): List { val since = record.retrySince - if (since != null && tip != null && SparkExitMath.isRetryReleased(since, tip)) return false - return skipped.any { + if (since != null && tip != null && SparkExitMath.isRetryReleased(since, tip)) return emptyList() + return skipped.filter { it.leafId in record.exitLeafIds && when (it.reason) { SkippedLeafReason.Unverified, SkippedLeafReason.FundsNotFound, @@ -313,7 +322,7 @@ class SparkExitDriver( is SkippedLeafReason.NotRecoverable -> isStoppedWaiting(record, it.leafId, stopped) SkippedLeafReason.FeeExceedsValue -> false } - } + }.map { it.leafId } } private fun prepareRequest(record: SparkExitRecord, selection: ExitLeafSelection) = PrepareRecoverFundsRequest( @@ -407,7 +416,8 @@ class SparkExitDriver( val stored = record.recovery ?: return record.copy(phase = SparkExitRecord.Phase.AwaitingFunding(0uL)) // Nothing to check or send: only the failed cooperative leaves are left, and their retry decides the end. if (stored.transactions.isEmpty() && stored.failed.isNotEmpty()) { - return retryFailedLeaves(record, stored.failed.map { it.leafId }, sdk) + if (!record.isFailedLeavesReleased) return retryFailedLeaves(record, stored.failed.map { it.leafId }, sdk) + return retryWaitingLeaves(record, sdk) ?: end(record.ended(), record) } // An SDK that cannot check this tick still leaves the stored, signed steps to send. val checked = runSuspendCatching { sdk.check(withConfirmations(stored)) } @@ -450,7 +460,8 @@ class SparkExitDriver( if (checked.recovery.failed.isNotEmpty() && !updated.isFailedLeavesReleased) { return retryFailedLeaves(updated, checked.recovery.failed.map { it.leafId }, sdk) } - end(updated.copy(phase = SparkExitRecord.Phase.Done, failedLeaves = emptyList()), updated) + retryWaitingLeaves(updated, sdk)?.let { return it } + end(updated.ended(), updated) } is RecoveryVerdict.Redo -> { Logger.warn( @@ -506,8 +517,9 @@ class SparkExitDriver( val since = record.failedLeafRetrySince if (since != null && SparkExitMath.isRetryReleased(since, height)) { Logger.warn("Releasing Spark exit leaves '$failedIds' the operators did not co-sign", context = TAG) - val released = record.copy(phase = SparkExitRecord.Phase.Done, isFailedLeavesReleased = true) - return end(released, record) + val released = record.copy(isFailedLeavesReleased = true) + retryWaitingLeaves(released, sdk)?.let { return it } + return end(released.ended(), record) } if (since != null && !SparkExitMath.isRetryDue(since, record.failedLeafRetriedAt, height)) return record record = record.copy(failedLeafRetrySince = since ?: height, failedLeafRetriedAt = height) @@ -535,6 +547,57 @@ class SparkExitDriver( return broadcastReady(adopted) } + /** + * Leaves a build skipped while they may still move, tried again on their own once the rest of the exit is done: + * at once, then at doubling gaps, until they build or about a week passed. Null once nothing waits, so the exit + * can end. + */ + private suspend fun retryWaitingLeaves(start: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord? { + val ids = start.waitingLeafIds.filter { it in start.exitLeafIds } + if (ids.isEmpty()) return null + val height = tip ?: return start + val since = start.retrySince + if (since != null && SparkExitMath.isRetryReleased(since, height)) { + Logger.warn("Releasing Spark exit leaves '$ids' that did not move in about a week", context = TAG) + return null + } + if (since != null && !SparkExitMath.isRetryDue(since, start.retriedAt, height)) return start + var record = start.copy(retrySince = since ?: height, retriedAt = height) + val prepared = runSuspendCatching { + record = withExitState(record, sdk) + sdk.prepare(prepareRequest(record, ExitLeafSelection.Specific(ids))) + }.onFailure { Logger.warn("Failed to prepare waiting Spark exit leaves '$ids'", it, context = TAG) } + .getOrNull() + ?: return record + val stopped = prepared.exitChainState.stoppedLeafIds.toSet() + record = record.seeStopped(stopped) + val still = waitingLeafIds(record, prepared.skipped, stopped) + if (prepared.leaves.isEmpty()) return record.takeIf { still.isNotEmpty() }?.copy(waitingLeafIds = still) + val needsFunding = prepared.funding != null + val built = runSuspendCatching { + sdk.recover( + RecoverFundsRequest(prepared, if (needsFunding) record.fundingInputs else emptyList()), + if (needsFunding) makeSigner() else null, + ) + }.onFailure { Logger.warn("Failed to build waiting Spark exit leaves '$ids'", it, context = TAG) } + .getOrNull() + if (built == null || built.transactions.isEmpty()) return record + val adopted = record.adopt(built, nowMillis()).copy(waitingLeafIds = still) + save(adopted) + Logger.info("Built a recovery of waiting Spark exit leaves '$ids' as '${adopted.generation}'", context = TAG) + return broadcastReady(adopted) + } + + /** Done, with the leaves it waited for let go; failed leaves it released stay listed. */ + private fun SparkExitRecord.ended() = copy( + phase = SparkExitRecord.Phase.Done, + failedLeaves = if (isFailedLeavesReleased) failedLeaves else emptyList(), + skippedLeafCount = maxOf(skippedLeafCount, waitingLeafIds.size), + waitingLeafIds = emptyList(), + retrySince = null, + retriedAt = null, + ) + private suspend fun rebuild(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { val rebuilding = record.copy(isRebuilding = true) save(rebuilding) @@ -932,11 +995,12 @@ class SparkExitDriver( // Every step confirmed and no leaf failed: the exit is done without an SDK verdict. val isAllConfirmed = transactions.isNotEmpty() && transactions.all { it.status is ExitTransactionStatus.Confirmed } - if (!isAllConfirmed || recovery.failed.isNotEmpty() || checked.phase != SparkExitRecord.Phase.Running) { + val isLeafLeft = recovery.failed.isNotEmpty() || checked.waitingLeafIds.isNotEmpty() + if (!isAllConfirmed || isLeafLeft || checked.phase != SparkExitRecord.Phase.Running) { return checked } Logger.info("Every Spark exit step confirmed; ending the exit without the SDK", context = TAG) - return end(checked.copy(phase = SparkExitRecord.Phase.Done, failedLeaves = emptyList()), checked) + return end(checked.ended(), checked) } /** diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 3dd19aae79..7c383a109f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -100,6 +100,11 @@ data class SparkExitRecord( val retrySince: UInt? = null, /** The tip of the last of those builds. */ val retriedAt: UInt? = null, + /** + * The exit's leaves a build skipped while they may still move, with the rest built: tried again on their own + * before the exit ends, at the same gaps, and let go about a week later. + */ + val waitingLeafIds: List = emptyList(), /** The SDK's exit data from just before the first build, imported again before every rebuild. */ val exitStateSnapshot: String? = null, /** The stored record could not be read, so the exit rebuilds from the chain with the funding it kept. */ @@ -441,11 +446,12 @@ data class SparkExitRecord( val isRetryingFailedLeaves: Boolean get() = isActive && failedLeafRetrySince != null /** - * Cooperative leaves the operators could not co-sign are still on their way to savings: the running recovery lists - * them, or their retry runs. + * Leaves are still on their way to savings outside the running recovery's steps: cooperative ones the operators + * could not co-sign (the recovery lists them, or their retry runs), or ones a build skipped while they may move. */ - val hasFailedLeavesOutstanding: Boolean - get() = isRetryingFailedLeaves || (isActive && recovery?.failed?.isNotEmpty() == true) + val hasLeavesOutstanding: Boolean + get() = isRetryingFailedLeaves || + (isActive && (recovery?.failed?.isNotEmpty() == true || waitingLeafIds.isNotEmpty())) /** While retrying, the current recovery still lists leaves the operators have not co-signed. */ val isWaitingForOperators: Boolean @@ -876,6 +882,9 @@ object SparkExitJson { } r.retrySince?.let { put("retrySince", it.toLong()) } r.retriedAt?.let { put("retriedAt", it.toLong()) } + if (r.waitingLeafIds.isNotEmpty()) { + put("waitingLeafIds", buildJsonArray { r.waitingLeafIds.forEach { add(JsonPrimitive(it)) } }) + } r.exitStateSnapshot?.let { put("exitStateSnapshot", it) } if (r.isRebuiltFromChain) put("isRebuiltFromChain", true) if (r.isRedoRebuild) put("isRedoRebuild", true) @@ -994,6 +1003,7 @@ object SparkExitJson { .orEmpty(), retrySince = o.ulongOrNull("retrySince")?.toUInt(), retriedAt = o.ulongOrNull("retriedAt")?.toUInt(), + waitingLeafIds = o.arrayOrEmpty("waitingLeafIds").map { it.jsonPrimitive.content }, exitStateSnapshot = o.stringOrNull("exitStateSnapshot"), isRebuiltFromChain = o.booleanOrNull("isRebuiltFromChain") ?: false, isRedoRebuild = o.booleanOrNull("isRedoRebuild") ?: false, diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 6dca80fa3d..abffaee23b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -322,7 +322,7 @@ class SparkExitRepo @Inject constructor( if (transferRepo.isSettled(transferId).getOrDefault(true)) return // Leaves the operators could not co-sign are still on their way to savings, before and while they are retried: // the transfer keeps counting them, less what already confirmed. - if (!record.isActive || (sweepActivity != null && !record.hasFailedLeavesOutstanding)) { + if (!record.isActive || (sweepActivity != null && !record.hasLeavesOutstanding)) { transferRepo.markSettled(transferId) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 71130c8071..ab1e1fa961 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1064,6 +1064,58 @@ class SparkExitDriverTest : BaseUnitTest() { assertTrue(ticked.isWaitingForLeaves) } + private fun partialBuild(reason: SkippedLeafReason): SparkExitRecord { + val record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) + .copy(isRebuilding = true, leafIds = listOf("leaf-1", "leaf-2")) + sdk.preparedResponse = SparkExitFixtures.prepared(skipped = listOf(SkippedLeaf("leaf-2", 50_000uL, reason))) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + val landed = SparkExitFixtures.recovery( + listOf(SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(990u))), + ) + repeat(4) { sdk.checks += check(landed, RecoveryVerdict.Done) } + return record + } + + @Test + fun `a leaf skipped while another builds is tried again before the exit ends`() = test { + var record = driver(tip = 1_000u).tick(partialBuild(SkippedLeafReason.Unverified)) + assertEquals(2, record.generation) + assertEquals(listOf("leaf-2"), record.waitingLeafIds) + assertEquals(record.waitingLeafIds, SparkExitJson.decode(SparkExitJson.encode(record)).waitingLeafIds) + + sdk.preparedResponse = sdk.preparedResponse.copy(leaves = emptyList()) + record = driver(tip = 1_000u).tick(record) + assertEquals(Phase.Running, record.phase, "leaf-2 may still move") + assertTrue(record.isWaitingForLeaves) + assertTrue(record.hasLeavesOutstanding, "leaf-2 is still in transfer") + assertEquals(listOf("leaf-2"), (sdk.prepareRequests.last().selection as ExitLeafSelection.Specific).leafIds) + + chain.confirmedTxids = setOf("n1") + record = driver(withSdk = false, tip = 1_001u).tick(record) + assertEquals(Phase.Running, record.phase, "the exit waits for the sdk to retry leaf-2") + + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-2")) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + record = driver(tip = 1_006u).tick(record) + assertNull(record.retrySince) + assertEquals(listOf("n1", "n2"), chain.broadcasts.map { it.txid }) + + record = driver(tip = 1_007u).tick(record) + assertEquals(Phase.Done, record.phase) + } + + @Test + fun `a leaf skipped while another builds is let go after about a week`() = test { + var record = driver(tip = 1_000u).tick(partialBuild(SkippedLeafReason.FundsNotFound)) + sdk.preparedResponse = sdk.preparedResponse.copy(leaves = emptyList()) + record = driver(tip = 1_000u).tick(record) + assertEquals(Phase.Running, record.phase) + + record = driver(tip = 2_008u).tick(record) + assertEquals(Phase.Done, record.phase) + assertNull(record.retrySince) + } + @Test fun `resumes after a restart mid-exit without repeating broadcasts`() = test { val store = SparkExitStore(File(tempFolder.root, "spark-exit.json")) From 6feee8e3401f52507eca9e10bb7022e77a75a4cc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:38:29 +0100 Subject: [PATCH 041/154] fix: show the spark exit sweep version that confirmed --- .../to/bitkit/repositories/SparkExitDriver.kt | 16 ++++++++++- .../to/bitkit/repositories/SparkExitRecord.kt | 27 +++++++++++++++++++ .../repositories/SparkExitDriverTest.kt | 19 +++++++++++++ 3 files changed, 61 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index c50dc6e7ea..d46d345dc0 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -755,9 +755,13 @@ class SparkExitDriver( */ private suspend fun sweepLanded( record: SparkExitRecord, - sweep: SparkExitRecord.LeftoverSweep, + current: SparkExitRecord.LeftoverSweep, txid: String, ): SparkExitRecord { + // A version it replaced confirmed instead: that one's amount and inputs are what reached savings. + val sweep = record.acceptedSweeps.firstOrNull { it.txid == txid && it.txid != current.txid } + ?.let { current.copy(txid = it.txid, txHex = it.txHex, valueSats = it.valueSats) } + ?: current val landed = record.copy(leftoverSweep = sweep.copy(isConfirmed = true)) val address = record.funding.firstOrNull()?.address ?: return landed // Read again on the next tick: what is left at the address decides how the sweep ends. @@ -910,6 +914,7 @@ class SparkExitDriver( rejection = null, sentAtHeight = sweep.sentAtHeight ?: tip ), + acceptedSweeps = record.acceptedSweepsWith(sweep, hex), ) // A replacement refused for another reason while the version it replaced may still confirm waits again. is SparkExitBroadcastOutcome.Rejected if sweep.replacedTxids.isNotEmpty() && tip != null && @@ -926,6 +931,15 @@ class SparkExitDriver( } } + private fun SparkExitRecord.acceptedSweepsWith( + sweep: SparkExitRecord.LeftoverSweep, + hex: String, + ): List { + val txid = sweep.txid ?: return acceptedSweeps + if (acceptedSweeps.any { it.txid == txid }) return acceptedSweeps + return acceptedSweeps + SparkExitRecord.AcceptedSweep(txid, hex, sweep.valueSats) + } + private fun isRebuildDue(record: SparkExitRecord): Boolean { val last = record.lastBuildAt ?: return true return nowMillis() - last >= REBUILD_INTERVAL.inWholeMilliseconds diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 7c383a109f..47f621735f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -133,6 +133,11 @@ data class SparkExitRecord( val landedSweepTxid: String? = null, /** Leftover sweeps that confirmed while more funding was still at the address, earliest first. */ val sweptLeftover: List = emptyList(), + /** + * Every leftover sweep a node accepted, so the one that confirms is shown and followed with its own amount and + * inputs even after a replacement took its place. + */ + val acceptedSweeps: List = emptyList(), /** Steps confirmed when the rebuild from the chain was adopted; one more clears [isRebuiltFromChain]. */ val rebuiltFromChainConfirmedCount: Int? = null, /** The tip of the first funding-wait tick that looked for [fundingPaymentTxid]. */ @@ -225,6 +230,8 @@ data class SparkExitRecord( data class SweptLeftover(val txid: String, val valueSats: ULong) + data class AcceptedSweep(val txid: String, val txHex: String, val valueSats: ULong) + data class LeftBehindLeaf(val leafId: String, val valueSats: ULong, val reason: String) /** A cooperative leaf the operators moved on-chain; [valueSats] is 0 until a retry's quote names it. */ @@ -908,6 +915,22 @@ object SparkExitJson { r.failedLeafRetriedAt?.let { put("failedLeafRetriedAt", it.toLong()) } if (r.isFailedLeavesReleased) put("isFailedLeavesReleased", true) r.landedSweepTxid?.let { put("landedSweepTxid", it) } + if (r.acceptedSweeps.isNotEmpty()) { + put( + "acceptedSweeps", + buildJsonArray { + r.acceptedSweeps.forEach { + add( + buildJsonObject { + put("txid", it.txid) + put("txHex", it.txHex) + put("valueSats", it.valueSats.toLong()) + }, + ) + } + }, + ) + } if (r.sweptLeftover.isNotEmpty()) { put( "sweptLeftover", @@ -1017,6 +1040,10 @@ object SparkExitJson { isFailedLeavesReleased = o.booleanOrNull("isFailedLeavesReleased") ?: false, landedSweepTxid = o.stringOrNull("landedSweepTxid"), sweptLeftover = sweptLeftoverFromJson(o), + acceptedSweeps = o.arrayOrEmpty("acceptedSweeps").map { + val s = it.jsonObject + SparkExitRecord.AcceptedSweep(s.string("txid"), s.string("txHex"), s.ulong("valueSats")) + }, rebuiltFromChainConfirmedCount = o.intOrNull("rebuiltFromChainConfirmedCount"), fundingPaymentSeenAtHeight = o.ulongOrNull("fundingPaymentSeenAtHeight")?.toUInt(), fundingPaymentMissingSince = o.ulongOrNull("fundingPaymentMissingSince")?.toUInt(), diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index ab1e1fa961..4af9727d25 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1641,6 +1641,25 @@ class SparkExitDriverTest : BaseUnitTest() { assertFalse(record.needsDriving) } + @Test + fun `a sweep whose replaced version confirmed shows the version that confirmed`() = test { + var record = driver(tip = 1_000u).tick(sweepDone()) + val first = assertNotNull(record.leftoverSweep) + record = driver(tip = 1_144u).tick(record) + val replacement = assertNotNull(record.leftoverSweep) + assertTrue(replacement.valueSats < first.valueSats) + chain.confirmedTxids = setOf(assertNotNull(first.txid)) + + record = driver(tip = 1_145u).tick(record) + + val landed = assertNotNull(record.leftoverSweep) + assertTrue(landed.isConfirmed) + assertEquals(first.txid, landed.txid) + assertEquals(first.valueSats, landed.valueSats) + assertEquals(first.txHex, landed.txHex) + assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) + } + @Test fun `a replacement that would be dust keeps the accepted sweep`() = test { var record = driver(tip = 1_000u).tick(sweepDone()) From 1be3366d13f98628eb090d37a71cf3923a29c837 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 15:50:59 +0100 Subject: [PATCH 042/154] fix: keep the spark exit start going when its requote write fails --- .../to/bitkit/repositories/SparkExitRepo.kt | 44 ++++++++++++------- .../bitkit/repositories/SparkExitRepoTest.kt | 29 ++++++++++++ 2 files changed, 58 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index abffaee23b..6d31098274 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -684,22 +684,10 @@ class SparkExitRepo @Inject constructor( if (!isStarting(createdAt)) return@withLock false // An optimization since the quote swapped leaves: the exit is quoted again over the leaves Spark holds now. requote(pending)?.let { fresh -> + // A failed write goes on with the confirmed quote, as a failed requote does. + val requoted = writeRequote(requireNotNull(_state.value.record), fresh) ?: return@let quote = fresh - val current = requireNotNull(_state.value.record) - transferRepo.markSettled(transferId) - val freshTransfer = transferRepo.createTransfer( - TransferType.SPARK_EXIT, - fresh.incomingSats.toLong(), - ).getOrThrow() - record = current.copy( - phase = SparkExitRecord.Phase.AwaitingFunding(fresh.fundingSats), - leafIds = fresh.leafIds, - expectedSats = fresh.incomingSats, - skippedLeafCount = fresh.prepared.skipped.size, - leafTotalSats = fresh.leafTotalSats, - transferId = freshTransfer, - ) - saveRecord(record) + record = requoted _state.update { it.copy(record = record) } } // Under the lock, so a cancel can't release Spark between the check and taking it off Lightning. @@ -717,6 +705,32 @@ class SparkExitRepo @Inject constructor( if (fundFromSavings && savingsSats > 0uL) payFunding(createdAt, key.address, savingsSats) } + /** + * The started exit moved onto [fresh]: a transfer for its amount, saved, then the confirmed quote's transfer + * settled. Null when that write fails, with a transfer made for it settled again. + */ + private suspend fun writeRequote(current: SparkExitRecord, fresh: SparkExitQuote): SparkExitRecord? { + val freshTransfer = transferRepo.createTransfer(TransferType.SPARK_EXIT, fresh.incomingSats.toLong()) + .onFailure { Logger.warn("Failed to create the requoted Spark exit transfer", it, context = TAG) } + .getOrNull() + ?: return null + val requoted = current.copy( + phase = SparkExitRecord.Phase.AwaitingFunding(fresh.fundingSats), + leafIds = fresh.leafIds, + expectedSats = fresh.incomingSats, + skippedLeafCount = fresh.prepared.skipped.size, + leafTotalSats = fresh.leafTotalSats, + transferId = freshTransfer, + ) + runCatching { saveRecord(requoted) }.onFailure { + Logger.warn("Failed to save the requoted Spark exit", it, context = TAG) + transferRepo.markSettled(freshTransfer) + return null + } + current.transferId?.let { transferRepo.markSettled(it) } + return requoted + } + /** The exit created at [createdAt] is still the one on record and running: no cancel or wipe ended it. */ private fun isStarting(createdAt: Long): Boolean = _state.value.record?.let { it.createdAt == createdAt && it.isActive } == true diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 07dd5534ae..f8e22c777f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -774,6 +774,35 @@ class SparkExitRepoTest : BaseUnitTest() { sut.onAppBackgrounded() } + @Test + fun `a requote whose transfer fails goes on with the confirmed quote and still reconnects`() = test { + val sdk = FakeSparkExitRecovering() + val sut = quotedSut(sdk) + sut.loadQuote().getOrThrow() + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-2")) + whenever( + transferRepo.createTransfer( + any(), + any(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull() + ) + ).thenReturn(Result.success("transfer-1"), Result.failure(SparkExitError("database locked"))) + + sut.start(fundFromSavings = false).getOrThrow() + + val record = assertNotNull(sut.state.value.record) + assertEquals(listOf("leaf-1"), record.leafIds) + assertEquals("transfer-1", record.transferId) + verify(transferRepo, never()).markSettled("transfer-1") + verify(sparkRepo).setExiting(true, true) + sut.onAppBackgrounded() + } + @Test fun `savings never pays more than the confirmed funding when the start quotes again`() = test { stubFunding { Result.success(OnchainSendOutcome.Accepted("paid")) } From ecae8233475d7bb082c2b6ba68bfdb12bccff00f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:05:03 +0100 Subject: [PATCH 043/154] fix: translate the spark exit strings --- app/src/main/res/values-ar/strings.xml | 188 +++++++++---------- app/src/main/res/values-b+es+419/strings.xml | 188 +++++++++---------- app/src/main/res/values-ca/strings.xml | 188 +++++++++---------- app/src/main/res/values-cs/strings.xml | 188 +++++++++---------- app/src/main/res/values-de/strings.xml | 188 +++++++++---------- app/src/main/res/values-el/strings.xml | 188 +++++++++---------- app/src/main/res/values-es-rES/strings.xml | 188 +++++++++---------- app/src/main/res/values-es/strings.xml | 188 +++++++++---------- app/src/main/res/values-fr/strings.xml | 188 +++++++++---------- app/src/main/res/values-it/strings.xml | 188 +++++++++---------- app/src/main/res/values-nl/strings.xml | 188 +++++++++---------- app/src/main/res/values-pl/strings.xml | 188 +++++++++---------- app/src/main/res/values-pt-rBR/strings.xml | 188 +++++++++---------- app/src/main/res/values-pt/strings.xml | 188 +++++++++---------- app/src/main/res/values-ru/strings.xml | 188 +++++++++---------- 15 files changed, 1410 insertions(+), 1410 deletions(-) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index f61063cb9f..3b13a914c6 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -229,101 +229,101 @@ انتظر إيداعات تمت المطالبة بها إيداعات قيد التنفيذ - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + المبلغ المراد إخراجه + خروج طارئ + إلغاء الخروج + تعذّر التحقق من عنوان التمويل. حاول مرة أخرى. + يعود Spark إلى ما كان عليه. إذا وصلت دفعة إلى عنوان تمويل رسوم الخروج، يعيدها Bitkit إلى المدخرات. + إلغاء الخروج؟ + ألغيت الخروج. يعود تمويل الرسوم الذي وصل إلى المدخرات. + تم إلغاء\n<accent>الخروج</accent> + لن تتمكن من استخدام هذه الأموال <accent>لمدة تصل إلى 4 أسابيع</accent>. + بدء\n<accent>الخروج؟</accent> + وصل {amount} إلى مدخراتك. + أموالك في المدخرات. + اكتمل\n<accent>الخروج</accent> + نقل مشغّلو Spark مبلغ {amount} على السلسلة ولم يعد على Spark. لا يزال بإمكان المشغّلين الإفراج عنه لك. + يبقى {amount} على Spark. + تعذّر استرداد أي شيء. + توقّف\n<accent>الخروج</accent> + ادفع رسومًا أعلى + استخدم هذه الرسوم + تعذّر تسعير رسوم أعلى. حاول مرة أخرى. + الرسوم الأعلى ستُبقي جزءًا من هذا الخروج على Spark، لذلك لا تُعرض. يتأكد الخروج عندما تنخفض رسوم الشبكة. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + يدفع هذا الخروج <accent>{rate} sat/vB</accent>، أقل مما تطلبه الشبكة الآن. اختر معدلًا أعلى وسيرسل Bitkit الخطوات المنتظرة مرة أخرى. يدفع الفرق من المدخرات: المبلغ بجانب كل سرعة. + ادفع\n<accent>رسومًا أعلى</accent> + الشبكة أكثر ازدحامًا من معدل رسوم هذا الخروج البالغ {rate} sat/vB. ادفع رسومًا أعلى، أو انتظر حتى تنخفض الرسوم. + ارتفعت رسوم الشبكة فوق رسوم هذا الخروج. قد يتباطأ. + رسوم الشبكة + التمويل من محفظة أخرى + أرسل {amount} على الأقل إلى هذا العنوان. يبدأ الخروج بمجرد تأكيده. + مدخراتك لا تكفي لتمويل الرسوم. + دُفع من المدخرات، بانتظار التأكيد. + تم استلام {received} من {required}، أرسل {missing} إضافية. + تم رصد الدفعة، بانتظار التأكيد. + ادفع من المدخرات + تم رصد الدفعة. + يلزم تمويل الرسوم + يقسمه Bitkit إلى {count} أجزاء، جزء لكل خطوة، حتى لا تعطّل خطوة عالقة الخطوات الأخرى. + يدفع الخروج رسومه من دفعة منفصلة على السلسلة بقيمة <accent>{amount}</accent>. ما لا يُنفق منها يعود إلى المدخرات في النهاية. + موّل\n<accent>الرسوم</accent> + معرّف المعاملة: {txid} + استخدم هذا فقط إذا توقّف Spark عن العمل لديك. ينقل رصيد الإنفاق إلى المدخرات <accent>من دون مشغّلي Spark</accent>.\n\nيستغرق <accent>ما يصل إلى 4 أسابيع</accent>، ويكلّف رسومًا على السلسلة تُدفع من المدخرات، وقد تبقى المبالغ الصغيرة جدًا على Spark. يعمل في الخلفية، ويُعلمك Bitkit إذا احتاج إليك. + غادر Spark\n<accent>على السلسلة</accent> + يبقى على Spark + لا يمكن إخراج {amount} بمعدل الرسوم هذا ويبقى على Spark. + لا يزال {amount} من تمويل الرسوم على {address}. + المتبقي من تمويل الرسوم بقيمة {amount} صغير جدًا لإرساله ويبقى على {address}، مسار الاشتقاق {path}. + تعذّر إرسال المتبقي من تمويل الرسوم بقيمة {amount} ويبقى على {address}، مسار الاشتقاق {path}. + جارٍ إرسال {amount} من تمويل الرسوم المتبقي إلى المدخرات. + تم إرسال {amount} من تمويل الرسوم المتبقي إلى المدخرات. + معرّف المعاملة: {txid} + سيصل {amount} من فكة الرسوم إلى مدخراتك عندما تنخفض رسوم الشبكة. + طالب مالك سابق لهذه الأموال بمبلغ {amount} على السلسلة ولا يمكن استرداده. + الخروج الطارئ + يحتاج الخروج إلى <accent>{amount}</accent> إضافية لدفع رسومه. موّله للمتابعة. + يلزم المزيد\n<accent>من الرسوم</accent> + الخروج لا يتقدم: {error} + قد يؤخر تحسين البطارية في Android الخروج بينما Bitkit مغلق. يُعلمك Bitkit إذا تأخر. + توفير البطارية مفعّل، لذا قد يؤخر Android الخروج بينما Bitkit مغلق. + الإشعارات متوقفة، لذا لا يستطيع Bitkit إخبارك إذا احتاج الخروج إليك. من دونها، افتح Bitkit كل بضع ساعات حتى ينتهي الخروج. + تفعيل الإشعارات + يقيّد Android عمل Bitkit في الخلفية، لذا لا يتقدم الخروج إلا وBitkit مفتوح. اسمح لـ Bitkit بالعمل في الخلفية من إعدادات Android. + لا يوجد ما يمكن إخراجه الآن. + أخّرت إعدادات البطارية في Android خروجك الطارئ. افتح Bitkit قبل {time} ليبقى في مساره. + تعذّر على خروجك الطارئ المتابعة في الخلفية. افتح Bitkit قبل {time} ليبقى في مساره. + توقّف خروجك الطارئ. افتح Bitkit لمعرفة السبب. + يحتاج خروجك الطارئ إلى مزيد من تمويل الرسوم. افتح Bitkit لتمويله. + تأخر خروجك الطارئ في الخلفية. افتح Bitkit لمتابعته. + لا يمكن استرداد {amount} من خروجك. افتح Bitkit لمعرفة السبب. + لا يمكن لخروجك الطارئ المتابعة من دون إنترنت. اتصل وافتح Bitkit قبل {time} ليبقى في مساره. + رُفضت بعض معاملات خروجك الطارئ. افتح Bitkit قبل {time} لمعرفة السبب. + يمنع Android تطبيق Bitkit من العمل في الخلفية. افتح Bitkit قبل {time} ليبقى خروجك الطارئ في مساره. + خروج طارئ + {amount} على Spark ليس جزءًا من هذا الخروج ويبقى على Spark. + بقيت {count} مبالغ صغيرة على Spark. + يعمل الخروج في الخلفية، حتى عندما يكون Bitkit مغلقًا. يُعلمك Bitkit إذا احتاج إليك. + الخروج\n<accent>قيد التنفيذ</accent> + تعذّر الحصول على عرض سعر للخروج. حاول مرة أخرى. + جارٍ الحصول على عرض سعر… + لا يمكن إخراج {amount} من رصيدك على Spark الآن: مبالغ أصغر من أن تغطي رسومها، أو لا تزال تتحرك داخل Spark. تبقى على Spark. + بانتظار أن ينتهي Spark من نقل رصيدك. قد يستغرق ذلك حتى 5 دقائق. + عرض سعر\n<accent>الخروج</accent> + جاهز خلال {duration} + تعذّر على Bitkit قراءة التقدم المحفوظ لهذا الخروج، لذا يعيد بناءه من السلسلة. + ستستلم نحو + رسوم الدفع من المدخرات + الإجمالي من المدخرات + تأكيد تمويل الرسوم + نشر معاملات الخروج + الإرسال إلى المدخرات + انتظار القفل الزمني + معرّف المعاملة: {txid} + اسحب للخروج + الرسوم أعلى مما ستستلمه. + لا يمكن قراءة جزء من هذا الخروج على السلسلة الآن. يحاول Bitkit مجددًا لمدة تصل إلى أسبوع. + ينتظر {amount} الذي نقله مشغّلو Spark على السلسلة أن يفرجوا عنه. يطلب Bitkit مجددًا لمدة تصل إلى أسبوع. المزوّد Spark عبر Breez بلا حد diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index f29a7a5ab1..68f32ce44c 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -236,101 +236,101 @@ Esperar Depósitos reclamados Depósitos en curso - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Monto a retirar + Salida de emergencia + Cancelar salida + No se pudo comprobar la dirección de financiación. Intenta de nuevo. + Spark vuelve a quedar como estaba. Si un pago llegó a la dirección de financiación de comisiones de la salida, Bitkit lo devuelve a tus ahorros. + ¿Cancelar la salida? + Cancelaste la salida. La financiación de comisiones que llegó vuelve a tus ahorros. + Salida\n<accent>cancelada</accent> + No podrás usar estos fondos durante <accent>hasta 4 semanas</accent>. + ¿Iniciar\n<accent>salida?</accent> + {amount} llegó a tus ahorros. + Tus fondos están en tus ahorros. + Salida\n<accent>completada</accent> + Los operadores de Spark movieron {amount} on-chain y ya no está en Spark. Los operadores aún pueden liberártelo. + {amount} se queda en Spark. + No se pudo recuperar nada. + Salida\n<accent>detenida</accent> + Pagar una comisión más alta + Usar esta comisión + No se pudo calcular una comisión más alta. Intenta de nuevo. + Una comisión más alta dejaría parte de esta salida en Spark, así que no se ofrece ninguna. La salida se confirma cuando bajen las comisiones de la red. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Esta salida paga <accent>{rate} sat/vB</accent>, menos de lo que pide la red ahora. Elige una tarifa más alta y Bitkit vuelve a enviar los pasos pendientes. La diferencia se paga desde tus ahorros: el monto junto a cada velocidad. + Pagar una\n<accent>comisión más alta</accent> + La red está más congestionada que la tarifa de {rate} sat/vB de esta salida. Paga una comisión más alta o espera a que bajen las comisiones. + Las comisiones de la red superaron la comisión de esta salida. Puede ralentizarse. + Comisiones de red + Financiar desde otro billetera + Envía al menos {amount} a esta dirección. La salida empieza cuando se confirme. + Tus ahorros no alcanzan para la financiación de comisiones. + Pagado desde ahorros, esperando confirmación. + {received} de {required} recibidos, envía {missing} más. + Pago detectado, esperando confirmación. + Pagar desde ahorros + Pago detectado. + Financiación de comisiones necesaria + Bitkit lo divide en {count} partes, una por cada paso, para que un paso atascado no bloquee a los demás. + La salida paga sus comisiones con un pago on-chain aparte de <accent>{amount}</accent>. Lo que no gaste vuelve a tus ahorros al final. + Financiar las\n<accent>comisiones</accent> + ID de transacción: {txid} + Úsala solo si Spark deja de funcionarte. Mueve tu saldo de gastos a tus ahorros <accent>sin los operadores de Spark</accent>.\n\nTarda <accent>hasta 4 semanas</accent>, cuesta comisiones on-chain pagadas desde tus ahorros y los montos muy pequeños pueden quedarse atrás. Funciona en segundo plano y Bitkit te avisa si te necesita. + Salir de Spark\n<accent>on-chain</accent> + Se queda en Spark + {amount} no se puede retirar con esta tarifa y se queda en Spark. + {amount} de la financiación de comisiones sigue en {address}. + {amount} de financiación de comisiones sobrante es demasiado poco para enviarse y se queda en {address}, ruta de derivación {path}. + {amount} de financiación de comisiones sobrante no se pudo enviar y se queda en {address}, ruta de derivación {path}. + Enviando {amount} de financiación de comisiones sobrante a tus ahorros. + {amount} de financiación de comisiones sobrante se envió a tus ahorros. + ID de transacción: {txid} + {amount} de cambio de comisiones llegará a tus ahorros cuando bajen las comisiones de la red. + Un propietario anterior de estos fondos reclamó {amount} on-chain y no se puede recuperar. + Salida de emergencia + La salida necesita <accent>{amount}</accent> más para pagar sus comisiones. Fináncala para continuar. + Se necesitan\n<accent>más comisiones</accent> + La salida no avanza: {error} + La optimización de batería de Android puede retrasar la salida mientras Bitkit está cerrado. Bitkit te avisa si se retrasa. + El ahorro de batería está activado, así que Android puede frenar la salida mientras Bitkit está cerrado. + Las notificaciones están desactivadas, así que Bitkit no puede avisarte si la salida te necesita. Sin ellas, abre Bitkit cada pocas horas hasta que termine la salida. + Activar notificaciones + Android restringe Bitkit en segundo plano, así que la salida solo avanza mientras Bitkit está abierto. Permite el uso en segundo plano para Bitkit en la configuración de Android. + En este momento no se puede retirar nada. + La configuración de batería de Android frenó tu salida de emergencia. Abre Bitkit antes de las {time} para que siga su curso. + Tu salida de emergencia no pudo continuar en segundo plano. Abre Bitkit antes de las {time} para que siga su curso. + Tu salida de emergencia se detuvo. Abre Bitkit para ver por qué. + Tu salida de emergencia necesita más financiación de comisiones. Abre Bitkit para financiarla. + Tu salida de emergencia se retrasó en segundo plano. Abre Bitkit para continuarla. + {amount} de tu salida no se puede recuperar. Abre Bitkit para ver por qué. + Tu salida de emergencia no puede continuar sin internet. Conéctate y abre Bitkit antes de las {time} para que siga su curso. + Se rechazaron algunas transacciones de tu salida de emergencia. Abre Bitkit antes de las {time} para ver por qué. + Android impide que Bitkit se ejecute en segundo plano. Abre Bitkit antes de las {time} para que tu salida de emergencia siga su curso. + Salida de emergencia + {amount} en Spark no forma parte de esta salida y se queda en Spark. + {count} montos pequeños se quedaron en Spark. + La salida funciona en segundo plano, también con Bitkit cerrado. Bitkit te avisa si te necesita. + Salida\n<accent>en curso</accent> + No se pudo obtener una cotización de salida. Intenta de nuevo. + Obteniendo cotización… + {amount} de tu saldo de Spark no se puede retirar ahora: montos demasiado pequeños para pagar sus propias comisiones, o que aún se están moviendo dentro de Spark. Se queda en Spark. + Esperando a que Spark termine de mover tu saldo. Esto puede tardar hasta 5 minutos. + Cotización\n<accent>de salida</accent> + Listo en {duration} + Bitkit no pudo leer el progreso guardado de esta salida, así que lo reconstruye a partir de la cadena. + Recibes aproximadamente + Comisión del pago desde ahorros + Total desde ahorros + Confirmación de la financiación de comisiones + Publicando transacciones de salida + Enviando a ahorros + Esperando el bloqueo temporal + ID de transacción: {txid} + Desliza para salir + Las comisiones son mayores que lo que recibirías. + En este momento no se puede leer on-chain parte de esta salida. Bitkit lo vuelve a intentar durante hasta una semana. + {amount} que los operadores de Spark movieron on-chain espera a que lo liberen. Bitkit vuelve a pedirlo durante hasta una semana. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 2141d6f922..f852f7dc22 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -233,101 +233,101 @@ Espera Dipòsits reclamats Dipòsits en curs - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Import a retirar + Sortida d\'emergència + Cancel·lar la sortida + No s\'ha pogut comprovar l\'adreça de finançament. Torna-ho a intentar. + Spark torna a l\'estat anterior. Si un pagament ha arribat a l\'adreça de finançament de comissions de la sortida, Bitkit el retorna als estalvis. + Cancel·lar la sortida? + Has cancel·lat la sortida. El finançament de comissions que ha arribat torna als estalvis. + Sortida\n<accent>cancel·lada</accent> + No podràs utilitzar aquests fons durant <accent>fins a 4 setmanes</accent>. + Iniciar la\n<accent>sortida?</accent> + {amount} ha arribat als teus estalvis. + Els teus fons són als estalvis. + Sortida\n<accent>completada</accent> + Els operadors de Spark han mogut {amount} on-chain i no és a Spark. Els operadors encara te\'l poden alliberar. + {amount} es queda a Spark. + No s\'ha pogut recuperar res. + Sortida\n<accent>aturada</accent> + Paga una comissió més alta + Utilitza aquesta comissió + No s\'ha pogut calcular una comissió més alta. Torna-ho a intentar. + Una comissió més alta deixaria part d\'aquesta sortida a Spark, per això no se n\'ofereix cap. La sortida es confirmarà quan baixin les comissions de xarxa. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Aquesta sortida paga <accent>{rate} sat/vB</accent>, menys del que ara demana la xarxa. Tria una tarifa més alta i Bitkit torna a enviar els passos pendents. La diferència es paga dels estalvis: l\'import al costat de cada velocitat. + Paga una\n<accent>comissió més alta</accent> + La xarxa està més congestionada que la tarifa d\'aquesta sortida, {rate} sat/vB. Paga una comissió més alta o espera que baixin les comissions. + Les comissions de xarxa han superat la comissió d\'aquesta sortida. Pot alentir-se. + Comissions de xarxa + Finança des d\'un altre moneder + Envia almenys {amount} a aquesta adreça. La sortida comença quan es confirmi. + Els teus estalvis no poden cobrir el finançament de comissions. + Pagat dels estalvis, esperant confirmació. + {received} de {required} rebuts, envia\'n {missing} més. + Pagament detectat, esperant confirmació. + Paga dels estalvis + Pagament detectat. + Cal finançament de comissions + Bitkit el divideix en {count} parts, una per a cada pas, perquè un pas encallat no aturi els altres. + La sortida paga les seves comissions amb un pagament on-chain separat de <accent>{amount}</accent>. El que no gasti torna als estalvis al final. + Finança les\n<accent>comissions</accent> + ID de transacció: {txid} + Utilitza-ho només si Spark deixa de funcionar-te. Mou el teu saldo de despesa als estalvis <accent>sense els operadors de Spark</accent>.\n\nTriga <accent>fins a 4 setmanes</accent>, costa comissions on-chain pagades dels estalvis, i imports molt petits es poden quedar enrere. Funciona en segon pla, i Bitkit t\'avisa si et necessita. + Surt de Spark\n<accent>on-chain</accent> + Es queda a Spark + {amount} no es pot retirar amb aquesta tarifa i es queda a Spark. + {amount} de finançament de comissions encara és a {address}. + {amount} de finançament de comissions sobrant és massa petit per enviar-lo i es queda a {address}, camí de derivació {path}. + {amount} de finançament de comissions sobrant no s\'ha pogut enviar i es queda a {address}, camí de derivació {path}. + Enviant {amount} de finançament de comissions sobrant als estalvis. + {amount} de finançament de comissions sobrant s\'ha enviat als estalvis. + ID de transacció: {txid} + {amount} de canvi de comissions arribarà als teus estalvis quan baixin les comissions de xarxa. + Un antic propietari d\'aquests fons ha reclamat {amount} on-chain i no es pot recuperar. + Sortida d\'emergència + La sortida necessita <accent>{amount}</accent> més per pagar les seves comissions. Finança-la per continuar. + Calen més\n<accent>comissions</accent> + La sortida no avança: {error} + L\'optimització de bateria d\'Android pot endarrerir la sortida mentre Bitkit està tancat. Bitkit t\'avisa si es queda enrere. + L\'estalvi de bateria està activat, així que Android pot frenar la sortida mentre Bitkit està tancat. + Les notificacions estan desactivades, així que Bitkit no et pot avisar si la sortida et necessita. Sense elles, obre Bitkit cada poques hores fins que acabi la sortida. + Activa les notificacions + Android restringeix Bitkit en segon pla, així que la sortida només avança mentre Bitkit està obert. Permet l\'ús en segon pla per a Bitkit a la configuració d\'Android. + Ara mateix no es pot retirar res. + La configuració de bateria d\'Android ha frenat la teva sortida d\'emergència. Obre Bitkit abans de les {time} perquè segueixi el seu curs. + La teva sortida d\'emergència no ha pogut continuar en segon pla. Obre Bitkit abans de les {time} perquè segueixi el seu curs. + La teva sortida d\'emergència s\'ha aturat. Obre Bitkit per veure per què. + La teva sortida d\'emergència necessita més finançament de comissions. Obre Bitkit per finançar-la. + La teva sortida d\'emergència s\'ha endarrerit en segon pla. Obre Bitkit per continuar-la. + {amount} de la teva sortida no es pot recuperar. Obre Bitkit per veure per què. + La teva sortida d\'emergència no pot continuar sense internet. Connecta\'t i obre Bitkit abans de les {time} perquè segueixi el seu curs. + S\'han rebutjat algunes transaccions de la teva sortida d\'emergència. Obre Bitkit abans de les {time} per veure per què. + Android impedeix que Bitkit funcioni en segon pla. Obre Bitkit abans de les {time} perquè la teva sortida d\'emergència segueixi el seu curs. + Sortida d\'emergència + {amount} a Spark no forma part d\'aquesta sortida i es queda a Spark. + {count} imports petits s\'han quedat a Spark. + La sortida funciona en segon pla, també mentre Bitkit està tancat. Bitkit t\'avisa si et necessita. + Sortida\n<accent>en curs</accent> + No s\'ha pogut obtenir un pressupost de sortida. Torna-ho a intentar. + Obtenint un pressupost… + {amount} del teu saldo de Spark no es pot retirar ara mateix: imports massa petits per pagar les seves pròpies comissions, o que encara s\'estan movent dins de Spark. Es queda a Spark. + Esperant que Spark acabi de moure el teu saldo. Pot trigar fins a 5 minuts. + Pressupost\n<accent>de sortida</accent> + A punt en {duration} + Bitkit no ha pogut llegir el progrés desat d\'aquesta sortida, així que el reconstrueix a partir de la cadena. + Rebràs aproximadament + Comissió del pagament dels estalvis + Total dels estalvis + Es confirma el finançament de comissions + Publicant les transaccions de sortida + Enviant als estalvis + Esperant el timelock + ID de transacció: {txid} + Llisca per sortir + Les comissions són més altes del que rebries. + Ara mateix no es pot llegir on-chain part d\'aquesta sortida. Bitkit ho torna a intentar durant un màxim d\'una setmana. + {amount} que els operadors de Spark han mogut on-chain espera que l\'alliberin. Bitkit els ho torna a demanar durant un màxim d\'una setmana. Proveïdor Spark mitjançant Breez Sense límit diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 655250310d..c7ef7d33d4 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -236,101 +236,101 @@ Počkat Připsané vklady Probíhající vklady - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Částka k odchodu + Nouzový odchod + Zrušit odchod + Adresu pro financování se nepodařilo zkontrolovat. Zkuste to znovu. + Spark se vrátí do původního stavu. Pokud na adresu pro financování poplatků odchodu dorazila platba, Bitkit ji pošle zpět do úspor. + Zrušit odchod? + Odchod jste zrušili. Prostředky na poplatky, které dorazily, se vrátí do úspor. + Odchod\n<accent>zrušen</accent> + Tyto prostředky nebudete moci používat <accent>až 4 týdny</accent>. + Zahájit\n<accent>odchod?</accent> + {amount} dorazilo do vašich úspor. + Vaše prostředky jsou v úsporách. + Odchod\n<accent>dokončen</accent> + {amount} přesunuli operátoři Sparku on-chain a není na Spark. Operátoři vám je stále mohou uvolnit. + {amount} zůstává na Spark. + Nic se nepodařilo získat zpět. + Odchod\n<accent>zastaven</accent> + Zaplatit vyšší poplatek + Použít tento poplatek + Vyšší poplatek se nepodařilo spočítat. Zkuste to znovu. + Vyšší poplatek by část tohoto odchodu nechal na Spark, proto se nenabízí. Odchod se potvrdí, až síťové poplatky klesnou. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Tento odchod platí <accent>{rate} sat/vB</accent>, méně, než teď žádá síť. Zvolte vyšší sazbu a Bitkit čekající kroky odešle znovu. Rozdíl zaplatí z úspor: je to částka u každé rychlosti. + Zaplatit\n<accent>vyšší poplatek</accent> + Síť je vytíženější, než odpovídá sazbě poplatku tohoto odchodu {rate} sat/vB. Zaplaťte vyšší poplatek, nebo počkejte, až poplatky klesnou. + Síťové poplatky vzrostly nad poplatek tohoto odchodu. Může se zpomalit. + Síťové poplatky + Financovat z jiné peněženky + Pošlete na tuto adresu alespoň {amount}. Odchod začne, jakmile se platba potvrdí. + Vaše úspory nepokryjí financování poplatků. + Zaplaceno z úspor, čeká na potvrzení. + Přijato {received} z {required}, pošlete ještě {missing}. + Platba zachycena, čeká na potvrzení. + Zaplatit z úspor + Platba zachycena. + Je potřeba financovat poplatky + Bitkit ji rozdělí na {count} částí, jednu pro každý krok, aby jeden zaseknutý krok nezdržel ostatní. + Odchod platí své poplatky ze samostatné on-chain platby ve výši <accent>{amount}</accent>. Co nespotřebuje, se na konci vrátí do úspor. + Financujte\n<accent>poplatky</accent> + ID transakce: {txid} + Použijte to, jen pokud vám Spark přestane fungovat. Přesune váš zůstatek k utrácení do úspor <accent>bez operátorů Sparku</accent>.\n\nTrvá <accent>až 4 týdny</accent>, stojí on-chain poplatky placené z úspor a velmi malé částky mohou zůstat na Spark. Běží na pozadí a Bitkit vás upozorní, pokud vás bude potřebovat. + Opustit Spark\n<accent>on-chain</accent> + Zůstává na Spark + {amount} nelze při této sazbě poplatku vyvést a zůstává na Spark. + {amount} z financování poplatků je stále na {address}. + {amount} ze zbylého financování poplatků je příliš málo na odeslání a zůstává na {address}, derivační cesta {path}. + {amount} ze zbylého financování poplatků se nepodařilo odeslat a zůstává na {address}, derivační cesta {path}. + Odesílání {amount} ze zbylého financování poplatků do úspor. + {amount} ze zbylého financování poplatků bylo odesláno do úspor. + ID transakce: {txid} + {amount} drobných z poplatků dorazí do vašich úspor, až síťové poplatky klesnou. + {amount} si on-chain nárokoval dřívější vlastník těchto prostředků a nelze je získat zpět. + Nouzový odchod + Odchod potřebuje na poplatky ještě <accent>{amount}</accent>. Pro pokračování jej financujte. + Je potřeba\n<accent>více poplatků</accent> + Odchod nepostupuje: {error} + Optimalizace baterie v Androidu může odchod zdržet, když je Bitkit zavřený. Bitkit vás upozorní, pokud se opozdí. + Spořič baterie je zapnutý, takže Android může odchod zdržovat, když je Bitkit zavřený. + Oznámení jsou vypnutá, takže vám Bitkit nemůže dát vědět, když vás odchod bude potřebovat. Bez nich otevírejte Bitkit každých pár hodin, dokud odchod neskončí. + Zapnout oznámení + Android omezuje Bitkit na pozadí, takže odchod postupuje jen při otevřeném Bitkitu. Povolte Bitkitu běh na pozadí v nastavení Androidu. + Teď není co vyvést. + Nastavení baterie v Androidu zdrželo váš nouzový odchod. Otevřete Bitkit před {time}, aby pokračoval podle plánu. + Váš nouzový odchod nemohl pokračovat na pozadí. Otevřete Bitkit před {time}, aby pokračoval podle plánu. + Váš nouzový odchod se zastavil. Otevřete Bitkit a zjistěte proč. + Váš nouzový odchod potřebuje více prostředků na poplatky. Otevřete Bitkit a financujte jej. + Váš nouzový odchod se na pozadí opozdil. Otevřete Bitkit a pokračujte v něm. + {amount} z vašeho odchodu nelze získat zpět. Otevřete Bitkit a zjistěte proč. + Váš nouzový odchod nemůže pokračovat bez internetu. Připojte se a otevřete Bitkit před {time}, aby pokračoval podle plánu. + Některé transakce vašeho nouzového odchodu byly odmítnuty. Otevřete Bitkit před {time} a zjistěte proč. + Android brání Bitkitu v běhu na pozadí. Otevřete Bitkit před {time}, aby váš nouzový odchod pokračoval podle plánu. + Nouzový odchod + {amount} na Spark není součástí tohoto odchodu a zůstává na Spark. + Malých částek, které zůstaly na Spark: {count}. + Odchod běží na pozadí, i když je Bitkit zavřený. Bitkit vás upozorní, pokud vás bude potřebovat. + Odchod\n<accent>probíhá</accent> + Nabídku odchodu se nepodařilo získat. Zkuste to znovu. + Získávání nabídky… + {amount} z vašeho zůstatku na Spark teď nelze vyvést: částky jsou příliš malé na zaplacení vlastních poplatků, nebo se ještě přesouvají uvnitř Sparku. Zůstávají na Spark. + Čekáme, až Spark dokončí přesun vašeho zůstatku. Může to trvat až 5 minut. + Nabídka\n<accent>odchodu</accent> + Připraveno za {duration} + Bitkit nemohl načíst uložený průběh tohoto odchodu, proto jej obnovuje z blockchainu. + Obdržíte přibližně + Poplatek za platbu z úspor + Celkem z úspor + Potvrzení financování poplatků + Zveřejnění transakcí odchodu + Odesílání do úspor + Čekání na časový zámek + ID transakce: {txid} + Přejeďte pro odchod + Poplatky jsou vyšší, než kolik byste obdrželi. + Část tohoto odchodu teď nelze on-chain načíst. Bitkit to bude zkoušet znovu až týden. + {amount}, které operátoři Sparku přesunuli on-chain, čeká, až je uvolní. Bitkit se bude ptát znovu až týden. Poskytovatel Spark přes Breez Bez limitu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 310712feeb..e5a3eedf3b 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -112,101 +112,101 @@ Warten Eingelöste Einzahlungen Laufende Einzahlungen - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Auszahlungsbetrag + Notausstieg + Ausstieg abbrechen + Die Finanzierungsadresse konnte nicht geprüft werden. Versuche es erneut. + Spark kehrt in den vorherigen Zustand zurück. Wenn eine Zahlung die Gebührenfinanzierungsadresse des Ausstiegs erreicht hat, sendet Bitkit sie zurück auf dein Sparkonto. + Ausstieg abbrechen? + Du hast den Ausstieg abgebrochen. Die eingegangene Gebührenfinanzierung geht zurück auf dein Sparkonto. + Ausstieg\n<accent>abgebrochen</accent> + Du kannst diese Mittel <accent>bis zu 4 Wochen</accent> lang nicht nutzen. + Ausstieg\n<accent>starten?</accent> + {amount} ist auf deinem Sparkonto angekommen. + Deine Mittel sind auf deinem Sparkonto. + Ausstieg\n<accent>abgeschlossen</accent> + {amount} wurde von den Spark-Betreibern on-chain verschoben und ist nicht auf Spark. Die Betreiber können es dir weiterhin freigeben. + {amount} bleibt auf Spark. + Es konnte nichts zurückgeholt werden. + Ausstieg\n<accent>gestoppt</accent> + Höhere Gebühr zahlen + Diese Gebühr verwenden + Eine höhere Gebühr konnte nicht berechnet werden. Versuche es erneut. + Eine höhere Gebühr würde einen Teil dieses Ausstiegs auf Spark lassen, daher wird keine angeboten. Der Ausstieg wird bestätigt, sobald die Netzgebühren sinken. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Dieser Ausstieg zahlt <accent>{rate} sat/vB</accent>, weniger als das Netzwerk derzeit verlangt. Wähle einen höheren Satz, und Bitkit sendet die wartenden Schritte erneut. Die Differenz zahlt es von deinem Sparkonto: den Betrag neben jeder Geschwindigkeit. + Höhere\n<accent>Gebühr zahlen</accent> + Das Netzwerk ist stärker ausgelastet als der Gebührensatz dieses Ausstiegs von {rate} sat/vB. Zahle eine höhere Gebühr oder warte, bis die Gebühren sinken. + Die Netzgebühren sind über die Gebühr dieses Ausstiegs gestiegen. Er kann sich verlangsamen. + Netzgebühren + Aus einer anderen Wallet finanzieren + Sende mindestens {amount} an diese Adresse. Der Ausstieg beginnt, sobald die Zahlung bestätigt ist. + Dein Sparkonto reicht für die Gebührenfinanzierung nicht aus. + Vom Sparkonto bezahlt, warte auf Bestätigung. + {received} von {required} erhalten, sende noch {missing}. + Zahlung erkannt, warte auf Bestätigung. + Vom Sparkonto zahlen + Zahlung erkannt. + Gebührenfinanzierung nötig + Bitkit teilt sie in {count} Teile auf, einen für jeden Schritt, damit ein hängender Schritt die anderen nicht aufhält. + Der Ausstieg zahlt seine Gebühren aus einer separaten On-Chain-Zahlung von <accent>{amount}</accent>. Was er nicht ausgibt, geht am Ende zurück auf dein Sparkonto. + Gebühren\n<accent>finanzieren</accent> + Transaktions-ID: {txid} + Nutze dies nur, wenn Spark für dich nicht mehr funktioniert. Es verschiebt dein Ausgabenguthaben auf dein Sparkonto, <accent>ohne die Spark-Betreiber</accent>.\n\nEs dauert <accent>bis zu 4 Wochen</accent>, kostet On-Chain-Gebühren, die vom Sparkonto bezahlt werden, und sehr kleine Beträge können zurückbleiben. Es läuft im Hintergrund, und Bitkit benachrichtigt dich, wenn es dich braucht. + Spark\n<accent>on-chain verlassen</accent> + Bleibt auf Spark + {amount} kann bei diesem Gebührensatz nicht ausgezahlt werden und bleibt auf Spark. + {amount} der Gebührenfinanzierung liegt noch bei {address}. + {amount} übrige Gebührenfinanzierung ist zu klein zum Senden und bleibt bei {address}, Ableitungspfad {path}. + {amount} übrige Gebührenfinanzierung konnte nicht gesendet werden und bleibt bei {address}, Ableitungspfad {path}. + {amount} übrige Gebührenfinanzierung wird an dein Sparkonto gesendet. + {amount} übrige Gebührenfinanzierung wurde an dein Sparkonto gesendet. + Transaktions-ID: {txid} + {amount} Gebührenwechselgeld erreicht dein Sparkonto, wenn die Netzgebühren sinken. + {amount} wurde von einem früheren Besitzer dieser Mittel on-chain beansprucht und kann nicht zurückgeholt werden. + Notausstieg + Der Ausstieg braucht noch <accent>{amount}</accent>, um seine Gebühren zu zahlen. Finanziere ihn, um fortzufahren. + Mehr Gebühren\n<accent>nötig</accent> + Der Ausstieg kommt nicht voran: {error} + Die Akku-Optimierung von Android kann den Ausstieg verzögern, während Bitkit geschlossen ist. Bitkit benachrichtigt dich, wenn er in Verzug gerät. + Der Energiesparmodus ist aktiv, daher kann Android den Ausstieg aufhalten, während Bitkit geschlossen ist. + Benachrichtigungen sind deaktiviert, daher kann Bitkit dir nicht mitteilen, wenn der Ausstieg dich braucht. Öffne Bitkit ohne sie alle paar Stunden, bis der Ausstieg abgeschlossen ist. + Benachrichtigungen aktivieren + Android schränkt Bitkit im Hintergrund ein, daher kommt der Ausstieg nur voran, während Bitkit geöffnet ist. Erlaube die Hintergrundnutzung für Bitkit in den Android-Einstellungen. + Derzeit kann nichts ausgezahlt werden. + Die Akku-Einstellungen von Android haben deinen Notausstieg aufgehalten. Öffne Bitkit vor {time}, damit er auf Kurs bleibt. + Dein Notausstieg konnte im Hintergrund nicht fortgesetzt werden. Öffne Bitkit vor {time}, damit er auf Kurs bleibt. + Dein Notausstieg wurde gestoppt. Öffne Bitkit, um den Grund zu sehen. + Dein Notausstieg braucht mehr Gebührenfinanzierung. Öffne Bitkit, um ihn zu finanzieren. + Dein Notausstieg ist im Hintergrund in Verzug geraten. Öffne Bitkit, um ihn fortzusetzen. + {amount} deines Ausstiegs kann nicht zurückgeholt werden. Öffne Bitkit, um den Grund zu sehen. + Dein Notausstieg kann ohne Internet nicht fortgesetzt werden. Verbinde dich und öffne Bitkit vor {time}, damit er auf Kurs bleibt. + Einige Transaktionen deines Notausstiegs wurden abgelehnt. Öffne Bitkit vor {time}, um den Grund zu sehen. + Android verhindert, dass Bitkit im Hintergrund läuft. Öffne Bitkit vor {time}, damit dein Notausstieg auf Kurs bleibt. + Notausstieg + {amount} auf Spark gehört nicht zu diesem Ausstieg und bleibt auf Spark. + {count} kleine Beträge sind auf Spark geblieben. + Der Ausstieg läuft im Hintergrund, auch wenn Bitkit geschlossen ist. Bitkit benachrichtigt dich, wenn es dich braucht. + Ausstieg\n<accent>läuft</accent> + Es konnte kein Angebot für den Ausstieg abgerufen werden. Versuche es erneut. + Angebot wird abgerufen… + {amount} deines Spark-Guthabens kann derzeit nicht ausgezahlt werden: Beträge, die zu klein sind, um ihre eigenen Gebühren zu zahlen, oder die sich noch innerhalb von Spark bewegen. Sie bleiben auf Spark. + Warte, bis Spark dein Guthaben fertig verschoben hat. Das kann bis zu 5 Minuten dauern. + Ausstiegs-\n<accent>angebot</accent> + Bereit in {duration} + Bitkit konnte den gespeicherten Fortschritt dieses Ausstiegs nicht lesen und stellt ihn daher aus der Blockchain wieder her. + Du erhältst etwa + Gebühr für Zahlung vom Sparkonto + Gesamt vom Sparkonto + Gebührenfinanzierung wird bestätigt + Ausstiegstransaktionen werden veröffentlicht + Wird an das Sparkonto gesendet + Warten auf die Zeitsperre + Transaktions-ID: {txid} + Swipe zum Aussteigen + Die Gebühren sind höher als der Betrag, den du erhalten würdest. + Ein Teil dieses Ausstiegs kann gerade nicht on-chain gelesen werden. Bitkit versucht es bis zu einer Woche lang erneut. + {amount}, das die Spark-Betreiber on-chain verschoben haben, wartet auf deren Freigabe. Bitkit fragt bis zu einer Woche lang erneut nach. Anbieter Spark über Breez Kein Limit diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index eb1c5ce199..22da66b290 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -229,101 +229,101 @@ Αναμονή Εξαργυρωμένες καταθέσεις Καταθέσεις σε εξέλιξη - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Ποσό εξόδου + Έξοδος έκτακτης ανάγκης + Ακύρωση εξόδου + Δεν ήταν δυνατός ο έλεγχος της διεύθυνσης χρηματοδότησης. Δοκιμάστε ξανά. + Το Spark επιστρέφει όπως ήταν. Αν μια πληρωμή έφτασε στη διεύθυνση χρηματοδότησης τελών της εξόδου, το Bitkit την επιστρέφει στις αποταμιεύσεις. + Ακύρωση εξόδου; + Ακυρώσατε την έξοδο. Η χρηματοδότηση τελών που έφτασε επιστρέφει στις αποταμιεύσεις. + Η έξοδος\n<accent>ακυρώθηκε</accent> + Δεν θα μπορείτε να χρησιμοποιήσετε αυτά τα κεφάλαια για <accent>έως 4 εβδομάδες</accent>. + Έναρξη\n<accent>εξόδου;</accent> + {amount} έφτασαν στις αποταμιεύσεις σας. + Τα κεφάλαιά σας είναι στις αποταμιεύσεις. + Η έξοδος\n<accent>ολοκληρώθηκε</accent> + {amount} μεταφέρθηκαν on-chain από τους διαχειριστές του Spark και δεν βρίσκονται στο Spark. Οι διαχειριστές μπορούν ακόμα να σας τα αποδεσμεύσουν. + {amount} παραμένουν στο Spark. + Δεν ήταν δυνατή η ανάκτηση τίποτα. + Η έξοδος\n<accent>σταμάτησε</accent> + Πληρωμή υψηλότερου τέλους + Χρήση αυτού του τέλους + Δεν ήταν δυνατός ο υπολογισμός υψηλότερου τέλους. Δοκιμάστε ξανά. + Ένα υψηλότερο τέλος θα άφηνε μέρος αυτής της εξόδου στο Spark, γι\' αυτό δεν προσφέρεται. Η έξοδος επιβεβαιώνεται όταν πέσουν τα τέλη δικτύου. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Αυτή η έξοδος πληρώνει <accent>{rate} sat/vB</accent>, λιγότερο από όσο ζητά τώρα το δίκτυο. Επιλέξτε υψηλότερο ποσοστό και το Bitkit στέλνει ξανά τα βήματα σε αναμονή. Πληρώνει τη διαφορά από τις αποταμιεύσεις: το ποσό δίπλα σε κάθε ταχύτητα. + Πληρωμή\n<accent>υψηλότερου τέλους</accent> + Το δίκτυο είναι πιο φορτωμένο από το ποσοστό τέλους αυτής της εξόδου, {rate} sat/vB. Πληρώστε υψηλότερο τέλος ή περιμένετε να πέσουν τα τέλη. + Τα τέλη δικτύου ανέβηκαν πάνω από το τέλος αυτής της εξόδου. Μπορεί να καθυστερήσει. + Τέλη δικτύου + Χρηματοδότηση από άλλο πορτοφόλι + Στείλτε τουλάχιστον {amount} σε αυτή τη διεύθυνση. Η έξοδος ξεκινά μόλις επιβεβαιωθεί. + Οι αποταμιεύσεις σας δεν επαρκούν για τη χρηματοδότηση τελών. + Πληρώθηκε από τις αποταμιεύσεις, αναμονή επιβεβαίωσης. + Λήφθηκαν {received} από {required}, στείλτε άλλα {missing}. + Η πληρωμή εντοπίστηκε, αναμονή επιβεβαίωσης. + Πληρωμή από αποταμιεύσεις + Η πληρωμή εντοπίστηκε. + Απαιτείται χρηματοδότηση τελών + Το Bitkit τη χωρίζει σε {count} μέρη, ένα για κάθε βήμα, ώστε ένα κολλημένο βήμα να μην καθυστερεί τα άλλα. + Η έξοδος πληρώνει τα τέλη της από μια ξεχωριστή on-chain πληρωμή <accent>{amount}</accent>. Ό,τι δεν ξοδέψει επιστρέφει στις αποταμιεύσεις στο τέλος. + Χρηματοδότηση\n<accent>τελών</accent> + ID συναλλαγής: {txid} + Χρησιμοποιήστε το μόνο αν το Spark σταματήσει να λειτουργεί για εσάς. Μεταφέρει το υπόλοιπο δαπανών σας στις αποταμιεύσεις <accent>χωρίς τους διαχειριστές του Spark</accent>.\n\nΔιαρκεί <accent>έως 4 εβδομάδες</accent>, κοστίζει τέλη on-chain που πληρώνονται από τις αποταμιεύσεις, και πολύ μικρά ποσά μπορεί να μείνουν πίσω. Εκτελείται στο παρασκήνιο και το Bitkit σας ειδοποιεί αν σας χρειαστεί. + Έξοδος από το Spark\n<accent>on-chain</accent> + Παραμένει στο Spark + {amount} δεν μπορούν να βγουν με αυτό το ποσοστό τέλους και παραμένουν στο Spark. + {amount} της χρηματοδότησης τελών βρίσκονται ακόμα στη διεύθυνση {address}. + {amount} από την υπόλοιπη χρηματοδότηση τελών είναι πολύ μικρά για αποστολή και παραμένουν στη διεύθυνση {address}, διαδρομή παραγωγής {path}. + {amount} από την υπόλοιπη χρηματοδότηση τελών δεν ήταν δυνατό να σταλούν και παραμένουν στη διεύθυνση {address}, διαδρομή παραγωγής {path}. + Αποστολή {amount} από την υπόλοιπη χρηματοδότηση τελών στις αποταμιεύσεις. + {amount} από την υπόλοιπη χρηματοδότηση τελών στάλθηκαν στις αποταμιεύσεις. + ID συναλλαγής: {txid} + {amount} ρέστα τελών θα φτάσουν στις αποταμιεύσεις σας όταν πέσουν τα τέλη δικτύου. + {amount} διεκδικήθηκαν on-chain από προηγούμενο κάτοχο αυτών των κεφαλαίων και δεν μπορούν να ανακτηθούν. + Έξοδος Έκτακτης Ανάγκης + Η έξοδος χρειάζεται άλλα <accent>{amount}</accent> για να πληρώσει τα τέλη της. Χρηματοδοτήστε την για να συνεχίσει. + Απαιτούνται\n<accent>περισσότερα τέλη</accent> + Η έξοδος δεν προχωρά: {error} + Η βελτιστοποίηση μπαταρίας του Android μπορεί να καθυστερήσει την έξοδο όταν το Bitkit είναι κλειστό. Το Bitkit σας ειδοποιεί αν μείνει πίσω. + Η εξοικονόμηση μπαταρίας είναι ενεργή, οπότε το Android μπορεί να καθυστερήσει την έξοδο όταν το Bitkit είναι κλειστό. + Οι ειδοποιήσεις είναι απενεργοποιημένες, οπότε το Bitkit δεν μπορεί να σας ενημερώσει αν η έξοδος σας χρειάζεται. Χωρίς αυτές, ανοίγετε το Bitkit κάθε λίγες ώρες μέχρι να ολοκληρωθεί η έξοδος. + Ενεργοποίηση ειδοποιήσεων + Το Android περιορίζει το Bitkit στο παρασκήνιο, οπότε η έξοδος προχωρά μόνο όταν το Bitkit είναι ανοιχτό. Επιτρέψτε τη χρήση στο παρασκήνιο για το Bitkit στις ρυθμίσεις του Android. + Τίποτα δεν μπορεί να βγει αυτή τη στιγμή. + Οι ρυθμίσεις μπαταρίας του Android καθυστέρησαν την έξοδο έκτακτης ανάγκης σας. Ανοίξτε το Bitkit πριν από τις {time} για να συνεχίσει κανονικά. + Η έξοδος έκτακτης ανάγκης σας δεν μπόρεσε να συνεχίσει στο παρασκήνιο. Ανοίξτε το Bitkit πριν από τις {time} για να συνεχίσει κανονικά. + Η έξοδος έκτακτης ανάγκης σας σταμάτησε. Ανοίξτε το Bitkit για να δείτε γιατί. + Η έξοδος έκτακτης ανάγκης σας χρειάζεται περισσότερη χρηματοδότηση τελών. Ανοίξτε το Bitkit για να τη χρηματοδοτήσετε. + Η έξοδος έκτακτης ανάγκης σας έμεινε πίσω στο παρασκήνιο. Ανοίξτε το Bitkit για να τη συνεχίσετε. + {amount} της εξόδου σας δεν μπορούν να ανακτηθούν. Ανοίξτε το Bitkit για να δείτε γιατί. + Η έξοδος έκτακτης ανάγκης σας δεν μπορεί να συνεχίσει χωρίς internet. Συνδεθείτε και ανοίξτε το Bitkit πριν από τις {time} για να συνεχίσει κανονικά. + Ορισμένες συναλλαγές της εξόδου έκτακτης ανάγκης σας απορρίφθηκαν. Ανοίξτε το Bitkit πριν από τις {time} για να δείτε γιατί. + Το Android εμποδίζει το Bitkit να εκτελείται στο παρασκήνιο. Ανοίξτε το Bitkit πριν από τις {time} για να συνεχίσει κανονικά η έξοδος έκτακτης ανάγκης σας. + Έξοδος έκτακτης ανάγκης + {amount} στο Spark δεν είναι μέρος αυτής της εξόδου και παραμένουν στο Spark. + {count} μικρά ποσά έμειναν στο Spark. + Η έξοδος εκτελείται στο παρασκήνιο, ακόμα και όταν το Bitkit είναι κλειστό. Το Bitkit σας ειδοποιεί αν σας χρειαστεί. + Έξοδος\n<accent>σε εξέλιξη</accent> + Δεν ήταν δυνατή η λήψη προσφοράς εξόδου. Δοκιμάστε ξανά. + Λήψη προσφοράς… + {amount} του υπολοίπου σας στο Spark δεν μπορούν να βγουν αυτή τη στιγμή: ποσά πολύ μικρά για να πληρώσουν τα δικά τους τέλη, ή που ακόμα μετακινούνται μέσα στο Spark. Παραμένουν στο Spark. + Αναμονή για να ολοκληρώσει το Spark τη μετακίνηση του υπολοίπου σας. Αυτό μπορεί να διαρκέσει έως 5 λεπτά. + Προσφορά\n<accent>εξόδου</accent> + Έτοιμο σε {duration} + Το Bitkit δεν μπόρεσε να διαβάσει την αποθηκευμένη πρόοδο αυτής της εξόδου, οπότε την ανακατασκευάζει από το blockchain. + Λαμβάνετε περίπου + Τέλος πληρωμής από αποταμιεύσεις + Σύνολο από αποταμιεύσεις + Επιβεβαίωση χρηματοδότησης τελών + Δημοσίευση συναλλαγών εξόδου + Αποστολή στις αποταμιεύσεις + Αναμονή για το timelock + ID συναλλαγής: {txid} + Σύρετε Για Έξοδο + Τα τέλη είναι υψηλότερα από όσα θα λαμβάνατε. + Μέρος αυτής της εξόδου δεν μπορεί να διαβαστεί on-chain αυτή τη στιγμή. Το Bitkit προσπαθεί ξανά για έως μία εβδομάδα. + {amount} που μετέφεραν on-chain οι διαχειριστές του Spark περιμένουν να τα αποδεσμεύσουν. Το Bitkit ζητά ξανά για έως μία εβδομάδα. Πάροχος Spark μέσω Breez Χωρίς όριο diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 64790a34ce..129e55b529 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -235,101 +235,101 @@ Esperar Depósitos reclamados Depósitos en curso - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Importe a retirar + Salida de emergencia + Cancelar salida + No se pudo comprobar la dirección de financiación. Inténtalo de nuevo. + Spark vuelve a quedar como estaba. Si un pago llegó a la dirección de financiación de comisiones de la salida, Bitkit lo devuelve a tus ahorros. + ¿Cancelar la salida? + Has cancelado la salida. La financiación de comisiones que llegó vuelve a tus ahorros. + Salida\n<accent>cancelada</accent> + No podrás usar estos fondos durante <accent>hasta 4 semanas</accent>. + ¿Iniciar\n<accent>salida?</accent> + {amount} ha llegado a tus ahorros. + Tus fondos están en tus ahorros. + Salida\n<accent>completada</accent> + Los operadores de Spark han movido {amount} on-chain y ya no está en Spark. Los operadores aún pueden liberártelo. + {amount} se queda en Spark. + No se pudo recuperar nada. + Salida\n<accent>detenida</accent> + Pagar una comisión más alta + Usar esta comisión + No se pudo calcular una comisión más alta. Inténtalo de nuevo. + Una comisión más alta dejaría parte de esta salida en Spark, así que no se ofrece ninguna. La salida se confirma cuando bajen las comisiones de la red. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Esta salida paga <accent>{rate} sat/vB</accent>, menos de lo que pide la red ahora. Elige una tarifa más alta y Bitkit vuelve a enviar los pasos pendientes. La diferencia se paga desde tus ahorros: el importe junto a cada velocidad. + Pagar una\n<accent>comisión más alta</accent> + La red está más congestionada que la tarifa de {rate} sat/vB de esta salida. Paga una comisión más alta o espera a que bajen las comisiones. + Las comisiones de la red superaron la comisión de esta salida. Puede ralentizarse. + Comisiones de red + Financiar desde otro monedero + Envía al menos {amount} a esta dirección. La salida empieza cuando se confirme. + Tus ahorros no alcanzan para la financiación de comisiones. + Pagado desde ahorros, esperando confirmación. + {received} de {required} recibidos, envía {missing} más. + Pago detectado, esperando confirmación. + Pagar desde ahorros + Pago detectado. + Financiación de comisiones necesaria + Bitkit lo divide en {count} partes, una por cada paso, para que un paso atascado no bloquee a los demás. + La salida paga sus comisiones con un pago on-chain aparte de <accent>{amount}</accent>. Lo que no gaste vuelve a tus ahorros al final. + Financiar las\n<accent>comisiones</accent> + ID de transacción: {txid} + Úsala solo si Spark deja de funcionarte. Mueve tu saldo de gastos a tus ahorros <accent>sin los operadores de Spark</accent>.\n\nTarda <accent>hasta 4 semanas</accent>, cuesta comisiones on-chain pagadas desde tus ahorros y los importes muy pequeños pueden quedarse atrás. Funciona en segundo plano y Bitkit te avisa si te necesita. + Salir de Spark\n<accent>on-chain</accent> + Se queda en Spark + {amount} no se puede retirar con esta tarifa y se queda en Spark. + {amount} de la financiación de comisiones sigue en {address}. + {amount} de financiación de comisiones sobrante es demasiado poco para enviarse y se queda en {address}, ruta de derivación {path}. + {amount} de financiación de comisiones sobrante no se pudo enviar y se queda en {address}, ruta de derivación {path}. + Enviando {amount} de financiación de comisiones sobrante a tus ahorros. + {amount} de financiación de comisiones sobrante se ha enviado a tus ahorros. + ID de transacción: {txid} + {amount} de cambio de comisiones llegará a tus ahorros cuando bajen las comisiones de la red. + Un propietario anterior de estos fondos ha reclamado {amount} on-chain y no se puede recuperar. + Salida de emergencia + La salida necesita <accent>{amount}</accent> más para pagar sus comisiones. Fináncala para continuar. + Se necesitan\n<accent>más comisiones</accent> + La salida no avanza: {error} + La optimización de batería de Android puede retrasar la salida mientras Bitkit está cerrado. Bitkit te avisa si se retrasa. + El ahorro de batería está activado, así que Android puede frenar la salida mientras Bitkit está cerrado. + Las notificaciones están desactivadas, así que Bitkit no puede avisarte si la salida te necesita. Sin ellas, abre Bitkit cada pocas horas hasta que termine la salida. + Activar notificaciones + Android restringe Bitkit en segundo plano, así que la salida solo avanza mientras Bitkit está abierto. Permite el uso en segundo plano para Bitkit en los ajustes de Android. + Ahora mismo no se puede retirar nada. + Los ajustes de batería de Android han frenado tu salida de emergencia. Abre Bitkit antes de las {time} para que siga su curso. + Tu salida de emergencia no pudo continuar en segundo plano. Abre Bitkit antes de las {time} para que siga su curso. + Tu salida de emergencia se ha detenido. Abre Bitkit para ver por qué. + Tu salida de emergencia necesita más financiación de comisiones. Abre Bitkit para financiarla. + Tu salida de emergencia se ha retrasado en segundo plano. Abre Bitkit para continuarla. + {amount} de tu salida no se puede recuperar. Abre Bitkit para ver por qué. + Tu salida de emergencia no puede continuar sin internet. Conéctate y abre Bitkit antes de las {time} para que siga su curso. + Se han rechazado algunas transacciones de tu salida de emergencia. Abre Bitkit antes de las {time} para ver por qué. + Android impide que Bitkit se ejecute en segundo plano. Abre Bitkit antes de las {time} para que tu salida de emergencia siga su curso. + Salida de emergencia + {amount} en Spark no forma parte de esta salida y se queda en Spark. + {count} importes pequeños se han quedado en Spark. + La salida funciona en segundo plano, también con Bitkit cerrado. Bitkit te avisa si te necesita. + Salida\n<accent>en curso</accent> + No se pudo obtener una cotización de salida. Inténtalo de nuevo. + Obteniendo cotización… + {amount} de tu saldo de Spark no se puede retirar ahora: importes demasiado pequeños para pagar sus propias comisiones, o que aún se están moviendo dentro de Spark. Se queda en Spark. + Esperando a que Spark termine de mover tu saldo. Esto puede tardar hasta 5 minutos. + Cotización\n<accent>de salida</accent> + Listo en {duration} + Bitkit no pudo leer el progreso guardado de esta salida, así que lo reconstruye a partir de la cadena. + Recibes aproximadamente + Comisión del pago desde ahorros + Total desde ahorros + Confirmación de la financiación de comisiones + Publicando transacciones de salida + Enviando a ahorros + Esperando el bloqueo temporal + ID de transacción: {txid} + Desliza para salir + Las comisiones son mayores que lo que recibirías. + Ahora mismo no se puede leer on-chain parte de esta salida. Bitkit lo vuelve a intentar durante hasta una semana. + {amount} que los operadores de Spark movieron on-chain espera a que lo liberen. Bitkit vuelve a pedirlo durante hasta una semana. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index e7e7df03f1..8cd88075af 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -177,101 +177,101 @@ Esperar Depósitos reclamados Depósitos en curso - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Importe a retirar + Salida de emergencia + Cancelar salida + No se pudo comprobar la dirección de financiación. Inténtalo de nuevo. + Spark vuelve a quedar como estaba. Si un pago llegó a la dirección de financiación de comisiones de la salida, Bitkit lo devuelve a tus ahorros. + ¿Cancelar la salida? + Cancelaste la salida. La financiación de comisiones que llegó vuelve a tus ahorros. + Salida\n<accent>cancelada</accent> + No podrás usar estos fondos durante <accent>hasta 4 semanas</accent>. + ¿Iniciar\n<accent>salida?</accent> + {amount} llegó a tus ahorros. + Tus fondos están en tus ahorros. + Salida\n<accent>completada</accent> + Los operadores de Spark movieron {amount} on-chain y ya no está en Spark. Los operadores aún pueden liberártelo. + {amount} se queda en Spark. + No se pudo recuperar nada. + Salida\n<accent>detenida</accent> + Pagar una comisión más alta + Usar esta comisión + No se pudo calcular una comisión más alta. Inténtalo de nuevo. + Una comisión más alta dejaría parte de esta salida en Spark, así que no se ofrece ninguna. La salida se confirma cuando bajen las comisiones de la red. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Esta salida paga <accent>{rate} sat/vB</accent>, menos de lo que pide la red ahora. Elige una tarifa más alta y Bitkit vuelve a enviar los pasos pendientes. La diferencia se paga desde tus ahorros: el importe junto a cada velocidad. + Pagar una\n<accent>comisión más alta</accent> + La red está más congestionada que la tarifa de {rate} sat/vB de esta salida. Paga una comisión más alta o espera a que bajen las comisiones. + Las comisiones de la red superaron la comisión de esta salida. Puede ralentizarse. + Comisiones de red + Financiar desde otro monedero + Envía al menos {amount} a esta dirección. La salida empieza cuando se confirme. + Tus ahorros no alcanzan para la financiación de comisiones. + Pagado desde ahorros, esperando confirmación. + {received} de {required} recibidos, envía {missing} más. + Pago detectado, esperando confirmación. + Pagar desde ahorros + Pago detectado. + Financiación de comisiones necesaria + Bitkit lo divide en {count} partes, una por cada paso, para que un paso atascado no bloquee a los demás. + La salida paga sus comisiones con un pago on-chain aparte de <accent>{amount}</accent>. Lo que no gaste vuelve a tus ahorros al final. + Financiar las\n<accent>comisiones</accent> + ID de transacción: {txid} + Úsala solo si Spark deja de funcionarte. Mueve tu saldo de gastos a tus ahorros <accent>sin los operadores de Spark</accent>.\n\nTarda <accent>hasta 4 semanas</accent>, cuesta comisiones on-chain pagadas desde tus ahorros y los importes muy pequeños pueden quedarse atrás. Funciona en segundo plano y Bitkit te avisa si te necesita. + Salir de Spark\n<accent>on-chain</accent> + Se queda en Spark + {amount} no se puede retirar con esta tarifa y se queda en Spark. + {amount} de la financiación de comisiones sigue en {address}. + {amount} de financiación de comisiones sobrante es demasiado poco para enviarse y se queda en {address}, ruta de derivación {path}. + {amount} de financiación de comisiones sobrante no se pudo enviar y se queda en {address}, ruta de derivación {path}. + Enviando {amount} de financiación de comisiones sobrante a tus ahorros. + {amount} de financiación de comisiones sobrante se envió a tus ahorros. + ID de transacción: {txid} + {amount} de cambio de comisiones llegará a tus ahorros cuando bajen las comisiones de la red. + Un propietario anterior de estos fondos reclamó {amount} on-chain y no se puede recuperar. + Salida de emergencia + La salida necesita <accent>{amount}</accent> más para pagar sus comisiones. Fináncala para continuar. + Se necesitan\n<accent>más comisiones</accent> + La salida no avanza: {error} + La optimización de batería de Android puede retrasar la salida mientras Bitkit está cerrado. Bitkit te avisa si se retrasa. + El ahorro de batería está activado, así que Android puede frenar la salida mientras Bitkit está cerrado. + Las notificaciones están desactivadas, así que Bitkit no puede avisarte si la salida te necesita. Sin ellas, abre Bitkit cada pocas horas hasta que termine la salida. + Activar notificaciones + Android restringe Bitkit en segundo plano, así que la salida solo avanza mientras Bitkit está abierto. Permite el uso en segundo plano para Bitkit en los ajustes de Android. + Ahora mismo no se puede retirar nada. + Los ajustes de batería de Android frenaron tu salida de emergencia. Abre Bitkit antes de las {time} para que siga su curso. + Tu salida de emergencia no pudo continuar en segundo plano. Abre Bitkit antes de las {time} para que siga su curso. + Tu salida de emergencia se detuvo. Abre Bitkit para ver por qué. + Tu salida de emergencia necesita más financiación de comisiones. Abre Bitkit para financiarla. + Tu salida de emergencia se retrasó en segundo plano. Abre Bitkit para continuarla. + {amount} de tu salida no se puede recuperar. Abre Bitkit para ver por qué. + Tu salida de emergencia no puede continuar sin internet. Conéctate y abre Bitkit antes de las {time} para que siga su curso. + Se rechazaron algunas transacciones de tu salida de emergencia. Abre Bitkit antes de las {time} para ver por qué. + Android impide que Bitkit se ejecute en segundo plano. Abre Bitkit antes de las {time} para que tu salida de emergencia siga su curso. + Salida de emergencia + {amount} en Spark no forma parte de esta salida y se queda en Spark. + {count} importes pequeños se quedaron en Spark. + La salida funciona en segundo plano, también con Bitkit cerrado. Bitkit te avisa si te necesita. + Salida\n<accent>en curso</accent> + No se pudo obtener una cotización de salida. Inténtalo de nuevo. + Obteniendo cotización… + {amount} de tu saldo de Spark no se puede retirar ahora: importes demasiado pequeños para pagar sus propias comisiones, o que aún se están moviendo dentro de Spark. Se queda en Spark. + Esperando a que Spark termine de mover tu saldo. Esto puede tardar hasta 5 minutos. + Cotización\n<accent>de salida</accent> + Listo en {duration} + Bitkit no pudo leer el progreso guardado de esta salida, así que lo reconstruye a partir de la cadena. + Recibes aproximadamente + Comisión del pago desde ahorros + Total desde ahorros + Confirmación de la financiación de comisiones + Publicando transacciones de salida + Enviando a ahorros + Esperando el bloqueo temporal + ID de transacción: {txid} + Desliza para salir + Las comisiones son mayores que lo que recibirías. + Ahora mismo no se puede leer on-chain parte de esta salida. Bitkit lo vuelve a intentar durante hasta una semana. + {amount} que los operadores de Spark movieron on-chain espera a que lo liberen. Bitkit vuelve a pedirlo durante hasta una semana. Proveedor Spark mediante Breez Sin límite diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 8d900ee081..f0a529688c 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -111,101 +111,101 @@ Attendre Dépôts réclamés Dépôts en cours - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Montant à sortir + Sortie d\'urgence + Annuler la sortie + Impossible de vérifier l\'adresse de financement. Réessayez. + Spark revient à son état précédent. Si un paiement a atteint l\'adresse de financement des frais de la sortie, Bitkit le renvoie vers l\'épargne. + Annuler la sortie ? + Vous avez annulé la sortie. Le financement des frais reçu retourne vers l\'épargne. + Sortie\n<accent>annulée</accent> + Vous ne pourrez pas utiliser ces fonds pendant <accent>jusqu\'à 4 semaines</accent>. + Lancer la\n<accent>sortie ?</accent> + {amount} est arrivé dans votre épargne. + Vos fonds sont dans votre épargne. + Sortie\n<accent>terminée</accent> + {amount} a été déplacé on-chain par les opérateurs Spark et n\'est pas sur Spark. Les opérateurs peuvent encore vous le libérer. + {amount} reste sur Spark. + Rien n\'a pu être récupéré. + Sortie\n<accent>interrompue</accent> + Payer des frais plus élevés + Utiliser ces frais + Impossible de calculer des frais plus élevés. Réessayez. + Des frais plus élevés laisseraient une partie de cette sortie sur Spark, donc aucun n\'est proposé. La sortie sera confirmée quand les frais de réseau baisseront. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Cette sortie paie <accent>{rate} sat/vB</accent>, moins que ce que le réseau demande actuellement. Choisissez un taux plus élevé et Bitkit renvoie les étapes en attente. La différence est payée depuis l\'épargne : le montant à côté de chaque vitesse. + Payer des\n<accent>frais plus élevés</accent> + Le réseau est plus chargé que le taux de frais de cette sortie, {rate} sat/vB. Payez des frais plus élevés ou attendez que les frais baissent. + Les frais de réseau ont dépassé ceux de cette sortie. Elle peut ralentir. + Frais de réseau + Financer depuis un autre portefeuille + Envoyez au moins {amount} à cette adresse. La sortie démarre dès sa confirmation. + Votre épargne ne peut pas couvrir le financement des frais. + Payé depuis l\'épargne, en attente de confirmation. + {received} sur {required} reçus, envoyez encore {missing}. + Paiement détecté, en attente de confirmation. + Payer depuis l\'épargne + Paiement détecté. + Financement des frais requis + Bitkit le divise en {count} parties, une pour chaque étape, afin qu\'une étape bloquée ne retarde pas les autres. + La sortie paie ses frais avec un paiement on-chain séparé de <accent>{amount}</accent>. Ce qu\'elle ne dépense pas revient à l\'épargne à la fin. + Financer les\n<accent>frais</accent> + ID de la transaction : {txid} + N\'utilisez ceci que si Spark ne fonctionne plus pour vous. Cela transfère votre solde de dépenses vers l\'épargne <accent>sans les opérateurs Spark</accent>.\n\nCela prend <accent>jusqu\'à 4 semaines</accent>, coûte des frais on-chain payés depuis l\'épargne, et de très petits montants peuvent rester sur place. Cela s\'exécute en arrière-plan, et Bitkit vous prévient s\'il a besoin de vous. + Quitter Spark\n<accent>on-chain</accent> + Reste sur Spark + {amount} ne peut pas sortir à ce taux de frais et reste sur Spark. + {amount} de financement des frais se trouve encore à {address}. + {amount} de financement des frais restant est trop faible pour être envoyé et reste à {address}, chemin de dérivation {path}. + {amount} de financement des frais restant n\'a pas pu être envoyé et reste à {address}, chemin de dérivation {path}. + Envoi de {amount} de financement des frais restant vers l\'épargne. + {amount} de financement des frais restant a été envoyé vers l\'épargne. + ID de la transaction : {txid} + {amount} de monnaie des frais arrivera dans votre épargne quand les frais de réseau baisseront. + {amount} a été réclamé on-chain par un ancien propriétaire de ces fonds et ne peut pas être récupéré. + Sortie d\'urgence + La sortie a besoin de <accent>{amount}</accent> de plus pour payer ses frais. Financez-la pour continuer. + Plus de frais\n<accent>requis</accent> + La sortie n\'avance pas : {error} + L\'optimisation de la batterie d\'Android peut retarder la sortie quand Bitkit est fermé. Bitkit vous prévient si elle prend du retard. + L\'économiseur de batterie est activé, Android peut donc freiner la sortie quand Bitkit est fermé. + Les notifications sont désactivées, Bitkit ne peut donc pas vous prévenir si la sortie a besoin de vous. Sans elles, ouvrez Bitkit toutes les quelques heures jusqu\'à la fin de la sortie. + Activer les notifications + Android limite Bitkit en arrière-plan, la sortie n\'avance donc que lorsque Bitkit est ouvert. Autorisez l\'utilisation en arrière-plan pour Bitkit dans les paramètres Android. + Rien ne peut sortir pour le moment. + Les paramètres de batterie d\'Android ont freiné votre sortie d\'urgence. Ouvrez Bitkit avant {time} pour qu\'elle reste sur la bonne voie. + Votre sortie d\'urgence n\'a pas pu continuer en arrière-plan. Ouvrez Bitkit avant {time} pour qu\'elle reste sur la bonne voie. + Votre sortie d\'urgence s\'est arrêtée. Ouvrez Bitkit pour savoir pourquoi. + Votre sortie d\'urgence a besoin de plus de financement des frais. Ouvrez Bitkit pour la financer. + Votre sortie d\'urgence a pris du retard en arrière-plan. Ouvrez Bitkit pour la poursuivre. + {amount} de votre sortie ne peut pas être récupéré. Ouvrez Bitkit pour savoir pourquoi. + Votre sortie d\'urgence ne peut pas continuer sans internet. Connectez-vous et ouvrez Bitkit avant {time} pour qu\'elle reste sur la bonne voie. + Certaines transactions de votre sortie d\'urgence ont été refusées. Ouvrez Bitkit avant {time} pour savoir pourquoi. + Android empêche Bitkit de fonctionner en arrière-plan. Ouvrez Bitkit avant {time} pour que votre sortie d\'urgence reste sur la bonne voie. + Sortie d\'urgence + {amount} sur Spark ne fait pas partie de cette sortie et reste sur Spark. + {count} petits montants sont restés sur Spark. + La sortie s\'exécute en arrière-plan, même quand Bitkit est fermé. Bitkit vous prévient s\'il a besoin de vous. + Sortie\n<accent>en cours</accent> + Impossible d\'obtenir un devis de sortie. Réessayez. + Obtention d\'un devis… + {amount} de votre solde Spark ne peut pas sortir pour le moment : des montants trop faibles pour payer leurs propres frais, ou encore en mouvement dans Spark. Il reste sur Spark. + En attente que Spark finisse de déplacer votre solde. Cela peut prendre jusqu\'à 5 minutes. + Devis de\n<accent>sortie</accent> + Prêt dans {duration} + Bitkit n\'a pas pu lire la progression enregistrée de cette sortie, il la reconstruit donc depuis la chaîne. + Vous recevez environ + Frais du paiement depuis l\'épargne + Total depuis l\'épargne + Confirmation du financement des frais + Publication des transactions de sortie + Envoi vers l\'épargne + En attente du timelock + ID de la transaction : {txid} + Glisser pour sortir + Les frais sont supérieurs à ce que vous recevriez. + Une partie de cette sortie ne peut pas être lue on-chain pour le moment. Bitkit réessaie pendant une semaine au maximum. + {amount} que les opérateurs Spark ont déplacé on-chain attend qu\'ils le libèrent. Bitkit le leur redemande pendant une semaine au maximum. Fournisseur Spark via Breez Sans limite diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 2c7f28cdd7..163b52059b 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -234,101 +234,101 @@ Attendi Depositi riscattati Depositi in corso - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Importo da far uscire + Uscita di emergenza + Annulla uscita + Impossibile verificare l\'indirizzo di finanziamento. Riprova. + Spark torna com\'era prima. Se un pagamento ha raggiunto l\'indirizzo di finanziamento delle commissioni dell\'uscita, Bitkit lo rimanda ai risparmi. + Annullare l\'uscita? + Hai annullato l\'uscita. Il finanziamento delle commissioni arrivato torna ai risparmi. + Uscita\n<accent>annullata</accent> + Non potrai usare questi fondi per <accent>un massimo di 4 settimane</accent>. + Avviare\n<accent>l\'uscita?</accent> + {amount} è arrivato nei tuoi risparmi. + I tuoi fondi sono nei risparmi. + Uscita\n<accent>completata</accent> + {amount} è stato spostato on-chain dagli operatori Spark e non è su Spark. Gli operatori possono ancora sbloccarlo per te. + {amount} resta su Spark. + Non è stato possibile recuperare nulla. + Uscita\n<accent>interrotta</accent> + Paga una commissione più alta + Usa questa commissione + Impossibile calcolare una commissione più alta. Riprova. + Una commissione più alta lascerebbe parte di questa uscita su Spark, quindi non ne viene proposta nessuna. L\'uscita si conferma quando le commissioni di rete scendono. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Questa uscita paga <accent>{rate} sat/vB</accent>, meno di quanto chiede ora la rete. Scegli una tariffa più alta e Bitkit invia di nuovo i passaggi in attesa. La differenza viene pagata dai risparmi: l\'importo accanto a ogni velocità. + Paga una\n<accent>commissione più alta</accent> + La rete è più congestionata della tariffa di questa uscita, {rate} sat/vB. Paga una commissione più alta o attendi che le commissioni scendano. + Le commissioni di rete hanno superato quella di questa uscita. Potrebbe rallentare. + Commissioni di rete + Finanzia da un altro portafoglio + Invia almeno {amount} a questo indirizzo. L\'uscita inizia appena viene confermato. + I tuoi risparmi non coprono il finanziamento delle commissioni. + Pagato dai risparmi, in attesa di conferma. + {received} di {required} ricevuti, invia altri {missing}. + Pagamento rilevato, in attesa di conferma. + Paga dai risparmi + Pagamento rilevato. + Finanziamento delle commissioni necessario + Bitkit lo divide in {count} parti, una per ogni passaggio, così un passaggio bloccato non ferma gli altri. + L\'uscita paga le commissioni con un pagamento on-chain separato di <accent>{amount}</accent>. Quello che non spende torna ai risparmi alla fine. + Finanzia le\n<accent>commissioni</accent> + ID Transazione: {txid} + Usala solo se Spark smette di funzionare per te. Sposta il tuo saldo di spesa nei risparmi <accent>senza gli operatori Spark</accent>.\n\nRichiede <accent>fino a 4 settimane</accent>, costa commissioni on-chain pagate dai risparmi e importi molto piccoli possono restare indietro. Funziona in background e Bitkit ti avvisa se ha bisogno di te. + Lascia Spark\n<accent>on-chain</accent> + Resta su Spark + {amount} non può uscire con questa tariffa e resta su Spark. + {amount} di finanziamento delle commissioni è ancora su {address}. + {amount} di finanziamento delle commissioni rimanente è troppo piccolo da inviare e resta su {address}, percorso di derivazione {path}. + {amount} di finanziamento delle commissioni rimanente non è stato inviato e resta su {address}, percorso di derivazione {path}. + Invio di {amount} di finanziamento delle commissioni rimanente ai risparmi. + {amount} di finanziamento delle commissioni rimanente è stato inviato ai risparmi. + ID Transazione: {txid} + {amount} di resto delle commissioni arriverà nei tuoi risparmi quando le commissioni di rete scendono. + {amount} è stato riscattato on-chain da un precedente proprietario di questi fondi e non può essere recuperato. + Uscita di Emergenza + All\'uscita servono altri <accent>{amount}</accent> per pagare le commissioni. Finanziala per continuare. + Servono altre\n<accent>commissioni</accent> + L\'uscita non avanza: {error} + L\'ottimizzazione della batteria di Android può ritardare l\'uscita mentre Bitkit è chiuso. Bitkit ti avvisa se resta indietro. + Il risparmio energetico è attivo, quindi Android può frenare l\'uscita mentre Bitkit è chiuso. + Le notifiche sono disattivate, quindi Bitkit non può avvisarti se l\'uscita ha bisogno di te. Senza notifiche, apri Bitkit ogni poche ore finché l\'uscita non termina. + Attiva le notifiche + Android limita Bitkit in background, quindi l\'uscita avanza solo mentre Bitkit è aperto. Consenti l\'uso in background per Bitkit nelle impostazioni di Android. + Al momento non è possibile far uscire nulla. + Le impostazioni della batteria di Android hanno frenato la tua uscita di emergenza. Apri Bitkit prima delle {time} per mantenerla in linea. + La tua uscita di emergenza non ha potuto continuare in background. Apri Bitkit prima delle {time} per mantenerla in linea. + La tua uscita di emergenza si è fermata. Apri Bitkit per scoprire perché. + La tua uscita di emergenza ha bisogno di altro finanziamento delle commissioni. Apri Bitkit per finanziarla. + La tua uscita di emergenza è rimasta indietro in background. Apri Bitkit per continuarla. + {amount} della tua uscita non può essere recuperato. Apri Bitkit per scoprire perché. + La tua uscita di emergenza non può continuare senza internet. Connettiti e apri Bitkit prima delle {time} per mantenerla in linea. + Alcune transazioni della tua uscita di emergenza sono state rifiutate. Apri Bitkit prima delle {time} per scoprire perché. + Android impedisce a Bitkit di funzionare in background. Apri Bitkit prima delle {time} per mantenere in linea la tua uscita di emergenza. + Uscita di emergenza + {amount} su Spark non fa parte di questa uscita e resta su Spark. + {count} piccoli importi sono rimasti su Spark. + L\'uscita funziona in background, anche mentre Bitkit è chiuso. Bitkit ti avvisa se ha bisogno di te. + Uscita\n<accent>in corso</accent> + Impossibile ottenere un preventivo di uscita. Riprova. + Recupero del preventivo… + {amount} del tuo saldo Spark non può uscire al momento: importi troppo piccoli per pagare le proprie commissioni, o ancora in movimento all\'interno di Spark. Resta su Spark. + In attesa che Spark finisca di spostare il tuo saldo. Può richiedere fino a 5 minuti. + Preventivo\n<accent>di uscita</accent> + Pronto tra {duration} + Bitkit non è riuscito a leggere i progressi salvati di questa uscita, quindi li ricostruisce dalla blockchain. + Riceverai circa + Commissione del pagamento dai risparmi + Totale dai risparmi + Conferma del finanziamento delle commissioni + Pubblicazione delle transazioni di uscita + Invio ai risparmi + In attesa del timelock + ID Transazione: {txid} + Scorri per uscire + Le commissioni sono più alte di quanto riceveresti. + Al momento una parte di questa uscita non può essere letta on-chain. Bitkit riprova per un massimo di una settimana. + {amount} che gli operatori Spark hanno spostato on-chain attende che lo sblocchino. Bitkit lo richiede di nuovo per un massimo di una settimana. Fornitore Spark tramite Breez Nessun limite diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 8e58ae6c45..72682c242c 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -233,101 +233,101 @@ Wachten Geclaimde stortingen Lopende stortingen - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Bedrag voor exit + Noodexit + Exit annuleren + Kon het financieringsadres niet controleren. Probeer opnieuw. + Spark keert terug naar hoe het was. Als er een betaling op het financieringsadres voor de kosten van de exit is aangekomen, stuurt Bitkit die terug naar spaargeld. + Exit annuleren? + Je hebt de exit geannuleerd. De aangekomen kostenfinanciering gaat terug naar spaargeld. + Exit\n<accent>geannuleerd</accent> + Je kunt dit geld <accent>tot 4 weken</accent> niet gebruiken. + Exit\n<accent>starten?</accent> + {amount} is in je spaargeld aangekomen. + Je geld staat in je spaargeld. + Exit\n<accent>voltooid</accent> + {amount} is door de Spark-beheerders on-chain verplaatst en staat niet op Spark. De beheerders kunnen het nog steeds aan je vrijgeven. + {amount} blijft op Spark. + Er kon niets worden teruggehaald. + Exit\n<accent>gestopt</accent> + Hogere kosten betalen + Deze kosten gebruiken + Kon geen prijs voor hogere kosten bepalen. Probeer opnieuw. + Hogere kosten zouden een deel van deze exit op Spark laten, dus die worden niet aangeboden. De exit wordt bevestigd zodra de netwerkkosten dalen. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Deze exit betaalt <accent>{rate} sat/vB</accent>, minder dan het netwerk nu vraagt. Kies een hoger tarief en Bitkit verstuurt de wachtende stappen opnieuw. Het verschil wordt betaald uit spaargeld: het bedrag naast elke snelheid. + Hogere\n<accent>kosten betalen</accent> + Het netwerk is drukker dan het kostentarief van deze exit van {rate} sat/vB. Betaal hogere kosten of wacht tot de kosten dalen. + De netwerkkosten zijn hoger geworden dan de kosten van deze exit. Het kan vertragen. + Netwerkkosten + Financieren vanuit een andere wallet + Stuur minstens {amount} naar dit adres. De exit start zodra het is bevestigd. + Je spaargeld is niet genoeg voor de kostenfinanciering. + Betaald uit spaargeld, wachten op bevestiging. + {received} van {required} ontvangen, stuur nog {missing}. + Betaling gezien, wachten op bevestiging. + Betalen uit spaargeld + Betaling gezien. + Kostenfinanciering nodig + Bitkit splitst het in {count} delen, één voor elke stap, zodat één vastgelopen stap de andere niet ophoudt. + De exit betaalt zijn kosten uit een aparte on-chain betaling van <accent>{amount}</accent>. Wat niet wordt uitgegeven, komt aan het einde terug naar spaargeld. + Financier de\n<accent>kosten</accent> + Transactie-ID: {txid} + Gebruik dit alleen als Spark niet meer voor je werkt. Het verplaatst je bestedingssaldo naar spaargeld <accent>zonder de Spark-beheerders</accent>.\n\nHet duurt <accent>tot 4 weken</accent>, kost on-chain kosten die uit spaargeld worden betaald, en zeer kleine bedragen kunnen achterblijven. Het loopt op de achtergrond en Bitkit laat het je weten als het je nodig heeft. + Spark verlaten\n<accent>via on-chain</accent> + Blijft op Spark + {amount} kan bij dit kostentarief niet worden opgenomen in de exit en blijft op Spark. + {amount} aan kostenfinanciering staat nog op {address}. + {amount} aan overgebleven kostenfinanciering is te klein om te versturen en blijft op {address}, afleidingspad {path}. + {amount} aan overgebleven kostenfinanciering kon niet worden verstuurd en blijft op {address}, afleidingspad {path}. + {amount} aan overgebleven kostenfinanciering wordt naar spaargeld gestuurd. + {amount} aan overgebleven kostenfinanciering is naar spaargeld gestuurd. + Transactie-ID: {txid} + {amount} aan wisselgeld van de kosten komt in je spaargeld aan wanneer de netwerkkosten dalen. + {amount} is on-chain geclaimd door een eerdere eigenaar van dit geld en kan niet worden teruggehaald. + Noodexit + De exit heeft nog <accent>{amount}</accent> nodig om zijn kosten te betalen. Financier het om door te gaan. + Meer kosten\n<accent>nodig</accent> + De exit schiet niet op: {error} + De batterijoptimalisatie van Android kan de exit vertragen terwijl Bitkit gesloten is. Bitkit laat het je weten als de exit achterloopt. + Batterijbesparing staat aan, dus Android kan de exit ophouden terwijl Bitkit gesloten is. + Meldingen staan uit, dus Bitkit kan je niet laten weten als de exit je nodig heeft. Open zonder meldingen Bitkit om de paar uur totdat de exit klaar is. + Meldingen inschakelen + Android beperkt Bitkit op de achtergrond, dus de exit schiet alleen op terwijl Bitkit open is. Sta achtergrondgebruik voor Bitkit toe in de Android-instellingen. + Er kan nu niets worden opgenomen in een exit. + De batterij-instellingen van Android hebben je noodexit opgehouden. Open Bitkit vóór {time} om hem op koers te houden. + Je noodexit kon niet doorgaan op de achtergrond. Open Bitkit vóór {time} om hem op koers te houden. + Je noodexit is gestopt. Open Bitkit om te zien waarom. + Je noodexit heeft meer kostenfinanciering nodig. Open Bitkit om hem te financieren. + Je noodexit is achtergeraakt op de achtergrond. Open Bitkit om hem voort te zetten. + {amount} van je exit kan niet worden teruggehaald. Open Bitkit om te zien waarom. + Je noodexit kan niet doorgaan zonder internet. Maak verbinding en open Bitkit vóór {time} om hem op koers te houden. + Sommige transacties van je noodexit zijn geweigerd. Open Bitkit vóór {time} om te zien waarom. + Android verhindert dat Bitkit op de achtergrond draait. Open Bitkit vóór {time} om je noodexit op koers te houden. + Noodexit + {amount} op Spark hoort niet bij deze exit en blijft op Spark. + {count} kleine bedragen zijn op Spark gebleven. + De exit loopt op de achtergrond, ook als Bitkit gesloten is. Bitkit laat het je weten als het je nodig heeft. + Exit\n<accent>bezig</accent> + Kon geen offerte voor de exit ophalen. Probeer opnieuw. + Offerte ophalen… + {amount} van je Spark-saldo kan nu niet worden opgenomen in de exit: bedragen die te klein zijn om hun eigen kosten te betalen, of die nog binnen Spark worden verplaatst. Het blijft op Spark. + Wachten tot Spark klaar is met het verplaatsen van je saldo. Dit kan tot 5 minuten duren. + Exit-\n<accent>offerte</accent> + Klaar over {duration} + Bitkit kon de opgeslagen voortgang van deze exit niet lezen en bouwt die daarom opnieuw op vanuit de blockchain. + Je ontvangt ongeveer + Kosten voor betaling uit spaargeld + Totaal uit spaargeld + Kostenfinanciering wordt bevestigd + Exittransacties publiceren + Naar spaargeld sturen + Wachten op de tijdvergrendeling + Transactie-ID: {txid} + Veeg om te verlaten + De kosten zijn hoger dan wat je zou ontvangen. + Een deel van deze exit kan nu niet on-chain worden gelezen. Bitkit probeert het tot een week lang opnieuw. + {amount} dat de Spark-beheerders on-chain hebben verplaatst, wacht tot zij het vrijgeven. Bitkit vraagt het tot een week lang opnieuw. Aanbieder Spark via Breez Geen limiet diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index b035bf84fc..b7551530f5 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -113,101 +113,101 @@ Czekaj Odebrane wpłaty Wpłaty w toku - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Kwota do wyjścia + Wyjście awaryjne + Anuluj wyjście + Nie udało się sprawdzić adresu finansowania. Spróbuj ponownie. + Spark wraca do poprzedniego stanu. Jeśli płatność dotarła na adres finansowania opłat wyjścia, Bitkit odeśle ją do Oszczędności. + Anulować wyjście? + Anulowałeś wyjście. Środki na opłaty, które dotarły, wracają do Oszczędności. + Wyjście\n<accent>anulowane</accent> + Nie będziesz mógł korzystać z tych środków <accent>przez maksymalnie 4 tygodnie</accent>. + Rozpocząć\n<accent>wyjście?</accent> + {amount} trafiło do Twoich Oszczędności. + Twoje środki są w Oszczędnościach. + Wyjście\n<accent>zakończone</accent> + {amount} zostało przeniesione on-chain przez operatorów Spark i nie jest na Spark. Operatorzy wciąż mogą Ci je zwolnić. + {amount} pozostaje na Spark. + Nie udało się niczego odzyskać. + Wyjście\n<accent>zatrzymane</accent> + Zapłać wyższą opłatę + Użyj tej opłaty + Nie udało się wycenić wyższej opłaty. Spróbuj ponownie. + Wyższa opłata zostawiłaby część tego wyjścia na Spark, więc nie jest oferowana. Wyjście zostanie potwierdzone, gdy opłaty sieciowe spadną. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + To wyjście płaci <accent>{rate} sat/vB</accent>, mniej niż sieć wymaga teraz. Wybierz wyższą stawkę, a Bitkit ponownie wyśle oczekujące kroki. Różnicę pokrywa z Oszczędności: kwota obok każdej prędkości. + Zapłać\n<accent>wyższą opłatę</accent> + Sieć jest bardziej obciążona niż stawka opłaty tego wyjścia wynosząca {rate} sat/vB. Zapłać wyższą opłatę lub poczekaj, aż opłaty spadną. + Opłaty sieciowe wzrosły powyżej opłaty tego wyjścia. Może ono zwolnić. + Opłaty sieciowe + Sfinansuj z innego portfela + Wyślij co najmniej {amount} na ten adres. Wyjście rozpocznie się po potwierdzeniu. + Twoje Oszczędności nie pokrywają finansowania opłat. + Zapłacono z Oszczędności, czekamy na potwierdzenie. + Otrzymano {received} z {required}, wyślij jeszcze {missing}. + Płatność widoczna, czekamy na potwierdzenie. + Zapłać z Oszczędności + Płatność widoczna. + Potrzebne finansowanie opłat + Bitkit dzieli je na {count} części, po jednej na każdy krok, aby jeden zablokowany krok nie wstrzymywał pozostałych. + Wyjście płaci swoje opłaty z osobnej płatności on-chain w wysokości <accent>{amount}</accent>. To, czego nie wyda, wraca na koniec do Oszczędności. + Sfinansuj\n<accent>opłaty</accent> + ID transakcji: {txid} + Używaj tego tylko wtedy, gdy Spark przestanie dla Ciebie działać. Przenosi saldo wydatków do Oszczędności <accent>bez operatorów Spark</accent>.\n\nTrwa <accent>do 4 tygodni</accent>, kosztuje opłaty on-chain pokrywane z Oszczędności, a bardzo małe kwoty mogą pozostać. Działa w tle, a Bitkit powiadomi Cię, jeśli będzie Cię potrzebować. + Opuść Spark\n<accent>on-chain</accent> + Pozostaje na Spark + {amount} nie może wyjść przy tej stawce opłaty i pozostaje na Spark. + {amount} finansowania opłat wciąż znajduje się pod adresem {address}. + {amount} pozostałego finansowania opłat to za mało, by je wysłać, i pozostaje pod adresem {address}, ścieżka derywacji {path}. + {amount} pozostałego finansowania opłat nie udało się wysłać i pozostaje pod adresem {address}, ścieżka derywacji {path}. + Wysyłanie {amount} pozostałego finansowania opłat do Oszczędności. + {amount} pozostałego finansowania opłat wysłano do Oszczędności. + ID transakcji: {txid} + {amount} reszty z opłat trafi do Twoich Oszczędności, gdy opłaty sieciowe spadną. + {amount} zostało przejęte on-chain przez wcześniejszego właściciela tych środków i nie można go odzyskać. + Wyjście awaryjne + Wyjście potrzebuje jeszcze <accent>{amount}</accent> na opłaty. Sfinansuj je, aby kontynuować. + Potrzebne\n<accent>więcej opłat</accent> + Wyjście nie postępuje: {error} + Optymalizacja baterii w Androidzie może opóźnić wyjście, gdy Bitkit jest zamknięty. Bitkit powiadomi Cię, jeśli wyjście się opóźni. + Oszczędzanie baterii jest włączone, więc Android może wstrzymywać wyjście, gdy Bitkit jest zamknięty. + Powiadomienia są wyłączone, więc Bitkit nie może Cię poinformować, gdy wyjście będzie Cię potrzebować. Bez nich otwieraj Bitkit co kilka godzin, aż wyjście się zakończy. + Włącz powiadomienia + Android ogranicza Bitkit w tle, więc wyjście postępuje tylko wtedy, gdy Bitkit jest otwarty. Zezwól na działanie Bitkit w tle w ustawieniach Androida. + Obecnie nic nie może wyjść. + Ustawienia baterii Androida wstrzymały Twoje wyjście awaryjne. Otwórz Bitkit przed {time}, aby utrzymać je na właściwym torze. + Twoje wyjście awaryjne nie mogło być kontynuowane w tle. Otwórz Bitkit przed {time}, aby utrzymać je na właściwym torze. + Twoje wyjście awaryjne zostało zatrzymane. Otwórz Bitkit, aby zobaczyć dlaczego. + Twoje wyjście awaryjne potrzebuje więcej środków na opłaty. Otwórz Bitkit, aby je sfinansować. + Twoje wyjście awaryjne opóźniło się w tle. Otwórz Bitkit, aby je kontynuować. + Nie można odzyskać {amount} z Twojego wyjścia. Otwórz Bitkit, aby zobaczyć dlaczego. + Twoje wyjście awaryjne nie może być kontynuowane bez internetu. Połącz się i otwórz Bitkit przed {time}, aby utrzymać je na właściwym torze. + Niektóre transakcje Twojego wyjścia awaryjnego zostały odrzucone. Otwórz Bitkit przed {time}, aby zobaczyć dlaczego. + Android nie pozwala Bitkit działać w tle. Otwórz Bitkit przed {time}, aby utrzymać wyjście awaryjne na właściwym torze. + Wyjście awaryjne + {amount} na Spark nie jest częścią tego wyjścia i pozostaje na Spark. + {count} małych kwot pozostało na Spark. + Wyjście działa w tle, także gdy Bitkit jest zamknięty. Bitkit powiadomi Cię, jeśli będzie Cię potrzebować. + Wyjście\n<accent>w toku</accent> + Nie udało się pobrać wyceny wyjścia. Spróbuj ponownie. + Pobieranie wyceny… + {amount} Twojego salda Spark nie może teraz wyjść: kwoty zbyt małe, by pokryć własne opłaty, lub wciąż przenoszone wewnątrz Spark. Pozostają na Spark. + Czekamy, aż Spark zakończy przenoszenie Twojego salda. Może to potrwać do 5 minut. + Wycena\n<accent>wyjścia</accent> + Gotowe za {duration} + Bitkit nie mógł odczytać zapisanego postępu tego wyjścia, więc odtwarza go z łańcucha. + Otrzymasz około + Opłata za płatność z Oszczędności + Razem z Oszczędności + Potwierdzanie finansowania opłat + Publikowanie transakcji wyjścia + Wysyłanie do Oszczędności + Oczekiwanie na blokadę czasową + ID transakcji: {txid} + Przesuń, aby wyjść + Opłaty są wyższe niż kwota, którą otrzymasz. + Części tego wyjścia nie można teraz odczytać on-chain. Bitkit będzie próbować ponownie przez maksymalnie tydzień. + {amount} przeniesione on-chain przez operatorów Spark czeka, aż je zwolnią. Bitkit będzie pytać ponownie przez maksymalnie tydzień. Dostawca Spark przez Breez Bez limitu diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 7ab7bf540e..a61d24bf8d 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -237,101 +237,101 @@ Esperar Depósitos resgatados Depósitos em andamento - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Valor a retirar + Saída de emergência + Cancelar saída + Não foi possível verificar o endereço de financiamento. Tente novamente. + A Spark volta a ser como era. Se um pagamento chegou ao endereço de financiamento das taxas da saída, a Bitkit o devolve para a poupança. + Cancelar saída? + Você cancelou a saída. O financiamento das taxas que chegou volta para a poupança. + Saída\n<accent>cancelada</accent> + Você não poderá usar esses fundos por <accent>até 4 semanas</accent>. + Iniciar\n<accent>saída?</accent> + {amount} chegou à sua poupança. + Seus fundos estão na poupança. + Saída\n<accent>concluída</accent> + {amount} foi movido on-chain pelos operadores da Spark e não está na Spark. Os operadores ainda podem liberá-lo para você. + {amount} fica na Spark. + Nada pôde ser recuperado. + Saída\n<accent>interrompida</accent> + Pagar uma taxa maior + Usar esta taxa + Não foi possível calcular uma taxa maior. Tente novamente. + Uma taxa maior deixaria parte desta saída na Spark, por isso nenhuma é oferecida. A saída é confirmada quando as taxas de rede caírem. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Esta saída paga <accent>{rate} sat/vB</accent>, menos do que a rede pede agora. Escolha uma taxa maior e a Bitkit envia de novo as etapas pendentes. A diferença é paga da poupança: o valor ao lado de cada velocidade. + Pagar uma\n<accent>taxa maior</accent> + A rede está mais congestionada do que a taxa desta saída, de {rate} sat/vB. Pague uma taxa maior ou espere as taxas caírem. + As taxas de rede subiram acima da taxa desta saída. Ela pode ficar mais lenta. + Taxas de rede + Financiar de outra carteira + Envie pelo menos {amount} para este endereço. A saída começa assim que ele for confirmado. + Sua poupança não cobre o financiamento das taxas. + Pago da poupança, aguardando confirmação. + {received} de {required} recebidos, envie mais {missing}. + Pagamento detectado, aguardando confirmação. + Pagar da poupança + Pagamento detectado. + Financiamento das taxas necessário + A Bitkit o divide em {count} partes, uma para cada etapa, para que uma etapa travada não segure as outras. + A saída paga suas taxas com um pagamento on-chain separado de <accent>{amount}</accent>. O que ela não gastar volta para a poupança no final. + Financiar as\n<accent>taxas</accent> + ID da transação: {txid} + Use isso apenas se a Spark parar de funcionar para você. Isso move seu saldo de gastos para a poupança <accent>sem os operadores da Spark</accent>.\n\nLeva <accent>até 4 semanas</accent>, custa taxas on-chain pagas da poupança, e valores muito pequenos podem ficar para trás. Roda em segundo plano, e a Bitkit avisa você se precisar de você. + Sair da Spark\n<accent>on-chain</accent> + Fica na Spark + {amount} não pode sair com esta taxa e fica na Spark. + {amount} do financiamento das taxas ainda está em {address}. + {amount} de sobra do financiamento das taxas é pequeno demais para enviar e fica em {address}, caminho de derivação {path}. + {amount} de sobra do financiamento das taxas não pôde ser enviado e fica em {address}, caminho de derivação {path}. + Enviando {amount} de sobra do financiamento das taxas para a poupança. + {amount} de sobra do financiamento das taxas foi enviado para a poupança. + ID da transação: {txid} + {amount} de troco das taxas chegará à sua poupança quando as taxas de rede caírem. + {amount} foi reivindicado on-chain por um antigo dono desses fundos e não pode ser recuperado. + Saída de Emergência + A saída precisa de mais <accent>{amount}</accent> para pagar suas taxas. Financie para continuar. + Mais taxas\n<accent>necessárias</accent> + A saída não está avançando: {error} + A otimização de bateria do Android pode atrasar a saída enquanto a Bitkit está fechada. A Bitkit avisa você se ela ficar para trás. + A economia de bateria está ativada, então o Android pode segurar a saída enquanto a Bitkit está fechada. + As notificações estão desativadas, então a Bitkit não consegue avisar se a saída precisar de você. Sem elas, abra a Bitkit a cada poucas horas até a saída terminar. + Ativar notificações + O Android restringe a Bitkit em segundo plano, então a saída só avança enquanto a Bitkit está aberta. Permita o uso em segundo plano da Bitkit nas configurações do Android. + Nada pode sair agora. + As configurações de bateria do Android seguraram sua saída de emergência. Abra a Bitkit antes de {time} para mantê-la no caminho certo. + Sua saída de emergência não pôde continuar em segundo plano. Abra a Bitkit antes de {time} para mantê-la no caminho certo. + Sua saída de emergência parou. Abra a Bitkit para ver o motivo. + Sua saída de emergência precisa de mais financiamento para as taxas. Abra a Bitkit para financiá-la. + Sua saída de emergência ficou para trás em segundo plano. Abra a Bitkit para continuá-la. + {amount} da sua saída não pode ser recuperado. Abra a Bitkit para ver o motivo. + Sua saída de emergência não pode continuar sem internet. Conecte-se e abra a Bitkit antes de {time} para mantê-la no caminho certo. + Algumas transações da sua saída de emergência foram recusadas. Abra a Bitkit antes de {time} para ver o motivo. + O Android impede a Bitkit de rodar em segundo plano. Abra a Bitkit antes de {time} para manter sua saída de emergência no caminho certo. + Saída de emergência + {amount} na Spark não faz parte desta saída e fica na Spark. + {count} valores pequenos ficaram na Spark. + A saída roda em segundo plano, inclusive com a Bitkit fechada. A Bitkit avisa você se precisar de você. + Saída\n<accent>em andamento</accent> + Não foi possível obter uma cotação da saída. Tente novamente. + Obtendo uma cotação… + {amount} do seu saldo Spark não pode sair agora: valores pequenos demais para pagar as próprias taxas, ou ainda em movimento dentro da Spark. Ele fica na Spark. + Aguardando a Spark terminar de mover seu saldo. Isso pode levar até 5 minutos. + Cotação\n<accent>da saída</accent> + Pronto em {duration} + A Bitkit não conseguiu ler o progresso salvo desta saída, então o reconstrói a partir da blockchain. + Você recebe cerca de + Taxa do pagamento da poupança + Total da poupança + Confirmação do financiamento das taxas + Publicando as transações de saída + Enviando para a poupança + Aguardando o timelock + ID da transação: {txid} + Deslize Para Sair + As taxas são maiores do que o que você receberia. + Parte desta saída não pode ser lida on-chain agora. A Bitkit tenta de novo por até uma semana. + {amount} que os operadores da Spark moveram on-chain aguarda a liberação por eles. A Bitkit pede de novo por até uma semana. Provedor Spark via Breez Sem limite diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index ee4f6e79b6..caa3d27b26 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -108,101 +108,101 @@ Esperar Depósitos resgatados Depósitos em curso - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Montante a retirar + Saída de emergência + Cancelar saída + Não foi possível verificar o endereço de financiamento. Tente novamente. + A Spark volta ao estado anterior. Se um pagamento chegou ao endereço de financiamento das taxas da saída, a Bitkit devolve-o à poupança. + Cancelar saída? + Cancelou a saída. O financiamento das taxas que chegou volta para a poupança. + Saída\n<accent>cancelada</accent> + Não poderá usar estes fundos durante <accent>até 4 semanas</accent>. + Iniciar\n<accent>saída?</accent> + {amount} chegou à sua poupança. + Os seus fundos estão na poupança. + Saída\n<accent>concluída</accent> + {amount} foi movido on-chain pelos operadores da Spark e não está na Spark. Os operadores ainda o podem libertar para si. + {amount} fica na Spark. + Não foi possível recuperar nada. + Saída\n<accent>interrompida</accent> + Pagar uma taxa mais alta + Usar esta taxa + Não foi possível calcular uma taxa mais alta. Tente novamente. + Uma taxa mais alta deixaria parte desta saída na Spark, por isso não é oferecida. A saída é confirmada quando as taxas de rede descerem. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Esta saída paga <accent>{rate} sat/vB</accent>, menos do que a rede pede agora. Escolha uma taxa mais alta e a Bitkit volta a enviar os passos em espera. A diferença é paga da poupança: o montante ao lado de cada velocidade. + Pagar uma\n<accent>taxa mais alta</accent> + A rede está mais congestionada do que a taxa desta saída de {rate} sat/vB. Pague uma taxa mais alta ou espere que as taxas desçam. + As taxas de rede subiram acima da taxa desta saída. Pode ficar mais lenta. + Taxas de rede + Financiar a partir de outra carteira + Envie pelo menos {amount} para este endereço. A saída começa assim que for confirmado. + A sua poupança não cobre o financiamento das taxas. + Pago da poupança, a aguardar confirmação. + {received} de {required} recebidos, envie mais {missing}. + Pagamento detetado, a aguardar confirmação. + Pagar da poupança + Pagamento detetado. + Financiamento das taxas necessário + A Bitkit divide-o em {count} partes, uma para cada passo, para que um passo bloqueado não atrase os outros. + A saída paga as suas taxas com um pagamento on-chain separado de <accent>{amount}</accent>. O que não gastar volta para a poupança no final. + Financiar as\n<accent>taxas</accent> + ID da transação: {txid} + Use isto apenas se a Spark deixar de funcionar para si. Move o seu saldo de gastos para a poupança <accent>sem os operadores da Spark</accent>.\n\nDemora <accent>até 4 semanas</accent>, custa taxas on-chain pagas da poupança, e montantes muito pequenos podem ficar para trás. Corre em segundo plano, e a Bitkit notifica-o se precisar de si. + Sair da Spark\n<accent>on-chain</accent> + Fica na Spark + {amount} não pode sair com esta taxa e fica na Spark. + {amount} do financiamento das taxas ainda está em {address}. + {amount} do financiamento das taxas restante é demasiado pequeno para enviar e fica em {address}, caminho de derivação {path}. + {amount} do financiamento das taxas restante não pôde ser enviado e fica em {address}, caminho de derivação {path}. + A enviar {amount} do financiamento das taxas restante para a poupança. + {amount} do financiamento das taxas restante foi enviado para a poupança. + ID da transação: {txid} + {amount} de troco das taxas chegará à sua poupança quando as taxas de rede descerem. + {amount} foi reclamado on-chain por um antigo proprietário destes fundos e não pode ser recuperado. + Saída de Emergência + A saída precisa de mais <accent>{amount}</accent> para pagar as suas taxas. Financie-a para continuar. + Mais taxas\n<accent>necessárias</accent> + A saída não está a avançar: {error} + A otimização da bateria do Android pode atrasar a saída enquanto a Bitkit estiver fechada. A Bitkit notifica-o se ficar atrasada. + A poupança de bateria está ativada, por isso o Android pode travar a saída enquanto a Bitkit estiver fechada. + As notificações estão desativadas, por isso a Bitkit não o pode avisar se a saída precisar de si. Sem elas, abra a Bitkit a cada poucas horas até a saída terminar. + Ativar notificações + O Android restringe a Bitkit em segundo plano, por isso a saída só avança enquanto a Bitkit estiver aberta. Permita a utilização em segundo plano da Bitkit nas definições do Android. + Nada pode sair neste momento. + As definições de bateria do Android travaram a sua saída de emergência. Abra a Bitkit antes das {time} para a manter no bom caminho. + A sua saída de emergência não pôde continuar em segundo plano. Abra a Bitkit antes das {time} para a manter no bom caminho. + A sua saída de emergência parou. Abra a Bitkit para ver porquê. + A sua saída de emergência precisa de mais financiamento para as taxas. Abra a Bitkit para a financiar. + A sua saída de emergência ficou atrasada em segundo plano. Abra a Bitkit para a continuar. + {amount} da sua saída não pode ser recuperado. Abra a Bitkit para ver porquê. + A sua saída de emergência não pode continuar sem internet. Ligue-se e abra a Bitkit antes das {time} para a manter no bom caminho. + Algumas transações da sua saída de emergência foram recusadas. Abra a Bitkit antes das {time} para ver porquê. + O Android impede a Bitkit de funcionar em segundo plano. Abra a Bitkit antes das {time} para manter a sua saída de emergência no bom caminho. + Saída de emergência + {amount} na Spark não faz parte desta saída e fica na Spark. + {count} montantes pequenos ficaram na Spark. + A saída corre em segundo plano, também com a Bitkit fechada. A Bitkit notifica-o se precisar de si. + Saída\n<accent>em curso</accent> + Não foi possível obter uma cotação para a saída. Tente novamente. + A obter uma cotação… + {amount} do seu saldo Spark não pode sair neste momento: montantes demasiado pequenos para pagar as suas próprias taxas, ou ainda em movimento dentro da Spark. Fica na Spark. + A aguardar que a Spark termine de mover o seu saldo. Isto pode demorar até 5 minutos. + Cotação\n<accent>da saída</accent> + Pronto em {duration} + A Bitkit não conseguiu ler o progresso guardado desta saída, por isso reconstrói-o a partir da blockchain. + Recebe cerca de + Taxa do pagamento da poupança + Total da poupança + Confirmação do financiamento das taxas + A publicar as transações de saída + A enviar para a poupança + A aguardar o timelock + ID da transação: {txid} + Deslizar Para Sair + As taxas são mais altas do que o que receberia. + Parte desta saída não pode ser lida on-chain neste momento. A Bitkit tenta novamente durante até uma semana. + {amount} que os operadores da Spark moveram on-chain aguarda que o libertem. A Bitkit volta a pedir durante até uma semana. Fornecedor Spark via Breez Sem limite diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 08e89458d0..cc56a79e61 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -245,101 +245,101 @@ Ждать Зачисленные депозиты Депозиты в обработке - Amount to exit - Emergency exit - Cancel exit - Couldn\'t check the funding address. Try again. - Spark goes back to how it was. If a payment reached the exit\'s fee funding address, Bitkit sends it back to savings. - Cancel exit? - You cancelled the exit. The fee funding that arrived goes back to savings. - Exit\n<accent>cancelled</accent> - You won\'t be able to use these funds for <accent>up to 4 weeks</accent>. - Start\n<accent>exit?</accent> - {amount} reached your savings. - Your funds are in savings. - Exit\n<accent>complete</accent> - {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. - {amount} stays on Spark. - Nothing could be recovered. - Exit\n<accent>stopped</accent> - Pay a higher fee - Use this fee - Could not price a higher fee. Try again. - A higher fee would leave part of this exit on Spark, so none is offered. The exit confirms once network fees drop. + Сумма выхода + Экстренный выход + Отменить выход + Не удалось проверить адрес пополнения. Попробуйте ещё раз. + Spark вернётся в прежнее состояние. Если на адрес для оплаты комиссий выхода пришёл платёж, Bitkit вернёт его в сбережения. + Отменить выход? + Вы отменили выход. Поступившие средства на комиссии вернутся в сбережения. + Выход\n<accent>отменён</accent> + Вы не сможете пользоваться этими средствами <accent>до 4 недель</accent>. + Начать\n<accent>выход?</accent> + {amount} поступили в ваши сбережения. + Ваши средства в сбережениях. + Выход\n<accent>завершён</accent> + {amount} операторы Spark перевели ончейн, и этих средств больше нет в Spark. Операторы всё ещё могут выдать их вам. + {amount} остаются в Spark. + Ничего не удалось вернуть. + Выход\n<accent>остановлен</accent> + Заплатить больше + Выбрать эту комиссию + Не удалось рассчитать более высокую комиссию. Попробуйте ещё раз. + При более высокой комиссии часть этого выхода осталась бы в Spark, поэтому она не предлагается. Выход подтвердится, когда сетевые комиссии снизятся. {rate} sat/vB - This exit pays <accent>{rate} sat/vB</accent>, less than the network asks now. Pick a higher rate and Bitkit sends the waiting steps again. It pays the difference from savings: the amount next to each speed. - Pay a\n<accent>higher fee</accent> - The network is busier than this exit\'s fee rate of {rate} sat/vB. Pay a higher fee, or wait for fees to drop. - Network fees rose above this exit\'s fee. It may slow down. - Network fees - Fund from another wallet - Send at least {amount} to this address. The exit starts once it confirms. - Your savings can\'t cover the fee funding. - Paid from savings, waiting for confirmation. - {received} of {required} received, send {missing} more. - Payment seen, waiting for confirmation. - Pay from savings - Payment seen. - Fee funding needed - Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. - The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. - Fund the\n<accent>fees</accent> - Transaction ID: {txid} - Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. - Leave Spark\n<accent>on-chain</accent> - Stays on Spark - {amount} can\'t be exited at this fee rate and stays on Spark. - {amount} of fee funding is still at {address}. - {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. - {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. - Sending {amount} of leftover fee funding to savings. - {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} - {amount} of fee change will reach your savings when network fees drop. - {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. - Emergency Exit - The exit needs <accent>{amount}</accent> more to pay its fees. Fund it to continue. - More fees\n<accent>needed</accent> - The exit is not moving: {error} - Android\'s battery optimization can delay the exit while Bitkit is closed. Bitkit notifies you if it falls behind. - Battery saver is on, so Android may hold back the exit while Bitkit is closed. - Notifications are off, so Bitkit can\'t tell you if the exit needs you. Without them, open Bitkit every few hours until the exit finishes. - Turn on notifications - Android restricts Bitkit in the background, so the exit only moves while Bitkit is open. Allow background use for Bitkit in Android settings. - Nothing can be exited right now. - Android\'s battery settings held back your emergency exit. Open Bitkit before {time} to keep it on track. - Your emergency exit could not continue in the background. Open Bitkit before {time} to keep it on track. - Your emergency exit stopped. Open Bitkit to see why. - Your emergency exit needs more fee funding. Open Bitkit to fund it. - Your emergency exit fell behind in the background. Open Bitkit to continue it. - {amount} of your exit can\'t be recovered. Open Bitkit to see why. - Your emergency exit can\'t continue without internet. Connect and open Bitkit before {time} to keep it on track. - Some of your emergency exit\'s transactions were refused. Open Bitkit before {time} to see why. - Android stops Bitkit from running in the background. Open Bitkit before {time} to keep your emergency exit on track. - Emergency exit - {amount} on Spark is not part of this exit and stays on Spark. - {count} small amounts stayed on Spark. - The exit runs in the background, also while Bitkit is closed. Bitkit notifies you if it needs you. - Exit in\n<accent>progress</accent> - Could not get an exit quote. Try again. - Getting a quote… - {amount} of your Spark balance can\'t be exited right now: amounts too small to pay their own fees, or still moving inside Spark. It stays on Spark. - Waiting for Spark to finish moving your balance. This can take up to 5 minutes. - Exit\n<accent>quote</accent> - Ready in {duration} - Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. - You receive about - Savings payment fee - Total from savings - Fee funding confirms - Publishing exit transactions - Sending to savings - Waiting for the timelock - Transaction ID: {txid} - Swipe To Exit - The fees are higher than what you would receive. - Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. - {amount} that the Spark operators moved on-chain waits for them to release it. Bitkit asks again for up to a week. + Этот выход платит <accent>{rate} sat/vB</accent>, меньше, чем сейчас требует сеть. Выберите ставку выше, и Bitkit заново отправит ожидающие шаги. Разницу он оплатит из сбережений: это сумма рядом с каждой скоростью. + Заплатить\n<accent>больше</accent> + Сеть сейчас загружена сильнее, чем позволяет ставка комиссии этого выхода в {rate} sat/vB. Заплатите больше или дождитесь снижения комиссий. + Сетевые комиссии превысили комиссию этого выхода. Он может замедлиться. + Сетевые комиссии + Пополнить с другого кошелька + Отправьте не менее {amount} на этот адрес. Выход начнётся после подтверждения. + В сбережениях недостаточно средств на комиссии. + Оплачено из сбережений, ожидает подтверждения. + Получено {received} из {required}, отправьте ещё {missing}. + Платёж обнаружен, ожидает подтверждения. + Оплатить из сбережений + Платёж обнаружен. + Нужны средства на комиссии + Bitkit делит сумму на {count} частей, по одной на каждый шаг, чтобы застрявший шаг не задерживал остальные. + Выход оплачивает свои комиссии отдельным ончейн-платежом на <accent>{amount}</accent>. Неизрасходованное в конце вернётся в сбережения. + Оплатите\n<accent>комиссии</accent> + ID транзакции: {txid} + Используйте это, только если Spark перестал у вас работать. Выход переводит ваш расходный баланс в сбережения <accent>без операторов Spark</accent>.\n\nОн занимает <accent>до 4 недель</accent>, требует ончейн-комиссий из сбережений, а очень маленькие суммы могут остаться в Spark. Выход работает в фоне, и Bitkit сообщит, если понадобится ваше участие. + Выйти из Spark\n<accent>ончейн</accent> + Остаётся в Spark + {amount} нельзя вывести при этой ставке комиссии, и они остаются в Spark. + {amount} средств на комиссии всё ещё находятся на {address}. + Остаток средств на комиссии {amount} слишком мал для отправки и остаётся на {address}, путь деривации {path}. + Остаток средств на комиссии {amount} не удалось отправить, он остаётся на {address}, путь деривации {path}. + Отправка остатка средств на комиссии {amount} в сбережения. + Остаток средств на комиссии {amount} отправлен в сбережения. + ID транзакции: {txid} + Сдача с комиссий {amount} поступит в сбережения, когда сетевые комиссии снизятся. + {amount} забрал ончейн один из прежних владельцев этих средств, и вернуть их нельзя. + Экстренный Выход + Выходу нужно ещё <accent>{amount}</accent> на комиссии. Пополните, чтобы продолжить. + Нужно больше\n<accent>комиссий</accent> + Выход не продвигается: {error} + Оптимизация батареи Android может задерживать выход, пока Bitkit закрыт. Bitkit сообщит, если выход отстанет. + Включён режим энергосбережения, поэтому Android может задерживать выход, пока Bitkit закрыт. + Уведомления выключены, поэтому Bitkit не сможет сообщить, если выходу понадобится ваше участие. Без них открывайте Bitkit каждые несколько часов, пока выход не завершится. + Включить уведомления + Android ограничивает работу Bitkit в фоне, поэтому выход продвигается, только пока Bitkit открыт. Разрешите Bitkit работу в фоне в настройках Android. + Сейчас выводить нечего. + Настройки батареи Android задержали ваш экстренный выход. Откройте Bitkit до {time}, чтобы он шёл по плану. + Ваш экстренный выход не смог продолжиться в фоне. Откройте Bitkit до {time}, чтобы он шёл по плану. + Ваш экстренный выход остановлен. Откройте Bitkit, чтобы узнать причину. + Вашему экстренному выходу нужно больше средств на комиссии. Откройте Bitkit, чтобы пополнить. + Ваш экстренный выход отстал в фоне. Откройте Bitkit, чтобы продолжить. + {amount} из вашего выхода нельзя вернуть. Откройте Bitkit, чтобы узнать причину. + Ваш экстренный выход не может продолжиться без интернета. Подключитесь и откройте Bitkit до {time}, чтобы он шёл по плану. + Часть транзакций вашего экстренного выхода была отклонена. Откройте Bitkit до {time}, чтобы узнать причину. + Android не даёт Bitkit работать в фоне. Откройте Bitkit до {time}, чтобы экстренный выход шёл по плану. + Экстренный выход + {amount} в Spark не входят в этот выход и остаются в Spark. + Небольших сумм, оставшихся в Spark: {count}. + Выход идёт в фоне, в том числе пока Bitkit закрыт. Bitkit сообщит, если понадобится ваше участие. + Выход\n<accent>выполняется</accent> + Не удалось получить расчёт выхода. Попробуйте ещё раз. + Получение расчёта… + {amount} вашего баланса Spark сейчас нельзя вывести: суммы слишком малы, чтобы оплатить собственные комиссии, или ещё перемещаются внутри Spark. Они остаются в Spark. + Ждём, пока Spark закончит перемещать ваш баланс. Это может занять до 5 минут. + Расчёт\n<accent>выхода</accent> + Будет готово через {duration} + Bitkit не смог прочитать сохранённый прогресс этого выхода, поэтому восстанавливает его по блокчейну. + Вы получите примерно + Комиссия платежа из сбережений + Всего из сбережений + Подтверждение средств на комиссии + Публикация транзакций выхода + Отправка в сбережения + Ожидание таймлока + ID транзакции: {txid} + Проведите для выхода + Комиссии больше, чем сумма, которую вы получите. + Часть этого выхода сейчас не удаётся прочитать в блокчейне. Bitkit будет пробовать снова в течение недели. + {amount}, которые операторы Spark перевели ончейн, ждут, пока операторы их выдадут. Bitkit будет запрашивать снова в течение недели. Провайдер Spark через Breez Без ограничений From bd56cda085dd16c3047012fe515f329acfc9fa4d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:05:08 +0100 Subject: [PATCH 044/154] fix: price spark exit savings funding only from read fee rates --- .../to/bitkit/repositories/SparkExitRepo.kt | 28 ++++++++--- .../bitkit/repositories/SparkExitRepoTest.kt | 47 +++++++++++++++++++ 2 files changed, 69 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 6d31098274..d24e5eecf1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -8,6 +8,7 @@ import breez_sdk_spark.PrepareRecoverFundsRequest import breez_sdk_spark.RecoveryTxKind import breez_sdk_spark.singleKeyCpfpSigner import com.synonym.bitkitcore.Activity +import com.synonym.bitkitcore.FeeRates import io.ktor.client.HttpClient import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job @@ -598,13 +599,23 @@ class SparkExitRepo @Inject constructor( selection = ExitLeafSelection.All, ) - /** The fee Savings pays to send the fee funding at the fast rate, or null when it cannot. */ + /** + * The fee Savings pays to send the fee funding at the fast rate. Fails when the rates cannot be read; the rates it + * priced are the ones the payment at the start sends at. + */ suspend fun savingsFundingFee(): Result = withContext(bgDispatcher) { runSuspendCatching { val pending = requireNotNull(_state.value.pending) { "No Spark exit quote" } val address = requireNotNull(_state.value.fundingAddress) { "No Spark exit funding address" } val fundingSats = pending.quote.fundingSats - val feeSats = lightningRepo.calculateTotalFee(fundingSats, address, TransactionSpeed.Fast).getOrThrow() + val feeRates = lightningRepo.getFeeRates().getOrThrow() + val feeSats = lightningRepo.calculateTotalFee( + amountSats = fundingSats, + address = address, + speed = TransactionSpeed.Fast, + feeRates = feeRates, + ).getOrThrow() + _state.update { it.copy(pending = it.pending?.copy(savingsFeeRates = feeRates)) } val spendable = lightningRepo.getBalancesAsync().getOrThrow().spendableOnchainBalanceSats SparkExitSavingsFunding( feeSats = feeSats, @@ -702,7 +713,9 @@ class SparkExitRepo @Inject constructor( onAppForegrounded() // Savings pays at most what the user confirmed: Progress asks for the rest of a higher fresh amount. val savingsSats = minOf(quote.fundingSats, pending.quote.fundingSats) - if (fundFromSavings && savingsSats > 0uL) payFunding(createdAt, key.address, savingsSats) + if (fundFromSavings && savingsSats > 0uL) { + payFunding(createdAt, key.address, savingsSats, pending.savingsFeeRates) + } } /** @@ -748,7 +761,7 @@ class SparkExitRepo @Inject constructor( return fresh.copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) } - private suspend fun payFunding(createdAt: Long, address: String, sats: ULong) { + private suspend fun payFunding(createdAt: Long, address: String, sats: ULong, feeRates: FeeRates?) { // Under the tick lock from the check to the saved txid: a cancel either ends the exit before anything is paid // or finds the payment and refuses. After the tick in flight, so its save cannot drop the txid. tickMutex.withLock { @@ -756,7 +769,7 @@ class SparkExitRepo @Inject constructor( Logger.info("Spark exit ended before savings paid its funding; nothing is paid", context = TAG) return@withLock } - val txid = sendFunding(address, sats) + val txid = sendFunding(address, sats, feeRates) val record = _state.value.record ?: return@withLock val paid = record.copy(fundingPaymentTxid = txid) saveRecord(paid) @@ -772,11 +785,12 @@ class SparkExitRepo @Inject constructor( return attempt?.address == address && attempt.isUnresolved } - private suspend fun sendFunding(address: String, sats: ULong): String { + private suspend fun sendFunding(address: String, sats: ULong, feeRates: FeeRates? = null): String { val outcome = lightningRepo.sendOnChain( address = address, sats = sats, speed = TransactionSpeed.Fast, + feeRates = feeRates, ).getOrThrow() if (outcome is OnchainSendOutcome.Rejected) { throw SparkExitError("Spark exit funding was not accepted: '$outcome'") @@ -915,6 +929,8 @@ data class SparkExitPending( val feeRate: ULong, /** The funding key index this exit takes. */ val fundingIndex: UInt, + /** The rates the fee of paying the funding from savings was priced at, which that payment sends at. */ + val savingsFeeRates: FeeRates? = null, ) data class SparkExitSavingsFunding( diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index f8e22c777f..2e2bf90eff 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -9,6 +9,7 @@ import breez_sdk_spark.RecoveryRedoReason import breez_sdk_spark.RecoveryTxKind import breez_sdk_spark.RecoveryVerdict import breez_sdk_spark.SdkException +import com.synonym.bitkitcore.FeeRates import com.synonym.bitkitcore.GetAddressResponse import com.synonym.bitkitcore.OnchainActivity import com.synonym.bitkitcore.PaymentType @@ -34,6 +35,7 @@ import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import org.lightningdevkit.ldknode.BalanceDetails import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.atLeastOnce @@ -803,6 +805,42 @@ class SparkExitRepoTest : BaseUnitTest() { sut.onAppBackgrounded() } + @Test + fun `pay from savings fails when the fee rates cannot be read`() = test { + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + whenever(lightning.getFeeRates()).thenReturn(Result.failure(SparkExitError("no estimates"))) + // What the fee helper falls back to once it cannot price. + whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + .thenReturn(Result.success(1_000uL)) + whenever(lightning.getBalancesAsync()).thenReturn(Result.success(balances(100_000uL))) + + assertTrue(sut.savingsFundingFee().isFailure) + } + + @Test + fun `pay from savings sends at the rate its fee was priced at`() = test { + stubFunding { Result.success(OnchainSendOutcome.Accepted("paid")) } + val rates = FeeRates(fast = 7u, mid = 4u, slow = 1u) + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + whenever(lightning.getFeeRates()).thenReturn(Result.success(rates)) + whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + .thenReturn(Result.success(300uL)) + whenever(lightning.getBalancesAsync()).thenReturn(Result.success(balances(100_000uL))) + sut.savingsFundingFee().getOrThrow() + + sut.start(fundFromSavings = true).getOrThrow() + sut.onAppBackgrounded() + + verify(lightning).sendOnChain( + eq(funding), any(), anyOrNull(), anyOrNull(), eq(rates), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + } + @Test fun `savings never pays more than the confirmed funding when the start quotes again`() = test { stubFunding { Result.success(OnchainSendOutcome.Accepted("paid")) } @@ -930,6 +968,15 @@ class SparkExitRepoTest : BaseUnitTest() { assertNotNull(store.load()) } + private fun balances(spendable: ULong) = BalanceDetails( + totalOnchainBalanceSats = spendable, + spendableOnchainBalanceSats = spendable, + totalAnchorChannelsReserveSats = 0u, + totalLightningBalanceSats = 0u, + lightningBalances = emptyList(), + pendingBalancesFromChannelClosures = emptyList(), + ) + private suspend fun stubFunding(answer: suspend () -> Result) { whenever { lightning.sendOnChain( From 0e90defd8ddbe18807818106d27e46156922bc28 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:08:57 +0100 Subject: [PATCH 045/154] fix: hold spark exit ticks until its start settles --- .../to/bitkit/repositories/SparkExitRepo.kt | 43 ++++++++++++------- .../bitkit/repositories/SparkExitRepoTest.kt | 22 ++++++++++ 2 files changed, 49 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index d24e5eecf1..9e9683bfa3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -82,6 +82,10 @@ class SparkExitRepo @Inject constructor( private val scope = appScope(bgDispatcher, TAG) private val tickMutex = Mutex() + /** The exit a start is still settling: no tick drives it until its optimization wait, requote and reconnect end. */ + @Volatile + private var startingCreatedAt: Long? = null + /** One start or fee payment at a time: a second tap never pays or creates twice. */ private val paymentMutex = Mutex() private var foregroundJob: Job? = null @@ -221,7 +225,8 @@ class SparkExitRepo @Inject constructor( /** Moves the exit one step forward; a tick already running makes this one a no-op. */ suspend fun tick(): Result = withContext(bgDispatcher) { - if (!tickMutex.tryLock()) return@withContext Result.success(_state.value.record) + val isStarting = _state.value.record?.let { it.createdAt == startingCreatedAt } == true + if (isStarting || !tickMutex.tryLock()) return@withContext Result.success(_state.value.record) try { runSuspendCatching { tickLocked() } .onFailure { @@ -685,25 +690,31 @@ class SparkExitRepo @Inject constructor( val transferId = transferRepo.createTransfer(TransferType.SPARK_EXIT, quote.incomingSats.toLong()).getOrThrow() record = record.copy(transferId = transferId) saveRecord(record) + val createdAt = record.createdAt + // Published for the screens and a cancel, but driven only once the start settled the leaves it exits. + startingCreatedAt = createdAt _state.update { it.copy(record = record, pending = null, fundingAddress = key.address) } isLoaded = true // Reconnecting for the exit disconnects Spark, which would cut a running leaf optimization short. - sparkRepo.awaitOptimizationIdle() - val createdAt = record.createdAt - // A cancel during the wait ended this exit: nothing more of the start runs, and nothing is paid. - val isCurrent = tickMutex.withLock { - if (!isStarting(createdAt)) return@withLock false - // An optimization since the quote swapped leaves: the exit is quoted again over the leaves Spark holds now. - requote(pending)?.let { fresh -> - // A failed write goes on with the confirmed quote, as a failed requote does. - val requoted = writeRequote(requireNotNull(_state.value.record), fresh) ?: return@let - quote = fresh - record = requoted - _state.update { it.copy(record = record) } + val isCurrent = try { + sparkRepo.awaitOptimizationIdle() + // A cancel during the wait ended this exit: nothing more of the start runs, and nothing is paid. + tickMutex.withLock { + if (!isStarting(createdAt)) return@withLock false + // An optimization since the quote swapped leaves: the exit is quoted again over the leaves Spark holds. + requote(pending)?.let { fresh -> + // A failed write goes on with the confirmed quote, as a failed requote does. + val requoted = writeRequote(requireNotNull(_state.value.record), fresh) ?: return@let + quote = fresh + record = requoted + _state.update { it.copy(record = record) } + } + // Under the lock, so a cancel can't release Spark between the check and taking it off Lightning. + sparkRepo.setExiting(true, reconnect = true) + true } - // Under the lock, so a cancel can't release Spark between the check and taking it off Lightning. - sparkRepo.setExiting(true, reconnect = true) - true + } finally { + startingCreatedAt = null } if (!isCurrent) throw SparkExitStartCancelled() work.schedulePeriodic() diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 2e2bf90eff..6cde930358 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -760,6 +760,28 @@ class SparkExitRepoTest : BaseUnitTest() { verify(sparkRepo, never()).setExiting(true, true) } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `no tick drives the exit while its start waits for the optimization`() = test { + val gate = CompletableDeferred() + whenever(sparkRepo.awaitOptimizationIdle()).doSuspendableAnswer { gate.await() } + val utxo = """[{"txid":"${"f0".repeat(32)}","vout":0,"value":30000,"status":{"confirmed":true}}]""" + val sdk = FakeSparkExitRecovering() + val sut = quotedSut(sdk, fundingChain(utxo)) + sut.loadQuote().getOrThrow() + val quotes = sdk.prepareRequests.size + + val start = async { sut.start(fundFromSavings = false) } + runCurrent() + sut.tick() + + assertEquals(quotes, sdk.prepareRequests.size, "nothing is built while optimization may still swap leaves") + assertNull(sut.state.value.record?.recovery) + gate.complete(Unit) + start.await().getOrThrow() + sut.onAppBackgrounded() + } + @Test fun `a leaf swap between the quote and the start quotes the exit again`() = test { val sdk = FakeSparkExitRecovering() From c09763dfa770c8008b6fdf7e7241a4e923402a55 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:09:01 +0100 Subject: [PATCH 046/154] fix: take lost spark exit leaves out of the transfer --- .../main/java/to/bitkit/repositories/SparkExitRepo.kt | 3 ++- .../to/bitkit/repositories/SparkExitFundingTest.kt | 10 ++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 9e9683bfa3..a8d75f31e3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -993,6 +993,7 @@ data class SparkExitState( get() { val exit = record ?: return null // Reached only once its sweep or cooperative step confirmed: the plan lists the sweep from the first build. + // A leaf an older state claimed never reaches savings, so it leaves the transfer too. val confirmed = exit.recovery?.let { SparkExitMath.confirmedReceived(it, exit.destination) }.orEmpty() val received = (exit.earlierReceivedSats + confirmed).values .fold(0uL) { sum, sats -> sum.safe() + sats.safe() } @@ -1000,6 +1001,6 @@ data class SparkExitState( ?.takeIf { exit.fundingPaymentTxid == null } ?.let { it.requiredSats.safe() - maxOf(exit.fundedSats, fundingSeenSats).safe() } ?: 0uL - return (exit.expectedSats.safe() - received.safe()).safe() - unpaid.safe() + return ((exit.expectedSats.safe() - received.safe()).safe() - unpaid.safe()).safe() - exit.lostSats.safe() } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 14c6bcf488..49953ce9ac 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -191,6 +191,16 @@ class SparkExitFundingTest { assertEquals(5_000uL, SparkExitState(record = landed).inTransferSats) } + @Test + fun `a leaf an older state claimed leaves the transfer`() { + val record = SparkExitFixtures.record(SparkExitRecord.Phase.Running) + .copy(expectedSats = 150_000uL, leafIds = listOf("leaf-1", "leaf-2")) + .adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))), 1L) + .copy(lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 100_000uL))) + + assertEquals(50_000uL, SparkExitState(record = record).inTransferSats) + } + @Test fun `a wait for a leaf that may still move tries again at doubling gaps up to a day and ends after a week`() { assertFalse(SparkExitMath.isRetryDue(since = 1_000u, retriedAt = 1_000u, tip = 1_005u)) From 34be64cd5710c1c1b628c014a1d9dfc4b61c66b2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 16:49:51 +0100 Subject: [PATCH 047/154] fix: fail the spark exit savings fee instead of a placeholder --- .../to/bitkit/repositories/LightningRepo.kt | 4 ++- .../to/bitkit/repositories/SparkExitRepo.kt | 1 + .../bitkit/repositories/LightningRepoTest.kt | 19 ++++++++++++++ .../bitkit/repositories/SparkExitRepoTest.kt | 6 +++-- .../to/bitkit/repositories/WalletRepoTest.kt | 2 +- .../transfer/SparkFundingViewModelTest.kt | 4 +-- .../send/SendCoinSelectionViewModelTest.kt | 14 +++++++--- .../wallets/send/SendFeeViewModelTest.kt | 4 +-- .../sheets/BoostTransactionViewModelTest.kt | 20 +++++++------- .../viewmodels/AppViewModelSendFlowTest.kt | 26 +++++++++---------- 10 files changed, 66 insertions(+), 34 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 04b4fbe26b..d9de50ab25 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -2200,6 +2200,8 @@ class LightningRepo @Inject constructor( speed: TransactionSpeed? = null, utxosToSpend: List? = null, feeRates: FeeRates? = null, + /** False when a placeholder fee would be shown as the real one: any error then fails the call. */ + allowFallback: Boolean = true, ): Result = withContext(bgDispatcher) { runCatching { val transactionSpeed = speed ?: settingsStore.data.first().defaultTransactionSpeed @@ -2214,7 +2216,7 @@ class LightningRepo @Inject constructor( ) return@runCatching fee }.recoverCatching { - if (it is CancellationException) throw it + if (it is CancellationException || !allowFallback) throw it val fallbackFee = 1000uL Logger.warn("calculateTotalFee error, using fallback of '$fallbackFee'", it, context = TAG) return@recoverCatching fallbackFee diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index a8d75f31e3..262a3aabb3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -619,6 +619,7 @@ class SparkExitRepo @Inject constructor( address = address, speed = TransactionSpeed.Fast, feeRates = feeRates, + allowFallback = false, ).getOrThrow() _state.update { it.copy(pending = it.pending?.copy(savingsFeeRates = feeRates)) } val spendable = lightningRepo.getBalancesAsync().getOrThrow().spendableOnchainBalanceSats diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 881b17ffbb..87117bfe59 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -196,6 +196,25 @@ class LightningRepoTest : BaseUnitTest() { sut.sync() } + @Test + fun `a fee that can't be priced falls back to a placeholder only when allowed`() = test { + val rates = FeeRates(fast = 7u, mid = 4u, slow = 1u) + whenever(lightningService.calculateTotalFee(any(), any(), any(), anyOrNull())) + .doSuspendableAnswer { throw NodeException.InsufficientFunds("insufficient funds") } + + val placeholder = sut.calculateTotalFee(20_000uL, "bcrt1qfunding", TransactionSpeed.Fast, feeRates = rates) + val strict = sut.calculateTotalFee( + 20_000uL, + "bcrt1qfunding", + TransactionSpeed.Fast, + feeRates = rates, + allowFallback = false, + ) + + assertEquals(1_000uL, placeholder.getOrThrow()) + assertTrue(strict.isFailure) + } + @Test fun `recovered spark funding hands only an accepted spark deposit to spark`() = test { val txid = "ab".repeat(32) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 6cde930358..1259adc377 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -833,7 +833,7 @@ class SparkExitRepoTest : BaseUnitTest() { sut.loadQuote().getOrThrow() whenever(lightning.getFeeRates()).thenReturn(Result.failure(SparkExitError("no estimates"))) // What the fee helper falls back to once it cannot price. - whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(1_000uL)) whenever(lightning.getBalancesAsync()).thenReturn(Result.success(balances(100_000uL))) @@ -847,10 +847,12 @@ class SparkExitRepoTest : BaseUnitTest() { val sut = quotedSut(FakeSparkExitRecovering()) sut.loadQuote().getOrThrow() whenever(lightning.getFeeRates()).thenReturn(Result.success(rates)) - whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(300uL)) whenever(lightning.getBalancesAsync()).thenReturn(Result.success(balances(100_000uL))) sut.savingsFundingFee().getOrThrow() + // A placeholder fee would confirm a total savings can't pay: any pricing error fails instead. + verify(lightning).calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), eq(rates), eq(false)) sut.start(fundFromSavings = true).getOrThrow() sut.onAppBackgrounded() diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index aeb0a50c56..0b228ef184 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -141,7 +141,7 @@ class WalletRepoTest : BaseUnitTest() { whenever(hwWalletRepo.wallets).thenReturn(MutableStateFlow(persistentListOf())) whenever(lightningRepo.nodeEventUpdates).thenReturn(MutableSharedFlow()) whenever(lightningRepo.listSpendableOutputs()).thenReturn(Result.success(emptyList())) - whenever(lightningRepo.calculateTotalFee(any(), any(), any(), any(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), any(), any(), any(), anyOrNull(), any())) .thenReturn(Result.success(SATS)) whenever(lightningRepo.canReceive()).thenReturn(false) whenever { privatePaykitAddressReservationRepo.nextReusableReceiveAddress() } diff --git a/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt index 713db8c2bf..6fd878f6fa 100644 --- a/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/transfer/SparkFundingViewModelTest.kt @@ -69,7 +69,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { whenever { lightningRepo.getFeeRates() }.thenReturn(Result.success(feeRates)) whenever { lightningRepo.getBalancesAsync() }.thenReturn(Result.success(balances(100_000uL))) whenever { lightningRepo.estimateSendAllFee(any(), any(), any()) }.thenReturn(Result.success(500uL)) - whenever { lightningRepo.calculateTotalFee(any(), any(), any(), anyOrNull(), any()) } + whenever { lightningRepo.calculateTotalFee(any(), any(), any(), anyOrNull(), any(), any()) } .thenReturn(Result.success(500uL)) } @@ -129,7 +129,7 @@ class SparkFundingViewModelTest : BaseUnitTest() { sut.onAmountChange(50_000) sut.onAmountContinue() advanceUntilIdle() - whenever { lightningRepo.calculateTotalFee(any(), any(), any(), anyOrNull(), any()) } + whenever { lightningRepo.calculateTotalFee(any(), any(), any(), anyOrNull(), any(), any()) } .thenReturn(Result.success(800uL)) val toasts = collectToasts { sut.onConfirm() } diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendCoinSelectionViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendCoinSelectionViewModelTest.kt index 41ada33cbb..7ae3622076 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendCoinSelectionViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendCoinSelectionViewModelTest.kt @@ -79,6 +79,7 @@ class SendCoinSelectionViewModelTest : BaseUnitTest() { speed = anyOrNull(), utxosToSpend = eq(expected), feeRates = anyOrNull(), + allowFallback = any(), ) } @@ -212,14 +213,21 @@ class SendCoinSelectionViewModelTest : BaseUnitTest() { fun `loadUtxos does not retry fee calculation failure`() = test { val error = ServiceError.NodeNotSetup() whenever(lightningRepo.listSpendableOutputs()).thenReturn(Result.success(listOf(LARGE_UTXO))) - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.failure(error)) sut.loadUtxos(REQUIRED_AMOUNT, ADDRESS) advanceUntilIdle() verify(lightningRepo, times(1)).listSpendableOutputs() - verify(lightningRepo, times(1)).calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) + verify(lightningRepo, times(1)).calculateTotalFee( + any(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + any(), + ) assertEquals(error, sut.uiState.value.loadError) assertFalse(sut.uiState.value.isLoading) } @@ -278,7 +286,7 @@ class SendCoinSelectionViewModelTest : BaseUnitTest() { } private suspend fun stubFee(fee: ULong = FEE) { - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(fee)) } } diff --git a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendFeeViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendFeeViewModelTest.kt index 12afee4b73..c68b327128 100644 --- a/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendFeeViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/wallets/send/SendFeeViewModelTest.kt @@ -42,7 +42,7 @@ class SendFeeViewModelTest : BaseUnitTest() { fun setUp() { whenever(context.getString(any())).thenReturn("text") - whenever { lightningRepo.calculateTotalFee(any(), any(), any(), any(), any()) } + whenever { lightningRepo.calculateTotalFee(any(), any(), any(), any(), any(), any()) } .thenReturn(Result.success(fee)) whenever(walletRepo.balanceState) @@ -113,7 +113,7 @@ class SendFeeViewModelTest : BaseUnitTest() { @Test fun `validateCustomFee should return true when fee calculation fails (999 fallback)`() = test { - whenever(lightningRepo.calculateTotalFee(any(), any(), any(), any(), any())) + whenever(lightningRepo.calculateTotalFee(any(), any(), any(), any(), any(), any())) .thenReturn(Result.success(0uL)) sut.init(createSendUiState()) sut.onKeyPress(KEY_DELETE) diff --git a/app/src/test/java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt b/app/src/test/java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt index 46862ec10b..ab615b1b52 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt @@ -114,7 +114,7 @@ class BoostTransactionViewModelTest : BaseUnitTest() { @Test fun `setupActivity should set loading state initially`() = runTest { whenever(lightningRepo.getFeeRateForSpeed(any(), anyOrNull())).thenReturn(Result.success(feeRate)) - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(totalFee)) sut.uiState.test { @@ -130,13 +130,13 @@ class BoostTransactionViewModelTest : BaseUnitTest() { @Test fun `setupActivity should call correct repository methods for sent transaction`() = runTest { whenever(lightningRepo.getFeeRateForSpeed(any(), anyOrNull())).thenReturn(Result.success(feeRate)) - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(totalFee)) sut.setupActivity(activitySent) verify(lightningRepo).getFeeRateForSpeed(eq(TransactionSpeed.Fast), anyOrNull()) - verify(lightningRepo).calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) + verify(lightningRepo).calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any()) } @Test @@ -174,7 +174,7 @@ class BoostTransactionViewModelTest : BaseUnitTest() { @Test fun `onChangeAmount should emit OnMaxFee when at maximum rate`() = runTest { whenever(lightningRepo.getFeeRateForSpeed(any(), anyOrNull())).thenReturn(Result.success(MAX_FEE_RATE)) - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(totalFee)) sut.setupActivity(activitySent) @@ -188,7 +188,7 @@ class BoostTransactionViewModelTest : BaseUnitTest() { @Test fun `onChangeAmount should emit OnMinFee when at minimum rate`() = runTest { whenever(lightningRepo.getFeeRateForSpeed(any(), anyOrNull())).thenReturn(Result.success(1UL)) // MIN_FEE_RATE - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(totalFee)) sut.setupActivity(activitySent) @@ -214,7 +214,7 @@ class BoostTransactionViewModelTest : BaseUnitTest() { val receivedActivity = Activity.Onchain(onchainActivity.copy(txType = PaymentType.RECEIVED)) whenever(lightningRepo.calculateCpfpFeeRate(any())).thenReturn(Result.success(feeRate)) - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(totalFee)) whenever(walletRepo.getOnchainAddress()).thenReturn(address) whenever(lightningRepo.accelerateByCpfp(any(), any(), any())).thenReturn(Result.success(newTxId)) @@ -244,7 +244,7 @@ class BoostTransactionViewModelTest : BaseUnitTest() { @Test fun `estimateTime shows fast description when fee rate at or above fast threshold`() = runTest { whenever(lightningRepo.getFeeRateForSpeed(any(), anyOrNull())).thenReturn(Result.success(25UL)) - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(totalFee)) sut.uiState.test { @@ -259,7 +259,7 @@ class BoostTransactionViewModelTest : BaseUnitTest() { @Test fun `estimateTime shows normal description when fee rate between mid and fast`() = runTest { whenever(lightningRepo.getFeeRateForSpeed(any(), anyOrNull())).thenReturn(Result.success(15UL)) - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(totalFee)) sut.uiState.test { @@ -275,7 +275,7 @@ class BoostTransactionViewModelTest : BaseUnitTest() { fun `estimateTime shows slow description when fee rate between slow and mid`() = runTest { val lowFeeActivity = Activity.Onchain(onchainActivity.copy(feeRate = 1UL)) whenever(lightningRepo.getFeeRateForSpeed(any(), anyOrNull())).thenReturn(Result.success(7UL)) - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(totalFee)) sut.uiState.test { @@ -291,7 +291,7 @@ class BoostTransactionViewModelTest : BaseUnitTest() { fun `estimateTime shows minimum description when fee rate below slow threshold`() = runTest { val lowFeeActivity = Activity.Onchain(onchainActivity.copy(feeRate = 1UL)) whenever(lightningRepo.getFeeRateForSpeed(any(), anyOrNull())).thenReturn(Result.success(3UL)) - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(totalFee)) sut.uiState.test { diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 5f57c7bce6..9bd467eba1 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -896,7 +896,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.success(Unit)) whenever(currencyRepo.convertSatsToFiat(any(), anyOrNull())) .thenReturn(Result.failure(Exception("not mocked"))) - whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull()) } + whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any()) } .thenReturn(Result.success(100uL)) whenever { lightningRepo.getFeeRateForSpeed(any(), anyOrNull()) } .thenReturn(Result.success(2u)) @@ -6913,7 +6913,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val feeEstimateStarted = CompletableDeferred() val finishFeeEstimate = CompletableDeferred() hwWallets.value = persistentListOf(hardwareWallet(fundingBalanceSats = 50_000uL)) - whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull()) } + whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any()) } .doSuspendableAnswer { feeEstimateStarted.complete(Unit) finishFeeEstimate.await() @@ -7614,13 +7614,13 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(sheet, sut.currentSheet.value) assertFalse(sut.sendUiState.value.isLoading) assertFalse(sut.sendUiState.value.shouldConfirmPay) - verify(lightningRepo, never()).calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull()) + verify(lightningRepo, never()).calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any()) assertNoNativeSend() blocked = false advanceUntilIdle() expectNoEvents() - verify(lightningRepo, never()).calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull()) + verify(lightningRepo, never()).calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any()) sut.setSendEvent(SendEvent.AmountChange(2_000u)) advanceUntilIdle() @@ -7668,7 +7668,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { } } if (coinSelection) { - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any())) .doSuspendableAnswer { estimate() } } else { whenever(lightningRepo.estimateRoutingFeesForAmount(any(), any())).doSuspendableAnswer { estimate() } @@ -7697,7 +7697,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { if (cancelScope) assertTrue(estimateCancelled) assertNoNativeSend() - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(100u)) whenever(lightningRepo.estimateRoutingFeesForAmount(any(), any())).thenReturn(Result.success(7u)) sut.setSendEvent(SendEvent.AmountChange(2_000u)) @@ -13738,7 +13738,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `initial onchain subscription payment stops at the fee warning`() = test { balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 100_000u) - whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull()) } + whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any()) } .thenReturn(Result.success(600uL)) whenever(currencyRepo.convertSatsToFiat(any(), anyOrNull())).thenReturn( Result.success( @@ -13775,7 +13775,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `initial onchain subscription payment shows the fee warning without a usd rate`() = test { balanceState.value = BalanceState(maxSendOnchainSats = 100_000u, maxSendLightningSats = 100_000u) - whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull()) } + whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any()) } .thenReturn(Result.success(600uL)) whenever(currencyRepo.convertSatsToFiat(any(), anyOrNull())) .thenReturn(Result.failure(AppError("no rate"))) @@ -13809,9 +13809,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { finishSelection.await() selectedUtxos } - whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull()) } + whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any()) } .thenReturn(Result.success(150uL)) - whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), eq(selectedUtxos), anyOrNull()) } + whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), eq(selectedUtxos), anyOrNull(), any()) } .thenReturn(Result.success(600uL)) whenever(currencyRepo.convertSatsToFiat(any(), anyOrNull())).thenReturn( Result.success( @@ -15972,7 +15972,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { @Test fun `changing speed resets selected utxos from previous rate`() = test { - whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull()) } + whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any()) } .thenReturn(Result.success(200uL)) whenever { lightningRepo.determineUtxosToSpend(any(), any()) } .thenReturn(null) @@ -16003,7 +16003,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { fun `changing speed keeps previous onchain fee while estimates refresh`() = test { val feeEstimateStarted = CompletableDeferred() val finishFeeEstimate = CompletableDeferred() - whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull()) } + whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any()) } .doSuspendableAnswer { feeEstimateStarted.complete(Unit) finishFeeEstimate.await() @@ -17797,7 +17797,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { fun `no-rate pay from toast keeps the confirmation fee refresh running`() = test { whenever(context.getString(R.string.wallet__payment_request_rate_unavailable)).thenReturn("Rates unavailable") val finishFeeEstimate = CompletableDeferred() - whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull()) } + whenever { lightningRepo.calculateTotalFee(any(), anyOrNull(), any(), anyOrNull(), anyOrNull(), any()) } .doSuspendableAnswer { if (sut.currentSheet.value == Sheet.Send(SendRoute.Confirm)) finishFeeEstimate.await() Result.success(150uL) From 653a8814ce1197aa43fbfee7c7bbdffbfe02b9c3 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:01:56 +0100 Subject: [PATCH 048/154] fix: ask for fee funding a skipped spark exit leaf's retry needs --- .../to/bitkit/repositories/SparkExitDriver.kt | 64 +++++++++++++------ .../to/bitkit/repositories/SparkExitRecord.kt | 7 +- .../repositories/SparkExitDriverTest.kt | 21 ++++++ 3 files changed, 72 insertions(+), 20 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index d46d345dc0..843ad7fd78 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -145,7 +145,13 @@ class SparkExitDriver( val shortfall = record.fundingShortfallSats // Nothing to fund when every leaf is recovered cooperatively. val funded = if (shortfall != null) adoptFunding(record, shortfall) else record - record = if (funded != null) build(funded, sdk) else countShortOwnPayment(record) + record = when { + funded == null -> countShortOwnPayment(record) + // Funding for leaves a partial build skipped: only they are built, once it arrived. + funded.isFundingWaitingLeaves -> retryWaitingLeaves(funded, sdk, isFunded = true) + ?: end(funded.ended(), funded) + else -> build(funded, sdk) + } } } SparkExitRecord.Phase.Running if record.isRebuilding -> { @@ -227,17 +233,7 @@ class SparkExitDriver( return record.leaveBehind(refusal.leafId, refusal.reason).copy(isRebuilding = true, lastBuildAt = null) } if (it !is SdkException.InsufficientCpfpFunds) throw it - // The SDK names the total its funding inputs must hold (CPFP cost plus change dust), not what is missing. - // After a Redo the inputs are partly spent, so what the address still holds decides the shortfall. - Logger.warn("Needs '${it.requiredSats}' sats of fee funding in total for the Spark exit", context = TAG) - val held = record.funding.firstOrNull()?.address?.let { address -> - runSuspendCatching { chain.utxos(address) }.getOrNull()?.let { SparkExitMath.heldSats(it, record) } - } - // Without a reading of the address the shortfall is unknown; the next tick builds again. - if (held == null && record.fundedSats > 0uL) return record - val inputFee = SparkExitMath.inputFeeSats(record.feeRateSatPerVbyte) - val needed = SparkExitMath.neededFunding(it.requiredSats, record.fundedSats, held, inputFee) - return record.copy(phase = SparkExitRecord.Phase.NeedsFunding(needed)) + return askForFunding(record, it) } if (built.transactions.isEmpty()) { // A first build of only cooperative leaves the operators could not co-sign is kept: they are retried for a @@ -547,12 +543,35 @@ class SparkExitDriver( return broadcastReady(adopted) } + /** + * The SDK names the total its funding inputs must hold (CPFP cost plus change dust), not what is missing. After a + * Redo the inputs are partly spent, so what the address still holds decides the shortfall. + */ + private suspend fun askForFunding( + record: SparkExitRecord, + error: SdkException.InsufficientCpfpFunds, + ): SparkExitRecord { + Logger.warn("Needs '${error.requiredSats}' sats of fee funding in total for the Spark exit", context = TAG) + val held = record.funding.firstOrNull()?.address?.let { address -> + runSuspendCatching { chain.utxos(address) }.getOrNull()?.let { SparkExitMath.heldSats(it, record) } + } + // Without a reading of the address the shortfall is unknown; the next tick builds again. + if (held == null && record.fundedSats > 0uL) return record + val inputFee = SparkExitMath.inputFeeSats(record.feeRateSatPerVbyte) + val needed = SparkExitMath.neededFunding(error.requiredSats, record.fundedSats, held, inputFee) + return record.copy(phase = SparkExitRecord.Phase.NeedsFunding(needed)) + } + /** * Leaves a build skipped while they may still move, tried again on their own once the rest of the exit is done: - * at once, then at doubling gaps, until they build or about a week passed. Null once nothing waits, so the exit - * can end. + * at once, then at doubling gaps, until they build or about a week passed. One that needs more fee funding asks + * for it and is built as soon as it arrives ([isFunded]). Null once nothing waits, so the exit can end. */ - private suspend fun retryWaitingLeaves(start: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord? { + private suspend fun retryWaitingLeaves( + start: SparkExitRecord, + sdk: SparkExitRecovering, + isFunded: Boolean = false, + ): SparkExitRecord? { val ids = start.waitingLeafIds.filter { it in start.exitLeafIds } if (ids.isEmpty()) return null val height = tip ?: return start @@ -561,8 +580,12 @@ class SparkExitDriver( Logger.warn("Releasing Spark exit leaves '$ids' that did not move in about a week", context = TAG) return null } - if (since != null && !SparkExitMath.isRetryDue(since, start.retriedAt, height)) return start - var record = start.copy(retrySince = since ?: height, retriedAt = height) + if (!isFunded && since != null && !SparkExitMath.isRetryDue(since, start.retriedAt, height)) return start + var record = start.copy( + phase = SparkExitRecord.Phase.Running, + retrySince = since ?: height, + retriedAt = height, + ) val prepared = runSuspendCatching { record = withExitState(record, sdk) sdk.prepare(prepareRequest(record, ExitLeafSelection.Specific(ids))) @@ -574,12 +597,15 @@ class SparkExitDriver( val still = waitingLeafIds(record, prepared.skipped, stopped) if (prepared.leaves.isEmpty()) return record.takeIf { still.isNotEmpty() }?.copy(waitingLeafIds = still) val needsFunding = prepared.funding != null - val built = runSuspendCatching { + val result = runSuspendCatching { sdk.recover( RecoverFundsRequest(prepared, if (needsFunding) record.fundingInputs else emptyList()), if (needsFunding) makeSigner() else null, ) - }.onFailure { Logger.warn("Failed to build waiting Spark exit leaves '$ids'", it, context = TAG) } + } + (result.exceptionOrNull() as? SdkException.InsufficientCpfpFunds)?.let { return askForFunding(record, it) } + val built = result + .onFailure { Logger.warn("Failed to build waiting Spark exit leaves '$ids'", it, context = TAG) } .getOrNull() if (built == null || built.transactions.isEmpty()) return record val adopted = record.adopt(built, nowMillis()).copy(waitingLeafIds = still) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 47f621735f..bc5b5a9ca3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -260,7 +260,12 @@ data class SparkExitRecord( /** A higher fee's top-up, not a diverged rebuild: the generation out there is still driven while it confirms. */ val isDrivingWhileFunding: Boolean - get() = phase is Phase.NeedsFunding && recovery != null && !isRebuilding + get() = phase is Phase.NeedsFunding && recovery != null && !isRebuilding && !isFundingWaitingLeaves + + /** Fee funding asked for [waitingLeafIds] once every step of the recovery confirmed. */ + val isFundingWaitingLeaves: Boolean + get() = phase is Phase.NeedsFunding && waitingLeafIds.isNotEmpty() && + recovery?.transactions?.all { it.status is ExitTransactionStatus.Confirmed } == true /** * [fundingPaymentTxid] at [tip], when [isKnown] says whether a host knows it: forgotten once missing for a block, diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 4af9727d25..68440e01bc 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1104,6 +1104,27 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(Phase.Done, record.phase) } + @Test + fun `a skipped leaf whose retry needs more fees asks for them and retries once they come`() = test { + // Unfunded: the record's funding has no coin yet, so the shortfall is the SDK's total plus one input's fee. + var record = driver(tip = 1_000u).tick(partialBuild(SkippedLeafReason.Unverified)) + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-2")) + sdk.recoverErrors += SdkException.InsufficientCpfpFunds(3_000uL, "") + + record = driver(tip = 1_000u).tick(record) + assertEquals(Phase.NeedsFunding(3_136uL), record.phase) + assertEquals(listOf("leaf-2"), record.waitingLeafIds) + + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f9", value = 3_136uL)) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n2"))) + record = driver(tip = 1_001u).tick(record) + + assertEquals(Phase.Running, record.phase) + assertEquals(listOf("leaf-2"), (sdk.prepareRequests.last().selection as ExitLeafSelection.Specific).leafIds) + assertEquals(listOf("n1", "n2"), chain.broadcasts.map { it.txid }) + assertTrue(record.fundingInputs.isNotEmpty()) + } + @Test fun `a leaf skipped while another builds is let go after about a week`() = test { var record = driver(tip = 1_000u).tick(partialBuild(SkippedLeafReason.FundsNotFound)) From 9b21c89fd6ae56bb949de17c7d780ea063f65cb6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:07:39 +0100 Subject: [PATCH 049/154] fix: pay a spark exit fee bump at the rates it was priced at --- .../bitkit/repositories/SparkExitFunding.kt | 3 +++ .../to/bitkit/repositories/SparkExitRepo.kt | 9 ++++--- .../bitkit/repositories/SparkExitRepoTest.kt | 24 +++++++++++++++++++ 3 files changed, 33 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index d6ef8212e3..b5c6365f2f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -5,6 +5,7 @@ import breez_sdk_spark.PrepareRecoverFundsResponse import breez_sdk_spark.RecoverFundsResponse import breez_sdk_spark.RecoveryTransaction import breez_sdk_spark.RecoveryTxKind +import com.synonym.bitkitcore.FeeRates import org.lightningdevkit.ldknode.Network import to.bitkit.models.FeeRate import to.bitkit.models.safe @@ -514,6 +515,8 @@ data class SparkExitFeeBumpOption( val rateSatPerVbyte: ULong, val extraSats: ULong, val totalSats: ULong, + /** The rates [totalSats] was priced at, which the payment sends at, so it never costs more than shown. */ + val feeRates: FeeRates? = null, ) { companion object { /** diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 262a3aabb3..2467623f12 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -504,15 +504,18 @@ class SparkExitRepo @Inject constructor( val fees = requireNotNull(_state.value.networkFees) { "No network fee rates" } val driver = driver(chain, recovering, record, _state.value.tipHeight) val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } + // The rates every option's savings payment is priced at, and later sent at. + val feeRates = lightningRepo.getFeeRates().getOrThrow() val priced = SparkExitFeeBumpOption.rates(record.feeRateSatPerVbyte, fees).map { (speed, rate) -> runSuspendCatching { val extra = driver.feeBumpShortfall(record, rate) val paymentFee = if (extra == 0uL) { 0uL } else { - lightningRepo.calculateTotalFee(extra, address, TransactionSpeed.Fast).getOrThrow() + lightningRepo.calculateTotalFee(extra, address, TransactionSpeed.Fast, feeRates = feeRates) + .getOrThrow() } - SparkExitFeeBumpOption(speed, rate, extra, extra.safe() + paymentFee.safe()) + SparkExitFeeBumpOption(speed, rate, extra, extra.safe() + paymentFee.safe(), feeRates) } } // A rate at which a leaf can't pay its own exit is not offered. With no rate left only for that reason, @@ -552,7 +555,7 @@ class SparkExitRepo @Inject constructor( private suspend fun payHigherFeeLocked(option: SparkExitFeeBumpOption) { val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } - val txid = if (option.extraSats > 0uL) sendFunding(address, option.extraSats) else null + val txid = if (option.extraSats > 0uL) sendFunding(address, option.extraSats, option.feeRates) else null tickMutex.withLock { val current = _state.value.record ?: return@withLock if (current.isRebuilding && current.isActive) { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 1259adc377..c90b6276a6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1139,6 +1139,30 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(record.copy(phase = Phase.Done).isEndedPaymentPending) } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a higher fee pays at the rates its total was priced at`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(runningRecord()) + stubFunding { Result.success(OnchainSendOutcome.Accepted("bump")) } + val rates = FeeRates(fast = 12u, mid = 8u, slow = 2u) + val sdk = FakeSparkExitRecovering().apply { preparedResponse = SparkExitFixtures.prepared(funding = null) } + val sut = quotedSut(sdk) + sut.load().getOrThrow() + whenever(lightning.getFeeRates()).thenReturn(Result.success(rates)) + + assertTrue(sut.feeBumpOptions().getOrThrow().all { it.feeRates == rates }) + + sut.payHigherFee(SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 6_000uL, 6_400uL, rates)).getOrThrow() + advanceUntilIdle() + verify(lightning).sendOnChain( + eq(funding), eq(6_000uL), anyOrNull(), anyOrNull(), eq(rates), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + } + @Test fun `fee bump rates are priced without broadcasting, leaving out a rate the sdk refuses a leaf at`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) From f413c2d363d8a19b405ec55c66a9ae7f84b3c8df Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:53:18 +0100 Subject: [PATCH 050/154] fix: offer no spark exit fee bump at a placeholder savings fee --- .../to/bitkit/repositories/SparkExitRepo.kt | 36 ++++++++++++++----- .../bitkit/repositories/SparkExitRepoTest.kt | 15 ++++++++ 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 2467623f12..8fa500fa74 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -32,6 +32,7 @@ import to.bitkit.di.BgDispatcher import to.bitkit.env.Env import to.bitkit.ext.nowMs import to.bitkit.ext.runSuspendCatching +import to.bitkit.models.FeeRate import to.bitkit.models.TransactionSpeed import to.bitkit.models.TransferType import to.bitkit.models.safe @@ -508,14 +509,7 @@ class SparkExitRepo @Inject constructor( val feeRates = lightningRepo.getFeeRates().getOrThrow() val priced = SparkExitFeeBumpOption.rates(record.feeRateSatPerVbyte, fees).map { (speed, rate) -> runSuspendCatching { - val extra = driver.feeBumpShortfall(record, rate) - val paymentFee = if (extra == 0uL) { - 0uL - } else { - lightningRepo.calculateTotalFee(extra, address, TransactionSpeed.Fast, feeRates = feeRates) - .getOrThrow() - } - SparkExitFeeBumpOption(speed, rate, extra, extra.safe() + paymentFee.safe(), feeRates) + feeBumpOption(speed, rate, driver.feeBumpShortfall(record, rate), address, feeRates) } } // A rate at which a leaf can't pay its own exit is not offered. With no rate left only for that reason, @@ -552,6 +546,32 @@ class SparkExitRepo @Inject constructor( } } + /** + * The option at [rate]: [extraSats] more at the funding address, + * and what savings pays to send it at [feeRates]. + */ + internal suspend fun feeBumpOption( + speed: FeeRate, + rate: ULong, + extraSats: ULong, + address: String, + feeRates: FeeRates, + ): SparkExitFeeBumpOption { + val paymentFee = if (extraSats == 0uL) { + 0uL + } else { + // A placeholder fee would show and approve a total the payment does not keep to: any error fails it. + lightningRepo.calculateTotalFee( + amountSats = extraSats, + address = address, + speed = TransactionSpeed.Fast, + feeRates = feeRates, + allowFallback = false, + ).getOrThrow() + } + return SparkExitFeeBumpOption(speed, rate, extraSats, extraSats.safe() + paymentFee.safe(), feeRates) + } + private suspend fun payHigherFeeLocked(option: SparkExitFeeBumpOption) { val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index c90b6276a6..14f686ebed 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1163,6 +1163,21 @@ class SparkExitRepoTest : BaseUnitTest() { ) } + @Test + fun `a fee bump whose savings payment can't be priced is not offered at a placeholder fee`() = test { + val sut = quotedSut(FakeSparkExitRecovering()) + val rates = FeeRates(fast = 12u, mid = 8u, slow = 2u) + // The fee helper's placeholder once it cannot price, and the failure it reports without it. + whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), eq(true))) + .thenReturn(Result.success(1_000uL)) + whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), eq(false))) + .thenReturn(Result.failure(SparkExitError("no estimates"))) + + val priced = runCatching { sut.feeBumpOption(FeeRate.FAST, 9uL, 6_000uL, funding, rates) } + + assertTrue(priced.isFailure) + } + @Test fun `fee bump rates are priced without broadcasting, leaving out a rate the sdk refuses a leaf at`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) From b68bdea8f48ea0d7a698df19da9facca00621fa7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 17:58:54 +0100 Subject: [PATCH 051/154] fix: end an unfunded spark exit leaf retry after its week --- .../to/bitkit/repositories/SparkExitDriver.kt | 16 ++++++++-- .../repositories/SparkExitDriverTest.kt | 32 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 843ad7fd78..1e16be4947 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -141,7 +141,14 @@ class SparkExitDriver( if (record.isDrivingWhileFunding) record = driveWhileFunding(record) record = lookForOwnPayment(record) val sdk = recovering - if (sdk != null && record.phase.requiredFundingSats != null) { + val since = record.retrySince + if (record.isFundingWaitingLeaves && since != null && tip != null && + SparkExitMath.isRetryReleased(since, tip) + ) { + // A skipped leaf's fee funding that never came: let go after the same week as its retries. + Logger.warn("Releasing Spark exit leaves '${record.waitingLeafIds}' unfunded", context = TAG) + record = end(record.ended(), record) + } else if (sdk != null && record.phase.requiredFundingSats != null) { val shortfall = record.fundingShortfallSats // Nothing to fund when every leaf is recovered cooperatively. val funded = if (shortfall != null) adoptFunding(record, shortfall) else record @@ -603,7 +610,12 @@ class SparkExitDriver( if (needsFunding) makeSigner() else null, ) } - (result.exceptionOrNull() as? SdkException.InsufficientCpfpFunds)?.let { return askForFunding(record, it) } + (result.exceptionOrNull() as? SdkException.InsufficientCpfpFunds)?.let { error -> + val asked = askForFunding(record, error) + // Unasked while the address can't be read: the next tick tries again, not the next retry gap. + if (asked.phase is SparkExitRecord.Phase.NeedsFunding) return asked + return asked.copy(retrySince = start.retrySince, retriedAt = start.retriedAt) + } val built = result .onFailure { Logger.warn("Failed to build waiting Spark exit leaves '$ids'", it, context = TAG) } .getOrNull() diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 68440e01bc..0fc73b584f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1125,6 +1125,38 @@ class SparkExitDriverTest : BaseUnitTest() { assertTrue(record.fundingInputs.isNotEmpty()) } + @Test + fun `a skipped leaf's fee ask nobody pays is let go after about a week`() = test { + var record = driver(tip = 1_000u).tick(partialBuild(SkippedLeafReason.Unverified)) + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-2")) + sdk.recoverErrors += SdkException.InsufficientCpfpFunds(3_000uL, "") + record = driver(tip = 1_000u).tick(record) + assertEquals(Phase.NeedsFunding(3_136uL), record.phase) + + record = driver(tip = 2_007u).tick(record) + assertEquals(Phase.NeedsFunding(3_136uL), record.phase) + record = driver(tip = 2_008u).tick(record) + assertEquals(Phase.Done, record.phase) + assertTrue(record.waitingLeafIds.isEmpty()) + } + + @Test + fun `a skipped leaf's fee ask waits only a tick when the funding address can't be read`() = test { + val funded = partialBuild(SkippedLeafReason.Unverified).let { + it.copy(funding = listOf(it.funding.single().copy(txid = "f0", vout = 0u, valueSats = 20_000uL))) + } + var record = driver(tip = 1_000u).tick(funded) + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-2")) + repeat(2) { sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") } + chain.utxosError = SparkExitChainError("timeout") + record = driver(tip = 1_000u).tick(record) + assertEquals(Phase.Running, record.phase) + + chain.utxosError = null + record = driver(tip = 1_001u).tick(record) + assertIs(record.phase, "the next tick asks") + } + @Test fun `a leaf skipped while another builds is let go after about a week`() = test { var record = driver(tip = 1_000u).tick(partialBuild(SkippedLeafReason.FundsNotFound)) From d27796f83dea6fed5c93755db18503bdba6a4dcd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 18:28:29 +0100 Subject: [PATCH 052/154] fix: keep spark exit leaves skipped beside failed cooperative ones --- .../to/bitkit/repositories/SparkExitDriver.kt | 6 +++ .../repositories/SparkExitDriverTest.kt | 44 +++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 1e16be4947..68995349d5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -247,6 +247,7 @@ class SparkExitDriver( // week like any failed leaf. A rebuild like it keeps the recovery it has and tries again on the next tick. if (built.failed.isNotEmpty() && record.recovery == null) { val adopted = record.adopt(built, nowMillis()) + .copy(waitingLeafIds = waitingLeafIds(record, prepared.skipped, stopped)) save(adopted) Logger.info("Built Spark exit of only '${built.failed.size}' failed cooperative leaves", context = TAG) return adopted @@ -526,6 +527,7 @@ class SparkExitDriver( } if (since != null && !SparkExitMath.isRetryDue(since, record.failedLeafRetriedAt, height)) return record record = record.copy(failedLeafRetrySince = since ?: height, failedLeafRetriedAt = height) + var skipped = emptyList() val retried = runSuspendCatching { record = withExitState(record, sdk) val prepared = sdk.prepare(prepareRequest(record, ExitLeafSelection.Specific(failedIds))) @@ -537,6 +539,9 @@ class SparkExitDriver( failedLeaves = record.failedLeaves.map { it.copy(valueSats = values[it.leafId] ?: it.valueSats) }, ) if (prepared.leaves.isEmpty()) return@runSuspendCatching null + // A failed leaf the prepare skipped while it may still move is kept and tried again on its own. + val stopped = prepared.exitChainState.stoppedLeafIds.toSet() + skipped = waitingLeafIds(record.seeStopped(stopped), prepared.skipped, stopped) val needsFunding = prepared.funding != null sdk.recover( RecoverFundsRequest(prepared, if (needsFunding) record.fundingInputs else emptyList()), @@ -545,6 +550,7 @@ class SparkExitDriver( }.onFailure { Logger.warn("Failed to retry Spark exit leaves '$failedIds'", it, context = TAG) }.getOrNull() if (retried == null || retried.transactions.isEmpty()) return record val adopted = record.adopt(retried, nowMillis()) + .copy(waitingLeafIds = (record.waitingLeafIds + skipped).distinct()) save(adopted) Logger.info("Built a recovery of Spark exit leaves '$failedIds' as '${adopted.generation}'", context = TAG) return broadcastReady(adopted) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 0fc73b584f..fb3293b493 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1157,6 +1157,50 @@ class SparkExitDriverTest : BaseUnitTest() { assertIs(record.phase, "the next tick asks") } + @Test + fun `a first build of only failed cooperative leaves keeps the leaf it skipped`() = test { + sdk.preparedResponse = SparkExitFixtures.prepared( + funding = null, + skipped = listOf(SkippedLeaf("leaf-2", 50_000uL, SkippedLeafReason.Unverified)), + ) + val failed = listOf( + CooperativeRecoveryFailure("leaf-1", "o", 0u, CooperativeRecoveryError.OperatorsUnavailable("down")), + ) + sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = failed) + val start = SparkExitFixtures.record(Phase.AwaitingFunding(0uL)).copy(leafIds = listOf("leaf-1", "leaf-2")) + + val record = driver(tip = 1_000u).tick(start) + + assertEquals(listOf("leaf-2"), record.waitingLeafIds) + } + + @Test + fun `a failed-leaf retry that builds one leaf and skips another keeps the skipped one`() = test { + val coop2 = CooperativeRecoveryFailure("coop-2", "o", 1u, CooperativeRecoveryError.OperatorsUnavailable("down")) + val done = SparkExitFixtures.recovery(emptyList(), failed = listOf(operatorsDown, coop2)) + var record = running(done).copy(leafIds = listOf("coop-1", "coop-2")) + sdk.preparedResponse = coopLeaf(16_384uL).copy( + skipped = listOf(SkippedLeaf("coop-2", 8_192uL, SkippedLeafReason.Unverified)), + ) + val coop = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("coop", kind = RecoveryTxKind.COOPERATIVE))) + sdk.builds += coop + + record = driver(tip = 1_000u).tick(record) + assertEquals(listOf("coop-2"), record.waitingLeafIds) + + val landed = coop.copy( + transactions = coop.transactions.map { it.copy(status = ExitTransactionStatus.Confirmed(1_001u)) }, + ) + sdk.checks += check(landed, RecoveryVerdict.Done) + sdk.preparedResponse = coopLeaf(0uL).copy( + leaves = emptyList(), + skipped = listOf(SkippedLeaf("coop-2", 8_192uL, SkippedLeafReason.Unverified)), + ) + record = driver(tip = 1_001u).tick(record) + assertEquals(Phase.Running, record.phase, "coop-2 may still move") + assertEquals(listOf("coop-2"), (sdk.prepareRequests.last().selection as ExitLeafSelection.Specific).leafIds) + } + @Test fun `a leaf skipped while another builds is let go after about a week`() = test { var record = driver(tip = 1_000u).tick(partialBuild(SkippedLeafReason.FundsNotFound)) From e7905377c314efd7173a5640bdfd301bf6c6d641 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 18:28:30 +0100 Subject: [PATCH 053/154] fix: count spark exit leaves let go after a week as left on spark --- .../java/to/bitkit/repositories/SparkExitDriver.kt | 3 ++- .../to/bitkit/repositories/SparkExitDriverTest.kt | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 68995349d5..83849551f5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -636,7 +636,8 @@ class SparkExitDriver( private fun SparkExitRecord.ended() = copy( phase = SparkExitRecord.Phase.Done, failedLeaves = if (isFailedLeavesReleased) failedLeaves else emptyList(), - skippedLeafCount = maxOf(skippedLeafCount, waitingLeafIds.size), + // The quote's skips never were exit leaves: the leaves let go here add to them. + skippedLeafCount = skippedLeafCount + waitingLeafIds.size, waitingLeafIds = emptyList(), retrySince = null, retriedAt = null, diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index fb3293b493..1b924f40d3 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1201,6 +1201,19 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("coop-2"), (sdk.prepareRequests.last().selection as ExitLeafSelection.Specific).leafIds) } + @Test + fun `a waiting leaf let go after a week adds to the leaves that stayed on spark`() = test { + var record = driver(tip = 1_000u).tick( + partialBuild(SkippedLeafReason.FundsNotFound).copy(skippedLeafCount = 13), + ) + sdk.preparedResponse = sdk.preparedResponse.copy(leaves = emptyList()) + record = driver(tip = 1_000u).tick(record) + record = driver(tip = 2_008u).tick(record) + + assertEquals(Phase.Done, record.phase) + assertEquals(14, record.skippedLeafCount) + } + @Test fun `a leaf skipped while another builds is let go after about a week`() = test { var record = driver(tip = 1_000u).tick(partialBuild(SkippedLeafReason.FundsNotFound)) From 397f14ddf8b9a8d1c77e64afc5cfc5fe67e0624f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:25:31 +0100 Subject: [PATCH 054/154] fix: post raw transactions as text/plain through the spark regtest proxy --- scripts/spark-regtest-esplora.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/spark-regtest-esplora.py b/scripts/spark-regtest-esplora.py index d5a3863116..a8f03853ee 100755 --- a/scripts/spark-regtest-esplora.py +++ b/scripts/spark-regtest-esplora.py @@ -64,8 +64,10 @@ def forward(self): return self.reply(200, json.dumps(block_status(parts[1])).encode(), "application/json") body = self.rfile.read(int(self.headers.get("Content-Length") or 0)) if self.command == "POST" else None request = urllib.request.Request(f"{UPSTREAM}{self.path}", data=body, method=self.command) - if self.headers.get("Content-Type"): - request.add_header("Content-Type", self.headers["Content-Type"]) + # Without one, urllib sends form-urlencoded, which Lightspark's POST /tx refuses with a bare code -1: a raw + # transaction is text/plain, which LDK's Esplora client does not name. + if body is not None: + request.add_header("Content-Type", self.headers.get("Content-Type") or "text/plain") try: with urllib.request.urlopen(request, timeout=30) as response: self.reply(response.status, response.read(), response.headers.get("Content-Type")) From 398b60e2a62df5afe8a06fd7f1f5423eaae98a47 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:34:31 +0100 Subject: [PATCH 055/154] feat: offer to pay a refused spark exit savings payment again --- .../bitkit/repositories/SparkExitFunding.kt | 11 +++ .../to/bitkit/repositories/SparkExitRepo.kt | 69 +++++++++++++++++-- .../lightning/SparkExitProgressScreen.kt | 19 +++++ .../settings/lightning/SparkExitViewModel.kt | 14 ++++ app/src/main/res/values/strings.xml | 1 + .../bitkit/repositories/SparkExitRepoTest.kt | 66 ++++++++++++++++++ 6 files changed, 175 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index b5c6365f2f..14c3808670 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -318,6 +318,17 @@ object SparkExitMath { return balanceSats - leafTotalSats } + /** + * A node refused the savings payment of [record]'s fee funding, and none was adopted since: only before the exit is + * funded, for the payment the start made. + */ + fun isSavingsPaymentRefused(record: SparkExitRecord, attempt: OnchainSendAttempt?): Boolean { + if (!record.isActive || record.phase !is SparkExitRecord.Phase.AwaitingFunding) return false + if (record.fundingPaymentTxid != null) return false + val address = record.funding.firstOrNull()?.address ?: return false + return attempt != null && attempt.address == address && attempt.evidence == OnchainSendEvidence.Rejected + } + /** * What progress shows while the exit still needs fee funding, or null when it does not. [utxos] is what the funding * address holds, null when it could not be read. A payment from savings that has not confirmed, or new funding diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 8fa500fa74..32c1432a5a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -259,7 +259,7 @@ class SparkExitRepo @Inject constructor( tip?.let { height -> sparkExitTip.height.update { height } } refreshNetworkFees(chain) refreshFundingSeen(chain, current) - if (current.isActive) _state.update { it.copy(isSavingsSendUnresolved = isSavingsSending(current)) } + if (current.isActive) noteSavingsSend(current) val store = store val recovering = sparkService.exitRecovering() val driver = driver(chain, recovering, current, tip) @@ -749,7 +749,10 @@ class SparkExitRepo @Inject constructor( // Savings pays at most what the user confirmed: Progress asks for the rest of a higher fresh amount. val savingsSats = minOf(quote.fundingSats, pending.quote.fundingSats) if (fundFromSavings && savingsSats > 0uL) { - payFunding(createdAt, key.address, savingsSats, pending.savingsFeeRates) + runSuspendCatching { payFunding(createdAt, key.address, savingsSats, pending.savingsFeeRates) } + // A refused payment shows on progress at once, with the offer to pay again. + .onFailure { _state.value.record?.let { current -> noteSavingsSend(current) } } + .getOrThrow() } } @@ -814,10 +817,60 @@ class SparkExitRepo @Inject constructor( } } - private suspend fun isSavingsSending(record: SparkExitRecord): Boolean { - val address = record.funding.firstOrNull()?.address ?: return false + private suspend fun savingsSend(record: SparkExitRecord): OnchainSendAttempt? { + val address = record.funding.firstOrNull()?.address ?: return null val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() - return attempt?.address == address && attempt.isUnresolved + return attempt?.takeIf { it.address == address } + } + + private suspend fun noteSavingsSend(record: SparkExitRecord) { + val attempt = savingsSend(record) + _state.update { + it.copy( + isSavingsSendUnresolved = attempt?.isUnresolved == true, + isSavingsPaymentRefused = SparkExitMath.isSavingsPaymentRefused(record, attempt), + ) + } + } + + /** + * Pays the exit's fee funding from savings again after a node refused the payment: the same attempt, re-signed at + * the rate the user approved over the inputs it already spends. Every version spends those inputs, so at most one + * ever confirms, and it never needs the refused one to be known gone from the mempool first. + */ + suspend fun retrySavingsPayment(): Result = withContext(bgDispatcher) { + runSuspendCatching { + if (!paymentMutex.tryLock()) throw SparkExitError("A Spark exit payment is already running") + try { + val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } + val refused = savingsSend(record)?.takeIf { SparkExitMath.isSavingsPaymentRefused(record, it) } + ?: throw SparkExitError("No refused savings payment to pay again") + val outcome = lightningRepo.retryOriginalOnchainSend( + attemptId = refused.attemptId, + walletId = refused.walletId, + feeRateSatsPerVByte = refused.feeRateSatsPerVByte, + ) { original -> check(original.attemptId == refused.attemptId && original.address == refused.address) } + .getOrThrow() + val txid = fundingTxid(outcome, refused.amountSats) + tickMutex.withLock { + val current = _state.value.record + if (current == null || current.createdAt != record.createdAt) return@withLock + val paid = current.copy(fundingPaymentTxid = txid) + saveRecord(paid) + _state.update { + it.copy( + record = paid, + fundingState = SparkExitMath.fundingState(paid, utxos = null), + isSavingsPaymentRefused = false, + ) + } + } + } finally { + paymentMutex.unlock() + } + }.onFailure { + Logger.error("Failed to pay the Spark exit funding from savings again", it, context = TAG) + } } private suspend fun sendFunding(address: String, sats: ULong, feeRates: FeeRates? = null): String { @@ -827,6 +880,10 @@ class SparkExitRepo @Inject constructor( speed = TransactionSpeed.Fast, feeRates = feeRates, ).getOrThrow() + return fundingTxid(outcome, sats) + } + + private suspend fun fundingTxid(outcome: OnchainSendOutcome, sats: ULong): String { if (outcome is OnchainSendOutcome.Rejected) { throw SparkExitError("Spark exit funding was not accepted: '$outcome'") } @@ -981,6 +1038,8 @@ data class SparkExitState( val fundingSeenSats: ULong = 0uL, /** A savings send to the funding address is unresolved and may be retried: cancel stays off. */ val isSavingsSendUnresolved: Boolean = false, + /** A node refused the savings payment of the exit's fee funding: progress says so and offers to pay again. */ + val isSavingsPaymentRefused: Boolean = false, /** How many payments make up [fundingSeenSats] before the exit starts: each adds its own input fee. */ val fundingSeenCount: Int = 0, /** What progress shows while the exit needs fee funding. */ diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 8a1a46a6e6..84507a7adb 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -71,6 +71,7 @@ fun SparkExitProgressScreen( onDone = onDone, onNotificationSettings = context::openNotificationSettings, onPayHigherFee = onPayHigherFee, + onRetrySavingsPayment = viewModel::retrySavingsPayment, ) } @@ -84,6 +85,7 @@ private fun Content( onDone: () -> Unit = {}, onNotificationSettings: () -> Unit = {}, onPayHigherFee: () -> Unit = {}, + onRetrySavingsPayment: () -> Unit = {}, ) { val record = uiState.record ScreenColumn { @@ -127,6 +129,15 @@ private fun Content( } } Column(modifier = Modifier.padding(horizontal = 16.dp)) { + if (uiState.isSavingsPaymentRefused) { + SecondaryButton( + text = stringResource(R.string.lightning__spark_exit__fund_savings), + onClick = onRetrySavingsPayment, + isLoading = uiState.isRetryingSavingsPayment, + testTag = "SparkExitRetrySavings", + ) + VerticalSpacer(16.dp) + } if (uiState.canPayHigherFee) { SecondaryButton( text = stringResource(R.string.lightning__spark_exit__fee_bump_button), @@ -183,6 +194,14 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, } val address = record.funding.firstOrNull()?.address val funding = uiState.progressFunding + if (uiState.isSavingsPaymentRefused) { + VerticalSpacer(24.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__savings_refused), + color = Colors.Red, + modifier = Modifier.testTag("SparkExitSavingsRefused") + ) + } if (funding != null && address != null) { VerticalSpacer(24.dp) when (funding) { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index 4c4c1c6af8..e9a8519661 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -85,6 +85,7 @@ class SparkExitViewModel @Inject constructor( fundingState = exit.fundingState, fundingAddress = exit.fundingAddress, canCancel = sparkExitRepo.canCancel, + isSavingsPaymentRefused = exit.isSavingsPaymentRefused, outsideExitSats = exit.outsideExitSats, staysOnSparkSats = SparkExitMath.staysOnSparkSats(balanceSats, exit.record), isSettling = exit.isSettling, @@ -231,6 +232,16 @@ class SparkExitViewModel @Inject constructor( } } + /** Pays the refused savings payment again, over the inputs it already spends. */ + fun retrySavingsPayment() { + if (_uiState.value.isRetryingSavingsPayment) return + viewModelScope.launch { + _uiState.update { it.copy(isRetryingSavingsPayment = true) } + sparkExitRepo.retrySavingsPayment().onFailure { ToastEventBus.send(it) } + _uiState.update { it.copy(isRetryingSavingsPayment = false) } + } + } + fun refreshBackgroundLimits() { _uiState.update { it.copy(backgroundLimits = sparkExitRepo.backgroundLimits()) } } @@ -279,6 +290,9 @@ data class SparkExitUiState( val fundingState: SparkExitFundingState? = null, val fundingAddress: String? = null, val canCancel: Boolean = false, + /** A node refused the savings payment of the fee funding: progress says so and offers to pay again. */ + val isSavingsPaymentRefused: Boolean = false, + val isRetryingSavingsPayment: Boolean = false, val backgroundLimits: SparkExitBackgroundLimits = SparkExitBackgroundLimits(), val outsideExitSats: ULong? = null, /** Spark's balance beyond the exit's leaves in any phase: what a stopped exit leaves on Spark. */ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 374077195e..a9d3e0f6d3 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -479,6 +479,7 @@ Bitkit couldn\'t read this exit\'s saved progress, so it rebuilds it from the chain. You receive about Savings payment fee + Your savings payment didn\'t go through. Pay again, or fund from another wallet. Total from savings Fee funding confirms Publishing exit transactions diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 14f686ebed..ce2c4aba89 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -964,6 +964,72 @@ class SparkExitRepoTest : BaseUnitTest() { assertNull(store.load()) } + private fun refusedSavingsPayment() = OnchainSendAttempt( + walletId = "wallet", + attemptId = "attempt", + requestId = null, + orderId = null, + address = funding, + amountSats = 9_000uL, + isMaxAmount = false, + feeRateSatsPerVByte = 9uL, + isTransfer = false, + channelId = null, + tags = emptyList(), + evidence = OnchainSendEvidence.Rejected, + txid = "refused", + refusalReason = "sendrawtransaction RPC error: {\"code\":-1}", + ) + + @Test + fun `a refused savings payment is shown, and a payment still unanswered is not`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord()) + whenever(lightning.currentOnchainSendAttempt()).thenReturn(refusedSavingsPayment()) + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + + sut.tick().getOrThrow() + assertTrue(sut.state.value.isSavingsPaymentRefused) + assertFalse(sut.canCancel, "the refused payment may still be sent, so the exit stays") + + whenever(lightning.currentOnchainSendAttempt()) + .thenReturn(refusedSavingsPayment().copy(evidence = OnchainSendEvidence.Unknown)) + sut.tick().getOrThrow() + assertFalse(sut.state.value.isSavingsPaymentRefused) + sut.onAppBackgrounded() + } + + @Test + fun `paying again from savings re-signs the refused payment over its own inputs`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord()) + val refused = refusedSavingsPayment() + whenever(lightning.currentOnchainSendAttempt()).thenReturn(refused) + whenever( + lightning.retryOriginalOnchainSend(any(), any(), any(), anyOrNull(), any(), any()) + ).thenReturn(Result.success(OnchainSendOutcome.Accepted("again"))) + whenever(lightning.completeAcceptedOrdinaryFollowup(any())).thenReturn(Unit) + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + sut.tick().getOrThrow() + + sut.retrySavingsPayment().getOrThrow() + + // The same attempt at the rate the user approved: it spends the refused payment's inputs, so at most one of + // the two can ever confirm. No new payment picks other coins. + verify(lightning).retryOriginalOnchainSend(eq("attempt"), eq("wallet"), eq(9uL), anyOrNull(), any(), any()) + verify(lightning, never()).sendOnChain( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + ) + assertEquals("again", assertNotNull(store.load()).fundingPaymentTxid) + assertFalse(sut.state.value.isSavingsPaymentRefused) + sut.onAppBackgrounded() + } + @Test fun `cancel keeps funding that reached the address and sends it back to savings`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) From e9c59c89b6058ce0428ebb2a7c4d3e8d1140ff5a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:44:25 +0100 Subject: [PATCH 056/154] fix: keep watching unconfirmed spark exit funding beside dust --- .../to/bitkit/repositories/SparkExitDriver.kt | 37 +++++++++++++++++-- .../repositories/SparkExitDriverTest.kt | 25 +++++++++++++ 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 83849551f5..57dc68e7d0 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -777,10 +777,7 @@ class SparkExitDriver( val isEverSweepable = runCatching { SparkExitSweep.plan(SparkExitSweep.worthSweeping(all, 1uL), record.destination, 1uL) != null }.getOrDefault(true) - if (!isEverSweepable) { - val total = all.fold(0uL) { sum, input -> sum.safe() + input.valueSats.safe() } - return current.copy(leftoverSweep = SparkExitRecord.LeftoverSweep(null, null, total, isDustKept = true)) - } + if (!isEverSweepable) return keepAsDust(record, current, utxos, built) val refused = built?.takeIf { it.isWaitingForFees }?.refusedFeeRate ?: 0uL // A refusal raises the rate up to the next block's or the exit's, never above: a node asking more is refused // again, and the sweep waits a block for fees to drop. @@ -794,6 +791,38 @@ class SparkExitDriver( return buildSweep(current, inputs, rate, built?.replacedTxids?.takeIf { it.isNotEmpty() }) } + /** + * Confirmed outputs not even the lowest relay rate can send stay as dust. Funding still unconfirmed beside them is + * not let go: the exit keeps every output and looks again after a recheck. + */ + private fun keepAsDust( + record: SparkExitRecord, + confirmedOnly: SparkExitRecord, + utxos: List, + built: SparkExitRecord.LeftoverSweep?, + ): SparkExitRecord { + val isAllConfirmed = utxos.all { it.status.confirmed } + val confirmed = if (isAllConfirmed) utxos else utxos.filter { it.status.confirmed } + val total = confirmed.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + if (isAllConfirmed) { + val kept = SparkExitRecord.LeftoverSweep(null, null, total, isDustKept = true) + return confirmedOnly.copy(leftoverSweep = kept) + } + val height = tip ?: return record + val waiting = SparkExitRecord.LeftoverSweep( + null, + null, + utxos.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() }, + replacedTxids = built?.replacedTxids.orEmpty(), + waitingSince = built?.takeIf { it.isWaitingForFees }?.waitingSince ?: height, + checkedAtHeight = height, + ) + return record.copy( + leftover = utxos.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) }, + leftoverSweep = waiting, + ) + } + /** * The sweep confirmed. Funding that reached the address after it was built is still there: it waits and goes out * in a sweep of its own, and the confirmed one is kept to show. diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 1b924f40d3..a1dab765cc 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1770,6 +1770,31 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) } + @Test + fun `dust confirmed beside unconfirmed funding keeps watching until that funding confirms`() = test { + val dust = SparkExitFixtures.utxo("d0".repeat(32), 0u, 294uL) + val late = SparkExitFixtures.utxo("e1".repeat(32), 0u, 30_000uL, confirmed = false) + chain.utxosByAddress[SWEEP_FUNDING] = listOf(dust, late) + chain.economyRate = 50uL + var record = SparkExitFixtures.record(Phase.Done).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + leftover = listOf(SparkExitRecord.Leftover(dust.txid, dust.vout, dust.value)), + ) + record = driver(tip = 1_000u).tick(record) + record = driver(tip = 1_144u).tick(record) + + assertTrue(record.needsDriving, "the unconfirmed funding is still to be swept") + assertFalse(assertNotNull(record.leftoverSweep).isDustKept) + assertTrue(record.leftover.any { it.txid == late.txid }) + + chain.utxosByAddress[SWEEP_FUNDING] = listOf(dust, late.copy(status = EsploraTxStatus(true, 1_200u))) + chain.economyRate = 1uL + record = driver(tip = 1_288u).tick(record) + assertEquals(1, chain.rawBroadcasts.size) + assertTrue(SparkExitTxInputs.decode(chain.rawBroadcasts.single())!!.any { it.prevTxid == late.txid }) + } + @Test fun `a replacement that would be dust keeps the accepted sweep`() = test { var record = driver(tip = 1_000u).tick(sweepDone()) From c9b3354525c9dca89d66c072eaa19ea75363fd46 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 19:57:57 +0100 Subject: [PATCH 057/154] fix: allow a higher spark exit fee once a failed-leaf retry built --- .../to/bitkit/repositories/SparkExitRecord.kt | 13 ++++++++---- .../repositories/SparkExitFundingTest.kt | 20 ++++++++++++++++++- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index bc5b5a9ca3..230a09f55c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -422,12 +422,17 @@ data class SparkExitRecord( ) /** - * Whether the user may raise the exit's fee rate: it runs on a built recovery, is not rebuilding or retrying leaves - * the operators moved, and the network finds its rate too low ([underpricedStep]) or asks more for the next block - * ([fees]). + * Whether the user may raise the exit's fee rate: it runs on a built recovery (a failed-leaf retry once it built + * steps of its own), is not rebuilding, and the network finds its rate too low ([underpricedStep]) or asks more + * for the next block ([fees]). */ fun canPayHigherFee(tip: UInt?, fees: SparkExitNetworkFees?): Boolean { - if (phase != Phase.Running || isRebuilding || recovery == null || isRetryingFailedLeaves) return false + val live = recovery ?: return false + if (phase != Phase.Running || isRebuilding) return false + // A failed-leaf retry that built a recovery of its own can be sped up, its timing kept for the leaves still + // outstanding; one waiting only on the operators has nothing to speed up. + val hasStepToConfirm = live.transactions.any { it.status !is ExitTransactionStatus.Confirmed } + if (isRetryingFailedLeaves && !hasStepToConfirm) return false return underpricedStep(tip) != null || isBelowNetwork(fees) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 49953ce9ac..9fda488262 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -1,5 +1,7 @@ package to.bitkit.repositories +import breez_sdk_spark.CooperativeRecoveryError +import breez_sdk_spark.CooperativeRecoveryFailure import breez_sdk_spark.CpfpFundingStrategy import breez_sdk_spark.ExitTransactionStatus import breez_sdk_spark.PerBranchFunding @@ -588,7 +590,23 @@ class SparkExitFundingTest { ) assertTrue(slow.canPayHigherFee(1_000u, calm)) assertFalse(slow.copy(isRebuilding = true).canPayHigherFee(1_000u, rising)) - assertFalse(slow.copy(failedLeafRetrySince = 1_000u).canPayHigherFee(1_000u, rising)) + // A retry of failed leaves that built its own recovery can be sped up; one waiting on the operators can't. + assertTrue(slow.copy(failedLeafRetrySince = 1_000u).canPayHigherFee(1_000u, rising)) + val waitingOnOperators = record.adopt( + SparkExitFixtures.recovery( + emptyList(), + failed = listOf( + CooperativeRecoveryFailure( + "leaf-1", + "o", + 0u, + CooperativeRecoveryError.OperatorsUnavailable("down"), + ), + ), + ), + 0L, + ).copy(failedLeafRetrySince = 1_000u) + assertFalse(waitingOnOperators.canPayHigherFee(1_000u, rising)) assertFalse(SparkExitFixtures.record().canPayHigherFee(1_000u, rising)) } From 311caae0f7c807f002f7c79ff4ce6021b3fac79a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 20:17:30 +0100 Subject: [PATCH 058/154] fix: keep a spark exit cancel out of its savings payment again --- .../to/bitkit/repositories/SparkExitRepo.kt | 25 +++++++------- .../bitkit/repositories/SparkExitRepoTest.kt | 34 +++++++++++++++++++ 2 files changed, 47 insertions(+), 12 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 32c1432a5a..b6ea1b51fc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -842,19 +842,20 @@ class SparkExitRepo @Inject constructor( runSuspendCatching { if (!paymentMutex.tryLock()) throw SparkExitError("A Spark exit payment is already running") try { - val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } - val refused = savingsSend(record)?.takeIf { SparkExitMath.isSavingsPaymentRefused(record, it) } - ?: throw SparkExitError("No refused savings payment to pay again") - val outcome = lightningRepo.retryOriginalOnchainSend( - attemptId = refused.attemptId, - walletId = refused.walletId, - feeRateSatsPerVByte = refused.feeRateSatsPerVByte, - ) { original -> check(original.attemptId == refused.attemptId && original.address == refused.address) } - .getOrThrow() - val txid = fundingTxid(outcome, refused.amountSats) + // Under the tick lock from the check to the saved txid, as the start's payment: a cancel either ends + // the exit before savings pays again or finds the payment and refuses. tickMutex.withLock { - val current = _state.value.record - if (current == null || current.createdAt != record.createdAt) return@withLock + val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } + val refused = savingsSend(record)?.takeIf { SparkExitMath.isSavingsPaymentRefused(record, it) } + ?: throw SparkExitError("No refused savings payment to pay again") + val outcome = lightningRepo.retryOriginalOnchainSend( + attemptId = refused.attemptId, + walletId = refused.walletId, + feeRateSatsPerVByte = refused.feeRateSatsPerVByte, + ) { check(it.attemptId == refused.attemptId && it.address == refused.address) } + .getOrThrow() + val txid = fundingTxid(outcome, refused.amountSats) + val current = _state.value.record ?: return@withLock val paid = current.copy(fundingPaymentTxid = txid) saveRecord(paid) _state.update { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index ce2c4aba89..f63fa85bbb 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1030,6 +1030,40 @@ class SparkExitRepoTest : BaseUnitTest() { sut.onAppBackgrounded() } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a cancel while savings pays again waits for the payment and then keeps the exit`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(awaitingRecord()) + val refused = refusedSavingsPayment() + whenever(lightning.currentOnchainSendAttempt()).thenReturn(refused) + val gate = CompletableDeferred() + whenever( + lightning.retryOriginalOnchainSend(any(), any(), any(), anyOrNull(), any(), any()) + ).doSuspendableAnswer { + // Savings accepted it: the attempt is no longer unresolved, but the exit has not recorded it yet. + whenever(lightning.currentOnchainSendAttempt()) + .thenReturn(refused.copy(evidence = OnchainSendEvidence.Accepted, txid = "again")) + gate.await() + Result.success(OnchainSendOutcome.Accepted("again")) + } + whenever(lightning.completeAcceptedOrdinaryFollowup(any())).thenReturn(Unit) + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + sut.tick().getOrThrow() + + val retry = async { sut.retrySavingsPayment() } + runCurrent() + val cancel = async { sut.cancel() } + runCurrent() + gate.complete(Unit) + retry.await().getOrThrow() + + assertTrue(cancel.await().isFailure, "savings paid this exit: it stays") + assertEquals("again", assertNotNull(store.load()).fundingPaymentTxid) + sut.onAppBackgrounded() + } + @Test fun `cancel keeps funding that reached the address and sends it back to savings`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) From 49a93c568b70fdab1b61d51ad30e4ce11d1b5400 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 20:17:30 +0100 Subject: [PATCH 059/154] fix: translate the refused spark exit savings payment line --- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + 15 files changed, 15 insertions(+) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 3b13a914c6..35c1de5e46 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -314,6 +314,7 @@ تعذّر على Bitkit قراءة التقدم المحفوظ لهذا الخروج، لذا يعيد بناءه من السلسلة. ستستلم نحو رسوم الدفع من المدخرات + لم يكتمل دفعك من المدخرات. ادفع مرة أخرى، أو موّل من محفظة أخرى. الإجمالي من المدخرات تأكيد تمويل الرسوم نشر معاملات الخروج diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 68f32ce44c..378d474a50 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -321,6 +321,7 @@ Bitkit no pudo leer el progreso guardado de esta salida, así que lo reconstruye a partir de la cadena. Recibes aproximadamente Comisión del pago desde ahorros + Tu pago desde ahorros no se completó. Paga de nuevo o financia desde otra billetera. Total desde ahorros Confirmación de la financiación de comisiones Publicando transacciones de salida diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index f852f7dc22..e01537fdcf 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -318,6 +318,7 @@ Bitkit no ha pogut llegir el progrés desat d\'aquesta sortida, així que el reconstrueix a partir de la cadena. Rebràs aproximadament Comissió del pagament dels estalvis + El teu pagament dels estalvis no s\'ha completat. Torna a pagar o finança des d\'un altre moneder. Total dels estalvis Es confirma el finançament de comissions Publicant les transaccions de sortida diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index c7ef7d33d4..c6465bc2e2 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -321,6 +321,7 @@ Bitkit nemohl načíst uložený průběh tohoto odchodu, proto jej obnovuje z blockchainu. Obdržíte přibližně Poplatek za platbu z úspor + Vaše platba z úspor neprošla. Zaplaťte znovu, nebo financujte z jiné peněženky. Celkem z úspor Potvrzení financování poplatků Zveřejnění transakcí odchodu diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index e5a3eedf3b..3209cf1b1f 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -197,6 +197,7 @@ Bitkit konnte den gespeicherten Fortschritt dieses Ausstiegs nicht lesen und stellt ihn daher aus der Blockchain wieder her. Du erhältst etwa Gebühr für Zahlung vom Sparkonto + Deine Zahlung vom Sparkonto ist nicht durchgegangen. Zahle erneut oder finanziere aus einer anderen Wallet. Gesamt vom Sparkonto Gebührenfinanzierung wird bestätigt Ausstiegstransaktionen werden veröffentlicht diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 22da66b290..33a85c1c80 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -314,6 +314,7 @@ Το Bitkit δεν μπόρεσε να διαβάσει την αποθηκευμένη πρόοδο αυτής της εξόδου, οπότε την ανακατασκευάζει από το blockchain. Λαμβάνετε περίπου Τέλος πληρωμής από αποταμιεύσεις + Η πληρωμή σας από αποταμιεύσεις δεν ολοκληρώθηκε. Πληρώστε ξανά ή χρηματοδοτήστε από άλλο πορτοφόλι. Σύνολο από αποταμιεύσεις Επιβεβαίωση χρηματοδότησης τελών Δημοσίευση συναλλαγών εξόδου diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 129e55b529..5496f169ca 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -320,6 +320,7 @@ Bitkit no pudo leer el progreso guardado de esta salida, así que lo reconstruye a partir de la cadena. Recibes aproximadamente Comisión del pago desde ahorros + Tu pago desde ahorros no se ha completado. Paga de nuevo o financia desde otro monedero. Total desde ahorros Confirmación de la financiación de comisiones Publicando transacciones de salida diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 8cd88075af..e2970f43c4 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -262,6 +262,7 @@ Bitkit no pudo leer el progreso guardado de esta salida, así que lo reconstruye a partir de la cadena. Recibes aproximadamente Comisión del pago desde ahorros + Tu pago desde ahorros no se completó. Paga de nuevo o financia desde otro monedero. Total desde ahorros Confirmación de la financiación de comisiones Publicando transacciones de salida diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f0a529688c..c930476743 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -196,6 +196,7 @@ Bitkit n\'a pas pu lire la progression enregistrée de cette sortie, il la reconstruit donc depuis la chaîne. Vous recevez environ Frais du paiement depuis l\'épargne + Votre paiement depuis l\'épargne n\'a pas abouti. Payez à nouveau ou financez depuis un autre portefeuille. Total depuis l\'épargne Confirmation du financement des frais Publication des transactions de sortie diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 163b52059b..286bc25956 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -319,6 +319,7 @@ Bitkit non è riuscito a leggere i progressi salvati di questa uscita, quindi li ricostruisce dalla blockchain. Riceverai circa Commissione del pagamento dai risparmi + Il tuo pagamento dai risparmi non è andato a buon fine. Paga di nuovo o finanzia da un altro portafoglio. Totale dai risparmi Conferma del finanziamento delle commissioni Pubblicazione delle transazioni di uscita diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 72682c242c..7c6ca1d491 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -318,6 +318,7 @@ Bitkit kon de opgeslagen voortgang van deze exit niet lezen en bouwt die daarom opnieuw op vanuit de blockchain. Je ontvangt ongeveer Kosten voor betaling uit spaargeld + Je betaling uit spaargeld is niet gelukt. Betaal opnieuw of financier vanuit een andere wallet. Totaal uit spaargeld Kostenfinanciering wordt bevestigd Exittransacties publiceren diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index b7551530f5..f486ef6cd7 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -198,6 +198,7 @@ Bitkit nie mógł odczytać zapisanego postępu tego wyjścia, więc odtwarza go z łańcucha. Otrzymasz około Opłata za płatność z Oszczędności + Twoja płatność z Oszczędności nie przeszła. Zapłać ponownie lub sfinansuj z innego portfela. Razem z Oszczędności Potwierdzanie finansowania opłat Publikowanie transakcji wyjścia diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index a61d24bf8d..3498d5972d 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -322,6 +322,7 @@ A Bitkit não conseguiu ler o progresso salvo desta saída, então o reconstrói a partir da blockchain. Você recebe cerca de Taxa do pagamento da poupança + Seu pagamento da poupança não foi concluído. Pague novamente ou financie de outra carteira. Total da poupança Confirmação do financiamento das taxas Publicando as transações de saída diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index caa3d27b26..2a3f098e9a 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -193,6 +193,7 @@ A Bitkit não conseguiu ler o progresso guardado desta saída, por isso reconstrói-o a partir da blockchain. Recebe cerca de Taxa do pagamento da poupança + O seu pagamento da poupança não foi concluído. Pague novamente ou financie a partir de outra carteira. Total da poupança Confirmação do financiamento das taxas A publicar as transações de saída diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index cc56a79e61..b43901754b 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -330,6 +330,7 @@ Bitkit не смог прочитать сохранённый прогресс этого выхода, поэтому восстанавливает его по блокчейну. Вы получите примерно Комиссия платежа из сбережений + Платёж из сбережений не прошёл. Оплатите снова или пополните с другого кошелька. Всего из сбережений Подтверждение средств на комиссии Публикация транзакций выхода From 750dc52aca8c635c44d8b00ee5835346cf9155c6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 21:35:17 +0100 Subject: [PATCH 060/154] fix: offer no spark exit fee rate a leaf can't pay its exit at --- .../java/to/bitkit/repositories/SparkExitDriver.kt | 7 +++++++ .../to/bitkit/repositories/SparkExitDriverTest.kt | 14 ++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 57dc68e7d0..c882749e51 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -491,6 +491,13 @@ class SparkExitDriver( // A rate at which a leaf can't pay its own exit would leave that leaf on Spark: never offered. val dropped = priced.leftBehindLeaves.drop(record.leftBehindLeaves.size) if (dropped.isNotEmpty() || prepared == null) throw SparkExitFeeBumpLeavesBehind(leavesSats(record, dropped)) + // A prepare that succeeds can still skip an exiting leaf whose exit costs more than it holds at this rate. + val unpaid = prepared.skipped.filter { + it.leafId in priced.exitLeafIds && it.reason == SkippedLeafReason.FeeExceedsValue + } + if (unpaid.isNotEmpty()) { + throw SparkExitFeeBumpLeavesBehind(unpaid.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() }) + } if (prepared.funding == null) return 0uL val built = runSuspendCatching { sdk.recover(RecoverFundsRequest(prepared, priced.fundingInputs), makeSigner()) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index a1dab765cc..c4c9e9c10a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -876,6 +876,20 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(SparkExitMath.FUNDING_DUST_SATS, driver().feeBumpShortfall(record, 9uL)) } + @Test + fun `a higher fee at which the prepare skips an exiting leaf for its fee is refused`() = test { + val record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) + .copy(leafIds = listOf("leaf-1", "leaf-2")) + sdk.preparedResponse = SparkExitFixtures.prepared( + funding = null, + skipped = listOf(SkippedLeaf("leaf-2", 2_000uL, SkippedLeafReason.FeeExceedsValue)), + ) + + val refused = assertFailsWith { driver().feeBumpShortfall(record, 9uL) } + + assertEquals(2_000uL, refused.sats) + } + @Test fun `a higher fee at which a leaf can't pay its own exit is refused, the live exit unchanged`() = test { val record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) From c2a62da9a06b15a10c57b550206affa70d52e092 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 21:35:20 +0100 Subject: [PATCH 061/154] fix: keep spark exit deadlines while a retry's steps confirm --- .../to/bitkit/repositories/SparkExitRecord.kt | 8 ++++++-- .../repositories/SparkExitFundingTest.kt | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 230a09f55c..52bc8ab34c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -470,9 +470,13 @@ data class SparkExitRecord( get() = isRetryingFailedLeaves || (isActive && (recovery?.failed?.isNotEmpty() == true || waitingLeafIds.isNotEmpty())) - /** While retrying, the current recovery still lists leaves the operators have not co-signed. */ + /** + * While retrying, the current recovery still lists leaves the operators have not co-signed and has no step of its + * own left to confirm: one that does keeps its deadline. + */ val isWaitingForOperators: Boolean - get() = isRetryingFailedLeaves && recovery?.failed?.isNotEmpty() == true + get() = isRetryingFailedLeaves && recovery?.failed?.isNotEmpty() == true && + recovery.transactions.all { it.status is ExitTransactionStatus.Confirmed } val failedLeafSats: ULong get() = failedLeaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 9fda488262..9bdcb886a4 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -610,6 +610,24 @@ class SparkExitFundingTest { assertFalse(SparkExitFixtures.record().canPayHigherFee(1_000u, rising)) } + @Test + fun `a failed-leaf retry with its own steps still to confirm is not waiting only on the operators`() { + val failed = listOf( + CooperativeRecoveryFailure("coop-2", "o", 0u, CooperativeRecoveryError.OperatorsUnavailable("down")), + ) + val live = SparkExitFixtures.record(SparkExitRecord.Phase.Running) + .adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("c1")), failed = failed), 0L) + .copy(failedLeafRetrySince = 1_000u) + assertFalse(live.isWaitingForOperators, "c1 still has a deadline") + + val landed = live.copy( + recovery = live.recovery?.copy( + transactions = listOf(SparkExitFixtures.tx("c1", status = ExitTransactionStatus.Confirmed(1_001u))), + ), + ) + assertTrue(landed.isWaitingForOperators) + } + @Test fun `a new generation keeps the sweep that landed before it`() { val swept = SparkExitFixtures.recovery( From 80912ba9644028282295dada774968d1b022616c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 22:08:30 +0100 Subject: [PATCH 062/154] test: pass the fallback flag in the merged boost fee mocks --- .../java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/test/java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt b/app/src/test/java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt index 73d3c65ab3..c304a46c48 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt @@ -365,7 +365,7 @@ class BoostTransactionViewModelTest : BaseUnitTest() { fun `late fee calculation cannot change the quote of an existing broadcast`() = runTest { prepareRbf() val estimated = CompletableDeferred() - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .doSuspendableAnswer { Result.success(estimated.await()) } whenever(activityRepo.publishRbfBoost(mockTxId, newTxId)) .thenReturn(Result.failure(IllegalStateException("sync failed"))) @@ -466,7 +466,7 @@ class BoostTransactionViewModelTest : BaseUnitTest() { private suspend fun prepareRbf() { whenever(lightningRepo.getFeeRateForSpeed(any(), anyOrNull())).thenReturn(Result.success(feeRate)) - whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull())) + whenever(lightningRepo.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) .thenReturn(Result.success(totalFee)) whenever(lightningRepo.bumpFeeByRbf(any(), any())).thenReturn(Result.success(newTxId)) sut.setupActivity(activitySent) From df3420d904db881cd16cceeaffebd736ec7c6352 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Mon, 9 Nov 2026 23:56:57 +0100 Subject: [PATCH 063/154] feat: emergency exit in app status --- .../ui/settings/appStatus/AppStatusScreen.kt | 19 +++++++++ .../settings/appStatus/AppStatusViewModel.kt | 17 +++++++- app/src/main/res/values/strings.xml | 3 ++ .../appStatus/AppStatusViewModelTest.kt | 39 +++++++++++++++++++ 4 files changed, 77 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt index f2092b5a3b..a4f81407ae 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt @@ -64,6 +64,7 @@ fun AppStatusScreen( onNodeClick = { navController.navigateTo(Routes.NodeInfo) }, onChannelsClick = { navController.navigateTo(Routes.LightningConnections) }, onBackupClick = { navController.navigateTo(Routes.BackupSettings) }, + onExitClick = { navController.navigateTo(Routes.SparkExitProgress) }, ) } @@ -76,6 +77,7 @@ private fun Content( onNodeClick: () -> Unit = {}, onChannelsClick: () -> Unit = {}, onBackupClick: () -> Unit = {}, + onExitClick: () -> Unit = {}, ) { ScreenColumn { AppTopBar( @@ -153,6 +155,22 @@ private fun Content( onClick = onChannelsClick, ) + uiState.exitStep?.let { exitStep -> + StatusItem( + statusUi = StatusUi( + id = "spark_exit", + title = stringResource(R.string.settings__status__exit__title), + subtitle = when (exitStep) { + ExitStep.FUNDING -> stringResource(R.string.settings__status__exit__funding) + ExitStep.RUNNING -> stringResource(R.string.settings__status__exit__pending) + }, + iconRes = R.drawable.ic_warning, + state = HealthState.PENDING, + ), + onClick = onExitClick, + ) + } + StatusItem( statusUi = StatusUi( id = "backup", @@ -262,6 +280,7 @@ private fun Preview() { ), backupSubtitle = now().minus(3.minutes).toEpochMilliseconds().toLocalizedTimestamp(), nodeSubtitle = "Running", + exitStep = ExitStep.RUNNING, ), ) } diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt index 5c9ec0d3f3..e0d5ec34fc 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt @@ -20,6 +20,8 @@ import to.bitkit.models.HealthState import to.bitkit.repositories.AppHealthState import to.bitkit.repositories.HealthRepo import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.SparkExitRecord +import to.bitkit.repositories.SparkExitRepo import javax.inject.Inject @HiltViewModel @@ -27,6 +29,7 @@ class AppStatusViewModel @Inject constructor( @ApplicationContext private val context: Context, private val healthRepo: HealthRepo, private val lightningRepo: LightningRepo, + private val sparkExitRepo: SparkExitRepo, private val cacheStore: CacheStore, ) : ViewModel() { @@ -42,7 +45,8 @@ class AppStatusViewModel @Inject constructor( healthRepo.healthState, cacheStore.backupStatuses, lightningRepo.lightningState, - ) { healthState, backupStatuses, lightningState -> + sparkExitRepo.state, + ) { healthState, backupStatuses, lightningState, exitState -> AppStatusUiState( health = healthState, backupSubtitle = computeBackupSubtitle(healthState.backups, backupStatuses), @@ -50,6 +54,7 @@ class AppStatusViewModel @Inject constructor( HealthState.ERROR -> context.getString(R.string.settings__status__lightning_node__error) else -> lightningState.nodeLifecycleState.uiText(context) }, + exitStep = exitState.record.exitStep(), ) }.collect { newState -> _uiState.update { newState } @@ -80,4 +85,14 @@ data class AppStatusUiState( val health: AppHealthState = AppHealthState(), val backupSubtitle: String = "", val nodeSubtitle: String = "", + /** Null while no emergency exit runs. */ + val exitStep: ExitStep? = null, ) + +enum class ExitStep { FUNDING, RUNNING } + +internal fun SparkExitRecord?.exitStep(): ExitStep? = when (this?.takeIf { it.isActive }?.phase) { + is SparkExitRecord.Phase.AwaitingFunding, is SparkExitRecord.Phase.NeedsFunding -> ExitStep.FUNDING + SparkExitRecord.Phase.Running -> ExitStep.RUNNING + else -> null +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 244d62fb48..f981d86caa 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1143,6 +1143,9 @@ Connecting... Connected Bitcoin Node + Fee funding needed + In progress + Emergency Exit Disconnected Reconnecting... Connected diff --git a/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt index dc5ff93a18..8348230d1f 100644 --- a/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt @@ -6,6 +6,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.flowOf import org.junit.Before import org.junit.Test +import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import to.bitkit.R @@ -18,6 +19,9 @@ import to.bitkit.repositories.AppHealthState import to.bitkit.repositories.HealthRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState +import to.bitkit.repositories.SparkExitRecord +import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals @@ -25,6 +29,7 @@ class AppStatusViewModelTest : BaseUnitTest() { private val context: Context = mock() private val healthRepo: HealthRepo = mock() private val lightningRepo: LightningRepo = mock() + private val sparkExitRepo: SparkExitRepo = mock() private val cacheStore: CacheStore = mock() private lateinit var sut: AppStatusViewModel @@ -44,6 +49,7 @@ class AppStatusViewModelTest : BaseUnitTest() { whenever(healthRepo.healthState).thenReturn(MutableStateFlow(AppHealthState())) whenever(lightningRepo.lightningState).thenReturn(MutableStateFlow(LightningState())) whenever(cacheStore.backupStatuses).thenReturn(flowOf(emptyMap())) + whenever(sparkExitRepo.state).thenReturn(MutableStateFlow(SparkExitState())) } private fun createSut(): AppStatusViewModel { @@ -51,6 +57,7 @@ class AppStatusViewModelTest : BaseUnitTest() { context = context, healthRepo = healthRepo, lightningRepo = lightningRepo, + sparkExitRepo = sparkExitRepo, cacheStore = cacheStore, ) } @@ -177,4 +184,36 @@ class AppStatusViewModelTest : BaseUnitTest() { cancelAndIgnoreRemainingEvents() } } + + @Test + fun `exit step is null without a running exit`() { + assertEquals(null, (null as SparkExitRecord?).exitStep()) + assertEquals(null, exitRecord(SparkExitRecord.Phase.Done, isActive = false).exitStep()) + assertEquals(null, exitRecord(SparkExitRecord.Phase.Failed("reason"), isActive = false).exitStep()) + } + + @Test + fun `exit step maps running and funding phases`() { + assertEquals(ExitStep.RUNNING, exitRecord(SparkExitRecord.Phase.Running).exitStep()) + assertEquals(ExitStep.FUNDING, exitRecord(SparkExitRecord.Phase.AwaitingFunding(1_000uL)).exitStep()) + assertEquals(ExitStep.FUNDING, exitRecord(SparkExitRecord.Phase.NeedsFunding(1_000uL)).exitStep()) + } + + @Test + fun `ui state shows the step of a running exit`() = test { + val record = exitRecord(SparkExitRecord.Phase.Running) + whenever(sparkExitRepo.state).thenReturn(MutableStateFlow(SparkExitState(record = record))) + + sut = createSut() + + sut.uiState.test { + assertEquals(ExitStep.RUNNING, awaitItem().exitStep) + cancelAndIgnoreRemainingEvents() + } + } + + private fun exitRecord(phase: SparkExitRecord.Phase, isActive: Boolean = true) = mock { + on { this.phase } doReturn phase + on { this.isActive } doReturn isActive + } } From 5513084897d77f2e0819a3d3b1c040a550c4f31f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 00:31:25 +0100 Subject: [PATCH 064/154] chore: add changelog fragment --- changelog.d/next/1832.added.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/1832.added.md diff --git a/changelog.d/next/1832.added.md b/changelog.d/next/1832.added.md new file mode 100644 index 0000000000..37aff52e5d --- /dev/null +++ b/changelog.d/next/1832.added.md @@ -0,0 +1 @@ +App Status shows an emergency exit while it runs. From 02510358b90d194fcb652c53e63be1a77fd0c6d0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 01:03:16 +0100 Subject: [PATCH 065/154] fix: scroll app status and translate exit row --- .../java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt | 3 +++ app/src/main/res/values-ar/strings.xml | 3 +++ app/src/main/res/values-b+es+419/strings.xml | 3 +++ app/src/main/res/values-ca/strings.xml | 3 +++ app/src/main/res/values-cs/strings.xml | 3 +++ app/src/main/res/values-de/strings.xml | 3 +++ app/src/main/res/values-el/strings.xml | 3 +++ app/src/main/res/values-es-rES/strings.xml | 3 +++ app/src/main/res/values-es/strings.xml | 3 +++ app/src/main/res/values-fr/strings.xml | 3 +++ app/src/main/res/values-it/strings.xml | 3 +++ app/src/main/res/values-nl/strings.xml | 3 +++ app/src/main/res/values-pl/strings.xml | 3 +++ app/src/main/res/values-pt-rBR/strings.xml | 3 +++ app/src/main/res/values-pt/strings.xml | 3 +++ app/src/main/res/values-ru/strings.xml | 3 +++ 16 files changed, 48 insertions(+) diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt index a4f81407ae..b944b057e3 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt @@ -11,7 +11,9 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.verticalScroll import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.runtime.Composable @@ -89,6 +91,7 @@ private fun Content( Column( modifier = Modifier .fillMaxSize() + .verticalScroll(rememberScrollState()) .padding(horizontal = 16.dp) ) { VerticalSpacer(16.dp) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 2b817eaa5c..6f8fd4f0d6 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1819,4 +1819,7 @@ صغير عريض جارٍ تحديث الرصيد… + يلزم تمويل الرسوم + قيد التنفيذ + الخروج الطارئ diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index dd6c86f0a3..c78d341f76 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1816,4 +1816,7 @@ Pequeño Ancho Actualizando saldo… + Financiación de comisiones necesaria + En curso + Salida de emergencia diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 4f7051e19c..91e719ce27 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1816,4 +1816,7 @@ Petit Ample S’està actualitzant el saldo… + Cal finançament de comissions + En curs + Sortida d\'emergència diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 3d7bba4497..3482020001 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1817,4 +1817,7 @@ Malý Široký Aktualizace zůstatku… + Je potřeba financovat poplatky + Probíhá + Nouzový odchod diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 1e7e7eae92..b1d22e9b52 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1815,4 +1815,7 @@ Klein Breit Kontostand wird aktualisiert… + Gebührenfinanzierung nötig + Läuft + Notausstieg diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 5ed47442fd..3ec828427c 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1815,4 +1815,7 @@ Μικρό Φαρδύ Ενημέρωση υπολοίπου… + Απαιτείται χρηματοδότηση τελών + Σε εξέλιξη + Έξοδος Έκτακτης Ανάγκης diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 84dbf0b154..cc04f4ecb0 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1816,4 +1816,7 @@ Pequeño Ancho Actualizando saldo… + Financiación de comisiones necesaria + En curso + Salida de emergencia diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 0e7cce8725..2b912556bc 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1816,4 +1816,7 @@ Pequeño Ancho Actualizando saldo… + Financiación de comisiones necesaria + En curso + Salida de emergencia diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index e8e0d5b10a..a7205e7081 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1816,4 +1816,7 @@ Petit Large Mise à jour du solde… + Financement des frais requis + En cours + Sortie d\'urgence diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 9393414546..61faf695b9 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1816,4 +1816,7 @@ Piccolo Largo Aggiornamento del saldo… + Finanziamento delle commissioni necessario + In corso + Uscita di Emergenza diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 96a1e726bd..bb37147824 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1815,4 +1815,7 @@ Klein Breed Saldo bijwerken… + Kostenfinanciering nodig + Bezig + Noodexit diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index d7e2e6f395..0000edc05e 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1817,4 +1817,7 @@ Mały Szeroki Aktualizowanie salda… + Potrzebne finansowanie opłat + W toku + Wyjście awaryjne diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 75752de68e..1f58b828ff 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1816,4 +1816,7 @@ Pequeno Largo Atualizando saldo… + Financiamento das taxas necessário + Em andamento + Saída de Emergência diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 632615cb21..266762fac1 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1816,4 +1816,7 @@ Pequeno Largo A atualizar o saldo… + Financiamento das taxas necessário + Em curso + Saída de Emergência diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 6554366ff8..32b9a045a5 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1831,4 +1831,7 @@ Маленький Широкий Обновление баланса… + Нужны средства на комиссии + Выполняется + Экстренный Выход From 6b761ec80974519364500d98cfd7cf034df4050d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 01:10:37 +0100 Subject: [PATCH 066/154] fix: exit row funding step and progress navigation --- app/src/main/java/to/bitkit/ui/ContentView.kt | 5 +++- .../settings/appStatus/AppStatusViewModel.kt | 13 +++++++---- .../appStatus/AppStatusViewModelTest.kt | 23 ++++++++++++++++--- .../settings/app-status-emergency-exit.xml | 19 +++++++++++++++ 4 files changed, 51 insertions(+), 9 deletions(-) create mode 100644 journeys/settings/app-status-emergency-exit.xml diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index f550337876..6b27a0cf7c 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -2078,7 +2078,10 @@ private fun NavGraphBuilder.sparkExit(navController: NavHostController) { val parentEntry = remember(entry) { navController.getBackStackEntry(Routes.ConnectionsNav) } return hiltViewModel(parentEntry) } - val leaveExit = { navController.popBackStack(inclusive = false) } + // Back to Spark, or to the screen that opened progress directly, such as App Status. + val leaveExit = { + navController.popBackStack(inclusive = false) || navController.popBackStack() + } composableWithDefaultTransitions { SparkExitIntroScreen( onBack = { navController.popBackStack() }, diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt index e0d5ec34fc..398ef8bb15 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt @@ -20,6 +20,7 @@ import to.bitkit.models.HealthState import to.bitkit.repositories.AppHealthState import to.bitkit.repositories.HealthRepo import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.SparkExitFundingState import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo import javax.inject.Inject @@ -54,7 +55,7 @@ class AppStatusViewModel @Inject constructor( HealthState.ERROR -> context.getString(R.string.settings__status__lightning_node__error) else -> lightningState.nodeLifecycleState.uiText(context) }, - exitStep = exitState.record.exitStep(), + exitStep = exitState.record.exitStep(exitState.fundingState), ) }.collect { newState -> _uiState.update { newState } @@ -91,8 +92,10 @@ data class AppStatusUiState( enum class ExitStep { FUNDING, RUNNING } -internal fun SparkExitRecord?.exitStep(): ExitStep? = when (this?.takeIf { it.isActive }?.phase) { - is SparkExitRecord.Phase.AwaitingFunding, is SparkExitRecord.Phase.NeedsFunding -> ExitStep.FUNDING - SparkExitRecord.Phase.Running -> ExitStep.RUNNING - else -> null +/** Asks for fee funding only while no payment covers it, as the progress screen does. */ +internal fun SparkExitRecord?.exitStep(funding: SparkExitFundingState? = null): ExitStep? { + val record = this?.takeIf { it.isActive } ?: return null + val isAskingFunding = record.fundingShortfallSats != null && + (funding == null || funding is SparkExitFundingState.Ask) + return if (isAskingFunding) ExitStep.FUNDING else ExitStep.RUNNING } diff --git a/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt index 8348230d1f..86e885beb3 100644 --- a/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt @@ -19,6 +19,7 @@ import to.bitkit.repositories.AppHealthState import to.bitkit.repositories.HealthRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LightningState +import to.bitkit.repositories.SparkExitFundingState import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkExitState @@ -195,8 +196,19 @@ class AppStatusViewModelTest : BaseUnitTest() { @Test fun `exit step maps running and funding phases`() { assertEquals(ExitStep.RUNNING, exitRecord(SparkExitRecord.Phase.Running).exitStep()) - assertEquals(ExitStep.FUNDING, exitRecord(SparkExitRecord.Phase.AwaitingFunding(1_000uL)).exitStep()) - assertEquals(ExitStep.FUNDING, exitRecord(SparkExitRecord.Phase.NeedsFunding(1_000uL)).exitStep()) + assertEquals(ExitStep.FUNDING, exitRecord(SparkExitRecord.Phase.AwaitingFunding(1_000uL), 1_000uL).exitStep()) + assertEquals(ExitStep.FUNDING, exitRecord(SparkExitRecord.Phase.NeedsFunding(1_000uL), 1_000uL).exitStep()) + val asked = exitRecord(SparkExitRecord.Phase.NeedsFunding(1_000uL), 1_000uL) + assertEquals(ExitStep.FUNDING, asked.exitStep(SparkExitFundingState.Ask(1_000uL))) + } + + @Test + fun `exit step is running once a payment covers the funding`() { + val awaiting = exitRecord(SparkExitRecord.Phase.AwaitingFunding(1_000uL), 1_000uL) + val needs = exitRecord(SparkExitRecord.Phase.NeedsFunding(1_000uL), 1_000uL) + assertEquals(ExitStep.RUNNING, awaiting.exitStep(SparkExitFundingState.Paid("txid"))) + assertEquals(ExitStep.RUNNING, needs.exitStep(SparkExitFundingState.Seen("txid"))) + assertEquals(ExitStep.RUNNING, exitRecord(SparkExitRecord.Phase.NeedsFunding(1_000uL)).exitStep()) } @Test @@ -212,8 +224,13 @@ class AppStatusViewModelTest : BaseUnitTest() { } } - private fun exitRecord(phase: SparkExitRecord.Phase, isActive: Boolean = true) = mock { + private fun exitRecord( + phase: SparkExitRecord.Phase, + shortfallSats: ULong? = null, + isActive: Boolean = true, + ) = mock { on { this.phase } doReturn phase on { this.isActive } doReturn isActive + on { fundingShortfallSats } doReturn shortfallSats } } diff --git a/journeys/settings/app-status-emergency-exit.xml b/journeys/settings/app-status-emergency-exit.xml new file mode 100644 index 0000000000..a342cfe527 --- /dev/null +++ b/journeys/settings/app-status-emergency-exit.xml @@ -0,0 +1,19 @@ + + + While an emergency exit is active, App Status shows an "Emergency Exit" row under Lightning Connection. + It reads "Fee funding needed" while the exit asks for fee funding and "In progress" otherwise, including + while a payment that covers the funding waits to confirm. The row opens the exit's progress screen, and + leaving that screen returns to App Status. With no active exit the row is absent. + + Precondition: dev build on regtest with Spark connected and an emergency exit started but not yet funded + (spark emergency exit journey, then swipe to start the exit with "Fund from another wallet"). Start on the + wallet home screen. Starting an exit takes the Spark balance out of Spending for days, so use a throwaway wallet. + + + Tap the menu button (testTag "HeaderMenu") and tap App Status (testTag "DrawerAppStatus") + Verify a row titled "Emergency Exit" (testTag "Status-spark_exit") sits under Lightning Connection (testTag "Status-lightning_connection") and reads "Fee funding needed" + Tap the row and verify the exit's progress screen (testTag "SparkExitProgress") opens + Tap "Cancel exit", confirm, and verify "Exit cancelled" shows + Tap "OK" (testTag "SparkExitProgressOk") and verify App Status shows again, now without the "Emergency Exit" row + + From 076d616f6872a0d9ccfc89646a0b41d8f690e366 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 02:04:30 +0100 Subject: [PATCH 067/154] fix: leave exit progress once and reachable exit journey --- app/src/main/java/to/bitkit/ui/ContentView.kt | 6 ++++-- journeys/settings/app-status-emergency-exit.xml | 14 ++++++++------ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index 6b27a0cf7c..c88a801a38 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -2078,9 +2078,11 @@ private fun NavGraphBuilder.sparkExit(navController: NavHostController) { val parentEntry = remember(entry) { navController.getBackStackEntry(Routes.ConnectionsNav) } return hiltViewModel(parentEntry) } - // Back to Spark, or to the screen that opened progress directly, such as App Status. + // Back to Spark, or to the screen that opened progress directly, such as App Status. Once progress is gone, + // a second call pops nothing. val leaveExit = { - navController.popBackStack(inclusive = false) || navController.popBackStack() + navController.popBackStack(inclusive = false) || + navController.popBackStack(inclusive = true) } composableWithDefaultTransitions { SparkExitIntroScreen( diff --git a/journeys/settings/app-status-emergency-exit.xml b/journeys/settings/app-status-emergency-exit.xml index a342cfe527..bee8d86510 100644 --- a/journeys/settings/app-status-emergency-exit.xml +++ b/journeys/settings/app-status-emergency-exit.xml @@ -5,15 +5,17 @@ while a payment that covers the funding waits to confirm. The row opens the exit's progress screen, and leaving that screen returns to App Status. With no active exit the row is absent. - Precondition: dev build on regtest with Spark connected and an emergency exit started but not yet funded - (spark emergency exit journey, then swipe to start the exit with "Fund from another wallet"). Start on the - wallet home screen. Starting an exit takes the Spark balance out of Spending for days, so use a throwaway wallet. + Precondition: dev build on regtest with Spark connected, a Spark balance and savings that can pay the exit's + fee funding. Start an emergency exit from Spark (spark emergency exit journey), pick "Pay from savings" and + swipe to start it. Starting an exit takes the Spark balance out of Spending for days, so use a throwaway + wallet. Start on the wallet home screen. Tap the menu button (testTag "HeaderMenu") and tap App Status (testTag "DrawerAppStatus") - Verify a row titled "Emergency Exit" (testTag "Status-spark_exit") sits under Lightning Connection (testTag "Status-lightning_connection") and reads "Fee funding needed" + Verify a row titled "Emergency Exit" (testTag "Status-spark_exit") sits under Lightning Connection (testTag "Status-lightning_connection") and reads "In progress", since savings paid the funding Tap the row and verify the exit's progress screen (testTag "SparkExitProgress") opens - Tap "Cancel exit", confirm, and verify "Exit cancelled" shows - Tap "OK" (testTag "SparkExitProgressOk") and verify App Status shows again, now without the "Emergency Exit" row + Tap "OK" (testTag "SparkExitProgressOk") and verify App Status shows again with the "Emergency Exit" row still there + Tap the row again, tap "Cancel exit" and confirm + Verify App Status shows without the "Emergency Exit" row; if "Exit cancelled" shows first, tap "OK" (testTag "SparkExitProgressOk") to get there From d498d4b92ed073f87d472849ff1952fd17188156 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 03:01:10 +0100 Subject: [PATCH 068/154] docs: exit journey without unreachable cancel --- journeys/settings/app-status-emergency-exit.xml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/journeys/settings/app-status-emergency-exit.xml b/journeys/settings/app-status-emergency-exit.xml index bee8d86510..968eb23dab 100644 --- a/journeys/settings/app-status-emergency-exit.xml +++ b/journeys/settings/app-status-emergency-exit.xml @@ -3,7 +3,8 @@ While an emergency exit is active, App Status shows an "Emergency Exit" row under Lightning Connection. It reads "Fee funding needed" while the exit asks for fee funding and "In progress" otherwise, including while a payment that covers the funding waits to confirm. The row opens the exit's progress screen, and - leaving that screen returns to App Status. With no active exit the row is absent. + leaving that screen returns to App Status. With no active exit the row is absent. An exit paid from savings cannot be + cancelled and runs for days, so the row's removal once an exit ends is covered by unit tests, not here. Precondition: dev build on regtest with Spark connected, a Spark balance and savings that can pay the exit's fee funding. Start an emergency exit from Spark (spark emergency exit journey), pick "Pay from savings" and @@ -15,7 +16,5 @@ Verify a row titled "Emergency Exit" (testTag "Status-spark_exit") sits under Lightning Connection (testTag "Status-lightning_connection") and reads "In progress", since savings paid the funding Tap the row and verify the exit's progress screen (testTag "SparkExitProgress") opens Tap "OK" (testTag "SparkExitProgressOk") and verify App Status shows again with the "Emergency Exit" row still there - Tap the row again, tap "Cancel exit" and confirm - Verify App Status shows without the "Emergency Exit" row; if "Exit cancelled" shows first, tap "OK" (testTag "SparkExitProgressOk") to get there From ac7103ebf17a7e232de3d7e22f5fcda8f705263a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 10:42:10 +0100 Subject: [PATCH 069/154] fix: keep an interrupted exit start in its transfer --- .../to/bitkit/repositories/SparkExitRepo.kt | 19 +++--- .../java/to/bitkit/repositories/SparkRepo.kt | 3 + .../bitkit/repositories/SparkExitRepoTest.kt | 58 +++++++++++++++++++ 3 files changed, 73 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index b6ea1b51fc..e42a145ef7 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -688,6 +688,11 @@ class SparkExitRepo @Inject constructor( val network = requireNotNull(sparkService.networkName) { "Spark is not available on this network" } val key = fundingKey(pending.fundingIndex) var quote = pending.quote + // Spark stops paying and receiving in the same step the transfer counts its balance, before any wait. + sparkRepo.holdForExit() + val transferId = transferRepo.createTransfer(TransferType.SPARK_EXIT, quote.incomingSats.toLong()) + .onFailure { sparkRepo.releaseExitHold() } + .getOrThrow() var record = SparkExitRecord( network = network, createdAt = clock.nowMs(), @@ -702,18 +707,18 @@ class SparkExitRepo @Inject constructor( skippedLeafCount = quote.prepared.skipped.size, fundingStrategy = SparkExitRecord.PER_NODE, leafTotalSats = quote.leafTotalSats, + transferId = transferId, ) - // Saved before the transfer exists, so a failed save never leaves a transfer counted with no exit behind. - saveRecord(record) + // Saved with its transfer in one write, so no running exit is ever stored without the transfer counting it. A + // failed save settles the transfer again; one a killed start left behind is settled as an orphan on load. + runCatching { saveRecord(record) }.onFailure { + transferRepo.markSettled(transferId) + sparkRepo.releaseExitHold() + }.getOrThrow() cacheStore.update { val next = it.sparkExitNextFundingIndexes + (fundingIndexKey to pending.fundingIndex.toInt() + 1) it.copy(sparkExitNextFundingIndexes = next) } - // Spark stops paying and receiving in the same step the transfer counts its balance, before any wait. - sparkRepo.holdForExit() - val transferId = transferRepo.createTransfer(TransferType.SPARK_EXIT, quote.incomingSats.toLong()).getOrThrow() - record = record.copy(transferId = transferId) - saveRecord(record) val createdAt = record.createdAt // Published for the screens and a cancel, but driven only once the start settled the leaves it exits. startingCreatedAt = createdAt diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 4c77152745..47fe5eda91 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -252,6 +252,9 @@ class SparkRepo @Inject constructor( */ fun holdForExit() = _state.update { it.copy(isExiting = true) } + /** Releases the hold of an exit whose start failed before anything was saved: Spark was never disconnected. */ + fun releaseExitHold() = _state.update { it.copy(isExiting = false) } + /** Whether an exit quote has to wait first: a leaf optimization runs, or one ran or was cut short recently. */ suspend fun needsSettling(): Boolean = isOptimizing.value || cacheStore.data.first().sparkOptimizationActivityAt != null diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index f63fa85bbb..f356a6c008 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -116,6 +116,17 @@ class SparkExitRepoTest : BaseUnitTest() { cacheStore = mock { on { data } doReturn flowOf(AppCacheData()) }, ) + private suspend fun createTransfer() = transferRepo.createTransfer( + any(), + any(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + anyOrNull(), + ) + private fun transfer(id: String, type: TransferType = TransferType.SPARK_EXIT) = TransferEntity(id = id, type = type, amountSats = 111_000L, createdAt = 0L) @@ -732,6 +743,53 @@ class SparkExitRepoTest : BaseUnitTest() { sut.onAppBackgrounded() } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a start killed before its transfer is written leaves no exit to resume`() = test { + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + val gate = CompletableDeferred>() + whenever(createTransfer()).doSuspendableAnswer { gate.await() } + + val start = async { sut.start(fundFromSavings = false) } + runCurrent() + start.cancel() + + assertNull(createSut().load(0).getOrThrow(), "no running exit lacks the transfer counting it") + } + + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a start killed after its transfer is written leaves that transfer settled and no exit`() = test { + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + // The row is in the database once the insert runs; the app dies before the start goes on. + val gate = CompletableDeferred>() + whenever(createTransfer()).doSuspendableAnswer { gate.await() } + + val start = async { sut.start(fundFromSavings = false) } + runCurrent() + start.cancel() + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + + assertNull(createSut().load(0).getOrThrow(), "no running exit lacks the transfer counting it") + verify(transferRepo, atLeastOnce()).markSettled("transfer-1") + } + + @Test + fun `a start whose transfer write fails saves no exit and releases spark`() = test { + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + whenever(createTransfer()).thenReturn(Result.failure(SparkExitError("database locked"))) + + assertTrue(sut.start(fundFromSavings = false).isFailure) + + assertNull(SparkExitStore(File(Env.sparkExitRecordPath(0))).load()) + assertNull(sut.state.value.record) + verify(sparkRepo).releaseExitHold() + verify(sparkRepo, never()).setExiting(true, true) + } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a cancel during the start's optimization wait ends the exit before anything is paid`() = test { From 639eb8ae7b3d5bea901c9efcd338ccc090af24fc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 11:27:30 +0100 Subject: [PATCH 070/154] fix: align exit screens with the explore cell and accents --- .../wallets/activity/ActivityExploreScreen.kt | 2 +- .../settings/lightning/SparkExitComponents.kt | 71 ++++++++++++------ .../lightning/SparkExitProgressScreen.kt | 72 ++++++++----------- .../lightning/SparkExitQuoteScreen.kt | 9 ++- app/src/main/res/values-ar/strings.xml | 3 - app/src/main/res/values-b+es+419/strings.xml | 3 - app/src/main/res/values-ca/strings.xml | 3 - app/src/main/res/values-cs/strings.xml | 3 - app/src/main/res/values-de/strings.xml | 3 - app/src/main/res/values-el/strings.xml | 3 - app/src/main/res/values-es-rES/strings.xml | 3 - app/src/main/res/values-es/strings.xml | 3 - app/src/main/res/values-fr/strings.xml | 3 - app/src/main/res/values-it/strings.xml | 3 - app/src/main/res/values-nl/strings.xml | 3 - app/src/main/res/values-pl/strings.xml | 3 - app/src/main/res/values-pt-rBR/strings.xml | 3 - app/src/main/res/values-pt/strings.xml | 3 - app/src/main/res/values-ru/strings.xml | 3 - app/src/main/res/values/strings.xml | 3 - 20 files changed, 87 insertions(+), 115 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityExploreScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityExploreScreen.kt index 2dd44a755a..b7d40c382c 100644 --- a/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityExploreScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/wallets/activity/ActivityExploreScreen.kt @@ -376,7 +376,7 @@ private fun ColumnScope.OnchainDetails( } @Composable -private fun Section( +internal fun Section( title: String, modifier: Modifier = Modifier, value: String? = null, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt index 62d58dceeb..de60217d06 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -1,46 +1,61 @@ package to.bitkit.ui.settings.lightning -import androidx.annotation.StringRes import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import breez_sdk_spark.RecoverFundsResponse import to.bitkit.R -import to.bitkit.ext.setClipboardText +import to.bitkit.ext.ellipsisMiddle +import to.bitkit.models.Toast import to.bitkit.repositories.SparkExitMath import to.bitkit.repositories.SparkExitPartialFunding import to.bitkit.repositories.SparkExitQuote import to.bitkit.repositories.SparkExitRecord +import to.bitkit.ui.appViewModel import to.bitkit.ui.components.BodyS import to.bitkit.ui.components.CaptionB import to.bitkit.ui.components.CaptionM import to.bitkit.ui.components.MoneyCaptionB import to.bitkit.ui.components.QrCodeImage import to.bitkit.ui.components.rememberMoneyText +import to.bitkit.ui.screens.wallets.activity.Section import to.bitkit.ui.shared.modifiers.clickableAlpha import to.bitkit.ui.theme.Colors +import to.bitkit.ui.utils.copyToClipboard import to.bitkit.ui.utils.withAccent +import to.bitkit.ui.utils.withAccentBoldBright import to.bitkit.utils.BlockTimeHelpers +import to.bitkit.viewmodels.AppViewModel /** An amount as plain text for copy that names it, in the user's primary unit. */ @Composable internal fun sparkExitAmountText(sats: ULong): String = rememberMoneyText(sats.toLong(), showSymbol = true)?.replace(Regex(""), "") ?: sats.toString() +/** The amount marked as an inline accent, for a line drawn with [withAccentBoldBright] or [withAccentBoldRed]. */ +@Composable +internal fun sparkExitAmountAccent(sats: ULong): String = "${sparkExitAmountText(sats)}" + +/** Bold red accents for a red line: its amounts stand out in the same red, the only red of the theme. */ +internal fun String.withAccentBoldRed() = + withAccent(accentStyle = SpanStyle(color = Colors.Red, fontWeight = FontWeight.Bold)) + @Composable internal fun SparkExitQuoteRows(quote: SparkExitQuote) { Column { @@ -80,16 +95,24 @@ internal fun SparkExitFundingAddress( partial: SparkExitPartialFunding? = SparkExitMath.partialFunding(seenSats, requiredSats), isCovered: Boolean = requiredSats > 0uL && seenSats >= requiredSats, ) { - val context = LocalContext.current + val app = appViewModel + val copied = stringResource(R.string.common__copied) Column( verticalArrangement = Arrangement.spacedBy(16.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = modifier.fillMaxWidth() ) { - QrCodeImage(content = address, size = 200.dp) + // The receive screen's tile, at a fixed size with black space around it. + QrCodeImage( + content = address, + size = 200.dp, + modifier = Modifier + .padding(vertical = 16.dp) + .size(200.dp) + ) BodyS( text = stringResource(R.string.lightning__spark_exit__fund_external_text) - .replace("{amount}", sparkExitAmountText(requiredSats)), + .replace("{amount}", sparkExitAmountAccent(requiredSats)).withAccentBoldBright(), color = Colors.White64, modifier = Modifier.fillMaxWidth() ) @@ -99,15 +122,15 @@ internal fun SparkExitFundingAddress( overflow = TextOverflow.MiddleEllipsis, modifier = Modifier .fillMaxWidth() - .clickableAlpha { context.setClipboardText(address) } + .clickableAlpha(onClick = copyToClipboard(address) { app.toastCopied(copied, it) }) .testTag("SparkExitFundingAddress") ) partial?.let { BodyS( text = stringResource(R.string.lightning__spark_exit__fund_partial) - .replace("{received}", sparkExitAmountText(it.receivedSats)) - .replace("{required}", sparkExitAmountText(it.requiredSats)) - .replace("{missing}", sparkExitAmountText(it.missingSats)), + .replace("{received}", sparkExitAmountAccent(it.receivedSats)) + .replace("{required}", sparkExitAmountAccent(it.requiredSats)) + .replace("{missing}", sparkExitAmountAccent(it.missingSats)).withAccentBoldBright(), color = Colors.White64, modifier = Modifier .fillMaxWidth() @@ -124,24 +147,25 @@ internal fun SparkExitFundingAddress( } } -/** A line of progress with the transaction it is about, whose id copies on tap. */ +/** A line of progress with the transaction it is about, in the activity explore cell whose id copies on tap. */ @Composable -internal fun SparkExitTxNote(text: String?, txid: String, @StringRes txidRes: Int, testTag: String) { - val context = LocalContext.current +internal fun SparkExitTxNote(text: String?, txid: String, testTag: String) { + val app = appViewModel + val copied = stringResource(R.string.common__copied) Column( - verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier .fillMaxWidth() .testTag(testTag) ) { - text?.let { BodyS(text = it, color = Colors.White64) } - CaptionB( - text = stringResource(txidRes).replace("{txid}", txid), - maxLines = 1, - overflow = TextOverflow.MiddleEllipsis, - modifier = Modifier - .fillMaxWidth() - .clickableAlpha { context.setClipboardText(txid) } + text?.let { BodyS(text = it.withAccentBoldBright(), color = Colors.White64) } + Section( + title = stringResource(R.string.wallet__activity_tx_id), + value = txid, + modifier = Modifier.clickableAlpha( + onClick = copyToClipboard(txid) { + app.toastCopied(copied, it) + } + ) ) } } @@ -195,3 +219,6 @@ private fun SparkExitStep(title: String, isDone: Boolean, detail: String? = null } HorizontalDivider() } + +private fun AppViewModel?.toastCopied(title: String, text: String) = + this?.toast(type = Toast.ToastType.SUCCESS, title = title, description = text.ellipsisMiddle(40)) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 84507a7adb..8f6d4989b6 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -119,16 +119,19 @@ private fun Content( ) VerticalSpacer(24.dp) record?.let { ProgressDetails(it, uiState, onPayHigherFee) } - if (record?.isActive == true) { - BackgroundNotes( - limits = uiState.backgroundLimits, - onNotificationSettings = onNotificationSettings, - ) - } + if (record?.isActive == true) BackgroundNotes(uiState.backgroundLimits) VerticalSpacer(32.dp) } } Column(modifier = Modifier.padding(horizontal = 16.dp)) { + if (record?.isActive == true && !uiState.backgroundLimits.areNotificationsEnabled) { + SecondaryButton( + text = stringResource(R.string.lightning__spark_exit__note_notifications_button), + onClick = onNotificationSettings, + testTag = "SparkExitNotificationSettings", + ) + VerticalSpacer(16.dp) + } if (uiState.isSavingsPaymentRefused) { SecondaryButton( text = stringResource(R.string.lightning__spark_exit__fund_savings), @@ -188,7 +191,6 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, SparkExitTxNote( text = null, txid = it, - txidRes = R.string.lightning__spark_exit__sweep_txid, testTag = "SparkExitSweepTxid", ) } @@ -214,13 +216,11 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, is SparkExitFundingState.Paid -> SparkExitTxNote( text = stringResource(R.string.lightning__spark_exit__fund_paid), txid = funding.txid, - txidRes = R.string.lightning__spark_exit__funding_txid, testTag = "SparkExitFundingPaid", ) is SparkExitFundingState.Seen -> SparkExitTxNote( text = stringResource(R.string.lightning__spark_exit__fund_pending), txid = funding.txid, - txidRes = R.string.lightning__spark_exit__funding_txid, testTag = "SparkExitFundingSeen", ) } @@ -237,7 +237,7 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, VerticalSpacer(16.dp) BodyS( text = stringResource(R.string.lightning__spark_exit__waiting_operators) - .replace("{amount}", sparkExitAmountText(record.failedLeafSats)), + .replace("{amount}", sparkExitAmountAccent(record.failedLeafSats)).withAccentBoldBright(), color = Colors.White64, modifier = Modifier.testTag("SparkExitWaitingOperators") ) @@ -280,7 +280,7 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, VerticalSpacer(16.dp) BodyS( text = stringResource(R.string.lightning__spark_exit__outside_exit) - .replace("{amount}", sparkExitAmountText(it)), + .replace("{amount}", sparkExitAmountAccent(it)).withAccentBoldBright(), color = Colors.White64, ) } @@ -288,7 +288,7 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, VerticalSpacer(16.dp) BodyS( text = stringResource(R.string.lightning__spark_exit__lost_leaves) - .replace("{amount}", sparkExitAmountText(record.lostSats)), + .replace("{amount}", sparkExitAmountAccent(record.lostSats)).withAccentBoldRed(), color = Colors.Red, modifier = Modifier.testTag("SparkExitLostLeaves") ) @@ -297,7 +297,7 @@ private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, VerticalSpacer(16.dp) BodyS( text = stringResource(R.string.lightning__spark_exit__left_behind_leaves) - .replace("{amount}", sparkExitAmountText(record.leftBehindLeafSats)), + .replace("{amount}", sparkExitAmountAccent(record.leftBehindLeafSats)).withAccentBoldBright(), color = Colors.White64, modifier = Modifier.testTag("SparkExitLeftBehindLeaves") ) @@ -313,9 +313,8 @@ private fun LeftoverNote(record: SparkExitRecord, address: String, path: String? VerticalSpacer(16.dp) SparkExitTxNote( text = stringResource(R.string.lightning__spark_exit__leftover_swept) - .replace("{amount}", sparkExitAmountText(it.valueSats)), + .replace("{amount}", sparkExitAmountAccent(it.valueSats)), txid = it.txid, - txidRes = R.string.lightning__spark_exit__leftover_txid, testTag = "SparkExitLeftoverSweptEarlier", ) } @@ -326,52 +325,49 @@ private fun LeftoverNote(record: SparkExitRecord, address: String, path: String? when { record.isLeftoverWaitingForFees -> BodyS( text = stringResource(R.string.lightning__spark_exit__leftover_waiting) - .replace("{amount}", sparkExitAmountText(total)), + .replace("{amount}", sparkExitAmountAccent(total)).withAccentBoldBright(), color = Colors.White64, modifier = Modifier.testTag("SparkExitLeftoverWaiting") ) sweep != null && sweep.txid == null -> BodyS( text = stringResource(R.string.lightning__spark_exit__leftover_dust) - .replace("{amount}", sparkExitAmountText(total)) + .replace("{amount}", sparkExitAmountAccent(total)) .replace("{address}", address) - .replace("{path}", path.orEmpty()), + .replace("{path}", path.orEmpty()).withAccentBoldBright(), color = Colors.White64, ) sweep?.txid != null && sweep.isAccepted -> SparkExitTxNote( text = stringResource(R.string.lightning__spark_exit__leftover_swept) - .replace("{amount}", sparkExitAmountText(sweep.valueSats)), + .replace("{amount}", sparkExitAmountAccent(sweep.valueSats)), txid = sweep.txid, - txidRes = R.string.lightning__spark_exit__leftover_txid, testTag = "SparkExitLeftoverSwept", ) - sweep?.txid != null && sweep.rejection == null -> BodyS( + sweep?.txid != null && sweep.rejection == null -> SparkExitTxNote( text = stringResource(R.string.lightning__spark_exit__leftover_sending) - .replace("{amount}", sparkExitAmountText(sweep.valueSats)), - color = Colors.White64, + .replace("{amount}", sparkExitAmountAccent(sweep.valueSats)), + txid = sweep.txid, + testTag = "SparkExitLeftoverSending", ) // Refused for good: where the leftover stays, with the path a wallet needs to find it. sweep?.rejection != null && path != null -> BodyS( text = stringResource(R.string.lightning__spark_exit__leftover_rejected) - .replace("{amount}", sparkExitAmountText(total)) + .replace("{amount}", sparkExitAmountAccent(total)) .replace("{address}", address) - .replace("{path}", path), + .replace("{path}", path).withAccentBoldBright(), color = Colors.White64, modifier = Modifier.testTag("SparkExitLeftoverRejected") ) else -> BodyS( text = stringResource(R.string.lightning__spark_exit__leftover) - .replace("{amount}", sparkExitAmountText(total)) - .replace("{address}", address), + .replace("{amount}", sparkExitAmountAccent(total)) + .replace("{address}", address).withAccentBoldBright(), color = Colors.White64, ) } } @Composable -private fun BackgroundNotes( - limits: SparkExitBackgroundLimits, - onNotificationSettings: () -> Unit, -) { +private fun BackgroundNotes(limits: SparkExitBackgroundLimits) { val notes = listOfNotNull( R.string.lightning__spark_exit__note_restricted.takeIf { limits.isRestricted }, R.string.lightning__spark_exit__note_battery_saver.takeIf { limits.isPowerSaveMode }, @@ -384,14 +380,6 @@ private fun BackgroundNotes( VerticalSpacer(16.dp) BodyS(text = stringResource(it), color = Colors.White64) } - if (!limits.areNotificationsEnabled) { - VerticalSpacer(16.dp) - SecondaryButton( - text = stringResource(R.string.lightning__spark_exit__note_notifications_button), - onClick = onNotificationSettings, - testTag = "SparkExitNotificationSettings", - ) - } } @Composable @@ -417,13 +405,13 @@ private fun progressText( SparkExitRecord.Phase.Done -> listOfNotNull( // What reached savings when it is known, else only that it did. receivedSats?.let { - stringResource(R.string.lightning__spark_exit__done_received).replace("{amount}", sparkExitAmountText(it)) + stringResource(R.string.lightning__spark_exit__done_received).replace("{amount}", sparkExitAmountAccent(it)) } ?: stringResource(R.string.lightning__spark_exit__done_text), record.skippedLeafCount.takeIf { it > 0 }?.let { stringResource(R.string.lightning__spark_exit__partial_text).replace("{count}", "$it") }, record.failedLeafSats.takeIf { record.isFailedLeavesReleased && it > 0uL }?.let { - stringResource(R.string.lightning__spark_exit__failed_leaves).replace("{amount}", sparkExitAmountText(it)) + stringResource(R.string.lightning__spark_exit__failed_leaves).replace("{amount}", sparkExitAmountAccent(it)) }, ).joinToString(" ") SparkExitRecord.Phase.Failed(CANCELLED_REASON) -> @@ -431,7 +419,7 @@ private fun progressText( is SparkExitRecord.Phase.Failed -> sparkExitFailedText( nothingText = stringResource(R.string.lightning__spark_exit__failed_text), staysText = stringResource(R.string.lightning__spark_exit__failed_stays), - outsideAmount = staysOnSparkSats?.let { sparkExitAmountText(it) }, + outsideAmount = staysOnSparkSats?.let { sparkExitAmountAccent(it) }, ) is SparkExitRecord.Phase.NeedsFunding -> when (val funding = progressFunding) { // A payment that covers it waits to confirm: nothing to ask for. diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt index ccf7e7f921..2060d4286c 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt @@ -25,6 +25,7 @@ import to.bitkit.ui.scaffold.ScreenColumn import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors import to.bitkit.ui.utils.withAccent +import to.bitkit.ui.utils.withAccentBoldBright /** What the exit takes on-chain, what it costs, and what stays behind. */ @Composable @@ -66,8 +67,12 @@ private fun Content( } uiState.isQuoting && uiState.isSettling -> BodyM( text = stringResource(R.string.lightning__spark_exit__quote_settling), + color = Colors.White64, + ) + uiState.isQuoting -> BodyM( + text = stringResource(R.string.lightning__spark_exit__quote_loading), + color = Colors.White64, ) - uiState.isQuoting -> BodyM(text = stringResource(R.string.lightning__spark_exit__quote_loading)) } block?.let { VerticalSpacer(16.dp) @@ -106,7 +111,7 @@ private fun UnexitableNote(sats: ULong) { VerticalSpacer(16.dp) BodyS( text = stringResource(R.string.lightning__spark_exit__quote_outside) - .replace("{amount}", sparkExitAmountText(sats)), + .replace("{amount}", sparkExitAmountAccent(sats)).withAccentBoldBright(), color = Colors.White64, modifier = Modifier.testTag("SparkExitQuoteOutside") ) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 2b817eaa5c..1de11525f0 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -268,7 +268,6 @@ يقسمه Bitkit إلى {count} أجزاء، جزء لكل خطوة، حتى لا تعطّل خطوة عالقة الخطوات الأخرى. يدفع الخروج رسومه من دفعة منفصلة على السلسلة بقيمة <accent>{amount}</accent>. ما لا يُنفق منها يعود إلى المدخرات في النهاية. موّل\n<accent>الرسوم</accent> - معرّف المعاملة: {txid} استخدم هذا فقط إذا توقّف Spark عن العمل لديك. ينقل رصيد الإنفاق إلى المدخرات <accent>من دون مشغّلي Spark</accent>.\n\nيستغرق <accent>ما يصل إلى 4 أسابيع</accent>، ويكلّف رسومًا على السلسلة تُدفع من المدخرات، وقد تبقى المبالغ الصغيرة جدًا على Spark. يعمل في الخلفية، ويُعلمك Bitkit إذا احتاج إليك. غادر Spark\n<accent>على السلسلة</accent> يبقى على Spark @@ -278,7 +277,6 @@ تعذّر إرسال المتبقي من تمويل الرسوم بقيمة {amount} ويبقى على {address}، مسار الاشتقاق {path}. جارٍ إرسال {amount} من تمويل الرسوم المتبقي إلى المدخرات. تم إرسال {amount} من تمويل الرسوم المتبقي إلى المدخرات. - معرّف المعاملة: {txid} سيصل {amount} من فكة الرسوم إلى مدخراتك عندما تنخفض رسوم الشبكة. طالب مالك سابق لهذه الأموال بمبلغ {amount} على السلسلة ولا يمكن استرداده. الخروج الطارئ @@ -320,7 +318,6 @@ نشر معاملات الخروج الإرسال إلى المدخرات انتظار القفل الزمني - معرّف المعاملة: {txid} اسحب للخروج الرسوم أعلى مما ستستلمه. لا يمكن قراءة جزء من هذا الخروج على السلسلة الآن. يحاول Bitkit مجددًا لمدة تصل إلى أسبوع. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index dd6c86f0a3..ddb4fac7a6 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -275,7 +275,6 @@ Bitkit lo divide en {count} partes, una por cada paso, para que un paso atascado no bloquee a los demás. La salida paga sus comisiones con un pago on-chain aparte de <accent>{amount}</accent>. Lo que no gaste vuelve a tus ahorros al final. Financiar las\n<accent>comisiones</accent> - ID de transacción: {txid} Úsala solo si Spark deja de funcionarte. Mueve tu saldo de gastos a tus ahorros <accent>sin los operadores de Spark</accent>.\n\nTarda <accent>hasta 4 semanas</accent>, cuesta comisiones on-chain pagadas desde tus ahorros y los montos muy pequeños pueden quedarse atrás. Funciona en segundo plano y Bitkit te avisa si te necesita. Salir de Spark\n<accent>on-chain</accent> Se queda en Spark @@ -285,7 +284,6 @@ {amount} de financiación de comisiones sobrante no se pudo enviar y se queda en {address}, ruta de derivación {path}. Enviando {amount} de financiación de comisiones sobrante a tus ahorros. {amount} de financiación de comisiones sobrante se envió a tus ahorros. - ID de transacción: {txid} {amount} de cambio de comisiones llegará a tus ahorros cuando bajen las comisiones de la red. Un propietario anterior de estos fondos reclamó {amount} on-chain y no se puede recuperar. Salida de emergencia @@ -327,7 +325,6 @@ Publicando transacciones de salida Enviando a ahorros Esperando el bloqueo temporal - ID de transacción: {txid} Desliza para salir Las comisiones son mayores que lo que recibirías. En este momento no se puede leer on-chain parte de esta salida. Bitkit lo vuelve a intentar durante hasta una semana. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 4f7051e19c..dded4415e9 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -272,7 +272,6 @@ Bitkit el divideix en {count} parts, una per a cada pas, perquè un pas encallat no aturi els altres. La sortida paga les seves comissions amb un pagament on-chain separat de <accent>{amount}</accent>. El que no gasti torna als estalvis al final. Finança les\n<accent>comissions</accent> - ID de transacció: {txid} Utilitza-ho només si Spark deixa de funcionar-te. Mou el teu saldo de despesa als estalvis <accent>sense els operadors de Spark</accent>.\n\nTriga <accent>fins a 4 setmanes</accent>, costa comissions on-chain pagades dels estalvis, i imports molt petits es poden quedar enrere. Funciona en segon pla, i Bitkit t\'avisa si et necessita. Surt de Spark\n<accent>on-chain</accent> Es queda a Spark @@ -282,7 +281,6 @@ {amount} de finançament de comissions sobrant no s\'ha pogut enviar i es queda a {address}, camí de derivació {path}. Enviant {amount} de finançament de comissions sobrant als estalvis. {amount} de finançament de comissions sobrant s\'ha enviat als estalvis. - ID de transacció: {txid} {amount} de canvi de comissions arribarà als teus estalvis quan baixin les comissions de xarxa. Un antic propietari d\'aquests fons ha reclamat {amount} on-chain i no es pot recuperar. Sortida d\'emergència @@ -324,7 +322,6 @@ Publicant les transaccions de sortida Enviant als estalvis Esperant el timelock - ID de transacció: {txid} Llisca per sortir Les comissions són més altes del que rebries. Ara mateix no es pot llegir on-chain part d\'aquesta sortida. Bitkit ho torna a intentar durant un màxim d\'una setmana. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 3d7bba4497..77d3077526 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -275,7 +275,6 @@ Bitkit ji rozdělí na {count} částí, jednu pro každý krok, aby jeden zaseknutý krok nezdržel ostatní. Odchod platí své poplatky ze samostatné on-chain platby ve výši <accent>{amount}</accent>. Co nespotřebuje, se na konci vrátí do úspor. Financujte\n<accent>poplatky</accent> - ID transakce: {txid} Použijte to, jen pokud vám Spark přestane fungovat. Přesune váš zůstatek k utrácení do úspor <accent>bez operátorů Sparku</accent>.\n\nTrvá <accent>až 4 týdny</accent>, stojí on-chain poplatky placené z úspor a velmi malé částky mohou zůstat na Spark. Běží na pozadí a Bitkit vás upozorní, pokud vás bude potřebovat. Opustit Spark\n<accent>on-chain</accent> Zůstává na Spark @@ -285,7 +284,6 @@ {amount} ze zbylého financování poplatků se nepodařilo odeslat a zůstává na {address}, derivační cesta {path}. Odesílání {amount} ze zbylého financování poplatků do úspor. {amount} ze zbylého financování poplatků bylo odesláno do úspor. - ID transakce: {txid} {amount} drobných z poplatků dorazí do vašich úspor, až síťové poplatky klesnou. {amount} si on-chain nárokoval dřívější vlastník těchto prostředků a nelze je získat zpět. Nouzový odchod @@ -327,7 +325,6 @@ Zveřejnění transakcí odchodu Odesílání do úspor Čekání na časový zámek - ID transakce: {txid} Přejeďte pro odchod Poplatky jsou vyšší, než kolik byste obdrželi. Část tohoto odchodu teď nelze on-chain načíst. Bitkit to bude zkoušet znovu až týden. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 1e7e7eae92..6c7ffd5cfa 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -151,7 +151,6 @@ Bitkit teilt sie in {count} Teile auf, einen für jeden Schritt, damit ein hängender Schritt die anderen nicht aufhält. Der Ausstieg zahlt seine Gebühren aus einer separaten On-Chain-Zahlung von <accent>{amount}</accent>. Was er nicht ausgibt, geht am Ende zurück auf dein Sparkonto. Gebühren\n<accent>finanzieren</accent> - Transaktions-ID: {txid} Nutze dies nur, wenn Spark für dich nicht mehr funktioniert. Es verschiebt dein Ausgabenguthaben auf dein Sparkonto, <accent>ohne die Spark-Betreiber</accent>.\n\nEs dauert <accent>bis zu 4 Wochen</accent>, kostet On-Chain-Gebühren, die vom Sparkonto bezahlt werden, und sehr kleine Beträge können zurückbleiben. Es läuft im Hintergrund, und Bitkit benachrichtigt dich, wenn es dich braucht. Spark\n<accent>on-chain verlassen</accent> Bleibt auf Spark @@ -161,7 +160,6 @@ {amount} übrige Gebührenfinanzierung konnte nicht gesendet werden und bleibt bei {address}, Ableitungspfad {path}. {amount} übrige Gebührenfinanzierung wird an dein Sparkonto gesendet. {amount} übrige Gebührenfinanzierung wurde an dein Sparkonto gesendet. - Transaktions-ID: {txid} {amount} Gebührenwechselgeld erreicht dein Sparkonto, wenn die Netzgebühren sinken. {amount} wurde von einem früheren Besitzer dieser Mittel on-chain beansprucht und kann nicht zurückgeholt werden. Notausstieg @@ -203,7 +201,6 @@ Ausstiegstransaktionen werden veröffentlicht Wird an das Sparkonto gesendet Warten auf die Zeitsperre - Transaktions-ID: {txid} Swipe zum Aussteigen Die Gebühren sind höher als der Betrag, den du erhalten würdest. Ein Teil dieses Ausstiegs kann gerade nicht on-chain gelesen werden. Bitkit versucht es bis zu einer Woche lang erneut. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 5ed47442fd..2b70863583 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -268,7 +268,6 @@ Το Bitkit τη χωρίζει σε {count} μέρη, ένα για κάθε βήμα, ώστε ένα κολλημένο βήμα να μην καθυστερεί τα άλλα. Η έξοδος πληρώνει τα τέλη της από μια ξεχωριστή on-chain πληρωμή <accent>{amount}</accent>. Ό,τι δεν ξοδέψει επιστρέφει στις αποταμιεύσεις στο τέλος. Χρηματοδότηση\n<accent>τελών</accent> - ID συναλλαγής: {txid} Χρησιμοποιήστε το μόνο αν το Spark σταματήσει να λειτουργεί για εσάς. Μεταφέρει το υπόλοιπο δαπανών σας στις αποταμιεύσεις <accent>χωρίς τους διαχειριστές του Spark</accent>.\n\nΔιαρκεί <accent>έως 4 εβδομάδες</accent>, κοστίζει τέλη on-chain που πληρώνονται από τις αποταμιεύσεις, και πολύ μικρά ποσά μπορεί να μείνουν πίσω. Εκτελείται στο παρασκήνιο και το Bitkit σας ειδοποιεί αν σας χρειαστεί. Έξοδος από το Spark\n<accent>on-chain</accent> Παραμένει στο Spark @@ -278,7 +277,6 @@ {amount} από την υπόλοιπη χρηματοδότηση τελών δεν ήταν δυνατό να σταλούν και παραμένουν στη διεύθυνση {address}, διαδρομή παραγωγής {path}. Αποστολή {amount} από την υπόλοιπη χρηματοδότηση τελών στις αποταμιεύσεις. {amount} από την υπόλοιπη χρηματοδότηση τελών στάλθηκαν στις αποταμιεύσεις. - ID συναλλαγής: {txid} {amount} ρέστα τελών θα φτάσουν στις αποταμιεύσεις σας όταν πέσουν τα τέλη δικτύου. {amount} διεκδικήθηκαν on-chain από προηγούμενο κάτοχο αυτών των κεφαλαίων και δεν μπορούν να ανακτηθούν. Έξοδος Έκτακτης Ανάγκης @@ -320,7 +318,6 @@ Δημοσίευση συναλλαγών εξόδου Αποστολή στις αποταμιεύσεις Αναμονή για το timelock - ID συναλλαγής: {txid} Σύρετε Για Έξοδο Τα τέλη είναι υψηλότερα από όσα θα λαμβάνατε. Μέρος αυτής της εξόδου δεν μπορεί να διαβαστεί on-chain αυτή τη στιγμή. Το Bitkit προσπαθεί ξανά για έως μία εβδομάδα. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 84dbf0b154..afdc90c850 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -274,7 +274,6 @@ Bitkit lo divide en {count} partes, una por cada paso, para que un paso atascado no bloquee a los demás. La salida paga sus comisiones con un pago on-chain aparte de <accent>{amount}</accent>. Lo que no gaste vuelve a tus ahorros al final. Financiar las\n<accent>comisiones</accent> - ID de transacción: {txid} Úsala solo si Spark deja de funcionarte. Mueve tu saldo de gastos a tus ahorros <accent>sin los operadores de Spark</accent>.\n\nTarda <accent>hasta 4 semanas</accent>, cuesta comisiones on-chain pagadas desde tus ahorros y los importes muy pequeños pueden quedarse atrás. Funciona en segundo plano y Bitkit te avisa si te necesita. Salir de Spark\n<accent>on-chain</accent> Se queda en Spark @@ -284,7 +283,6 @@ {amount} de financiación de comisiones sobrante no se pudo enviar y se queda en {address}, ruta de derivación {path}. Enviando {amount} de financiación de comisiones sobrante a tus ahorros. {amount} de financiación de comisiones sobrante se ha enviado a tus ahorros. - ID de transacción: {txid} {amount} de cambio de comisiones llegará a tus ahorros cuando bajen las comisiones de la red. Un propietario anterior de estos fondos ha reclamado {amount} on-chain y no se puede recuperar. Salida de emergencia @@ -326,7 +324,6 @@ Publicando transacciones de salida Enviando a ahorros Esperando el bloqueo temporal - ID de transacción: {txid} Desliza para salir Las comisiones son mayores que lo que recibirías. Ahora mismo no se puede leer on-chain parte de esta salida. Bitkit lo vuelve a intentar durante hasta una semana. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 0e7cce8725..9e9a42b4c1 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -216,7 +216,6 @@ Bitkit lo divide en {count} partes, una por cada paso, para que un paso atascado no bloquee a los demás. La salida paga sus comisiones con un pago on-chain aparte de <accent>{amount}</accent>. Lo que no gaste vuelve a tus ahorros al final. Financiar las\n<accent>comisiones</accent> - ID de transacción: {txid} Úsala solo si Spark deja de funcionarte. Mueve tu saldo de gastos a tus ahorros <accent>sin los operadores de Spark</accent>.\n\nTarda <accent>hasta 4 semanas</accent>, cuesta comisiones on-chain pagadas desde tus ahorros y los importes muy pequeños pueden quedarse atrás. Funciona en segundo plano y Bitkit te avisa si te necesita. Salir de Spark\n<accent>on-chain</accent> Se queda en Spark @@ -226,7 +225,6 @@ {amount} de financiación de comisiones sobrante no se pudo enviar y se queda en {address}, ruta de derivación {path}. Enviando {amount} de financiación de comisiones sobrante a tus ahorros. {amount} de financiación de comisiones sobrante se envió a tus ahorros. - ID de transacción: {txid} {amount} de cambio de comisiones llegará a tus ahorros cuando bajen las comisiones de la red. Un propietario anterior de estos fondos reclamó {amount} on-chain y no se puede recuperar. Salida de emergencia @@ -268,7 +266,6 @@ Publicando transacciones de salida Enviando a ahorros Esperando el bloqueo temporal - ID de transacción: {txid} Desliza para salir Las comisiones son mayores que lo que recibirías. Ahora mismo no se puede leer on-chain parte de esta salida. Bitkit lo vuelve a intentar durante hasta una semana. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index e8e0d5b10a..71400d19b4 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -150,7 +150,6 @@ Bitkit le divise en {count} parties, une pour chaque étape, afin qu\'une étape bloquée ne retarde pas les autres. La sortie paie ses frais avec un paiement on-chain séparé de <accent>{amount}</accent>. Ce qu\'elle ne dépense pas revient à l\'épargne à la fin. Financer les\n<accent>frais</accent> - ID de la transaction : {txid} N\'utilisez ceci que si Spark ne fonctionne plus pour vous. Cela transfère votre solde de dépenses vers l\'épargne <accent>sans les opérateurs Spark</accent>.\n\nCela prend <accent>jusqu\'à 4 semaines</accent>, coûte des frais on-chain payés depuis l\'épargne, et de très petits montants peuvent rester sur place. Cela s\'exécute en arrière-plan, et Bitkit vous prévient s\'il a besoin de vous. Quitter Spark\n<accent>on-chain</accent> Reste sur Spark @@ -160,7 +159,6 @@ {amount} de financement des frais restant n\'a pas pu être envoyé et reste à {address}, chemin de dérivation {path}. Envoi de {amount} de financement des frais restant vers l\'épargne. {amount} de financement des frais restant a été envoyé vers l\'épargne. - ID de la transaction : {txid} {amount} de monnaie des frais arrivera dans votre épargne quand les frais de réseau baisseront. {amount} a été réclamé on-chain par un ancien propriétaire de ces fonds et ne peut pas être récupéré. Sortie d\'urgence @@ -202,7 +200,6 @@ Publication des transactions de sortie Envoi vers l\'épargne En attente du timelock - ID de la transaction : {txid} Glisser pour sortir Les frais sont supérieurs à ce que vous recevriez. Une partie de cette sortie ne peut pas être lue on-chain pour le moment. Bitkit réessaie pendant une semaine au maximum. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 9393414546..a9d9c99e40 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -273,7 +273,6 @@ Bitkit lo divide in {count} parti, una per ogni passaggio, così un passaggio bloccato non ferma gli altri. L\'uscita paga le commissioni con un pagamento on-chain separato di <accent>{amount}</accent>. Quello che non spende torna ai risparmi alla fine. Finanzia le\n<accent>commissioni</accent> - ID Transazione: {txid} Usala solo se Spark smette di funzionare per te. Sposta il tuo saldo di spesa nei risparmi <accent>senza gli operatori Spark</accent>.\n\nRichiede <accent>fino a 4 settimane</accent>, costa commissioni on-chain pagate dai risparmi e importi molto piccoli possono restare indietro. Funziona in background e Bitkit ti avvisa se ha bisogno di te. Lascia Spark\n<accent>on-chain</accent> Resta su Spark @@ -283,7 +282,6 @@ {amount} di finanziamento delle commissioni rimanente non è stato inviato e resta su {address}, percorso di derivazione {path}. Invio di {amount} di finanziamento delle commissioni rimanente ai risparmi. {amount} di finanziamento delle commissioni rimanente è stato inviato ai risparmi. - ID Transazione: {txid} {amount} di resto delle commissioni arriverà nei tuoi risparmi quando le commissioni di rete scendono. {amount} è stato riscattato on-chain da un precedente proprietario di questi fondi e non può essere recuperato. Uscita di Emergenza @@ -325,7 +323,6 @@ Pubblicazione delle transazioni di uscita Invio ai risparmi In attesa del timelock - ID Transazione: {txid} Scorri per uscire Le commissioni sono più alte di quanto riceveresti. Al momento una parte di questa uscita non può essere letta on-chain. Bitkit riprova per un massimo di una settimana. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 96a1e726bd..4d709bfdf4 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -272,7 +272,6 @@ Bitkit splitst het in {count} delen, één voor elke stap, zodat één vastgelopen stap de andere niet ophoudt. De exit betaalt zijn kosten uit een aparte on-chain betaling van <accent>{amount}</accent>. Wat niet wordt uitgegeven, komt aan het einde terug naar spaargeld. Financier de\n<accent>kosten</accent> - Transactie-ID: {txid} Gebruik dit alleen als Spark niet meer voor je werkt. Het verplaatst je bestedingssaldo naar spaargeld <accent>zonder de Spark-beheerders</accent>.\n\nHet duurt <accent>tot 4 weken</accent>, kost on-chain kosten die uit spaargeld worden betaald, en zeer kleine bedragen kunnen achterblijven. Het loopt op de achtergrond en Bitkit laat het je weten als het je nodig heeft. Spark verlaten\n<accent>via on-chain</accent> Blijft op Spark @@ -282,7 +281,6 @@ {amount} aan overgebleven kostenfinanciering kon niet worden verstuurd en blijft op {address}, afleidingspad {path}. {amount} aan overgebleven kostenfinanciering wordt naar spaargeld gestuurd. {amount} aan overgebleven kostenfinanciering is naar spaargeld gestuurd. - Transactie-ID: {txid} {amount} aan wisselgeld van de kosten komt in je spaargeld aan wanneer de netwerkkosten dalen. {amount} is on-chain geclaimd door een eerdere eigenaar van dit geld en kan niet worden teruggehaald. Noodexit @@ -324,7 +322,6 @@ Exittransacties publiceren Naar spaargeld sturen Wachten op de tijdvergrendeling - Transactie-ID: {txid} Veeg om te verlaten De kosten zijn hoger dan wat je zou ontvangen. Een deel van deze exit kan nu niet on-chain worden gelezen. Bitkit probeert het tot een week lang opnieuw. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index d7e2e6f395..ff1550817a 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -152,7 +152,6 @@ Bitkit dzieli je na {count} części, po jednej na każdy krok, aby jeden zablokowany krok nie wstrzymywał pozostałych. Wyjście płaci swoje opłaty z osobnej płatności on-chain w wysokości <accent>{amount}</accent>. To, czego nie wyda, wraca na koniec do Oszczędności. Sfinansuj\n<accent>opłaty</accent> - ID transakcji: {txid} Używaj tego tylko wtedy, gdy Spark przestanie dla Ciebie działać. Przenosi saldo wydatków do Oszczędności <accent>bez operatorów Spark</accent>.\n\nTrwa <accent>do 4 tygodni</accent>, kosztuje opłaty on-chain pokrywane z Oszczędności, a bardzo małe kwoty mogą pozostać. Działa w tle, a Bitkit powiadomi Cię, jeśli będzie Cię potrzebować. Opuść Spark\n<accent>on-chain</accent> Pozostaje na Spark @@ -162,7 +161,6 @@ {amount} pozostałego finansowania opłat nie udało się wysłać i pozostaje pod adresem {address}, ścieżka derywacji {path}. Wysyłanie {amount} pozostałego finansowania opłat do Oszczędności. {amount} pozostałego finansowania opłat wysłano do Oszczędności. - ID transakcji: {txid} {amount} reszty z opłat trafi do Twoich Oszczędności, gdy opłaty sieciowe spadną. {amount} zostało przejęte on-chain przez wcześniejszego właściciela tych środków i nie można go odzyskać. Wyjście awaryjne @@ -204,7 +202,6 @@ Publikowanie transakcji wyjścia Wysyłanie do Oszczędności Oczekiwanie na blokadę czasową - ID transakcji: {txid} Przesuń, aby wyjść Opłaty są wyższe niż kwota, którą otrzymasz. Części tego wyjścia nie można teraz odczytać on-chain. Bitkit będzie próbować ponownie przez maksymalnie tydzień. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 75752de68e..e2fa1dd424 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -276,7 +276,6 @@ A Bitkit o divide em {count} partes, uma para cada etapa, para que uma etapa travada não segure as outras. A saída paga suas taxas com um pagamento on-chain separado de <accent>{amount}</accent>. O que ela não gastar volta para a poupança no final. Financiar as\n<accent>taxas</accent> - ID da transação: {txid} Use isso apenas se a Spark parar de funcionar para você. Isso move seu saldo de gastos para a poupança <accent>sem os operadores da Spark</accent>.\n\nLeva <accent>até 4 semanas</accent>, custa taxas on-chain pagas da poupança, e valores muito pequenos podem ficar para trás. Roda em segundo plano, e a Bitkit avisa você se precisar de você. Sair da Spark\n<accent>on-chain</accent> Fica na Spark @@ -286,7 +285,6 @@ {amount} de sobra do financiamento das taxas não pôde ser enviado e fica em {address}, caminho de derivação {path}. Enviando {amount} de sobra do financiamento das taxas para a poupança. {amount} de sobra do financiamento das taxas foi enviado para a poupança. - ID da transação: {txid} {amount} de troco das taxas chegará à sua poupança quando as taxas de rede caírem. {amount} foi reivindicado on-chain por um antigo dono desses fundos e não pode ser recuperado. Saída de Emergência @@ -328,7 +326,6 @@ Publicando as transações de saída Enviando para a poupança Aguardando o timelock - ID da transação: {txid} Deslize Para Sair As taxas são maiores do que o que você receberia. Parte desta saída não pode ser lida on-chain agora. A Bitkit tenta de novo por até uma semana. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 632615cb21..60702c143a 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -147,7 +147,6 @@ A Bitkit divide-o em {count} partes, uma para cada passo, para que um passo bloqueado não atrase os outros. A saída paga as suas taxas com um pagamento on-chain separado de <accent>{amount}</accent>. O que não gastar volta para a poupança no final. Financiar as\n<accent>taxas</accent> - ID da transação: {txid} Use isto apenas se a Spark deixar de funcionar para si. Move o seu saldo de gastos para a poupança <accent>sem os operadores da Spark</accent>.\n\nDemora <accent>até 4 semanas</accent>, custa taxas on-chain pagas da poupança, e montantes muito pequenos podem ficar para trás. Corre em segundo plano, e a Bitkit notifica-o se precisar de si. Sair da Spark\n<accent>on-chain</accent> Fica na Spark @@ -157,7 +156,6 @@ {amount} do financiamento das taxas restante não pôde ser enviado e fica em {address}, caminho de derivação {path}. A enviar {amount} do financiamento das taxas restante para a poupança. {amount} do financiamento das taxas restante foi enviado para a poupança. - ID da transação: {txid} {amount} de troco das taxas chegará à sua poupança quando as taxas de rede descerem. {amount} foi reclamado on-chain por um antigo proprietário destes fundos e não pode ser recuperado. Saída de Emergência @@ -199,7 +197,6 @@ A publicar as transações de saída A enviar para a poupança A aguardar o timelock - ID da transação: {txid} Deslizar Para Sair As taxas são mais altas do que o que receberia. Parte desta saída não pode ser lida on-chain neste momento. A Bitkit tenta novamente durante até uma semana. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 6554366ff8..74c86c066a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -284,7 +284,6 @@ Bitkit делит сумму на {count} частей, по одной на каждый шаг, чтобы застрявший шаг не задерживал остальные. Выход оплачивает свои комиссии отдельным ончейн-платежом на <accent>{amount}</accent>. Неизрасходованное в конце вернётся в сбережения. Оплатите\n<accent>комиссии</accent> - ID транзакции: {txid} Используйте это, только если Spark перестал у вас работать. Выход переводит ваш расходный баланс в сбережения <accent>без операторов Spark</accent>.\n\nОн занимает <accent>до 4 недель</accent>, требует ончейн-комиссий из сбережений, а очень маленькие суммы могут остаться в Spark. Выход работает в фоне, и Bitkit сообщит, если понадобится ваше участие. Выйти из Spark\n<accent>ончейн</accent> Остаётся в Spark @@ -294,7 +293,6 @@ Остаток средств на комиссии {amount} не удалось отправить, он остаётся на {address}, путь деривации {path}. Отправка остатка средств на комиссии {amount} в сбережения. Остаток средств на комиссии {amount} отправлен в сбережения. - ID транзакции: {txid} Сдача с комиссий {amount} поступит в сбережения, когда сетевые комиссии снизятся. {amount} забрал ончейн один из прежних владельцев этих средств, и вернуть их нельзя. Экстренный Выход @@ -336,7 +334,6 @@ Публикация транзакций выхода Отправка в сбережения Ожидание таймлока - ID транзакции: {txid} Проведите для выхода Комиссии больше, чем сумма, которую вы получите. Часть этого выхода сейчас не удаётся прочитать в блокчейне. Bitkit будет пробовать снова в течение недели. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 244d62fb48..19e9f4dd56 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -433,7 +433,6 @@ Bitkit splits it into {count} parts, one for each step, so one stuck step can\'t hold up the others. The exit pays its fees from a separate on-chain payment of <accent>{amount}</accent>. What it doesn\'t spend comes back to savings at the end. Fund the\n<accent>fees</accent> - Transaction ID: {txid} Use this only if Spark stops working for you. It moves your spending balance to savings <accent>without the Spark operators</accent>.\n\nIt takes <accent>up to 4 weeks</accent>, costs on-chain fees paid from savings, and very small amounts can stay behind. It runs in the background, and Bitkit notifies you if it needs you. Leave Spark\n<accent>on-chain</accent> Stays on Spark @@ -443,7 +442,6 @@ {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. {amount} of leftover fee funding was sent to savings. - Transaction ID: {txid} {amount} of fee change will reach your savings when network fees drop. {amount} was claimed on-chain by an older owner of these funds and can\'t be recovered. Emergency Exit @@ -485,7 +483,6 @@ Publishing exit transactions Sending to savings Waiting for the timelock - Transaction ID: {txid} Swipe To Exit The fees are higher than what you would receive. Part of this exit can\'t be read on-chain right now. Bitkit tries again for up to a week. From 9184723199b6eabaae9470f9b59326542650faf1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:38:15 +0100 Subject: [PATCH 071/154] fix: match the exit screens across apps --- .../bitkit/ui/settings/lightning/SparkExitComponents.kt | 6 +++--- .../ui/settings/lightning/SparkExitConfirmScreen.kt | 2 ++ .../ui/settings/lightning/SparkExitFeeBumpScreen.kt | 8 +++++--- .../ui/settings/lightning/SparkExitFundingScreen.kt | 8 +++++--- .../bitkit/ui/settings/lightning/SparkExitIntroScreen.kt | 2 ++ .../ui/settings/lightning/SparkExitProgressScreen.kt | 8 ++------ .../bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt | 2 ++ 7 files changed, 21 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt index de60217d06..7524342e6f 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -29,8 +29,8 @@ import to.bitkit.repositories.SparkExitQuote import to.bitkit.repositories.SparkExitRecord import to.bitkit.ui.appViewModel import to.bitkit.ui.components.BodyS +import to.bitkit.ui.components.Caption import to.bitkit.ui.components.CaptionB -import to.bitkit.ui.components.CaptionM import to.bitkit.ui.components.MoneyCaptionB import to.bitkit.ui.components.QrCodeImage import to.bitkit.ui.components.rememberMoneyText @@ -138,8 +138,8 @@ internal fun SparkExitFundingAddress( ) } if (isCovered) { - CaptionM( - text = stringResource(R.string.lightning__spark_exit__fund_seen).withAccent(), + Caption( + text = stringResource(R.string.lightning__spark_exit__fund_seen), color = Colors.Green, modifier = Modifier.fillMaxWidth() ) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt index a70e45cc0d..11ecbbf9bd 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt @@ -19,6 +19,7 @@ import to.bitkit.ui.components.Display import to.bitkit.ui.components.SwipeToConfirm import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.DrawerNavIcon import to.bitkit.ui.scaffold.ScreenColumn import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors @@ -59,6 +60,7 @@ private fun Content( AppTopBar( titleText = stringResource(R.string.lightning__spark_exit__nav_title), onBackClick = onBack, + actions = { DrawerNavIcon() }, ) Column( modifier = Modifier diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt index 23a29118e7..4509913008 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt @@ -22,11 +22,12 @@ import to.bitkit.R import to.bitkit.models.FeeRate import to.bitkit.repositories.SparkExitFeeBumpOption import to.bitkit.ui.components.BodyM -import to.bitkit.ui.components.CaptionM +import to.bitkit.ui.components.Caption import to.bitkit.ui.components.Display import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.DrawerNavIcon import to.bitkit.ui.scaffold.ScreenColumn import to.bitkit.ui.screens.wallets.send.FeeItem import to.bitkit.ui.theme.AppThemeSurface @@ -72,6 +73,7 @@ private fun Content( AppTopBar( titleText = stringResource(R.string.lightning__spark_exit__nav_title), onBackClick = onBack, + actions = { DrawerNavIcon() }, ) Column( modifier = Modifier @@ -132,8 +134,8 @@ private fun Content( } Column(modifier = Modifier.padding(horizontal = 16.dp)) { if (bump.isSavingsShort) { - CaptionM( - text = stringResource(R.string.lightning__spark_exit__fund_insufficient).withAccent(), + Caption( + text = stringResource(R.string.lightning__spark_exit__fund_insufficient), color = Colors.White64, modifier = Modifier.testTag("SparkExitFeeBumpInsufficient") ) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt index fd79bec998..e9973fa101 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt @@ -18,12 +18,13 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import to.bitkit.R import to.bitkit.ui.components.BodyM import to.bitkit.ui.components.BodyS -import to.bitkit.ui.components.CaptionM +import to.bitkit.ui.components.Caption import to.bitkit.ui.components.Display import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.DrawerNavIcon import to.bitkit.ui.scaffold.ScreenColumn import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors @@ -68,6 +69,7 @@ private fun Content( AppTopBar( titleText = stringResource(R.string.lightning__spark_exit__nav_title), onBackClick = onBack, + actions = { DrawerNavIcon() }, ) Column( modifier = Modifier @@ -118,8 +120,8 @@ private fun Content( } else { val isPricing = uiState.savingsFeeSats == null && !uiState.hasSavingsFeeFailed if (!isPricing && !uiState.canFundFromSavings) { - CaptionM( - text = stringResource(R.string.lightning__spark_exit__fund_insufficient).withAccent(), + Caption( + text = stringResource(R.string.lightning__spark_exit__fund_insufficient), color = Colors.White64, ) VerticalSpacer(16.dp) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt index 11078db7f2..1e10a7141c 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt @@ -28,6 +28,7 @@ import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.DrawerNavIcon import to.bitkit.ui.scaffold.ScreenColumn import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors @@ -44,6 +45,7 @@ fun SparkExitIntroScreen( AppTopBar( titleText = stringResource(R.string.lightning__spark_exit__nav_title), onBackClick = onBack, + actions = { DrawerNavIcon() }, ) BoxWithConstraints( modifier = Modifier diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 8f6d4989b6..b15fe1211e 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -36,6 +36,7 @@ import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.openNotificationSettings import to.bitkit.ui.scaffold.AppAlertDialog import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.DrawerNavIcon import to.bitkit.ui.scaffold.ScreenColumn import to.bitkit.ui.shared.modifiers.clickableAlpha import to.bitkit.ui.theme.AppThemeSurface @@ -92,6 +93,7 @@ private fun Content( AppTopBar( titleText = stringResource(R.string.lightning__spark_exit__nav_title), onBackClick = onBack, + actions = { DrawerNavIcon() }, ) PullToRefreshBox( isRefreshing = uiState.isRefreshing, @@ -336,12 +338,6 @@ private fun LeftoverNote(record: SparkExitRecord, address: String, path: String? .replace("{path}", path.orEmpty()).withAccentBoldBright(), color = Colors.White64, ) - sweep?.txid != null && sweep.isAccepted -> SparkExitTxNote( - text = stringResource(R.string.lightning__spark_exit__leftover_swept) - .replace("{amount}", sparkExitAmountAccent(sweep.valueSats)), - txid = sweep.txid, - testTag = "SparkExitLeftoverSwept", - ) sweep?.txid != null && sweep.rejection == null -> SparkExitTxNote( text = stringResource(R.string.lightning__spark_exit__leftover_sending) .replace("{amount}", sparkExitAmountAccent(sweep.valueSats)), diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt index 2060d4286c..25f4d43d5f 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt @@ -21,6 +21,7 @@ import to.bitkit.ui.components.Display import to.bitkit.ui.components.PrimaryButton import to.bitkit.ui.components.VerticalSpacer import to.bitkit.ui.scaffold.AppTopBar +import to.bitkit.ui.scaffold.DrawerNavIcon import to.bitkit.ui.scaffold.ScreenColumn import to.bitkit.ui.theme.AppThemeSurface import to.bitkit.ui.theme.Colors @@ -50,6 +51,7 @@ private fun Content( AppTopBar( titleText = stringResource(R.string.lightning__spark_exit__nav_title), onBackClick = onBack, + actions = { DrawerNavIcon() }, ) Column( modifier = Modifier From 6cd48b76c1c2ec12b24468f51f941fee300ee9cd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:44:32 +0100 Subject: [PATCH 072/154] fix: show a leftover sweep's txid once it is accepted --- .../ui/settings/lightning/SparkExitProgressScreen.kt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index b15fe1211e..00d1e67a16 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -338,12 +338,18 @@ private fun LeftoverNote(record: SparkExitRecord, address: String, path: String? .replace("{path}", path.orEmpty()).withAccentBoldBright(), color = Colors.White64, ) - sweep?.txid != null && sweep.rejection == null -> SparkExitTxNote( + // Its txid shows once the network accepted the sweep, as it may never go out before that. + sweep?.txid != null && sweep.isAccepted -> SparkExitTxNote( text = stringResource(R.string.lightning__spark_exit__leftover_sending) .replace("{amount}", sparkExitAmountAccent(sweep.valueSats)), txid = sweep.txid, testTag = "SparkExitLeftoverSending", ) + sweep?.txid != null && sweep.rejection == null -> BodyS( + text = stringResource(R.string.lightning__spark_exit__leftover_sending) + .replace("{amount}", sparkExitAmountAccent(sweep.valueSats)).withAccentBoldBright(), + color = Colors.White64, + ) // Refused for good: where the leftover stays, with the path a wallet needs to find it. sweep?.rejection != null && path != null -> BodyS( text = stringResource(R.string.lightning__spark_exit__leftover_rejected) From 0823f51d37b6b3fc85845dd8340f71ce67d6d9ea Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 12:57:40 +0100 Subject: [PATCH 073/154] fix: exit progress ok returns to the screen that opened it --- app/src/main/java/to/bitkit/ui/ContentView.kt | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index c88a801a38..509107a6f1 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -2078,12 +2078,9 @@ private fun NavGraphBuilder.sparkExit(navController: NavHostController) { val parentEntry = remember(entry) { navController.getBackStackEntry(Routes.ConnectionsNav) } return hiltViewModel(parentEntry) } - // Back to Spark, or to the screen that opened progress directly, such as App Status. Once progress is gone, - // a second call pops nothing. - val leaveExit = { - navController.popBackStack(inclusive = false) || - navController.popBackStack(inclusive = true) - } + // Progress always sits right above the screen it returns to: Spark, which starting an exit pops back to first, + // or the screen that opened it directly, such as App Status. Once progress is gone, a second call pops nothing. + val leaveExit = { navController.popBackStack(inclusive = true) } composableWithDefaultTransitions { SparkExitIntroScreen( onBack = { navController.popBackStack() }, @@ -2111,7 +2108,7 @@ private fun NavGraphBuilder.sparkExit(navController: NavHostController) { viewModel = exitViewModel(it), onBack = { navController.popBackStack() }, onStart = { - leaveExit() + navController.popBackStack(inclusive = false) navController.navigateTo(Routes.SparkExitProgress) }, ) From 14ae952bfe710d871be475b9afb9c10660d7e240 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:09:01 +0100 Subject: [PATCH 074/154] fix: savings-paid exit row reads in progress after cold start --- .../ui/settings/appStatus/AppStatusViewModel.kt | 5 ++++- .../appStatus/AppStatusViewModelTest.kt | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt index 398ef8bb15..81f8840de3 100644 --- a/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusViewModel.kt @@ -95,7 +95,10 @@ enum class ExitStep { FUNDING, RUNNING } /** Asks for fee funding only while no payment covers it, as the progress screen does. */ internal fun SparkExitRecord?.exitStep(funding: SparkExitFundingState? = null): ExitStep? { val record = this?.takeIf { it.isActive } ?: return null + // Before the first tick reads the funding, a savings payment the exit has not adopted yet counts as paid, + // as on iOS. + val isPaymentPending = record.fundingPaymentTxid?.let { txid -> record.funding.none { it.txid == txid } } == true val isAskingFunding = record.fundingShortfallSats != null && - (funding == null || funding is SparkExitFundingState.Ask) + if (funding == null) !isPaymentPending else funding is SparkExitFundingState.Ask return if (isAskingFunding) ExitStep.FUNDING else ExitStep.RUNNING } diff --git a/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt index 86e885beb3..05f5ff6d5b 100644 --- a/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt @@ -211,6 +211,19 @@ class AppStatusViewModelTest : BaseUnitTest() { assertEquals(ExitStep.RUNNING, exitRecord(SparkExitRecord.Phase.NeedsFunding(1_000uL)).exitStep()) } + @Test + fun `exit step is running for a savings payment before the first funding read`() { + val paid = exitRecord(SparkExitRecord.Phase.AwaitingFunding(1_000uL), 1_000uL, paymentTxid = "txid") + assertEquals(ExitStep.RUNNING, paid.exitStep()) + val adopted = exitRecord( + SparkExitRecord.Phase.AwaitingFunding(1_000uL), + 1_000uL, + paymentTxid = "txid", + funding = listOf(SparkExitRecord.Funding(0u, "address", "pubkey", txid = "txid")), + ) + assertEquals(ExitStep.FUNDING, adopted.exitStep()) + } + @Test fun `ui state shows the step of a running exit`() = test { val record = exitRecord(SparkExitRecord.Phase.Running) @@ -228,9 +241,13 @@ class AppStatusViewModelTest : BaseUnitTest() { phase: SparkExitRecord.Phase, shortfallSats: ULong? = null, isActive: Boolean = true, + paymentTxid: String? = null, + funding: List = emptyList(), ) = mock { on { this.phase } doReturn phase on { this.isActive } doReturn isActive on { fundingShortfallSats } doReturn shortfallSats + on { fundingPaymentTxid } doReturn paymentTxid + on { this.funding } doReturn funding } } From e47f7ad147c4700e04bf698ecc18d1e0c540baf2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 13:25:52 +0100 Subject: [PATCH 075/154] fix: match exit spacing and dialogs across apps --- .../to/bitkit/ui/settings/lightning/SparkExitComponents.kt | 6 ++++++ .../bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt | 1 - .../bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt | 1 - .../bitkit/ui/settings/lightning/SparkExitFundingScreen.kt | 1 - .../to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt | 1 - .../bitkit/ui/settings/lightning/SparkExitProgressScreen.kt | 6 ++++-- .../to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt | 2 +- 7 files changed, 11 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt index 7524342e6f..bf7eeff1e2 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -48,6 +48,12 @@ import to.bitkit.viewmodels.AppViewModel internal fun sparkExitAmountText(sats: ULong): String = rememberMoneyText(sats.toLong(), showSymbol = true)?.replace(Regex(""), "") ?: sats.toString() +/** + * What Display's line height adds under a headline on Android against iOS: master's spacers under an exit headline + * render 9 dp more here, so exit screens take it off and look the same on both apps. Measured on 2x media devices. + */ +internal val SparkExitDisplayExtra = 9.dp + /** The amount marked as an inline accent, for a line drawn with [withAccentBoldBright] or [withAccentBoldRed]. */ @Composable internal fun sparkExitAmountAccent(sats: ULong): String = "${sparkExitAmountText(sats)}" diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt index 11ecbbf9bd..36cca7041d 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt @@ -70,7 +70,6 @@ private fun Content( ) { VerticalSpacer(32.dp) Display(text = stringResource(R.string.lightning__spark_exit__confirm_title).withAccent()) - VerticalSpacer(8.dp) BodyM( text = stringResource(R.string.lightning__spark_exit__confirm_text).withAccentBoldBright(), color = Colors.White64, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt index 4509913008..3fdd6265d1 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt @@ -83,7 +83,6 @@ private fun Content( Column(modifier = Modifier.padding(horizontal = 16.dp)) { VerticalSpacer(32.dp) Display(text = stringResource(R.string.lightning__spark_exit__fee_bump_title).withAccent()) - VerticalSpacer(8.dp) BodyM( text = stringResource(R.string.lightning__spark_exit__fee_bump_text) .replace("{rate}", "${uiState.record?.feeRateSatPerVbyte ?: 0uL}") diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt index e9973fa101..7899b46242 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt @@ -79,7 +79,6 @@ private fun Content( ) { VerticalSpacer(32.dp) Display(text = stringResource(R.string.lightning__spark_exit__funding_title).withAccent()) - VerticalSpacer(8.dp) BodyM( text = stringResource(R.string.lightning__spark_exit__funding_text) .replace("{amount}", sparkExitAmountText(fundingSats)) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt index 1e10a7141c..c3e000fa8d 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt @@ -65,7 +65,6 @@ fun SparkExitIntroScreen( text = stringResource(R.string.lightning__spark_exit__intro_title).withAccent(), modifier = Modifier.fillMaxWidth() ) - VerticalSpacer(8.dp) BodyM( text = stringResource(R.string.lightning__spark_exit__intro_text).withAccentBoldBright(), color = Colors.White64, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 00d1e67a16..5d00ee3e09 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -109,7 +109,6 @@ private fun Content( ) { VerticalSpacer(32.dp) Display(text = progressTitle(record?.phase, uiState.progressFunding).withAccent()) - VerticalSpacer(8.dp) BodyM( text = progressText( record = record, @@ -164,6 +163,8 @@ private fun Content( title = stringResource(R.string.lightning__spark_exit__cancel_title), text = stringResource(R.string.lightning__spark_exit__cancel_text), confirmText = stringResource(R.string.lightning__spark_exit__cancel), + dismissText = stringResource(R.string.common__cancel), + confirmTextColor = Colors.Red, onConfirm = { isConfirming = false onCancel() @@ -189,7 +190,8 @@ private fun Content( private fun ProgressDetails(record: SparkExitRecord, uiState: SparkExitUiState, onPayHigherFee: () -> Unit) { SparkExitSteps(record = record, tipHeight = uiState.tipHeight) uiState.sweepTxid?.let { - VerticalSpacer(24.dp) + // With the cell's own 16 dp above its caption it sits as far below the steps as on iOS. + VerticalSpacer(9.dp) SparkExitTxNote( text = null, txid = it, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt index 25f4d43d5f..38ceaa8bfe 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt @@ -61,7 +61,7 @@ private fun Content( ) { VerticalSpacer(32.dp) Display(text = stringResource(R.string.lightning__spark_exit__quote_title).withAccent()) - VerticalSpacer(32.dp) + VerticalSpacer(32.dp - SparkExitDisplayExtra) when { uiState.quote != null -> { SparkExitQuoteRows(uiState.quote) From cdbe3674c9df3d97a1e037f147f62147f38d23df Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 16:20:01 +0100 Subject: [PATCH 076/154] fix: keep the kept spark balance out of an exit --- .../java/to/bitkit/repositories/SparkRepo.kt | 9 +++++---- .../LightningConnectionsViewModel.kt | 6 +++++- .../to/bitkit/repositories/SparkRepoTest.kt | 20 +++++++++++++++++++ 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index f5daee829f..6709d30b4e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -256,7 +256,7 @@ class SparkRepo @Inject constructor( suspend fun setExiting(isExiting: Boolean, reconnect: Boolean = false): Result = withContext(bgDispatcher) { val isCurrent = _state.value.isExiting == isExiting && sparkService.isConnected if (isCurrent && !reconnect) return@withContext Result.success(Unit) - _state.update { it.copy(isExiting = isExiting) } + _state.update { it.copy(isExiting = isExiting, keptBalanceSats = it.keptBalanceSats.takeUnless { isExiting }) } runSuspendCatching { onOptimizationCutShort() sparkService.disconnect() @@ -268,10 +268,10 @@ class SparkRepo @Inject constructor( } /** - * Holds Spark for an exit about to start: no sends, receives or spending balance, in the same step the exit's + * Holds Spark for an exit about to start: no sends, receives, spending or kept balance, in the same step the exit's * transfer starts counting it. [setExiting] reconnects it for the exit afterwards. */ - fun holdForExit() = _state.update { it.copy(isExiting = true) } + fun holdForExit() = _state.update { it.copy(isExiting = true, keptBalanceSats = null) } /** Releases the hold of an exit whose start failed before anything was saved: Spark was never disconnected. */ fun releaseExitHold() = _state.update { it.copy(isExiting = false) } @@ -777,8 +777,9 @@ class SparkRepo @Inject constructor( it.copy( isReady = true, balanceSats = info.balanceSats, + // An exit moves the balance to savings, so a zero read during one keeps nothing. keptBalanceSats = it.shownBalanceSats.takeIf { kept -> - info.balanceSats == 0uL && isStale && kept > 0uL + info.balanceSats == 0uL && isStale && kept > 0uL && !it.isExiting }, pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, deposits = (pending + claimed).toImmutableList(), diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt index ced798eea2..97ca2d960d 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt @@ -240,7 +240,10 @@ data class LightningConnectionsUiState( /** The Spark wallet shown as a connection, present once it holds a balance or a deposit. */ data class SparkUi( + /** The balance shown, which can be a kept figure while Spark reads 0. */ val balanceSats: ULong, + /** What Spark read, which an emergency exit moves. */ + val readBalanceSats: ULong = balanceSats, val deposits: ImmutableList = persistentListOf(), val withdrawals: ImmutableList = persistentListOf(), val recoverableFundsSats: ULong = 0uL, @@ -249,7 +252,7 @@ data class SparkUi( val showsExitResult: Boolean = false, ) { /** The emergency exit is offered while Spark holds funds, and leads to its progress while it shows one. */ - val showsExit get() = balanceSats > 0uL || recoverableFundsSats > 0uL || showsExitResult + val showsExit get() = readBalanceSats > 0uL || recoverableFundsSats > 0uL || showsExitResult val pendingDeposits get() = deposits.filterNot { it.deposit.isClaimed } val claimedDeposits get() = deposits.filter { it.deposit.isClaimed } @@ -270,6 +273,7 @@ internal suspend fun SparkState.toUi(lightningRepo: LightningRepo, showsExitResu if (shownBalanceSats == 0uL && deposits.isEmpty() && !hasExit && Env.network != Network.REGTEST) return null return SparkUi( balanceSats = shownBalanceSats, + readBalanceSats = balanceSats, deposits = deposits.map { SparkDepositUi(it, if (it.isClaimed) null else lightningRepo.onchainConfirmations(it.txid)) }.toImmutableList(), diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 0f07b32775..030e0cec0c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -927,6 +927,26 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(0uL, sut.state.value.shownBalanceSats) } + @Test + fun `an emergency exit drops the kept balance so spending does not count it again after the exit`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) + val sut = createSut() + sut.refreshState().getOrThrow() + val syncFailed = info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + whenever { sparkService.getInfo() }.thenReturn(syncFailed) + sut.refreshState().getOrThrow() + assertEquals(10_000uL, sut.state.value.shownBalanceSats) + + sut.setExiting(true).getOrThrow() + assertEquals(0uL, sut.state.value.shownBalanceSats, "the exit kept the balance it moves to savings") + sut.refreshState().getOrThrow() + assertEquals(0uL, sut.state.value.shownBalanceSats, "a zero read during the exit kept a balance") + + sut.setExiting(false).getOrThrow() + assertEquals(0uL, sut.state.value.shownSpendingSats, "spending counted the exited balance again") + } + @Test fun `a deposit claimed early is listed only as claimed`() = test { whenever(sparkService.isConnected).thenReturn(true) From 42adfd7d8126b073f2c4bb17d7d0e138cd4d6496 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 16:28:40 +0100 Subject: [PATCH 077/154] test: match the exit funding stubs to the approved fee parameter --- .../test/java/to/bitkit/repositories/SparkExitRepoTest.kt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index f356a6c008..fb72c76cef 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -814,6 +814,7 @@ class SparkExitRepoTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) verify(sparkRepo, never()).setExiting(true, true) } @@ -920,6 +921,7 @@ class SparkExitRepoTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -941,6 +943,7 @@ class SparkExitRepoTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } @@ -1082,6 +1085,7 @@ class SparkExitRepoTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) assertEquals("again", assertNotNull(store.load()).fundingPaymentTxid) assertFalse(sut.state.value.isSavingsPaymentRefused) @@ -1166,6 +1170,7 @@ class SparkExitRepoTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) }.doSuspendableAnswer { answer() } whenever(lightning.completeAcceptedOrdinaryFollowup(any())).thenReturn(Unit) @@ -1318,6 +1323,7 @@ class SparkExitRepoTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), ) } From 17e525e1ec009d7e171985a77d8d7b1520e9e497 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:00:42 +0100 Subject: [PATCH 078/154] fix: ask again for saved exit confirmations after a reorg --- .../to/bitkit/repositories/SparkExitDriver.kt | 49 +++++++++++++--- .../repositories/SparkExitDriverTest.kt | 58 +++++++++++++++++++ .../bitkit/repositories/SparkExitFixtures.kt | 9 ++- 3 files changed, 106 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index c882749e51..ad2d913ca2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -1055,19 +1055,30 @@ class SparkExitDriver( private suspend fun broadcastWithoutSdk(record: SparkExitRecord): SparkExitRecord { val recovery = record.recovery ?: return record val tip = chain.tipHeight() - val statuses = recovery.transactions + // A saved confirmation is asked again, since a reorg can undo it; it stands only while no host answers. + val saved = recovery.transactions .mapNotNull { tx -> (tx.status as? ExitTransactionStatus.Confirmed)?.let { tx.txid to it.blockHeight } } .associate { (txid, height) -> txid to EsploraTxStatus(true, height) } - .toMutableMap() + val statuses = mutableMapOf() suspend fun status(txid: String): EsploraTxStatus? { - if (txid !in statuses) statuses[txid] = runSuspendCatching { chain.txStatus(txid) }.getOrNull() + if (txid !in statuses) { + statuses[txid] = runSuspendCatching { chain.txStatus(txid) }.getOrNull() ?: saved[txid] + } return statuses[txid] } - var current = record - val transactions = recovery.transactions.map { tx -> - if (tx.status is ExitTransactionStatus.Confirmed) return@map tx - val own = status(tx.txid) - if (own?.confirmed == true) return@map tx.copy(status = ExitTransactionStatus.Confirmed(own.blockHeight)) + val reorged = saved.keys.filter { status(it)?.confirmed == false }.toSet() + var current = if (reorged.isEmpty()) record else withReorgUndone(record, recovery, reorged) + val transactions = recovery.transactions.map { saved -> + val own = status(saved.txid) + if (own?.confirmed == true) { + val height = own.blockHeight ?: (saved.status as? ExitTransactionStatus.Confirmed)?.blockHeight + return@map saved.copy(status = ExitTransactionStatus.Confirmed(height)) + } + val tx = if (saved.txid in reorged) { + saved.copy(status = ExitTransactionStatus.WaitingForDependencies) + } else { + saved + } if (!tx.dependsOn.all { status(it)?.confirmed == true }) return@map tx // A height the SDK already worked out still holds. val known = (tx.status as? ExitTransactionStatus.WaitingForTimelock)?.spendableAtHeight @@ -1141,6 +1152,28 @@ class SparkExitDriver( ) } + private fun withReorgUndone( + record: SparkExitRecord, + recovery: RecoverFundsResponse, + reorged: Set, + ): SparkExitRecord { + Logger.warn("Asking again after a reorg undid Spark exit steps '$reorged'", context = TAG) + // What was concluded from those confirmations, a spent input or a failed fee chain, no longer holds. + val undone = reorged.toMutableSet() + while (true) { + val added = recovery.transactions + .filter { it.txid !in undone && it.dependsOn.any { parent -> parent in undone } } + .map { it.txid } + if (added.isEmpty()) break + undone += added + } + val log = record.broadcastLog.map { + if (it.generation != record.generation || it.txid !in undone) return@map it + it.copy(isInputSpent = false, feeChainFailures = 0) + } + return record.copy(broadcastLog = log) + } + private suspend fun parentHeight(txid: String, known: EsploraTxStatus?): UInt? { if (known?.confirmed != true) return null return known.blockHeight ?: runSuspendCatching { chain.txStatus(txid) }.getOrNull()?.blockHeight diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index c4c9e9c10a..52d57d5cda 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -355,6 +355,7 @@ class SparkExitDriverTest : BaseUnitTest() { SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), ), ) + chain.confirmedTxids = setOf("n1") driver(withSdk = false).tick(running(recovery)) @@ -1512,6 +1513,63 @@ class SparkExitDriverTest : BaseUnitTest() { assertNull(record.surfacedRejection) } + private fun reorgedParentRecovery() = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx( + "r1", + kind = RecoveryTxKind.REFUND, + dependsOn = listOf("n1"), + status = ExitTransactionStatus.WaitingForDependencies, + ), + ), + ) + + @Test + fun `without the sdk a saved confirmation a reorg undid is asked again before its child goes out`() = test { + var record = running(reorgedParentRecovery()) + chain.outcome = SparkExitBroadcastOutcome.InputsMissing("bad-txns-inputs-missingorspent") + + record = driver(withSdk = false).tick(record) + + assertTrue(chain.broadcasts.none { it.txid == "r1" }) + val parent = record.recovery?.transactions?.first { it.txid == "n1" } + assertFalse(parent?.status is ExitTransactionStatus.Confirmed) + assertTrue(record.broadcastLog.none { it.txid == "r1" && it.isInputSpent }) + + // Confirmed again: its child goes out. + chain.confirmedTxids = setOf("n1") + chain.outcome = SparkExitBroadcastOutcome.Accepted + now += SparkExitDriver.REBROADCAST_INTERVAL.inWholeMilliseconds + record = driver(withSdk = false).tick(record) + + assertEquals(listOf("r1"), chain.broadcasts.map { it.txid }.filter { it == "r1" }) + } + + @Test + fun `without the sdk a reorg clears the spent input its child was refused for`() = test { + val spent = SparkExitRecord.BroadcastAttempt(1, "r1", 1, 0, now, "inputs missing", false, isInputSpent = true) + var record = running(reorgedParentRecovery()).copy(broadcastLog = listOf(spent)) + + record = driver(withSdk = false).tick(record) + assertFalse(record.broadcastLog.single { it.txid == "r1" }.isInputSpent) + + chain.confirmedTxids = setOf("n1") + record = driver(withSdk = false).tick(record) + + assertEquals(listOf("r1"), chain.broadcasts.map { it.txid }.filter { it == "r1" }) + } + + @Test + fun `without the sdk a saved confirmation stays while no host answers`() = test { + chain.statusErrorTxids = setOf("n1") + + val record = driver(withSdk = false).tick(running(reorgedParentRecovery())) + + assertEquals(ExitTransactionStatus.Confirmed(900u), record.recovery?.transactions?.first()?.status) + assertEquals(listOf("r1"), chain.broadcasts.map { it.txid }) + } + /** The qa-03 run: an older state's refund took the leaf, and every Redo rebuilt the same spent refund. */ private fun lostLeafRecovery(leafId: String = "leaf-1") = SparkExitFixtures.recovery( listOf( diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt index 743bfd1592..465b335255 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -155,8 +155,13 @@ class FakeSparkExitChain : SparkExitChain { return utxosByAddress[address].orEmpty() } - override suspend fun txStatus(txid: String) = - EsploraTxStatus(txid in confirmedTxids, if (txid in confirmedTxids) heights[txid] ?: 900u else null) + /** Txids whose status no host answers for. */ + var statusErrorTxids = setOf() + + override suspend fun txStatus(txid: String): EsploraTxStatus { + if (txid in statusErrorTxids) throw SparkExitChainError("No host answered for '$txid'") + return EsploraTxStatus(txid in confirmedTxids, if (txid in confirmedTxids) heights[txid] ?: 900u else null) + } override suspend fun isTxKnown(txid: String): Boolean { knownLookups += txid From 48f072308fa26febc6451c21aff22cc0296ff905 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:00:56 +0100 Subject: [PATCH 079/154] fix: cap exit funding sends at the confirmed mining fee --- .../to/bitkit/repositories/SparkExitRepo.kt | 33 +++++++++++++++---- .../settings/lightning/SparkExitViewModel.kt | 15 ++++++++- .../bitkit/repositories/SparkExitRepoTest.kt | 6 ++-- .../lightning/SparkExitViewModelTest.kt | 22 +++++++++++++ 4 files changed, 67 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index e42a145ef7..a9f50b77e3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -575,7 +575,11 @@ class SparkExitRepo @Inject constructor( private suspend fun payHigherFeeLocked(option: SparkExitFeeBumpOption) { val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } - val txid = if (option.extraSats > 0uL) sendFunding(address, option.extraSats, option.feeRates) else null + val txid = if (option.extraSats > 0uL) { + sendFunding(address, option.extraSats, option.feeRates, option.totalSats.safe() - option.extraSats.safe()) + } else { + null + } tickMutex.withLock { val current = _state.value.record ?: return@withLock if (current.isRebuilding && current.isActive) { @@ -644,7 +648,7 @@ class SparkExitRepo @Inject constructor( feeRates = feeRates, allowFallback = false, ).getOrThrow() - _state.update { it.copy(pending = it.pending?.copy(savingsFeeRates = feeRates)) } + _state.update { it.copy(pending = it.pending?.copy(savingsFeeRates = feeRates, savingsFeeSats = feeSats)) } val spendable = lightningRepo.getBalancesAsync().getOrThrow().spendableOnchainBalanceSats SparkExitSavingsFunding( feeSats = feeSats, @@ -754,7 +758,9 @@ class SparkExitRepo @Inject constructor( // Savings pays at most what the user confirmed: Progress asks for the rest of a higher fresh amount. val savingsSats = minOf(quote.fundingSats, pending.quote.fundingSats) if (fundFromSavings && savingsSats > 0uL) { - runSuspendCatching { payFunding(createdAt, key.address, savingsSats, pending.savingsFeeRates) } + runSuspendCatching { + payFunding(createdAt, key.address, savingsSats, pending.savingsFeeRates, pending.savingsFeeSats) + } // A refused payment shows on progress at once, with the offer to pay again. .onFailure { _state.value.record?.let { current -> noteSavingsSend(current) } } .getOrThrow() @@ -804,7 +810,13 @@ class SparkExitRepo @Inject constructor( return fresh.copy(sparkBalanceSats = sparkRepo.state.value.balanceSats) } - private suspend fun payFunding(createdAt: Long, address: String, sats: ULong, feeRates: FeeRates?) { + private suspend fun payFunding( + createdAt: Long, + address: String, + sats: ULong, + feeRates: FeeRates?, + approvedFeeSats: ULong?, + ) { // Under the tick lock from the check to the saved txid: a cancel either ends the exit before anything is paid // or finds the payment and refuses. After the tick in flight, so its save cannot drop the txid. tickMutex.withLock { @@ -812,7 +824,7 @@ class SparkExitRepo @Inject constructor( Logger.info("Spark exit ended before savings paid its funding; nothing is paid", context = TAG) return@withLock } - val txid = sendFunding(address, sats, feeRates) + val txid = sendFunding(address, sats, feeRates, approvedFeeSats) val record = _state.value.record ?: return@withLock val paid = record.copy(fundingPaymentTxid = txid) saveRecord(paid) @@ -879,12 +891,19 @@ class SparkExitRepo @Inject constructor( } } - private suspend fun sendFunding(address: String, sats: ULong, feeRates: FeeRates? = null): String { + /** Savings never pays more fee than [approvedFeeSats], the one confirmed: a higher one asks again. */ + private suspend fun sendFunding( + address: String, + sats: ULong, + feeRates: FeeRates?, + approvedFeeSats: ULong?, + ): String { val outcome = lightningRepo.sendOnChain( address = address, sats = sats, speed = TransactionSpeed.Fast, feeRates = feeRates, + approvedMiningFeeSats = approvedFeeSats, ).getOrThrow() return fundingTxid(outcome, sats) } @@ -1029,6 +1048,8 @@ data class SparkExitPending( val fundingIndex: UInt, /** The rates the fee of paying the funding from savings was priced at, which that payment sends at. */ val savingsFeeRates: FeeRates? = null, + /** The fee of paying the funding from savings the user confirmed, which that payment never exceeds. */ + val savingsFeeSats: ULong? = null, ) data class SparkExitSavingsFunding( diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index e9a8519661..b77c1a7bca 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -25,6 +25,7 @@ import to.bitkit.env.Env import to.bitkit.models.FeeRate import to.bitkit.models.Toast import to.bitkit.models.safe +import to.bitkit.repositories.OnchainSendChangedError import to.bitkit.repositories.SparkExitBackgroundLimits import to.bitkit.repositories.SparkExitCancel import to.bitkit.repositories.SparkExitCancelUnreadable @@ -213,7 +214,19 @@ class SparkExitViewModel @Inject constructor( _uiState.update { it.copy(feeBump = it.feeBump.copy(isPaying = true)) } sparkExitRepo.payHigherFee(option) .onSuccess { _effects.emit(SparkExitEffect.FeeBumped) } - .onFailure { ToastEventBus.send(it) } + .onFailure { + // Savings never pays more than the fee confirmed: the rates are priced again for another confirm. + if (it.cause is OnchainSendChangedError) { + ToastEventBus.send( + type = Toast.ToastType.INFO, + title = context.getString(R.string.lightning__spending_confirm__fees_changed_title), + ) + _uiState.update { state -> state.copy(feeBump = state.feeBump.copy(isPaying = false)) } + loadFeeBump() + return@launch + } + ToastEventBus.send(it) + } _uiState.update { it.copy(feeBump = it.feeBump.copy(isPaying = false)) } } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index fb72c76cef..d0561d6f3c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -921,7 +921,8 @@ class SparkExitRepoTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), - approvedMiningFeeSats = anyOrNull(), + // Savings never pays more fee than the one confirmed. + approvedMiningFeeSats = eq(300uL), ) } @@ -1323,7 +1324,8 @@ class SparkExitRepoTest : BaseUnitTest() { any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), paymentDeadlineAt = anyOrNull(), contactPublicKey = anyOrNull(), - approvedMiningFeeSats = anyOrNull(), + // The total shown less the extra funding. + approvedMiningFeeSats = eq(400uL), ) } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 9e8a255f82..739683858c 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -4,10 +4,15 @@ import android.content.Context import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.flow.MutableStateFlow import org.junit.Test +import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock +import org.mockito.kotlin.times +import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.models.FeeRate +import to.bitkit.repositories.OnchainSendChangedError +import to.bitkit.repositories.OnchainSendNotDispatchedError import to.bitkit.repositories.SparkExitFeeBumpOption import to.bitkit.repositories.SparkExitFixtures import to.bitkit.repositories.SparkExitFundingState @@ -87,6 +92,23 @@ class SparkExitViewModelTest : BaseUnitTest() { assertFalse(SparkExitFeeBumpUiState(options = persistentListOf(fast), spendableSats = 5_000uL).isSavingsShort) } + @Test + fun `a higher fee whose savings payment now costs more is priced again for another confirm`() = test { + val fast = SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 4_200uL, 4_620uL) + whenever(repo.spendableSavingsSats()).thenReturn(Result.success(10_000uL)) + whenever(repo.feeBumpOptions()).thenReturn(Result.success(listOf(fast))) + whenever(repo.payHigherFee(fast)) + .thenReturn(Result.failure(OnchainSendNotDispatchedError(OnchainSendChangedError(preparedFeeSats = 600uL)))) + val context = mock { on { getString(any()) } doReturn "Fees changed" } + val sut = SparkExitViewModel(context, repo, sparkRepo) + sut.loadFeeBump() + + sut.payHigherFee() + + verify(repo, times(2)).feeBumpOptions() + assertFalse(sut.uiState.value.feeBump.isPaying) + } + @Test fun `a paid higher fee no longer shows the fee as too low`() { val running = SparkExitFixtures.record(SparkExitRecord.Phase.Running) From 9ab94f1235d6e3351f31a75f7d300d50f92d7412 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:00:56 +0100 Subject: [PATCH 080/154] fix: keep the kept spark balance after a cancelled exit --- .../to/bitkit/repositories/SparkExitRepo.kt | 4 ++- .../java/to/bitkit/repositories/SparkRepo.kt | 20 +++++++++-- .../LightningConnectionsViewModel.kt | 10 +++--- .../bitkit/repositories/SparkExitRepoTest.kt | 5 ++- .../to/bitkit/repositories/SparkRepoTest.kt | 36 +++++++++++++++++++ .../ui/settings/lightning/SparkUiTest.kt | 23 ++++++++++++ 6 files changed, 88 insertions(+), 10 deletions(-) create mode 100644 app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index a9f50b77e3..1d7dc4aef6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -990,7 +990,9 @@ class SparkExitRepo @Inject constructor( work.schedulePeriodic() SparkExitCancel.Sweeping } - sparkRepo.setExiting(false) + // Nothing was paid from Spark: the balance it showed before the exit shows again. + sparkRepo.releaseExitHold() + sparkRepo.setExiting(false, reconnect = true) Logger.info("Cancelled the Spark exit with outcome '$outcome'", context = TAG) outcome } diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 6709d30b4e..f76b9334de 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -129,6 +129,10 @@ class SparkRepo @Inject constructor( @Volatile private var withdrawalFailedAtSecs: ULong? = null + /** The kept balance when an exit's hold started, shown again should the exit pay nothing. */ + @Volatile + private var keptBeforeExit: ULong? = null + /** Deposits this app broadcast that Spark hasn't listed yet, by txid, so they show as pending at once. */ private val broadcastDeposits = ConcurrentHashMap() @@ -271,10 +275,20 @@ class SparkRepo @Inject constructor( * Holds Spark for an exit about to start: no sends, receives, spending or kept balance, in the same step the exit's * transfer starts counting it. [setExiting] reconnects it for the exit afterwards. */ - fun holdForExit() = _state.update { it.copy(isExiting = true, keptBalanceSats = null) } + fun holdForExit() { + keptBeforeExit = _state.value.keptBalanceSats + _state.update { it.copy(isExiting = true, keptBalanceSats = null) } + } - /** Releases the hold of an exit whose start failed before anything was saved: Spark was never disconnected. */ - fun releaseExitHold() = _state.update { it.copy(isExiting = false) } + /** + * Releases the hold of an exit that paid nothing: its start failed before anything was saved, or it was cancelled. + * The balance kept before it shows again while Spark still reads 0. + */ + fun releaseExitHold() { + val kept = keptBeforeExit + keptBeforeExit = null + _state.update { it.copy(isExiting = false, keptBalanceSats = if (it.balanceSats == 0uL) kept else null) } + } /** Whether an exit quote has to wait first: a leaf optimization runs, or one ran or was cut short recently. */ suspend fun needsSettling(): Boolean = diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt index 97ca2d960d..a68a661b50 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt @@ -242,8 +242,6 @@ data class LightningConnectionsUiState( data class SparkUi( /** The balance shown, which can be a kept figure while Spark reads 0. */ val balanceSats: ULong, - /** What Spark read, which an emergency exit moves. */ - val readBalanceSats: ULong = balanceSats, val deposits: ImmutableList = persistentListOf(), val withdrawals: ImmutableList = persistentListOf(), val recoverableFundsSats: ULong = 0uL, @@ -251,8 +249,11 @@ data class SparkUi( /** An exit runs, or ended with leftover fee funding not yet swept: Emergency exit opens its progress. */ val showsExitResult: Boolean = false, ) { - /** The emergency exit is offered while Spark holds funds, and leads to its progress while it shows one. */ - val showsExit get() = readBalanceSats > 0uL || recoverableFundsSats > 0uL || showsExitResult + /** + * The emergency exit is offered while Spark holds funds, also a kept balance while it reads 0, and leads to its + * progress while it shows one. + */ + val showsExit get() = balanceSats > 0uL || recoverableFundsSats > 0uL || showsExitResult val pendingDeposits get() = deposits.filterNot { it.deposit.isClaimed } val claimedDeposits get() = deposits.filter { it.deposit.isClaimed } @@ -273,7 +274,6 @@ internal suspend fun SparkState.toUi(lightningRepo: LightningRepo, showsExitResu if (shownBalanceSats == 0uL && deposits.isEmpty() && !hasExit && Env.network != Network.REGTEST) return null return SparkUi( balanceSats = shownBalanceSats, - readBalanceSats = balanceSats, deposits = deposits.map { SparkDepositUi(it, if (it.isClaimed) null else lightningRepo.onchainConfirmations(it.txid)) }.toImmutableList(), diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index d0561d6f3c..ceb7462b1d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -969,7 +969,9 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(sut.canCancel) assertEquals(SparkExitCancel.Cancelled, sut.cancel().getOrThrow()) assertNull(store.load()) - verify(sparkRepo).setExiting(false, false) + // Nothing was paid: Spark keeps the balance it showed before the exit. + verify(sparkRepo).releaseExitHold() + verify(sparkRepo).setExiting(false, true) } @OptIn(ExperimentalCoroutinesApi::class) @@ -1142,6 +1144,7 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(Phase.Failed(CANCELLED_REASON), record.phase) assertEquals(5_000uL, record.leftover.single().valueSats) assertTrue(record.needsDriving) + verify(sparkRepo).releaseExitHold() } @Test diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 030e0cec0c..639632c76c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -947,6 +947,42 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(0uL, sut.state.value.shownSpendingSats, "spending counted the exited balance again") } + private suspend fun keptAfterFailedSync(): SparkRepo { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) + val sut = createSut() + sut.refreshState().getOrThrow() + val syncFailed = info(0uL).copy(lastSyncError = SyncError.Network("operators unreachable")) + whenever { sparkService.getInfo() }.thenReturn(syncFailed) + sut.refreshState().getOrThrow() + assertEquals(10_000uL, sut.state.value.shownBalanceSats) + return sut + } + + @Test + fun `an exit start that failed before saving keeps the kept balance`() = test { + val sut = keptAfterFailedSync() + + sut.holdForExit() + sut.releaseExitHold() + sut.refreshState().getOrThrow() + + assertEquals(10_000uL, sut.state.value.shownBalanceSats, "the failed start dropped the kept balance") + } + + @Test + fun `a cancelled exit keeps the kept balance`() = test { + val sut = keptAfterFailedSync() + + sut.holdForExit() + sut.setExiting(true, reconnect = true).getOrThrow() + sut.releaseExitHold() + sut.setExiting(false, reconnect = true).getOrThrow() + + assertEquals(10_000uL, sut.state.value.shownBalanceSats, "the cancel dropped the kept balance") + assertEquals(10_000uL, sut.state.value.shownSpendingSats) + } + @Test fun `a deposit claimed early is listed only as claimed`() = test { whenever(sparkService.isConnected).thenReturn(true) diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt new file mode 100644 index 0000000000..c5bbce8bb3 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt @@ -0,0 +1,23 @@ +package to.bitkit.ui.settings.lightning + +import org.junit.Test +import org.mockito.kotlin.mock +import to.bitkit.repositories.SparkState +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +class SparkUiTest : BaseUnitTest() { + @Test + fun `emergency exit is offered for a kept balance while spark reads zero`() = test { + val kept = SparkState(isReady = true, balanceSats = 0uL, keptBalanceSats = 10_000uL) + + assertTrue(assertNotNull(kept.toUi(mock())).showsExit) + } + + @Test + fun `emergency exit is not offered with nothing on spark`() { + assertFalse(SparkUi(balanceSats = 0uL).showsExit) + } +} From 4234458eee063d65906559f0ba60f38827297d9b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 19:50:13 +0100 Subject: [PATCH 081/154] fix: approve the refused savings fee on the next fee bump confirm --- .../settings/lightning/SparkExitViewModel.kt | 16 ++++++++++++-- .../lightning/SparkExitViewModelTest.kt | 21 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index b77c1a7bca..a53363aa48 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -67,6 +67,9 @@ class SparkExitViewModel @Inject constructor( private var fundingWatch: Job? = null + /** The savings fee a higher-fee payment was refused for, by rate: the next confirm approves at least that. */ + private val feeBumpFeeFloors = mutableMapOf() + init { viewModelScope.launch { // Spark's live balance, for what a stopped exit leaves on Spark after a relaunch too. @@ -187,7 +190,8 @@ class SparkExitViewModel @Inject constructor( _uiState.update { it.copy(feeBump = SparkExitFeeBumpUiState(isLoading = true)) } val spendable = sparkExitRepo.spendableSavingsSats().getOrNull() sparkExitRepo.feeBumpOptions() - .onSuccess { options -> + .onSuccess { priced -> + val options = priced.map { it.withFeeFloor(feeBumpFeeFloors[it.rateSatPerVbyte]) } val bump = SparkExitFeeBumpUiState(options = options.toImmutableList(), spendableSats = spendable) // The fastest rate savings can pay for, or none when it covers no rate. val selected = options.firstOrNull(bump::canPay)?.speed @@ -216,7 +220,10 @@ class SparkExitViewModel @Inject constructor( .onSuccess { _effects.emit(SparkExitEffect.FeeBumped) } .onFailure { // Savings never pays more than the fee confirmed: the rates are priced again for another confirm. - if (it.cause is OnchainSendChangedError) { + val changed = it.cause as? OnchainSendChangedError + if (changed != null) { + // Coin selection can need more fee than the estimate: the next confirm approves what it asked. + changed.preparedFeeSats?.let { fee -> feeBumpFeeFloors[option.rateSatPerVbyte] = fee } ToastEventBus.send( type = Toast.ToastType.INFO, title = context.getString(R.string.lightning__spending_confirm__fees_changed_title), @@ -410,3 +417,8 @@ data class SparkExitFeeBumpUiState( fun canPay(option: SparkExitFeeBumpOption): Boolean = option.totalSats == 0uL || (spendableSats ?: 0uL) >= option.totalSats } + +private fun SparkExitFeeBumpOption.withFeeFloor(floorSats: ULong?): SparkExitFeeBumpOption { + if (floorSats == null || extraSats == 0uL || floorSats <= totalSats.safe() - extraSats.safe()) return this + return copy(totalSats = extraSats.safe() + floorSats.safe()) +} diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 739683858c..f3c49a6198 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -109,6 +109,27 @@ class SparkExitViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.feeBump.isPaying) } + @Test + fun `the next confirm after a refused higher fee approves the fee it was refused for`() = test { + val fast = SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 4_200uL, 4_620uL) + // Savings' coin selection needs 600 sats where the estimate says 420. + val floored = fast.copy(totalSats = 4_800uL) + whenever(repo.spendableSavingsSats()).thenReturn(Result.success(10_000uL)) + whenever(repo.feeBumpOptions()).thenReturn(Result.success(listOf(fast))) + whenever(repo.payHigherFee(fast)) + .thenReturn(Result.failure(OnchainSendNotDispatchedError(OnchainSendChangedError(preparedFeeSats = 600uL)))) + whenever(repo.payHigherFee(floored)).thenReturn(Result.success(Unit)) + val context = mock { on { getString(any()) } doReturn "Fees changed" } + val sut = SparkExitViewModel(context, repo, sparkRepo) + sut.loadFeeBump() + + sut.payHigherFee() + assertEquals(floored, sut.uiState.value.feeBump.selectedOption) + sut.payHigherFee() + + verify(repo).payHigherFee(floored) + } + @Test fun `a paid higher fee no longer shows the fee as too low`() { val running = SparkExitFixtures.record(SparkExitRecord.Phase.Running) From 1dcb54f7f90f67cc8ec488d56a1a3dd9bf3036fe Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 21:35:09 +0100 Subject: [PATCH 082/154] fix: approve the refused savings fee on the next exit start --- .../to/bitkit/repositories/SparkExitRepo.kt | 50 +++++++++++-------- .../settings/lightning/SparkExitViewModel.kt | 24 +++++++-- .../bitkit/repositories/SparkExitRepoTest.kt | 23 +++++++++ .../lightning/SparkExitViewModelTest.kt | 20 ++++++++ 4 files changed, 91 insertions(+), 26 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 1d7dc4aef6..571641f219 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -632,30 +632,36 @@ class SparkExitRepo @Inject constructor( ) /** - * The fee Savings pays to send the fee funding at the fast rate. Fails when the rates cannot be read; the rates it - * priced are the ones the payment at the start sends at. + * The fee Savings pays to send the fee funding at the fast rate, at least [floorSats], the fee a start was + * refused for. Fails when the rates cannot be read; the rates it priced are the ones the payment at the start + * sends at. */ - suspend fun savingsFundingFee(): Result = withContext(bgDispatcher) { - runSuspendCatching { - val pending = requireNotNull(_state.value.pending) { "No Spark exit quote" } - val address = requireNotNull(_state.value.fundingAddress) { "No Spark exit funding address" } - val fundingSats = pending.quote.fundingSats - val feeRates = lightningRepo.getFeeRates().getOrThrow() - val feeSats = lightningRepo.calculateTotalFee( - amountSats = fundingSats, - address = address, - speed = TransactionSpeed.Fast, - feeRates = feeRates, - allowFallback = false, - ).getOrThrow() - _state.update { it.copy(pending = it.pending?.copy(savingsFeeRates = feeRates, savingsFeeSats = feeSats)) } - val spendable = lightningRepo.getBalancesAsync().getOrThrow().spendableOnchainBalanceSats - SparkExitSavingsFunding( - feeSats = feeSats, - canPay = SparkExitMath.canFundFromSavings(spendable, fundingSats, feeSats), - ) + suspend fun savingsFundingFee(floorSats: ULong? = null): Result = + withContext(bgDispatcher) { + runSuspendCatching { + val pending = requireNotNull(_state.value.pending) { "No Spark exit quote" } + val address = requireNotNull(_state.value.fundingAddress) { "No Spark exit funding address" } + val fundingSats = pending.quote.fundingSats + val feeRates = lightningRepo.getFeeRates().getOrThrow() + val estimateSats = lightningRepo.calculateTotalFee( + amountSats = fundingSats, + address = address, + speed = TransactionSpeed.Fast, + feeRates = feeRates, + allowFallback = false, + ).getOrThrow() + // Coin selection can need more fee than the estimate: the start approves what it was refused for. + val feeSats = maxOf(estimateSats, floorSats ?: 0uL) + _state.update { + it.copy(pending = it.pending?.copy(savingsFeeRates = feeRates, savingsFeeSats = feeSats)) + } + val spendable = lightningRepo.getBalancesAsync().getOrThrow().spendableOnchainBalanceSats + SparkExitSavingsFunding( + feeSats = feeSats, + canPay = SparkExitMath.canFundFromSavings(spendable, fundingSats, feeSats), + ) + } } - } /** Reads what reached the funding address, for the funding screen while the user pays from another wallet. */ suspend fun refreshFundingAddress(): Result = withContext(bgDispatcher) { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index a53363aa48..bd86d76769 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -70,6 +70,9 @@ class SparkExitViewModel @Inject constructor( /** The savings fee a higher-fee payment was refused for, by rate: the next confirm approves at least that. */ private val feeBumpFeeFloors = mutableMapOf() + /** The savings fee a start's funding was refused for: the next funding prices and approves at least that. */ + private var savingsFeeFloorSats: ULong? = null + init { viewModelScope.launch { // Spark's live balance, for what a stopped exit leaves on Spark after a relaunch too. @@ -124,7 +127,7 @@ class SparkExitViewModel @Inject constructor( fun loadSavingsFunding() { viewModelScope.launch { _uiState.update { it.copy(savingsFeeSats = null, hasSavingsFeeFailed = false) } - sparkExitRepo.savingsFundingFee() + sparkExitRepo.savingsFundingFee(savingsFeeFloorSats) .onSuccess { funding -> _uiState.update { it.copy(savingsFeeSats = funding.feeSats, canFundFromSavings = funding.canPay) } } @@ -173,10 +176,23 @@ class SparkExitViewModel @Inject constructor( viewModelScope.launch { _uiState.update { it.copy(isStarting = true) } sparkExitRepo.start(_uiState.value.fundFromSavings) - .onSuccess { _effects.emit(SparkExitEffect.Started) } + .onSuccess { + savingsFeeFloorSats = null + _effects.emit(SparkExitEffect.Started) + } .onFailure { - // A cancel during the start already said so on progress. - if (it !is SparkExitStartCancelled) ToastEventBus.send(it) + // Savings never pays more than the fee confirmed: the next funding asks for the refused one. + val changed = it.cause as? OnchainSendChangedError + if (changed != null) { + changed.preparedFeeSats?.let { fee -> savingsFeeFloorSats = fee } + ToastEventBus.send( + type = Toast.ToastType.INFO, + title = context.getString(R.string.lightning__spending_confirm__fees_changed_title), + ) + } else if (it !is SparkExitStartCancelled) { + // A cancel during the start already said so on progress. + ToastEventBus.send(it) + } // The exit started but paying its fee funding failed: progress shows where to fund it. if (sparkExitRepo.state.value.isExiting) _effects.emit(SparkExitEffect.Started) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index ceb7462b1d..fa38e25cf2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -926,6 +926,29 @@ class SparkExitRepoTest : BaseUnitTest() { ) } + @Test + fun `pay from savings approves at least the fee a start was refused for`() = test { + stubFunding { Result.success(OnchainSendOutcome.Accepted("paid")) } + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + whenever(lightning.getFeeRates()).thenReturn(Result.success(FeeRates(fast = 7u, mid = 4u, slow = 1u))) + whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success(420uL)) + whenever(lightning.getBalancesAsync()).thenReturn(Result.success(balances(100_000uL))) + + assertEquals(600uL, sut.savingsFundingFee(floorSats = 600uL).getOrThrow().feeSats) + sut.start(fundFromSavings = true).getOrThrow() + sut.onAppBackgrounded() + + verify(lightning).sendOnChain( + eq(funding), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = eq(600uL), + ) + } + @Test fun `savings never pays more than the confirmed funding when the start quotes again`() = test { stubFunding { Result.success(OnchainSendOutcome.Accepted("paid")) } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index f3c49a6198..d522aff48c 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -5,6 +5,7 @@ import kotlinx.collections.immutable.persistentListOf import kotlinx.coroutines.flow.MutableStateFlow import org.junit.Test import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.times @@ -21,6 +22,7 @@ import to.bitkit.repositories.SparkExitNetworkFees import to.bitkit.repositories.SparkExitQuote import to.bitkit.repositories.SparkExitRecord import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitSavingsFunding import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.SparkRepo import to.bitkit.repositories.SparkState @@ -130,6 +132,24 @@ class SparkExitViewModelTest : BaseUnitTest() { verify(repo).payHigherFee(floored) } + @Test + fun `the next funding after a start refused for a higher savings fee prices at least that fee`() = test { + whenever(repo.savingsFundingFee(anyOrNull())).thenReturn(Result.success(SparkExitSavingsFunding(420uL, true))) + whenever(repo.start(true)) + .thenReturn(Result.failure(OnchainSendNotDispatchedError(OnchainSendChangedError(preparedFeeSats = 600uL)))) + val context = mock { on { getString(any()) } doReturn "Fees changed" } + val sut = SparkExitViewModel(context, repo, sparkRepo) + sut.loadSavingsFunding() + sut.onFundFromSavings() + + sut.start() + sut.loadSavingsFunding() + + // Savings' coin selection needs 600 sats where the estimate says 420: the next funding prices that. + verify(repo).savingsFundingFee(null) + verify(repo).savingsFundingFee(600uL) + } + @Test fun `a paid higher fee no longer shows the fee as too low`() { val running = SparkExitFixtures.record(SparkExitRecord.Phase.Running) From b8eb8e2430785611b65ad821076f5c63d53682fd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 21:37:30 +0100 Subject: [PATCH 083/154] fix: forget the kept spark balance after an exit ends or a wipe --- .../main/java/to/bitkit/repositories/SparkRepo.kt | 3 +++ .../java/to/bitkit/repositories/SparkRepoTest.kt | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 56725803de..d977594445 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -236,6 +236,7 @@ class SparkRepo @Inject constructor( preparedWithdrawal = null withdrawalTxids.clear() withdrawalFailedAtSecs = null + keptBeforeExit = null broadcastDeposits.clear() sendsRecordedWithoutFee.clear() unsavedPayments.clear() @@ -259,6 +260,8 @@ class SparkRepo @Inject constructor( */ suspend fun setExiting(isExiting: Boolean, reconnect: Boolean = false): Result = withContext(bgDispatcher) { val isCurrent = _state.value.isExiting == isExiting && sparkService.isConnected + // An ended exit forgets the balance kept before it: a cancel already showed it again. + if (!isExiting) keptBeforeExit = null if (isCurrent && !reconnect) return@withContext Result.success(Unit) _state.update { it.copy(isExiting = isExiting, keptBalanceSats = it.keptBalanceSats.takeUnless { isExiting }) } runSuspendCatching { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 6e7d1a8e1c..fadf83c8b5 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1067,6 +1067,19 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(10_000uL, sut.state.value.shownSpendingSats) } + @Test + fun `an exit that ended and a wipe forget the kept balance from before the exit`() = test { + val sut = keptAfterFailedSync() + sut.holdForExit() + sut.setExiting(false).getOrThrow() + sut.wipe(0).getOrThrow() + + // A restored wallet's exit cancelled while Spark reads 0 shows none of the previous wallet's kept balance. + sut.releaseExitHold() + + assertEquals(0uL, sut.state.value.shownBalanceSats, "the previous wallet's kept balance came back") + } + @Test fun `a deposit claimed early is listed only as claimed`() = test { whenever(sparkService.isConnected).thenReturn(true) From f6ac4e6d8fba22b001fbed2025f08e54a2b3fb1c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 23:22:08 +0100 Subject: [PATCH 084/154] fix: cap the leftover sweep fee at bitkit's own rate --- .../to/bitkit/repositories/SparkExitDriver.kt | 23 +++++++++++++-- .../to/bitkit/repositories/SparkExitRepo.kt | 1 + .../repositories/SparkExitDriverTest.kt | 29 ++++++++++++++++--- 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index ad2d913ca2..331301c902 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -93,6 +93,11 @@ class SparkExitDriver( private val nowMillis: () -> Long, /** The chain tip this tick, null when it could not be read. */ private val tip: UInt? = null, + /** + * The fast rate of Bitkit's own fee source, null when it cannot be read: with the exit's own rate, the most a + * leftover sweep pays, whatever the chain host asks. + */ + private val trustedFeeRate: suspend () -> ULong? = { null }, ) { companion object { private const val TAG = "SparkExitDriver" @@ -788,7 +793,11 @@ class SparkExitDriver( val refused = built?.takeIf { it.isWaitingForFees }?.refusedFeeRate ?: 0uL // A refusal raises the rate up to the next block's or the exit's, never above: a node asking more is refused // again, and the sweep waits a block for fees to drop. - val cap = if (refused > 0uL) maxOf(nextBlockRate() ?: 0uL, record.feeRateSatPerVbyte) else 0uL + val cap = if (refused > 0uL) { + minOf(maxOf(nextBlockRate() ?: 0uL, record.feeRateSatPerVbyte), sweepFeeCeiling(record)) + } else { + 0uL + } val floor = minOf(refused, cap) val rate = maxOf(SparkExitMath.sweepFeeRate(economyRate(), record.feeRateSatPerVbyte), floor) val inputs = SparkExitSweep.worthSweeping( @@ -891,6 +900,13 @@ class SparkExitDriver( .onFailure { Logger.warn("Failed to read the next-block fee rate for the leftover sweep", it, context = TAG) } .getOrNull() + /** + * The most a leftover sweep pays per vbyte: the exit's own rate, which the user confirmed, or Bitkit's own fast + * rate when higher. The chain host's estimates and refusals are not trusted past it. + */ + private suspend fun sweepFeeCeiling(record: SparkExitRecord): ULong = + maxOf(record.feeRateSatPerVbyte, runSuspendCatching { trustedFeeRate() }.getOrNull() ?: 0uL) + private suspend fun economyRate(): ULong? = runSuspendCatching { chain.economyFeeRate() } .onFailure { Logger.warn("Failed to read the economy fee rate for the leftover sweep", it, context = TAG) } .getOrNull() @@ -927,7 +943,10 @@ class SparkExitDriver( .onFailure { Logger.warn("Failed to read the Spark exit leftover sweep fee rate", it, context = TAG) } .getOrNull() ?: return null - val rate = maxOf(nextBlock, (old.feeRateSatPerVbyte ?: record.feeRateSatPerVbyte) + 1uL) + val oldRate = old.feeRateSatPerVbyte ?: record.feeRateSatPerVbyte + val rate = minOf(maxOf(nextBlock, oldRate + 1uL), sweepFeeCeiling(record)) + // At the ceiling already: sent again as it is until it confirms. + if (rate <= oldRate) return null val values = record.leftover.associate { "${it.txid}:${it.vout}" to it.valueSats } val inputs = SparkExitTxInputs.decode(hex)?.map { SparkExitSweep.Input(it.prevTxid, it.vout, values["${it.prevTxid}:${it.vout}"] ?: return null) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 571641f219..af6825bb1c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -298,6 +298,7 @@ class SparkExitRepo @Inject constructor( save = ::saveRecord, nowMillis = clock::nowMs, tip = tip, + trustedFeeRate = { lightningRepo.getFeeRates().getOrNull()?.fast?.toULong() }, ) private suspend fun afterTick( diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 52d57d5cda..267b2ef6ee 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -55,6 +55,7 @@ class SparkExitDriverTest : BaseUnitTest() { withSdk: Boolean = true, tip: UInt? = null, save: (SparkExitRecord) -> Unit = { saved += it }, + trustedFeeRate: ULong? = 10uL, ) = SparkExitDriver( chain = chain, recovering = sdk.takeIf { withSdk }, @@ -62,6 +63,7 @@ class SparkExitDriverTest : BaseUnitTest() { save = save, nowMillis = { now }, tip = tip, + trustedFeeRate = { trustedFeeRate }, ) private val interval = SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds @@ -1663,12 +1665,12 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals("exit-state-1", record.exitStateSnapshot) } - private fun sweepDone(): SparkExitRecord { - chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0".repeat(32), 1u, 25_000uL)) + private fun sweepDone(valueSats: ULong = 25_000uL): SparkExitRecord { + chain.utxosByAddress[SWEEP_FUNDING] = listOf(SparkExitFixtures.utxo("f0".repeat(32), 1u, valueSats)) return SparkExitFixtures.record(Phase.Done).copy( destination = SWEEP_DESTINATION, funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), - leftover = listOf(SparkExitRecord.Leftover("f0".repeat(32), 1u, 25_000uL)), + leftover = listOf(SparkExitRecord.Leftover("f0".repeat(32), 1u, valueSats)), ) } @@ -1743,6 +1745,25 @@ class SparkExitDriverTest : BaseUnitTest() { ) } + @Test + fun `a host quoting an absurd fee rate cannot push the leftover sweep past bitkit's own rate`() = test { + // The host's next block asks 5,000 sat/vB and its refusal 550,000 sats for a ~110 vB sweep of 2M sats. + chain.nextBlockRate = 5_000uL + chain.outcome = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 110 < 550000") + var record = driver(tip = 1_000u).tick(sweepDone(valueSats = 2_000_000uL)) + record = driver(tip = 1_000u).tick(record) + chain.outcome = SparkExitBroadcastOutcome.Accepted + record = driver(tip = 1_001u).tick(record) + + val sent = assertNotNull(record.leftoverSweep) + assertEquals(10uL, sent.feeRateSatPerVbyte, "the refused sweep went out at the host's rate") + + // A day unconfirmed: no replacement above the ceiling, the same sweep is sent again. + record = driver(tip = 1_145u).tick(record) + assertEquals(sent.txid, record.leftoverSweep?.txid) + assertEquals(10uL, record.leftoverSweep?.feeRateSatPerVbyte) + } + @Test fun `a leftover sweep refused for another reason is final`() = test { chain.outcome = SparkExitBroadcastOutcome.Rejected("bad-txns-nonstandard-inputs") @@ -1873,7 +1894,7 @@ class SparkExitDriverTest : BaseUnitTest() { val first = assertNotNull(record.leftoverSweep) chain.nextBlockRate = 1_000uL - record = driver(tip = 1_144u).tick(record) + record = driver(tip = 1_144u, trustedFeeRate = 1_000uL).tick(record) assertEquals(first.txid, record.leftoverSweep?.txid) assertTrue(assertNotNull(record.leftoverSweep).isAccepted) From 52bac5dbdcbeb0450c6225076f2df79c6a72dc28 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Tue, 10 Nov 2026 23:31:17 +0100 Subject: [PATCH 085/154] fix: forget a savings payment only after three blocks unseen --- .../to/bitkit/repositories/SparkExitRecord.kt | 12 ++++++---- .../repositories/SparkExitDriverTest.kt | 24 +++++++++++++++---- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 52bc8ab34c..2d7f9f7a57 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -156,8 +156,11 @@ data class SparkExitRecord( /** Blocks a step a node accepted may go unconfirmed before the exit's fee rate counts as too low. */ const val UNCONFIRMED_BLOCKS_TO_SURFACE = 6u - /** Blocks a payment from savings may be unknown to every host before the exit forgets it and asks again. */ - const val OWN_PAYMENT_MISSING_BLOCKS = 1u + /** + * Blocks a payment from savings may be unknown to every host before the exit forgets it and asks again: long + * enough that a host still indexing it, or one false miss, never asks for the funding twice. + */ + const val OWN_PAYMENT_MISSING_BLOCKS = 3u /** Blocks after the first look a payment from savings may stay unadopted before the exit asks again. */ const val OWN_PAYMENT_TIMEOUT_BLOCKS = 144u @@ -268,8 +271,9 @@ data class SparkExitRecord( recovery?.transactions?.all { it.status is ExitTransactionStatus.Confirmed } == true /** - * [fundingPaymentTxid] at [tip], when [isKnown] says whether a host knows it: forgotten once missing for a block, - * or 144 blocks after the first look without being adopted, so the ask and its reminder come back. + * [fundingPaymentTxid] at [tip], when [isKnown] says whether a host knows it: forgotten once missing for + * [OWN_PAYMENT_MISSING_BLOCKS] blocks, or 144 blocks after the first look without being adopted, so the ask and + * its reminder come back. */ fun withOwnPaymentLooked(tip: UInt, isKnown: Boolean): SparkExitRecord { if (!isAwaitingOwnPayment && !isEndedPaymentPending) return this diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 267b2ef6ee..15e30c63ad 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -632,13 +632,16 @@ class SparkExitDriverTest : BaseUnitTest() { assertIs(record.phase) assertTrue(record.isAwaitingOwnPayment) assertEquals(1_001u, record.fundingPaymentSeenAtHeight) - // No host knows the payment for a block: the exit forgets it and asks again. + // No host knows the payment for three blocks: the exit forgets it and asks again. chain.unknownTxids = setOf("bump") sdk.checks += check(recovery, RecoveryVerdict.Valid) record = driver(tip = 1_002u).tick(record) assertEquals(1_002u, record.fundingPaymentMissingSince) sdk.checks += check(recovery, RecoveryVerdict.Valid) - record = driver(tip = 1_003u).tick(record) + record = driver(tip = 1_004u).tick(record) + assertTrue(record.isAwaitingOwnPayment) + sdk.checks += check(recovery, RecoveryVerdict.Valid) + record = driver(tip = 1_005u).tick(record) assertFalse(record.isAwaitingOwnPayment) assertNull(record.fundingPaymentTxid) } @@ -663,6 +666,19 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(20_000uL, ask.receivedSats) } + @Test + fun `a payment from savings one host misses for a block or a single read is not forgotten`() { + val waiting = SparkExitFixtures.record(Phase.NeedsFunding(30_000uL)).copy(fundingPaymentTxid = "bump") + // Missed just before a block and just after it, seconds apart: the host may still be indexing it. + val missed = waiting.withOwnPaymentLooked(1_000u, isKnown = false).withOwnPaymentLooked(1_001u, isKnown = false) + assertTrue(missed.isAwaitingOwnPayment, "a one-block miss asked for the funding again") + + // A read that finds it starts the count over; only a miss that lasts three blocks forgets it. + val found = missed.withOwnPaymentLooked(1_002u, isKnown = true).withOwnPaymentLooked(1_003u, isKnown = false) + assertTrue(found.withOwnPaymentLooked(1_005u, isKnown = false).isAwaitingOwnPayment) + assertFalse(found.withOwnPaymentLooked(1_006u, isKnown = false).isAwaitingOwnPayment) + } + @Test fun `a payment from savings never adopted is forgotten 144 blocks after the first look`() { val waiting = SparkExitFixtures.record(Phase.NeedsFunding(30_000uL)).copy(fundingPaymentTxid = "bump") @@ -1306,10 +1322,10 @@ class SparkExitDriverTest : BaseUnitTest() { assertNull(record.fundingPaymentTxid) assertNotNull(assertNotNull(record.leftoverSweep).txHex) - // One no host ever sees is forgotten after a block, and the exit stops. + // One no host sees for three blocks is forgotten, and the exit stops. chain.unknownTxids = setOf("gone") var forgotten = driver(tip = 1_000u).tick(ended.copy(fundingPaymentTxid = "gone")) - forgotten = driver(tip = 1_001u).tick(forgotten) + forgotten = driver(tip = 1_003u).tick(forgotten) assertNull(forgotten.fundingPaymentTxid) assertFalse(forgotten.needsDriving) } From 5ff94608f7a2b71dca80f44b4ee9e69a6448aa06 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:13:41 +0100 Subject: [PATCH 086/154] fix: finish a spark exit start its screen left --- .../to/bitkit/repositories/SparkExitRepo.kt | 216 ++++++++++-------- app/src/main/java/to/bitkit/ui/ContentView.kt | 18 +- .../settings/lightning/SparkExitComponents.kt | 18 ++ .../lightning/SparkExitConfirmScreen.kt | 5 +- .../settings/lightning/SparkExitViewModel.kt | 11 +- .../bitkit/repositories/SparkExitRepoTest.kt | 20 ++ .../lightning/SparkExitViewModelTest.kt | 13 ++ 7 files changed, 190 insertions(+), 111 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index af6825bb1c..f673eff8f8 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -12,6 +12,7 @@ import com.synonym.bitkitcore.FeeRates import io.ktor.client.HttpClient import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow @@ -538,7 +539,8 @@ class SparkExitRepo @Inject constructor( runSuspendCatching { if (!paymentMutex.tryLock()) throw SparkExitError("A Spark exit payment is already being made") try { - payHigherFeeLocked(option) + // A payment that went out is always saved, even when the fee bump screen goes away meanwhile. + withContext(NonCancellable) { payHigherFeeLocked(option) } } finally { paymentMutex.unlock() } @@ -726,51 +728,59 @@ class SparkExitRepo @Inject constructor( transferRepo.markSettled(transferId) sparkRepo.releaseExitHold() }.getOrThrow() - cacheStore.update { - val next = it.sparkExitNextFundingIndexes + (fundingIndexKey to pending.fundingIndex.toInt() + 1) - it.copy(sparkExitNextFundingIndexes = next) - } - val createdAt = record.createdAt - // Published for the screens and a cancel, but driven only once the start settled the leaves it exits. - startingCreatedAt = createdAt - _state.update { it.copy(record = record, pending = null, fundingAddress = key.address) } - isLoaded = true - // Reconnecting for the exit disconnects Spark, which would cut a running leaf optimization short. - val isCurrent = try { - sparkRepo.awaitOptimizationIdle() - // A cancel during the wait ended this exit: nothing more of the start runs, and nothing is paid. - tickMutex.withLock { - if (!isStarting(createdAt)) return@withLock false - // An optimization since the quote swapped leaves: the exit is quoted again over the leaves Spark holds. - requote(pending)?.let { fresh -> - // A failed write goes on with the confirmed quote, as a failed requote does. - val requoted = writeRequote(requireNotNull(_state.value.record), fresh) ?: return@let - quote = fresh - record = requoted - _state.update { it.copy(record = record) } + // Once saved, the start runs to its end even when its screen goes away: an exit left half started would keep + // Spark on Lightning with its leaf optimization on, and nothing would drive or fund it. + withContext(NonCancellable) { + cacheStore.update { + val next = it.sparkExitNextFundingIndexes + (fundingIndexKey to pending.fundingIndex.toInt() + 1) + it.copy(sparkExitNextFundingIndexes = next) + } + val createdAt = record.createdAt + // Published for the screens and a cancel, but driven only once the start settled the leaves it exits. + startingCreatedAt = createdAt + _state.update { it.copy(record = record, pending = null, fundingAddress = key.address) } + isLoaded = true + // Reconnecting for the exit disconnects Spark, which would cut a running leaf optimization short. + val isCurrent = try { + sparkRepo.awaitOptimizationIdle() + // A cancel during the wait ended this exit: nothing more of the start runs, and nothing is paid. + tickMutex.withLock { + if (!isStarting(createdAt)) return@withLock false + // An optimization since the quote swapped leaves: the exit is quoted again over the leaves Spark + // holds. + requote(pending)?.let { fresh -> + // A failed write goes on with the confirmed quote, as a failed requote does. + val requoted = writeRequote(requireNotNull(_state.value.record), fresh) ?: return@let + quote = fresh + record = requoted + _state.update { it.copy(record = record) } + } + // Under the lock, so a cancel can't release Spark between the check and taking it off Lightning. + sparkRepo.setExiting(true, reconnect = true) + true } - // Under the lock, so a cancel can't release Spark between the check and taking it off Lightning. - sparkRepo.setExiting(true, reconnect = true) - true + } finally { + startingCreatedAt = null } - } finally { - startingCreatedAt = null - } - if (!isCurrent) throw SparkExitStartCancelled() - work.schedulePeriodic() - Logger.info("Started Spark exit of '${quote.exitSats}' sats over '${quote.leafIds.size}' leaves", context = TAG) - // Driven before paying, so a failed payment from savings still leaves the exit watching its address. - scope.launch { tick() } - onAppForegrounded() - // Savings pays at most what the user confirmed: Progress asks for the rest of a higher fresh amount. - val savingsSats = minOf(quote.fundingSats, pending.quote.fundingSats) - if (fundFromSavings && savingsSats > 0uL) { - runSuspendCatching { - payFunding(createdAt, key.address, savingsSats, pending.savingsFeeRates, pending.savingsFeeSats) + if (!isCurrent) throw SparkExitStartCancelled() + work.schedulePeriodic() + Logger.info( + "Started Spark exit of '${quote.exitSats}' sats over '${quote.leafIds.size}' leaves", + context = TAG, + ) + // Driven before paying, so a failed payment from savings still leaves the exit watching its address. + scope.launch { tick() } + onAppForegrounded() + // Savings pays at most what the user confirmed: Progress asks for the rest of a higher fresh amount. + val savingsSats = minOf(quote.fundingSats, pending.quote.fundingSats) + if (fundFromSavings && savingsSats > 0uL) { + runSuspendCatching { + payFunding(createdAt, key.address, savingsSats, pending.savingsFeeRates, pending.savingsFeeSats) + } + // A refused payment shows on progress at once, with the offer to pay again. + .onFailure { _state.value.record?.let { current -> noteSavingsSend(current) } } + .getOrThrow() } - // A refused payment shows on progress at once, with the offer to pay again. - .onFailure { _state.value.record?.let { current -> noteSavingsSend(current) } } - .getOrThrow() } } @@ -867,27 +877,31 @@ class SparkExitRepo @Inject constructor( if (!paymentMutex.tryLock()) throw SparkExitError("A Spark exit payment is already running") try { // Under the tick lock from the check to the saved txid, as the start's payment: a cancel either ends - // the exit before savings pays again or finds the payment and refuses. - tickMutex.withLock { - val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } - val refused = savingsSend(record)?.takeIf { SparkExitMath.isSavingsPaymentRefused(record, it) } - ?: throw SparkExitError("No refused savings payment to pay again") - val outcome = lightningRepo.retryOriginalOnchainSend( - attemptId = refused.attemptId, - walletId = refused.walletId, - feeRateSatsPerVByte = refused.feeRateSatsPerVByte, - ) { check(it.attemptId == refused.attemptId && it.address == refused.address) } - .getOrThrow() - val txid = fundingTxid(outcome, refused.amountSats) - val current = _state.value.record ?: return@withLock - val paid = current.copy(fundingPaymentTxid = txid) - saveRecord(paid) - _state.update { - it.copy( - record = paid, - fundingState = SparkExitMath.fundingState(paid, utxos = null), - isSavingsPaymentRefused = false, - ) + // the exit before savings pays again or finds the payment and refuses. Never cut short between the two. + withContext(NonCancellable) { + tickMutex.withLock { + val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { + "No running Spark exit" + } + val refused = savingsSend(record)?.takeIf { SparkExitMath.isSavingsPaymentRefused(record, it) } + ?: throw SparkExitError("No refused savings payment to pay again") + val outcome = lightningRepo.retryOriginalOnchainSend( + attemptId = refused.attemptId, + walletId = refused.walletId, + feeRateSatsPerVByte = refused.feeRateSatsPerVByte, + ) { check(it.attemptId == refused.attemptId && it.address == refused.address) } + .getOrThrow() + val txid = fundingTxid(outcome, refused.amountSats) + val current = _state.value.record ?: return@withLock + val paid = current.copy(fundingPaymentTxid = txid) + saveRecord(paid) + _state.update { + it.copy( + record = paid, + fundingState = SparkExitMath.fundingState(paid, utxos = null), + isSavingsPaymentRefused = false, + ) + } } } } finally { @@ -967,41 +981,47 @@ class SparkExitRepo @Inject constructor( */ suspend fun cancel(): Result = withContext(bgDispatcher) { runSuspendCatching { - tickMutex.withLock { - val record = _state.value.record ?: throw SparkExitError("No Spark exit to cancel") - val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } - // A savings send to the address still unresolved may be retried later: the exit keeps watching it. - val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() } - .getOrElse { throw SparkExitCancelUnreadable() } - val isSending = attempt?.address == address && attempt.isUnresolved - _state.update { it.copy(isSavingsSendUnresolved = isSending) } - if (!canCancel) throw SparkExitError("The Spark exit can no longer be cancelled") - val chain = requireNotNull(chain) { "No chain host for this network" } - val utxos = runSuspendCatching { chain.utxos(address) }.getOrElse { throw SparkExitCancelUnreadable() } - record.transferId?.let { transferRepo.markSettled(it) } - val outcome = if (utxos.isEmpty()) { - store.delete() - _state.update { it.copy(record = null) } - work.cancelAll() - SparkExitCancel.Cancelled - } else { - val leftover = utxos.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) } - val ended = record.copy( - phase = SparkExitRecord.Phase.Failed(CANCELLED_REASON), - leftover = leftover, - isResultSeen = true, - isCancelled = true, - ) - saveRecord(ended) - _state.update { it.copy(record = ended) } - work.schedulePeriodic() - SparkExitCancel.Sweeping + // Runs to its end once begun, so a cancel that settled the transfer always releases Spark. + withContext(NonCancellable) { + tickMutex.withLock { + val record = _state.value.record ?: throw SparkExitError("No Spark exit to cancel") + val address = requireNotNull(record.funding.firstOrNull()?.address) { + "No Spark exit funding address" + } + // A savings send to the address still unresolved may be retried later: the exit keeps watching it. + val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() } + .getOrElse { throw SparkExitCancelUnreadable() } + val isSending = attempt?.address == address && attempt.isUnresolved + _state.update { it.copy(isSavingsSendUnresolved = isSending) } + if (!canCancel) throw SparkExitError("The Spark exit can no longer be cancelled") + val chain = requireNotNull(chain) { "No chain host for this network" } + val utxos = runSuspendCatching { chain.utxos(address) } + .getOrElse { throw SparkExitCancelUnreadable() } + record.transferId?.let { transferRepo.markSettled(it) } + val outcome = if (utxos.isEmpty()) { + store.delete() + _state.update { it.copy(record = null) } + work.cancelAll() + SparkExitCancel.Cancelled + } else { + val leftover = utxos.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) } + val ended = record.copy( + phase = SparkExitRecord.Phase.Failed(CANCELLED_REASON), + leftover = leftover, + isResultSeen = true, + isCancelled = true, + ) + saveRecord(ended) + _state.update { it.copy(record = ended) } + work.schedulePeriodic() + SparkExitCancel.Sweeping + } + // Nothing was paid from Spark: the balance it showed before the exit shows again. + sparkRepo.releaseExitHold() + sparkRepo.setExiting(false, reconnect = true) + Logger.info("Cancelled the Spark exit with outcome '$outcome'", context = TAG) + outcome } - // Nothing was paid from Spark: the balance it showed before the exit shows again. - sparkRepo.releaseExitHold() - sparkRepo.setExiting(false, reconnect = true) - Logger.info("Cancelled the Spark exit with outcome '$outcome'", context = TAG) - outcome } } } diff --git a/app/src/main/java/to/bitkit/ui/ContentView.kt b/app/src/main/java/to/bitkit/ui/ContentView.kt index e0b08c9eee..d43eed48c2 100644 --- a/app/src/main/java/to/bitkit/ui/ContentView.kt +++ b/app/src/main/java/to/bitkit/ui/ContentView.kt @@ -213,6 +213,7 @@ import to.bitkit.ui.settings.lightning.SparkExitFundingScreen import to.bitkit.ui.settings.lightning.SparkExitIntroScreen import to.bitkit.ui.settings.lightning.SparkExitProgressScreen import to.bitkit.ui.settings.lightning.SparkExitQuoteScreen +import to.bitkit.ui.settings.lightning.SparkExitStartedEffect import to.bitkit.ui.settings.lightning.SparkExitViewModel import to.bitkit.ui.settings.pin.PinManagementScreen import to.bitkit.ui.settings.quickPay.QuickPayIntroScreen @@ -2082,6 +2083,10 @@ private fun NavGraphBuilder.sparkExit(navController: NavHostController) { return hiltViewModel(parentEntry) } val leaveExit = { navController.popBackStack(inclusive = false) } + val openProgress = { + leaveExit() + navController.navigateTo(Routes.SparkExitProgress) + } composableWithDefaultTransitions { SparkExitIntroScreen( onBack = { navController.popBackStack() }, @@ -2089,8 +2094,10 @@ private fun NavGraphBuilder.sparkExit(navController: NavHostController) { ) } composableWithDefaultTransitions { + val viewModel = exitViewModel(it) + SparkExitStartedEffect(viewModel, openProgress) SparkExitQuoteScreen( - viewModel = exitViewModel(it), + viewModel = viewModel, onBack = { navController.popBackStack() }, onContinue = { needsFunding -> navController.navigateTo(if (needsFunding) Routes.SparkExitFunding else Routes.SparkExitConfirm) @@ -2098,8 +2105,10 @@ private fun NavGraphBuilder.sparkExit(navController: NavHostController) { ) } composableWithDefaultTransitions { + val viewModel = exitViewModel(it) + SparkExitStartedEffect(viewModel, openProgress) SparkExitFundingScreen( - viewModel = exitViewModel(it), + viewModel = viewModel, onBack = { navController.popBackStack() }, onContinue = { navController.navigateTo(Routes.SparkExitConfirm) }, ) @@ -2108,10 +2117,7 @@ private fun NavGraphBuilder.sparkExit(navController: NavHostController) { SparkExitConfirmScreen( viewModel = exitViewModel(it), onBack = { navController.popBackStack() }, - onStart = { - leaveExit() - navController.navigateTo(Routes.SparkExitProgress) - }, + onStart = openProgress, ) } composableWithDefaultTransitions { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt index bf7eeff1e2..a9e3452970 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -10,6 +10,8 @@ import androidx.compose.foundation.layout.size import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag @@ -19,6 +21,7 @@ import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle import breez_sdk_spark.RecoverFundsResponse import to.bitkit.R import to.bitkit.ext.ellipsisMiddle @@ -43,6 +46,21 @@ import to.bitkit.ui.utils.withAccentBoldBright import to.bitkit.utils.BlockTimeHelpers import to.bitkit.viewmodels.AppViewModel +/** + * Opens the progress of an exit that started, from whichever exit screen shows: the start runs on when the user goes + * back from Confirm meanwhile. + */ +@Composable +internal fun SparkExitStartedEffect(viewModel: SparkExitViewModel, onStarted: () -> Unit) { + val uiState by viewModel.uiState.collectAsStateWithLifecycle() + val isStarted = uiState.isStarted + LaunchedEffect(isStarted) { + if (!isStarted) return@LaunchedEffect + viewModel.onStartShown() + onStarted() + } +} + /** An amount as plain text for copy that names it, in the user's primary unit. */ @Composable internal fun sparkExitAmountText(sats: ULong): String = diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt index 36cca7041d..b6c473fa28 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt @@ -5,7 +5,6 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag @@ -35,9 +34,7 @@ fun SparkExitConfirmScreen( onStart: () -> Unit, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() - LaunchedEffect(Unit) { - viewModel.effects.collect { if (it == SparkExitEffect.Started) onStart() } - } + SparkExitStartedEffect(viewModel, onStart) // Asked as the exit starts: the notifications are how a stalled background run reaches the user. val requestNotifications = rememberSubscriptionNotificationsRequest() Content( diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index bd86d76769..f37787e363 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -178,7 +178,7 @@ class SparkExitViewModel @Inject constructor( sparkExitRepo.start(_uiState.value.fundFromSavings) .onSuccess { savingsFeeFloorSats = null - _effects.emit(SparkExitEffect.Started) + _uiState.update { it.copy(isStarted = true) } } .onFailure { // Savings never pays more than the fee confirmed: the next funding asks for the refused one. @@ -194,12 +194,16 @@ class SparkExitViewModel @Inject constructor( ToastEventBus.send(it) } // The exit started but paying its fee funding failed: progress shows where to fund it. - if (sparkExitRepo.state.value.isExiting) _effects.emit(SparkExitEffect.Started) + if (sparkExitRepo.state.value.isExiting) _uiState.update { state -> state.copy(isStarted = true) } } _uiState.update { it.copy(isStarting = false) } } } + fun onStartShown() { + _uiState.update { it.copy(isStarted = false) } + } + /** Prices the higher rates the running exit can move to, selecting the fastest. */ fun loadFeeBump() { viewModelScope.launch { @@ -299,7 +303,6 @@ class SparkExitViewModel @Inject constructor( } sealed interface SparkExitEffect { - data object Started : SparkExitEffect data object Cancelled : SparkExitEffect data object FeeBumped : SparkExitEffect } @@ -315,6 +318,8 @@ data class SparkExitUiState( val fundFromSavings: Boolean = false, val showsFundingAddress: Boolean = false, val isStarting: Boolean = false, + /** The exit started: whichever exit screen shows, also one the user went back to meanwhile, opens its progress. */ + val isStarted: Boolean = false, val isRefreshing: Boolean = false, val record: SparkExitRecord? = null, val tipHeight: UInt? = null, diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index fa38e25cf2..070a58eb0b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -841,6 +841,26 @@ class SparkExitRepoTest : BaseUnitTest() { sut.onAppBackgrounded() } + @OptIn(ExperimentalCoroutinesApi::class) + @Test + fun `a start whose screen goes away after its record is saved still takes spark off lightning`() = test { + val gate = CompletableDeferred() + whenever(sparkRepo.awaitOptimizationIdle()).doSuspendableAnswer { gate.await() } + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + + val start = async { sut.start(fundFromSavings = false) } + runCurrent() + start.cancel() + gate.complete(Unit) + runCurrent() + + verify(sparkRepo).setExiting(true, true) + verify(work, atLeastOnce()).schedulePeriodic() + assertTrue(sut.state.value.isExiting) + sut.onAppBackgrounded() + } + @Test fun `a leaf swap between the quote and the start quotes the exit again`() = test { val sdk = FakeSparkExitRecovering() diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index d522aff48c..dd3c36fcd6 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -62,6 +62,19 @@ class SparkExitViewModelTest : BaseUnitTest() { sut.stopWatchingFundingAddress() } + @Test + fun `a started exit stays started until a screen opens its progress`() = test { + whenever(repo.start(any())).thenReturn(Result.success(Unit)) + val sut = SparkExitViewModel(mock(), repo, sparkRepo) + + // No screen collects while the user went back from Confirm. + sut.start() + + assertTrue(sut.uiState.value.isStarted) + sut.onStartShown() + assertFalse(sut.uiState.value.isStarted) + } + @Test fun `funding from another wallet continues only once the address holds what the quote asks`() { val quote = SparkExitQuote(SparkExitFixtures.prepared(funding = 20_000uL)) From ada28adf92ae86f9ebda9d3a3fff737fc89bd965 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:13:54 +0100 Subject: [PATCH 087/154] fix: retry a spark exit rebuild of only failed cooperative leaves --- .../to/bitkit/repositories/SparkExitDriver.kt | 7 +++---- .../repositories/SparkExitDriverTest.kt | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 331301c902..6eb711cdb4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -248,16 +248,15 @@ class SparkExitDriver( return askForFunding(record, it) } if (built.transactions.isEmpty()) { - // A first build of only cooperative leaves the operators could not co-sign is kept: they are retried for a - // week like any failed leaf. A rebuild like it keeps the recovery it has and tries again on the next tick. - if (built.failed.isNotEmpty() && record.recovery == null) { + // A build of only cooperative leaves the operators could not co-sign is kept, a rebuild's too: they are + // retried for a week like any failed leaf, then let go. + if (built.failed.isNotEmpty()) { val adopted = record.adopt(built, nowMillis()) .copy(waitingLeafIds = waitingLeafIds(record, prepared.skipped, stopped)) save(adopted) Logger.info("Built Spark exit of only '${built.failed.size}' failed cooperative leaves", context = TAG) return adopted } - if (built.failed.isNotEmpty()) return record.copy(failedLeafCount = built.failed.size) return end(record.copy(phase = SparkExitRecord.Phase.Failed("Nothing to recover")), record) } // A leaf the operators' watchtower stopped is waited for, not struck, until its wait is over. diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 15e30c63ad..dfd40137f6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -793,6 +793,26 @@ class SparkExitDriverTest : BaseUnitTest() { assertTrue(record.isFailedLeavesReleased) } + @Test + fun `a redo that rebuilds only cooperative leaves the operators can't sign retries them, then lets go`() = test { + var record = running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("old"))), builtAt = 0L) + sdk.checks += check(assertNotNull(record.recovery), redo) + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null) + val failed = listOf( + CooperativeRecoveryFailure("leaf-1", "o", 0u, CooperativeRecoveryError.OperatorsUnavailable("down")), + ) + repeat(1_100) { sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = failed) } + + for (tip in 1_000u..2_010u) { + record = driver(tip = tip).tick(record) + now += interval + } + + assertNotNull(record.failedLeafRetrySince) + assertEquals(Phase.Done, record.phase) + assertTrue(record.isFailedLeavesReleased) + } + private val operatorsDown = CooperativeRecoveryFailure( "coop-1", "o", From 8e72a8171e27aec44bdd27f3c36b2b46ff2cacd2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:13:55 +0100 Subject: [PATCH 088/154] fix: keep a valid spark exit generation going while its rebuild waits --- .../to/bitkit/repositories/SparkExitDriver.kt | 10 +++++- .../repositories/SparkExitDriverTest.kt | 33 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 6eb711cdb4..08a53faa55 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -461,7 +461,11 @@ class SparkExitDriver( Logger.info("Rebuilding Spark exit over steps the SDK could not read", context = TAG) val rebuilding = sent.copy(isRebuilding = true, unverifiedRebuiltAtHeight = tip, isRedoRebuild = false) save(rebuilding) - build(rebuilding, sdk) + val rebuilt = build(rebuilding, sdk) + // A rebuild that adopted nothing, such as one waiting for a leaf it could not read either, leaves the + // valid generation going: checked and sent every tick, and rebuilt over again once a block. + if (!rebuilt.isAdoptionPending(sent)) return rebuilt + rebuilt.copy(isRebuilding = false, retrySince = sent.retrySince, retriedAt = sent.retriedAt) } RecoveryVerdict.Done -> { // Leaves the operators moved on-chain but could not co-sign stay part of the exit, retried for a week. @@ -683,6 +687,10 @@ class SparkExitDriver( return copy(stallRebuilds = 0, stallConfirmedCount = null) } + private fun SparkExitRecord.isAdoptionPending(before: SparkExitRecord): Boolean = + isRebuilding && phase == SparkExitRecord.Phase.Running && generation == before.generation && + lostLeaves == before.lostLeaves + private fun needsUnverifiedRebuild(record: SparkExitRecord): Boolean { val height = tip ?: return false if (record.unverifiedRebuiltAtHeight == height) return false diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index dfd40137f6..3a8c450cf2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -332,6 +332,39 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(1, sdk.recoverRequests.size) } + @Test + fun `an unverified rebuild that adopts nothing keeps checking and sending the valid generation`() = test { + val unverified = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + val readable = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1")), + ), + ) + sdk.checks += check(unverified, RecoveryVerdict.Valid) + sdk.checks += check(readable, RecoveryVerdict.Valid) + sdk.preparedResponse = SparkExitFixtures.prepared( + leaves = emptyList(), + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + + var record = driver(tip = 1_000u).tick(running(unverified)) + assertFalse(record.isRebuilding) + assertFalse(record.isWaitingForLeaves) + assertEquals(1, record.generation) + + record = driver(tip = 1_001u).tick(record) + + assertEquals(2, sdk.checkedRecoveries.size) + assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }) + assertEquals(1, record.generation) + } + @Test fun `an unverified unilateral step waits while another unilateral step is ready`() = test { val recovery = SparkExitFixtures.recovery( From 2ce44ba92f5b3f0d62147fe8446fb5958ecdfa9e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:13:55 +0100 Subject: [PATCH 089/154] fix: refuse a spark send once an exit holds spark --- .../to/bitkit/repositories/SparkExitRepo.kt | 2 + .../java/to/bitkit/repositories/SparkRepo.kt | 51 +++++++++++--- .../bitkit/repositories/SparkExitRepoTest.kt | 1 + .../to/bitkit/repositories/SparkRepoTest.kt | 67 +++++++++++++++++++ 4 files changed, 113 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index f673eff8f8..33831bb39e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -743,6 +743,8 @@ class SparkExitRepo @Inject constructor( // Reconnecting for the exit disconnects Spark, which would cut a running leaf optimization short. val isCurrent = try { sparkRepo.awaitOptimizationIdle() + // A send that passed its exit check before the hold may still spend leaves: the requote comes after it. + sparkRepo.awaitSpendsIdle() // A cancel during the wait ended this exit: nothing more of the start runs, and nothing is paid. tickMutex.withLock { if (!isStarting(createdAt)) return@withLock false diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 7dadf2b50f..4948a8f4a7 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -167,6 +167,8 @@ class SparkRepo @Inject constructor( /** The SDK is swapping leaves with the operators; their value is in flight until it ends. */ private val isOptimizing = MutableStateFlow(false) + private val spendsInFlight = MutableStateFlow(0) + /** Watchers of the claims of deposits this app sent, by txid; they outlive the screens that start them. */ private val claimJobs = ConcurrentHashMap() @@ -327,6 +329,29 @@ class SparkRepo @Inject constructor( } } + /** + * Waits for the sends that passed their exit check before [holdForExit] to finish, at most [OPTIMIZATION_WAIT], so + * an exit starting quotes the leaves they leave. + */ + suspend fun awaitSpendsIdle() { + if (withTimeoutOrNull(OPTIMIZATION_WAIT) { spendsInFlight.first { it == 0 } } == null) { + Logger.warn("Gave up waiting for Spark sends in flight to end", context = TAG) + } + } + + private suspend fun spending(send: suspend () -> T): T { + spendsInFlight.update { it + 1 } + try { + return send() + } finally { + spendsInFlight.update { it - 1 } + } + } + + private fun ensureNotExiting() { + if (_state.value.isExiting) throw SparkError.SendRefused("Spark is in an emergency exit") + } + private suspend fun onOptimization(event: AutoOptimizationEvent) { when (event) { is AutoOptimizationEvent.Started, is AutoOptimizationEvent.RoundCompleted -> { @@ -411,7 +436,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { ensurePaymentDeadline(paymentDeadlineAt) if (!sparkService.isConnected) throw SparkError.SendRefused("Spark is not connected") - if (_state.value.isExiting) throw SparkError.SendRefused("Spark is in an emergency exit") + ensureNotExiting() val prepared = runSuspendCatching { sparkService.prepareSend(bolt11, amountSats) }.getOrElse { if (it.isInvoiceExpired()) throw SparkError.InvoiceExpired(it) throw SparkError.SendRefused("Spark could not prepare the payment", it) @@ -443,12 +468,18 @@ class SparkRepo @Inject constructor( val sent = try { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.coerceAtMost(Long.MAX_VALUE.toULong()).toLong()) - // The checks above and saving the hash suspend, so the deadline is checked last, before the send. - runCatching { ensurePaymentDeadline(paymentDeadlineAt) }.onFailure { - cacheStore.removeSparkSendHash(paymentHash) - throw it + spending { + // The checks above and saving the hash suspend, so the deadline and an exit that started + // meanwhile are checked last, before the send. + runCatching { + ensurePaymentDeadline(paymentDeadlineAt) + ensureNotExiting() + }.onFailure { + cacheStore.removeSparkSendHash(paymentHash) + throw it + } + runSuspendCatching { sparkService.send(prepared) } } - runSuspendCatching { sparkService.send(prepared) } } finally { sendsInFlight.remove(paymentHash.lowercase()) } @@ -690,10 +721,14 @@ class SparkRepo @Inject constructor( */ suspend fun withdrawAll(address: String, confirmedFeeSats: ULong): Result = withContext(bgDispatcher) { runSuspendCatching { - if (_state.value.isExiting) throw SparkError.SendRefused("Spark is in an emergency exit") + ensureNotExiting() val prepared = prepareWithdrawAll(address) if (prepared.feeSats() > confirmedFeeSats) throw SparkError.WithdrawalFeeChanged() - val payment = sparkService.send(prepared.response) + val payment = spending { + // Preparing suspends, so an exit can start meanwhile. + ensureNotExiting() + sparkService.send(prepared.response) + } preparedWithdrawal = null (payment.details as? PaymentDetails.Withdraw)?.txId?.let { withdrawalTxids += it } Unit diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 070a58eb0b..ebe249366f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -731,6 +731,7 @@ class SparkExitRepoTest : BaseUnitTest() { transferRepo ).createTransfer(any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) order.verify(sparkRepo).awaitOptimizationIdle() + order.verify(sparkRepo).awaitSpendsIdle() order.verify(sparkRepo).setExiting(true, true) val record = assertNotNull(sut.state.value.record) assertEquals(SparkExitRecord.PER_NODE, record.fundingStrategy) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 692de5d12d..afc8b4f672 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1257,6 +1257,73 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any()) } + @Test + fun `an exit starting while a send prepares sends nothing`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val sut = createSut() + val paused = CompletableDeferred() + val resume = CompletableDeferred() + + val result = async { + sut.payInvoice("lnbc1", 100uL, onBeforeSend = { + paused.complete(Unit) + resume.await() + true + }) + } + paused.await() + sut.holdForExit() + resume.complete(Unit) + val error = result.await().exceptionOrNull() + + verify(sparkService, never()).send(any()) + assertIs(error) + } + + @Test + fun `an exit start waits for a send already past its exit check`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val sending = CompletableDeferred() + val sent = CompletableDeferred() + whenever { sparkService.send(any()) }.doSuspendableAnswer { + sending.complete(Unit) + sent.await() + } + val sut = createSut() + val send = async { sut.payInvoice("lnbc1", 100uL) } + sending.await() + sut.holdForExit() + + val idle = async { sut.awaitSpendsIdle() } + runCurrent() + + assertFalse(idle.isCompleted) + sent.complete(sentPayment(fees = 0)) + idle.await() + send.await() + } + + @Test + fun `an exit starting while a withdrawal prepares withdraws nothing`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val sut = createSut() + whenever { sparkService.getInfo() }.thenAnswer { + sut.holdForExit() + info(10_000uL) + } + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) } + .thenReturn(withdrawal(expiresAt = now.epochSeconds.toULong() + 600uL)) + + val error = sut.withdrawAll(ADDRESS, confirmedFeeSats = 500uL).exceptionOrNull() + + verify(sparkService, never()).send(any()) + assertIs(error) + } + @Test fun `an expired invoice spark refuses is a typed refusal`() = test { whenever(sparkService.isConnected).thenReturn(true) From e4ce21810e580139e9d89e108ef300f07fc46a3f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:13:55 +0100 Subject: [PATCH 090/154] fix: open the spark exit from its notification once loaded --- .../to/bitkit/repositories/SparkExitRepo.kt | 12 ++++++--- .../java/to/bitkit/viewmodels/AppViewModel.kt | 9 ++++--- .../viewmodels/AppViewModelSendFlowTest.kt | 25 ++++++++++++++++++- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 33831bb39e..d0df6ea3e6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -148,11 +148,15 @@ class SparkExitRepo @Inject constructor( // region lifecycle - /** Loads the exit of [walletIndex] once, takes Spark off Lightning while it runs, and settles a finished one. */ - suspend fun load(walletIndex: Int = sparkRepo.walletIndex): Result = withContext(bgDispatcher) { + /** + * Loads the exit of [walletIndex], Spark's own by default, once, takes Spark off Lightning while it runs, and + * settles a finished one. + */ + suspend fun load(walletIndex: Int? = null): Result = withContext(bgDispatcher) { runSuspendCatching { - if (isLoaded && this@SparkExitRepo.walletIndex == walletIndex) return@runSuspendCatching _state.value.record - this@SparkExitRepo.walletIndex = walletIndex + val index = walletIndex ?: sparkRepo.walletIndex + if (isLoaded && this@SparkExitRepo.walletIndex == index) return@runSuspendCatching _state.value.record + this@SparkExitRepo.walletIndex = index val record = runSuspendCatching { store.load() }.getOrElse { Logger.error("Failed to read the Spark exit record", it, context = TAG) salvage() diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 8c712e8dec..183b2aba6a 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -1416,7 +1416,6 @@ class AppViewModel @Inject constructor( private fun isAutomaticPaykitWorkPaused(): Boolean = isPaymentRequestPollingStopped.value || privatePaykitRepo.isProfileDeletionInProgress.value - /** Drives a Spark emergency exit every minute while Bitkit is in the foreground. */ private val _isSparkExitRequested = MutableStateFlow(false) /** An emergency exit notification was tapped; kept until the UI opens the exit, so a cold start keeps it. */ @@ -1424,13 +1423,17 @@ class AppViewModel @Inject constructor( fun onSparkExitNotificationTapped() = _isSparkExitRequested.update { true } - /** Clears the tapped notification and says whether the exit opens on its progress rather than a new exit. */ + /** + * Says whether the exit opens on its progress rather than a new exit, then clears the tapped notification: cleared + * once nothing more suspends, as the screen that waits on it restarts and would cut the open short. + */ suspend fun onSparkExitOpened(): Boolean { - _isSparkExitRequested.update { false } sparkExitRepo.load() + _isSparkExitRequested.update { false } return sparkExitRepo.state.value.showsResult } + /** Drives a Spark emergency exit every minute while Bitkit is in the foreground. */ fun startSparkExitDriving() = sparkExitRepo.onAppForegrounded() fun stopSparkExitDriving() = sparkExitRepo.onAppBackgrounded() diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index cb1c3907bb..3bfc8c93e2 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -160,6 +160,8 @@ import to.bitkit.repositories.CurrencyRepo import to.bitkit.repositories.CurrencyState import to.bitkit.repositories.Endpoint import to.bitkit.repositories.HealthRepo +import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.IncomingPaykitPaymentRequestFailureReason import to.bitkit.repositories.LightningRepo @@ -290,6 +292,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { private val quickPayRepo = mock() private val quickPayUnhandledFailures = MutableSharedFlow(extraBufferCapacity = 8) private val transferRepo = mock() + private val sparkExitRepo = mock() private val migrationService = mock() private val coreService = mock() private val nodeServiceFgState = NodeServiceFgState() @@ -394,6 +397,26 @@ class AppViewModelSendFlowTest : BaseUnitTest() { App.currentActivity = null } + @Test + fun `a tapped exit notification stays requested until the exit loaded`() = test { + val loaded = CompletableDeferred() + whenever(sparkExitRepo.state).thenReturn(MutableStateFlow(SparkExitState())) + whenever(sparkExitRepo.load(anyOrNull())).doSuspendableAnswer { + loaded.await() + Result.success(null) + } + sut.onSparkExitNotificationTapped() + + val opened = async { sut.onSparkExitOpened() } + runCurrent() + + // Clearing it earlier recomposes the screen that waits on it, which cancels the open before it navigates. + assertTrue(sut.isSparkExitRequested.value) + loaded.complete(Unit) + assertFalse(opened.await()) + assertFalse(sut.isSparkExitRequested.value) + } + @Test fun `new USDT action waits for explicit enable and resumes exactly once`() = test { usdtEnabled.value = false @@ -975,7 +998,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { widgetsRepo = widgetsRepo, pubkyRepo = pubkyRepo, timeSource = testDispatcher.scheduler.timeSource, - sparkExitRepo = mock(), + sparkExitRepo = sparkExitRepo, ) private suspend fun emitNodeEvent( From 318d4fe35fad4342f13db106a5704021419df719 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:13:55 +0100 Subject: [PATCH 091/154] fix: keep counting what stays on spark during an exit --- .../to/bitkit/repositories/SparkExitRecord.kt | 8 ++++++++ .../to/bitkit/repositories/SparkExitRepo.kt | 9 ++++++--- .../repositories/SparkExitRecordTest.kt | 1 + .../usecases/DeriveBalanceStateUseCaseTest.kt | 19 +++++++++++++++++++ 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 2d7f9f7a57..1d4e2b4aea 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -65,6 +65,11 @@ data class SparkExitRecord( val lastBuildAt: Long? = null, /** The value of the quote's leaves, to show what Spark holds outside the exit. */ val leafTotalSats: ULong? = null, + /** + * Spark's balance beyond the quote's leaves when the exit started: what stays on Spark, also once published leaves + * left the balance. + */ + val outsideSats: ULong? = null, /** * The CPFP child and fan-out txids of replaced generations, whose outputs at the funding address are not new * funding. The name predates the fan-out ids, kept so stored records read the same. @@ -720,6 +725,7 @@ object SparkExitJson { transferId = read { o.stringOrNull("transferId") }, expectedSats = read { o.ulong("expectedSats") } ?: 0uL, leafTotalSats = read { o.ulongOrNull("leafTotalSats") }, + outsideSats = read { o.ulongOrNull("outsideSats") }, lostLeaves = read { o.arrayOrEmpty("lostLeaves").map { val l = it.jsonObject @@ -828,6 +834,7 @@ object SparkExitJson { put("isRebuilding", r.isRebuilding) r.lastBuildAt?.let { put("lastBuildAt", it) } r.leafTotalSats?.let { put("leafTotalSats", it.toLong()) } + r.outsideSats?.let { put("outsideSats", it.toLong()) } if (r.earlierCpfpTxids.isNotEmpty()) { put("earlierCpfpTxids", buildJsonArray { r.earlierCpfpTxids.forEach { add(JsonPrimitive(it)) } }) } @@ -1021,6 +1028,7 @@ object SparkExitJson { isRebuilding = o.booleanOrNull("isRebuilding") ?: false, lastBuildAt = o.millisOrNull("lastBuildAt"), leafTotalSats = o.ulongOrNull("leafTotalSats"), + outsideSats = o.ulongOrNull("outsideSats"), earlierCpfpTxids = o.arrayOrEmpty("earlierCpfpTxids").map { it.jsonPrimitive.content }, leftoverSweep = o.objectOrNull("leftoverSweep")?.let(::sweepFromJson), fundingPaymentTxid = o.stringOrNull("fundingPaymentTxid"), diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index d0df6ea3e6..a623e6a392 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -724,6 +724,7 @@ class SparkExitRepo @Inject constructor( skippedLeafCount = quote.prepared.skipped.size, fundingStrategy = SparkExitRecord.PER_NODE, leafTotalSats = quote.leafTotalSats, + outsideSats = SparkExitMath.outsideExitSats(quote.leafTotalSats, quote.sparkBalanceSats), transferId = transferId, ) // Saved with its transfer in one write, so no running exit is ever stored without the transfer counting it. A @@ -805,6 +806,7 @@ class SparkExitRepo @Inject constructor( expectedSats = fresh.incomingSats, skippedLeafCount = fresh.prepared.skipped.size, leafTotalSats = fresh.leafTotalSats, + outsideSats = SparkExitMath.outsideExitSats(fresh.leafTotalSats, fresh.sparkBalanceSats), transferId = freshTransfer, ) runCatching { saveRecord(requoted) }.onFailure { @@ -1121,13 +1123,14 @@ data class SparkExitState( val showsResult: Boolean get() = record?.showsResult == true /** - * Spark's balance beyond the quote's leaves while the exit runs: value outside the exit, which stays on Spark. A - * signal only, exact while the exit's leaves still count in the balance; published leaves leave it. + * What stays on Spark while the exit runs: Spark's balance beyond the quote's leaves, or, once published leaves + * left the balance, what the start saw beyond them, whichever is more. */ val outsideExitSats: ULong? get() { val active = record?.takeIf { it.isActive } ?: return null - return SparkExitMath.outsideExitSats(active.leafTotalSats, sparkBalanceSats) + val live = SparkExitMath.outsideExitSats(active.leafTotalSats, sparkBalanceSats) ?: 0uL + return maxOf(live, active.outsideSats ?: 0uL).takeIf { it > 0uL } } /** diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt index 2c9b64f479..5e5b861579 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -96,6 +96,7 @@ class SparkExitRecordTest { leftover = listOf(SparkExitRecord.Leftover("change", 3u, 700uL)), isRebuilding = true, leafTotalSats = 90_112uL, + outsideSats = 14_167uL, earlierCpfpTxids = listOf("child"), leftoverSweep = SparkExitRecord.LeftoverSweep( "sweep", diff --git a/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt index 438a4794e6..958ecf2d13 100644 --- a/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt +++ b/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt @@ -117,6 +117,25 @@ class DeriveBalanceStateUseCaseTest : BaseUnitTest() { assertEquals(80_000uL, balanceState.totalLightningSats) } + @Test + fun `spending keeps what stays on spark once the exit's published leaves left its balance`() = test { + newBalanceDetails() + whenever(lightningRepo.getChannels()).thenReturn(emptyList()) + // The hosted-regtest run: 14,167 sats stay on Spark, the exit's 100,000 sats of leaves are published. + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isReady = true, balanceSats = 14_167uL, isExiting = true)), + ) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(emptyList())) + sparkExitState.value = SparkExitState( + record = SparkExitFixtures.record().copy(leafTotalSats = 100_000uL, outsideSats = 14_167uL), + sparkBalanceSats = 14_167uL, + ) + + val balanceState = sut().getOrThrow() + + assertEquals(64_167uL, balanceState.totalLightningSats) + } + @Test fun `should subtract estimated fee from channelFundableBalance`() = test { val fundableBalance = 75_000uL From d5d098b77da619f4ba883e6cbd9858d146b454dd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:13:56 +0100 Subject: [PATCH 092/154] fix: stop the spark exit background job with no exit to drive --- .../main/java/to/bitkit/repositories/SparkExitRepo.kt | 11 ++++++++--- .../java/to/bitkit/repositories/SparkExitRepoTest.kt | 11 +++++++++++ 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index a623e6a392..df4ade42fc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -213,7 +213,11 @@ class SparkExitRepo @Inject constructor( runSuspendCatching { // Spark has not started in a cold background run, so its wallet index is not known yet. load(work.activeWalletIndex()).getOrThrow() - if (_state.value.record?.needsDriving != true) return@runSuspendCatching _state.value.record + if (_state.value.record?.needsDriving != true) { + // Queued for a record that could not be read, or by a tick before a wipe: nothing is left to drive. + work.cancelAll() + return@runSuspendCatching _state.value.record + } tick() if (_state.value.isExiting && !sparkService.isConnected) { // The connect keeps going past the timeout, so the next run finds Spark connecting or connected. @@ -249,9 +253,10 @@ class SparkExitRepo @Inject constructor( } } } finally { - tickMutex.unlock() - // Every tick keeps the background work queued, so one failed or skipped run never ends the chain. + // Every tick keeps the background work queued, so one failed or skipped run never ends the chain. Before + // the unlock, so a wipe waiting on the lock cancels it after. if (_state.value.record?.needsDriving == true) work.schedulePeriodic() + tickMutex.unlock() } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index ebe249366f..732697269c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -597,6 +597,17 @@ class SparkExitRepoTest : BaseUnitTest() { verify(work, never()).cancelAll() } + @Test + fun `a background run that finds no exit to drive stops the background work`() = test { + // An unreadable record schedules the work before the run finds nothing to salvage. + File(Env.sparkExitRecordPath(0)).apply { parentFile?.mkdirs() }.writeText("not json") + whenever(transferRepo.activeTransfers).thenReturn(flowOf(emptyList())) + + assertNull(createSut().runInBackground().getOrThrow()) + + verify(work).cancelAll() + } + @Test fun `a restarted exit signs with the funding key of its own record`() = test { val address = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" From 379a5dc9d1f54e2ec7639893738ef71fb5577a20 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:13:56 +0100 Subject: [PATCH 093/154] fix: show spark exit funding amounts in bitcoin --- .../settings/lightning/SparkExitComponents.kt | 25 ++++++++++++++++--- .../lightning/SparkExitFundingScreen.kt | 2 +- .../lightning/SparkExitProgressScreen.kt | 2 +- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt index a9e3452970..5cd66951e6 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -25,7 +25,10 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import breez_sdk_spark.RecoverFundsResponse import to.bitkit.R import to.bitkit.ext.ellipsisMiddle +import to.bitkit.models.BITCOIN_SYMBOL +import to.bitkit.models.PrimaryDisplay import to.bitkit.models.Toast +import to.bitkit.models.formatToModernDisplay import to.bitkit.repositories.SparkExitMath import to.bitkit.repositories.SparkExitPartialFunding import to.bitkit.repositories.SparkExitQuote @@ -66,6 +69,20 @@ internal fun SparkExitStartedEffect(viewModel: SparkExitViewModel, onStarted: () internal fun sparkExitAmountText(sats: ULong): String = rememberMoneyText(sats.toLong(), showSymbol = true)?.replace(Regex(""), "") ?: sats.toString() +/** + * An amount the user sends from another wallet, always in bitcoin: the exit needs it exact, which a fiat figure + * converted at another wallet's rate is not. + */ +@Composable +internal fun sparkExitSendAmountText(sats: ULong): String = + rememberMoneyText(sats.toLong(), unit = PrimaryDisplay.BITCOIN, showSymbol = true) + ?.replace(Regex(""), "") + ?: "$BITCOIN_SYMBOL ${sats.formatToModernDisplay()}" + +/** [sparkExitSendAmountText] marked as an inline accent. */ +@Composable +internal fun sparkExitSendAmountAccent(sats: ULong): String = "${sparkExitSendAmountText(sats)}" + /** * What Display's line height adds under a headline on Android against iOS: master's spacers under an exit headline * render 9 dp more here, so exit screens take it off and look the same on both apps. Measured on 2x media devices. @@ -136,7 +153,7 @@ internal fun SparkExitFundingAddress( ) BodyS( text = stringResource(R.string.lightning__spark_exit__fund_external_text) - .replace("{amount}", sparkExitAmountAccent(requiredSats)).withAccentBoldBright(), + .replace("{amount}", sparkExitSendAmountAccent(requiredSats)).withAccentBoldBright(), color = Colors.White64, modifier = Modifier.fillMaxWidth() ) @@ -152,9 +169,9 @@ internal fun SparkExitFundingAddress( partial?.let { BodyS( text = stringResource(R.string.lightning__spark_exit__fund_partial) - .replace("{received}", sparkExitAmountAccent(it.receivedSats)) - .replace("{required}", sparkExitAmountAccent(it.requiredSats)) - .replace("{missing}", sparkExitAmountAccent(it.missingSats)).withAccentBoldBright(), + .replace("{received}", sparkExitSendAmountAccent(it.receivedSats)) + .replace("{required}", sparkExitSendAmountAccent(it.requiredSats)) + .replace("{missing}", sparkExitSendAmountAccent(it.missingSats)).withAccentBoldBright(), color = Colors.White64, modifier = Modifier .fillMaxWidth() diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt index 7899b46242..2d32db54d1 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt @@ -81,7 +81,7 @@ private fun Content( Display(text = stringResource(R.string.lightning__spark_exit__funding_title).withAccent()) BodyM( text = stringResource(R.string.lightning__spark_exit__funding_text) - .replace("{amount}", sparkExitAmountText(fundingSats)) + .replace("{amount}", sparkExitSendAmountText(fundingSats)) .withAccentBoldBright(), color = Colors.White64, ) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 5d00ee3e09..3fd5c590d2 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -428,7 +428,7 @@ private fun progressText( is SparkExitRecord.Phase.NeedsFunding -> when (val funding = progressFunding) { // A payment that covers it waits to confirm: nothing to ask for. is SparkExitFundingState.Ask -> stringResource(R.string.lightning__spark_exit__needs_funding_text) - .replace("{amount}", sparkExitAmountText(funding.sats)) + .replace("{amount}", sparkExitSendAmountText(funding.sats)) else -> stringResource(R.string.lightning__spark_exit__progress_text) } else -> stringResource(R.string.lightning__spark_exit__progress_text) From 8931678ea563e74d014683184d2882002b1590be Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:13:56 +0100 Subject: [PATCH 094/154] fix: show a confirmed spark exit leftover sweep as sent --- .../ui/settings/lightning/SparkExitProgressScreen.kt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt index 3fd5c590d2..d967538fb1 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -340,6 +340,13 @@ private fun LeftoverNote(record: SparkExitRecord, address: String, path: String? .replace("{path}", path.orEmpty()).withAccentBoldBright(), color = Colors.White64, ) + // A sweep that confirmed reached savings: sent, no longer sending. + sweep?.txid != null && sweep.isConfirmed -> SparkExitTxNote( + text = stringResource(R.string.lightning__spark_exit__leftover_swept) + .replace("{amount}", sparkExitAmountAccent(sweep.valueSats)), + txid = sweep.txid, + testTag = "SparkExitLeftoverSwept", + ) // Its txid shows once the network accepted the sweep, as it may never go out before that. sweep?.txid != null && sweep.isAccepted -> SparkExitTxNote( text = stringResource(R.string.lightning__spark_exit__leftover_sending) From 345d0532ffb42d17eec39440bfb33c5145444723 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:13:56 +0100 Subject: [PATCH 095/154] docs: point the exit journey at its ios twin --- journeys/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/journeys/README.md b/journeys/README.md index 5dd68684c8..87601f5d1a 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -199,7 +199,7 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `backup/confirm-mnemonic-clear-wrong-word.xml` | not ported — `BackupConfirmMnemonic.swift` clears only the last word by its chip, with no red-word tap | | `coin-selection/manual-coin-selection-load.xml` | not ported — iOS has `SendUtxoSelectionView` but no load error, retry or identifiers to assert on | | `transfer/spending-confirm-amount-change.xml` | same file — both platforms show the same "Fees changed" info toast; closing the received sheet re-sizes iOS's Spending Confirm, so the lower amounts can show before the swipe | -| `transfer/spark-emergency-exit.xml` | not ported yet — iOS ships the same screens and identifiers in synonymdev/bitkit-ios#1128, without a journey | +| `transfer/spark-emergency-exit.xml` | not ported yet — iOS ships the same screens and identifiers in synonymdev/bitkit-ios#1217, without a journey | | `transfer/savings-select-funds.xml` | same file and steps — iOS runs it as J8 on synonymdev/bitkit-ios#1128 | | — | `hardware-wallet/transfer-to-spending-over-max.xml` exists only on iOS | From 66c5f7069c68908278d041666006223494ae7c45 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:14:21 +0100 Subject: [PATCH 096/154] test: order the spark exit imports of the app view model test --- .../java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 3bfc8c93e2..6f957699c7 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -160,8 +160,6 @@ import to.bitkit.repositories.CurrencyRepo import to.bitkit.repositories.CurrencyState import to.bitkit.repositories.Endpoint import to.bitkit.repositories.HealthRepo -import to.bitkit.repositories.SparkExitRepo -import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.HwWalletRepo import to.bitkit.repositories.IncomingPaykitPaymentRequestFailureReason import to.bitkit.repositories.LightningRepo @@ -215,6 +213,8 @@ import to.bitkit.repositories.QuickPayRepo import to.bitkit.repositories.SamRockRepo import to.bitkit.repositories.SettledReceiveAddress import to.bitkit.repositories.SettledReceiveInvoice +import to.bitkit.repositories.SparkExitRepo +import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.TransferRepo import to.bitkit.repositories.UsdtPreferencesRepo import to.bitkit.repositories.UsdtRepo From dee1db56a880e0148604deee55d8895bbd6d5a29 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 11:19:14 +0100 Subject: [PATCH 097/154] fix: resume a valid spark exit generation after a killed rebuild --- app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt | 3 ++- .../test/java/to/bitkit/repositories/SparkExitDriverTest.kt | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 08a53faa55..9284524038 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -460,7 +460,8 @@ class SparkExitDriver( // A check cannot settle a step the SDK could not read; a fresh build reads the chain again. Logger.info("Rebuilding Spark exit over steps the SDK could not read", context = TAG) val rebuilding = sent.copy(isRebuilding = true, unverifiedRebuiltAtHeight = tip, isRedoRebuild = false) - save(rebuilding) + // Saved as the valid generation: a run killed during the rebuild goes on sending it. + save(rebuilding.copy(isRebuilding = false)) val rebuilt = build(rebuilding, sdk) // A rebuild that adopted nothing, such as one waiting for a leaf it could not read either, leaves the // valid generation going: checked and sent every tick, and rebuilt over again once a block. diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 3a8c450cf2..c335079942 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -354,6 +354,8 @@ class SparkExitDriverTest : BaseUnitTest() { ) var record = driver(tip = 1_000u).tick(running(unverified)) + // A run killed during the rebuild resumes the valid generation, not a rebuild only the SDK moves on from. + assertFalse(saved.first().isRebuilding) assertFalse(record.isRebuilding) assertFalse(record.isWaitingForLeaves) assertEquals(1, record.generation) From 72b82214d1b981a9edac49e7fc5c7f355b75e019 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:18:53 +0100 Subject: [PATCH 098/154] fix: refuse a spark exit start while a send is still active A send still active after the two-minute wait now fails the start before its record is saved: the transfer is settled, Spark is released, and the user can start again once the send ended. The wait moved ahead of the record save, so no exit goes ahead while a send can spend its leaves. --- .../to/bitkit/repositories/SparkExitRepo.kt | 8 ++++-- .../java/to/bitkit/repositories/SparkRepo.kt | 6 ++-- .../bitkit/repositories/SparkExitRepoTest.kt | 28 ++++++++++++++++++- .../to/bitkit/repositories/SparkRepoTest.kt | 26 +++++++++++++++++ 4 files changed, 63 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index df4ade42fc..81c7dfce99 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -715,6 +715,12 @@ class SparkExitRepo @Inject constructor( val transferId = transferRepo.createTransfer(TransferType.SPARK_EXIT, quote.incomingSats.toLong()) .onFailure { sparkRepo.releaseExitHold() } .getOrThrow() + // A send that passed its exit check before the hold may still spend leaves. One still sending after the wait + // refuses the start before anything is saved, so the user starts again once it ended. + runCatching { sparkRepo.awaitSpendsIdle() }.onFailure { + withContext(NonCancellable) { transferRepo.markSettled(transferId) } + sparkRepo.releaseExitHold() + }.getOrThrow() var record = SparkExitRecord( network = network, createdAt = clock.nowMs(), @@ -753,8 +759,6 @@ class SparkExitRepo @Inject constructor( // Reconnecting for the exit disconnects Spark, which would cut a running leaf optimization short. val isCurrent = try { sparkRepo.awaitOptimizationIdle() - // A send that passed its exit check before the hold may still spend leaves: the requote comes after it. - sparkRepo.awaitSpendsIdle() // A cancel during the wait ended this exit: nothing more of the start runs, and nothing is paid. tickMutex.withLock { if (!isStarting(createdAt)) return@withLock false diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 6b80fed44a..0eda3d9ef3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -330,12 +330,14 @@ class SparkRepo @Inject constructor( } /** - * Waits for the sends that passed their exit check before [holdForExit] to finish, at most [OPTIMIZATION_WAIT], so - * an exit starting quotes the leaves they leave. + * Waits for the sends that passed their exit check before [holdForExit] to finish, so an exit starting quotes the + * leaves they leave. Fails with [SparkExitError] when one is still sending after [OPTIMIZATION_WAIT]: the exit must + * not start while a send can still spend its leaves. */ suspend fun awaitSpendsIdle() { if (withTimeoutOrNull(OPTIMIZATION_WAIT) { spendsInFlight.first { it == 0 } } == null) { Logger.warn("Gave up waiting for Spark sends in flight to end", context = TAG) + throw SparkExitError("A Spark payment is still sending") } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 732697269c..7441d25dd1 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -741,8 +741,8 @@ class SparkExitRepoTest : BaseUnitTest() { order.verify( transferRepo ).createTransfer(any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull()) - order.verify(sparkRepo).awaitOptimizationIdle() order.verify(sparkRepo).awaitSpendsIdle() + order.verify(sparkRepo).awaitOptimizationIdle() order.verify(sparkRepo).setExiting(true, true) val record = assertNotNull(sut.state.value.record) assertEquals(SparkExitRecord.PER_NODE, record.fundingStrategy) @@ -755,6 +755,32 @@ class SparkExitRepoTest : BaseUnitTest() { sut.onAppBackgrounded() } + @Test + fun `a start refused while a spark send is still active saves nothing and can be retried`() = test { + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + var isSending = true + whenever(sparkRepo.awaitSpendsIdle()).doSuspendableAnswer { + if (isSending) throw SparkExitError("A Spark payment is still sending") + } + + val error = sut.start(fundFromSavings = false).exceptionOrNull() + + assertIs(error) + assertNull(sut.state.value.record) + assertNull(createSut().load(0).getOrThrow(), "no exit starts while a send can still spend its leaves") + verify(transferRepo).markSettled("transfer-1") + verify(sparkRepo).releaseExitHold() + verify(sparkRepo, never()).awaitOptimizationIdle() + verify(sparkRepo, never()).setExiting(any(), any()) + + isSending = false + sut.start(fundFromSavings = false).getOrThrow() + + assertEquals("transfer-2", sut.state.value.record?.transferId) + sut.onAppBackgrounded() + } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a start killed before its transfer is written leaves no exit to resume`() = test { diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 9a1bc27a50..3b1ad19081 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1308,6 +1308,32 @@ class SparkRepoTest : BaseUnitTest() { send.await() } + @Test + fun `an exit start is refused while a send stays active past the wait`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = prepared(feeSats = 0uL) + whenever { sparkService.prepareSend(any(), anyOrNull(), anyOrNull()) }.thenReturn(prepared) + val sending = CompletableDeferred() + val sent = CompletableDeferred() + whenever { sparkService.send(any()) }.doSuspendableAnswer { + sending.complete(Unit) + sent.await() + } + val sut = createSut() + val send = async { sut.payInvoice("lnbc1", 100uL) } + sending.await() + sut.holdForExit() + + val idle = async { runCatching { sut.awaitSpendsIdle() } } + advanceTimeBy(2.minutes + 1.seconds) + runCurrent() + + assertTrue(idle.isCompleted) + assertIs(idle.await().exceptionOrNull()) + sent.complete(sentPayment(fees = 0)) + send.await() + } + @Test fun `an exit starting while a withdrawal prepares withdraws nothing`() = test { whenever(sparkService.isConnected).thenReturn(true) From 2d160e7e8af5790bddf1a4e75ec35d1c2a12f28f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:19:06 +0100 Subject: [PATCH 099/154] docs: record the ported ios spark exit journey synonymdev/bitkit-ios#1217 carries the same transfer/spark-emergency-exit.xml, so the parity row records it as ported. --- journeys/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/journeys/README.md b/journeys/README.md index 87601f5d1a..823789ce2f 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -199,7 +199,7 @@ Known differences in the corpus, as of the iOS port (synonymdev/bitkit-ios#691): | `backup/confirm-mnemonic-clear-wrong-word.xml` | not ported — `BackupConfirmMnemonic.swift` clears only the last word by its chip, with no red-word tap | | `coin-selection/manual-coin-selection-load.xml` | not ported — iOS has `SendUtxoSelectionView` but no load error, retry or identifiers to assert on | | `transfer/spending-confirm-amount-change.xml` | same file — both platforms show the same "Fees changed" info toast; closing the received sheet re-sizes iOS's Spending Confirm, so the lower amounts can show before the swipe | -| `transfer/spark-emergency-exit.xml` | not ported yet — iOS ships the same screens and identifiers in synonymdev/bitkit-ios#1217, without a journey | +| `transfer/spark-emergency-exit.xml` | same file, ported in synonymdev/bitkit-ios#1217 — same steps and identifiers; only the description differs, naming the iOS unit tests and the Background App Refresh, Low Power Mode and notification notes in place of Android's battery notes | | `transfer/savings-select-funds.xml` | same file and steps — iOS runs it as J8 on synonymdev/bitkit-ios#1128 | | — | `hardware-wallet/transfer-to-spending-over-max.xml` exists only on iOS | From c2a663f6faf631b9eee7bc6928b6c859dc7c88fd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:30:59 +0100 Subject: [PATCH 100/154] fix: keep sending a valid spark exit generation while its rebuild asks for funding An unverified rebuild that needs more fee funding left isRebuilding set, so neither the foreground nor the keyless pass sent the still-valid generation until the user paid. It now clears isRebuilding, as a fee bump does, so driveWhileFunding keeps sending it. --- .../to/bitkit/repositories/SparkExitDriver.kt | 19 ++++++++++-- .../repositories/SparkExitDriverTest.kt | 31 +++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 9284524038..4852a0d3af 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -197,7 +197,15 @@ class SparkExitDriver( return record.copy(funding = funding) } - private suspend fun build(start: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { + /** + * Builds [start]'s leaves as a new generation. With [isUnverifiedRebuild], the generation it rebuilds over is still + * valid: a build that asks for more fee funding keeps sending it while the top-up waits. + */ + private suspend fun build( + start: SparkExitRecord, + sdk: SparkExitRecovering, + isUnverifiedRebuild: Boolean = false, + ): SparkExitRecord { // A build waiting for a leaf that may still move tries again only at its paced heights, or once its wait ends. val since = start.retrySince if (since != null && tip != null && !SparkExitMath.isRetryDue(since, start.retriedAt, tip) && @@ -245,7 +253,12 @@ class SparkExitDriver( return record.leaveBehind(refusal.leafId, refusal.reason).copy(isRebuilding = true, lastBuildAt = null) } if (it !is SdkException.InsufficientCpfpFunds) throw it - return askForFunding(record, it) + val asked = askForFunding(record, it) + // Like a fee bump's, the valid generation keeps going while the funding it asks for comes. + if (isUnverifiedRebuild && asked.phase is SparkExitRecord.Phase.NeedsFunding) { + return asked.copy(isRebuilding = false) + } + return asked } if (built.transactions.isEmpty()) { // A build of only cooperative leaves the operators could not co-sign is kept, a rebuild's too: they are @@ -462,7 +475,7 @@ class SparkExitDriver( val rebuilding = sent.copy(isRebuilding = true, unverifiedRebuiltAtHeight = tip, isRedoRebuild = false) // Saved as the valid generation: a run killed during the rebuild goes on sending it. save(rebuilding.copy(isRebuilding = false)) - val rebuilt = build(rebuilding, sdk) + val rebuilt = build(rebuilding, sdk, isUnverifiedRebuild = true) // A rebuild that adopted nothing, such as one waiting for a leaf it could not read either, leaves the // valid generation going: checked and sent every tick, and rebuilt over again once a block. if (!rebuilt.isAdoptionPending(sent)) return rebuilt diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index c335079942..058459e49b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -367,6 +367,37 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(1, record.generation) } + @Test + fun `an unverified rebuild that needs more fee funding keeps sending the valid generation`() = test { + val unverified = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + val readable = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1")), + ), + ) + sdk.checks += check(unverified, RecoveryVerdict.Valid) + sdk.checks += check(readable, RecoveryVerdict.Valid) + sdk.recoverError = SdkException.InsufficientCpfpFunds(30_000uL, "") + + var record = driver(tip = 1_000u).tick(running(unverified)) + + assertIs(record.phase) + assertFalse(record.isRebuilding) + assertTrue(record.isDrivingWhileFunding, "the valid generation stops going while the top-up waits") + assertEquals(1, record.generation) + + record = driver(tip = 1_001u).tick(record) + + assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }) + assertEquals(1, record.generation) + } + @Test fun `an unverified unilateral step waits while another unilateral step is ready`() = test { val recovery = SparkExitFixtures.recovery( From 124d6617097cc7b70a43147e1221cafeac870b04 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:31:00 +0100 Subject: [PATCH 101/154] fix: leave lost leaves out of what stays on spark during an exit The start and the requote saved Spark's balance beyond the exit's leaves with the lost leaves Spark still counts, so Spending kept them after Spark dropped them. SparkExitQuote.outsideSats now subtracts them. --- .../bitkit/repositories/SparkExitFunding.kt | 9 ++++++ .../to/bitkit/repositories/SparkExitRepo.kt | 4 +-- .../bitkit/repositories/SparkExitRepoTest.kt | 29 ++++++++++++++++++- 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 14c3808670..d197f16fb1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -109,6 +109,15 @@ data class SparkExitQuote( */ val unexitableSats: ULong? get() = SparkExitMath.unexitableSats(sparkBalanceSats, this) + /** + * What stays on Spark once the exit took its leaves: Spark's balance beyond them, skipped leaves included, less the + * lost leaves it still counts until a sync drops them. Null when nothing. + */ + val outsideSats: ULong? + get() = SparkExitMath.outsideExitSats(leafTotalSats, sparkBalanceSats) + ?.let { SparkExitMath.beyondLostLeaves(it, lostLeafSats) } + ?.takeIf { it > 0uL } + /** Spark's balance beyond every leaf the quote lists, skipped ones included, less the lost leaves it holds. */ val beyondLeavesSats: ULong? get() { diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 81c7dfce99..1f6eb5b86d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -735,7 +735,7 @@ class SparkExitRepo @Inject constructor( skippedLeafCount = quote.prepared.skipped.size, fundingStrategy = SparkExitRecord.PER_NODE, leafTotalSats = quote.leafTotalSats, - outsideSats = SparkExitMath.outsideExitSats(quote.leafTotalSats, quote.sparkBalanceSats), + outsideSats = quote.outsideSats, transferId = transferId, ) // Saved with its transfer in one write, so no running exit is ever stored without the transfer counting it. A @@ -815,7 +815,7 @@ class SparkExitRepo @Inject constructor( expectedSats = fresh.incomingSats, skippedLeafCount = fresh.prepared.skipped.size, leafTotalSats = fresh.leafTotalSats, - outsideSats = SparkExitMath.outsideExitSats(fresh.leafTotalSats, fresh.sparkBalanceSats), + outsideSats = fresh.outsideSats, transferId = freshTransfer, ) runCatching { saveRecord(requoted) }.onFailure { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 7441d25dd1..7e134cc178 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -5,10 +5,14 @@ import breez_sdk_spark.CooperativeRecoveryError import breez_sdk_spark.CooperativeRecoveryFailure import breez_sdk_spark.CpfpFundingStrategy import breez_sdk_spark.ExitTransactionStatus +import breez_sdk_spark.RecoverFundsLeaf +import breez_sdk_spark.RecoveryMethod import breez_sdk_spark.RecoveryRedoReason import breez_sdk_spark.RecoveryTxKind import breez_sdk_spark.RecoveryVerdict import breez_sdk_spark.SdkException +import breez_sdk_spark.SkippedLeaf +import breez_sdk_spark.SkippedLeafReason import com.synonym.bitkitcore.FeeRates import com.synonym.bitkitcore.GetAddressResponse import com.synonym.bitkitcore.OnchainActivity @@ -78,10 +82,11 @@ class SparkExitRepoTest : BaseUnitTest() { private val transferRepo = mock() private val wiped = MutableSharedFlow(extraBufferCapacity = 1) + private val sparkState = MutableStateFlow(SparkState()) private val sparkRepo = mock { on { walletWiped } doReturn wiped on { walletIndex } doReturn 0 - on { state } doReturn MutableStateFlow(SparkState()) + on { state } doReturn sparkState } private val work = mock() @@ -781,6 +786,28 @@ class SparkExitRepoTest : BaseUnitTest() { sut.onAppBackgrounded() } + @Test + fun `a start saves what stays on spark without the lost leaves spark still counts`() = test { + SparkExitLostLeafStore(File(Env.sparkExitLostLeavesPath(0))).add(listOf("leaf-lost")) + val dust = listOf(SkippedLeaf("dust", 1_696uL, SkippedLeafReason.FeeExceedsValue)) + val sdk = FakeSparkExitRecovering() + sdk.preparedResponses += SparkExitFixtures.prepared(skipped = dust).let { + it.copy(leaves = it.leaves + RecoverFundsLeaf("leaf-lost", 32_768uL, RecoveryMethod.UNILATERAL)) + } + sdk.preparedResponse = SparkExitFixtures.prepared(skipped = dust) + sparkState.value = SparkState(balanceSats = 134_464uL) + val sut = quotedSut(sdk) + val quote = sut.loadQuote().getOrThrow() + assertEquals(100_000uL, quote.leafTotalSats) + assertEquals(listOf(32_768uL), quote.lostLeafSats) + + sut.start(fundFromSavings = false).getOrThrow() + // Stops the foreground ticks first, so a failed assertion ends the test. + sut.onAppBackgrounded() + + assertEquals(1_696uL, sut.state.value.record?.outsideSats) + } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a start killed before its transfer is written leaves no exit to resume`() = test { From c92648ebfb2c507fe173ebb490e4c007fc654b99 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:31:00 +0100 Subject: [PATCH 102/154] fix: forget a spark exit start once its exit ends A start no exit screen showed kept isStarted set after a cancel or after the exit ended, so the next exit's Quote opened Progress. The flag now lasts only while the exit runs. --- .../settings/lightning/SparkExitViewModel.kt | 2 + .../lightning/SparkExitViewModelTest.kt | 37 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index f37787e363..e5d7b4e8c7 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -84,6 +84,8 @@ class SparkExitViewModel @Inject constructor( private fun showExit(exit: SparkExitState, balanceSats: ULong) { _uiState.update { it.copy( + // A start no screen showed is forgotten once its exit ended, a cancel too: the next exit starts anew. + isStarted = it.isStarted && exit.isExiting, record = exit.record, tipHeight = exit.tipHeight, fundingSeenSats = exit.fundingSeenSats, diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index dd3c36fcd6..bbea6691ff 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -7,6 +7,7 @@ import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.doReturn +import org.mockito.kotlin.doSuspendableAnswer import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify @@ -14,6 +15,7 @@ import org.mockito.kotlin.whenever import to.bitkit.models.FeeRate import to.bitkit.repositories.OnchainSendChangedError import to.bitkit.repositories.OnchainSendNotDispatchedError +import to.bitkit.repositories.SparkExitCancel import to.bitkit.repositories.SparkExitFeeBumpOption import to.bitkit.repositories.SparkExitFixtures import to.bitkit.repositories.SparkExitFundingState @@ -75,6 +77,41 @@ class SparkExitViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.isStarted) } + @Test + fun `a start no screen showed is forgotten once its exit ends`() = test { + whenever(repo.start(any())).thenReturn(Result.success(Unit)) + exitState.value = SparkExitState(record = SparkExitFixtures.record(SparkExitRecord.Phase.Running)) + val sut = SparkExitViewModel(mock(), repo, sparkRepo) + + // The user left the exit screens while the start ran: nothing calls onStartShown. + sut.start() + assertTrue(sut.uiState.value.isStarted) + + exitState.value = SparkExitState() + + assertFalse(sut.uiState.value.isStarted, "the next exit's Quote screen would jump to Progress") + } + + @Test + fun `cancelling an exit whose savings funding failed leaves no start for the next exit`() = test { + // The exit started, but paying its fee funding failed before it was submitted. + whenever(repo.start(any())).thenReturn(Result.failure(IllegalStateException("Savings payment failed"))) + exitState.value = SparkExitState(record = SparkExitFixtures.record()) + val sut = SparkExitViewModel(mock(), repo, sparkRepo) + + // Progress was opened directly, so no screen consumes the start. + sut.start() + assertTrue(sut.uiState.value.isStarted) + // The repo deletes the record of a cancelled exit nothing paid into. + whenever(repo.cancel()).doSuspendableAnswer { + exitState.value = SparkExitState() + Result.success(SparkExitCancel.Cancelled) + } + sut.cancel() + + assertFalse(sut.uiState.value.isStarted, "the next exit's Quote screen would jump to Progress") + } + @Test fun `funding from another wallet continues only once the address holds what the quote asks`() { val quote = SparkExitQuote(SparkExitFixtures.prepared(funding = 20_000uL)) From 1eaf8037a4811ae9719c7abbd03c677f63067d0f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:33:05 +0100 Subject: [PATCH 103/154] fix: keep a valid spark exit generation over a failed-only unverified rebuild An unverified rebuild that skipped the leaf it could not read and built only failed cooperative leaves was adopted, dropping that leaf's signed steps while the failed leaves were retried for about 1008 blocks. build no longer adopts it, before anything is saved, so the valid generation keeps being checked and sent. --- .../to/bitkit/repositories/SparkExitDriver.kt | 11 ++++-- .../repositories/SparkExitDriverTest.kt | 38 +++++++++++++++++++ 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 4852a0d3af..01415f22e3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -199,7 +199,9 @@ class SparkExitDriver( /** * Builds [start]'s leaves as a new generation. With [isUnverifiedRebuild], the generation it rebuilds over is still - * valid: a build that asks for more fee funding keeps sending it while the top-up waits. + * valid and stays the exit's, sent every tick, unless the build replaces it with signed steps: a build that asks + * for more fee funding keeps sending it while the top-up waits, and one of only failed cooperative leaves beside a + * leaf it could not read is not adopted. */ private suspend fun build( start: SparkExitRecord, @@ -264,8 +266,11 @@ class SparkExitDriver( // A build of only cooperative leaves the operators could not co-sign is kept, a rebuild's too: they are // retried for a week like any failed leaf, then let go. if (built.failed.isNotEmpty()) { - val adopted = record.adopt(built, nowMillis()) - .copy(waitingLeafIds = waitingLeafIds(record, prepared.skipped, stopped)) + val waiting = waitingLeafIds(record, prepared.skipped, stopped) + // Adopted, it would drop the signed steps of the leaf it could not read for the week the failed + // leaves are retried, past the window in which they are ours to publish. + if (isUnverifiedRebuild && waiting.isNotEmpty()) return record + val adopted = record.adopt(built, nowMillis()).copy(waitingLeafIds = waiting) save(adopted) Logger.info("Built Spark exit of only '${built.failed.size}' failed cooperative leaves", context = TAG) return adopted diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 058459e49b..e52f7809c9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -398,6 +398,44 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(1, record.generation) } + @Test + fun `an unverified rebuild of only failed cooperative leaves keeps the valid generation`() = test { + val failed = CooperativeRecoveryFailure( + "coop-1", + "o", + 0u, + CooperativeRecoveryError.OperatorsUnavailable("down"), + ) + val unverified = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + failed = listOf(failed), + ) + val readable = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1")), + ), + failed = listOf(failed), + ) + sdk.checks += check(unverified, RecoveryVerdict.Valid) + sdk.checks += check(readable, RecoveryVerdict.Valid) + sdk.preparedResponse = coopLeaf(16_384uL).copy( + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + repeat(2) { sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = listOf(failed)) } + val start = running(unverified).copy(leafIds = listOf("leaf-1", "coop-1")) + + var record = driver(tip = 1_000u).tick(start) + assertEquals(1, record.generation, "rebuild adopted a recovery without leaf-1's signed steps") + assertTrue(saved.none { it.generation != 1 }, "a killed run would resume the recovery without leaf-1") + + record = driver(tip = 1_001u).tick(record) + assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }, "leaf-1's matured step n2 was not sent") + } + @Test fun `an unverified unilateral step waits while another unilateral step is ready`() = test { val recovery = SparkExitFixtures.recovery( From 6bcd3562eac3fdf80c2c97a88e9e413865ba2f05 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:41:38 +0100 Subject: [PATCH 104/154] fix: read a spark exit step already in the utxo set as accepted Esplora hosts answer a step that already confirmed with Core's plain-text 'RPC error -27: Transaction outputs already in utxo set', which the classifier read as a refusal. --- .../main/java/to/bitkit/repositories/SparkExitChain.kt | 10 ++++++++-- .../java/to/bitkit/repositories/SparkExitChainTest.kt | 9 +++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index a849ed10a0..08b8f8e2c5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -322,6 +322,8 @@ object SparkExitBroadcastClassifier { "txn-already-known", "txn-same-nonwitness-data-in-mempool", "already in block chain", + // Core's newer wording, which esplora hosts pass on as plain text. + "already in utxo set", ) private val notMatureMessages = listOf("non-BIP68-final", "non-final") private val inputsMissingMessages = listOf("bad-txns-inputs-missingorspent", "missing-inputs", "missingorspent") @@ -441,6 +443,10 @@ object SparkExitBroadcastClassifier { private const val MAX_REASON_LENGTH = 200 - /** The RPC code, also when the node's error sits JSON-escaped inside mempool's own error object. */ - private fun hasRpcCode(code: Int, text: String) = Regex("""code\\?"\s*:\s*$code\b""").containsMatchIn(text) + /** + * The RPC code, also when the node's error sits JSON-escaped inside mempool's own error object, or as esplora's + * plain text (`sendrawtransaction RPC error -27: …`). + */ + private fun hasRpcCode(code: Int, text: String) = + Regex("""(code\\?"\s*:\s*|RPC error )$code\b""").containsMatchIn(text) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt index d179c733d3..20423a5744 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -233,6 +233,15 @@ class SparkExitChainTest : BaseUnitTest() { assertTrue(reason.length <= 200) } + @Test + fun `a step esplora reports already in the utxo set is accepted`() { + val classifier = SparkExitBroadcastClassifier + val text = "sendrawtransaction RPC error -27: Transaction outputs already in utxo set" + assertEquals(SparkExitBroadcastOutcome.Accepted, classifier.single(400, text)) + val codeOnly = "sendrawtransaction RPC error -27: unknown" + assertEquals(SparkExitBroadcastOutcome.Accepted, classifier.classify(codeOnly)) + } + @Test fun `classifies node answers`() { val failedPackage = """{"package_msg":"transaction failed","tx-results":""" From f723f4efcab9dddde69c466b8e19e458202968c8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:43:53 +0100 Subject: [PATCH 105/154] fix: stop sending a spark exit generation that diverged during a top-up A Redo while a higher fee's payment confirmed kept the record driving while funding, so the keyless pass and the step reminders went on with the diverged generation. It now marks the record as a Redo rebuild that waits for the funding. --- .../to/bitkit/repositories/SparkExitDriver.kt | 8 ++++++-- .../bitkit/repositories/SparkExitDriverTest.kt | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 01415f22e3..8f17a95307 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -433,8 +433,12 @@ class SparkExitDriver( // Finished before the higher fee was needed: running again, the next check ends it and the payment goes // back with the leftover. RecoveryVerdict.Done -> updated.copy(phase = SparkExitRecord.Phase.Running) - // A rebuild waits for the funding it was paid for. - is RecoveryVerdict.Redo -> updated + // The diverged generation is never sent again: its rebuild, a Redo one, waits for the funding it was paid + // for. + is RecoveryVerdict.Redo -> { + Logger.warn("Spark exit diverged on-chain while a top-up is awaited", context = TAG) + updated.copy(isRebuilding = true, isRedoRebuild = true) + } } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index e52f7809c9..056beceb02 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1054,6 +1054,23 @@ class SparkExitDriverTest : BaseUnitTest() { assertTrue(saved.isEmpty()) } + @Test + fun `a generation that diverges while a higher fee's payment confirms is never sent again`() = test { + val diverged = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + var record = funded(running(diverged)).applyFeeBump(rate = 9uL, extraSats = 6_612uL, paymentTxid = "bump") + assertTrue(record.isDrivingWhileFunding) + sdk.checks += check(diverged, redo) + + record = driver().tick(record) + + assertIs(record.phase) + assertTrue(record.isRebuilding) + assertTrue(record.isRedoRebuild) + assertFalse(record.isDrivingWhileFunding, "the diverged generation keeps being sent") + record = driver(withSdk = false).tick(record) + assertTrue(chain.broadcasts.isEmpty()) + } + @Test fun `a paid higher fee rebuilds at the new rate once its payment confirms`() = test { var record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) From caa349d4b0506e36cfe5b5e1f3258fc0312553f6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:47:35 +0100 Subject: [PATCH 106/154] fix: count left-behind leaves on spark, not in the exit transfer Leaves a build left behind stay on Spark, but inTransferSats kept counting them as on their way to savings for the whole exit. They now leave the transfer and count in what stays on Spark. --- .../java/to/bitkit/repositories/SparkExitFunding.kt | 2 +- .../java/to/bitkit/repositories/SparkExitRepo.kt | 8 ++++++-- .../to/bitkit/repositories/SparkExitFundingTest.kt | 13 +++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index d197f16fb1..1588597ebf 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -309,7 +309,7 @@ object SparkExitMath { */ fun staysOnSparkSats(balanceSats: ULong?, record: SparkExitRecord?): ULong? { val leafTotal = record?.leafTotalSats ?: return null - val liveLeafTotal = if (leafTotal > record.lostSats) leafTotal - record.lostSats else 0uL + val liveLeafTotal = (leafTotal.safe() - record.lostSats.safe()).safe() - record.leftBehindLeafSats.safe() val beyond = outsideExitSats(liveLeafTotal, balanceSats) ?: return null return beyondLostLeaves(beyond, record.lostLeaves.map { it.valueSats }).takeIf { it > 0uL } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 1f6eb5b86d..e2d021d61c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -1138,7 +1138,9 @@ data class SparkExitState( val outsideExitSats: ULong? get() { val active = record?.takeIf { it.isActive } ?: return null - val live = SparkExitMath.outsideExitSats(active.leafTotalSats, sparkBalanceSats) ?: 0uL + // A leaf the exit left behind stays on Spark, so it counts here, not in the transfer. + val exitLeafSats = active.leafTotalSats?.let { it.safe() - active.leftBehindLeafSats.safe() } + val live = SparkExitMath.outsideExitSats(exitLeafSats, sparkBalanceSats) ?: 0uL return maxOf(live, active.outsideSats ?: 0uL).takeIf { it > 0uL } } @@ -1158,6 +1160,8 @@ data class SparkExitState( ?.takeIf { exit.fundingPaymentTxid == null } ?.let { it.requiredSats.safe() - maxOf(exit.fundedSats, fundingSeenSats).safe() } ?: 0uL - return ((exit.expectedSats.safe() - received.safe()).safe() - unpaid.safe()).safe() - exit.lostSats.safe() + // A leaf the exit left behind stays on Spark. + val notComing = exit.lostSats.safe() + exit.leftBehindLeafSats.safe() + return ((exit.expectedSats.safe() - received.safe()).safe() - unpaid.safe()).safe() - notComing.safe() } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 9bdcb886a4..889fe9beae 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -203,6 +203,19 @@ class SparkExitFundingTest { assertEquals(50_000uL, SparkExitState(record = record).inTransferSats) } + @Test + fun `a leaf the exit left behind leaves the transfer`() { + val record = SparkExitFixtures.record(SparkExitRecord.Phase.Running) + .copy(expectedSats = 150_000uL, leafIds = listOf("leaf-1", "leaf-2"), leafTotalSats = 108_192uL) + .adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))), 1L) + .copy(leftBehindLeaves = listOf(SparkExitRecord.LeftBehindLeaf("leaf-2", 8_192uL, "its refund cannot pay"))) + val state = SparkExitState(record = record, sparkBalanceSats = 108_192uL) + + assertEquals(141_808uL, state.inTransferSats, "the leaf stays on Spark") + assertEquals(8_192uL, state.outsideExitSats, "Spending counts the leaf that stays on Spark") + assertEquals(8_192uL, SparkExitMath.staysOnSparkSats(108_192uL, record)) + } + @Test fun `a wait for a leaf that may still move tries again at doubling gaps up to a day and ends after a week`() { assertFalse(SparkExitMath.isRetryDue(since = 1_000u, retriedAt = 1_000u, tip = 1_005u)) From 8de5af3a2e35449b267c9997b2bbf8e7bf79953a Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:51:52 +0100 Subject: [PATCH 107/154] fix: keep the value of leaves the first spark exit build leaves behind leaveBehind priced a leaf from the current recovery, which the first build out of AwaitingFunding does not have yet, so such a leaf was recorded at 0 sats and Progress hid its line. The record now keeps each quoted leaf's value. --- .../to/bitkit/repositories/SparkExitFunding.kt | 3 +++ .../to/bitkit/repositories/SparkExitRecord.kt | 15 +++++++++++++-- .../java/to/bitkit/repositories/SparkExitRepo.kt | 2 ++ .../to/bitkit/repositories/SparkExitRepoTest.kt | 15 +++++++++++++++ 4 files changed, 33 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 1588597ebf..a9690ac63a 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -100,6 +100,9 @@ data class SparkExitQuote( val leafIds: List get() = prepared.leaves.map { it.leafId } + /** Each listed leaf's value, kept with the exit for a leaf its first build leaves behind. */ + val leafSats: Map get() = prepared.leaves.associate { it.leafId to it.valueSats } + /** The value of the leaves the quote lists, which the exit takes on-chain. */ val leafTotalSats: ULong get() = prepared.leaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 1d4e2b4aea..8b58401287 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -118,6 +118,8 @@ data class SparkExitRecord( val isRedoRebuild: Boolean = false, /** What confirmed SWEEP and COOPERATIVE steps of replaced generations paid to [destination], by txid. */ val earlierReceivedSats: Map = emptyMap(), + /** Each quoted leaf's value, so a leaf the first build leaves behind before any recovery lists it keeps it. */ + val leafSats: Map = emptyMap(), /** * How the funding pays the CPFP children, [PER_NODE] for exits started on SDK 0.28 and later; null funds one UTXO * per branch, as exits started before did. Every prepare of the exit resumes with it. @@ -389,8 +391,9 @@ data class SparkExitRecord( fun leaveBehind(leafId: String, reason: String): SparkExitRecord = copy(leftBehindLeaves = leftBehindLeaves + LeftBehindLeaf(leafId, leafValueSats(leafId), reason)) - /** What the exit knows of [leafId]'s value, from its current recovery, else 0. */ - fun leafValueSats(leafId: String): ULong = recovery?.leaves?.firstOrNull { it.leafId == leafId }?.valueSats ?: 0uL + /** What the exit knows of [leafId]'s value, from its current recovery, else its quote, else 0. */ + fun leafValueSats(leafId: String): ULong = + recovery?.leaves?.firstOrNull { it.leafId == leafId }?.valueSats ?: leafSats[leafId] ?: 0uL val fundedSats: ULong get() = funding.fold(0uL) { sum, f -> sum.safe() + (f.valueSats ?: 0uL).safe() } @@ -754,6 +757,7 @@ object SparkExitJson { earlierReceivedSats = read { o.objectOrNull("earlierReceivedSats")?.mapValues { it.value.jsonPrimitive.content.toULong() } }.orEmpty(), + leafSats = read { leafSatsFromJson(o) }.orEmpty(), landedSweepTxid = read { o.stringOrNull("landedSweepTxid") }, sweptLeftover = read { sweptLeftoverFromJson(o) }.orEmpty(), ) @@ -981,6 +985,9 @@ object SparkExitJson { buildJsonObject { r.earlierReceivedSats.forEach { (txid, sats) -> put(txid, sats.toLong()) } }, ) } + if (r.leafSats.isNotEmpty()) { + put("leafSats", buildJsonObject { r.leafSats.forEach { (leafId, sats) -> put(leafId, sats.toLong()) } }) + } } private fun recordFromJson(o: JsonObject) = SparkExitRecord( @@ -1077,8 +1084,12 @@ object SparkExitJson { earlierReceivedSats = o.objectOrNull("earlierReceivedSats") ?.mapValues { it.value.jsonPrimitive.content.toULong() } .orEmpty(), + leafSats = leafSatsFromJson(o), ) + private fun leafSatsFromJson(o: JsonObject) = + o.objectOrNull("leafSats")?.mapValues { it.value.jsonPrimitive.content.toULong() }.orEmpty() + private fun sweptLeftoverFromJson(o: JsonObject) = o.arrayOrEmpty("sweptLeftover").map { val l = it.jsonObject SparkExitRecord.SweptLeftover(l.string("txid"), l.ulong("valueSats")) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index e2d021d61c..d398941ca1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -735,6 +735,7 @@ class SparkExitRepo @Inject constructor( skippedLeafCount = quote.prepared.skipped.size, fundingStrategy = SparkExitRecord.PER_NODE, leafTotalSats = quote.leafTotalSats, + leafSats = quote.leafSats, outsideSats = quote.outsideSats, transferId = transferId, ) @@ -815,6 +816,7 @@ class SparkExitRepo @Inject constructor( expectedSats = fresh.incomingSats, skippedLeafCount = fresh.prepared.skipped.size, leafTotalSats = fresh.leafTotalSats, + leafSats = fresh.leafSats, outsideSats = fresh.outsideSats, transferId = freshTransfer, ) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 7e134cc178..c59c9d3e5f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -808,6 +808,21 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(1_696uL, sut.state.value.record?.outsideSats) } + @Test + fun `a start keeps each quoted leaf's value for a leaf its first build leaves behind`() = test { + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + + sut.start(fundFromSavings = false).getOrThrow() + sut.onAppBackgrounded() + + val record = assertNotNull(sut.state.value.record) + assertNull(record.recovery) + assertEquals(100_000uL, record.leafValueSats("leaf-1")) + assertEquals(100_000uL, SparkExitJson.decode(SparkExitJson.encode(record)).leafValueSats("leaf-1")) + assertEquals(100_000uL, record.leaveBehind("leaf-1", "refused").leftBehindLeafSats) + } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a start killed before its transfer is written leaves no exit to resume`() = test { From d61eb02d92414b0d97b8499fa97ab7e771f14ee5 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:54:54 +0100 Subject: [PATCH 108/154] fix: connect spark again for an exit whose reconnect failed A failed reconnect for the exit left Spark ready but without an SDK, and foreground ticks never connected it again, so a funded exit stayed in AwaitingFunding until a background run or a restart. A tick of a running exit now connects Spark again when it is ready but disconnected. --- .../java/to/bitkit/repositories/SparkExitRepo.kt | 2 ++ .../java/to/bitkit/repositories/SparkRepo.kt | 11 +++++++++++ .../to/bitkit/repositories/SparkExitRepoTest.kt | 15 +++++++++++++++ .../java/to/bitkit/repositories/SparkRepoTest.kt | 16 ++++++++++++++++ 4 files changed, 44 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index d398941ca1..0b432291a0 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -271,6 +271,8 @@ class SparkExitRepo @Inject constructor( refreshFundingSeen(chain, current) if (current.isActive) noteSavingsSend(current) val store = store + // A reconnect for the exit that failed left Spark ready but disconnected: the tick connects it again. + if (current.isActive && !sparkService.isConnected) sparkRepo.reconnectForExit() val recovering = sparkService.exitRecovering() val driver = driver(chain, recovering, current, tip) // Read before this tick's losses are kept, so a leaf lost now is still reported once. diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 0eda3d9ef3..38fc8035eb 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -281,6 +281,17 @@ class SparkRepo @Inject constructor( } } + /** + * Connects Spark again when a reconnect for an exit disconnected it and then failed: Spark was ready but has no + * SDK, so neither the exit's builds nor its leaf optimization would run until a background run or a restart. + */ + suspend fun reconnectForExit() = withContext(bgDispatcher) { + if (!_state.value.isReady || sparkService.isConnected) return@withContext + runSuspendCatching { + if (sparkService.connect(walletIndex, _state.value.isExiting)) refresh() + }.onFailure { Logger.warn("Failed to connect Spark again for the exit", it, context = TAG) } + } + /** * Holds Spark for an exit about to start: no sends, receives, spending or kept balance, in the same step the exit's * transfer starts counting it. [setExiting] reconnects it for the exit afterwards. diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index c59c9d3e5f..bd38180233 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -537,6 +537,21 @@ class SparkExitRepoTest : BaseUnitTest() { verify(work, times(2)).armDeadline(any(), any()) } + @Test + fun `a tick without the sdk connects spark again for a running exit`() = test { + SparkExitStore(File(Env.sparkExitRecordPath(0))).save(SparkExitFixtures.record()) + whenever(transferRepo.activeTransfers).thenReturn(flowOf(listOf(transfer("transfer-1")))) + whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) + whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) + val disconnected = mock { on { networkName } doReturn "regtest" } + val sut = createSut(disconnected, fundingChain()) + sut.load(0).getOrThrow() + + sut.tick().getOrThrow() + + verify(sparkRepo).reconnectForExit() + } + @Test fun `a tick that leaves the exit short of fees asks for at least dust at once`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 3b1ad19081..124e27c385 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1092,6 +1092,22 @@ class SparkRepoTest : BaseUnitTest() { return sut } + @Test + fun `an exit's tick connects spark again after its reconnect failed`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever { sparkService.getInfo() }.thenReturn(info(10_000uL)) + val sut = createSut() + sut.refreshState().getOrThrow() + sut.holdForExit() + // The exit's reconnect disconnected Spark, then failed to connect it. + whenever(sparkService.isConnected).thenReturn(false) + whenever { sparkService.connect(any(), any()) }.thenReturn(true) + + sut.reconnectForExit() + + verify(sparkService).connect(0, true) + } + @Test fun `an exit start that failed before saving keeps the kept balance`() = test { val sut = keptAfterFailedSync() From 4bcb7506e918b71cbe22db161bbc4f19a23cfb17 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 12:58:42 +0100 Subject: [PATCH 109/154] fix: give a forgotten spark exit's funding address back A cancel that found nothing at the funding address deleted the exit, while the start had already moved the funding index past it, so a payment landing there late reached an address no later exit watched. The index goes back when it was the last one used, so the next exit uses that address again. --- .../bitkit/repositories/SparkExitFunding.kt | 7 +++++++ .../to/bitkit/repositories/SparkExitRepo.kt | 8 ++++++++ .../repositories/SparkExitFundingTest.kt | 7 +++++++ .../bitkit/repositories/SparkExitRepoTest.kt | 20 ++++++++++++++++++- 4 files changed, 41 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index a9690ac63a..9cf16fe91f 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -500,6 +500,13 @@ object SparkExitMath { return maxOf(kept?.toUInt() ?: 0u, pastStored) } + /** + * The next funding index once an exit at [index] is forgotten: given back when it was the last one used, so the + * next exit watches that address again and a payment landing there late is not left where nothing looks. + */ + fun fundingIndexAfterForget(kept: Int?, index: UInt): Int? = + if (kept != null && kept.toLong() == index.toLong() + 1) index.toInt() else kept + /** Savings can pay the fee funding when its spendable balance covers the funding and the payment's own fee. */ fun canFundFromSavings(spendableSats: ULong, fundingSats: ULong, paymentFeeSats: ULong): Boolean = fundingSats > 0uL && spendableSats >= fundingSats.safe() + paymentFeeSats.safe() diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 0b432291a0..371f411506 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -1021,6 +1021,7 @@ class SparkExitRepo @Inject constructor( record.transferId?.let { transferRepo.markSettled(it) } val outcome = if (utxos.isEmpty()) { store.delete() + giveFundingIndexBack(record.fundingIndex) _state.update { it.copy(record = null) } work.cancelAll() SparkExitCancel.Cancelled @@ -1053,6 +1054,13 @@ class SparkExitRepo @Inject constructor( private val fundingIndexKey get() = "${Env.network.name.lowercase()}/wallet$walletIndex" + /** A payment landing late at a forgotten exit's funding address is seen by the next exit, which uses it. */ + private suspend fun giveFundingIndexBack(index: UInt) = cacheStore.update { + val indexes = it.sparkExitNextFundingIndexes + val back = SparkExitMath.fundingIndexAfterForget(indexes[fundingIndexKey], index) ?: return@update it + it.copy(sparkExitNextFundingIndexes = indexes + (fundingIndexKey to back)) + } + private suspend fun nextFundingIndex(): UInt = SparkExitMath.nextFundingIndex( kept = cacheStore.data.first().sparkExitNextFundingIndexes[fundingIndexKey], stored = runSuspendCatching { store.load() }.getOrNull(), diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 889fe9beae..8648f5e84f 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -461,6 +461,13 @@ class SparkExitFundingTest { assertEquals(3_392uL, quote.copy(sparkBalanceSats = 3_392uL).unexitableSats) } + @Test + fun `a forgotten exit gives its funding address back when it was the last one used`() { + assertEquals(3, SparkExitMath.fundingIndexAfterForget(kept = 4, index = 3u), "a late payment goes unwatched") + assertEquals(6, SparkExitMath.fundingIndexAfterForget(kept = 6, index = 3u)) + assertNull(SparkExitMath.fundingIndexAfterForget(kept = null, index = 3u)) + } + @Test fun `quote names what it skips and spark's balance beyond every leaf it lists`() { val prepared = SparkExitFixtures.prepared() diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index bd38180233..ac1029436b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -42,6 +42,7 @@ import org.junit.rules.TemporaryFolder import org.lightningdevkit.ldknode.BalanceDetails import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull +import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.atLeastOnce import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn @@ -89,6 +90,7 @@ class SparkExitRepoTest : BaseUnitTest() { on { state } doReturn sparkState } private val work = mock() + private val cacheStore = mock { on { data } doReturn flowOf(AppCacheData()) } @Before fun setUp() { @@ -118,7 +120,7 @@ class SparkExitRepoTest : BaseUnitTest() { override fun now() = Instant.fromEpochSeconds(1_800_000_000) }, sparkExitTip = SparkExitTip(), - cacheStore = mock { on { data } doReturn flowOf(AppCacheData()) }, + cacheStore = cacheStore, ) private suspend fun createTransfer() = transferRepo.createTransfer( @@ -885,6 +887,22 @@ class SparkExitRepoTest : BaseUnitTest() { verify(sparkRepo, never()).setExiting(true, true) } + @Test + fun `a cancel that forgets the exit gives its funding address to the next exit`() = test { + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + sut.start(fundFromSavings = false).getOrThrow() + sut.onAppBackgrounded() + + assertEquals(SparkExitCancel.Cancelled, sut.cancel().getOrThrow()) + + val updates = argumentCaptor<(AppCacheData) -> AppCacheData>() + verify(cacheStore, atLeastOnce()).update(updates.capture()) + val cache = updates.allValues.fold(AppCacheData()) { data, update -> update(data) } + val indexes = cache.sparkExitNextFundingIndexes + assertEquals(listOf(0), indexes.values.toList(), "a payment landing late at the address goes unwatched") + } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a cancel during the start's optimization wait ends the exit before anything is paid`() = test { From 496aaeebc28dd75cde463facac6dd2704834803e Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:02:21 +0100 Subject: [PATCH 110/154] fix: pay from savings only what the spark exit funding address lacks After part of the funding came from another wallet, Pay from savings priced and sent the whole amount again, which only came back with the leftover sweep weeks later. Savings now prices and sends what the address still lacks, with its own payment's input fee. --- .../bitkit/repositories/SparkExitFunding.kt | 10 +++++++ .../to/bitkit/repositories/SparkExitRepo.kt | 10 +++++-- .../lightning/SparkExitFundingScreen.kt | 7 +++-- .../settings/lightning/SparkExitViewModel.kt | 6 ++++- .../repositories/SparkExitFundingTest.kt | 8 ++++++ .../bitkit/repositories/SparkExitRepoTest.kt | 27 +++++++++++++++++++ .../lightning/SparkExitViewModelTest.kt | 15 +++++++++++ 7 files changed, 76 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 9cf16fe91f..fef8b6e155 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -387,6 +387,16 @@ object SparkExitMath { return SparkExitPrestartFunding(isCovered, partial) } + /** + * What savings pays to the funding address for [fundingSats]: all of it while nothing arrived, else what + * [prestartFunding] still finds missing once its own payment's input fee is counted, and nothing once covered. + */ + fun savingsFundingSats(fundingSats: ULong, payments: Int, receivedSats: ULong, feeRateSatPerVbyte: ULong): ULong { + if (receivedSats == 0uL) return fundingSats + val funding = prestartFunding(fundingSats, payments, receivedSats, feeRateSatPerVbyte) + return if (funding.isCovered) 0uL else funding.partial?.missingSats ?: 0uL + } + /** What reached the funding address against [requiredSats], once some but not all of it did; else null. */ fun partialFunding(receivedSats: ULong, requiredSats: ULong): SparkExitPartialFunding? { if (receivedSats == 0uL || receivedSats >= requiredSats) return null diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 371f411506..ef03628da3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -655,7 +655,7 @@ class SparkExitRepo @Inject constructor( runSuspendCatching { val pending = requireNotNull(_state.value.pending) { "No Spark exit quote" } val address = requireNotNull(_state.value.fundingAddress) { "No Spark exit funding address" } - val fundingSats = pending.quote.fundingSats + val fundingSats = savingsFundingSats(pending.quote.fundingSats, pending.feeRate) val feeRates = lightningRepo.getFeeRates().getOrThrow() val estimateSats = lightningRepo.calculateTotalFee( amountSats = fundingSats, @@ -677,6 +677,11 @@ class SparkExitRepo @Inject constructor( } } + /** What savings pays toward [fundingSats]: what the funding address still lacks after what reached it. */ + private fun savingsFundingSats(fundingSats: ULong, feeRate: ULong): ULong = _state.value.let { + SparkExitMath.savingsFundingSats(fundingSats, it.fundingSeenCount, it.fundingSeenSats, feeRate) + } + /** Reads what reached the funding address, for the funding screen while the user pays from another wallet. */ suspend fun refreshFundingAddress(): Result = withContext(bgDispatcher) { runSuspendCatching { @@ -791,7 +796,8 @@ class SparkExitRepo @Inject constructor( scope.launch { tick() } onAppForegrounded() // Savings pays at most what the user confirmed: Progress asks for the rest of a higher fresh amount. - val savingsSats = minOf(quote.fundingSats, pending.quote.fundingSats) + // Funding another wallet already sent to the address is not paid again. + val savingsSats = savingsFundingSats(minOf(quote.fundingSats, pending.quote.fundingSats), pending.feeRate) if (fundFromSavings && savingsSats > 0uL) { runSuspendCatching { payFunding(createdAt, key.address, savingsSats, pending.savingsFeeRates, pending.savingsFeeSats) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt index 2d32db54d1..3a04d717b2 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt @@ -39,10 +39,9 @@ fun SparkExitFundingScreen( onContinue: () -> Unit, ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() - LaunchedEffect(Unit) { - viewModel.onFundingShown() - viewModel.loadSavingsFunding() - } + LaunchedEffect(Unit) { viewModel.onFundingShown() } + // Priced again once another wallet's payment shows: savings then sends only the rest. + LaunchedEffect(uiState.savingsFundingSats) { viewModel.loadSavingsFunding() } DisposableEffect(Unit) { onDispose { viewModel.stopWatchingFundingAddress() } } Content( uiState = uiState, diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index e5d7b4e8c7..aca40cb8ec 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -350,10 +350,14 @@ data class SparkExitUiState( val networkFees: SparkExitNetworkFees? = null, val feeBump: SparkExitFeeBumpUiState = SparkExitFeeBumpUiState(), ) { + /** What savings pays to the funding address: the funding less what another wallet already sent there. */ + val savingsFundingSats: ULong + get() = SparkExitMath.savingsFundingSats(fundingSats, fundingSeenCount, fundingSeenSats, fundingFeeRate ?: 0uL) + /** What leaves savings when it pays the fee funding: the funding and the fee of the payment that sends it. */ val savingsTotalSats: ULong? get() { - val fundingSats = quote?.fundingSats?.takeIf { fundFromSavings && it > 0uL } ?: return null + val fundingSats = savingsFundingSats.takeIf { fundFromSavings && it > 0uL } ?: return null val feeSats = savingsFeeSats ?: return null return fundingSats.safe() + feeSats.safe() } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 8648f5e84f..61117e5c9d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -468,6 +468,14 @@ class SparkExitFundingTest { assertNull(SparkExitMath.fundingIndexAfterForget(kept = null, index = 3u)) } + @Test + fun `savings pays only what the funding address still lacks`() { + assertEquals(20_000uL, SparkExitMath.savingsFundingSats(20_000uL, 0, 0uL, 2uL)) + // Another wallet sent 8,000: savings sends the rest, plus the input fee its own payment adds. + assertEquals(12_136uL, SparkExitMath.savingsFundingSats(20_000uL, 1, 8_000uL, 2uL), "savings pays it again") + assertEquals(0uL, SparkExitMath.savingsFundingSats(20_000uL, 1, 20_000uL, 2uL)) + } + @Test fun `quote names what it skips and spark's balance beyond every leaf it lists`() { val prepared = SparkExitFixtures.prepared() diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index ac1029436b..87bf4f2559 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1032,6 +1032,33 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(sut.savingsFundingFee().isFailure) } + @Test + fun `pay from savings sends only what another wallet's payment left missing`() = test { + stubFunding { Result.success(OnchainSendOutcome.Accepted("paid")) } + val paid = """[{"txid":"${"e1".repeat(32)}","vout":0,"value":8000,"status":{"confirmed":false}}]""" + val sut = quotedSut(FakeSparkExitRecovering(), fundingChain(utxos = paid)) + sut.loadQuote().getOrThrow() + assertEquals(8_000uL, sut.refreshFundingAddress().getOrThrow()) + whenever(lightning.getFeeRates()).thenReturn(Result.success(FeeRates(fast = 7u, mid = 4u, slow = 1u))) + whenever(lightning.calculateTotalFee(any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any())) + .thenReturn(Result.success(300uL)) + whenever(lightning.getBalancesAsync()).thenReturn(Result.success(balances(100_000uL))) + sut.savingsFundingFee().getOrThrow() + + sut.start(fundFromSavings = true).getOrThrow() + sut.onAppBackgrounded() + + // The quote's 20,000 less the 8,000 that arrived, plus the 612 input fee its second payment adds at 9 sat/vB. + verify(lightning).calculateTotalFee(eq(12_612uL), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), any()) + verify(lightning).sendOnChain( + eq(funding), eq(12_612uL), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = anyOrNull(), + ) + } + @Test fun `pay from savings sends at the rate its fee was priced at`() = test { stubFunding { Result.success(OnchainSendOutcome.Accepted("paid")) } diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index bbea6691ff..8fdd141f2e 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -112,6 +112,21 @@ class SparkExitViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.isStarted, "the next exit's Quote screen would jump to Progress") } + @Test + fun `pay from savings totals only what another wallet's payment left missing`() { + val state = SparkExitUiState( + quote = SparkExitQuote(SparkExitFixtures.prepared(funding = 20_000uL)), + fundFromSavings = true, + savingsFeeSats = 500uL, + fundingSeenSats = 8_000uL, + fundingSeenCount = 1, + fundingFeeRate = 2uL, + ) + + assertEquals(12_136uL, state.savingsFundingSats) + assertEquals(12_636uL, state.savingsTotalSats, "savings pays the funding another wallet sent again") + } + @Test fun `funding from another wallet continues only once the address holds what the quote asks`() { val quote = SparkExitQuote(SparkExitFixtures.prepared(funding = 20_000uL)) From e83afd580f70828108b0a246d7cd5d11b5c6ae62 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:05:12 +0100 Subject: [PATCH 111/154] fix: show kept spark exit fee change once with its recovery details Fee change kept at the funding address after the four-week wait ended the exit's result, so Emergency exit opened a new quote and the funding address and its derivation path were out of reach. A kept change now shows the result again until the user opened it. --- .../main/java/to/bitkit/repositories/SparkExitDriver.kt | 3 ++- .../main/java/to/bitkit/repositories/SparkExitRecord.kt | 7 +++++-- .../java/to/bitkit/repositories/SparkExitDriverTest.kt | 4 ++++ 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 8f17a95307..aa9c232036 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -782,7 +782,8 @@ class SparkExitDriver( val since = requireNotNull(built.waitingSince) if (height >= since + SWEEP_RELEASE_BLOCKS) { Logger.info("Keeping the Spark exit leftover as dust after waiting for cheaper fees", context = TAG) - return record.copy(leftoverSweep = built.copy(isDustKept = true)) + // Shown once more with its path, even after the result was opened: nothing else reaches that address. + return record.copy(leftoverSweep = built.copy(isDustKept = true), isResultSeen = false) } val next = built.retryAtHeight ?: ((built.checkedAtHeight ?: since) + SWEEP_RECHECK_BLOCKS) if (height < next) return record diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 8b58401287..b6dc3a21ce 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -353,9 +353,12 @@ data class SparkExitRecord( (leftover.isNotEmpty() && leftoverSweep?.rejection != null) || hasUnseenResult - /** The exit ended failed or with leaves lost, and the user has not opened its result yet. */ + /** The exit ended failed, with leaves lost or its fee change kept, and the user has not opened its result yet. */ val hasUnseenResult: Boolean - get() = !isActive && (phase is Phase.Failed || lostSats > 0uL) && !isResultSeen + get() = !isActive && (phase is Phase.Failed || lostSats > 0uL || isChangeKept) && !isResultSeen + + /** The fee change stays at the funding address for good, shown with the path that spends it. */ + val isChangeKept: Boolean get() = leftover.isNotEmpty() && leftoverSweep?.isDustKept == true /** Background runs and the foreground loop keep going while the exit runs and until its leftover is swept. */ val needsDriving: Boolean get() = isActive || isLeftoverSweepPending || isEndedPaymentPending diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 056beceb02..a203215340 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -663,6 +663,7 @@ class SparkExitDriverTest : BaseUnitTest() { funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), leftover = listOf(SparkExitRecord.Leftover("f0", 1u, 1_000uL)), feeRateSatPerVbyte = 9uL, + isResultSeen = true, ) // At 9 sat/vB the sweep's fee leaves less than dust: it waits, and the exit is still driven. @@ -686,6 +687,9 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) assertTrue(chain.rawBroadcasts.isEmpty()) assertFalse(record.needsDriving) + // Shown once more with the path that spends it, though its result was opened: nothing else reaches it. + assertTrue(record.showsResult, "the kept change loses its recovery screen") + assertFalse(record.copy(isResultSeen = true).showsResult) } @Test From b5b82275c1626dd47334e832c0c6092e389af141 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:07:08 +0100 Subject: [PATCH 112/154] fix: delete the spark exit record's copies on wipe A wipe left the unreadable-record copies set aside for support, which hold the wiped wallet's addresses and signed transactions, and a delete that failed went unnoticed. The wipe now deletes the copies too and fails when one stays. --- .../java/to/bitkit/repositories/SparkExitRecord.kt | 10 ++++++++++ .../java/to/bitkit/repositories/SparkExitRepo.kt | 2 +- .../main/java/to/bitkit/repositories/SparkRepo.kt | 2 +- .../java/to/bitkit/repositories/SparkRepoTest.kt | 13 +++++++++++++ 4 files changed, 25 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index b6dc3a21ce..8d02beaeee 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -613,6 +613,16 @@ class SparkExitStore(private val file: File) { fun delete() { file.delete() } + + /** + * Deletes the record and the copies [setAside] kept for support, for a wallet being wiped: they hold its addresses + * and signed transactions. Fails when one stays, so the wipe is retried rather than the next wallet driving it. + */ + fun deleteWithCopies() { + val prefix = "${file.nameWithoutExtension}.unreadable-" + val copies = file.parentFile?.listFiles().orEmpty().filter { it.name.startsWith(prefix) } + (copies + file).forEach { copy -> check(!copy.exists() || copy.delete()) { "Failed to delete '${copy.name}'" } } + } } /** diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index ef03628da3..24f3255d81 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -110,7 +110,7 @@ class SparkExitRepo @Inject constructor( foregroundJob?.cancel() foregroundJob = null tickMutex.withLock { - runCatching { store.delete() } + runCatching { store.deleteWithCopies() } .onFailure { e -> Logger.warn( "Failed to delete the wiped Spark exit record", diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 38fc8035eb..0a7107d5b5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -254,7 +254,7 @@ class SparkRepo @Inject constructor( _state.update { SparkState(isSupported = sparkService.isSupported) } val storage = runSuspendCatching { sparkService.wipeStorage(walletIndex) } val exitRecords = runSuspendCatching { - exitStore(walletIndex).delete() + exitStore(walletIndex).deleteWithCopies() SparkExitLostLeafStore(File(Env.sparkExitLostLeavesPath(walletIndex))).delete() } _walletWiped.emit(walletIndex) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index 124e27c385..6b6c3455c6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -1600,6 +1600,19 @@ class SparkRepoTest : BaseUnitTest() { assertEquals("state", sut.exitBackup().getOrThrow()?.exitState) } + @Test + fun `a wipe deletes the exit record and the copies set aside for support`() = test { + val file = File(Env.sparkExitRecordPath(0)) + SparkExitStore(file).save(SparkExitFixtures.record()) + SparkExitStore(file).setAside(42L) + + createSut().wipe(0).getOrThrow() + + assertFalse(file.exists()) + val copies = file.parentFile?.listFiles().orEmpty().filter { "unreadable" in it.name } + assertTrue(copies.isEmpty(), "the wiped wallet's addresses and signed steps outlive the wipe") + } + @Test fun `wipe fails when spark storage is not deleted and clears what spark held`() = test { whenever(sparkService.isConnected).thenReturn(true) From 018dd7ba3889111ddfbbaf3bedf14afed8f552c8 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:11:27 +0100 Subject: [PATCH 113/154] fix: saturate the refused spark exit sweep rate on overflow refusedFeeRate scaled a host's number without overflow checks, so a huge one wrapped to an arbitrary lower rate. It now saturates, and the caller's cap applies. --- .../main/java/to/bitkit/repositories/SparkExitSweep.kt | 8 ++++++-- .../java/to/bitkit/repositories/SparkExitDriverTest.kt | 6 ++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt index 0d4d084ccc..dba8733f34 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt @@ -34,8 +34,12 @@ object SparkExitSweep { val match = rejection?.let { feeNotMet.find(it) } val paid = match?.groupValues?.get(1)?.toULongOrNull()?.takeIf { it > 0uL } val asked = match?.groupValues?.get(2)?.toULongOrNull() - val scaled = if (paid != null && asked != null) (rate * asked + paid - 1uL) / paid else 0uL - return maxOf(scaled, rate + 1uL) + if (paid == null || asked == null) return rate.safe() + 1uL.safe() + // A host's number can be anything: one too big to scale asks for more than any cap, which the caller applies. + val product = rate.safe() * asked.safe() + if (product == ULong.MAX_VALUE) return ULong.MAX_VALUE + val scaled = (product.safe() + (paid - 1uL).safe()) / paid + return maxOf(scaled, rate.safe() + 1uL.safe()) } /** The inputs worth more than the fee each adds to a sweep at [feeRateSatPerVbyte]: the rest cost more to send. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index a203215340..e61e205254 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1889,6 +1889,12 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(3uL, SparkExitSweep.refusedFeeRate("insufficient fee", 2uL)) } + @Test + fun `a refused minimum too big to scale asks for more than any cap`() { + val refusal = "mempool min fee not met, 450 < 10000000000000000000" + assertEquals(ULong.MAX_VALUE, SparkExitSweep.refusedFeeRate(refusal, 2uL), "the scaled rate wrapped around") + } + @Test fun `a host's refusal cannot push the leftover sweep above the network's next-block rate`() = test { // A host answers a 1 sat/vB sweep with an absurd ask: 22,000 sats for a ~110 vB transaction. From 35ad08680dcdd578c14fc626a9864bc7d149bfce Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 13:39:26 +0100 Subject: [PATCH 114/154] fix: keep kept fee change's recovery details reachable --- .../main/java/to/bitkit/repositories/SparkExitRecord.kt | 5 +++-- .../java/to/bitkit/repositories/SparkExitDriverTest.kt | 7 +++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 8d02beaeee..5e864956fc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -345,12 +345,13 @@ data class SparkExitRecord( /** * Emergency exit opens progress, not a new exit, while this one runs and until its leftover fee funding is swept - * and confirmed, or kept as dust. A rejected sweep keeps it too: progress names the address the leftover is at. + * and confirmed. A leftover left at the funding address for good, its sweep rejected or its change kept, keeps + * it too: progress names the address and the path that spends it, and no new exit replaces the record. * An exit that failed or lost leaves keeps it until the user opened it once. */ val showsResult: Boolean get() = isActive || isLeftoverSweepPending || isEndedPaymentPending || - (leftover.isNotEmpty() && leftoverSweep?.rejection != null) || + (leftover.isNotEmpty() && leftoverSweep?.rejection != null) || isChangeKept || hasUnseenResult /** The exit ended failed, with leaves lost or its fee change kept, and the user has not opened its result yet. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index e61e205254..6816b8fa18 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -687,9 +687,12 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) assertTrue(chain.rawBroadcasts.isEmpty()) assertFalse(record.needsDriving) - // Shown once more with the path that spends it, though its result was opened: nothing else reaches it. + // Shown with the path that spends it, even once its result was opened: nothing else reaches it. assertTrue(record.showsResult, "the kept change loses its recovery screen") - assertFalse(record.copy(isResultSeen = true).showsResult) + assertTrue( + record.copy(isResultSeen = true).showsResult, + "the funding address and its path went out of reach once the result was opened", + ) } @Test From c671dfa20322d05e2c9db396e6e143be5834fddd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:11:00 +0100 Subject: [PATCH 115/154] fix: refresh wallet balances when exit funding arrives --- .../java/to/bitkit/repositories/WalletRepo.kt | 16 +++++++--- .../bitkit/repositories/LightningRepoTest.kt | 1 + .../to/bitkit/repositories/WalletRepoTest.kt | 29 +++++++++++++++++++ 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt index 8a85c96fd8..8f7b7084e9 100644 --- a/app/src/main/java/to/bitkit/repositories/WalletRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WalletRepo.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.filter @@ -81,6 +82,7 @@ class WalletRepo @Inject constructor( private val hwWalletRepo: HwWalletRepo, private val connectionRecovery: WalletConnectionRecovery, private val sparkRepo: SparkRepo, + private val sparkExitRepo: SparkExitRepo, private val backupRepo: BackupRepo, ) { private val repoScope = appScope(bgDispatcher, TAG) @@ -137,10 +139,16 @@ class WalletRepo @Inject constructor( repoScope.launch { // The read balance too, as sends use it: it can come back to the shown one while that stays the same. An // exit's start or end changes what Spending counts with no balance change. - sparkRepo.state.map { listOf(it.balanceSats, it.shownBalanceSats, it.pendingDepositSats) to it.isExiting } - .distinctUntilChanged().collect { - if (walletExists()) syncBalances() - } + val spark = sparkRepo.state + .map { listOf(it.balanceSats, it.shownBalanceSats, it.pendingDepositSats) to it.isExiting } + .distinctUntilChanged() + // Funding reaching the exit changes what it brings to savings with no Spark balance change. + val exit = sparkExitRepo.state + .map { Triple(it.inTransferSats, it.outsideExitSats, it.record?.transferId) } + .distinctUntilChanged() + combine(spark, exit) { _, _ -> }.collect { + if (walletExists()) syncBalances() + } } } diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index f87048252c..195afe714f 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -335,6 +335,7 @@ class LightningRepoTest : BaseUnitTest() { hwWalletRepo = hardware, connectionRecovery = connectionRecoveryFixture(settingsStore), sparkRepo = sparkRepo, + sparkExitRepo = mock { on { state } doReturn MutableStateFlow(SparkExitState()) }, backupRepo = mock { on { restoreInProgress } doReturn MutableStateFlow(false) }, ) } diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index b5639961ac..4c3789c5fb 100644 --- a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt @@ -94,6 +94,8 @@ class WalletRepoTest : BaseUnitTest() { private val activityRepo = mock() private val hwWalletRepo = mock() private val backupRepo = mock() + private val sparkExitState = MutableStateFlow(SparkExitState()) + private val sparkExitRepo = mock { on { state } doReturn sparkExitState } private val connectionRecovery = connectionRecoveryFixture(settingsStore) companion object Fixtures { @@ -196,6 +198,7 @@ class WalletRepoTest : BaseUnitTest() { hwWalletRepo = hwWalletRepo, connectionRecovery = connectionRecovery, sparkRepo = spark, + sparkExitRepo = sparkExitRepo, backupRepo = backupRepo, ) @@ -276,6 +279,32 @@ class WalletRepoTest : BaseUnitTest() { verify(deriveBalanceStateUseCase).invoke() } + @Test + fun `funding reaching a running exit syncs balances`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + sparkExitState.value = SparkExitState(record = SparkExitFixtures.record()) + testScheduler.runCurrent() + clearInvocations(deriveBalanceStateUseCase) + + sparkExitState.update { it.copy(fundingSeenSats = 5_000uL) } + testScheduler.runCurrent() + + verify(deriveBalanceStateUseCase).invoke() + } + + @Test + fun `an exit write that leaves the balances alone syncs nothing`() = test { + whenever(keychain.exists(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn(true) + sparkExitState.value = SparkExitState(record = SparkExitFixtures.record()) + testScheduler.runCurrent() + clearInvocations(deriveBalanceStateUseCase) + + sparkExitState.update { it.copy(tipHeight = 1_000u, lastError = "error") } + testScheduler.runCurrent() + + verify(deriveBalanceStateUseCase, never()).invoke() + } + private fun sparkRepoWith(state: MutableStateFlow): SparkRepo = mock { on { this.state } doReturn state on { nodeEvents } doReturn MutableSharedFlow() From 72245e3f728bd2e9189a2caabb796a44cfcb5871 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:15:33 +0100 Subject: [PATCH 116/154] fix: keep the valid exit generation when funding an unverified rebuild --- .../to/bitkit/repositories/SparkExitDriver.kt | 14 ++++++-- .../to/bitkit/repositories/SparkExitRecord.kt | 5 +++ .../repositories/SparkExitDriverTest.kt | 36 +++++++++++++++++++ 3 files changed, 52 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index aa9c232036..a3a9b1e0b7 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -162,7 +162,8 @@ class SparkExitDriver( // Funding for leaves a partial build skipped: only they are built, once it arrived. funded.isFundingWaitingLeaves -> retryWaitingLeaves(funded, sdk, isFunded = true) ?: end(funded.ended(), funded) - else -> build(funded, sdk) + // Funding an unverified rebuild asked for resumes that rebuild, with its guards. + else -> build(funded, sdk, isUnverifiedRebuild = funded.isUnverifiedAsk) } } } @@ -258,7 +259,7 @@ class SparkExitDriver( val asked = askForFunding(record, it) // Like a fee bump's, the valid generation keeps going while the funding it asks for comes. if (isUnverifiedRebuild && asked.phase is SparkExitRecord.Phase.NeedsFunding) { - return asked.copy(isRebuilding = false) + return asked.copy(isRebuilding = false, isUnverifiedAsk = true) } return asked } @@ -269,7 +270,7 @@ class SparkExitDriver( val waiting = waitingLeafIds(record, prepared.skipped, stopped) // Adopted, it would drop the signed steps of the leaf it could not read for the week the failed // leaves are retried, past the window in which they are ours to publish. - if (isUnverifiedRebuild && waiting.isNotEmpty()) return record + if (isUnverifiedRebuild && waiting.isNotEmpty()) return record.keepingValidGeneration() val adopted = record.adopt(built, nowMillis()).copy(waitingLeafIds = waiting) save(adopted) Logger.info("Built Spark exit of only '${built.failed.size}' failed cooperative leaves", context = TAG) @@ -1454,3 +1455,10 @@ object SparkExitTxOutputs { List(compactSize()) { Output(le(8).toULong(), take(compactSize())) } }.getOrNull() } + +/** + * The valid generation stays the exit's over a rebuild it does not adopt. Funding an unverified rebuild asked for, once + * adopted, goes back to running it: the funding stays the exit's for the next rebuild. + */ +private fun SparkExitRecord.keepingValidGeneration(): SparkExitRecord = + if (isUnverifiedAsk) copy(phase = SparkExitRecord.Phase.Running, isUnverifiedAsk = false) else this diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 5e864956fc..7f7a455fb1 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -116,6 +116,8 @@ data class SparkExitRecord( val isRebuiltFromChain: Boolean = false, /** The rebuild in progress started from a Redo verdict, the only one whose reproduced spent steps strike. */ val isRedoRebuild: Boolean = false, + /** The fee funding asked for came from a rebuild over unverified steps, while the generation out there is valid. */ + val isUnverifiedAsk: Boolean = false, /** What confirmed SWEEP and COOPERATIVE steps of replaced generations paid to [destination], by txid. */ val earlierReceivedSats: Map = emptyMap(), /** Each quoted leaf's value, so a leaf the first build leaves behind before any recovery lists it keeps it. */ @@ -413,6 +415,7 @@ data class SparkExitRecord( fun adopt(built: RecoverFundsResponse, atMillis: Long): SparkExitRecord = copy( spentStepStrikes = if (isRedoRebuild) spentStepStrikes(built) else spentStepStrikes, isRedoRebuild = false, + isUnverifiedAsk = false, earlierReceivedSats = earlierReceivedSats + recovery?.let { SparkExitMath.confirmedReceived(it, destination) } .orEmpty(), earlierCpfpTxids = (earlierCpfpTxids + recovery?.let(SparkExitTxids::fundingTxids).orEmpty()).distinct(), @@ -938,6 +941,7 @@ object SparkExitJson { r.exitStateSnapshot?.let { put("exitStateSnapshot", it) } if (r.isRebuiltFromChain) put("isRebuiltFromChain", true) if (r.isRedoRebuild) put("isRedoRebuild", true) + if (r.isUnverifiedAsk) put("isUnverifiedAsk", true) r.fundingStrategy?.let { put("fundingStrategy", it) } if (r.failedLeaves.isNotEmpty()) { put( @@ -1077,6 +1081,7 @@ object SparkExitJson { exitStateSnapshot = o.stringOrNull("exitStateSnapshot"), isRebuiltFromChain = o.booleanOrNull("isRebuiltFromChain") ?: false, isRedoRebuild = o.booleanOrNull("isRedoRebuild") ?: false, + isUnverifiedAsk = o.booleanOrNull("isUnverifiedAsk") ?: false, fundingStrategy = o.stringOrNull("fundingStrategy"), failedLeaves = o.arrayOrEmpty("failedLeaves").map { val l = it.jsonObject diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 6816b8fa18..502af582c8 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -436,6 +436,42 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }, "leaf-1's matured step n2 was not sent") } + @Test + fun `funding an unverified rebuild's ask keeps the valid generation over only failed cooperative leaves`() = test { + val failed = CooperativeRecoveryFailure( + "coop-1", + "o", + 0u, + CooperativeRecoveryError.OperatorsUnavailable("down"), + ) + val unverified = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + failed = listOf(failed), + ) + repeat(3) { sdk.checks += check(unverified, RecoveryVerdict.Valid) } + sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") + sdk.preparedResponses += SparkExitFixtures.prepared() + sdk.preparedResponse = coopLeaf(16_384uL).copy( + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = listOf(failed)) + val start = running(unverified).copy(leafIds = listOf("leaf-1", "coop-1")) + + var record = driver(tip = 1_000u).tick(start) + assertIs(record.phase) + + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", value = 100_000uL)) + record = driver(tip = 1_001u).tick(record) + + assertEquals(1, record.generation, "the funded rebuild adopted a recovery without leaf-1's signed steps") + assertTrue(saved.none { it.generation != 1 }, "a killed run would resume the recovery without leaf-1") + assertEquals(Phase.Running, record.phase) + assertEquals(unverified.transactions.map { it.txid }, record.recovery?.transactions?.map { it.txid }) + } + @Test fun `an unverified unilateral step waits while another unilateral step is ready`() = test { val recovery = SparkExitFixtures.recovery( From e4ad61ad8ed0177b79f5838c9453a51fcff71dbc Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:18:40 +0100 Subject: [PATCH 117/154] fix: drop an unverified rebuild's fee ask once its steps read again --- .../to/bitkit/repositories/SparkExitDriver.kt | 13 +++++++++++- .../to/bitkit/repositories/SparkExitRepo.kt | 1 + .../to/bitkit/repositories/SparkExitWorker.kt | 11 ++++++++++ .../repositories/SparkExitAlertsTest.kt | 10 ++++++++++ .../repositories/SparkExitDriverTest.kt | 20 +++++++++++++++++++ 5 files changed, 54 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index a3a9b1e0b7..e286c14e8c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -430,7 +430,18 @@ class SparkExitDriver( ?: return broadcastWithoutSdk(record) val updated = record.copy(recovery = checked.recovery) return when (checked.verdict) { - RecoveryVerdict.Valid -> broadcastReady(updated) + RecoveryVerdict.Valid -> { + // An unverified rebuild's ask ends once every step reads again: the valid generation needs nothing + // more. Funding paid meanwhile stays at the address, for a later rebuild or the leftover sweep. + val isAskOver = record.isUnverifiedAsk && record.fundingPaymentTxid == null && + checked.recovery.transactions.none { it.status == ExitTransactionStatus.Unverified } + val current = if (isAskOver) { + updated.copy(phase = SparkExitRecord.Phase.Running, isUnverifiedAsk = false) + } else { + updated + } + broadcastReady(current) + } // Finished before the higher fee was needed: running again, the next check ends it and the payment goes // back with the leftover. RecoveryVerdict.Done -> updated.copy(phase = SparkExitRecord.Phase.Running) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 24f3255d81..aca25f676d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -421,6 +421,7 @@ class SparkExitRepo @Inject constructor( ) } if (SparkExitAlerts.isFundingAskBack(record, previous)) work.notify(SparkExitAlert.Funding) + if (SparkExitAlerts.isFundingAskWithdrawn(record, previous)) work.dismissNotification() when (record.phase) { // Waiting on the operators for a week needs nothing from the user, so nothing reminds them. SparkExitRecord.Phase.Running if record.isWaitingForOperators -> { diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index dfb315735f..eaa4b8e4a2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -39,6 +39,7 @@ import to.bitkit.di.BgDispatcher import to.bitkit.env.Env import to.bitkit.ext.alarmManager import to.bitkit.ext.connectivityManager +import to.bitkit.ext.notificationManagerCompat import to.bitkit.ext.nowMs import to.bitkit.ext.runSuspendCatching import to.bitkit.models.BITCOIN_SYMBOL @@ -158,6 +159,11 @@ class SparkExitWork @Inject constructor( ) } + /** Takes back the exit's posted notification, such as a fee ask the exit no longer has. */ + fun dismissNotification() { + context.notificationManagerCompat.cancel(NOTIFICATION_ID) + } + fun cancelDeadline() { deadlinePendingIntent(PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE)?.let { context.alarmManager.cancel(it) @@ -379,6 +385,11 @@ object SparkExitAlerts { previous.isAwaitingOwnPayment && !record.isAwaitingOwnPayment && record.fundingShortfallSats != null && record.fundingPaymentTxid == null + /** An unverified rebuild's fee ask the tick from [previous] withdrew: the valid generation needs nothing more. */ + fun isFundingAskWithdrawn(record: SparkExitRecord, previous: SparkExitRecord): Boolean = + previous.isUnverifiedAsk && previous.phase is SparkExitRecord.Phase.NeedsFunding && + record.phase == SparkExitRecord.Phase.Running + /** A started exit nothing was paid into: no adopted funding, no payment from savings. */ fun isAwaitingFirstFunding(record: SparkExitRecord): Boolean = record.phase is SparkExitRecord.Phase.AwaitingFunding && record.fundingShortfallSats != null && diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt index 06528162f6..765ab54987 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt @@ -72,6 +72,16 @@ class SparkExitAlertsTest { assertNull(SparkExitAlerts.reason(null, isOnline = false, unlimited)) } + @Test + fun `an unverified rebuild's fee ask that ended is withdrawn`() { + val asked = SparkExitFixtures.record(Phase.NeedsFunding(5_000uL)).copy(isUnverifiedAsk = true) + val running = SparkExitFixtures.record(Phase.Running) + + assertTrue(SparkExitAlerts.isFundingAskWithdrawn(running, asked)) + assertFalse(SparkExitAlerts.isFundingAskWithdrawn(running, asked.copy(isUnverifiedAsk = false))) + assertFalse(SparkExitAlerts.isFundingAskWithdrawn(asked, asked)) + } + @Test fun `posts each lost leaf event, and a failure unless every leaf was lost`() { val lost = running.copy(lostLeaves = listOf(SparkExitRecord.LostLeaf("leaf-1", 16_384uL))) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 502af582c8..36c97aa8a5 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -396,6 +396,26 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }) assertEquals(1, record.generation) + assertEquals(Phase.Running, record.phase, "the fee ask stayed once every step read again") + assertFalse(record.isUnverifiedAsk) + } + + @Test + fun `an unverified rebuild's fee ask stays while a step still reads unverified`() = test { + val unverified = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + repeat(2) { sdk.checks += check(unverified, RecoveryVerdict.Valid) } + sdk.recoverError = SdkException.InsufficientCpfpFunds(30_000uL, "") + + var record = driver(tip = 1_000u).tick(running(unverified)) + record = driver(tip = 1_000u).tick(record) + + assertIs(record.phase) + assertTrue(record.isUnverifiedAsk) } @Test From 7c43beb5d9e5660e13f5b49d27de0975e73e9a4f Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:24:06 +0100 Subject: [PATCH 118/154] fix: cap a refused sweep rate so the exit record still loads --- .../to/bitkit/repositories/SparkExitSweep.kt | 9 ++++--- .../repositories/SparkExitDriverTest.kt | 26 ++++++++++++++++++- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt index dba8733f34..4da6b5382b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt @@ -27,7 +27,7 @@ object SparkExitSweep { /** * The least rate a node takes after it refused a sweep built at [feeRateSatPerVbyte] with [rejection], such as * `min relay fee not met, 450 < 674` (fees in sats): that rate scaled to the fee asked for, rounded up, and at - * least one more than the refused rate. + * least one more than the refused rate. Never above [MAX_REFUSED_FEE_RATE], so the record can save it. */ fun refusedFeeRate(rejection: String?, feeRateSatPerVbyte: ULong): ULong { val rate = maxOf(1uL, feeRateSatPerVbyte) @@ -37,11 +37,14 @@ object SparkExitSweep { if (paid == null || asked == null) return rate.safe() + 1uL.safe() // A host's number can be anything: one too big to scale asks for more than any cap, which the caller applies. val product = rate.safe() * asked.safe() - if (product == ULong.MAX_VALUE) return ULong.MAX_VALUE + if (product == ULong.MAX_VALUE) return MAX_REFUSED_FEE_RATE val scaled = (product.safe() + (paid - 1uL).safe()) / paid - return maxOf(scaled, rate.safe() + 1uL.safe()) + return maxOf(scaled, rate.safe() + 1uL.safe()).coerceAtMost(MAX_REFUSED_FEE_RATE) } + /** The record saves rates as signed longs: anything higher reads back as negative and breaks the next load. */ + private val MAX_REFUSED_FEE_RATE = Long.MAX_VALUE.toULong() + /** The inputs worth more than the fee each adds to a sweep at [feeRateSatPerVbyte]: the rest cost more to send. */ fun worthSweeping(inputs: List, feeRateSatPerVbyte: ULong): List { val inputFee = SparkExitMath.inputFeeSats(maxOf(1uL, feeRateSatPerVbyte)) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 36c97aa8a5..459eadfae1 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1951,7 +1951,31 @@ class SparkExitDriverTest : BaseUnitTest() { @Test fun `a refused minimum too big to scale asks for more than any cap`() { val refusal = "mempool min fee not met, 450 < 10000000000000000000" - assertEquals(ULong.MAX_VALUE, SparkExitSweep.refusedFeeRate(refusal, 2uL), "the scaled rate wrapped around") + assertEquals( + Long.MAX_VALUE.toULong(), + SparkExitSweep.refusedFeeRate(refusal, 2uL), + "the scaled rate wrapped around, or cannot be saved", + ) + assertEquals(Long.MAX_VALUE.toULong(), SparkExitSweep.refusedFeeRate("fee not met, 1 < 10000000000000000000", 1uL)) + } + + @Test + fun `a leftover sweep refused with a rate too big to scale saves and loads`() = test { + val coins = List(6) { SparkExitFixtures.utxo("%064x".format(it), 0u, 294uL) } + chain.utxosByAddress[SWEEP_FUNDING] = coins + chain.outcome = SparkExitBroadcastOutcome.Rejected("mempool min fee not met, 450 < 18446744073709551615") + val done = SparkExitFixtures.record(Phase.Done).copy( + destination = SWEEP_DESTINATION, + funding = listOf(SparkExitRecord.Funding(0u, SWEEP_FUNDING, "02ab")), + feeRateSatPerVbyte = 2uL, + leftover = coins.map { SparkExitRecord.Leftover(it.txid, it.vout, it.value) }, + ) + + var record = driver(tip = 1_000u).tick(done) + record = driver(tip = 1_000u).tick(record) + + assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record)), "the saved record did not load") + assertEquals(Long.MAX_VALUE.toULong(), assertNotNull(record.leftoverSweep).refusedFeeRate) } @Test From 81aaad7ef35c43be975a918ec05d19208c04d8f1 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:27:30 +0100 Subject: [PATCH 119/154] fix: forget an earlier exit's funding reading when a quote loads --- .../java/to/bitkit/repositories/SparkExitRepo.kt | 3 +++ .../to/bitkit/repositories/SparkExitRepoTest.kt | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index aca25f676d..f618dc3a0d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -498,6 +498,9 @@ class SparkExitRepo @Inject constructor( it.copy( pending = SparkExitPending(quote, destination, feeRate, fundingIndex), fundingAddress = fundingAddress, + // What an earlier exit's address showed is not paid toward this one. + fundingSeenSats = 0uL, + fundingSeenCount = 0, ) } quote diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 87bf4f2559..f6fbeb3dc1 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -1032,6 +1032,19 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(sut.savingsFundingFee().isFailure) } + @Test + fun `a new quote forgets what an earlier funding address showed`() = test { + val paid = """[{"txid":"${"e1".repeat(32)}","vout":0,"value":8000,"status":{"confirmed":false}}]""" + val sut = quotedSut(FakeSparkExitRecovering(), fundingChain(utxos = paid)) + sut.loadQuote().getOrThrow() + assertEquals(8_000uL, sut.refreshFundingAddress().getOrThrow()) + + sut.loadQuote().getOrThrow() + + assertEquals(0uL, sut.state.value.fundingSeenSats) + assertEquals(0, sut.state.value.fundingSeenCount) + } + @Test fun `pay from savings sends only what another wallet's payment left missing`() = test { stubFunding { Result.success(OnchainSendOutcome.Accepted("paid")) } From 8a9ac7bb18d06f2894bcb73b4a87f6fee1976d2d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:30:06 +0100 Subject: [PATCH 120/154] fix: keep left-behind exit leaves in spending after a sync --- .../java/to/bitkit/repositories/SparkExitRepo.kt | 5 +++-- .../to/bitkit/repositories/SparkExitFundingTest.kt | 13 +++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index f618dc3a0d..b07be8fec2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -1155,7 +1155,7 @@ data class SparkExitState( /** * What stays on Spark while the exit runs: Spark's balance beyond the quote's leaves, or, once published leaves - * left the balance, what the start saw beyond them, whichever is more. + * left the balance, what the start saw beyond them and the leaves the exit left behind, whichever is more. */ val outsideExitSats: ULong? get() { @@ -1163,7 +1163,8 @@ data class SparkExitState( // A leaf the exit left behind stays on Spark, so it counts here, not in the transfer. val exitLeafSats = active.leafTotalSats?.let { it.safe() - active.leftBehindLeafSats.safe() } val live = SparkExitMath.outsideExitSats(exitLeafSats, sparkBalanceSats) ?: 0uL - return maxOf(live, active.outsideSats ?: 0uL).takeIf { it > 0uL } + val floor = (active.outsideSats ?: 0uL).safe() + active.leftBehindLeafSats.safe() + return maxOf(live, floor).takeIf { it > 0uL } } /** diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 61117e5c9d..02dfb2a08d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -216,6 +216,19 @@ class SparkExitFundingTest { assertEquals(8_192uL, SparkExitMath.staysOnSparkSats(108_192uL, record)) } + @Test + fun `a leaf the exit left behind stays counted once the exit's leaves left spark's balance`() { + val record = SparkExitFixtures.record(SparkExitRecord.Phase.Running) + .copy(expectedSats = 150_000uL, leafIds = listOf("leaf-1", "leaf-2"), leafTotalSats = 108_192uL) + .adopt(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))), 1L) + .copy(leftBehindLeaves = listOf(SparkExitRecord.LeftBehindLeaf("leaf-2", 8_192uL, "its refund cannot pay"))) + + val state = SparkExitState(record = record, sparkBalanceSats = 8_192uL) + + assertEquals(141_808uL, state.inTransferSats) + assertEquals(8_192uL, state.outsideExitSats, "the left-behind leaf vanished from Spending") + } + @Test fun `a wait for a leaf that may still move tries again at doubling gaps up to a day and ends after a week`() { assertFalse(SparkExitMath.isRetryDue(since = 1_000u, retriedAt = 1_000u, tip = 1_005u)) From f9f30beffbc44c04ec0d679214891c3fff3686ee Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:33:33 +0100 Subject: [PATCH 121/154] fix: keep a cancelled exit's start from opening progress --- .../ui/settings/lightning/SparkExitViewModel.kt | 3 ++- .../settings/lightning/SparkExitViewModelTest.kt | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index aca40cb8ec..c3bf9c22bf 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -180,7 +180,8 @@ class SparkExitViewModel @Inject constructor( sparkExitRepo.start(_uiState.value.fundFromSavings) .onSuccess { savingsFeeFloorSats = null - _uiState.update { it.copy(isStarted = true) } + // A cancel during the start removed its record: nothing started for progress to show. + if (sparkExitRepo.state.value.isExiting) _uiState.update { it.copy(isStarted = true) } } .onFailure { // Savings never pays more than the fee confirmed: the next funding asks for the refused one. diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 8fdd141f2e..6a71e7d073 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -67,6 +67,7 @@ class SparkExitViewModelTest : BaseUnitTest() { @Test fun `a started exit stays started until a screen opens its progress`() = test { whenever(repo.start(any())).thenReturn(Result.success(Unit)) + exitState.value = SparkExitState(record = SparkExitFixtures.record()) val sut = SparkExitViewModel(mock(), repo, sparkRepo) // No screen collects while the user went back from Confirm. @@ -92,6 +93,21 @@ class SparkExitViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.isStarted, "the next exit's Quote screen would jump to Progress") } + @Test + fun `a cancel during the start leaves no start for the next exit`() = test { + // The start wrote its record, then a cancel removed it before the savings payment took its lock. + whenever(repo.start(any())).doSuspendableAnswer { + exitState.value = SparkExitState(record = SparkExitFixtures.record()) + exitState.value = SparkExitState() + Result.success(Unit) + } + val sut = SparkExitViewModel(mock(), repo, sparkRepo) + + sut.start() + + assertFalse(sut.uiState.value.isStarted, "the next exit's Quote screen would jump to Progress") + } + @Test fun `cancelling an exit whose savings funding failed leaves no start for the next exit`() = test { // The exit started, but paying its fee funding failed before it was submitted. From 4a555d273dd8a34a67d0a9606d790390f5725f5c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:45:23 +0100 Subject: [PATCH 122/154] fix: never drive a diverged exit generation from an unverified ask --- .../to/bitkit/repositories/SparkExitDriver.kt | 9 ++++-- .../repositories/SparkExitDriverTest.kt | 32 ++++++++++++++++++- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index e286c14e8c..8c9da21b58 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -163,7 +163,10 @@ class SparkExitDriver( funded.isFundingWaitingLeaves -> retryWaitingLeaves(funded, sdk, isFunded = true) ?: end(funded.ended(), funded) // Funding an unverified rebuild asked for resumes that rebuild, with its guards. - else -> build(funded, sdk, isUnverifiedRebuild = funded.isUnverifiedAsk) + else -> { + val isUnverified = funded.isUnverifiedAsk && !funded.isRebuilding + build(funded, sdk, isUnverifiedRebuild = isUnverified) + } } } } @@ -444,12 +447,12 @@ class SparkExitDriver( } // Finished before the higher fee was needed: running again, the next check ends it and the payment goes // back with the leftover. - RecoveryVerdict.Done -> updated.copy(phase = SparkExitRecord.Phase.Running) + RecoveryVerdict.Done -> updated.copy(phase = SparkExitRecord.Phase.Running, isUnverifiedAsk = false) // The diverged generation is never sent again: its rebuild, a Redo one, waits for the funding it was paid // for. is RecoveryVerdict.Redo -> { Logger.warn("Spark exit diverged on-chain while a top-up is awaited", context = TAG) - updated.copy(isRebuilding = true, isRedoRebuild = true) + updated.copy(isRebuilding = true, isRedoRebuild = true, isUnverifiedAsk = false) } } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 459eadfae1..c403ae5f3b 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -483,7 +483,8 @@ class SparkExitDriverTest : BaseUnitTest() { var record = driver(tip = 1_000u).tick(start) assertIs(record.phase) - chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", value = 100_000uL)) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + listOf(SparkExitFixtures.utxo("f0", value = 100_000uL)) record = driver(tip = 1_001u).tick(record) assertEquals(1, record.generation, "the funded rebuild adopted a recovery without leaf-1's signed steps") @@ -492,6 +493,35 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(unverified.transactions.map { it.txid }, record.recovery?.transactions?.map { it.txid }) } + @Test + fun `an unverified rebuild's ask that diverged never sends the diverged generation again`() = test { + val unverified = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + sdk.checks += check(unverified, RecoveryVerdict.Valid) + sdk.checks += check(unverified, redo) + repeat(2) { sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") } + + var record = driver(tip = 1_000u).tick(running(unverified)) + assertTrue(record.isUnverifiedAsk) + record = driver(tip = 1_001u).tick(record) + assertTrue(record.isRebuilding) + assertFalse(record.isUnverifiedAsk, "the ask now waits for the diverged generation's rebuild") + + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + listOf(SparkExitFixtures.utxo("f0", value = 100_000uL)) + now += interval + record = driver(tip = 1_002u).tick(record) + + assertIs(record.phase) + assertTrue(record.isRebuilding, "the diverged generation would be driven again") + record = driver(tip = 1_003u).tick(record) + assertTrue(chain.broadcasts.none { it.txid == "n1" || it.txid == "n2" }, "a diverged step was sent again") + } + @Test fun `an unverified unilateral step waits while another unilateral step is ready`() = test { val recovery = SparkExitFixtures.recovery( From 40662e5ad6f7c992bd1ea7a8b28bd871972e710c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:45:23 +0100 Subject: [PATCH 123/154] test: round-trip the review's refused sweep rate --- .../to/bitkit/repositories/SparkExitDriverTest.kt | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index c403ae5f3b..a0e14a19d1 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1986,7 +1986,19 @@ class SparkExitDriverTest : BaseUnitTest() { SparkExitSweep.refusedFeeRate(refusal, 2uL), "the scaled rate wrapped around, or cannot be saved", ) - assertEquals(Long.MAX_VALUE.toULong(), SparkExitSweep.refusedFeeRate("fee not met, 1 < 10000000000000000000", 1uL)) + assertEquals( + Long.MAX_VALUE.toULong(), + SparkExitSweep.refusedFeeRate("fee not met, 1 < 10000000000000000000", 1uL), + ) + // The host's text from the review, at 2 sat/vB: the rate it gives saves and loads. + val sweep = SparkExitRecord.LeftoverSweep( + txid = null, + txHex = null, + valueSats = 1_764uL, + refusedFeeRate = SparkExitSweep.refusedFeeRate(refusal, 2uL), + ) + val record = SparkExitFixtures.record(Phase.Done).copy(leftoverSweep = sweep) + assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) } @Test From f65a9c5eb46955cdcbb14cb7aace37174da96bf6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:49:40 +0100 Subject: [PATCH 124/154] fix: ignore fee estimates no node would ask for --- .../main/java/to/bitkit/repositories/SparkExitChain.kt | 5 +++++ .../java/to/bitkit/repositories/SparkExitChainTest.kt | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 08b8f8e2c5..8397a9d227 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -106,10 +106,15 @@ private const val MIN_RELAY_RATE = 1uL object SparkExitFeeEstimates { private val json = Json { ignoreUnknownKeys = true } + /** The highest rate in sat/vB an estimate is believed at. */ + private const val MAX_ESTIMATE_RATE = 10_000.0 + fun parse(body: String): Map = runCatching { json.parseToJsonElement(body).jsonObject.mapNotNull { (key, value) -> val target = key.toIntOrNull() ?: return@mapNotNull null val rate = (value as? JsonPrimitive)?.content?.toDoubleOrNull() ?: return@mapNotNull null + // A rate no node asks for, such as 1e30, reads as no estimate rather than the largest rate there is. + if (!rate.isFinite() || rate <= 0.0 || rate > MAX_ESTIMATE_RATE) return@mapNotNull null target to rate }.toMap() }.getOrDefault(emptyMap()) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt index 20423a5744..ac6df02170 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -140,6 +140,16 @@ class SparkExitChainTest : BaseUnitTest() { assertEquals(sparse, SparkExitFeeEstimates.parse("""{"6":3.2,"144":1.1,"x":2}""")) } + @Test + fun `an estimate no node would ask for reads as none`() = test { + val absurd = chain(Route("a.example/api/fee-estimates", 200, """{"1":1e30,"3":2.5}""")) + assertEquals(SparkExitNetworkFees(fastest = 3uL, halfHour = 3uL), absurd.networkFees()) + assertEquals( + mapOf(3 to 2.5), + SparkExitFeeEstimates.parse("""{"1":1e30,"2":0,"4":-3,"5":"NaN","6":"Infinity","3":2.5}"""), + ) + } + @Test fun `falls back to the unversioned package path then the next host`() = test { val sut = chain( From d998ce8b64f985ae868a7bc39b8429430ce552c2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 14:53:40 +0100 Subject: [PATCH 125/154] fix: rebuild a diverged exit from its funding when a top-up is dropped --- .../to/bitkit/repositories/SparkExitDriver.kt | 10 +++++ .../repositories/SparkExitDriverTest.kt | 39 ++++++++++++++++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 8c9da21b58..054847ab39 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -158,6 +158,16 @@ class SparkExitDriver( // Nothing to fund when every leaf is recovered cooperatively. val funded = if (shortfall != null) adoptFunding(record, shortfall) else record record = when { + // A generation that diverged while a top-up was awaited rebuilds from the funding it already + // has when that pays for it, so a top-up that never comes does not leave the exit waiting. + funded == null && record.isRedoRebuild && record.isRebuilding && isRebuildDue(record) -> + build(record, sdk).let { tried -> + if (tried.phase is SparkExitRecord.Phase.NeedsFunding) { + countShortOwnPayment(tried.copy(lastBuildAt = nowMillis())) + } else { + tried + } + } funded == null -> countShortOwnPayment(record) // Funding for leaves a partial build skipped: only they are built, once it arrived. funded.isFundingWaitingLeaves -> retryWaitingLeaves(funded, sdk, isFunded = true) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index a0e14a19d1..2123684e84 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -503,7 +503,8 @@ class SparkExitDriverTest : BaseUnitTest() { ) sdk.checks += check(unverified, RecoveryVerdict.Valid) sdk.checks += check(unverified, redo) - repeat(2) { sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") } + // The diverged generation's rebuild keeps needing more than the funding holds. + repeat(3) { sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") } var record = driver(tip = 1_000u).tick(running(unverified)) assertTrue(record.isUnverifiedAsk) @@ -1164,6 +1165,42 @@ class SparkExitDriverTest : BaseUnitTest() { assertTrue(chain.broadcasts.isEmpty()) } + @Test + fun `a generation that diverges while a dropped higher fee's payment waits rebuilds from the funding it has`() = + test { + val diverged = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + var record = funded(running(diverged, builtAt = now - interval)) + .applyFeeBump(rate = 9uL, extraSats = 6_612uL, paymentTxid = "bump") + sdk.checks += check(diverged, redo) + // The higher fee's payment never reached the address: only the confirmed funding is there. + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + listOf(SparkExitFixtures.utxo("f0", value = 20_000uL)) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1c"))) + + record = driver(tip = 1_000u).tick(record) + + assertEquals(Phase.Running, record.phase, "the rebuild waited for a payment that was dropped") + assertEquals(2, record.generation) + assertEquals(listOf("f0"), sdk.recoverRequests.single().fundingInputs.map { (it as CpfpInput.P2wpkh).txid }) + } + + @Test + fun `a diverged generation's rebuild the funding cannot pay keeps waiting for the top-up`() = test { + val diverged = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) + var record = funded(running(diverged, builtAt = now - interval)) + .applyFeeBump(rate = 9uL, extraSats = 6_612uL, paymentTxid = "bump") + sdk.checks += check(diverged, redo) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", value = 20_000uL)) + sdk.recoverErrors += SdkException.InsufficientCpfpFunds(26_000uL, "") + + record = driver(tip = 1_000u).tick(record) + assertIs(record.phase) + assertTrue(record.isRebuilding) + // Not built again on every tick while the top-up is out. + record = driver(tip = 1_000u).tick(record) + assertEquals(1, sdk.recoverRequests.size) + } + @Test fun `a paid higher fee rebuilds at the new rate once its payment confirms`() = test { var record = funded(running(SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))))) From 523506d9acb69990f6d23437f9c4cbd709811976 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:00:47 +0100 Subject: [PATCH 126/154] feat: keep earlier spark exit addresses past their record --- app/src/main/java/to/bitkit/env/Env.kt | 7 ++ .../repositories/SparkExitEarlierAddress.kt | 116 ++++++++++++++++++ .../to/bitkit/repositories/SparkExitRepo.kt | 30 ++++- .../bitkit/repositories/SparkExitRepoTest.kt | 66 ++++++++++ 4 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt diff --git a/app/src/main/java/to/bitkit/env/Env.kt b/app/src/main/java/to/bitkit/env/Env.kt index 91356f18a2..bde981fa8f 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -271,6 +271,13 @@ internal object Env { return Path(appStoragePath, network.name.lowercase(), wallet, "spark-exit-lost-leaves.json").toString() } + /** Earlier exits' funding addresses that hold, or may still receive, coins, kept past the exit record. */ + fun sparkExitEarlierAddressesPath(walletIndex: Int): String { + require(::appStoragePath.isInitialized) { "App storage path should be 'context.filesDir.absolutePath'." } + val wallet = "wallet$walletIndex" + return Path(appStoragePath, network.name.lowercase(), wallet, "spark-exit-earlier-addresses.json").toString() + } + fun bitkitCoreStoragePath(walletIndex: Int): String { return storagePathOf(walletIndex, network.name.lowercase(), "core") } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt new file mode 100644 index 0000000000..5b1e904b0d --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt @@ -0,0 +1,116 @@ +package to.bitkit.repositories + +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import org.lightningdevkit.ldknode.Network +import to.bitkit.models.safe +import java.io.File +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import kotlin.time.Duration.Companion.days + +/** + * A funding address an earlier exit left coins at, or may still receive a payment at, kept past its record so a later + * exit can replace that record: the address and the derivation path that spends it. + */ +@Serializable +data class SparkExitEarlierAddress( + val address: String, + val path: String, + val kind: Kind, + /** What the address holds, when known. */ + val sats: ULong? = null, + val atMillis: Long, +) { + enum class Kind { + /** Fee change too small to send, kept at the funding address for good. */ + KEPT_CHANGE, + + /** The funding address of a cancelled exit that was forgotten: a late payment can still land there. */ + CANCELLED_FUNDING, + } + + /** A cancelled exit's address younger than about four weeks, read in the foreground for a late payment. */ + fun isWatched(nowMillis: Long): Boolean = + kind == Kind.CANCELLED_FUNDING && nowMillis - atMillis < WATCH_PERIOD.inWholeMilliseconds + + companion object { + val WATCH_PERIOD = 28.days + + /** The kept fee change of an ended exit, or null when it kept none. */ + fun keptChange(record: SparkExitRecord, network: Network, atMillis: Long): SparkExitEarlierAddress? { + if (!record.isChangeKept) return null + val address = record.funding.firstOrNull()?.address ?: return null + return SparkExitEarlierAddress( + address = address, + path = SparkExitFundingKey.path(record.fundingIndex.toInt(), network), + kind = Kind.KEPT_CHANGE, + sats = record.leftover.fold(0uL) { sum, it -> sum.safe() + it.valueSats.safe() }, + atMillis = atMillis, + ) + } + + /** The funding address of a cancelled exit being forgotten. */ + fun cancelledFunding(record: SparkExitRecord, network: Network, atMillis: Long): SparkExitEarlierAddress? { + val address = record.funding.firstOrNull()?.address ?: return null + return SparkExitEarlierAddress( + address = address, + path = SparkExitFundingKey.path(record.fundingIndex.toInt(), network), + kind = Kind.CANCELLED_FUNDING, + atMillis = atMillis, + ) + } + } +} + +/** The earlier exits' addresses, in their own file next to the exit record. A wipe deletes it. */ +class SparkExitEarlierAddressStore(private val file: File) { + private val json = Json { ignoreUnknownKeys = true } + + fun load(): List { + if (!file.exists()) return emptyList() + return json.decodeFromString(file.readText()) + } + + /** Adds [entry], once per address: a known address keeps its entry, with [entry]'s amount when it has one. */ + fun add(entry: SparkExitEarlierAddress): List { + val known = runCatching { load() }.getOrDefault(emptyList()) + val existing = known.firstOrNull { it.address == entry.address } + val updated = when { + existing == null -> known + entry + entry.sats == null || entry.sats == existing.sats -> return known + else -> known.map { if (it.address == entry.address) it.copy(sats = entry.sats) else it } + } + save(updated) + return updated + } + + /** Sets what [address] holds, writing only when it changed. */ + fun updateSats(address: String, sats: ULong): List { + val known = runCatching { load() }.getOrDefault(emptyList()) + if (known.none { it.address == address && it.sats != sats }) return known + val updated = known.map { if (it.address == address) it.copy(sats = sats) else it } + save(updated) + return updated + } + + /** Drops [address], such as one a new exit funds again. */ + fun remove(address: String): List { + val known = runCatching { load() }.getOrDefault(emptyList()) + if (known.none { it.address == address }) return known + val updated = known.filter { it.address != address } + save(updated) + return updated + } + + fun delete() { + check(!file.exists() || file.delete()) { "Failed to delete '${file.name}'" } + } + + private fun save(entries: List) { + file.parentFile?.mkdirs() + val temp = File(file.parentFile, "${file.name}.tmp") + writeDurably(temp, json.encodeToString(entries)) + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } +} diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index b07be8fec2..975dfdf5ce 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -119,6 +119,8 @@ class SparkExitRepo @Inject constructor( ) } runCatching { lostLeafStore.delete() } + runCatching { earlierAddressStore.delete() } + .onFailure { e -> Logger.warn("Failed to delete the wiped exit addresses", e, context = TAG) } work.cancelAll() _state.update { SparkExitState() } isLoaded = false @@ -142,6 +144,17 @@ class SparkExitRepo @Inject constructor( private val lostLeafStore get() = SparkExitLostLeafStore(File(Env.sparkExitLostLeavesPath(walletIndex))) + private val earlierAddressStore + get() = SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(walletIndex))) + + /** Lists [entry] next to the record, which a later exit may then replace; a failed write only logs. */ + private fun keepEarlierAddress(entry: SparkExitEarlierAddress?) { + entry ?: return + runCatching { earlierAddressStore.add(entry) } + .onSuccess { listed -> _state.update { it.copy(earlierAddresses = listed) } } + .onFailure { Logger.warn("Failed to keep the Spark exit address '${entry.address}'", it, context = TAG) } + } + private val chain: SparkExitChain? get() = EsploraSparkExitChain.defaultHosts(sparkService.networkName) ?.let { EsploraSparkExitChain(it, httpClient) } @@ -162,7 +175,12 @@ class SparkExitRepo @Inject constructor( salvage() } isLoaded = true - _state.update { it.copy(record = record) } + val earlier = runCatching { earlierAddressStore.load() } + .onFailure { Logger.warn("Failed to read the earlier exit addresses", it, context = TAG) } + .getOrDefault(emptyList()) + _state.update { it.copy(record = record, earlierAddresses = earlier) } + // A record that kept its change before the list existed is listed too. + record?.let { keepEarlierAddress(SparkExitEarlierAddress.keptChange(it, Env.network, clock.nowMs())) } rememberLostLeaves(record) record?.let { settleIfFinished(it) } settleOrphanedTransfers(record) @@ -320,6 +338,9 @@ class SparkExitRepo @Inject constructor( reportedLost: Set, ) { record.transferId?.let { transferRepo.updateClaimableAtHeight(it, record.claimableAtHeight) } + if (record.isChangeKept && !previous.isChangeKept) { + keepEarlierAddress(SparkExitEarlierAddress.keptChange(record, Env.network, clock.nowMs())) + } settleIfFinished(record) updateAlerts(record, previous, isOnTrack, reportedLost) if (!record.isActive && previous.isActive) { @@ -763,6 +784,9 @@ class SparkExitRepo @Inject constructor( val next = it.sparkExitNextFundingIndexes + (fundingIndexKey to pending.fundingIndex.toInt() + 1) it.copy(sparkExitNextFundingIndexes = next) } + // A cancelled exit's address this exit funds again is this exit's now, not an earlier exit's. + runCatching { earlierAddressStore.remove(key.address) } + .onSuccess { listed -> _state.update { it.copy(earlierAddresses = listed) } } val createdAt = record.createdAt // Published for the screens and a cancel, but driven only once the start settled the leaves it exits. startingCreatedAt = createdAt @@ -1030,6 +1054,8 @@ class SparkExitRepo @Inject constructor( .getOrElse { throw SparkExitCancelUnreadable() } record.transferId?.let { transferRepo.markSettled(it) } val outcome = if (utxos.isEmpty()) { + // Its address stays listed, and is read for a late payment in the foreground for four weeks. + keepEarlierAddress(SparkExitEarlierAddress.cancelledFunding(record, Env.network, clock.nowMs())) store.delete() giveFundingIndexBack(record.fundingIndex) _state.update { it.copy(record = null) } @@ -1147,6 +1173,8 @@ data class SparkExitState( val isSettling: Boolean = false, /** What the network asks now, for the fee bump and its hint. */ val networkFees: SparkExitNetworkFees? = null, + /** Funding addresses of earlier exits that hold, or may still receive, coins. */ + val earlierAddresses: List = emptyList(), ) { val isExiting: Boolean get() = record?.isActive == true diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index f6fbeb3dc1..9d486206f9 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -427,6 +427,15 @@ class SparkExitRepoTest : BaseUnitTest() { fun `a wipe waits for the tick in flight and deletes what it saved`() = test { val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) store.save(runningRecord()) + SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(0))).add( + SparkExitEarlierAddress( + address = "bcrt1qearlier", + path = "m/84'/1'/0'/0/3", + kind = SparkExitEarlierAddress.Kind.KEPT_CHANGE, + sats = 294uL, + atMillis = 0L, + ), + ) val gate = CompletableDeferred() val chain = HttpClient( MockEngine.create { @@ -461,6 +470,7 @@ class SparkExitRepoTest : BaseUnitTest() { assertNull(store.load()) assertNull(sut.state.value.record) verify(work, atLeastOnce()).cancelAll() + assertFalse(File(Env.sparkExitEarlierAddressesPath(0)).exists(), "the wiped wallet's addresses stayed") } @Test @@ -903,6 +913,62 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(listOf(0), indexes.values.toList(), "a payment landing late at the address goes unwatched") } + @Test + fun `a cancel that forgets the exit keeps its funding address and path listed`() = test { + val sut = quotedSut(FakeSparkExitRecovering()) + sut.loadQuote().getOrThrow() + sut.start(fundFromSavings = false).getOrThrow() + sut.onAppBackgrounded() + + sut.cancel().getOrThrow() + + val listed = SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(0))).load().single() + assertEquals(funding, listed.address) + assertEquals("m/84'/1'/${SparkExitFundingKey.ACCOUNT}'/0/0", listed.path) + assertEquals(SparkExitEarlierAddress.Kind.CANCELLED_FUNDING, listed.kind) + assertEquals(listOf(listed), sut.state.value.earlierAddresses) + } + + @Test + fun `an exit that funds a cancelled exit's address again takes it off the list`() = test { + val store = SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(0))) + val kind = SparkExitEarlierAddress.Kind.CANCELLED_FUNDING + store.add(SparkExitEarlierAddress(funding, "m/84'/1'/0'/0/0", kind, atMillis = 0L)) + val sut = quotedSut(FakeSparkExitRecovering()) + sut.load().getOrThrow() + sut.loadQuote().getOrThrow() + + sut.start(fundFromSavings = false).getOrThrow() + sut.onAppBackgrounded() + + assertTrue(store.load().isEmpty(), "the running exit's funding shows as an earlier exit's") + assertTrue(sut.state.value.earlierAddresses.isEmpty()) + } + + @Test + fun `an exit that kept its fee change lists the address, so the next exit can start`() = test { + val kept = SparkExitFixtures.record(Phase.Done).copy( + leftover = listOf(SparkExitRecord.Leftover("ab".repeat(32), 0u, 294uL)), + leftoverSweep = SparkExitRecord.LeftoverSweep( + txid = null, + txHex = null, + valueSats = 294uL, + isDustKept = true, + ), + isResultSeen = true, + ) + SparkExitStore(File(Env.sparkExitRecordPath(0))).save(kept) + val sut = quotedSut(FakeSparkExitRecovering()) + + sut.load().getOrThrow() + + val listed = sut.state.value.earlierAddresses.single() + assertEquals(SparkExitFixtures.FUNDING_ADDRESS, listed.address) + assertEquals(SparkExitEarlierAddress.Kind.KEPT_CHANGE, listed.kind) + assertEquals(294uL, listed.sats) + assertEquals(listOf(listed), SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(0))).load()) + } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a cancel during the start's optimization wait ends the exit before anything is paid`() = test { From aace83cea6e4d2324283768cfcc909e6a1dd61fa Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:02:42 +0100 Subject: [PATCH 127/154] fix: let a new exit start after an earlier one kept its change --- .../main/java/to/bitkit/repositories/SparkExitRecord.kt | 8 ++++---- .../java/to/bitkit/repositories/SparkExitDriverTest.kt | 7 ++----- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 7f7a455fb1..1322713d7c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -347,13 +347,13 @@ data class SparkExitRecord( /** * Emergency exit opens progress, not a new exit, while this one runs and until its leftover fee funding is swept - * and confirmed. A leftover left at the funding address for good, its sweep rejected or its change kept, keeps - * it too: progress names the address and the path that spends it, and no new exit replaces the record. - * An exit that failed or lost leaves keeps it until the user opened it once. + * and confirmed, or kept as dust. A rejected sweep keeps it too: progress names the address the leftover is at. + * An exit that failed, lost leaves or kept its change keeps it until the user opened it once; kept change then + * stays listed among the earlier exit addresses, so a new exit can replace the record. */ val showsResult: Boolean get() = isActive || isLeftoverSweepPending || isEndedPaymentPending || - (leftover.isNotEmpty() && leftoverSweep?.rejection != null) || isChangeKept || + (leftover.isNotEmpty() && leftoverSweep?.rejection != null) || hasUnseenResult /** The exit ended failed, with leaves lost or its fee change kept, and the user has not opened its result yet. */ diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 2123684e84..442b11272a 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -774,12 +774,9 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(record, SparkExitJson.decode(SparkExitJson.encode(record))) assertTrue(chain.rawBroadcasts.isEmpty()) assertFalse(record.needsDriving) - // Shown with the path that spends it, even once its result was opened: nothing else reaches it. + // Shown once with the path that spends it; the earlier exit addresses keep it after that. assertTrue(record.showsResult, "the kept change loses its recovery screen") - assertTrue( - record.copy(isResultSeen = true).showsResult, - "the funding address and its path went out of reach once the result was opened", - ) + assertFalse(record.copy(isResultSeen = true).showsResult, "kept change blocks every later exit") } @Test From 3507f254433269bfb4c74577d52c07fe27fc52de Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:08:26 +0100 Subject: [PATCH 128/154] feat: watch a cancelled spark exit's address for a late payment --- .../to/bitkit/repositories/SparkExitRepo.kt | 17 ++++++++++++++++ .../bitkit/repositories/SparkExitRepoTest.kt | 20 +++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 975dfdf5ce..50a6439159 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -211,6 +211,7 @@ class SparkExitRepo @Inject constructor( if (foregroundJob?.isActive == true) return foregroundJob = scope.launch { load().onFailure { Logger.error("Failed to load the Spark exit", it, context = TAG) } + refreshEarlierAddresses() while (isActive && _state.value.record?.needsDriving == true) { tick() delay(FOREGROUND_TICK_INTERVAL) @@ -218,6 +219,22 @@ class SparkExitRepo @Inject constructor( } } + /** + * Reads what reached each cancelled exit's address still watched, about four weeks after the cancel, so a late + * payment shows with its balance among the earlier exit addresses. + */ + suspend fun refreshEarlierAddresses() = withContext(bgDispatcher) { + val chain = chain ?: return@withContext + val now = clock.nowMs() + val watched = runCatching { earlierAddressStore.load() }.getOrDefault(emptyList()).filter { it.isWatched(now) } + for (entry in watched) { + val utxos = runSuspendCatching { chain.utxos(entry.address) }.getOrNull() ?: continue + val sats = utxos.fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + runCatching { earlierAddressStore.updateSats(entry.address, sats) } + .onSuccess { listed -> _state.update { it.copy(earlierAddresses = listed) } } + } + } + fun onAppBackgrounded() { foregroundJob?.cancel() foregroundJob = null diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 9d486206f9..2f92c9460c 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -75,6 +75,7 @@ import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.time.Clock +import kotlin.time.Duration.Companion.days import kotlin.time.Instant class SparkExitRepoTest : BaseUnitTest() { @@ -945,6 +946,25 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(sut.state.value.earlierAddresses.isEmpty()) } + @Test + fun `a late payment to a cancelled exit's address shows with its balance for four weeks`() = test { + val now = 1_800_000_000_000L + val kind = SparkExitEarlierAddress.Kind.CANCELLED_FUNDING + val store = SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(0))) + val recent = now - 1.days.inWholeMilliseconds + val old = now - 29.days.inWholeMilliseconds + store.add(SparkExitEarlierAddress(funding, "m/84'/1'/7797'/0/0", kind, atMillis = recent)) + store.add(SparkExitEarlierAddress("bcrt1qold", "m/84'/1'/7797'/0/1", kind, atMillis = old)) + val paid = """[{"txid":"${"e1".repeat(32)}","vout":0,"value":8000,"status":{"confirmed":true}}]""" + val sut = quotedSut(FakeSparkExitRecovering(), fundingChain(utxos = paid)) + sut.load().getOrThrow() + + sut.refreshEarlierAddresses() + + assertEquals(listOf(8_000uL, null), sut.state.value.earlierAddresses.map { it.sats }) + assertEquals(8_000uL, store.load().first().sats) + } + @Test fun `an exit that kept its fee change lists the address, so the next exit can start`() = test { val kept = SparkExitFixtures.record(Phase.Done).copy( From 4100deceb11a91bea7ccadddffe9a71387ba3317 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:08:26 +0100 Subject: [PATCH 129/154] feat: show earlier spark exit addresses on spark details --- .../LightningConnectionsViewModel.kt | 26 ++++++++++--- .../settings/lightning/SparkDetailScreen.kt | 38 +++++++++++++++++++ .../lightning/SparkDetailViewModel.kt | 19 +++++++--- app/src/main/res/values/strings.xml | 3 ++ .../ui/settings/lightning/SparkUiTest.kt | 18 +++++++++ 5 files changed, 94 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt index a68a661b50..b4cc77fc34 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/LightningConnectionsViewModel.kt @@ -38,6 +38,7 @@ import to.bitkit.repositories.BlocktankRepo import to.bitkit.repositories.LightningRepo import to.bitkit.repositories.LogsRepo import to.bitkit.repositories.SparkDeposit +import to.bitkit.repositories.SparkExitEarlierAddress import to.bitkit.repositories.SparkExitRepo import to.bitkit.repositories.SparkExitState import to.bitkit.repositories.SparkRepo @@ -122,7 +123,11 @@ class LightningConnectionsViewModel @Inject constructor( .reversed().toImmutableList(), localBalance = calculateLocalBalance(channels).safe() + sparkState.shownSpendingSats.safe(), remoteBalance = channels.calculateRemoteBalance(), - spark = sparkState.toUi(lightningRepo, snapshot.exitState.showsResult), + spark = sparkState.toUi( + lightningRepo, + snapshot.exitState.showsResult, + snapshot.exitState.earlierAddresses, + ), isSparkReceiving = sparkState.isUsable, ) } @@ -248,6 +253,8 @@ data class SparkUi( val isExiting: Boolean = false, /** An exit runs, or ended with leftover fee funding not yet swept: Emergency exit opens its progress. */ val showsExitResult: Boolean = false, + /** Earlier exits' funding addresses that hold, or may still receive, coins. */ + val earlierAddresses: ImmutableList = persistentListOf(), ) { /** * The emergency exit is offered while Spark holds funds, also a kept balance while it reads 0, and leads to its @@ -265,13 +272,21 @@ data class SparkDepositUi( val confirmations: UInt? = null, ) -internal suspend fun SparkState.toUi(lightningRepo: LightningRepo, showsExitResult: Boolean = false): SparkUi? { +internal suspend fun SparkState.toUi( + lightningRepo: LightningRepo, + showsExitResult: Boolean = false, + earlierAddresses: List = emptyList(), +): SparkUi? { val showsExit = isExiting || showsExitResult - // An emergency exit keeps Spark listed, also while it cannot connect, so its progress stays reachable. - if (!isReady && !showsExit) return null + // An emergency exit keeps Spark listed, also while it cannot connect, so its progress stays reachable. So do an + // earlier exit's addresses, once Spark is empty. + val hasEarlier = earlierAddresses.isNotEmpty() + if (!isReady && !showsExit && !hasEarlier) return null // On regtest Spark always shows, so testers reach its deposit address to fund it from the faucet. val hasExit = showsExit || recoverableFundsSats > 0uL - if (shownBalanceSats == 0uL && deposits.isEmpty() && !hasExit && Env.network != Network.REGTEST) return null + if (shownBalanceSats == 0uL && deposits.isEmpty() && !hasExit && !hasEarlier && Env.network != Network.REGTEST) { + return null + } return SparkUi( balanceSats = shownBalanceSats, deposits = deposits.map { @@ -281,6 +296,7 @@ internal suspend fun SparkState.toUi(lightningRepo: LightningRepo, showsExitResu recoverableFundsSats = recoverableFundsSats, isExiting = isExiting, showsExitResult = showsExit, + earlierAddresses = earlierAddresses.toImmutableList(), ) } diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt index 6adbdaceea..53df70e275 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailScreen.kt @@ -28,6 +28,7 @@ import kotlinx.collections.immutable.persistentListOf import to.bitkit.R import to.bitkit.ext.setClipboardText import to.bitkit.repositories.SparkDeposit +import to.bitkit.repositories.SparkExitEarlierAddress import to.bitkit.repositories.SparkWithdrawal import to.bitkit.ui.components.BodyS import to.bitkit.ui.components.CaptionB @@ -154,6 +155,15 @@ private fun Content( } } + if (spark.earlierAddresses.isNotEmpty()) { + SectionTitle(stringResource(R.string.lightning__spark_exit__earlier_addresses)) + BodyS( + text = stringResource(R.string.lightning__spark_exit__earlier_addresses_text), + color = Colors.White64, + ) + spark.earlierAddresses.forEach { EarlierExitAddressRows(it, onCopyText) } + } + if (spark.withdrawals.isNotEmpty()) { SectionTitle(stringResource(R.string.lightning__savings_confirm__label)) spark.withdrawals.forEach { withdrawal -> @@ -200,6 +210,34 @@ private fun Content( } } +@Composable +private fun EarlierExitAddressRows(entry: SparkExitEarlierAddress, onCopyText: (String) -> Unit) { + SectionRow( + name = stringResource(R.string.wallet__activity_address), + valueContent = { + CaptionB( + text = entry.address, + maxLines = 1, + overflow = TextOverflow.MiddleEllipsis, + textAlign = TextAlign.End, + ) + }, + onClick = { onCopyText(entry.address) }, + modifier = Modifier.testTag("SparkEarlierExitAddress"), + ) + SectionRow( + name = stringResource(R.string.lightning__spark_exit__earlier_path), + valueContent = { CaptionB(text = entry.path, textAlign = TextAlign.End) }, + onClick = { onCopyText(entry.path) }, + ) + entry.sats?.takeIf { it > 0uL }?.let { sats -> + SectionRow( + name = stringResource(R.string.lightning__balance), + valueContent = { MoneyCaptionB(sats = sats.toLong(), symbol = true) }, + ) + } +} + @Preview @Composable private fun Preview() { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt index dbea63b108..fb62bd377a 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkDetailViewModel.kt @@ -32,11 +32,17 @@ class SparkDetailViewModel @Inject constructor( init { viewModelScope.launch(bgDispatcher) { - combine(sparkRepo.state, sparkExitRepo.state) { state, exit -> state to exit.showsResult } - .collect { (state, showsResult) -> - _uiState.update { it.copy(spark = state.toUi(lightningRepo, showsResult)) } + combine(sparkRepo.state, sparkExitRepo.state) { state, exit -> state to exit } + .collect { (state, exit) -> + _uiState.update { + it.copy(spark = state.toUi(lightningRepo, exit.showsResult, exit.earlierAddresses)) + } } } + viewModelScope.launch(bgDispatcher) { + // A cancelled exit's address may still receive a late payment: its balance shows here. + sparkExitRepo.refreshEarlierAddresses() + } if (Env.network == Network.REGTEST) { viewModelScope.launch(bgDispatcher) { sparkRepo.depositAddress().onSuccess { address -> @@ -54,8 +60,11 @@ class SparkDetailViewModel @Inject constructor( viewModelScope.launch { _uiState.update { it.copy(isRefreshing = true) } sparkRepo.refreshState() - val showsResult = sparkExitRepo.state.value.showsResult - _uiState.update { it.copy(spark = sparkRepo.state.value.toUi(lightningRepo, showsResult)) } + sparkExitRepo.refreshEarlierAddresses() + val exit = sparkExitRepo.state.value + _uiState.update { + it.copy(spark = sparkRepo.state.value.toUi(lightningRepo, exit.showsResult, exit.earlierAddresses)) + } delay(500.milliseconds) _uiState.update { it.copy(isRefreshing = false) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 91aef2849d..230a83c4cf 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -439,6 +439,9 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. + Earlier exit addresses + Earlier emergency exits used these funding addresses. Coins left at one stay yours: spend them with your recovery phrase and its derivation path. + Derivation path {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt index c5bbce8bb3..d00e9bf478 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt @@ -2,8 +2,10 @@ package to.bitkit.ui.settings.lightning import org.junit.Test import org.mockito.kotlin.mock +import to.bitkit.repositories.SparkExitEarlierAddress import to.bitkit.repositories.SparkState import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue @@ -20,4 +22,20 @@ class SparkUiTest : BaseUnitTest() { fun `emergency exit is not offered with nothing on spark`() { assertFalse(SparkUi(balanceSats = 0uL).showsExit) } + + @Test + fun `earlier exit addresses keep spark listed once it is empty or offline`() = test { + val earlier = SparkExitEarlierAddress( + address = "bcrt1qearlier", + path = "m/84'/1'/7797'/0/0", + kind = SparkExitEarlierAddress.Kind.KEPT_CHANGE, + sats = 294uL, + atMillis = 0L, + ) + + val ui = assertNotNull(SparkState(isReady = false).toUi(mock(), earlierAddresses = listOf(earlier))) + + assertEquals(listOf(earlier), ui.earlierAddresses) + assertFalse(ui.showsExit, "an empty spark offers no exit") + } } From d9169400c4941ea4a98a78350e5d40970aa0bf2d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:15:13 +0100 Subject: [PATCH 130/154] refactor: split the exit's funding build out of the tick --- .../to/bitkit/repositories/SparkExitDriver.kt | 50 ++++++++++--------- .../repositories/SparkExitEarlierAddress.kt | 2 +- 2 files changed, 27 insertions(+), 25 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 054847ab39..1c7c2420f4 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -154,30 +154,7 @@ class SparkExitDriver( Logger.warn("Releasing Spark exit leaves '${record.waitingLeafIds}' unfunded", context = TAG) record = end(record.ended(), record) } else if (sdk != null && record.phase.requiredFundingSats != null) { - val shortfall = record.fundingShortfallSats - // Nothing to fund when every leaf is recovered cooperatively. - val funded = if (shortfall != null) adoptFunding(record, shortfall) else record - record = when { - // A generation that diverged while a top-up was awaited rebuilds from the funding it already - // has when that pays for it, so a top-up that never comes does not leave the exit waiting. - funded == null && record.isRedoRebuild && record.isRebuilding && isRebuildDue(record) -> - build(record, sdk).let { tried -> - if (tried.phase is SparkExitRecord.Phase.NeedsFunding) { - countShortOwnPayment(tried.copy(lastBuildAt = nowMillis())) - } else { - tried - } - } - funded == null -> countShortOwnPayment(record) - // Funding for leaves a partial build skipped: only they are built, once it arrived. - funded.isFundingWaitingLeaves -> retryWaitingLeaves(funded, sdk, isFunded = true) - ?: end(funded.ended(), funded) - // Funding an unverified rebuild asked for resumes that rebuild, with its guards. - else -> { - val isUnverified = funded.isUnverifiedAsk && !funded.isRebuilding - build(funded, sdk, isUnverifiedRebuild = isUnverified) - } - } + record = buildOnceFunded(record, sdk) } } SparkExitRecord.Phase.Running if record.isRebuilding -> { @@ -201,6 +178,31 @@ class SparkExitDriver( return record } + /** Builds once the funding [record] waits for arrived, or from what it holds when that pays for a Redo rebuild. */ + private suspend fun buildOnceFunded(record: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { + val shortfall = record.fundingShortfallSats + // Nothing to fund when every leaf is recovered cooperatively. + val funded = if (shortfall != null) adoptFunding(record, shortfall) else record + return when { + // A generation that diverged while a top-up was awaited rebuilds from the funding it already has when + // that pays for it, so a top-up that never comes does not leave the exit waiting. + funded == null && record.isRedoRebuild && record.isRebuilding && isRebuildDue(record) -> + build(record, sdk).let { tried -> + if (tried.phase is SparkExitRecord.Phase.NeedsFunding) { + countShortOwnPayment(tried.copy(lastBuildAt = nowMillis())) + } else { + tried + } + } + funded == null -> countShortOwnPayment(record) + // Funding for leaves a partial build skipped: only they are built, once it arrived. + funded.isFundingWaitingLeaves -> retryWaitingLeaves(funded, sdk, isFunded = true) + ?: end(funded.ended(), funded) + // Funding an unverified rebuild asked for resumes that rebuild, with its guards. + else -> build(funded, sdk, isUnverifiedRebuild = funded.isUnverifiedAsk && !funded.isRebuilding) + } + } + private suspend fun adoptFunding(record: SparkExitRecord, requiredSats: ULong): SparkExitRecord? { val first = record.funding.firstOrNull() ?: return null val candidates = SparkExitMath.newFunding(chain.utxos(first.address), record) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt index 5b1e904b0d..7901be5018 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt @@ -45,7 +45,7 @@ data class SparkExitEarlierAddress( address = address, path = SparkExitFundingKey.path(record.fundingIndex.toInt(), network), kind = Kind.KEPT_CHANGE, - sats = record.leftover.fold(0uL) { sum, it -> sum.safe() + it.valueSats.safe() }, + sats = record.leftover.fold(0uL) { sum, leftover -> sum.safe() + leftover.valueSats.safe() }, atMillis = atMillis, ) } From 223194ef6af464cd1764f20b4efcdfc7ffc47bf6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:18:14 +0100 Subject: [PATCH 131/154] fix: keep a loss alert posted when an exit's fee ask ends --- .../to/bitkit/repositories/SparkExitRepo.kt | 2 +- .../to/bitkit/repositories/SparkExitWorker.kt | 14 +++++-- .../bitkit/repositories/SparkExitWorkTest.kt | 39 +++++++++++++++++++ 3 files changed, 51 insertions(+), 4 deletions(-) create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitWorkTest.kt diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 50a6439159..a5d0eafd3b 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -459,7 +459,7 @@ class SparkExitRepo @Inject constructor( ) } if (SparkExitAlerts.isFundingAskBack(record, previous)) work.notify(SparkExitAlert.Funding) - if (SparkExitAlerts.isFundingAskWithdrawn(record, previous)) work.dismissNotification() + if (SparkExitAlerts.isFundingAskWithdrawn(record, previous)) work.dismissFundingAsk() when (record.phase) { // Waiting on the operators for a week needs nothing from the user, so nothing reminds them. SparkExitRecord.Phase.Running if record.isWaitingForOperators -> { diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt index eaa4b8e4a2..7afb717d83 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -89,6 +89,7 @@ class SparkExitWork @Inject constructor( private const val KEY_DEADLINE_AT = "deadline-at" private const val KEY_FEE_LOW_RATE = "fee-low-rate" private const val KEY_FUNDING_REMINDED = "funding-reminded-exit" + private const val KEY_POSTED_ALERT = "posted-alert" private const val NOTIFICATION_ID = 7797 /** The shortest period WorkManager runs periodic work at. */ @@ -159,9 +160,14 @@ class SparkExitWork @Inject constructor( ) } - /** Takes back the exit's posted notification, such as a fee ask the exit no longer has. */ - fun dismissNotification() { + /** + * Takes back a fee ask the exit no longer has, while it is what the exit's notification shows: a loss or another + * alert posted over it stays. + */ + fun dismissFundingAsk() { + if (preferences.getString(KEY_POSTED_ALERT, null) != SparkExitAlert.Funding.name) return context.notificationManagerCompat.cancel(NOTIFICATION_ID) + preferences.edit { remove(KEY_POSTED_ALERT) } } fun cancelDeadline() { @@ -282,13 +288,15 @@ class SparkExitWork @Inject constructor( .replace("{time}", time.orEmpty()) .replace("{amount}", amount.orEmpty()) .replace("{rate}", feeRateSatPerVbyte?.toString().orEmpty()) - context.pushNotification( + val id = context.pushNotification( title = context.getString(R.string.lightning__spark_exit__notification_title), text = text, extras = bundleOf(EXTRA_SPARK_EXIT to true), bigText = text, id = NOTIFICATION_ID, ) + // The exit posts one notification at a time: what it shows now, so taking back a fee ask leaves any other. + if (id == NOTIFICATION_ID) preferences.edit { putString(KEY_POSTED_ALERT, alert.name) } } fun backgroundLimits(): SparkExitBackgroundLimits { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitWorkTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitWorkTest.kt new file mode 100644 index 0000000000..8da88a997f --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitWorkTest.kt @@ -0,0 +1,39 @@ +package to.bitkit.repositories + +import android.app.NotificationManager +import android.content.Context +import androidx.test.core.app.ApplicationProvider +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.kotlin.mock +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import to.bitkit.test.BaseUnitTest +import kotlin.test.assertEquals + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [32]) +class SparkExitWorkTest : BaseUnitTest() { + private val context = ApplicationProvider.getApplicationContext() + private val sut = SparkExitWork(context, testDispatcher, mock(), mock()) + private val posted get() = context.getSystemService(NotificationManager::class.java).activeNotifications + + @Test + fun `a loss posted in the tick that clears the fee ask stays posted`() { + sut.notify(SparkExitAlert.Funding) + sut.notify(SparkExitAlert.Lost, amountSats = 8_192uL) + + sut.dismissFundingAsk() + + assertEquals(1, posted.size, "the loss alert was taken back with the fee ask") + } + + @Test + fun `a fee ask the exit no longer has is taken back`() { + sut.notify(SparkExitAlert.Funding) + + sut.dismissFundingAsk() + + assertEquals(0, posted.size) + } +} From 62d696a9ec41412663a4fa42bb5917588a4a4721 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:20:49 +0100 Subject: [PATCH 132/154] fix: keep the valid exit generation over a rebuild that skips an unread leaf --- .../to/bitkit/repositories/SparkExitDriver.kt | 13 +++-- .../repositories/SparkExitDriverTest.kt | 51 +++++++++++++++++++ 2 files changed, 61 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 1c7c2420f4..c47b1701d6 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -285,7 +285,7 @@ class SparkExitDriver( val waiting = waitingLeafIds(record, prepared.skipped, stopped) // Adopted, it would drop the signed steps of the leaf it could not read for the week the failed // leaves are retried, past the window in which they are ours to publish. - if (isUnverifiedRebuild && waiting.isNotEmpty()) return record.keepingValidGeneration() + if (isUnverifiedRebuild && record.recoversAny(waiting)) return record.keepingValidGeneration() val adopted = record.adopt(built, nowMillis()).copy(waitingLeafIds = waiting) save(adopted) Logger.info("Built Spark exit of only '${built.failed.size}' failed cooperative leaves", context = TAG) @@ -297,8 +297,11 @@ class SparkExitDriver( val lost = record.lostLeaves(built).filter { !isStoppedWaiting(record, it.leafId, stopped) } if (lost.isNotEmpty()) return loseLeaves(record, lost) // A leaf that may still move is kept apart and tried again before the exit ends. - val adopted = record.adopt(built, nowMillis()) - .copy(waitingLeafIds = waitingLeafIds(record, prepared.skipped, stopped)) + val waiting = waitingLeafIds(record, prepared.skipped, stopped) + // An unverified rebuild of other leaves would drop the signed steps of a waiting leaf the valid generation + // recovers, until the other leaves' chains confirm: the valid generation stays, rebuilt over once a block. + if (isUnverifiedRebuild && record.recoversAny(waiting)) return record.keepingValidGeneration() + val adopted = record.adopt(built, nowMillis()).copy(waitingLeafIds = waiting) // Saved before any of it is broadcast, so a crash never leaves broadcast transactions without their record. save(adopted) Logger.info( @@ -1488,3 +1491,7 @@ object SparkExitTxOutputs { */ private fun SparkExitRecord.keepingValidGeneration(): SparkExitRecord = if (isUnverifiedAsk) copy(phase = SparkExitRecord.Phase.Running, isUnverifiedAsk = false) else this + +/** The current recovery recovers one of [leafIds]: its signed steps for them would go with a new generation. */ +private fun SparkExitRecord.recoversAny(leafIds: List): Boolean = + recovery?.leaves?.any { it.leafId in leafIds } == true diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 442b11272a..fc8559f62d 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -523,6 +523,57 @@ class SparkExitDriverTest : BaseUnitTest() { assertTrue(chain.broadcasts.none { it.txid == "n1" || it.txid == "n2" }, "a diverged step was sent again") } + /** + * An unverified rebuild that skips the leaf it could not read but builds another unilateral leaf keeps the valid + * generation: the unread leaf's signed steps are still sent once the chain reads again. + */ + @Test + fun `an unverified rebuild beside another unilateral leaf keeps the valid generation`() = test { + val unread = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + SparkExitFixtures.tx("m1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx( + "m2", + dependsOn = listOf("m1"), + status = ExitTransactionStatus.WaitingForTimelock(2_000u), + ), + ), + ) + sdk.checks += check(unread, RecoveryVerdict.Valid) + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-2")).copy( + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + repeat(2) { + sdk.builds += SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("m1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx( + "m2b", + dependsOn = listOf("m1"), + status = ExitTransactionStatus.WaitingForTimelock(2_000u), + ), + ), + ) + } + val start = running(unread).copy(leafIds = listOf("leaf-1", "leaf-2")) + + var record = driver(tip = 1_000u).tick(start) + assertEquals(1, record.generation, "rebuild adopted a recovery without leaf-1's signed steps") + + // The chain reads again: whatever the record holds, its unverified steps now read as ready. + val held = assertNotNull(record.recovery) + val reread = held.copy( + transactions = held.transactions.map { + if (it.status == ExitTransactionStatus.Unverified) it.copy(status = ExitTransactionStatus.Ready) else it + }, + ) + sdk.checks += check(reread, RecoveryVerdict.Valid) + record = driver(tip = 1_001u).tick(record) + assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }, "leaf-1's matured step n2 was not sent") + } + @Test fun `an unverified unilateral step waits while another unilateral step is ready`() = test { val recovery = SparkExitFixtures.recovery( From f1bbfe4f60a3307d247bc1750c57dfac1208ec9b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 15:32:59 +0100 Subject: [PATCH 133/154] fix: refuse move to spark while an exit holds spark --- .../to/bitkit/repositories/MoveToSparkRepo.kt | 2 +- .../to/bitkit/repositories/MoveToSparkRepoTest.kt | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt index 5336be59bd..e46b0f3da3 100644 --- a/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/MoveToSparkRepo.kt @@ -240,7 +240,7 @@ object MoveToSparkMath { fun movableSats(channels: List?): ULong = channels.totalNextOutboundHtlcLimitSats() /** Whether Spark can take a move; every Move to Spark check goes through here. */ - fun isSparkUsable(spark: SparkState): Boolean = spark.isReady + fun isSparkUsable(spark: SparkState): Boolean = spark.isReady && !spark.isExiting /** Whether the channels hold a balance worth moving to a usable Spark wallet. */ fun canMove(channels: List?, spark: SparkState): Boolean = diff --git a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt index f40f18134e..5ff73f3f3d 100644 --- a/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/MoveToSparkRepoTest.kt @@ -130,6 +130,21 @@ class MoveToSparkRepoTest : BaseUnitTest() { assertIs(sut.quote().exceptionOrNull()) } + @Test + fun `quote fails while an exit holds Spark`() = test { + sendable(100_000uL) + sparkState.value = SparkState(isReady = true, isExiting = true) + + assertIs(sut.quote().exceptionOrNull()) + verify(sparkRepo, never()).createInvoice(anyOrNull(), any(), any()) + } + + @Test + fun `a move is not offered while an exit holds Spark`() { + val channels = listOf(createChannelDetails().copy(isUsable = true, nextOutboundHtlcLimitMsat = 5_000_000uL)) + assertTrue(!MoveToSparkMath.canMove(channels, SparkState(isReady = true, isExiting = true))) + } + @Test fun `a move is offered only with a usable Spark and a balance above the minimum`() { val channels = listOf(createChannelDetails().copy(isUsable = true, nextOutboundHtlcLimitMsat = 5_000_000uL)) From 5b6da91a5f4c21d16fa6b2892dd7e9557d7b1ea6 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 16:26:22 +0100 Subject: [PATCH 134/154] fix: keep the retry clock after a funded unverified rebuild --- .../to/bitkit/repositories/SparkExitDriver.kt | 7 ++- .../repositories/SparkExitDriverTest.kt | 58 +++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index c47b1701d6..c12e73adc2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -199,7 +199,12 @@ class SparkExitDriver( funded.isFundingWaitingLeaves -> retryWaitingLeaves(funded, sdk, isFunded = true) ?: end(funded.ended(), funded) // Funding an unverified rebuild asked for resumes that rebuild, with its guards. - else -> build(funded, sdk, isUnverifiedRebuild = funded.isUnverifiedAsk && !funded.isRebuilding) + funded.isUnverifiedAsk && !funded.isRebuilding -> build(funded, sdk, isUnverifiedRebuild = true).let { + // A resume that adopted nothing keeps the valid generation's retry clock, as a check's rebuild does. + if (it.generation != funded.generation || !it.isActive) return@let it + it.copy(retrySince = funded.retrySince, retriedAt = funded.retriedAt) + } + else -> build(funded, sdk) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index fc8559f62d..ec5be21c0e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -493,6 +493,64 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(unverified.transactions.map { it.txid }, record.recovery?.transactions?.map { it.txid }) } + @Test + fun `a funded unverified rebuild that waits for the unread leaf leaves no stale retry clock`() = test { + val unread = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + val timelocked = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx( + "n2", + dependsOn = listOf("n1"), + status = ExitTransactionStatus.WaitingForTimelock(3_000u), + ), + ), + ) + val ready = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1")), + ), + ) + sdk.checks += check(unread, RecoveryVerdict.Valid) + sdk.checks += check(unread, RecoveryVerdict.Valid) + sdk.checks += check(timelocked, RecoveryVerdict.Valid) + sdk.checks += check(unread, RecoveryVerdict.Valid) + sdk.checks += check(ready, RecoveryVerdict.Valid) + sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") + sdk.preparedResponses += SparkExitFixtures.prepared() + sdk.preparedResponse = SparkExitFixtures.prepared( + leaves = emptyList(), + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + + var record = driver(tip = 1_000u).tick(running(unread)) + assertIs(record.phase) + assertTrue(record.isUnverifiedAsk) + + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + listOf(SparkExitFixtures.utxo("f0", value = 100_000uL)) + record = driver(tip = 1_001u).tick(record) + assertEquals(1, record.generation) + assertNull(record.retrySince, "the funded unverified rebuild saved a retry clock at '${record.retrySince}'") + + record = driver(tip = 1_002u).tick(record) + assertEquals(Phase.Running, record.phase) + assertNull(record.retrySince, "the ask ended Running with a stale retry clock '${record.retrySince}'") + + record = driver(tip = 2_100u).tick(record) + assertEquals(Phase.Running, record.phase, "the exit ended before leaf-1's signed step n2 was sent") + assertEquals(1, record.generation) + + record = driver(tip = 3_000u).tick(record) + assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }, "leaf-1's matured step n2 was not sent") + } + @Test fun `an unverified rebuild's ask that diverged never sends the diverged generation again`() = test { val unverified = SparkExitFixtures.recovery( From 20d4be0de64e5907617b6254992fb50a0dd9ac9c Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 18:09:37 +0100 Subject: [PATCH 135/154] fix: let a refused leftover sweep show once A leftover sweep refused for good now shows its result once, like kept change, then lets a later exit start. Its funding address and derivation path go onto Earlier exit addresses. --- .../to/bitkit/repositories/SparkExitDriver.kt | 8 ++++--- .../repositories/SparkExitEarlierAddress.kt | 6 ++--- .../to/bitkit/repositories/SparkExitRecord.kt | 21 +++++++++++------- .../to/bitkit/repositories/SparkExitRepo.kt | 2 +- .../repositories/SparkExitRecordTest.kt | 22 +++++++++++++++++++ 5 files changed, 44 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index c12e73adc2..be4e81c4f9 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -1086,9 +1086,11 @@ class SparkExitDriver( is SparkExitBroadcastOutcome.Rejected if sweep.replacedTxids.isNotEmpty() && tip != null && !outcome.reason.contains("fee", ignoreCase = true) -> waitForFees(record.copy(leftoverSweep = sweep)) - is SparkExitBroadcastOutcome.Rejected -> record.copy( - leftoverSweep = sweep.copy(isAccepted = false, rejection = outcome.reason), - ) + is SparkExitBroadcastOutcome.Rejected -> { + val refused = sweep.copy(isAccepted = false, rejection = outcome.reason) + // A refusal for anything but its fee is final: shown once more with its address, as kept change is. + record.copy(leftoverSweep = refused, isResultSeen = record.isResultSeen && refused.isFeeRejection) + } // Its inputs went elsewhere: what is still at the address is read and swept again. is SparkExitBroadcastOutcome.InputsMissing -> readAddressAgain(record, sweep) is SparkExitBroadcastOutcome.RetryLater, diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt index 7901be5018..720b042c27 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt @@ -23,7 +23,7 @@ data class SparkExitEarlierAddress( val atMillis: Long, ) { enum class Kind { - /** Fee change too small to send, kept at the funding address for good. */ + /** Fee funding left at the funding address for good: change too small to send, or a refused sweep's. */ KEPT_CHANGE, /** The funding address of a cancelled exit that was forgotten: a late payment can still land there. */ @@ -37,9 +37,9 @@ data class SparkExitEarlierAddress( companion object { val WATCH_PERIOD = 28.days - /** The kept fee change of an ended exit, or null when it kept none. */ + /** The leftover an ended exit kept at its funding address, or null when it kept none. */ fun keptChange(record: SparkExitRecord, network: Network, atMillis: Long): SparkExitEarlierAddress? { - if (!record.isChangeKept) return null + if (!record.isLeftoverKept) return null val address = record.funding.firstOrNull()?.address ?: return null return SparkExitEarlierAddress( address = address, diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index 1322713d7c..b38e73f0b5 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -347,22 +347,27 @@ data class SparkExitRecord( /** * Emergency exit opens progress, not a new exit, while this one runs and until its leftover fee funding is swept - * and confirmed, or kept as dust. A rejected sweep keeps it too: progress names the address the leftover is at. - * An exit that failed, lost leaves or kept its change keeps it until the user opened it once; kept change then - * stays listed among the earlier exit addresses, so a new exit can replace the record. + * and confirmed, or kept as dust. An exit that failed, lost leaves or left its leftover at the funding address + * keeps it until the user opened it once; that address then stays listed among the earlier exit addresses, so a + * new exit can replace the record. */ val showsResult: Boolean - get() = isActive || isLeftoverSweepPending || isEndedPaymentPending || - (leftover.isNotEmpty() && leftoverSweep?.rejection != null) || - hasUnseenResult + get() = isActive || isLeftoverSweepPending || isEndedPaymentPending || hasUnseenResult - /** The exit ended failed, with leaves lost or its fee change kept, and the user has not opened its result yet. */ + /** The exit ended failed, with leaves lost or its leftover kept, and the user has not opened its result yet. */ val hasUnseenResult: Boolean - get() = !isActive && (phase is Phase.Failed || lostSats > 0uL || isChangeKept) && !isResultSeen + get() = !isActive && (phase is Phase.Failed || lostSats > 0uL || isLeftoverKept) && !isResultSeen /** The fee change stays at the funding address for good, shown with the path that spends it. */ val isChangeKept: Boolean get() = leftover.isNotEmpty() && leftoverSweep?.isDustKept == true + /** + * The leftover stays at the funding address for good: change too small to send, or a sweep refused for a reason + * other than its fee, which nothing retries. + */ + val isLeftoverKept: Boolean + get() = isChangeKept || (leftover.isNotEmpty() && leftoverSweep?.rejection != null && !isLeftoverSweepPending) + /** Background runs and the foreground loop keep going while the exit runs and until its leftover is swept. */ val needsDriving: Boolean get() = isActive || isLeftoverSweepPending || isEndedPaymentPending diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index a5d0eafd3b..fc75d221d7 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -355,7 +355,7 @@ class SparkExitRepo @Inject constructor( reportedLost: Set, ) { record.transferId?.let { transferRepo.updateClaimableAtHeight(it, record.claimableAtHeight) } - if (record.isChangeKept && !previous.isChangeKept) { + if (record.isLeftoverKept && !previous.isLeftoverKept) { keepEarlierAddress(SparkExitEarlierAddress.keptChange(record, Env.network, clock.nowMs())) } settleIfFinished(record) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt index 5e5b861579..11d7a2d0d6 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -16,6 +16,7 @@ import kotlinx.serialization.json.jsonPrimitive import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder +import org.lightningdevkit.ldknode.Network import java.io.File import kotlin.test.assertEquals import kotlin.test.assertFailsWith @@ -340,4 +341,25 @@ class SparkExitRecordTest { val seen = failed.copy(isResultSeen = true) assertEquals(seen, SparkExitJson.decode(SparkExitJson.encode(seen))) } + + @Test + fun `a leftover sweep refused for good shows once, then its address stays listed`() { + val refused = SparkExitFixtures.record(SparkExitRecord.Phase.Done).copy( + leftover = listOf(SparkExitRecord.Leftover("ab".repeat(32), 0u, 5_035uL)), + leftoverSweep = SparkExitRecord.LeftoverSweep( + txid = "t", + txHex = "02", + valueSats = 4_000uL, + rejection = "non-mandatory-script-verify-flag", + ), + ) + assertTrue(refused.showsResult, "the leftover's address and path were out of reach") + assertTrue(refused.hasUnseenResult, "opening the result never lets the refused sweep go") + assertFalse(refused.copy(isResultSeen = true).showsResult, "the refused sweep blocks every later exit") + + val listed = assertNotNull(SparkExitEarlierAddress.keptChange(refused, Network.REGTEST, 0L), "in no list") + assertEquals(SparkExitFixtures.FUNDING_ADDRESS, listed.address) + assertEquals(SparkExitEarlierAddress.Kind.KEPT_CHANGE, listed.kind) + assertEquals(5_035uL, listed.sats) + } } From a8652b94bee9b53a36442ea23a26be4df68f18ac Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 18:09:37 +0100 Subject: [PATCH 136/154] fix: read kept change at earlier exit addresses Kept change entries are read whenever the list is, as cancelled exits' addresses are, so the balance shown is current once the change was spent by hand. --- .../bitkit/repositories/SparkExitEarlierAddress.kt | 7 +++++-- .../java/to/bitkit/repositories/SparkExitRepo.kt | 4 ++-- .../to/bitkit/repositories/SparkExitRepoTest.kt | 13 +++++++++++++ 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt index 720b042c27..9555c540fc 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt @@ -30,9 +30,12 @@ data class SparkExitEarlierAddress( CANCELLED_FUNDING, } - /** A cancelled exit's address younger than about four weeks, read in the foreground for a late payment. */ + /** + * Read in the foreground for what it holds: kept change always, so change spent by hand shows as spent, and a + * cancelled exit's address for about four weeks, for a late payment. + */ fun isWatched(nowMillis: Long): Boolean = - kind == Kind.CANCELLED_FUNDING && nowMillis - atMillis < WATCH_PERIOD.inWholeMilliseconds + kind == Kind.KEPT_CHANGE || nowMillis - atMillis < WATCH_PERIOD.inWholeMilliseconds companion object { val WATCH_PERIOD = 28.days diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index fc75d221d7..679f8f5c18 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -220,8 +220,8 @@ class SparkExitRepo @Inject constructor( } /** - * Reads what reached each cancelled exit's address still watched, about four weeks after the cancel, so a late - * payment shows with its balance among the earlier exit addresses. + * Reads what each watched earlier exit address holds: kept change, and a cancelled exit's address for about four + * weeks after the cancel, so a late payment or change spent by hand shows with its balance. */ suspend fun refreshEarlierAddresses() = withContext(bgDispatcher) { val chain = chain ?: return@withContext diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 2f92c9460c..5fbf058cdb 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -965,6 +965,19 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(8_000uL, store.load().first().sats) } + @Test + fun `kept change spent by hand shows its current balance`() = test { + val store = SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(0))) + val kind = SparkExitEarlierAddress.Kind.KEPT_CHANGE + store.add(SparkExitEarlierAddress(funding, "m/84'/1'/7797'/0/0", kind, sats = 600uL, atMillis = 0L)) + val sut = quotedSut(FakeSparkExitRecovering(), fundingChain(utxos = "[]")) + sut.load().getOrThrow() + + sut.refreshEarlierAddresses() + + assertEquals(listOf(0uL), sut.state.value.earlierAddresses.map { it.sats }, "the spent change still shows") + } + @Test fun `an exit that kept its fee change lists the address, so the next exit can start`() = test { val kept = SparkExitFixtures.record(Phase.Done).copy( From 712ae3411fc1100c14cf0c8ea3ca1c51f097ed09 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 18:09:37 +0100 Subject: [PATCH 137/154] docs: fix kept change comment --- app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index be4e81c4f9..38c4aaee36 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -817,7 +817,8 @@ class SparkExitDriver( val since = requireNotNull(built.waitingSince) if (height >= since + SWEEP_RELEASE_BLOCKS) { Logger.info("Keeping the Spark exit leftover as dust after waiting for cheaper fees", context = TAG) - // Shown once more with its path, even after the result was opened: nothing else reaches that address. + // Shown once more with its path, even after the result was opened; the earlier exit addresses keep + // listing it after that. return record.copy(leftoverSweep = built.copy(isDustKept = true), isResultSeen = false) } val next = built.retryAtHeight ?: ((built.checkedAtHeight ?: since) + SWEEP_RECHECK_BLOCKS) From 52e5d34690fe8aebfd255cc9d2aa7413d73b9425 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 19:26:41 +0100 Subject: [PATCH 138/154] fix: guard every rebuild over a valid exit generation --- .../to/bitkit/repositories/SparkExitDriver.kt | 32 +++++---- .../repositories/SparkExitDriverTest.kt | 69 +++++++++++++++++++ 2 files changed, 87 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 38c4aaee36..1301112240 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -219,10 +219,10 @@ class SparkExitDriver( } /** - * Builds [start]'s leaves as a new generation. With [isUnverifiedRebuild], the generation it rebuilds over is still - * valid and stays the exit's, sent every tick, unless the build replaces it with signed steps: a build that asks - * for more fee funding keeps sending it while the top-up waits, and one of only failed cooperative leaves beside a - * leaf it could not read is not adopted. + * Builds [start]'s leaves as a new generation. Over a generation that did not diverge, however the build was + * reached (an unverified rebuild, a fee bump, a rebuild after a leaf was left behind), a build that leaves + * waiting a leaf that generation recovers is not adopted: the generation stays the exit's, sent every tick. + * With [isUnverifiedRebuild], a build that asks for more fee funding also keeps sending it while the top-up waits. */ private suspend fun build( start: SparkExitRecord, @@ -290,7 +290,7 @@ class SparkExitDriver( val waiting = waitingLeafIds(record, prepared.skipped, stopped) // Adopted, it would drop the signed steps of the leaf it could not read for the week the failed // leaves are retried, past the window in which they are ours to publish. - if (isUnverifiedRebuild && record.recoversAny(waiting)) return record.keepingValidGeneration() + if (record.keepsValidGenerationOver(waiting)) return record.keepingValidGeneration() val adopted = record.adopt(built, nowMillis()).copy(waitingLeafIds = waiting) save(adopted) Logger.info("Built Spark exit of only '${built.failed.size}' failed cooperative leaves", context = TAG) @@ -303,9 +303,9 @@ class SparkExitDriver( if (lost.isNotEmpty()) return loseLeaves(record, lost) // A leaf that may still move is kept apart and tried again before the exit ends. val waiting = waitingLeafIds(record, prepared.skipped, stopped) - // An unverified rebuild of other leaves would drop the signed steps of a waiting leaf the valid generation - // recovers, until the other leaves' chains confirm: the valid generation stays, rebuilt over once a block. - if (isUnverifiedRebuild && record.recoversAny(waiting)) return record.keepingValidGeneration() + // A rebuild of other leaves would drop the signed steps of a waiting leaf the valid generation recovers, until + // the other leaves' chains confirm: the valid generation stays, rebuilt over once a block. + if (record.keepsValidGenerationOver(waiting)) return record.keepingValidGeneration() val adopted = record.adopt(built, nowMillis()).copy(waitingLeafIds = waiting) // Saved before any of it is broadcast, so a crash never leaves broadcast transactions without their record. save(adopted) @@ -1494,12 +1494,16 @@ object SparkExitTxOutputs { } /** - * The valid generation stays the exit's over a rebuild it does not adopt. Funding an unverified rebuild asked for, once - * adopted, goes back to running it: the funding stays the exit's for the next rebuild. + * The valid generation stays the exit's over a rebuild it does not adopt, running again and sent every tick. Funding + * adopted for the rebuild, such as a fee bump's or an unverified rebuild's ask, and a bumped rate stay the exit's for + * the next rebuild. */ private fun SparkExitRecord.keepingValidGeneration(): SparkExitRecord = - if (isUnverifiedAsk) copy(phase = SparkExitRecord.Phase.Running, isUnverifiedAsk = false) else this + copy(phase = SparkExitRecord.Phase.Running, isRebuilding = false, isUnverifiedAsk = false) -/** The current recovery recovers one of [leafIds]: its signed steps for them would go with a new generation. */ -private fun SparkExitRecord.recoversAny(leafIds: List): Boolean = - recovery?.leaves?.any { it.leafId in leafIds } == true +/** + * The current generation did not diverge and recovers one of [leafIds]: its signed steps for them would go with a new + * generation that leaves them waiting. + */ +private fun SparkExitRecord.keepsValidGenerationOver(leafIds: List): Boolean = + !isRedoRebuild && recovery?.leaves?.any { it.leafId in leafIds } == true diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index ec5be21c0e..29d49f04f1 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1349,6 +1349,75 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("n1b"), chain.broadcasts.map { it.txid }) } + @Test + fun `a paid higher fee keeps the valid generation over a build that drops leaf-1's refund n2`() = test { + val failed = CooperativeRecoveryFailure( + "coop-1", + "o", + 0u, + CooperativeRecoveryError.OperatorsUnavailable("down"), + ) + val unread = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + var record = funded(running(unread).copy(leafIds = listOf("leaf-1", "coop-1"))) + .applyFeeBump(rate = 9uL, extraSats = 6_612uL, paymentTxid = "bump") + sdk.checks += check(unread, RecoveryVerdict.Valid) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf( + SparkExitFixtures.utxo("f0", value = 20_000uL), + SparkExitFixtures.utxo("bump", value = 6_612uL), + ) + sdk.preparedResponse = coopLeaf(16_384uL).copy( + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = listOf(failed)) + + record = driver(tip = 1_000u).tick(record) + + assertEquals(1, record.generation, "the paid bump adopted a recovery without leaf-1's refund n2") + assertTrue(saved.none { it.generation != 1 }, "a killed run would resume the recovery without leaf-1") + assertEquals(Phase.Running, record.phase) + assertFalse(record.isRebuilding) + assertEquals(listOf("n1", "n2"), record.recovery?.transactions?.map { it.txid }) + } + + @Test + fun `a higher fee with nothing to pay keeps the valid generation over a build that drops leaf-1's refund n2`() = + test { + val unread = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + var record = funded(running(unread).copy(leafIds = listOf("leaf-1", "leaf-2"))) + .applyFeeBump(rate = 9uL, extraSats = 0uL, paymentTxid = null) + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-2")).copy( + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("m1"))) + + record = driver(tip = 1_000u).tick(record) + + assertEquals(1, record.generation, "the bump adopted a recovery without leaf-1's refund n2") + assertTrue(saved.none { it.generation != 1 }, "a killed run would resume the recovery without leaf-1") + assertEquals(Phase.Running, record.phase) + assertFalse(record.isRebuilding, "the valid generation is no longer checked or sent") + + val reread = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1")), + ), + ) + sdk.checks += check(reread, RecoveryVerdict.Valid) + record = driver(tip = 1_001u).tick(record) + assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }, "leaf-1's refund n2 was not sent") + } + @Test fun `a rebuild from the chain keeps its note until one of its steps confirms`() = test { val built = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) From 4111d43a270935a60ba5816e9f107ff374e8bfb4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 19:26:50 +0100 Subject: [PATCH 139/154] test: keep the valid generation after a leaf is left behind --- .../repositories/SparkExitDriverTest.kt | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 29d49f04f1..a412ef7343 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -551,6 +551,39 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }, "leaf-1's matured step n2 was not sent") } + @Test + fun `a funded unverified rebuild that leaves a leaf behind keeps leaf-1's refund n2 on the next rebuild`() = test { + val unread = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + repeat(3) { sdk.checks += check(unread, RecoveryVerdict.Valid) } + sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") + sdk.recoverErrors += ladderRefusal("leaf-3") + sdk.preparedResponses += SparkExitFixtures.prepared() + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-2", "leaf-3")).copy( + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("m1"))) + val start = running(unread).copy(leafIds = listOf("leaf-1", "leaf-2", "leaf-3")) + + var record = driver(tip = 1_000u).tick(start) + assertTrue(record.isUnverifiedAsk) + + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + listOf(SparkExitFixtures.utxo("f0", value = 100_000uL)) + // The funded resume cannot exit leaf-3 and leaves it behind; leaf-1 still reads unverified. + record = driver(tip = 1_001u).tick(record) + now += interval + record = driver(tip = 1_002u).tick(record) + + assertEquals(1, record.generation, "the rebuild adopted a recovery without leaf-1's refund n2") + assertTrue(saved.none { it.generation != 1 }, "a killed run would resume the recovery without leaf-1") + assertEquals(listOf("n1", "n2"), record.recovery?.transactions?.map { it.txid }) + } + @Test fun `an unverified rebuild's ask that diverged never sends the diverged generation again`() = test { val unverified = SparkExitFixtures.recovery( From d3500913abe5206228958c1e0dd0fca87ef86294 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 19:28:15 +0100 Subject: [PATCH 140/154] fix: pace a funded unverified resume once a block --- .../to/bitkit/repositories/SparkExitDriver.kt | 16 +++++++--- .../repositories/SparkExitDriverTest.kt | 31 +++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index 1301112240..f85a274378 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -198,11 +198,17 @@ class SparkExitDriver( // Funding for leaves a partial build skipped: only they are built, once it arrived. funded.isFundingWaitingLeaves -> retryWaitingLeaves(funded, sdk, isFunded = true) ?: end(funded.ended(), funded) - // Funding an unverified rebuild asked for resumes that rebuild, with its guards. - funded.isUnverifiedAsk && !funded.isRebuilding -> build(funded, sdk, isUnverifiedRebuild = true).let { - // A resume that adopted nothing keeps the valid generation's retry clock, as a check's rebuild does. - if (it.generation != funded.generation || !it.isActive) return@let it - it.copy(retrySince = funded.retrySince, retriedAt = funded.retriedAt) + // Funding an unverified rebuild asked for resumes that rebuild, with its guards, once a block like the + // check's rebuild: the valid generation's retry clock does not pace it. + funded.isUnverifiedAsk && !funded.isRebuilding -> { + if (tip != null && funded.unverifiedRebuiltAtHeight == tip) return funded + val resumed = funded.copy(unverifiedRebuiltAtHeight = tip) + build(resumed, sdk, isUnverifiedRebuild = true).let { + // A resume that adopted nothing keeps the valid generation's retry clock, as a check's rebuild + // does. + if (it.generation != resumed.generation || !it.isActive) return@let it + it.copy(retrySince = resumed.retrySince, retriedAt = resumed.retriedAt) + } } else -> build(funded, sdk) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index a412ef7343..1c61eee3ab 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -584,6 +584,37 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("n1", "n2"), record.recovery?.transactions?.map { it.txid }) } + @Test + fun `a funded unverified rebuild waiting for the unread leaf prepares once a block`() = test { + val unread = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + repeat(4) { sdk.checks += check(unread, RecoveryVerdict.Valid) } + sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") + sdk.preparedResponses += SparkExitFixtures.prepared() + sdk.preparedResponse = SparkExitFixtures.prepared( + leaves = emptyList(), + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + + var record = driver(tip = 1_000u).tick(running(unread)) + assertTrue(record.isUnverifiedAsk) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + listOf(SparkExitFixtures.utxo("f0", value = 100_000uL)) + + record = driver(tip = 1_001u).tick(record) + assertEquals(2, sdk.prepareRequests.size) + record = driver(tip = 1_001u).tick(record) + assertEquals(2, sdk.prepareRequests.size, "the funded resume prepared again at the same tip") + + record = driver(tip = 1_002u).tick(record) + assertEquals(3, sdk.prepareRequests.size, "the funded resume stopped trying at the next block") + assertTrue(record.isUnverifiedAsk) + } + @Test fun `an unverified rebuild's ask that diverged never sends the diverged generation again`() = test { val unverified = SparkExitFixtures.recovery( From 77b2d92edc1f50be6da5e8fa14405af51dd04a41 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 19:28:30 +0100 Subject: [PATCH 141/154] chore: order the earlier exit address strings --- app/src/main/res/values/strings.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0cabd16624..6254236fef 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -433,6 +433,9 @@ {amount} reached your savings. Your funds are in savings. Exit\n<accent>complete</accent> + Earlier exit addresses + Earlier emergency exits used these funding addresses. Coins left at one stay yours: spend them with your recovery phrase and its derivation path. + Derivation path {amount} was moved on-chain by the Spark operators and is not on Spark. The operators can still release it to you. {amount} stays on Spark. Nothing could be recovered. @@ -464,9 +467,6 @@ Stays on Spark {amount} can\'t be exited at this fee rate and stays on Spark. {amount} of fee funding is still at {address}. - Earlier exit addresses - Earlier emergency exits used these funding addresses. Coins left at one stay yours: spend them with your recovery phrase and its derivation path. - Derivation path {amount} of leftover fee funding is too small to send and stays at {address}, derivation path {path}. {amount} of leftover fee funding could not be sent and stays at {address}, derivation path {path}. Sending {amount} of leftover fee funding to savings. From be0fb1177a3b62f21335e0cefa964edcc3d5be63 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 19:32:12 +0100 Subject: [PATCH 142/154] fix: keep reading kept change at a reused address --- .../repositories/SparkExitEarlierAddress.kt | 7 ++++++- .../bitkit/repositories/SparkExitRepoTest.kt | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt index 9555c540fc..03a15cfe9c 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt @@ -75,12 +75,17 @@ class SparkExitEarlierAddressStore(private val file: File) { return json.decodeFromString(file.readText()) } - /** Adds [entry], once per address: a known address keeps its entry, with [entry]'s amount when it has one. */ + /** + * Adds [entry], once per address: a known address keeps its entry, with [entry]'s amount when it has one. Kept + * change at a cancelled exit's address, which a later exit reused, replaces that entry, so it is read for good. + */ fun add(entry: SparkExitEarlierAddress): List { val known = runCatching { load() }.getOrDefault(emptyList()) val existing = known.firstOrNull { it.address == entry.address } val updated = when { existing == null -> known + entry + entry.kind == SparkExitEarlierAddress.Kind.KEPT_CHANGE && existing.kind != entry.kind -> + known.map { if (it.address == entry.address) entry.copy(sats = entry.sats ?: it.sats) else it } entry.sats == null || entry.sats == existing.sats -> return known else -> known.map { if (it.address == entry.address) it.copy(sats = entry.sats) else it } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 5fbf058cdb..5edf944569 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -946,6 +946,24 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(sut.state.value.earlierAddresses.isEmpty()) } + @Test + fun `kept change at a cancelled exit's reused address is read past the cancel's four weeks`() = test { + val store = SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(0))) + val path = "m/84'/1'/7797'/0/0" + val cancelledAt = 1_800_000_000_000L + val keptAt = cancelledAt + 20.days.inWholeMilliseconds + val cancelled = SparkExitEarlierAddress.Kind.CANCELLED_FUNDING + store.add(SparkExitEarlierAddress(funding, path, cancelled, atMillis = cancelledAt)) + + store.add(SparkExitEarlierAddress(funding, path, SparkExitEarlierAddress.Kind.KEPT_CHANGE, 600uL, keptAt)) + + val listed = store.load().single() + assertEquals(SparkExitEarlierAddress.Kind.KEPT_CHANGE, listed.kind, "the kept change stays a cancel's entry") + assertEquals(keptAt, listed.atMillis) + assertEquals(600uL, listed.sats) + assertTrue(listed.isWatched(cancelledAt + 60.days.inWholeMilliseconds), "the kept change is no longer read") + } + @Test fun `a late payment to a cancelled exit's address shows with its balance for four weeks`() = test { val now = 1_800_000_000_000L From 6b050833ee9221d3fe06718d5c92fd9e53851d18 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 20:48:57 +0100 Subject: [PATCH 143/154] fix: keep the valid generation over an unexitable leaf --- .../to/bitkit/repositories/SparkExitDriver.kt | 8 ++++- .../repositories/SparkExitDriverTest.kt | 30 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index f85a274378..f1a3b24eb0 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -279,7 +279,13 @@ class SparkExitDriver( // A leaf the SDK refuses to build is left behind, and the rest rebuilt on the next tick. SparkExitUnexitable.parse(it)?.takeIf { refusal -> refusal.leafId in record.exitLeafIds }?.let { refusal -> Logger.warn("Leaving behind Spark exit leaf '${refusal.leafId}': '${refusal.reason}'", context = TAG) - return record.leaveBehind(refusal.leafId, refusal.reason).copy(isRebuilding = true, lastBuildAt = null) + val left = record.leaveBehind(refusal.leafId, refusal.reason) + // Over a valid generation that recovers a leaf this build left waiting, that generation stays, + // rebuilt over again under this guard once a block. + if (left.keepsValidGenerationOver(waitingLeafIds(record, prepared.skipped, stopped))) { + return left.keepingValidGeneration() + } + return left.copy(isRebuilding = true, lastBuildAt = null) } if (it !is SdkException.InsufficientCpfpFunds) throw it val asked = askForFunding(record, it) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 1c61eee3ab..52d11d8920 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -584,6 +584,36 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("n1", "n2"), record.recovery?.transactions?.map { it.txid }) } + @Test + fun `a funded unverified rebuild that cannot exit a leaf keeps the valid generation running`() = test { + val unread = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + repeat(2) { sdk.checks += check(unread, RecoveryVerdict.Valid) } + sdk.recoverErrors += SdkException.InsufficientCpfpFunds(30_000uL, "") + sdk.recoverErrors += ladderRefusal("leaf-3") + sdk.preparedResponses += SparkExitFixtures.prepared() + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-2", "leaf-3")).copy( + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + val start = running(unread).copy(leafIds = listOf("leaf-1", "leaf-2", "leaf-3")) + var record = driver(tip = 1_000u).tick(start) + assertTrue(record.isUnverifiedAsk) + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = + listOf(SparkExitFixtures.utxo("f0", value = 100_000uL)) + + record = driver(tip = 1_001u).tick(record) + + assertEquals(1, record.generation) + assertFalse(record.isRebuilding, "the next tick rebuilds the exit without sending leaf-1's refund n2") + assertEquals(Phase.Running, record.phase) + assertEquals(listOf("n1", "n2"), record.recovery?.transactions?.map { it.txid }) + assertEquals(listOf("leaf-3"), record.leftBehindLeaves.map { it.leafId }) + } + @Test fun `a funded unverified rebuild waiting for the unread leaf prepares once a block`() = test { val unread = SparkExitFixtures.recovery( From 4f67dd8802aeb7380a7f9fca6482aa8ab71cccf4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 20:48:57 +0100 Subject: [PATCH 144/154] fix: fund the exit from savings only on spark's chain --- .../java/to/bitkit/repositories/SparkExitFunding.kt | 13 ++++++++++--- .../java/to/bitkit/repositories/SparkExitRepo.kt | 7 ++++++- .../to/bitkit/repositories/SparkExitFundingTest.kt | 11 ++++++++--- 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index fef8b6e155..49da94490e 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -517,9 +517,16 @@ object SparkExitMath { fun fundingIndexAfterForget(kept: Int?, index: UInt): Int? = if (kept != null && kept.toLong() == index.toLong() + 1) index.toInt() else kept - /** Savings can pay the fee funding when its spendable balance covers the funding and the payment's own fee. */ - fun canFundFromSavings(spendableSats: ULong, fundingSats: ULong, paymentFeeSats: ULong): Boolean = - fundingSats > 0uL && spendableSats >= fundingSats.safe() + paymentFeeSats.safe() + /** + * Savings can pay the fee funding when Spark reads the node's chain, which the payment goes out on + * ([sharesNodeChain]), and its spendable balance covers the funding and the payment's own fee. + */ + fun canFundFromSavings( + spendableSats: ULong, + fundingSats: ULong, + paymentFeeSats: ULong, + sharesNodeChain: Boolean, + ): Boolean = sharesNodeChain && fundingSats > 0uL && spendableSats >= fundingSats.safe() + paymentFeeSats.safe() } /** The fee funding an exit still needs, as progress shows it. */ diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 679f8f5c18..15dc82a721 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -714,7 +714,12 @@ class SparkExitRepo @Inject constructor( val spendable = lightningRepo.getBalancesAsync().getOrThrow().spendableOnchainBalanceSats SparkExitSavingsFunding( feeSats = feeSats, - canPay = SparkExitMath.canFundFromSavings(spendable, fundingSats, feeSats), + canPay = SparkExitMath.canFundFromSavings( + spendable, + fundingSats, + feeSats, + Env.sparkSharesNodeChain, + ), ) } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index 02dfb2a08d..d9d93977d7 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -319,9 +319,14 @@ class SparkExitFundingTest { @Test fun `savings must cover the funding and its fee`() { - assertTrue(SparkExitMath.canFundFromSavings(10_500uL, 10_000uL, 500uL)) - assertFalse(SparkExitMath.canFundFromSavings(10_499uL, 10_000uL, 500uL)) - assertFalse(SparkExitMath.canFundFromSavings(10_000uL, 0uL, 0uL)) + assertTrue(SparkExitMath.canFundFromSavings(10_500uL, 10_000uL, 500uL, sharesNodeChain = true)) + assertFalse(SparkExitMath.canFundFromSavings(10_499uL, 10_000uL, 500uL, sharesNodeChain = true)) + assertFalse(SparkExitMath.canFundFromSavings(10_000uL, 0uL, 0uL, sharesNodeChain = true)) + } + + @Test + fun `savings cannot fund an exit on a chain spark does not read`() { + assertFalse(SparkExitMath.canFundFromSavings(10_500uL, 10_000uL, 500uL, sharesNodeChain = false)) } @Test From 3d4e52babd063f56a65487419e478d28e5bcdb2d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 22:50:53 +0100 Subject: [PATCH 145/154] fix: keep the higher spark exit funding index on restore A restore from the metadata backup replaced the device's kept funding index of each wallet with the backed-up one. It now keeps the higher of the two, so a later exit never funds from an address an earlier exit used. --- .../java/to/bitkit/repositories/BackupRepo.kt | 11 ++++- .../bitkit/repositories/SparkExitFunding.kt | 4 ++ .../to/bitkit/repositories/BackupRepoTest.kt | 45 +++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 4945114a10..0c343fe70c 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1201,7 +1201,16 @@ class BackupRepo @Inject constructor( ) val parsed = decodeBackup(migration.json) val cleanCache = parsed.cache.resetBip21() // Force address rotation - cacheStore.update { cleanCache.copy(backupStatuses = it.backupStatuses) } + cacheStore.update { + cleanCache.copy( + backupStatuses = it.backupStatuses, + // The higher index of each wallet, so an exit never funds from an address an earlier one used. + sparkExitNextFundingIndexes = SparkExitMath.mergeFundingIndexes( + it.sparkExitNextFundingIndexes, + cleanCache.sparkExitNextFundingIndexes, + ), + ) + } Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.copy(cachedRates = emptyList()))}", TAG) onCacheRestored() val persisted = preActivityMetadataRepo.upsertPreActivityMetadata(parsed.tagMetadata) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 49da94490e..9d9c6ce5a9 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -510,6 +510,10 @@ object SparkExitMath { return maxOf(kept?.toUInt() ?: 0u, pastStored) } + /** Each wallet's higher next funding index of [local] and [restored]. */ + fun mergeFundingIndexes(local: Map, restored: Map): Map = + (local.keys + restored.keys).associateWith { maxOf(local[it] ?: 0, restored[it] ?: 0) } + /** * The next funding index once an exit at [index] is forgotten: given back when it was the last one used, so the * next exit watches that address again and a payment landing there late is not left where nothing looks. diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index a21e8842bd..35df40bf01 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -1829,6 +1829,51 @@ class BackupRepoTest : BaseUnitTest() { verify(vssBackupClient, never()).putObject(any(), any()) } + private suspend fun applyCacheUpdates() = doAnswer { + val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) + cacheData.update(transform) + }.whenever(cacheStore).update(any()) + + @Test + fun `a restore keeps the higher spark exit funding index of the device and the backup`() = test { + applyCacheUpdates() + cacheData.value = AppCacheData(sparkExitNextFundingIndexes = mapOf("regtest/wallet0" to 5)) + val backedUp = mapOf("regtest/wallet0" to 3, "regtest/wallet1" to 2) + stubMetadataRestore(envelope = metadataEnvelope(cache = AppCacheData(sparkExitNextFundingIndexes = backedUp))) + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals( + mapOf("regtest/wallet0" to 5, "regtest/wallet1" to 2), + cacheData.value.sparkExitNextFundingIndexes, + "an exit would fund from an address an earlier exit used", + ) + } + + @Test + fun `a restore brings back the backed-up spark exit funding index`() = test { + applyCacheUpdates() + val backedUp = mapOf("regtest/wallet0" to 3) + stubMetadataRestore(envelope = metadataEnvelope(cache = AppCacheData(sparkExitNextFundingIndexes = backedUp))) + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals(backedUp, cacheData.value.sparkExitNextFundingIndexes) + } + + @Test + fun `a metadata backup written before the spark exit funding index restores with none kept`() = test { + applyCacheUpdates() + val cache = json.parseToJsonElement(json.encodeToString(AppCacheData())).jsonObject - + "sparkExitNextFundingIndexes" + stubMetadataRestore(envelope = envelopeWithRawField(metadataEnvelope(), "cache", JsonObject(cache).toString())) + + val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertFalse(BackupCategory.METADATA in failed) + assertTrue(cacheData.value.sparkExitNextFundingIndexes.isEmpty(), "an exit then scans for the index") + } + @Test fun `metadata cache failure remains optional after public address quarantine succeeds`() = test { val publicAddress = "bcrt1qpublic" From 92d24048bb032e1a4a0bd95c62417b28e78ed27d Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 22:51:02 +0100 Subject: [PATCH 146/154] fix: find the spark exit funding index after a restore without one A wallet restored from the phrase, or from a backup older than the kept index, started its next exit at funding index 0. With no index kept and no record, the quote now reads the funding addresses from index 0 until 20 unused ones follow the last used (at most 1000), takes the index past it, and keeps it. A scan the chain fails fails the quote and keeps nothing. --- .../to/bitkit/repositories/SparkExitChain.kt | 11 +++ .../bitkit/repositories/SparkExitFunding.kt | 20 +++++ .../to/bitkit/repositories/SparkExitRepo.kt | 31 +++++-- .../bitkit/repositories/SparkExitChainTest.kt | 16 ++++ .../bitkit/repositories/SparkExitFixtures.kt | 6 ++ .../repositories/SparkExitFundingTest.kt | 27 ++++++ .../bitkit/repositories/SparkExitRepoTest.kt | 90 ++++++++++++++++++- 7 files changed, 195 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt index 8397a9d227..f779833419 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -71,6 +71,9 @@ sealed interface SparkExitBroadcastOutcome { interface SparkExitChain { suspend fun tipHeight(): UInt suspend fun utxos(address: String): List + + /** Whether [address] has any transaction, in a block or the mempool, from `/address/{address}`. */ + suspend fun isAddressUsed(address: String): Boolean suspend fun txStatus(txid: String): EsploraTxStatus /** @@ -199,6 +202,14 @@ class EsploraSparkExitChain( ) } + override suspend fun isAddressUsed(address: String): Boolean { + val stats = json.parseToJsonElement(get("/address/$address")).jsonObject + return listOf("chain_stats", "mempool_stats").any { key -> + val count = stats[key]?.jsonObject?.get("tx_count")?.jsonPrimitive?.longOrNull ?: 0L + count > 0 + } + } + override suspend fun txStatus(txid: String): EsploraTxStatus = status(json.parseToJsonElement(get("/tx/$txid/status")).jsonObject) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 9d9c6ce5a9..b6682799fe 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -510,6 +510,26 @@ object SparkExitMath { return maxOf(kept?.toUInt() ?: 0u, pastStored) } + /** Unused funding addresses a scan reads past the last used one before it stops. */ + const val FUNDING_SCAN_GAP_LIMIT = 20 + + /** The most funding addresses one scan reads, even when a host reports every one used. */ + const val FUNDING_SCAN_MAX_ADDRESSES = 1_000 + + /** + * The funding index past the last one [isUsed] reports used, read from 0 until [FUNDING_SCAN_GAP_LIMIT] unused ones + * follow it, for a wallet that kept no index, such as one restored from the phrase or an older backup. + */ + suspend fun scanNextFundingIndex(isUsed: suspend (UInt) -> Boolean): UInt { + var next = 0u + var index = 0u + while (index < next + FUNDING_SCAN_GAP_LIMIT.toUInt() && index < FUNDING_SCAN_MAX_ADDRESSES.toUInt()) { + if (isUsed(index)) next = index + 1u + index++ + } + return next + } + /** Each wallet's higher next funding index of [local] and [restored]. */ fun mergeFundingIndexes(local: Map, restored: Map): Map = (local.keys + restored.keys).associateWith { maxOf(local[it] ?: 0, restored[it] ?: 0) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 15dc82a721..f44ed55ac3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -9,6 +9,7 @@ import breez_sdk_spark.RecoveryTxKind import breez_sdk_spark.singleKeyCpfpSigner import com.synonym.bitkitcore.Activity import com.synonym.bitkitcore.FeeRates +import com.synonym.bitkitcore.GetAddressResponse import io.ktor.client.HttpClient import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job @@ -1119,16 +1120,36 @@ class SparkExitRepo @Inject constructor( it.copy(sparkExitNextFundingIndexes = indexes + (fundingIndexKey to back)) } - private suspend fun nextFundingIndex(): UInt = SparkExitMath.nextFundingIndex( - kept = cacheStore.data.first().sparkExitNextFundingIndexes[fundingIndexKey], - stored = runSuspendCatching { store.load() }.getOrNull(), - ) + /** + * With no index kept and no record, as after a restore from the phrase or from a backup older than the index, the + * funding addresses are scanned once and the result kept. A scan the chain fails keeps nothing. + */ + private suspend fun nextFundingIndex(): UInt { + val kept = cacheStore.data.first().sparkExitNextFundingIndexes[fundingIndexKey] + val stored = runSuspendCatching { store.load() }.getOrNull() + if (kept != null || stored != null) return SparkExitMath.nextFundingIndex(kept, stored) + val chain = chain ?: return 0u + val scanned = SparkExitMath.scanNextFundingIndex { chain.isAddressUsed(fundingAddress(it).address) } + cacheStore.update { + val indexes = it.sparkExitNextFundingIndexes + val next = maxOf(indexes[fundingIndexKey] ?: 0, scanned.toInt()) + it.copy(sparkExitNextFundingIndexes = indexes + (fundingIndexKey to next)) + } + return scanned + } + + private suspend fun fundingAddress(index: UInt): GetAddressResponse { + val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() + val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) + val path = SparkExitFundingKey.path(index = index.toInt(), network = Env.network) + return coreService.onchain.deriveBitcoinAddress(mnemonic, path, Env.network, passphrase) + } private suspend fun fundingKey(index: UInt): SparkExitFundingKey.Derived { val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) val path = SparkExitFundingKey.path(index = index.toInt(), network = Env.network) - val address = coreService.onchain.deriveBitcoinAddress(mnemonic, path, Env.network, passphrase) + val address = fundingAddress(index) val wif = coreService.onchain.derivePrivateKey(mnemonic, path, Env.network, passphrase) return SparkExitFundingKey.Derived(address.address, address.publicKey, SparkExitFundingKey.secretKey(wif)) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt index ac6df02170..7bb8a1b1d7 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -54,6 +54,22 @@ class SparkExitChainTest : BaseUnitTest() { return respond(route.body, HttpStatusCode.fromValue(route.status)) } + @Test + fun `an address with a transaction in a block or the mempool reads as used`() = test { + val stats = { chain: Int, mempool: Int -> + """{"chain_stats":{"tx_count":$chain},"mempool_stats":{"tx_count":$mempool}}""" + } + val sut = chain( + Route("a.example/api/address/bcrt1qmempool", 200, stats(0, 1)), + Route("a.example/api/address/bcrt1qspent", 200, stats(2, 0)), + Route("a.example/api/address/bcrt1qfresh", 200, stats(0, 0)), + ) + + assertTrue(sut.isAddressUsed("bcrt1qmempool")) + assertTrue(sut.isAddressUsed("bcrt1qspent")) + assertFalse(sut.isAddressUsed("bcrt1qfresh")) + } + @Test fun `sends a package as a raw json array of hex`() = test { val sut = chain(Route("a.example/api/v1/txs/package", 200, """{"package_msg":"success","tx-results":{}}""")) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt index 465b335255..ddc7ed36d2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -150,6 +150,12 @@ class FakeSparkExitChain : SparkExitChain { override suspend fun tipHeight() = tip + /** Addresses with a transaction though they hold nothing now. */ + var usedAddresses = setOf() + + override suspend fun isAddressUsed(address: String) = + address in usedAddresses || utxosByAddress[address].orEmpty().isNotEmpty() + override suspend fun utxos(address: String): List { utxosError?.let { throw it } return utxosByAddress[address].orEmpty() diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt index d9d93977d7..ec062e76bc 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -9,6 +9,7 @@ import breez_sdk_spark.RecoveryFunding import breez_sdk_spark.RecoveryTxKind import breez_sdk_spark.SkippedLeaf import breez_sdk_spark.SkippedLeafReason +import kotlinx.coroutines.test.runTest import org.junit.Test import org.lightningdevkit.ldknode.Network import to.bitkit.models.FeeRate @@ -725,4 +726,30 @@ class SparkExitFundingTest { val again = assertIs(SparkExitMath.fundingState(topUp, second)) assertEquals(SparkExitPartialFunding(2_283uL, 2_555uL, 294uL), again.partial) } + + @Test + fun `a funding scan takes the index past the last used address and reads the gap limit past it`() = runTest { + val reads = mutableListOf() + + val next = SparkExitMath.scanNextFundingIndex { + reads += it + it in setOf(0u, 2u, 5u) + } + + assertEquals(6u, next) + assertEquals((0u..(5u + SparkExitMath.FUNDING_SCAN_GAP_LIMIT.toUInt())).toList(), reads) + } + + @Test + fun `a funding scan stops at its ceiling when every address reads as used`() = runTest { + var reads = 0 + + val next = SparkExitMath.scanNextFundingIndex { + reads++ + true + } + + assertEquals(SparkExitMath.FUNDING_SCAN_MAX_ADDRESSES.toUInt(), next) + assertEquals(SparkExitMath.FUNDING_SCAN_MAX_ADDRESSES, reads) + } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 5edf944569..8c365d8f27 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -686,9 +686,11 @@ class SparkExitRepoTest : BaseUnitTest() { /** A compressed regtest WIF of a 32-byte secret of 0x01s. */ private val wif = "cMceqPhHedrhbcR9eXgzmfWy7kRqLyAxMYwFT6ABDWsiwUp9Nsq9" + private val keyedOnchain = mock() + private suspend fun keyed(): Pair { val keychain = mock { on { loadString(any()) } doReturn "mnemonic" } - val onchain = mock() + val onchain = keyedOnchain whenever(onchain.deriveBitcoinAddress(any(), anyOrNull(), anyOrNull(), anyOrNull())) .thenReturn(GetAddressResponse(funding, "m/84'/1'/7797'/0/0", "02ab")) whenever(onchain.derivePrivateKey(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenReturn(wif) @@ -712,6 +714,7 @@ class SparkExitRepoTest : BaseUnitTest() { val url = request.url.toString() when { url.endsWith("/address/$funding/utxo") && utxos != null -> respond(utxos) + url.endsWith("/address/$funding") -> respond(addressStats(txCount = 0)) url.endsWith("/blocks/tip/height") -> respond("1000") url.endsWith("/fee-estimates") -> respond("""{"1":9,"3":6,"144":1}""") else -> throw IOException("unreachable '$url'") @@ -720,6 +723,91 @@ class SparkExitRepoTest : BaseUnitTest() { }, ) { defaultRequest { contentType(ContentType.Application.Json) } } + private fun addressStats(txCount: Int) = + """{"chain_stats":{"tx_count":$txCount},"mempool_stats":{"tx_count":0}}""" + + private fun scannedAddress(index: Int) = "bcrt1qfunding$index" + + /** + * A chain where the funding addresses at [used] have a transaction, each index its own address, and the address + * reads [reads] lists; [isDown] answers every address read with a server error. + */ + private fun scanChain(used: Set, reads: MutableList, isDown: Boolean = false) = HttpClient( + MockEngine.create { + dispatcher = testDispatcher + addHandler { request -> + val url = request.url.toString() + val index = url.substringAfter("/address/bcrt1qfunding", "").toIntOrNull() + when { + index != null && isDown -> respond("", HttpStatusCode.InternalServerError) + index != null -> { + reads += index + respond(addressStats(txCount = if (index in used) 1 else 0)) + } + url.endsWith("/utxo") -> respond("[]") + url.endsWith("/blocks/tip/height") -> respond("1000") + url.endsWith("/fee-estimates") -> respond("""{"1":9,"3":6,"144":1}""") + else -> throw IOException("unreachable '$url'") + } + } + }, + ) { defaultRequest { contentType(ContentType.Application.Json) } } + + /** A quoted exit whose funding key at each index derives [scannedAddress] of that index. */ + private suspend fun scannedSut(http: HttpClient): SparkExitRepo { + val sut = quotedSut(FakeSparkExitRecovering(), http) + val onchain = keyedOnchain + whenever(onchain.deriveBitcoinAddress(any(), anyOrNull(), anyOrNull(), anyOrNull())).thenAnswer { + val path = it.getArgument(1) + GetAddressResponse(scannedAddress(path.substringAfterLast('/').toInt()), path, "02ab") + } + return sut + } + + private suspend fun keptFundingIndexes(): Map { + val updates = argumentCaptor<(AppCacheData) -> AppCacheData>() + verify(cacheStore, atLeastOnce()).update(updates.capture()) + return updates.allValues.fold(AppCacheData()) { data, update -> update(data) }.sparkExitNextFundingIndexes + } + + @Test + fun `a restored wallet with no kept funding index scans past the funding address its last exit used`() = test { + // Funding indexes 0 to 2 were used before the restore; index 2 still holds what a lost exit received. + val reads = mutableListOf() + val sut = scannedSut(scanChain(used = setOf(0, 1, 2), reads = reads)) + + sut.loadQuote().getOrThrow() + + assertEquals(3u, sut.state.value.pending?.fundingIndex) + assertEquals(scannedAddress(3), sut.state.value.fundingAddress) + assertTrue(2 in reads, "the funding at index 2 goes unseen") + assertEquals((0..2 + SparkExitMath.FUNDING_SCAN_GAP_LIMIT).toList(), reads) + assertEquals(listOf(3), keptFundingIndexes().values.toList(), "the next quote scans again") + } + + @Test + fun `a funding index restored from the backup is used without a scan`() = test { + val key = "${Env.network.name.lowercase()}/wallet0" + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(sparkExitNextFundingIndexes = mapOf(key to 3)))) + val reads = mutableListOf() + val sut = scannedSut(scanChain(used = setOf(0, 1, 2), reads = reads)) + + sut.loadQuote().getOrThrow() + + assertEquals(3u, sut.state.value.pending?.fundingIndex) + assertTrue(reads.isEmpty(), "a backed-up index needs no scan") + } + + @Test + fun `a funding scan the chain fails fails the quote and keeps no index`() = test { + val sut = scannedSut(scanChain(used = emptySet(), reads = mutableListOf(), isDown = true)) + + assertTrue(sut.loadQuote().isFailure, "an exit could fund from an address an earlier exit used") + + assertNull(sut.state.value.pending) + verify(cacheStore, never()).update(any()) + } + private suspend fun quotedSut(sdk: FakeSparkExitRecovering, http: HttpClient = fundingChain()): SparkExitRepo { whenever(sparkRepo.needsSettling()).thenReturn(false) whenever(sparkRepo.settleForExit()).thenReturn(Result.success(Unit)) From ac75f59afdc3a2f48e2c482f6d20b57e83bd3e77 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 23:16:48 +0100 Subject: [PATCH 147/154] fix: back up the earlier spark exit addresses The earlier exit addresses each wallet watches, kept change and cancelled exits' funding, lived only on the device. The metadata backup now carries them as sparkExitEarlierAddresses, keyed {network}/wallet{n}, with the kind written as keptChange or cancelledFunding like bitkit-ios. A restore lists them next to the device's own entries and skips a kind it does not know. --- .../java/to/bitkit/models/BackupPayloads.kt | 17 +++++ .../java/to/bitkit/repositories/BackupRepo.kt | 31 +++++++++ .../repositories/SparkExitEarlierAddress.kt | 24 ++++++- .../bitkit/repositories/SparkExitFunding.kt | 7 ++ .../to/bitkit/repositories/SparkExitRepo.kt | 2 +- .../to/bitkit/repositories/BackupRepoTest.kt | 64 +++++++++++++++++++ 6 files changed, 141 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/models/BackupPayloads.kt b/app/src/main/java/to/bitkit/models/BackupPayloads.kt index f3e05e639b..ef9d2d903c 100644 --- a/app/src/main/java/to/bitkit/models/BackupPayloads.kt +++ b/app/src/main/java/to/bitkit/models/BackupPayloads.kt @@ -39,6 +39,23 @@ data class MetadataBackupV1( val pubkyContactProfileOverrides: Map? = null, /** User-set hardware wallet names, keyed by wallet id. Null in envelopes written before this field. */ val hwWalletNames: Map? = null, + /** + * The earlier Spark exit addresses each wallet watches, keyed `{network}/wallet{n}` like the cache's + * `sparkExitNextFundingIndexes`. Null in envelopes written before this field. + */ + val sparkExitEarlierAddresses: Map>? = null, +) + +/** + * An earlier Spark exit address as both apps back it up. [kind] is `keptChange` or `cancelledFunding`; a reader skips + * one it does not know. What the address holds is read again from the chain. + */ +@Serializable +data class SparkExitEarlierAddressBackupV1( + val address: String, + val path: String, + val kind: String, + val atMillis: Long, ) @Serializable diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 0c343fe70c..b203bc33bf 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -75,6 +75,7 @@ import to.bitkit.models.PaykitAllowanceStateBackup import to.bitkit.models.PaykitPaymentStateBackup import to.bitkit.models.SettingsBackupV1 import to.bitkit.models.SparkExitBackupV1 +import to.bitkit.models.SparkExitEarlierAddressBackupV1 import to.bitkit.models.Toast import to.bitkit.models.WalletBackupV1 import to.bitkit.models.WalletScope @@ -90,6 +91,7 @@ import to.bitkit.utils.AppError import to.bitkit.utils.Logger import to.bitkit.utils.NetworkValidationHelper import to.bitkit.utils.jsonLogOf +import java.io.File import java.security.MessageDigest import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicLong @@ -479,6 +481,7 @@ class BackupRepo @Inject constructor( // Hardware tags are carried by the metadata backup. Observe the narrower tag signal so ordinary // payment and sync traffic does not re-upload the whole metadata envelope. dataListenerJobs.add(observeBackupChanges(activityRepo.activityTagsChanged, BackupCategory.METADATA)) + dataListenerJobs.add(observeBackupChanges(SparkExitEarlierAddressStore.writes, BackupCategory.METADATA)) // SPARK_EXIT - back up once per Spark connection when it is ready and synced, even if observing starts after // that, and again whenever Spark announces its unilateral exit data changed @@ -911,11 +914,37 @@ class BackupRepo @Inject constructor( pubkySession = pubkySession, pubkyContactProfileOverrides = pubkyContactProfileOverrides, hwWalletNames = hwWalletNames, + sparkExitEarlierAddresses = sparkExitEarlierAddressesBackup(), ) json.encodeToString(payload).toByteArray() } + /** + * The backed-up wallet's earlier Spark exit addresses, null with none. A list that can't be read is left out with a + * warning rather than block the rest of the metadata. + */ + private suspend fun sparkExitEarlierAddressesBackup(): Map>? { + val walletIndex = backupWalletIndex() + val entries = runCatching { + SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(walletIndex))).load() + } + .onFailure { Logger.warn("Failed to read the earlier Spark exit addresses to back up", it, context = TAG) } + .getOrNull() + ?.takeIf { it.isNotEmpty() } + ?: return null + return mapOf(SparkExitMath.walletKey(Env.network, walletIndex) to entries.map { it.toBackup() }) + } + + /** Lists each backed-up earlier Spark exit address of this network next to the device's own, which stay as is. */ + private fun restoreSparkExitEarlierAddresses(backedUp: Map>?) { + for ((key, entries) in backedUp.orEmpty()) { + val walletIndex = SparkExitMath.walletIndexOf(key, Env.network) ?: continue + val store = SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(walletIndex))) + entries.mapNotNull(SparkExitEarlierAddress::fromBackup).forEach { store.add(it) } + } + } + private suspend fun getWalletBackupDataBytes(): ByteArray { val sdkGeneration = paykitSdkService.runtimeGeneration var attemptsRemaining = WALLET_SNAPSHOT_ATTEMPTS @@ -1211,6 +1240,8 @@ class BackupRepo @Inject constructor( ), ) } + runCatching { restoreSparkExitEarlierAddresses(parsed.sparkExitEarlierAddresses) } + .onFailure { Logger.warn("Failed to restore the earlier Spark exit addresses", it, context = TAG) } Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.copy(cachedRates = emptyList()))}", TAG) onCacheRestored() val persisted = preActivityMetadataRepo.upsertPreActivityMetadata(parsed.tagMetadata) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt index 03a15cfe9c..4bd52675c2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt @@ -1,8 +1,11 @@ package to.bitkit.repositories +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.update import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import org.lightningdevkit.ldknode.Network +import to.bitkit.models.SparkExitEarlierAddressBackupV1 import to.bitkit.models.safe import java.io.File import java.nio.file.Files @@ -22,14 +25,17 @@ data class SparkExitEarlierAddress( val sats: ULong? = null, val atMillis: Long, ) { - enum class Kind { + /** [backupName] is how both apps' metadata backups name the kind. */ + enum class Kind(val backupName: String) { /** Fee funding left at the funding address for good: change too small to send, or a refused sweep's. */ - KEPT_CHANGE, + KEPT_CHANGE("keptChange"), /** The funding address of a cancelled exit that was forgotten: a late payment can still land there. */ - CANCELLED_FUNDING, + CANCELLED_FUNDING("cancelledFunding"), } + fun toBackup() = SparkExitEarlierAddressBackupV1(address, path, kind.backupName, atMillis) + /** * Read in the foreground for what it holds: kept change always, so change spent by hand shows as spent, and a * cancelled exit's address for about four weeks, for a late payment. @@ -40,6 +46,12 @@ data class SparkExitEarlierAddress( companion object { val WATCH_PERIOD = 28.days + /** The backed-up entry, with what it holds read again later; null for a kind this app does not know. */ + fun fromBackup(backup: SparkExitEarlierAddressBackupV1): SparkExitEarlierAddress? { + val kind = Kind.entries.firstOrNull { it.backupName == backup.kind } ?: return null + return SparkExitEarlierAddress(backup.address, backup.path, kind, atMillis = backup.atMillis) + } + /** The leftover an ended exit kept at its funding address, or null when it kept none. */ fun keptChange(record: SparkExitRecord, network: Network, atMillis: Long): SparkExitEarlierAddress? { if (!record.isLeftoverKept) return null @@ -68,6 +80,11 @@ data class SparkExitEarlierAddress( /** The earlier exits' addresses, in their own file next to the exit record. A wipe deletes it. */ class SparkExitEarlierAddressStore(private val file: File) { + companion object { + /** Counts the writes of every wallet's list, so the metadata backup that carries them runs again. */ + val writes = MutableStateFlow(0L) + } + private val json = Json { ignoreUnknownKeys = true } fun load(): List { @@ -120,5 +137,6 @@ class SparkExitEarlierAddressStore(private val file: File) { val temp = File(file.parentFile, "${file.name}.tmp") writeDurably(temp, json.encodeToString(entries)) Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + writes.update { it + 1 } } } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index b6682799fe..53c4101c6d 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -530,6 +530,13 @@ object SparkExitMath { return next } + /** How the cache and the metadata backup key a wallet's exit state: `{network}/wallet{n}`. */ + fun walletKey(network: Network, walletIndex: Int) = "${network.name.lowercase()}/wallet$walletIndex" + + /** The wallet index [key] names on [network], null for another network's. */ + fun walletIndexOf(key: String, network: Network): Int? = + key.takeIf { it.startsWith("${network.name.lowercase()}/wallet") }?.substringAfterLast("/wallet")?.toIntOrNull() + /** Each wallet's higher next funding index of [local] and [restored]. */ fun mergeFundingIndexes(local: Map, restored: Map): Map = (local.keys + restored.keys).associateWith { maxOf(local[it] ?: 0, restored[it] ?: 0) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index f44ed55ac3..c6265355ac 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -1111,7 +1111,7 @@ class SparkExitRepo @Inject constructor( // region keys - private val fundingIndexKey get() = "${Env.network.name.lowercase()}/wallet$walletIndex" + private val fundingIndexKey get() = SparkExitMath.walletKey(Env.network, walletIndex) /** A payment landing late at a forgotten exit's funding address is seen by the next exit, which uses it. */ private suspend fun giveFundingIndexBack(index: UInt) = cacheStore.update { diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 35df40bf01..c929225137 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -29,7 +29,9 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import org.junit.Before +import org.junit.Rule import org.junit.Test +import org.junit.rules.TemporaryFolder import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argThat @@ -71,6 +73,7 @@ import to.bitkit.data.entities.TransferEntity import to.bitkit.data.keychain.Keychain import to.bitkit.data.withPublicSharingDisabledForRestore import to.bitkit.di.json +import to.bitkit.env.Env import to.bitkit.models.ActivityBackupV1 import to.bitkit.models.BackupCategory import to.bitkit.models.BackupItemStatus @@ -83,6 +86,7 @@ import to.bitkit.models.PubkySessionBackupKind import to.bitkit.models.PubkySessionBackupV1 import to.bitkit.models.SettingsBackupV1 import to.bitkit.models.SparkExitBackupV1 +import to.bitkit.models.SparkExitEarlierAddressBackupV1 import to.bitkit.models.TransportType import to.bitkit.models.WalletBackupV1 import to.bitkit.models.WalletScope @@ -95,6 +99,7 @@ import to.bitkit.services.PaykitSdkService import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture import to.bitkit.utils.AppError +import java.io.File import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.TimeUnit @@ -115,6 +120,9 @@ import kotlin.time.Instant @OptIn(ExperimentalCoroutinesApi::class, ExperimentalTime::class) class BackupRepoTest : BaseUnitTest() { + @get:Rule + val tempFolder = TemporaryFolder() + private val context = mock() private val cacheStore = mock() private val vssBackupClient = mock() @@ -1874,6 +1882,62 @@ class BackupRepoTest : BaseUnitTest() { assertTrue(cacheData.value.sparkExitNextFundingIndexes.isEmpty(), "an exit then scans for the index") } + private fun earlierAddressStore(): SparkExitEarlierAddressStore { + Env.initAppStoragePath(tempFolder.root.absolutePath) + return SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(0))) + } + + private val sparkWalletKey get() = "${Env.network.name.lowercase()}/wallet0" + + @Test + fun `a metadata backup carries the wallet's earlier spark exit addresses`() = test { + val store = earlierAddressStore() + val kept = SparkExitEarlierAddress.Kind.KEPT_CHANGE + val cancelled = SparkExitEarlierAddress.Kind.CANCELLED_FUNDING + store.add(SparkExitEarlierAddress("bcrt1qkept", "m/84'/1'/7797'/0/2", kept, sats = 600uL, atMillis = 1L)) + store.add(SparkExitEarlierAddress("bcrt1qcancelled", "m/84'/1'/7797'/0/0", cancelled, atMillis = 2L)) + stubMetadataBackupReads() + val dataCaptor = argumentCaptor() + + sut.triggerBackup(BackupCategory.METADATA) + + verifyBlocking(vssBackupClient) { putObject(eq(BackupCategory.METADATA.name), dataCaptor.capture()) } + val payload = json.decodeFromString(dataCaptor.firstValue.decodeToString()) + val expected = listOf( + SparkExitEarlierAddressBackupV1("bcrt1qkept", "m/84'/1'/7797'/0/2", "keptChange", 1L), + SparkExitEarlierAddressBackupV1("bcrt1qcancelled", "m/84'/1'/7797'/0/0", "cancelledFunding", 2L), + ) + assertEquals(mapOf(sparkWalletKey to expected), payload.sparkExitEarlierAddresses) + } + + @Test + fun `a restore lists the backed-up earlier spark exit addresses and keeps the device's`() = test { + val store = earlierAddressStore() + val kept = SparkExitEarlierAddress.Kind.KEPT_CHANGE + val onDevice = SparkExitEarlierAddress("bcrt1qdevice", "m/84'/1'/7797'/0/1", kept, sats = 600uL, atMillis = 5L) + store.add(onDevice) + val backedUp = listOf( + SparkExitEarlierAddressBackupV1("bcrt1qdevice", "m/84'/1'/7797'/0/1", "cancelledFunding", 1L), + SparkExitEarlierAddressBackupV1("bcrt1qrestored", "m/84'/1'/7797'/0/2", "keptChange", 2L), + SparkExitEarlierAddressBackupV1("bcrt1qfuture", "m/84'/1'/7797'/0/3", "someLaterKind", 3L), + ) + val envelope = json.encodeToString( + MetadataBackupV1( + createdAt = 123, + tagMetadata = emptyList(), + cache = AppCacheData(), + sparkExitEarlierAddresses = mapOf(sparkWalletKey to backedUp), + ) + ) + stubMetadataRestore(envelope = envelope) + + val failed = sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertFalse(BackupCategory.METADATA in failed, "a kind this app does not know fails the whole metadata") + val restored = SparkExitEarlierAddress("bcrt1qrestored", "m/84'/1'/7797'/0/2", kept, atMillis = 2L) + assertEquals(listOf(onDevice, restored), store.load()) + } + @Test fun `metadata cache failure remains optional after public address quarantine succeeds`() = test { val publicAddress = "bcrt1qpublic" From 46e4fb2001ef84e925f57efbf0755846199b19a7 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Wed, 11 Nov 2026 23:16:58 +0100 Subject: [PATCH 148/154] fix: watch earlier exits' funding that still holds coins after a restore Funding an exit received at an address above index 0 went unwatched once the wallet was restored, as its record is not backed up. On each foreground start after a restore (with no funding index kept, or once after a restore brought one back), the exit reads its funding addresses, and lists each one that still holds coins and nothing watches as kept change, so it is watched for good and shown with what it holds. A read that fails keeps the restore pending, so the next start reads again. --- .../main/java/to/bitkit/data/CacheStore.kt | 5 ++ .../java/to/bitkit/repositories/BackupRepo.kt | 3 + .../to/bitkit/repositories/SparkExitRepo.kt | 52 +++++++++-- .../to/bitkit/repositories/BackupRepoTest.kt | 11 +++ .../bitkit/repositories/SparkExitRepoTest.kt | 88 ++++++++++++++++++- 5 files changed, 153 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index acce19ac50..2f01199fd0 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -316,6 +316,11 @@ data class AppCacheData( * from an address of its own. */ val sparkExitNextFundingIndexes: Map = mapOf(), + /** + * The `{network}/wallet{n}` keys whose funding index a restore brought back, so the exit looks once for funding + * addresses that still hold coins and nothing watches. + */ + val sparkExitFundingRecoveryPending: Set = emptySet(), /** Hashes of the latest Lightning sends Spark started, so the node holds off while Spark can't list them. */ val sparkSendHashes: List = listOf(), /** Invoice expiry in epoch seconds of the [sparkSendHashes] that know it. */ diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index b203bc33bf..fa3df5d07f 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1230,6 +1230,7 @@ class BackupRepo @Inject constructor( ) val parsed = decodeBackup(migration.json) val cleanCache = parsed.cache.resetBip21() // Force address rotation + val restoredIndexKeys = cleanCache.sparkExitNextFundingIndexes.keys cacheStore.update { cleanCache.copy( backupStatuses = it.backupStatuses, @@ -1238,6 +1239,8 @@ class BackupRepo @Inject constructor( it.sparkExitNextFundingIndexes, cleanCache.sparkExitNextFundingIndexes, ), + // The exit then looks once for funding addresses that still hold coins and nothing watches. + sparkExitFundingRecoveryPending = it.sparkExitFundingRecoveryPending + restoredIndexKeys, ) } runCatching { restoreSparkExitEarlierAddresses(parsed.sparkExitEarlierAddresses) } diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index c6265355ac..0f6705c4ca 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -226,6 +226,8 @@ class SparkExitRepo @Inject constructor( */ suspend fun refreshEarlierAddresses() = withContext(bgDispatcher) { val chain = chain ?: return@withContext + runSuspendCatching { recoverFunding(chain) } + .onFailure { Logger.warn("Failed to look for earlier exits' funding after a restore", it, context = TAG) } val now = clock.nowMs() val watched = runCatching { earlierAddressStore.load() }.getOrDefault(emptyList()).filter { it.isWatched(now) } for (entry in watched) { @@ -1122,18 +1124,58 @@ class SparkExitRepo @Inject constructor( /** * With no index kept and no record, as after a restore from the phrase or from a backup older than the index, the - * funding addresses are scanned once and the result kept. A scan the chain fails keeps nothing. + * funding addresses are scanned first. A scan the chain fails keeps nothing. */ private suspend fun nextFundingIndex(): UInt { val kept = cacheStore.data.first().sparkExitNextFundingIndexes[fundingIndexKey] val stored = runSuspendCatching { store.load() }.getOrNull() if (kept != null || stored != null) return SparkExitMath.nextFundingIndex(kept, stored) - val chain = chain ?: return 0u - val scanned = SparkExitMath.scanNextFundingIndex { chain.isAddressUsed(fundingAddress(it).address) } + return chain?.let { recoverFunding(it) } ?: 0u + } + + /** + * Finds earlier exits' funding after a restore. With no index kept and no record, scans for the next index and + * keeps it; with an index a restore brought back, reads each funding address below it, once. Each funding address + * that still holds coins and nothing watches is listed as kept change, so it is watched for good. Throws when a + * read fails, keeping no index and the restore pending, so it runs again on the next start. + * + * @return the index a scan found, or null when there was nothing to scan. + */ + private suspend fun recoverFunding(chain: SparkExitChain): UInt? { + val cache = cacheStore.data.first() + val kept = cache.sparkExitNextFundingIndexes[fundingIndexKey] + val stored = runSuspendCatching { store.load() }.getOrNull() + val isPending = if (kept == null) stored == null else fundingIndexKey in cache.sparkExitFundingRecoveryPending + if (!isPending) return null + val addresses = mutableMapOf() + suspend fun address(index: UInt) = addresses.getOrPut(index) { fundingAddress(index).address } + val used = mutableListOf() + val scanned = if (kept != null) { + null + } else { + SparkExitMath.scanNextFundingIndex { index -> + chain.isAddressUsed(address(index)).also { if (it) used += index } + } + } + val candidates = if (kept == null) used else (0u until kept.toUInt()).toList() + val listed = runCatching { earlierAddressStore.load() }.getOrDefault(emptyList()).map { it.address } + val watched = listed + stored?.funding?.map { it.address }.orEmpty() + for (index in candidates.filter { address(it) !in watched }) { + val address = address(index) + val sats = chain.utxos(address).fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } + if (sats == 0uL) continue + val path = SparkExitFundingKey.path(index.toInt(), Env.network) + keepEarlierAddress( + SparkExitEarlierAddress(address, path, SparkExitEarlierAddress.Kind.KEPT_CHANGE, sats, clock.nowMs()) + ) + } cacheStore.update { val indexes = it.sparkExitNextFundingIndexes - val next = maxOf(indexes[fundingIndexKey] ?: 0, scanned.toInt()) - it.copy(sparkExitNextFundingIndexes = indexes + (fundingIndexKey to next)) + val next = scanned?.let { found -> maxOf(indexes[fundingIndexKey] ?: 0, found.toInt()) } + it.copy( + sparkExitNextFundingIndexes = next?.let { found -> indexes + (fundingIndexKey to found) } ?: indexes, + sparkExitFundingRecoveryPending = it.sparkExitFundingRecoveryPending - fundingIndexKey, + ) } return scanned } diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index c929225137..771a59a938 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -1869,6 +1869,17 @@ class BackupRepoTest : BaseUnitTest() { assertEquals(backedUp, cacheData.value.sparkExitNextFundingIndexes) } + @Test + fun `a restore marks each restored spark exit funding index for a look at its funding addresses`() = test { + applyCacheUpdates() + val backedUp = mapOf("regtest/wallet0" to 3) + stubMetadataRestore(envelope = metadataEnvelope(cache = AppCacheData(sparkExitNextFundingIndexes = backedUp))) + + sut.performFullRestoreFromLatestBackup().getOrThrow() + + assertEquals(setOf("regtest/wallet0"), cacheData.value.sparkExitFundingRecoveryPending) + } + @Test fun `a metadata backup written before the spark exit funding index restores with none kept`() = test { applyCacheUpdates() diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 8c365d8f27..7bd1f932d2 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -732,18 +732,29 @@ class SparkExitRepoTest : BaseUnitTest() { * A chain where the funding addresses at [used] have a transaction, each index its own address, and the address * reads [reads] lists; [isDown] answers every address read with a server error. */ - private fun scanChain(used: Set, reads: MutableList, isDown: Boolean = false) = HttpClient( + private fun scanChain( + used: Set, + reads: MutableList, + isDown: Boolean = false, + coins: Map = emptyMap(), + ) = HttpClient( MockEngine.create { dispatcher = testDispatcher addHandler { request -> val url = request.url.toString() val index = url.substringAfter("/address/bcrt1qfunding", "").toIntOrNull() + val coinIndex = url.substringAfter("/address/bcrt1qfunding", "").removeSuffix("/utxo").toIntOrNull() when { index != null && isDown -> respond("", HttpStatusCode.InternalServerError) index != null -> { reads += index respond(addressStats(txCount = if (index in used) 1 else 0)) } + url.endsWith("/utxo") && coinIndex != null -> respond( + coins[coinIndex]?.let { + """[{"txid":"${"ab".repeat(32)}","vout":0,"value":$it,"status":{"confirmed":true}}]""" + } ?: "[]" + ) url.endsWith("/utxo") -> respond("[]") url.endsWith("/blocks/tip/height") -> respond("1000") url.endsWith("/fee-estimates") -> respond("""{"1":9,"3":6,"144":1}""") @@ -785,6 +796,81 @@ class SparkExitRepoTest : BaseUnitTest() { assertEquals(listOf(3), keptFundingIndexes().values.toList(), "the next quote scans again") } + private val now = 1_800_000_000_000L + + private fun keptCoins(index: Int, sats: ULong) = SparkExitEarlierAddress( + scannedAddress(index), + SparkExitFundingKey.path(index, Env.network), + SparkExitEarlierAddress.Kind.KEPT_CHANGE, + sats, + now, + ) + + private suspend fun keptCache(initial: AppCacheData): AppCacheData { + val updates = argumentCaptor<(AppCacheData) -> AppCacheData>() + verify(cacheStore, atLeastOnce()).update(updates.capture()) + return updates.allValues.fold(initial) { data, update -> update(data) } + } + + @Test + fun `a restored wallet with no kept funding index watches the funding addresses that still hold coins`() = test { + // Index 2 still holds what a lost exit received; 0 and 1 were spent by earlier exits. + val sut = scannedSut(scanChain(used = setOf(0, 1, 2), reads = mutableListOf(), coins = mapOf(2 to 5_000))) + sut.load(0).getOrThrow() + + sut.refreshEarlierAddresses() + + assertEquals(listOf(keptCoins(2, 5_000uL)), sut.state.value.earlierAddresses, "the lost funding goes unwatched") + val stored = SparkExitEarlierAddressStore(File(Env.sparkExitEarlierAddressesPath(0))).load() + assertEquals(listOf(keptCoins(2, 5_000uL)), stored) + assertEquals(listOf(3), keptCache(AppCacheData()).sparkExitNextFundingIndexes.values.toList()) + } + + @Test + fun `a funding address with history but no coins is not watched`() = test { + val sut = scannedSut(scanChain(used = setOf(0, 1), reads = mutableListOf(), coins = mapOf(1 to 700))) + sut.load(0).getOrThrow() + + sut.refreshEarlierAddresses() + + assertEquals(listOf(keptCoins(1, 700uL)), sut.state.value.earlierAddresses) + } + + @Test + fun `a restored funding index brings back the funding addresses that still hold coins`() = test { + val key = "${Env.network.name.lowercase()}/wallet0" + val restored = AppCacheData( + sparkExitNextFundingIndexes = mapOf(key to 3), + sparkExitFundingRecoveryPending = setOf(key), + ) + whenever(cacheStore.data).thenReturn(flowOf(restored)) + val reads = mutableListOf() + val sut = scannedSut(scanChain(used = setOf(0, 1, 2), reads = reads, coins = mapOf(2 to 5_000))) + sut.load(0).getOrThrow() + + sut.refreshEarlierAddresses() + + assertEquals(listOf(keptCoins(2, 5_000uL)), sut.state.value.earlierAddresses, "the lost funding goes unwatched") + assertTrue(reads.isEmpty(), "a restored index needs no scan for the next one") + val cache = keptCache(restored) + assertTrue(cache.sparkExitFundingRecoveryPending.isEmpty(), "every start reads the funding addresses again") + assertEquals(mapOf(key to 3), cache.sparkExitNextFundingIndexes) + } + + @Test + fun `a kept funding index with no restore pending reads no funding address`() = test { + val key = "${Env.network.name.lowercase()}/wallet0" + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(sparkExitNextFundingIndexes = mapOf(key to 3)))) + val reads = mutableListOf() + val sut = scannedSut(scanChain(used = setOf(0, 1, 2), reads = reads, coins = mapOf(2 to 5_000))) + sut.load(0).getOrThrow() + + sut.refreshEarlierAddresses() + + assertTrue(reads.isEmpty()) + assertTrue(sut.state.value.earlierAddresses.isEmpty()) + } + @Test fun `a funding index restored from the backup is used without a scan`() = test { val key = "${Env.network.name.lowercase()}/wallet0" From 79752a83197b4e58e0f269c122f6cffd29dddda2 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 00:47:22 +0100 Subject: [PATCH 149/154] fix: build a kept fee bump at its rate A fee bump whose build would leave a leaf waiting kept the valid generation with the bumped rate on the record but the old rate in its signed steps, and nothing built at the new rate afterwards. The bump now stays pending until a build at its rate is adopted: the check builds at that rate again once a block, whatever the leaf waits for, and the kept generation is still sent meanwhile, also while that build asks for more fee funding. A dead fee chain beside a waiting leaf keeps the valid generation too, so the leaf's signed steps stay; its rebuilds stop once stalled and it rebuilds once the leaf's step confirms. A test pins that. --- .../to/bitkit/repositories/SparkExitDriver.kt | 33 +++++++ .../to/bitkit/repositories/SparkExitRecord.kt | 28 +++++- .../repositories/SparkExitDriverTest.kt | 96 ++++++++++++++++++- .../repositories/SparkExitRecordTest.kt | 4 + 4 files changed, 158 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt index f1a3b24eb0..9d360ae8e3 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -235,6 +235,10 @@ class SparkExitDriver( sdk: SparkExitRecovering, isUnverifiedRebuild: Boolean = false, ): SparkExitRecord { + // A pending fee bump builds at its rate at most once a block, however the build was reached. + if (start.isFeeBumpPending && start.feeBumpBuiltAtHeight != tip) { + return build(start.copy(feeBumpBuiltAtHeight = tip), sdk, isUnverifiedRebuild) + } // A build waiting for a leaf that may still move tries again only at its paced heights, or once its wait ends. val since = start.retrySince if (since != null && tip != null && !SparkExitMath.isRetryDue(since, start.retriedAt, tip) && @@ -525,6 +529,9 @@ class SparkExitDriver( Logger.warn("Rebuilding Spark exit over step '${stuck.txid}' that keeps failing", context = TAG) return stallRebuild(sent, sdk) } + if (sent.isFeeBumpPending && tip != null && sent.feeBumpBuiltAtHeight != tip) { + return buildFeeBump(sent, sdk) + } if (!needsUnverifiedRebuild(sent)) return sent // A check cannot settle a step the SDK could not read; a fresh build reads the chain again. Logger.info("Rebuilding Spark exit over steps the SDK could not read", context = TAG) @@ -556,6 +563,32 @@ class SparkExitDriver( } } + /** + * A fee bump whose build kept [sent], the valid generation, over a waiting leaf is built at its rate again once a + * block, whatever the leaf waits for, until a build at it is adopted; that build also settles any unread step. A + * build it does not adopt leaves [sent] going, checked and sent every tick, and one that asks for more fee funding + * keeps sending it while the top-up waits. + */ + private suspend fun buildFeeBump(sent: SparkExitRecord, sdk: SparkExitRecovering): SparkExitRecord { + Logger.info("Rebuilding Spark exit at its higher fee rate '${sent.feeRateSatPerVbyte}' sat/vB", context = TAG) + val rebuilding = sent.copy( + isRebuilding = true, + feeBumpBuiltAtHeight = tip, + unverifiedRebuiltAtHeight = tip, + isRedoRebuild = false, + ) + // Saved as the valid generation: a run killed during the rebuild goes on sending it. + save(rebuilding.copy(isRebuilding = false)) + val rebuilt = build(rebuilding, sdk) + return when { + rebuilt.isAdoptionPending(sent) -> + rebuilt.copy(isRebuilding = false, retrySince = sent.retrySince, retriedAt = sent.retriedAt) + rebuilt.generation == sent.generation && rebuilt.phase is SparkExitRecord.Phase.NeedsFunding -> + rebuilt.copy(isRebuilding = false) + else -> rebuilt + } + } + /** * What the exit's funding address must still receive to rebuild at [rate]: a build of the exit's leaves with the * funding it holds, nothing broadcast, on a copy with the rebuild's drop-and-retry. A leaf the prepare or the build diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt index b38e73f0b5..01cbe6e701 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -118,6 +118,13 @@ data class SparkExitRecord( val isRedoRebuild: Boolean = false, /** The fee funding asked for came from a rebuild over unverified steps, while the generation out there is valid. */ val isUnverifiedAsk: Boolean = false, + /** + * A higher fee rate the steps out there are not built at yet: a fee bump whose build kept the valid generation over + * a leaf it would leave waiting. Built at that rate again until a build at it is adopted. + */ + val isFeeBumpPending: Boolean = false, + /** The tip of the last build at a pending fee bump's rate, so it builds at most once a block. */ + val feeBumpBuiltAtHeight: UInt? = null, /** What confirmed SWEEP and COOPERATIVE steps of replaced generations paid to [destination], by txid. */ val earlierReceivedSats: Map = emptyMap(), /** Each quoted leaf's value, so a leaf the first build leaves behind before any recovery lists it keeps it. */ @@ -421,6 +428,8 @@ data class SparkExitRecord( spentStepStrikes = if (isRedoRebuild) spentStepStrikes(built) else spentStepStrikes, isRedoRebuild = false, isUnverifiedAsk = false, + isFeeBumpPending = false, + feeBumpBuiltAtHeight = null, earlierReceivedSats = earlierReceivedSats + recovery?.let { SparkExitMath.confirmedReceived(it, destination) } .orEmpty(), earlierCpfpTxids = (earlierCpfpTxids + recovery?.let(SparkExitTxids::fundingTxids).orEmpty()).distinct(), @@ -466,14 +475,20 @@ data class SparkExitRecord( /** * The exit at [rate]: with [extraSats] of funding paid in [paymentTxid], it waits for that payment as a top-up * and then rebuilds; with nothing to pay, it rebuilds on the next tick. Either way what has not confirmed goes - * out again at the new rate and replaces what is in the mempool. Not a Redo, so it strikes nothing. + * out again at the new rate and replaces what is in the mempool. Not a Redo, so it strikes nothing. The bump stays + * pending until a build at the new rate is adopted. */ fun applyFeeBump( rate: ULong, extraSats: ULong, paymentTxid: String?, ): SparkExitRecord { - val bumped = copy(feeRateSatPerVbyte = rate, isRedoRebuild = false) + val bumped = copy( + feeRateSatPerVbyte = rate, + isRedoRebuild = false, + isFeeBumpPending = true, + feeBumpBuiltAtHeight = null, + ) if (extraSats == 0uL) return bumped.copy(isRebuilding = true, lastBuildAt = null) return bumped.copy( phase = Phase.NeedsFunding(fundedSats.safe() + extraSats.safe()), @@ -927,6 +942,12 @@ object SparkExitJson { sweep.builtAtHeight?.let { put("builtAtHeight", it.toLong()) } } + /** A fee bump still to be built at its rate, left out once none is pending. */ + private fun JsonObjectBuilder.putFeeBumpState(r: SparkExitRecord) { + if (r.isFeeBumpPending) put("isFeeBumpPending", true) + r.feeBumpBuiltAtHeight?.let { put("feeBumpBuiltAtHeight", it.toLong()) } + } + /** What the exit keeps to pace and bound its rebuilds and waits, each left out at its default. */ private fun JsonObjectBuilder.putRebuildState(r: SparkExitRecord) { if (r.stallRebuilds > 0) put("stallRebuilds", r.stallRebuilds) @@ -947,6 +968,7 @@ object SparkExitJson { if (r.isRebuiltFromChain) put("isRebuiltFromChain", true) if (r.isRedoRebuild) put("isRedoRebuild", true) if (r.isUnverifiedAsk) put("isUnverifiedAsk", true) + putFeeBumpState(r) r.fundingStrategy?.let { put("fundingStrategy", it) } if (r.failedLeaves.isNotEmpty()) { put( @@ -1087,6 +1109,8 @@ object SparkExitJson { isRebuiltFromChain = o.booleanOrNull("isRebuiltFromChain") ?: false, isRedoRebuild = o.booleanOrNull("isRedoRebuild") ?: false, isUnverifiedAsk = o.booleanOrNull("isUnverifiedAsk") ?: false, + isFeeBumpPending = o.booleanOrNull("isFeeBumpPending") ?: false, + feeBumpBuiltAtHeight = o.ulongOrNull("feeBumpBuiltAtHeight")?.toUInt(), fundingStrategy = o.stringOrNull("fundingStrategy"), failedLeaves = o.arrayOrEmpty("failedLeaves").map { val l = it.jsonObject diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt index 52d11d8920..2a87c1c1b4 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -1492,7 +1492,8 @@ class SparkExitDriverTest : BaseUnitTest() { sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-2")).copy( skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), ) - sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("m1"))) + // The second build is the bump's again, at the next block. + repeat(2) { sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("m1"))) } record = driver(tip = 1_000u).tick(record) @@ -1512,6 +1513,99 @@ class SparkExitDriverTest : BaseUnitTest() { assertEquals(listOf("n2"), chain.broadcasts.map { it.txid }, "leaf-1's refund n2 was not sent") } + @Test + fun `a higher fee kept over a waiting leaf builds at the bumped rate once the leaf reads`() = test { + val unread = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1"), status = ExitTransactionStatus.Unverified), + ), + ) + var record = funded(running(unread).copy(leafIds = listOf("leaf-1", "leaf-2"))) + .applyFeeBump(rate = 9uL, extraSats = 0uL, paymentTxid = null) + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-2")).copy( + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + repeat(2) { sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("m1"))) } + record = driver(tip = 1_000u).tick(record) + assertEquals(1, record.generation) + + val reread = SparkExitFixtures.recovery( + listOf( + SparkExitFixtures.tx("n1", status = ExitTransactionStatus.Confirmed(900u)), + SparkExitFixtures.tx("n2", dependsOn = listOf("n1")), + ), + ) + sdk.checks += check(reread, RecoveryVerdict.Valid) + record = driver(tip = 1_001u).tick(record) + assertEquals(1, record.generation, "the rebuild that drops leaf-1's refund n2 was adopted") + assertFalse(record.isRebuilding, "the valid generation is no longer checked or sent") + assertEquals( + listOf("n2"), + chain.broadcasts.map { it.txid }, + "leaf-1's refund n2 was not sent while the bump waits", + ) + + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-1", "leaf-2")) + sdk.builds.clear() + sdk.builds += SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("b1"), SparkExitFixtures.tx("b2"))) + sdk.checks += check(reread, RecoveryVerdict.Valid) + val preparesBefore = sdk.prepareRequests.size + record = driver(tip = 1_002u).tick(record) + + assertEquals(2, record.generation, "the bump was never built at its rate") + assertEquals(listOf(9uL), sdk.prepareRequests.drop(preparesBefore).map { it.feeRateSatPerVbyte }) + assertEquals(listOf("b1", "b2"), record.recovery?.transactions?.map { it.txid }) + } + + @Test + fun `a dead fee chain beside a waiting leaf rebuilds once the leaf's step confirms`() = test { + val bothLeaves = listOf( + RecoverFundsLeaf("leaf-1", 100_000uL, RecoveryMethod.UNILATERAL), + RecoverFundsLeaf("leaf-2", 100_000uL, RecoveryMethod.UNILATERAL), + ) + fun steps(l1: ExitTransactionStatus, node1: ExitTransactionStatus = ExitTransactionStatus.Confirmed(11_600u)) = + Race.recovery(node1).let { + it.copy(leaves = bothLeaves, transactions = it.transactions + SparkExitFixtures.tx("l1", status = l1)) + } + var record = running(steps(ExitTransactionStatus.Unverified, node1 = ExitTransactionStatus.Ready)).copy( + leafIds = listOf("leaf-1", "leaf-2"), + funding = listOf( + SparkExitRecord.Funding(0u, SparkExitFixtures.FUNDING_ADDRESS, "02ab", Race.FUNDING_TXID, 0u, 20_000uL) + ), + ) + chain.confirmedTxids = setOf(Race.NODE_1) + chain.unknownTxids = setOf(Race.firstTxid) + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-2")).copy( + skipped = listOf(SkippedLeaf("leaf-1", 100_000uL, SkippedLeafReason.Unverified)), + ) + repeat(SparkExitDriver.STALL_REBUILDS_TO_SURFACE + 1) { + sdk.builds += Race.rebuilt.copy(leaves = listOf(bothLeaves[1])) + } + + repeat(SparkExitDriver.STALL_REBUILDS_TO_SURFACE + 1) { i -> + sdk.checks += check(steps(ExitTransactionStatus.Unverified), RecoveryVerdict.Valid) + now += interval + record = driver(tip = 1_000u + i.toUInt()).tick(record) + if (record.isRebuilding) record = driver(tip = 1_000u + i.toUInt()).tick(record) + assertEquals(1, record.generation, "a rebuild dropped leaf-1's signed step l1") + } + assertTrue(record.isStalled) + val rebuildsWhileStalled = sdk.recoverRequests.size + + // leaf-1 reads again and its step confirms: the exit moves, so the dead chain is rebuilt over. + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null, leaves = listOf("leaf-2")) + chain.confirmedTxids = setOf(Race.NODE_1, "l1") + sdk.checks += check(steps(ExitTransactionStatus.Confirmed(1_004u)), RecoveryVerdict.Valid) + now += interval + record = driver(tip = 1_005u).tick(record) + if (record.isRebuilding) record = driver(tip = 1_005u).tick(record) + + assertEquals(rebuildsWhileStalled + 1, sdk.recoverRequests.size) + assertEquals(2, record.generation, "the dead fee chain was never rebuilt over") + assertEquals(Race.rebuiltSecond, chain.broadcasts.last().cpfpTxHex) + } + @Test fun `a rebuild from the chain keeps its note until one of its steps confirms`() = test { val built = SparkExitFixtures.recovery(listOf(SparkExitFixtures.tx("n1"))) diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt index 11d7a2d0d6..efa5b2c6ae 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -122,6 +122,8 @@ class SparkExitRecordTest { exitStateSnapshot = "exit-state", isRebuiltFromChain = true, isRedoRebuild = true, + isFeeBumpPending = true, + feeBumpBuiltAtHeight = 1_004u, earlierReceivedSats = mapOf("sweep-0" to 90_000uL), ) @@ -227,6 +229,8 @@ class SparkExitRecordTest { "exitStateSnapshot", "isRebuiltFromChain", "isRedoRebuild", + "isFeeBumpPending", + "feeBumpBuiltAtHeight", "earlierReceivedSats", ).forEach { assertFalse(it in json, it) } assertEquals( From 24c5fedda004cef0ee2363202ab8311b9f5040cd Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 00:47:22 +0100 Subject: [PATCH 150/154] fix: pay a higher fee from savings only on spark's chain The Pay a higher fee screen and its payment checked only the spendable balance. On a chain Spark does not read, such as its hosted regtest, the extra funding went out on the node's chain and the exit never saw it. Both now check that Spark shares the node's chain, as the start's funding does; a rate with nothing to pay is still offered. --- .../to/bitkit/repositories/SparkExitRepo.kt | 5 +++++ .../settings/lightning/SparkExitViewModel.kt | 15 ++++++++++--- .../bitkit/repositories/SparkExitRepoTest.kt | 22 ++++++++++++++++++- .../lightning/SparkExitViewModelTest.kt | 19 ++++++++++------ 4 files changed, 50 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 0f6705c4ca..09ca7ef372 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -72,6 +72,9 @@ class SparkExitRepo @Inject constructor( private val sparkExitTip: SparkExitTip, private val cacheStore: CacheStore, ) { + /** Spark reads the node's chain, so a savings payment, which goes out on it, reaches the exit. */ + internal var sharesNodeChain: () -> Boolean = { Env.sparkSharesNodeChain } + companion object { private const val TAG = "SparkExitRepo" @@ -634,6 +637,8 @@ class SparkExitRepo @Inject constructor( private suspend fun payHigherFeeLocked(option: SparkExitFeeBumpOption) { val record = requireNotNull(_state.value.record?.takeIf { it.isActive }) { "No running Spark exit" } val address = requireNotNull(record.funding.firstOrNull()?.address) { "No Spark exit funding address" } + // On a chain Spark does not read, the exit would never see the payment. + require(option.extraSats == 0uL || sharesNodeChain()) { "Spark does not read the node's chain" } val txid = if (option.extraSats > 0uL) { sendFunding(address, option.extraSats, option.feeRates, option.totalSats.safe() - option.extraSats.safe()) } else { diff --git a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt index c3bf9c22bf..e4468cdd03 100644 --- a/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -59,6 +59,9 @@ class SparkExitViewModel @Inject constructor( private val FUNDING_POLL_INTERVAL = 15.seconds } + /** Spark reads the node's chain, so savings can pay a higher fee's extra funding. */ + internal var sharesNodeChain: () -> Boolean = { Env.sparkSharesNodeChain } + private val _uiState = MutableStateFlow(SparkExitUiState()) val uiState = _uiState.asStateFlow() @@ -215,7 +218,11 @@ class SparkExitViewModel @Inject constructor( sparkExitRepo.feeBumpOptions() .onSuccess { priced -> val options = priced.map { it.withFeeFloor(feeBumpFeeFloors[it.rateSatPerVbyte]) } - val bump = SparkExitFeeBumpUiState(options = options.toImmutableList(), spendableSats = spendable) + val bump = SparkExitFeeBumpUiState( + options = options.toImmutableList(), + spendableSats = spendable, + sharesNodeChain = sharesNodeChain(), + ) // The fastest rate savings can pay for, or none when it covers no rate. val selected = options.firstOrNull(bump::canPay)?.speed _uiState.update { it.copy(feeBump = bump.copy(selected = selected)) } @@ -434,6 +441,8 @@ data class SparkExitFeeBumpUiState( val options: ImmutableList = persistentListOf(), val selected: FeeRate? = null, val spendableSats: ULong? = null, + /** Spark reads the node's chain, which a savings payment goes out on. */ + val sharesNodeChain: Boolean = false, val isPaying: Boolean = false, ) { val selectedOption: SparkExitFeeBumpOption? get() = options.firstOrNull { it.speed == selected } @@ -441,9 +450,9 @@ data class SparkExitFeeBumpUiState( /** Savings covers none of the rates offered. */ val isSavingsShort: Boolean get() = options.isNotEmpty() && options.none(::canPay) - /** Savings covers [option]'s cost, or there is nothing to pay. */ + /** Savings covers [option]'s cost on a chain Spark reads, or there is nothing to pay. */ fun canPay(option: SparkExitFeeBumpOption): Boolean = - option.totalSats == 0uL || (spendableSats ?: 0uL) >= option.totalSats + option.totalSats == 0uL || (sharesNodeChain && (spendableSats ?: 0uL) >= option.totalSats) } private fun SparkExitFeeBumpOption.withFeeFloor(floorSats: ULong?): SparkExitFeeBumpOption { diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 7bd1f932d2..6c4bc3b48e 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -916,7 +916,8 @@ class SparkExitRepoTest : BaseUnitTest() { whenever(transferRepo.isSettled(any())).thenReturn(Result.success(false)) whenever(transferRepo.updateClaimableAtHeight(any(), anyOrNull())).thenReturn(Result.success(Unit)) val (keychain, core) = keyed() - return createSut(connectedSpark(sdk), http, keychain, core, lightning) + // Spark reads the node's chain, so savings can pay the exit's funding. + return createSut(connectedSpark(sdk), http, keychain, core, lightning).apply { sharesNodeChain = { true } } } @Test @@ -1704,6 +1705,25 @@ class SparkExitRepoTest : BaseUnitTest() { assertTrue(ended.payHigherFee(option).isFailure) } + @Test + fun `a higher fee is never paid from savings on a chain spark does not read`() = test { + val store = SparkExitStore(File(Env.sparkExitRecordPath(0))) + store.save(runningRecord()) + var isPaid = false + stubFunding { + isPaid = true + Result.success(OnchainSendOutcome.Accepted("bump")) + } + val sut = quotedSut(FakeSparkExitRecovering()) + sut.sharesNodeChain = { false } + sut.load().getOrThrow() + + assertTrue(sut.payHigherFee(SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 6_000uL, 6_400uL)).isFailure) + + assertFalse(isPaid, "savings paid on a chain spark does not read") + assertEquals(2uL, assertNotNull(store.load()).feeRateSatPerVbyte) + } + @OptIn(ExperimentalCoroutinesApi::class) @Test fun `a higher fee paid while the exit ends is watched until its outputs reach the address`() = test { diff --git a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt index 6a71e7d073..aa1ab4e150 100644 --- a/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -168,11 +168,16 @@ class SparkExitViewModelTest : BaseUnitTest() { assertFalse(rising.copy(networkFees = SparkExitNetworkFees(2uL, 1uL)).canPayHigherFee) val fast = SparkExitFeeBumpOption(FeeRate.FAST, 9uL, 4_200uL, 4_620uL) - assertTrue(SparkExitFeeBumpUiState(spendableSats = 4_620uL).canPay(fast)) - assertFalse(SparkExitFeeBumpUiState(spendableSats = 4_619uL).canPay(fast)) - assertTrue(SparkExitFeeBumpUiState(spendableSats = 0uL).canPay(fast.copy(extraSats = 0uL, totalSats = 0uL))) - assertTrue(SparkExitFeeBumpUiState(options = persistentListOf(fast), spendableSats = 1_000uL).isSavingsShort) - assertFalse(SparkExitFeeBumpUiState(options = persistentListOf(fast), spendableSats = 5_000uL).isSavingsShort) + val onChain = SparkExitFeeBumpUiState(sharesNodeChain = true) + assertTrue(onChain.copy(spendableSats = 4_620uL).canPay(fast)) + assertFalse(onChain.copy(spendableSats = 4_619uL).canPay(fast)) + assertTrue(onChain.copy(spendableSats = 0uL).canPay(fast.copy(extraSats = 0uL, totalSats = 0uL))) + assertTrue(onChain.copy(options = persistentListOf(fast), spendableSats = 1_000uL).isSavingsShort) + assertFalse(onChain.copy(options = persistentListOf(fast), spendableSats = 5_000uL).isSavingsShort) + // Savings pays on the node's chain: while Spark reads another, only a rate with nothing to pay is offered. + val offChain = SparkExitFeeBumpUiState(spendableSats = 5_000uL, sharesNodeChain = false) + assertFalse(offChain.canPay(fast)) + assertTrue(offChain.canPay(fast.copy(extraSats = 0uL, totalSats = 0uL))) } @Test @@ -183,7 +188,7 @@ class SparkExitViewModelTest : BaseUnitTest() { whenever(repo.payHigherFee(fast)) .thenReturn(Result.failure(OnchainSendNotDispatchedError(OnchainSendChangedError(preparedFeeSats = 600uL)))) val context = mock { on { getString(any()) } doReturn "Fees changed" } - val sut = SparkExitViewModel(context, repo, sparkRepo) + val sut = SparkExitViewModel(context, repo, sparkRepo).apply { sharesNodeChain = { true } } sut.loadFeeBump() sut.payHigherFee() @@ -203,7 +208,7 @@ class SparkExitViewModelTest : BaseUnitTest() { .thenReturn(Result.failure(OnchainSendNotDispatchedError(OnchainSendChangedError(preparedFeeSats = 600uL)))) whenever(repo.payHigherFee(floored)).thenReturn(Result.success(Unit)) val context = mock { on { getString(any()) } doReturn "Fees changed" } - val sut = SparkExitViewModel(context, repo, sparkRepo) + val sut = SparkExitViewModel(context, repo, sparkRepo).apply { sharesNodeChain = { true } } sut.loadFeeBump() sut.payHigherFee() From 6bc1e3c63b4dad04c376f9d0fcb925d875f99272 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 10:26:08 +0100 Subject: [PATCH 151/154] fix: keep an exit's earlier addresses when two writers update them at once --- .../repositories/SparkExitEarlierAddress.kt | 53 +++++++++++-------- .../SparkExitEarlierAddressStoreTest.kt | 51 ++++++++++++++++++ 2 files changed, 83 insertions(+), 21 deletions(-) create mode 100644 app/src/test/java/to/bitkit/repositories/SparkExitEarlierAddressStoreTest.kt diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt index 4bd52675c2..2f5b9ae321 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt @@ -10,6 +10,7 @@ import to.bitkit.models.safe import java.io.File import java.nio.file.Files import java.nio.file.StandardCopyOption +import java.util.concurrent.ConcurrentHashMap import kotlin.time.Duration.Companion.days /** @@ -83,9 +84,13 @@ class SparkExitEarlierAddressStore(private val file: File) { companion object { /** Counts the writes of every wallet's list, so the metadata backup that carries them runs again. */ val writes = MutableStateFlow(0L) + + /** One lock per file, shared by every store over it, so no writer saves a list read before another's write. */ + private val locks = ConcurrentHashMap() } private val json = Json { ignoreUnknownKeys = true } + private val lock = locks.getOrPut(file.canonicalPath) { Any() } fun load(): List { if (!file.exists()) return emptyList() @@ -97,38 +102,44 @@ class SparkExitEarlierAddressStore(private val file: File) { * change at a cancelled exit's address, which a later exit reused, replaces that entry, so it is read for good. */ fun add(entry: SparkExitEarlierAddress): List { - val known = runCatching { load() }.getOrDefault(emptyList()) - val existing = known.firstOrNull { it.address == entry.address } - val updated = when { - existing == null -> known + entry - entry.kind == SparkExitEarlierAddress.Kind.KEPT_CHANGE && existing.kind != entry.kind -> - known.map { if (it.address == entry.address) entry.copy(sats = entry.sats ?: it.sats) else it } - entry.sats == null || entry.sats == existing.sats -> return known - else -> known.map { if (it.address == entry.address) it.copy(sats = entry.sats) else it } + synchronized(lock) { + val known = runCatching { load() }.getOrDefault(emptyList()) + val existing = known.firstOrNull { it.address == entry.address } + val updated = when { + existing == null -> known + entry + entry.kind == SparkExitEarlierAddress.Kind.KEPT_CHANGE && existing.kind != entry.kind -> + known.map { if (it.address == entry.address) entry.copy(sats = entry.sats ?: it.sats) else it } + entry.sats == null || entry.sats == existing.sats -> return known + else -> known.map { if (it.address == entry.address) it.copy(sats = entry.sats) else it } + } + save(updated) + return updated } - save(updated) - return updated } /** Sets what [address] holds, writing only when it changed. */ fun updateSats(address: String, sats: ULong): List { - val known = runCatching { load() }.getOrDefault(emptyList()) - if (known.none { it.address == address && it.sats != sats }) return known - val updated = known.map { if (it.address == address) it.copy(sats = sats) else it } - save(updated) - return updated + synchronized(lock) { + val known = runCatching { load() }.getOrDefault(emptyList()) + if (known.none { it.address == address && it.sats != sats }) return known + val updated = known.map { if (it.address == address) it.copy(sats = sats) else it } + save(updated) + return updated + } } /** Drops [address], such as one a new exit funds again. */ fun remove(address: String): List { - val known = runCatching { load() }.getOrDefault(emptyList()) - if (known.none { it.address == address }) return known - val updated = known.filter { it.address != address } - save(updated) - return updated + synchronized(lock) { + val known = runCatching { load() }.getOrDefault(emptyList()) + if (known.none { it.address == address }) return known + val updated = known.filter { it.address != address } + save(updated) + return updated + } } - fun delete() { + fun delete() = synchronized(lock) { check(!file.exists() || file.delete()) { "Failed to delete '${file.name}'" } } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitEarlierAddressStoreTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitEarlierAddressStoreTest.kt new file mode 100644 index 0000000000..142afe3b6f --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitEarlierAddressStoreTest.kt @@ -0,0 +1,51 @@ +package to.bitkit.repositories + +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import kotlin.test.assertEquals + +class SparkExitEarlierAddressStoreTest { + @get:Rule + val tmp = TemporaryFolder() + + @Test + fun `concurrent writers through separate stores of one file keep every address`() { + val file = File(tmp.root, "spark-exit-earlier.json") + // A foreground balance read and an exit tick each build their own store over the same file. + val stores = listOf( + SparkExitEarlierAddressStore(file), + SparkExitEarlierAddressStore(File(tmp.root, "./${file.name}")), + ) + val count = 200 + val start = CountDownLatch(1) + val pool = Executors.newFixedThreadPool(8) + val failures = mutableListOf() + repeat(count) { i -> + pool.execute { + start.await() + runCatching { + stores[i % stores.size].add( + SparkExitEarlierAddress( + address = "bcrt1q$i", + path = "m/86'/1'/0'/0/$i", + kind = SparkExitEarlierAddress.Kind.KEPT_CHANGE, + sats = i.toULong(), + atMillis = i.toLong(), + ), + ) + }.onFailure { synchronized(failures) { failures += it } } + } + } + start.countDown() + pool.shutdown() + pool.awaitTermination(30, TimeUnit.SECONDS) + + assertEquals(emptyList(), failures) + assertEquals((0 until count).map { "bcrt1q$it" }.toSet(), stores[0].load().map { it.address }.toSet()) + } +} From 126436b6ca53b59e18f6a17d604c580b5e36e93b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 10:28:51 +0100 Subject: [PATCH 152/154] fix: lightning connection reads using spark only outside an exit --- .../java/to/bitkit/repositories/HealthRepo.kt | 2 +- .../to/bitkit/repositories/HealthRepoTest.kt | 17 +++++++++++++++++ journeys/settings/app-status-emergency-exit.xml | 6 ++++-- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/HealthRepo.kt b/app/src/main/java/to/bitkit/repositories/HealthRepo.kt index a0773537b2..4a50965471 100644 --- a/app/src/main/java/to/bitkit/repositories/HealthRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/HealthRepo.kt @@ -97,7 +97,7 @@ class HealthRepo @Inject constructor( } val hasUsableChannels = lightningState.channels.any { it.isUsable } - val isLightningViaSpark = isOnline && !hasUsableChannels && sparkState.isReady + val isLightningViaSpark = isOnline && !hasUsableChannels && sparkState.isUsable val channelsHealth = when { !isOnline -> HealthState.ERROR diff --git a/app/src/test/java/to/bitkit/repositories/HealthRepoTest.kt b/app/src/test/java/to/bitkit/repositories/HealthRepoTest.kt index b245b0e541..f07f1b2a07 100644 --- a/app/src/test/java/to/bitkit/repositories/HealthRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/HealthRepoTest.kt @@ -309,6 +309,23 @@ class HealthRepoTest : BaseUnitTest() { } } + @Test + fun `channels status is not through spark while an emergency exit runs`() = test { + whenever(sparkRepo.state).thenReturn( + MutableStateFlow(SparkState(isSupported = true, isReady = true, isExiting = true)) + ) + + sut = createSut() + + sut.healthState.test { + val state = awaitItem() + assertEquals(HealthState.ERROR, state.channels) + assertEquals(false, state.isLightningViaSpark) + assertEquals(HealthState.READY, state.spark) + cancelAndIgnoreRemainingEvents() + } + } + @Test fun `channels status is error when neither a channel nor spark can pay`() = test { whenever(sparkRepo.state).thenReturn(MutableStateFlow(SparkState(isSupported = true))) diff --git a/journeys/settings/app-status-emergency-exit.xml b/journeys/settings/app-status-emergency-exit.xml index 968eb23dab..6173f75650 100644 --- a/journeys/settings/app-status-emergency-exit.xml +++ b/journeys/settings/app-status-emergency-exit.xml @@ -4,16 +4,18 @@ It reads "Fee funding needed" while the exit asks for fee funding and "In progress" otherwise, including while a payment that covers the funding waits to confirm. The row opens the exit's progress screen, and leaving that screen returns to App Status. With no active exit the row is absent. An exit paid from savings cannot be - cancelled and runs for days, so the row's removal once an exit ends is covered by unit tests, not here. + cancelled and runs for days, so the row's removal once an exit ends is covered by unit tests, not here. An exit takes Spark off the Lightning rail, so with no usable channel + Lightning Connection stops reading "Using Spark" while it runs. Precondition: dev build on regtest with Spark connected, a Spark balance and savings that can pay the exit's - fee funding. Start an emergency exit from Spark (spark emergency exit journey), pick "Pay from savings" and + fee funding. The wallet has no Lightning channel. Start an emergency exit from Spark (spark emergency exit journey), pick "Pay from savings" and swipe to start it. Starting an exit takes the Spark balance out of Spending for days, so use a throwaway wallet. Start on the wallet home screen. Tap the menu button (testTag "HeaderMenu") and tap App Status (testTag "DrawerAppStatus") Verify a row titled "Emergency Exit" (testTag "Status-spark_exit") sits under Lightning Connection (testTag "Status-lightning_connection") and reads "In progress", since savings paid the funding + Verify Lightning Connection (testTag "Status-lightning_connection") reads "No open connections", not "Using Spark" Tap the row and verify the exit's progress screen (testTag "SparkExitProgress") opens Tap "OK" (testTag "SparkExitProgressOk") and verify App Status shows again with the "Emergency Exit" row still there From b2e809b134bd540cfd327882a84c6c9cf714c628 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 10:34:49 +0100 Subject: [PATCH 153/154] chore: changelog fragment for the exit lightning connection fix --- changelog.d/next/1880.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/1880.fixed.md diff --git a/changelog.d/next/1880.fixed.md b/changelog.d/next/1880.fixed.md new file mode 100644 index 0000000000..9c61ea4154 --- /dev/null +++ b/changelog.d/next/1880.fixed.md @@ -0,0 +1 @@ +App Status no longer shows Lightning Connection as using Spark while an emergency exit runs. From 46c16d1035bd197feae90d57ad1e8f9c6cb32887 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Thu, 12 Nov 2026 10:55:49 +0100 Subject: [PATCH 154/154] fix: find a restored wallet's exit funding past its backed-up index --- .../bitkit/repositories/SparkExitFunding.kt | 11 +++-- .../to/bitkit/repositories/SparkExitRepo.kt | 31 ++++++------ .../bitkit/repositories/SparkExitRepoTest.kt | 48 ++++++++++++++++++- 3 files changed, 69 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt index 53c4101c6d..445530cdd9 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -517,12 +517,13 @@ object SparkExitMath { const val FUNDING_SCAN_MAX_ADDRESSES = 1_000 /** - * The funding index past the last one [isUsed] reports used, read from 0 until [FUNDING_SCAN_GAP_LIMIT] unused ones - * follow it, for a wallet that kept no index, such as one restored from the phrase or an older backup. + * The funding index past the last one [isUsed] reports used, read from [from] until [FUNDING_SCAN_GAP_LIMIT] unused + * ones follow it: from 0 for a wallet that kept no index, such as one restored from the phrase or an older backup, + * and from a restored index, which can predate the last exit's funding. */ - suspend fun scanNextFundingIndex(isUsed: suspend (UInt) -> Boolean): UInt { - var next = 0u - var index = 0u + suspend fun scanNextFundingIndex(from: UInt = 0u, isUsed: suspend (UInt) -> Boolean): UInt { + var next = from + var index = from while (index < next + FUNDING_SCAN_GAP_LIMIT.toUInt() && index < FUNDING_SCAN_MAX_ADDRESSES.toUInt()) { if (isUsed(index)) next = index + 1u index++ diff --git a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt index 09ca7ef372..9f0ed4c8b2 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -1139,12 +1139,13 @@ class SparkExitRepo @Inject constructor( } /** - * Finds earlier exits' funding after a restore. With no index kept and no record, scans for the next index and - * keeps it; with an index a restore brought back, reads each funding address below it, once. Each funding address - * that still holds coins and nothing watches is listed as kept change, so it is watched for good. Throws when a - * read fails, keeping no index and the restore pending, so it runs again on the next start. + * Finds earlier exits' funding after a restore. Scans for the next index and keeps it: from 0 with no index kept + * and no record, else from the index a restore brought back, reading each funding address below it once too. Each + * funding address that still holds coins and nothing watches is listed as kept change, so it is watched for good. + * Throws when a read or that listing fails, keeping no index and the restore pending, so it runs again on the next + * start. * - * @return the index a scan found, or null when there was nothing to scan. + * @return the index the scan found, or null when no restore was pending. */ private suspend fun recoverFunding(chain: SparkExitChain): UInt? { val cache = cacheStore.data.first() @@ -1155,14 +1156,12 @@ class SparkExitRepo @Inject constructor( val addresses = mutableMapOf() suspend fun address(index: UInt) = addresses.getOrPut(index) { fundingAddress(index).address } val used = mutableListOf() - val scanned = if (kept != null) { - null - } else { - SparkExitMath.scanNextFundingIndex { index -> - chain.isAddressUsed(address(index)).also { if (it) used += index } - } + // A restored index can predate the last exit's funding, when its backup didn't land, so the scan goes on from + // it. + val scanned = SparkExitMath.scanNextFundingIndex(from = kept?.toUInt() ?: 0u) { index -> + chain.isAddressUsed(address(index)).also { if (it) used += index } } - val candidates = if (kept == null) used else (0u until kept.toUInt()).toList() + val candidates = if (kept == null) used else (0u until kept.toUInt()).toList() + used val listed = runCatching { earlierAddressStore.load() }.getOrDefault(emptyList()).map { it.address } val watched = listed + stored?.funding?.map { it.address }.orEmpty() for (index in candidates.filter { address(it) !in watched }) { @@ -1170,15 +1169,17 @@ class SparkExitRepo @Inject constructor( val sats = chain.utxos(address).fold(0uL) { sum, utxo -> sum.safe() + utxo.value.safe() } if (sats == 0uL) continue val path = SparkExitFundingKey.path(index.toInt(), Env.network) - keepEarlierAddress( + // A failed write throws here, so the restore stays pending and the address is looked for again. + val listedNow = earlierAddressStore.add( SparkExitEarlierAddress(address, path, SparkExitEarlierAddress.Kind.KEPT_CHANGE, sats, clock.nowMs()) ) + _state.update { it.copy(earlierAddresses = listedNow) } } cacheStore.update { val indexes = it.sparkExitNextFundingIndexes - val next = scanned?.let { found -> maxOf(indexes[fundingIndexKey] ?: 0, found.toInt()) } + val next = maxOf(indexes[fundingIndexKey] ?: 0, scanned.toInt()) it.copy( - sparkExitNextFundingIndexes = next?.let { found -> indexes + (fundingIndexKey to found) } ?: indexes, + sparkExitNextFundingIndexes = indexes + (fundingIndexKey to next), sparkExitFundingRecoveryPending = it.sparkExitFundingRecoveryPending - fundingIndexKey, ) } diff --git a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt index 6c4bc3b48e..3307dd0d23 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -44,6 +44,7 @@ import org.mockito.kotlin.any import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argumentCaptor import org.mockito.kotlin.atLeastOnce +import org.mockito.kotlin.atMost import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn import org.mockito.kotlin.doSuspendableAnswer @@ -851,12 +852,57 @@ class SparkExitRepoTest : BaseUnitTest() { sut.refreshEarlierAddresses() assertEquals(listOf(keptCoins(2, 5_000uL)), sut.state.value.earlierAddresses, "the lost funding goes unwatched") - assertTrue(reads.isEmpty(), "a restored index needs no scan for the next one") + assertEquals((3 until 23).toList(), reads, "a restored index is scanned forward from, once") val cache = keptCache(restored) assertTrue(cache.sparkExitFundingRecoveryPending.isEmpty(), "every start reads the funding addresses again") assertEquals(mapOf(key to 3), cache.sparkExitNextFundingIndexes) } + @Test + fun `a restored funding index that predates the last exit's funding finds its coins`() = test { + // The backup carrying index 4 never landed: the exit that funded address 3 is lost with it. + val key = "${Env.network.name.lowercase()}/wallet0" + val restored = AppCacheData( + sparkExitNextFundingIndexes = mapOf(key to 3), + sparkExitFundingRecoveryPending = setOf(key), + ) + whenever(cacheStore.data).thenReturn(flowOf(restored)) + val reads = mutableListOf() + val sut = scannedSut(scanChain(used = setOf(0, 1, 2, 3), reads = reads, coins = mapOf(3 to 7_000))) + sut.load(0).getOrThrow() + + sut.refreshEarlierAddresses() + + assertEquals(listOf(keptCoins(3, 7_000uL)), sut.state.value.earlierAddresses, "address 3's coins stay hidden") + assertEquals(mapOf(key to 4), keptCache(restored).sparkExitNextFundingIndexes, "the next exit reuses address 3") + } + + @Test + fun `a failed listing of a restored funding address keeps the restore pending`() = test { + val key = "${Env.network.name.lowercase()}/wallet0" + val restored = AppCacheData( + sparkExitNextFundingIndexes = mapOf(key to 3), + sparkExitFundingRecoveryPending = setOf(key), + ) + whenever(cacheStore.data).thenReturn(flowOf(restored)) + // A non-empty folder where the list goes makes its write fail. + File(Env.sparkExitEarlierAddressesPath(0)).apply { mkdirs() }.resolve("blocker").writeText("x") + val reads = mutableListOf() + val sut = scannedSut(scanChain(used = setOf(0, 1, 2), reads = reads, coins = mapOf(2 to 5_000))) + sut.load(0).getOrThrow() + + sut.refreshEarlierAddresses() + + val updates = argumentCaptor<(AppCacheData) -> AppCacheData>() + verify(cacheStore, atMost(Int.MAX_VALUE)).update(updates.capture()) + val cache = updates.allValues.fold(restored) { data, update -> update(data) } + assertEquals( + setOf(key), + cache.sparkExitFundingRecoveryPending, + "the coin-holding address is never looked for again", + ) + } + @Test fun `a kept funding index with no restore pending reads no funding address`() = test { val key = "${Env.network.name.lowercase()}/wallet0"