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..a77e2cd11d --- /dev/null +++ b/app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt @@ -0,0 +1,117 @@ +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.CpfpFundingStrategy +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( + feeRateSatPerVbyte = feeRate, + fundingKind = CpfpFundingKind.P2wpkh, + fundingStrategy = CpfpFundingStrategy.PER_NODE, + destination = address.address, + selection = ExitLeafSelection.All, + ), + ) + assertTrue(prepared.leaves.isEmpty()) + assertFalse(SparkExitQuote(prepared).isWorthExiting) + + val chain = EsploraSparkExitChain(checkNotNull(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 @@ + + + + + + + @@ -61,6 +65,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 bbede61b0d..1db082d407 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -336,6 +336,22 @@ 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(), + /** + * 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(), /** A Spark withdrawal to a Paykit contact that started, kept until Spark's payment list settles it. */ val pendingSparkWithdrawal: PendingSparkWithdrawal? = null, /** The latest Spark withdrawals to Paykit contacts that settled as sent, so a restart never reads one as unsent. */ 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 7b23a2a6ac..40f321a491 100644 --- a/app/src/main/java/to/bitkit/env/Env.kt +++ b/app/src/main/java/to/bitkit/env/Env.kt @@ -261,6 +261,26 @@ 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() + } + + /** 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() + } + + /** 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/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/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/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/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 2faa96a4e2..86601183b0 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 @@ -480,6 +482,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 @@ -912,11 +915,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 @@ -1213,6 +1242,7 @@ class BackupRepo @Inject constructor( ) val parsed = decodeBackup(migration.json) val cleanCache = parsed.cache.resetBip21() // Force address rotation + val restoredIndexKeys = cleanCache.sparkExitNextFundingIndexes.keys // The backed-up send hashes can predate either rail's latest sends, so each rail's own list seeds them again. val restoredAt = currentTimeMillis().milliseconds.inWholeSeconds cacheStore.update { @@ -1221,8 +1251,17 @@ class BackupRepo @Inject constructor( sparkHistoryUnseededSince = restoredAt, ldkHistoryUnseededSince = restoredAt, sparkRestoredAt = restoredAt, + // 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, + ), + // The exit then looks once for funding addresses that still hold coins and nothing watches. + sparkExitFundingRecoveryPending = it.sparkExitFundingRecoveryPending + restoredIndexKeys, ) } + 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/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/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 576552bb45..4dad77b605 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -2434,6 +2434,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 @@ -2448,7 +2450,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/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/main/java/to/bitkit/repositories/SparkExitChain.kt b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt new file mode 100644 index 0000000000..f779833419 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitChain.kt @@ -0,0 +1,468 @@ +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.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) + +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() = "$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. */ + 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 + + /** 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 + + /** + * 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 + + /** + * 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. */ + 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 + + /** 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 } + + /** 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()) + + /** 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) + +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: a transaction with a CPFP child goes out as a package (a JSON array of hex), one + * without as a single `/tx`. A host that answers `/tx` with a bare `{"code":-1}`, as Spark's hosted regtest does for + * every lone transaction, gets the same hex again as a one-item package, whose answer decides. + */ +class EsploraSparkExitChain( + private val hosts: SparkExitHosts, + private val client: HttpClient, +) : SparkExitChain { + companion object { + private val json = Json { ignoreUnknownKeys = true } + + /** + * 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) + + private const val NOT_FOUND = 404 + } + + 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 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) + + override suspend fun nextBlockFeeRate(): ULong = SparkExitFeeEstimates.at(feeEstimates(), 1) ?: MIN_RELAY_RATE + + override suspend fun networkFees(): SparkExitNetworkFees { + 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" + var lastError: Throwable? = null + for (host in hosts.reads) { + 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() + 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) + } + // 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.broadcasts.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: SparkExitBroadcastHost, + hexes: List, + parentTxid: String?, + ): SparkExitBroadcastOutcome? { + val body = JsonArray(hexes.map(::JsonPrimitive)).toString() + 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) + } + 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 + 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 + } + + 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.reads) { + 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", + // 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") + 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(shortReason(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 + } + + 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) + + 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) + + 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(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(shortReason(text)) + inputsMissingMessages.any { it in text } || hasRpcCode(-25, text) -> SparkExitBroadcastOutcome.InputsMissing( + shortReason(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, 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/main/java/to/bitkit/repositories/SparkExitDriver.kt b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt new file mode 100644 index 0000000000..9d360ae8e3 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitDriver.kt @@ -0,0 +1,1554 @@ +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.ImportUnilateralExitStateResponse +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.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 +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 + + /** 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): ImportUnilateralExitStateResponse +} + +/** + * 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. The + * quote carries the values of the lost leaves the operators still list. + */ +suspend fun SparkExitRecovering.prepareAll( + request: PrepareRecoverFundsRequest, + lost: Set, +): 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 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 -> + 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 + } + val nothing = all.copy( + leaves = emptyList(), + skipped = skipped, + recoverableValueSats = 0uL, + totalFeeSats = 0uL, + cooperativeFeeSats = 0uL, + cpfpFeeSats = 0uL, + fanoutFeeSats = 0uL, + refundFeeSats = 0uL, + sweepFeeSats = 0uL, + funding = null, + ) + return SparkExitQuote(nothing, null, lostLeafSats) +} + +/** + * 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 + * 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, + /** 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" + + /** 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 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 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 + + /** 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 + + 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 && !record.isEndedPaymentPending) return record + record = watchEndedPayment(record) + if (record.isLeftoverSweepPending) record = sweepLeftover(record) + save(record) + return record + } + is SparkExitRecord.Phase.AwaitingFunding, is SparkExitRecord.Phase.NeedsFunding -> { + // 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 + 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) { + record = buildOnceFunded(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) + } + } + // 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.isActive) record = watchEndedPayment(record) + if (record.isLeftoverSweepPending) record = sweepLeftover(record) + save(record) + 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, 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) + } + } + + 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 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) + } + + /** + * 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, + 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) && + !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 + val failed = record.copy(phase = SparkExitRecord.Phase.Failed(reason), isRebuilding = false) + return end(failed, record) + } + if (prepared.leaves.isEmpty()) { + // 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) { + 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) + 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) + // 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, isUnverifiedAsk = true) + } + 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 + // retried for a week like any failed leaf, then let go. + if (built.failed.isNotEmpty()) { + 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 (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) + return adopted + } + 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. + 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 waiting = waitingLeafIds(record, prepared.skipped, stopped) + // 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) + Logger.info( + "Built Spark exit generation '${adopted.generation}' of '${built.transactions.size}' transactions", + context = TAG, + ) + return broadcastReady(adopted) + } + + 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 + } + // 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) + } + + 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 }) + } + + 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 + } + + 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 emptyList() + return skipped.filter { + it.leafId in record.exitLeafIds && when (it.reason) { + SkippedLeafReason.Unverified, + SkippedLeafReason.FundsNotFound, + SkippedLeafReason.OperatorsUnavailable, + -> true + is SkippedLeafReason.NotRecoverable -> isStoppedWaiting(record, it.leafId, stopped) + SkippedLeafReason.FeeExceedsValue -> false + } + }.map { it.leafId } + } + + private fun prepareRequest(record: SparkExitRecord, selection: ExitLeafSelection) = PrepareRecoverFundsRequest( + feeRateSatPerVbyte = record.feeRateSatPerVbyte, + fundingKind = CpfpFundingKind.P2wpkh, + fundingStrategy = record.cpfpFundingStrategy, + destination = record.destination, + selection = selection, + ) + + 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) + } + 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))) + } + } + + 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) + } + + /** + * 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 + 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 -> { + // 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, 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, isUnverifiedAsk = false) + } + } + } + + 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()) { + 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)) } + .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 + ).withProgress(checked.recovery).withRebuildLanded(checked.recovery) + return when (checked.verdict) { + RecoveryVerdict.Valid -> { + val confirmed = checked.recovery.transactions + .filter { it.status is ExitTransactionStatus.Confirmed } + .map { it.txid } + .toSet() + 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 = 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 (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) + 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, 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 + 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. + if (checked.recovery.failed.isNotEmpty() && !updated.isFailedLeavesReleased) { + return retryFailedLeaves(updated, checked.recovery.failed.map { it.leafId }, sdk) + } + retryWaitingLeaves(updated, sdk)?.let { return it } + end(updated.ended(), updated) + } + is RecoveryVerdict.Redo -> { + Logger.warn( + "Rebuilding Spark exit diverged on-chain as generation '${record.generation + 1}'", + context = TAG, + ) + // Only a rebuild over a diverged chain can find a leaf an older state claimed. + rebuild(updated.copy(isRedoRebuild = true), sdk) + } + } + } + + /** + * 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 + * 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" } + 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)) + // 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()) } + 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, + 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(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) + var skipped = emptyList() + 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 } + + 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 + // 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()), + 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()) + .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) + } + + /** + * 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. 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, + isFunded: Boolean = false, + ): 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 (!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))) + }.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 result = runSuspendCatching { + sdk.recover( + RecoverFundsRequest(prepared, if (needsFunding) record.fundingInputs else emptyList()), + if (needsFunding) makeSigner() else null, + ) + } + (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() + 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(), + // 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, + ) + + 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) + } + + 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) + } + + 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) + } + + 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) + } + + 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 + val transactions = record.recovery?.transactions.orEmpty().filter { it.kind != RecoveryTxKind.COOPERATIVE } + return transactions.any { it.status == ExitTransactionStatus.Unverified } && + transactions.none { it.status == ExitTransactionStatus.Ready } + } + + 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) + } + + private suspend fun isUnknownToChain(txid: String): Boolean = + runSuspendCatching { !chain.isTxKnown(txid) }.getOrDefault(false) + + 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) + } + + private suspend fun sweepLeftover(record: SparkExitRecord): SparkExitRecord { + val built = record.leftoverSweep + if (built?.txHex != null) { + // The sweep, or a version it replaced, confirmed. + 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 readAddressAgain(record, built) + } + 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 } + // 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. + 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) { + 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; 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) + 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()) + // 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) 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. + 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( + confirmed.map { SparkExitSweep.Input(it.txid, it.vout, it.value) }, + rate, + ) + 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. + */ + private suspend fun sweepLanded( + record: SparkExitRecord, + 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. + // 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 nextBlockRate(): ULong? = runSuspendCatching { chain.nextBlockFeeRate() } + .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() + + 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 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 ?: earlier)?.sentTxids.orEmpty(), + waitingSince = since, + checkedAtHeight = height, + refusedFeeRate = floor, + retryAtHeight = floor?.let { height + 1u }, + ), + ) + } + + 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 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) + } ?: 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 }) + return buildSweep(record, inputs, rate, replaced) + } + + private suspend fun isConfirmed(txid: String): Boolean = + runSuspendCatching { chain.txStatus(txid) }.getOrNull()?.confirmed == true + + private suspend fun buildSweep( + record: SparkExitRecord, + inputs: List, + feeRate: ULong, + replaced: List? = null, + ): SparkExitRecord { + val address = record.funding.firstOrNull()?.address ?: return record + 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 + } + // A replacement of an accepted sweep keeps that one; otherwise the leftover waits for cheaper fees. + ?: 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) + SparkExitRecord.LeftoverSweep( + txid = SignedTransactionId.fromHex(hex), + txHex = hex, + 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) + 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, + 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 && + !outcome.reason.contains("fee", ignoreCase = true) -> + waitForFees(record.copy(leftoverSweep = sweep)) + 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, + is SparkExitBroadcastOutcome.NotMature, + -> record + } + } + + 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 + } + + 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) } + } + + 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 + // 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.isCooperativeUnverified } + .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 + } + + private suspend fun broadcastWithoutSdk(record: SparkExitRecord): SparkExitRecord { + val recovery = record.recovery ?: return record + val tip = chain.tipHeight() + // 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) } + val statuses = mutableMapOf() + suspend fun status(txid: String): EsploraTxStatus? { + if (txid !in statuses) { + statuses[txid] = runSuspendCatching { chain.txStatus(txid) }.getOrNull() ?: saved[txid] + } + return statuses[txid] + } + 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 + 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 + } + 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 } + 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.ended(), 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 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 + } + + 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) + + private suspend fun broadcast( + tx: RecoveryTransaction, + record: SparkExitRecord, + parentsConfirmed: Boolean, + ): 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 + // 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( + attempts = existing.attempts + 1, + rejections = existing.rejections + rejection, + lastAttemptAt = nowMillis(), + lastOutcome = outcome.summary, + 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, + attempts = 1, + rejections = rejection, + lastAttemptAt = nowMillis(), + lastOutcome = outcome.summary, + isAccepted = isAccepted, + isInputSpent = isInputSpent, + feeChainFailures = if (isStuck) 1 else 0, + acceptedAtHeight = if (isAccepted) tip else null, + ) + val log = if (existing == null) { + record.broadcastLog + entry + } else { + record.broadcastLog.map { if (it === existing) entry else it } + } + return record.copy(broadcastLog = log) + } +} + +/** + * 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() { + 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 + * 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 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. */ +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" + + 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() +} + +/** 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() +} + +/** + * 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 = + copy(phase = SparkExitRecord.Phase.Running, isRebuilding = false, isUnverifiedAsk = false) + +/** + * 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/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt new file mode 100644 index 0000000000..2f5b9ae321 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitEarlierAddress.kt @@ -0,0 +1,153 @@ +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 +import java.nio.file.StandardCopyOption +import java.util.concurrent.ConcurrentHashMap +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, +) { + /** [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("keptChange"), + + /** The funding address of a cancelled exit that was forgotten: a late payment can still land there. */ + 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. + */ + fun isWatched(nowMillis: Long): Boolean = + kind == Kind.KEPT_CHANGE || nowMillis - atMillis < WATCH_PERIOD.inWholeMilliseconds + + 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 + 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, leftover -> sum.safe() + leftover.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) { + 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() + return json.decodeFromString(file.readText()) + } + + /** + * 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 { + 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 + } + } + + /** Sets what [address] holds, writing only when it changed. */ + fun updateSats(address: String, sats: ULong): List { + 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 { + 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() = synchronized(lock) { + 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) + 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 new file mode 100644 index 0000000000..445530cdd9 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitFunding.kt @@ -0,0 +1,618 @@ +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 com.synonym.bitkitcore.FeeRates +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 +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. [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, + val lostLeafSats: List = emptyList(), +) { + /** 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 } + + /** 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() } + + /** + * 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) + + /** + * 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() { + val leaves = prepared.leaves.fold(0uL) { sum, leaf -> sum.safe() + leaf.valueSats.safe() } + val beyond = SparkExitMath.outsideExitSats(leaves.safe() + leftBehindSats.safe(), sparkBalanceSats) + 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 +} + +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: [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 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() + + /** + * 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 + .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 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::fundingTxids).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. 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?, 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() + } + + /** 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 } + } + + /** + * 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 count only while the balance still holds them ([beyondLostLeaves]). + */ + fun staysOnSparkSats(balanceSats: ULong?, record: SparkExitRecord?): ULong? { + val leafTotal = record?.leafTotalSats ?: return null + 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 } + } + + /** + * [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? { + if (leafTotalSats == null || balanceSats == null || balanceSats <= leafTotalSats) return null + 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 + * 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 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 + 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() } + // 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) + } + // 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) + } + + /** + * 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 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 + return SparkExitPartialFunding( + receivedSats, + requiredSats, + maxOf(requiredSats - receivedSats, FUNDING_DUST_SATS) + ) + } + + /** + * 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 } + 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]. */ + 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 + + /** 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 + + /** + * 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) + } + + /** 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 [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(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++ + } + 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) } + + /** + * 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 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. */ +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) + +/** + * 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, + /** The rates [totalSats] was priced at, which the payment sends at, so it never costs more than shown. */ + val feeRates: FeeRates? = null, +) { + 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?) + +/** 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..01cbe6e701 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRecord.kt @@ -0,0 +1,1439 @@ +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 +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.JsonObjectBuilder +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.io.FileOutputStream +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, + /** + * 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. + */ + 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(), + /** + * 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 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. */ + 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, + /** + * 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. */ + 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. + */ + 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, + /** 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(), + /** + * 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]. */ + 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 + + /** 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 + + /** + * 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 + + /** [fundingStrategy] of an exit that funds each fee-bumped transaction from a UTXO of its own. */ + const val PER_NODE = "perNode" + } + + 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, + /** 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( + val txid: String, + val vout: UInt, + val valueSats: ULong, + ) + + data class LostLeaf(val leafId: String, val valueSats: ULong) + + 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. */ + 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() { + 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 + 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 && !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 + * [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 + 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?, + val txHex: String?, + val valueSats: ULong, + 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(), + /** 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, + /** + * 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, + /** 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 + + /** 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 + } + + /** 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 + if (sweep.isWaitingForFees) return true + return sweep.txid != null && (sweep.rejection == null || sweep.isFeeRejection) && !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. 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 || hasUnseenResult + + /** 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 || 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 + + 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 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 + + /** 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 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() } + + /** 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 = 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(), + landedSweepTxid = recovery?.transactions + ?.firstOrNull { it.kind == RecoveryTxKind.SWEEP && it.status is ExitTransactionStatus.Confirmed } + ?.txid + ?: landedSweepTxid, + generation = generation + 1, + recovery = built, + broadcastLog = emptyList(), + phase = Phase.Running, + isRebuilding = false, + lastBuildAt = atMillis, + failedLeafCount = built.failed.size, + retrySince = null, + retriedAt = null, + // A rebuild from the chain keeps saying so until one of its steps confirms. + rebuiltFromChainConfirmedCount = if (isRebuiltFromChain) { + rebuiltFromChainConfirmedCount ?: SparkExitMath.confirmedCount(built) + } else { + null + }, + ) + + /** + * 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 { + 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) + } + + /** 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. 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, + isFeeBumpPending = true, + feeBumpBuiltAtHeight = null, + ) + 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, + ) + } + + /** The exit retries cooperative leaves the operators moved on-chain but could not co-sign. */ + val isRetryingFailedLeaves: Boolean get() = isActive && failedLeafRetrySince != null + + /** + * 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 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 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 && + recovery.transactions.all { it.status is ExitTransactionStatus.Confirmed } + + 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 + + /** + * 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 + 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 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? { + 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 + tip != null && 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. + */ + 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 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 + .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. 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() + + /** 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.copy(file.toPath(), aside.toPath(), StandardCopyOption.REPLACE_EXISTING) + } + + fun save(record: SparkExitRecord) { + file.parentFile?.mkdirs() + val temp = File(file.parentFile, "${file.name}.tmp") + writeDurably(temp, SparkExitJson.encode(record)) + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } + + 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}'" } } + } +} + +/** + * 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") + writeDurably(temp, JsonArray((known + leafIds).sorted().map(::JsonPrimitive)).toString()) + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } + + fun delete() { + file.delete() + } +} + +/** 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) + +/** + * 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'") + +/** + * 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 { + 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") }, + outsideSats = read { o.ulongOrNull("outsideSats") }, + 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") }, + fundingStrategy = read { o.stringOrNull("fundingStrategy") }, + // 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(), + leafSats = read { leafSatsFromJson(o) }.orEmpty(), + landedSweepTxid = read { o.stringOrNull("landedSweepTxid") }, + sweptLeftover = read { sweptLeftoverFromJson(o) }.orEmpty(), + ) + } + + 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) + if (it.feeChainFailures > 0) put("feeChainFailures", it.feeChainFailures) + it.acceptedAtHeight?.let { height -> put("acceptedAtHeight", height.toLong()) } + }, + ) + } + }, + ) + 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()) } + r.outsideSats?.let { put("outsideSats", it.toLong()) } + if (r.earlierCpfpTxids.isNotEmpty()) { + put("earlierCpfpTxids", buildJsonArray { r.earlierCpfpTxids.forEach { add(JsonPrimitive(it)) } }) + } + r.leftoverSweep?.let { put("leftoverSweep", sweepToJson(it)) } + 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) } }, + ) + } + putRebuildState(r) + 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 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)) } }) + } + 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()) } + 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) + 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()) } + 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) + if (r.isUnverifiedAsk) put("isUnverifiedAsk", true) + putFeeBumpState(r) + 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) + 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", + 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()) } + if (r.isCancelled) put("isCancelled", true) + if (r.earlierReceivedSats.isNotEmpty()) { + put( + "earlierReceivedSats", + 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( + 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, + feeChainFailures = b.intOrNull("feeChainFailures") ?: 0, + acceptedAtHeight = b.ulongOrNull("acceptedAtHeight")?.toUInt(), + ) + }, + transferId = o.stringOrNull("transferId"), + expectedSats = o.ulong("expectedSats"), + claimableAtHeight = o.ulongOrNull("claimableAtHeight")?.toUInt(), + 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"), + outsideSats = o.ulongOrNull("outsideSats"), + earlierCpfpTxids = o.arrayOrEmpty("earlierCpfpTxids").map { it.jsonPrimitive.content }, + leftoverSweep = o.objectOrNull("leftoverSweep")?.let(::sweepFromJson), + 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")) + }, + 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(), + waitingLeafIds = o.arrayOrEmpty("waitingLeafIds").map { it.jsonPrimitive.content }, + exitStateSnapshot = o.stringOrNull("exitStateSnapshot"), + 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 + SparkExitRecord.FailedLeaf(l.string("leafId"), l.ulong("valueSats")) + }, + failedLeafRetrySince = o.ulongOrNull("failedLeafRetrySince")?.toUInt(), + failedLeafRetriedAt = o.ulongOrNull("failedLeafRetriedAt")?.toUInt(), + 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(), + isCancelled = o.booleanOrNull("isCancelled") ?: false, + 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")) + } + + 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()) }) + 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..9f0ed4c8b2 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitRepo.kt @@ -0,0 +1,1309 @@ +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 +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 +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.async +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.FeeRate +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, +) { + /** 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" + + /** 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() + + /** 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 + + @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 + // 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.deleteWithCopies() } + .onFailure { e -> + Logger.warn( + "Failed to delete the wiped Spark exit record", + e, + context = TAG + ) + } + 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 + // 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 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) } + + // region lifecycle + + /** + * 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 { + 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() + } + isLoaded = true + 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) + if (record?.needsDriving == true) work.schedulePeriodic() + record + } + } + + 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()) } + if (salvaged == null) { + // Nothing to rebuild from: only the copy set aside stays. + runCatching { store.delete() } + return null + } + 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 + } + + /** 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) } + refreshEarlierAddresses() + while (isActive && _state.value.record?.needsDriving == true) { + tick() + delay(FOREGROUND_TICK_INTERVAL) + } + } + } + + /** + * 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 + 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) { + 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 + } + + /** + * 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 { + // 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) { + // 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. + val connect = scope.async { sparkRepo.start(walletIndex) } + withTimeoutOrNull(BACKGROUND_CONNECT_TIMEOUT) { connect.await() } + 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) { + 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 { + 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()) } + .onFailure { e -> Logger.warn("Failed to update Spark exit alerts", e, context = TAG) } + } + } + } finally { + // 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() + } + } + + 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 } } + refreshNetworkFees(chain) + 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. + 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) + // 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 + // 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 && + updated.unpublishedStep == null && + !isStuckWithoutSdk && updated.underpricedStep(tip) == null + afterTick(updated, current, isOnTrack, reportedLost) + 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 = ::saveRecord, + nowMillis = clock::nowMs, + tip = tip, + trustedFeeRate = { lightningRepo.getFeeRates().getOrNull()?.fast?.toULong() }, + ) + + private suspend fun afterTick( + record: SparkExitRecord, + previous: SparkExitRecord, + isOnTrack: Boolean, + reportedLost: Set, + ) { + record.transferId?.let { transferRepo.updateClaimableAtHeight(it, record.claimableAtHeight) } + if (record.isLeftoverKept && !previous.isLeftoverKept) { + keepEarlierAddress(SparkExitEarlierAddress.keptChange(record, Env.network, clock.nowMs())) + } + settleIfFinished(record) + updateAlerts(record, previous, isOnTrack, reportedLost) + if (!record.isActive && previous.isActive) { + Logger.info("Ended Spark exit with phase '${record.phase}'", context = TAG) + sparkRepo.setExiting(false) + } + if (!record.needsDriving) work.cancelAll() + } + + 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 + // 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.hasLeavesOutstanding)) { + transferRepo.markSettled(transferId) + } + } + + 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 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) } + 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), + ) + } + } + + private fun updateAlerts( + record: SparkExitRecord, + previous: SparkExitRecord, + 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 }) + } + // 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.NotMoving, + deadlineAtMillis = clock.nowMs() + deadline.deadlineIn.inWholeMilliseconds + ) + } + if (SparkExitAlerts.isFundingAskBack(record, previous)) work.notify(SparkExitAlert.Funding) + 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 -> { + work.keepFeeLow(null) + work.cancelDeadline() + } + SparkExitRecord.Phase.Running -> { + 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), + 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. + if (previous.phase !is SparkExitRecord.Phase.NeedsFunding && !record.isAwaitingOwnPayment) { + work.notify(SparkExitAlert.Funding) + } + } + else -> work.cancelDeadline() + } + } + + 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() + + // 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() + // 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(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 + _state.update { + 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 + }.onFailure { + Logger.error("Failed to quote the Spark exit", it, context = TAG) + } + } + + /** + * 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" } + // 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 { + 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, + // that is the error the screen names. + priced.mapNotNull { it.getOrNull() }.ifEmpty { + 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) + } + } + + /** 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 { + if (!paymentMutex.tryLock()) throw SparkExitError("A Spark exit payment is already being made") + try { + // A payment that went out is always saved, even when the fee bump screen goes away meanwhile. + withContext(NonCancellable) { payHigherFeeLocked(option) } + } finally { + paymentMutex.unlock() + } + }.onFailure { + Logger.error("Failed to raise the Spark exit fee", it, context = TAG) + } + } + + /** + * 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" } + // 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 { + null + } + tickMutex.withLock { + val current = _state.value.record ?: return@withLock + if (current.isRebuilding && current.isActive) { + // 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) { + // 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) + watchPayment(current, paid) + return@withLock + } + val bumped = current.applyFeeBump(option.rateSatPerVbyte, option.extraSats, txid) + saveRecord(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() } + } + + 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( + 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, 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(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 = savingsFundingSats(pending.quote.fundingSats, pending.feeRate) + 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, + Env.sparkSharesNodeChain, + ), + ) + } + } + + /** 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 { + val chain = requireNotNull(chain) { "No chain host for this network" } + val address = requireNotNull(_state.value.fundingAddress) { "No Spark exit funding address" } + 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 + } + } + + /** + * 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 (!paymentMutex.tryLock()) throw SparkExitError("A Spark exit is already starting") + try { + startLocked(fundFromSavings) + } finally { + paymentMutex.unlock() + } + }.onFailure { + Logger.error("Failed to start the Spark exit", it, context = TAG) + } + } + + 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 + // 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() + // 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(), + 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, + leafSats = quote.leafSats, + 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 + // 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() + // 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) + } + // 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 + _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 + } + } 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. + // 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) + } + // A refused payment shows on progress at once, with the offer to pay again. + .onFailure { _state.value.record?.let { current -> noteSavingsSend(current) } } + .getOrThrow() + } + } + } + + /** + * 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, + leafSats = fresh.leafSats, + outsideSats = fresh.outsideSats, + 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 + + 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( + 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 { + 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, feeRates, approvedFeeSats) + val record = _state.value.record ?: return@withLock + val paid = record.copy(fundingPaymentTxid = txid) + saveRecord(paid) + _state.update { + it.copy(record = paid, fundingState = SparkExitMath.fundingState(paid, utxos = null)) + } + } + } + + private suspend fun savingsSend(record: SparkExitRecord): OnchainSendAttempt? { + val address = record.funding.firstOrNull()?.address ?: return null + val attempt = runSuspendCatching { lightningRepo.currentOnchainSendAttempt() }.getOrNull() + 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 { + // 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. 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 { + paymentMutex.unlock() + } + }.onFailure { + Logger.error("Failed to pay the Spark exit funding from savings again", it, context = TAG) + } + } + + /** 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) + } + + private suspend fun fundingTxid(outcome: OnchainSendOutcome, sats: ULong): String { + 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) } + Logger.info("Funded the Spark exit with '$sats' sats in '${outcome.txid}'", context = TAG) + return outcome.txid + } + + /** + * 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 && + record.fundingPaymentTxid == null && + !exit.isSavingsSendUnresolved && + 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) + saveRecord(seen) + _state.update { it.copy(record = seen) } + } + } + } + + /** + * 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 { + // 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()) { + // 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) } + 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 + } + } + } + } + + // endregion + + // region keys + + 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 { + val indexes = it.sparkExitNextFundingIndexes + val back = SparkExitMath.fundingIndexAfterForget(indexes[fundingIndexKey], index) ?: return@update it + it.copy(sparkExitNextFundingIndexes = indexes + (fundingIndexKey to back)) + } + + /** + * 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 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) + return chain?.let { recoverFunding(it) } ?: 0u + } + + /** + * 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 the scan found, or null when no restore was pending. + */ + 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() + // 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() + 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 }) { + 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) + // 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 = maxOf(indexes[fundingIndexKey] ?: 0, scanned.toInt()) + it.copy( + sparkExitNextFundingIndexes = indexes + (fundingIndexKey to next), + sparkExitFundingRecoveryPending = it.sparkExitFundingRecoveryPending - fundingIndexKey, + ) + } + 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 = fundingAddress(index) + 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) + +/** 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" + +/** 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, + val destination: String, + 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, + /** The fee of paying the funding from savings the user confirmed, which that payment never exceeds. */ + val savingsFeeSats: ULong? = null, +) + +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, + /** 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. */ + 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, + /** 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 + + /** Emergency exit opens progress rather than a new exit. */ + val showsResult: Boolean get() = record?.showsResult == true + + /** + * 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 and the leaves the exit left behind, whichever is more. + */ + val outsideExitSats: ULong? + get() { + val active = record?.takeIf { it.isActive } ?: return null + // 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 + val floor = (active.outsideSats ?: 0uL).safe() + active.leftBehindLeafSats.safe() + return maxOf(live, floor).takeIf { it > 0uL } + } + + /** + * 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 + // 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() } + val unpaid = (exit.phase as? SparkExitRecord.Phase.AwaitingFunding) + ?.takeIf { exit.fundingPaymentTxid == null } + ?.let { it.requiredSats.safe() - maxOf(exit.fundedSats, fundingSeenSats).safe() } + ?: 0uL + // 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/main/java/to/bitkit/repositories/SparkExitSweep.kt b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt new file mode 100644 index 0000000000..4da6b5382b --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitSweep.kt @@ -0,0 +1,284 @@ +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) + + 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. Never above [MAX_REFUSED_FEE_RATE], so the record can save it. + */ + 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() + 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 MAX_REFUSED_FEE_RATE + val scaled = (product.safe() + (paid - 1uL).safe()) / paid + 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)) + 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) + 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..7afb717d83 --- /dev/null +++ b/app/src/main/java/to/bitkit/repositories/SparkExitWorker.kt @@ -0,0 +1,531 @@ +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.core.os.bundleOf +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 androidx.work.workDataOf +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.flow.first +import kotlinx.coroutines.launch +import org.lightningdevkit.ldknode.Network +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.notificationManagerCompat +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 +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.hours +import kotlin.time.Duration.Companion.milliseconds +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, + private val db: AppDb, +) { + 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" + 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" + 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. */ + val PERIOD = 15.minutes + } + + /** The exit of the wallet Bitkit runs, read before the wallet graph exists. */ + 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() + ?.toInt() + ?: 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 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) + schedulePeriodic() + return@launch + } + val record = loaded.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, + ) + } + + /** + * 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() { + 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) + 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()) + } + } + } + + fun cancelAll() { + 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) { + // 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)) + .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) { + 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) + } + + /** + * 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 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() + armDeadline(SparkExitMath.deadline(Duration.ZERO, Env.network)) + return + } + val record = loaded.getOrNull() + 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, + ) + // 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 + } + val deadlineAt = preferences.getLong(KEY_DEADLINE_AT, 0L).takeIf { it > clock.nowMs() } + notify(alert, deadlineAt, feeRateSatPerVbyte = feeLowRate) + enqueueCatchUp() + armDeadline(SparkExitMath.deadline(Duration.ZERO, Env.network)) + } + + private fun enqueueCatchUp() { + WorkManager.getInstance(context).enqueueUniqueWork( + CATCH_UP_WORK, + ExistingWorkPolicy.KEEP, + OneTimeWorkRequestBuilder().setConstraints(constraints).build(), + ) + } + + /** 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, + feeRateSatPerVbyte: ULong? = null, + ) { + // 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)) + .replace("{time}", time.orEmpty()) + .replace("{amount}", amount.orEmpty()) + .replace("{rate}", feeRateSatPerVbyte?.toString().orEmpty()) + 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 { + 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. [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 } + +/** 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 { + /** + * 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. A leaf + * in [reportedLost] was already reported by an earlier exit. + */ + 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.any { it.leafId !in known } }, + SparkExitAlert.Failed.takeIf { + phase is SparkExitRecord.Phase.Failed && !record.isEveryLeafLost && + previous.phase !is SparkExitRecord.Phase.Failed + }, + ) + } + + /** 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 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 + + /** 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 && + 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 + + /** + * 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 && !record.isDrivingWhileFunding -> + SparkExitAlert.Funding + !record.isSendingSteps -> 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. + 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.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 + SparkExitAlert.Behind if hasDeadline -> R.string.lightning__spark_exit__notification_behind + 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, + @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 288cc90a65..9eadf920c6 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 @@ -108,6 +109,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 + /** How long a send's settlement waits for the send screen to track it as pending before it reports. */ private val PENDING_TRACK_WAIT = 10.seconds @@ -141,6 +148,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 + /** * When a withdrawal moved the whole balance, in epoch seconds, so a read of 0 is real until a sync after it reads * a balance again. A refresh that read its balance before the withdrawal can't clear it. @@ -192,6 +203,11 @@ class SparkRepo @Inject constructor( var hasMergedRemoteExitState = false private set + /** 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() @@ -221,8 +237,19 @@ class SparkRepo @Inject constructor( */ val exitStateGeneration: StateFlow = _exitStateGeneration.asStateFlow() + /** 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 // A retry reads as connecting until it fails again. _state.update { it.copy(hasStartFailed = false) } runSuspendCatching { @@ -230,7 +257,9 @@ class SparkRepo @Inject constructor( scope.launch { sparkService.events.collect { onSdkEvent(it) } } } restoreUncertainSends() - val connected = sparkService.connect(walletIndex) + val isExiting = exitStore(walletIndex).isActive() + _state.update { it.copy(isExiting = isExiting) } + val connected = sparkService.connect(walletIndex, isExiting) importRestoredExitState(walletIndex) // The SDK starts syncing inside build(), before the listener exists, so its first Synced can be missed. A // sync that never reached Spark still returns, so only one that did may drop an unlisted withdrawal. @@ -255,8 +284,8 @@ class SparkRepo @Inject constructor( fun setWiping(isWiping: Boolean) = run { sparkService.isWiping = isWiping } /** - * Disconnects Spark and deletes its storage and in-memory state. Spark stays connected for the life of the - * process otherwise, so a node stopped in background keeps Lightning available through it. + * Disconnects Spark and deletes its storage, its emergency exit records and its in-memory state. Spark stays + * connected for the life of the process otherwise, so a node stopped in background keeps Lightning available. */ suspend fun wipe(walletIndex: Int): Result = withContext(bgDispatcher) { claimJobs.values.forEach { it.cancel() } @@ -265,6 +294,7 @@ class SparkRepo @Inject constructor( preparedWithdrawal = null withdrawalTxids.clear() withdrawalFailedAtSecs = null + keptBeforeExit = null withdrewAllAtSecs = null broadcastDeposits.clear() sendsRecordedWithoutFee.clear() @@ -275,10 +305,150 @@ class SparkRepo @Inject constructor( hasMergedRemoteExitState = false _depositClaims.update { emptyMap() } _state.update { SparkState(isSupported = sparkService.isSupported) } - runSuspendCatching { sparkService.wipeStorage(walletIndex) } + val storage = runSuspendCatching { sparkService.wipeStorage(walletIndex) } + val exitRecords = runSuspendCatching { + exitStore(walletIndex).deleteWithCopies() + SparkExitLostLeafStore(File(Env.sparkExitLostLeavesPath(walletIndex))).delete() + } + _walletWiped.emit(walletIndex) + storage.mapCatching { exitRecords.getOrThrow() } } - fun canReceive(): Boolean = _state.value.isReady + /** + * 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, 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 { + onOptimizationCutShort() + sparkService.disconnect() + sparkService.connect(walletIndex, isExiting) + refresh() + }.onFailure { + Logger.error("Failed to reconnect Spark with exit '$isExiting'", it, context = TAG) + } + } + + /** + * 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. + */ + fun holdForExit() { + keptBeforeExit = _state.value.keptBalanceSats + _state.update { it.copy(isExiting = true, keptBalanceSats = null) } + } + + /** + * 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 = + 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) + } + } + + /** + * 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") + } + } + + 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 -> { + 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() + } + + 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.canSend(amountSats) @@ -337,6 +507,7 @@ class SparkRepo @Inject constructor( runSuspendCatching { ensurePaymentDeadline(paymentDeadlineAt) if (!sparkService.isConnected) throw SparkError.SendRefused("Spark is not connected") + 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) @@ -376,15 +547,21 @@ class SparkRepo @Inject constructor( val sent = try { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) - // Kept until the call returns, so a send cut off by process death or cancellation stays held. - cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) - // The checks above and both writes suspend, so the deadline is checked last, before the send. - runCatching { ensurePaymentDeadline(paymentDeadlineAt) }.onFailure { - cacheStore.removeSparkUncertainSend(paymentHash) - cacheStore.removeSparkSendHash(paymentHash) - throw it + spending { + // Kept until the call returns, so a send cut off by process death or cancellation stays held. + cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds) + // The checks above and both writes suspend, so the deadline and an exit that started meanwhile + // are checked last, before the send. + runCatching { + ensurePaymentDeadline(paymentDeadlineAt) + ensureNotExiting() + }.onFailure { + cacheStore.removeSparkUncertainSend(paymentHash) + cacheStore.removeSparkSendHash(paymentHash) + throw it + } + runSuspendCatching { sparkService.send(prepared) } } - runSuspendCatching { sparkService.send(prepared) } } finally { sendsInFlight.remove(paymentHash.lowercase()) } @@ -629,9 +806,14 @@ class SparkRepo @Inject constructor( */ suspend fun withdrawAll(address: String, confirmedFeeSats: ULong): Result = withContext(bgDispatcher) { runSuspendCatching { + 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 @@ -782,6 +964,7 @@ class SparkRepo @Inject constructor( ): Result = withContext(bgDispatcher) { runSuspendCatching { + ensureNotExiting() // Claimed before anything suspends, so a second withdrawal started while this one prepares is refused // instead of overwriting its journal. if (!isClaimingWithdrawal.compareAndSet(false, true)) throw SparkError.WithdrawalPending() @@ -813,12 +996,19 @@ class SparkRepo @Inject constructor( ) journal = opened cacheStore.update { it.copy(pendingSparkWithdrawal = opened) } - // Saving the journal suspends, so the deadline is checked last, before the send. - runCatching { ensurePaymentDeadline(paymentDeadlineAt) }.onFailure { - clearJournal(opened) - throw it + spending { + // Saving the journal suspends, so the deadline and an exit that started meanwhile are checked + // last, before the send. + runCatching { + ensurePaymentDeadline(paymentDeadlineAt) + ensureNotExiting() + }.onFailure { + clearJournal(opened) + throw it + } + runSuspendCatching { sparkService.send(prepared, opened.paymentId) } + .also { sendReturned = true } } - runSuspendCatching { sparkService.send(prepared, opened.paymentId) }.also { sendReturned = true } } finally { if (!sendReturned) endWithdrawalSend() isClaimingWithdrawal.set(false) @@ -895,12 +1085,17 @@ class SparkRepo @Inject constructor( /** * The exit data backup, or null until Spark has connected and synced once, since an export taken before its - * first sync can miss what the wallet holds. + * first sync can miss what the wallet holds. 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 || !_state.value.hasSynced) 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()) } } @@ -999,12 +1194,14 @@ 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 && withdrewAllAtSecs == null && kept > 0uL + info.balanceSats == 0uL && isStale && withdrewAllAtSecs == null && kept > 0uL && !it.isExiting }, pendingDepositSats = pending.sumOf { deposit -> deposit.amountSats }, deposits = (pending + claimed).toImmutableList(), withdrawals = transfers, + recoverableFundsSats = info.recoverableFundsSats, ).withBroadcastDeposits() } markClaimedDeposits(claimed) @@ -1519,6 +1716,7 @@ class SparkRepo @Inject constructor( is SdkEvent.NewDeposits -> refresh() is SdkEvent.UnilateralExitStateChanged -> _exitStateGeneration.update { it + 1 } is SdkEvent.ClaimedDeposits -> refresh() + is SdkEvent.AutoOptimization -> onOptimization(event.optimizationEvent) else -> Unit } }.onFailure { @@ -1784,15 +1982,27 @@ data class SparkState( val pendingDepositSats: ULong = 0uL, 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 /** Whether Spark is ready and can send [amountSats] once its service fee is paid. */ fun canSend(amountSats: ULong): Boolean = isReady && sendableSats >= amountSats /** The balance shown in Spending and on the Spark connection, which [keptBalanceSats] stands in for. */ val shownBalanceSats: ULong get() = keptBalanceSats ?: balanceSats + + /** The [spendingSats] shown in Spending, which [keptBalanceSats] stands in for. */ + val shownSpendingSats: ULong get() = if (isExiting) 0uL else shownBalanceSats } 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 71d527ef98..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) @@ -135,11 +137,18 @@ 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. - sparkRepo.state.map { Triple(it.balanceSats, it.shownBalanceSats, it.pendingDepositSats) } - .distinctUntilChanged().collect { - if (walletExists()) syncBalances() - } + // 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. + 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/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index e82d8e302e..f6aacd68a3 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -2,9 +2,12 @@ package to.bitkit.services import breez_sdk_spark.BreezSdk import breez_sdk_spark.ChainApiType +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.CpfpSigner import breez_sdk_spark.DepositInfo import breez_sdk_spark.EventListener import breez_sdk_spark.FeePolicy @@ -22,10 +25,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.SdkBuilder import breez_sdk_spark.SdkEvent import breez_sdk_spark.Seed @@ -44,6 +51,7 @@ import to.bitkit.data.keychain.Keychain import to.bitkit.env.Env import to.bitkit.ext.runSuspendCatching 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 @@ -71,7 +79,7 @@ class SparkService @Inject constructor( * Bitkit's settings over the SDK's [defaults]. Breez's real-time data sync server, its Lightning address * (LNURL) server and its default external input parsers 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 @@ -83,6 +91,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. */ @@ -147,14 +156,18 @@ class SparkService @Inject constructor( */ val prefersSpark: Boolean get() = Env.network == Network.REGTEST - /** Connects the SDK and returns true, or false when it was already connected. */ - suspend fun connect(walletIndex: Int): Boolean = 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. + * Returns true, or false when it was already connected. + */ + suspend fun connect(walletIndex: Int, isExiting: Boolean = false): Boolean = mutex.withLock { if (sdk != null) return@withLock false if (isWiping) throw SparkError.WipeInProgress() 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 chainServiceUrl = Env.sparkChainServiceUrl(Env.network) val connected = SdkBuilder(config, Seed.Mnemonic(mnemonic, passphrase)).use { builder -> @@ -170,7 +183,8 @@ class SparkService @Inject constructor( }, ) sdk = connected - Logger.info("Connected Spark wallet on '$network' with chain '${chainServiceUrl ?: "default"}'", context = TAG) + val chain = chainServiceUrl ?: "default" + Logger.info("Connected Spark wallet on '$network' with chain '$chain' and exit '$isExiting'", context = TAG) true } @@ -288,6 +302,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() @@ -300,6 +317,22 @@ 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)) + + override suspend fun exportExitState(): String = sdk.exportUnilateralExitState().exitState + + override suspend fun importExitState(exitState: String): ImportUnilateralExitStateResponse = + sdk.importUnilateralExitState(ImportUnilateralExitStateRequest(exitState)) +} + 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 d8d91ae6f2..e3899f6cb4 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 @@ -208,6 +209,14 @@ import to.bitkit.ui.settings.lightning.LightningConnectionsScreen import to.bitkit.ui.settings.lightning.LightningConnectionsViewModel import to.bitkit.ui.settings.lightning.MoveToSparkScreen 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 +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 import to.bitkit.ui.settings.quickPay.QuickPaySettingsScreen @@ -334,10 +343,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() @@ -388,6 +399,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) { @@ -1125,7 +1146,7 @@ private fun RootNavHost( val balances = LocalBalances.current val hasSeenSpendingIntro by settingsViewModel.hasSeenSpendingIntro.collectAsStateWithLifecycle() FundingScreen( - canFundWithSpark = sparkState.isReady, + canFundWithSpark = sparkState.isUsable, canFundOnChain = Env.sparkSharesNodeChain, onTransfer = { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) }, onFund = { @@ -1214,7 +1235,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() }, ) @@ -1373,7 +1394,7 @@ private fun NavGraphBuilder.home( }, onEmptyActivityRowClick = { appViewModel.showSheet(Sheet.Receive()) }, onTransferToSpendingClick = { - if (sparkState.isReady && Env.sparkSharesNodeChain) { + if (sparkState.isUsable && Env.sparkSharesNodeChain) { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) } else { appViewModel.showSheet(Sheet.TransferUnavailable) @@ -1392,7 +1413,7 @@ private fun NavGraphBuilder.home( SpendingWalletScreen( channels = lightningState.channels, - hasSparkBalance = sparkState.shownBalanceSats > 0uL, + hasSparkBalance = sparkState.shownSpendingSats > 0uL, canMoveToSpark = MoveToSparkMath.canMove(lightningState.channels, sparkState), onMoveToSparkClick = { navController.navigateTo(Routes.MoveToSpark) }, lightningActivities = lightningActivities ?: persistentListOf(), @@ -1411,7 +1432,7 @@ private fun NavGraphBuilder.home( } }, onTransferFromSavingsClick = { - if (sparkState.isReady && Env.sparkSharesNodeChain) { + if (sparkState.isUsable && Env.sparkSharesNodeChain) { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro) } else { appViewModel.showSheet(Sheet.TransferUnavailable) @@ -1432,7 +1453,7 @@ private fun NavGraphBuilder.home( ) }, onTransferToSpendingClick = { walletId -> - if (sparkState.isReady && Env.sparkSharesNodeChain) { + if (sparkState.isUsable && Env.sparkSharesNodeChain) { navController.navigateToTransferSpendingStart(hasSeenSpendingIntro, walletId) } else { appViewModel.showSheet(Sheet.TransferUnavailable) @@ -2052,8 +2073,12 @@ private fun NavGraphBuilder.lightningConnections( navController.navigateToTransferSavingsIntro() } }, + onEmergencyExit = { showsResult -> + navController.navigateTo(if (showsResult) Routes.SparkExitProgress else Routes.SparkExitIntro) + }, ) } + sparkExit(navController) composableWithDefaultTransitions { MoveToSparkScreen( viewModel = hiltViewModel(), @@ -2076,6 +2101,69 @@ 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) + } + // 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) } + val openProgress = { + navController.popBackStack(inclusive = false) + navController.navigateTo(Routes.SparkExitProgress) + } + composableWithDefaultTransitions { + SparkExitIntroScreen( + onBack = { navController.popBackStack() }, + onContinue = { navController.navigateTo(Routes.SparkExitQuote) }, + ) + } + composableWithDefaultTransitions { + val viewModel = exitViewModel(it) + SparkExitStartedEffect(viewModel, openProgress) + SparkExitQuoteScreen( + viewModel = viewModel, + onBack = { navController.popBackStack() }, + onContinue = { needsFunding -> + navController.navigateTo(if (needsFunding) Routes.SparkExitFunding else Routes.SparkExitConfirm) + }, + ) + } + composableWithDefaultTransitions { + val viewModel = exitViewModel(it) + SparkExitStartedEffect(viewModel, openProgress) + SparkExitFundingScreen( + viewModel = viewModel, + onBack = { navController.popBackStack() }, + onContinue = { navController.navigateTo(Routes.SparkExitConfirm) }, + ) + } + composableWithDefaultTransitions { + SparkExitConfirmScreen( + viewModel = exitViewModel(it), + onBack = { navController.popBackStack() }, + onStart = openProgress, + ) + } + composableWithDefaultTransitions { + SparkExitProgressScreen( + viewModel = exitViewModel(it), + onBack = { navController.popBackStack() }, + onDone = { leaveExit() }, + onPayHigherFee = { navController.navigateTo(Routes.SparkExitFeeBump) }, + ) + } + composableWithDefaultTransitions { + SparkExitFeeBumpScreen( + viewModel = exitViewModel(it), + onBack = { navController.popBackStack() }, + onDone = { navController.popBackStack() }, + ) + } +} + private fun NavGraphBuilder.activityItem( activityListViewModel: ActivityListViewModel, navController: NavHostController, @@ -2543,6 +2631,24 @@ 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 SparkExitFeeBump : Routes.InternalOnly + @Serializable data object MoveToSpark : Routes.InternalOnly diff --git a/app/src/main/java/to/bitkit/ui/MainActivity.kt b/app/src/main/java/to/bitkit/ui/MainActivity.kt index df8e69d790..5fe9fcb7bd 100644 --- a/app/src/main/java/to/bitkit/ui/MainActivity.kt +++ b/app/src/main/java/to/bitkit/ui/MainActivity.kt @@ -299,6 +299,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/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 c5048860ba..f9745ad615 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 @@ -90,7 +90,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 8989f45bb2..18d3fb6708 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/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/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/screens/wallets/send/SendFeeRateScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendFeeRateScreen.kt index 6f7e31fd7d..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,14 +148,20 @@ private fun Content( } } +/** + * 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 -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, + showsSymbols: Boolean = false, unit: PrimaryDisplay = LocalCurrencies.current.primaryDisplay, ) { val color = if (isDisabled) Colors.Gray3 else MaterialTheme.colorScheme.primary @@ -186,15 +192,20 @@ 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) { 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/appStatus/AppStatusScreen.kt b/app/src/main/java/to/bitkit/ui/settings/appStatus/AppStatusScreen.kt index f958f3ec65..afa20d7177 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 @@ -67,6 +67,7 @@ fun AppStatusScreen( onChannelsClick = { navController.navigateTo(Routes.LightningConnections) }, onSparkClick = { navController.navigateTo(Routes.SparkDetail) }, onBackupClick = { navController.navigateTo(Routes.BackupSettings) }, + onExitClick = { navController.navigateTo(Routes.SparkExitProgress) }, ) } @@ -80,6 +81,7 @@ private fun Content( onChannelsClick: () -> Unit = {}, onSparkClick: () -> Unit = {}, onBackupClick: () -> Unit = {}, + onExitClick: () -> Unit = {}, ) { ScreenColumn { AppTopBar( @@ -183,6 +185,22 @@ private fun Content( ) } + 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", @@ -294,6 +312,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..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 @@ -20,6 +20,9 @@ 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 @HiltViewModel @@ -27,6 +30,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 +46,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 +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(exitState.fundingState), ) }.collect { newState -> _uiState.update { newState } @@ -80,4 +86,19 @@ 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 } + +/** 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 && + if (funding == null) !isPaymentPending else funding is SparkExitFundingState.Ask + return if (isAskingFunding) ExitStep.FUNDING else ExitStep.RUNNING +} 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 2771235bd9..2cf199ddda 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 @@ -36,9 +36,13 @@ import to.bitkit.models.safe import to.bitkit.repositories.ActivityRepo import to.bitkit.repositories.BlocktankRepo import to.bitkit.repositories.LightningRepo +import to.bitkit.repositories.LightningState import to.bitkit.repositories.LogsRepo import to.bitkit.repositories.MoveToSparkMath 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 import to.bitkit.repositories.SparkState import to.bitkit.repositories.SparkWithdrawal @@ -56,6 +60,7 @@ class LightningConnectionsViewModel @Inject constructor( private val logsRepo: LogsRepo, private val activityRepo: ActivityRepo, private val sparkRepo: SparkRepo, + private val sparkExitRepo: SparkExitRepo, ) : ViewModel() { companion object { @@ -102,9 +107,11 @@ class LightningConnectionsViewModel @Inject constructor( lightningRepo.lightningState, lightningRepo.lastKnownChannels, sparkRepo.state, - ) { lightningState, channels, sparkState -> - Triple(lightningState, channels, sparkState) - }.collect { (lightningState, channels, sparkState) -> + sparkExitRepo.state, + ) { lightningState, channels, sparkState, exitState -> + ConnectionsSnapshot(lightningState, channels, sparkState, exitState) + }.collect { snapshot -> + val (lightningState, channels, sparkState) = snapshot val isNodeRunning = lightningState.nodeLifecycleState.isRunning() val connectionText = context.getString(R.string.lightning__connection) @@ -117,12 +124,16 @@ class LightningConnectionsViewModel @Inject constructor( pendingConnections = channels.filterPending() .map { it.mapToUiModel(channels, connectionText) } .reversed().toImmutableList(), - localBalance = calculateLocalBalance(channels).safe() + sparkState.shownBalanceSats.safe(), + localBalance = calculateLocalBalance(channels).safe() + sparkState.shownSpendingSats.safe(), remoteBalance = channels.calculateRemoteBalance(), // The cached channels outlive a stopped node; the move reads the live ones. canMoveToSpark = MoveToSparkMath.canMove(lightningState.channels, sparkState), - spark = sparkState.toUi(lightningRepo), - isSparkReceiving = sparkState.isReady, + spark = sparkState.toUi( + lightningRepo, + snapshot.exitState.showsResult, + snapshot.exitState.earlierAddresses, + ), + isSparkReceiving = sparkState.isUsable, ) } } @@ -241,10 +252,23 @@ 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, 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, + /** 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 + * 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 } } @@ -255,19 +279,41 @@ 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, + earlierAddresses: List = emptyList(), +): SparkUi? { + val showsExit = isExiting || showsExitResult + // 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. - if (shownBalanceSats == 0uL && deposits.isEmpty() && Env.network != Network.REGTEST) return null + val hasExit = showsExit || recoverableFundsSats > 0uL + if (shownBalanceSats == 0uL && deposits.isEmpty() && !hasExit && !hasEarlier && Env.network != Network.REGTEST) { + return null + } return SparkUi( balanceSats = shownBalanceSats, deposits = deposits.map { SparkDepositUi(it, if (it.isClaimed) null else lightningRepo.onchainConfirmations(it.txid)) }.toImmutableList(), withdrawals = withdrawals, + recoverableFundsSats = recoverableFundsSats, + isExiting = isExiting, + showsExitResult = showsExit, + earlierAddresses = earlierAddresses.toImmutableList(), ) } +private data class ConnectionsSnapshot( + val lightningState: LightningState, + 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..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 @@ -35,6 +36,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 +49,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 +62,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 +75,7 @@ private fun Content( onOpenTx: (String) -> Unit = {}, onCopyText: (String) -> Unit = {}, onTransferToSavings: () -> Unit = {}, + onEmergencyExit: () -> Unit = {}, ) { val spark = uiState.spark ?: SparkUi(balanceSats = 0uL) ScreenColumn { @@ -150,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 -> @@ -178,17 +192,52 @@ 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) } } } +@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 ac14080045..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 @@ -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,23 @@ 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 } + .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) { @@ -48,7 +60,11 @@ class SparkDetailViewModel @Inject constructor( viewModelScope.launch { _uiState.update { it.copy(isRefreshing = true) } sparkRepo.refreshState() - _uiState.update { it.copy(spark = sparkRepo.state.value.toUi(lightningRepo)) } + 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/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..5cd66951e6 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitComponents.kt @@ -0,0 +1,265 @@ +package to.bitkit.ui.settings.lightning + +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.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.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 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 +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.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 + +/** + * 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 = + 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. + */ +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)}" + +/** 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 { + 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) + } + } +} + +/** 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) }) +} + +/** 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), + isCovered: Boolean = requiredSats > 0uL && seenSats >= requiredSats, +) { + val app = appViewModel + val copied = stringResource(R.string.common__copied) + Column( + verticalArrangement = Arrangement.spacedBy(16.dp), + horizontalAlignment = Alignment.CenterHorizontally, + modifier = modifier.fillMaxWidth() + ) { + // 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}", sparkExitSendAmountAccent(requiredSats)).withAccentBoldBright(), + color = Colors.White64, + modifier = Modifier.fillMaxWidth() + ) + CaptionB( + text = address, + maxLines = 2, + overflow = TextOverflow.MiddleEllipsis, + modifier = Modifier + .fillMaxWidth() + .clickableAlpha(onClick = copyToClipboard(address) { app.toastCopied(copied, it) }) + .testTag("SparkExitFundingAddress") + ) + partial?.let { + BodyS( + text = stringResource(R.string.lightning__spark_exit__fund_partial) + .replace("{received}", sparkExitSendAmountAccent(it.receivedSats)) + .replace("{required}", sparkExitSendAmountAccent(it.requiredSats)) + .replace("{missing}", sparkExitSendAmountAccent(it.missingSats)).withAccentBoldBright(), + color = Colors.White64, + modifier = Modifier + .fillMaxWidth() + .testTag("SparkExitFundingPartial") + ) + } + if (isCovered) { + Caption( + text = stringResource(R.string.lightning__spark_exit__fund_seen), + color = Colors.Green, + modifier = Modifier.fillMaxWidth() + ) + } + } +} + +/** 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, testTag: String) { + val app = appViewModel + val copied = stringResource(R.string.common__copied) + Column( + modifier = Modifier + .fillMaxWidth() + .testTag(testTag) + ) { + 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) + } + ) + ) + } +} + +/** 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 + // 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) + 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() +} + +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/SparkExitConfirmScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt new file mode 100644 index 0000000000..b6c473fa28 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitConfirmScreen.kt @@ -0,0 +1,101 @@ +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.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.DrawerNavIcon +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() + SparkExitStartedEffect(viewModel, 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, + actions = { DrawerNavIcon() }, + ) + 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()) + BodyM( + text = stringResource(R.string.lightning__spark_exit__confirm_text).withAccentBoldBright(), + color = Colors.White64, + ) + 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)) { + 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/SparkExitFeeBumpScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt new file mode 100644 index 0000000000..3fdd6265d1 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFeeBumpScreen.kt @@ -0,0 +1,190 @@ +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.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 +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, + actions = { DrawerNavIcon() }, + ) + 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()) + 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.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, + 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), + showsSymbols = true, + 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 (bump.isSavingsShort) { + Caption( + text = stringResource(R.string.lightning__spark_exit__fund_insufficient), + 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 if (!bump.isLeavingLeaves) { + 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/SparkExitFundingScreen.kt b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt new file mode 100644 index 0000000000..3a04d717b2 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitFundingScreen.kt @@ -0,0 +1,154 @@ +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.BodyS +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 +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() } + // 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, + 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, + actions = { DrawerNavIcon() }, + ) + 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()) + BodyM( + text = stringResource(R.string.lightning__spark_exit__funding_text) + .replace("{amount}", sparkExitSendAmountText(fundingSats)) + .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, + partial = uiState.prestartFunding.partial, + isCovered = uiState.canContinueFunding, + ) + } + 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) { + Caption( + text = stringResource(R.string.lightning__spark_exit__fund_insufficient), + 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..c3e000fa8d --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitIntroScreen.kt @@ -0,0 +1,112 @@ +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.DrawerNavIcon +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, + actions = { DrawerNavIcon() }, + ) + 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() + ) + 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..d967538fb1 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitProgressScreen.kt @@ -0,0 +1,473 @@ +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.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 +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.CANCELLED_REASON +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.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 +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, + onPayHigherFee: () -> 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, + onPayHigherFee = onPayHigherFee, + onRetrySavingsPayment = viewModel::retrySavingsPayment, + ) +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +private fun Content( + uiState: SparkExitUiState, + onBack: () -> Unit = {}, + onRefresh: () -> Unit = {}, + onCancel: () -> Unit = {}, + onDone: () -> Unit = {}, + onNotificationSettings: () -> Unit = {}, + onPayHigherFee: () -> Unit = {}, + onRetrySavingsPayment: () -> Unit = {}, +) { + val record = uiState.record + ScreenColumn { + AppTopBar( + titleText = stringResource(R.string.lightning__spark_exit__nav_title), + onBackClick = onBack, + actions = { DrawerNavIcon() }, + ) + 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, uiState.progressFunding).withAccent()) + 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, onPayHigherFee) } + 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), + onClick = onRetrySavingsPayment, + isLoading = uiState.isRetryingSavingsPayment, + testTag = "SparkExitRetrySavings", + ) + VerticalSpacer(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) { + var isConfirming by remember { mutableStateOf(false) } + SecondaryButton( + text = stringResource(R.string.lightning__spark_exit__cancel), + 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), + dismissText = stringResource(R.string.common__cancel), + confirmTextColor = Colors.Red, + onConfirm = { + isConfirming = false + onCancel() + }, + onDismiss = { isConfirming = false }, + confirmTestTag = "SparkExitCancelConfirm", + ) + } + } + 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, onPayHigherFee: () -> Unit) { + SparkExitSteps(record = record, tipHeight = uiState.tipHeight) + uiState.sweepTxid?.let { + // 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, + testTag = "SparkExitSweepTxid", + ) + } + 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) { + 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, + testTag = "SparkExitFundingPaid", + ) + is SparkExitFundingState.Seen -> SparkExitTxNote( + text = stringResource(R.string.lightning__spark_exit__fund_pending), + txid = funding.txid, + testTag = "SparkExitFundingSeen", + ) + } + } + 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.isWaitingForOperators) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__waiting_operators) + .replace("{amount}", sparkExitAmountAccent(record.failedLeafSats)).withAccentBoldBright(), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitWaitingOperators") + ) + } + 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__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") + ) + } + 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( + text = stringResource(R.string.lightning__spark_exit__outside_exit) + .replace("{amount}", sparkExitAmountAccent(it)).withAccentBoldBright(), + color = Colors.White64, + ) + } + if (record.lostSats > 0uL) { + VerticalSpacer(16.dp) + BodyS( + text = stringResource(R.string.lightning__spark_exit__lost_leaves) + .replace("{amount}", sparkExitAmountAccent(record.lostSats)).withAccentBoldRed(), + 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}", sparkExitAmountAccent(record.leftBehindLeafSats)).withAccentBoldBright(), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitLeftBehindLeaves") + ) + } + 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, 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}", sparkExitAmountAccent(it.valueSats)), + txid = it.txid, + testTag = "SparkExitLeftoverSweptEarlier", + ) + } + if (record.leftover.isEmpty()) return + val total = record.leftover.fold(0uL) { sum, leftover -> sum + leftover.valueSats } + val sweep = record.leftoverSweep + VerticalSpacer(16.dp) + when { + record.isLeftoverWaitingForFees -> BodyS( + text = stringResource(R.string.lightning__spark_exit__leftover_waiting) + .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}", sparkExitAmountAccent(total)) + .replace("{address}", address) + .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) + .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) + .replace("{amount}", sparkExitAmountAccent(total)) + .replace("{address}", address) + .replace("{path}", path).withAccentBoldBright(), + color = Colors.White64, + modifier = Modifier.testTag("SparkExitLeftoverRejected") + ) + else -> BodyS( + text = stringResource(R.string.lightning__spark_exit__leftover) + .replace("{amount}", sparkExitAmountAccent(total)) + .replace("{address}", address).withAccentBoldBright(), + color = Colors.White64, + ) + } +} + +@Composable +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 }, + 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) + } +} + +@Composable +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 -> + R.string.lightning__spark_exit__needs_funding_title + else -> R.string.lightning__spark_exit__progress_title + }, +) + +@Composable +private fun progressText( + record: SparkExitRecord?, + receivedSats: ULong?, + progressFunding: SparkExitFundingState?, + staysOnSparkSats: ULong?, +): String = when (record?.phase) { + 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}", 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}", sparkExitAmountAccent(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), + 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. + is SparkExitFundingState.Ask -> stringResource(R.string.lightning__spark_exit__needs_funding_text) + .replace("{amount}", sparkExitSendAmountText(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..38ceaa8bfe --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitQuoteScreen.kt @@ -0,0 +1,128 @@ +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.DrawerNavIcon +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 +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, + actions = { DrawerNavIcon() }, + ) + 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 - SparkExitDisplayExtra) + 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), + color = Colors.White64, + ) + uiState.isQuoting -> BodyM( + text = stringResource(R.string.lightning__spark_exit__quote_loading), + color = Colors.White64, + ) + } + 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}", sparkExitAmountAccent(sats)).withAccentBoldBright(), + 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..e4468cdd03 --- /dev/null +++ b/app/src/main/java/to/bitkit/ui/settings/lightning/SparkExitViewModel.kt @@ -0,0 +1,461 @@ +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 +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.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.models.safe +import to.bitkit.repositories.OnchainSendChangedError +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 +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 +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 +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( + @ApplicationContext private val context: Context, + 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. */ + 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() + + private val _effects = MutableSharedFlow(extraBufferCapacity = 1) + val effects = _effects.asSharedFlow() + + 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() + + /** 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. + 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( + // 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, + fundingSeenCount = exit.fundingSeenCount, + fundingFeeRate = exit.pending?.feeRate, + fundingState = exit.fundingState, + fundingAddress = exit.fundingAddress, + canCancel = sparkExitRepo.canCancel, + isSavingsPaymentRefused = exit.isSavingsPaymentRefused, + 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) + }, + ) + } + } + + /** 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. + 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(savingsFeeFloorSats) + .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 { + savingsFeeFloorSats = null + // 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. + 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) _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 { + _uiState.update { it.copy(feeBump = SparkExitFeeBumpUiState(isLoading = true)) } + val spendable = sparkExitRepo.spendableSavingsSats().getOrNull() + sparkExitRepo.feeBumpOptions() + .onSuccess { priced -> + val options = priced.map { it.withFeeFloor(feeBumpFeeFloors[it.rateSatPerVbyte]) } + 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)) } + } + .onFailure { error -> + val bump = if (error is SparkExitFeeBumpLeavesBehind) { + SparkExitFeeBumpUiState(isLeavingLeaves = true) + } else { + SparkExitFeeBumpUiState(hasError = true) + } + _uiState.update { it.copy(feeBump = bump) } + } + } + } + + 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 { + // Savings never pays more than the fee confirmed: the rates are priced again for another confirm. + 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), + ) + _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)) } + } + } + + /** 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) } + } + } + + /** 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()) } + } + + fun cancel() { + viewModelScope.launch { + sparkExitRepo.cancel() + // 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) + ) + } + } + } +} + +sealed interface SparkExitEffect { + data object Cancelled : SparkExitEffect + data object FeeBumped : 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, + /** 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, + 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, + 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. */ + 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, + /** What the network asks now, for the fee bump and its hint. */ + 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 = savingsFundingSats.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 + + /** 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. */ + 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? + 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 exit's fee rate, while a step the network accepted does not confirm for longer than that rate needs. */ + val lowFeeRate: ULong? + get() { + // 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. */ + val sweepTxid: String? + 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 + * funding address was read. + */ + val progressFunding: SparkExitFundingState? + get() { + val shortfall = record?.fundingShortfallSats ?: return null + return fundingState ?: SparkExitFundingState.Ask(maxOf(shortfall, SparkExitMath.FUNDING_DUST_SATS)) + } +} + +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, + /** 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, + /** 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 } + + /** Savings covers none of the rates offered. */ + val isSavingsShort: Boolean get() = options.isNotEmpty() && options.none(::canPay) + + /** Savings covers [option]'s cost on a chain Spark reads, or there is nothing to pay. */ + fun canPay(option: SparkExitFeeBumpOption): Boolean = + option.totalSats == 0uL || (sharesNodeChain && (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/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 eab2df0941..b6ef2e6da2 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,10 @@ 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.shownBalanceSats + // During an exit, Spark's value outside it stays on Spark. + val sparkSats = sparkRepo.state.value.shownSpendingSats.safe() + + (sparkExitRepo.state.value.outsideExitSats ?: 0uL).safe() + val sparkExitSats = getSparkExitSats(activeTransfers) val afterLingeringCoopClose = afterClosingChannels.safe() - lingeringCoopCloseSats.safe() val totalLightningSats = afterLingeringCoopClose.safe() + sparkSats.safe() @@ -66,7 +71,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 +113,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 +124,21 @@ class DeriveBalanceStateUseCase @Inject constructor( return toSavingsAmount } + /** + * 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/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 1c93230e4b..03cc20685f 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -228,6 +228,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.SparkWithdrawalOutcome import to.bitkit.repositories.SparkWithdrawalSettlement import to.bitkit.repositories.TransferRepo @@ -347,6 +348,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 @@ -1490,6 +1492,28 @@ class AppViewModel @Inject constructor( private fun isAutomaticPaykitWorkPaused(): Boolean = isPaymentRequestPollingStopped.value || privatePaykitRepo.isProfileDeletionInProgress.value + 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 } + + /** + * 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 { + 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() + 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 e030640169..5744b8ff59 100644 --- a/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/TransferViewModel.kt @@ -453,7 +453,7 @@ class TransferViewModel @Inject constructor( private suspend fun runSparkWithdrawal() { sparkFeeJob?.join() - if (sparkRepo.state.value.balanceSats == 0uL) return + if (sparkRepo.state.value.spendingSats == 0uL) return val address = sparkWithdrawAddress() val confirmedFeeSats = confirmedSparkFeeSats if (address == null || confirmedFeeSats == null) { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 4ded8612f6..e4cd0e3bca 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -229,6 +229,99 @@ انتظر إيداعات تمت المطالبة بها إيداعات قيد التنفيذ + المبلغ المراد إخراجه + خروج طارئ + إلغاء الخروج + تعذّر التحقق من عنوان التمويل. حاول مرة أخرى. + يعود 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 + يدفع هذا الخروج <accent>{rate} sat/vB</accent>، أقل مما تطلبه الشبكة الآن. اختر معدلًا أعلى وسيرسل Bitkit الخطوات المنتظرة مرة أخرى. يدفع الفرق من المدخرات: المبلغ بجانب كل سرعة. + ادفع\n<accent>رسومًا أعلى</accent> + الشبكة أكثر ازدحامًا من معدل رسوم هذا الخروج البالغ {rate} sat/vB. ادفع رسومًا أعلى، أو انتظر حتى تنخفض الرسوم. + ارتفعت رسوم الشبكة فوق رسوم هذا الخروج. قد يتباطأ. + رسوم الشبكة + التمويل من محفظة أخرى + أرسل {amount} على الأقل إلى هذا العنوان. يبدأ الخروج بمجرد تأكيده. + مدخراتك لا تكفي لتمويل الرسوم. + دُفع من المدخرات، بانتظار التأكيد. + تم استلام {received} من {required}، أرسل {missing} إضافية. + تم رصد الدفعة، بانتظار التأكيد. + ادفع من المدخرات + تم رصد الدفعة. + يلزم تمويل الرسوم + يقسمه Bitkit إلى {count} أجزاء، جزء لكل خطوة، حتى لا تعطّل خطوة عالقة الخطوات الأخرى. + يدفع الخروج رسومه من دفعة منفصلة على السلسلة بقيمة <accent>{amount}</accent>. ما لا يُنفق منها يعود إلى المدخرات في النهاية. + موّل\n<accent>الرسوم</accent> + استخدم هذا فقط إذا توقّف 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} من تمويل الرسوم المتبقي إلى المدخرات. + سيصل {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 قراءة التقدم المحفوظ لهذا الخروج، لذا يعيد بناءه من السلسلة. + ستستلم نحو + رسوم الدفع من المدخرات + لم يكتمل دفعك من المدخرات. ادفع مرة أخرى، أو موّل من محفظة أخرى. + الإجمالي من المدخرات + تأكيد تمويل الرسوم + نشر معاملات الخروج + الإرسال إلى المدخرات + انتظار القفل الزمني + اسحب للخروج + الرسوم أعلى مما ستستلمه. + لا يمكن قراءة جزء من هذا الخروج على السلسلة الآن. يحاول Bitkit مجددًا لمدة تصل إلى أسبوع. + ينتظر {amount} الذي نقله مشغّلو Spark على السلسلة أن يفرجوا عنه. يطلب Bitkit مجددًا لمدة تصل إلى أسبوع. المزوّد Spark عبر Breez بلا حد @@ -1731,6 +1824,9 @@ صغير عريض جارٍ تحديث الرصيد… + يلزم تمويل الرسوم + قيد التنفيذ + الخروج الطارئ يستخدم Spark غير متصل جارٍ الاتصال... 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 9abde4e2d7..692bc2f515 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -236,6 +236,99 @@ Esperar Depósitos reclamados Depósitos en curso + 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 + 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> + Ú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. + {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 + 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 + Enviando a ahorros + Esperando el bloqueo temporal + 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 @@ -1728,6 +1821,9 @@ Pequeño Ancho Actualizando saldo… + Financiación de comisiones necesaria + En curso + Salida de emergencia Usando Spark Sin conexión Conectando... diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 9b8488f56e..012af26c5e 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -233,6 +233,99 @@ Espera Dipòsits reclamats Dipòsits en curs + 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 + 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> + 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. + {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 + 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 + Enviant als estalvis + Esperant el timelock + 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 @@ -1728,6 +1821,9 @@ Petit Ample S’està actualitzant el saldo… + Cal finançament de comissions + En curs + Sortida d\'emergència Utilitzant Spark Fora de línia Connectant... diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index ba81dc1aa0..32e9c3b9be 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -236,6 +236,99 @@ Počkat Připsané vklady Probíhající vklady + Čá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 + 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> + 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. + {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 + 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 + Odesílání do úspor + Čekání na časový zámek + 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 @@ -1729,6 +1822,9 @@ Malý Široký Aktualizace zůstatku… + Je potřeba financovat poplatky + Probíhá + Nouzový odchod Používá Spark Offline Připojování... diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 7892e96b5d..3c67d6f9ec 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -112,6 +112,99 @@ Warten Eingelöste Einzahlungen Laufende Einzahlungen + 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 + 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> + 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. + {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 + 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 + Wird an das Sparkonto gesendet + Warten auf die Zeitsperre + 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 @@ -1727,6 +1820,9 @@ Klein Breit Kontostand wird aktualisiert… + Gebührenfinanzierung nötig + Läuft + Notausstieg Nutzt Spark Offline Verbinden... diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 365a13c557..e63ed7a2bd 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -229,6 +229,99 @@ Αναμονή Εξαργυρωμένες καταθέσεις Καταθέσεις σε εξέλιξη + Ποσό εξόδου + Έξοδος έκτακτης ανάγκης + Ακύρωση εξόδου + Δεν ήταν δυνατός ο έλεγχος της διεύθυνσης χρηματοδότησης. Δοκιμάστε ξανά. + Το 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 + Αυτή η έξοδος πληρώνει <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> + Χρησιμοποιήστε το μόνο αν το 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} από την υπόλοιπη χρηματοδότηση τελών στάλθηκαν στις αποταμιεύσεις. + {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 + Σύρετε Για Έξοδο + Τα τέλη είναι υψηλότερα από όσα θα λαμβάνατε. + Μέρος αυτής της εξόδου δεν μπορεί να διαβαστεί on-chain αυτή τη στιγμή. Το Bitkit προσπαθεί ξανά για έως μία εβδομάδα. + {amount} που μετέφεραν on-chain οι διαχειριστές του Spark περιμένουν να τα αποδεσμεύσουν. Το Bitkit ζητά ξανά για έως μία εβδομάδα. Πάροχος Spark μέσω Breez Χωρίς όριο @@ -1727,6 +1820,9 @@ Μικρό Φαρδύ Ενημέρωση υπολοίπου… + Απαιτείται χρηματοδότηση τελών + Σε εξέλιξη + Έξοδος Έκτακτης Ανάγκης Χρήση Spark Εκτός σύνδεσης Σύνδεση... diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index cfbe542d62..f4b03b2a0e 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -235,6 +235,99 @@ Esperar Depósitos reclamados Depósitos en curso + 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 + 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> + Ú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. + {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 + 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 + Enviando a ahorros + Esperando el bloqueo temporal + 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 @@ -1728,6 +1821,9 @@ Pequeño Ancho Actualizando saldo… + Financiación de comisiones necesaria + En curso + Salida de emergencia Usando Spark Sin conexión Conectando... diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index faa46b79b4..cb250a075a 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -177,6 +177,99 @@ Esperar Depósitos reclamados Depósitos en curso + 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 + 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> + Ú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. + {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 + 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 + Enviando a ahorros + Esperando el bloqueo temporal + 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 @@ -1728,6 +1821,9 @@ Pequeño Ancho Actualizando saldo… + Financiación de comisiones necesaria + En curso + Salida de emergencia Usando Spark Sin conexión Conectando... diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 53155daee9..f4a8687132 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -111,6 +111,99 @@ Attendre Dépôts réclamés Dépôts en cours + 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 + 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> + 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. + {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 + 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 + Envoi vers l\'épargne + En attente du timelock + 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 @@ -1728,6 +1821,9 @@ Petit Large Mise à jour du solde… + Financement des frais requis + En cours + Sortie d\'urgence Via Spark Hors ligne Connexion... diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index b20813bcc4..a44dda72c2 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -234,6 +234,99 @@ Attendi Depositi riscattati Depositi in corso + 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 + 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> + 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. + {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 + 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 + Invio ai risparmi + In attesa del timelock + 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 @@ -1728,6 +1821,9 @@ Piccolo Largo Aggiornamento del saldo… + Finanziamento delle commissioni necessario + In corso + Uscita di Emergenza Tramite Spark Offline In connessione... diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index beb98cef5b..b210d10775 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -233,6 +233,99 @@ Wachten Geclaimde stortingen Lopende stortingen + 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 + 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> + 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. + {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 + Je betaling uit spaargeld is niet gelukt. Betaal opnieuw of financier vanuit een andere wallet. + Totaal uit spaargeld + Kostenfinanciering wordt bevestigd + Exittransacties publiceren + Naar spaargeld sturen + Wachten op de tijdvergrendeling + 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 @@ -1727,6 +1820,9 @@ Klein Breed Saldo bijwerken… + Kostenfinanciering nodig + Bezig + Noodexit Via Spark Offline Verbinden... diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 3be2130e01..480fd04042 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -113,6 +113,99 @@ Czekaj Odebrane wpłaty Wpłaty w toku + 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 + 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> + 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. + {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 + 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 + Wysyłanie do Oszczędności + Oczekiwanie na blokadę czasową + 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 @@ -1729,6 +1822,9 @@ Mały Szeroki Aktualizowanie salda… + Potrzebne finansowanie opłat + W toku + Wyjście awaryjne Przez Spark Offline Łączenie... diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index dffbb3a987..7d48e5a6f6 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -237,6 +237,99 @@ Esperar Depósitos resgatados Depósitos em andamento + 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 + 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> + 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. + {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 + 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 + Enviando para a poupança + Aguardando o timelock + 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 @@ -1728,6 +1821,9 @@ Pequeno Largo Atualizando saldo… + Financiamento das taxas necessário + Em andamento + Saída de Emergência Usando o Spark Offline Conectando... diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index d82fda8d2f..aef7c3de1f 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -108,6 +108,99 @@ Esperar Depósitos resgatados Depósitos em curso + 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 + 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> + 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. + {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 + 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 + A enviar para a poupança + A aguardar o timelock + 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 @@ -1728,6 +1821,9 @@ Pequeno Largo A atualizar o saldo… + Financiamento das taxas necessário + Em curso + Saída de Emergência Usando o Spark Offline Conectando... diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 80d38344a2..6885fd0628 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -245,6 +245,99 @@ Ждать Зачисленные депозиты Депозиты в обработке + Сумма выхода + Экстренный выход + Отменить выход + Не удалось проверить адрес пополнения. Попробуйте ещё раз. + 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 + Этот выход платит <accent>{rate} sat/vB</accent>, меньше, чем сейчас требует сеть. Выберите ставку выше, и Bitkit заново отправит ожидающие шаги. Разницу он оплатит из сбережений: это сумма рядом с каждой скоростью. + Заплатить\n<accent>больше</accent> + Сеть сейчас загружена сильнее, чем позволяет ставка комиссии этого выхода в {rate} sat/vB. Заплатите больше или дождитесь снижения комиссий. + Сетевые комиссии превысили комиссию этого выхода. Он может замедлиться. + Сетевые комиссии + Пополнить с другого кошелька + Отправьте не менее {amount} на этот адрес. Выход начнётся после подтверждения. + В сбережениях недостаточно средств на комиссии. + Оплачено из сбережений, ожидает подтверждения. + Получено {received} из {required}, отправьте ещё {missing}. + Платёж обнаружен, ожидает подтверждения. + Оплатить из сбережений + Платёж обнаружен. + Нужны средства на комиссии + Bitkit делит сумму на {count} частей, по одной на каждый шаг, чтобы застрявший шаг не задерживал остальные. + Выход оплачивает свои комиссии отдельным ончейн-платежом на <accent>{amount}</accent>. Неизрасходованное в конце вернётся в сбережения. + Оплатите\n<accent>комиссии</accent> + Используйте это, только если 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} отправлен в сбережения. + Сдача с комиссий {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 не смог прочитать сохранённый прогресс этого выхода, поэтому восстанавливает его по блокчейну. + Вы получите примерно + Комиссия платежа из сбережений + Платёж из сбережений не прошёл. Оплатите снова или пополните с другого кошелька. + Всего из сбережений + Подтверждение средств на комиссии + Публикация транзакций выхода + Отправка в сбережения + Ожидание таймлока + Проведите для выхода + Комиссии больше, чем сумма, которую вы получите. + Часть этого выхода сейчас не удаётся прочитать в блокчейне. Bitkit будет пробовать снова в течение недели. + {amount}, которые операторы Spark перевели ончейн, ждут, пока операторы их выдадут. Bitkit будет запрашивать снова в течение недели. Провайдер Spark через Breez Без ограничений @@ -1743,6 +1836,9 @@ Маленький Широкий Обновление баланса… + Нужны средства на комиссии + Выполняется + Экстренный Выход Через Spark Не в сети Подключение... diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 451407d7da..c195a779ce 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -420,6 +420,102 @@ Wait Claimed deposits Deposits in progress + 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> + 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. + 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. + {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> + 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. + {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 + Your savings payment didn\'t go through. Pay again, or fund from another wallet. + Total from savings + 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. + 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 @@ -1079,6 +1175,9 @@ Connecting... Connected Bitcoin Node + Fee funding needed + In progress + Emergency Exit Disconnected Reconnecting... Connected diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 70901da134..53c6a5fa16 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 @@ -116,6 +121,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() @@ -1830,6 +1838,118 @@ 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 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() + 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") + } + + 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 `a metadata restore keeps spark's backed-up send hashes but holds older invoices until spark lists them`() = test { 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/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 92527d1807..81b9fc2dc8 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -201,6 +201,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) @@ -317,6 +336,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/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)) 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..765ab54987 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitAlertsTest.kt @@ -0,0 +1,151 @@ +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) + 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)) + // 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)), + ) + 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)) + // 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 + 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 `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))) + 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)) + } + + @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")), + ) + } + + @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)) + // 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) + } + + @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/SparkExitChainTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt new file mode 100644 index 0000000000..7bb8a1b1d7 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitChainTest.kt @@ -0,0 +1,438 @@ +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.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertTrue + +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 = + 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. + 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 `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":{}}""")) + + 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"]) + } + + 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("min relay fee not met")) + assertTrue(SparkExitBroadcastClassifier.isUnplaceable(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 `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( + 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 `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 `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":""" + val classifier = SparkExitBroadcastClassifier + assertEquals( + SparkExitBroadcastOutcome.Accepted, + classifier.single(400, """sendrawtransaction RPC error: {"code":-27}"""), + ) + assertEquals( + SparkExitBroadcastOutcome.InputsMissing("RPC error -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("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"}}}""" + 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)) + } + + @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 `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") + 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") } + } + + @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/SparkExitDriverTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt new file mode 100644 index 0000000000..2a87c1c1b4 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitDriverTest.kt @@ -0,0 +1,2958 @@ +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 +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 +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 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 +import kotlin.test.assertFailsWith +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" + val BUMP = "be".repeat(32) + val UNPAID = SparkExitBroadcastOutcome.Rejected("min relay fee not met, 0 < 17") + } + + @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, + tip: UInt? = null, + save: (SparkExitRecord) -> Unit = { saved += it }, + trustedFeeRate: ULong? = 10uL, + ) = SparkExitDriver( + chain = chain, + recovering = sdk.takeIf { withSdk }, + makeSigner = { StubCpfpSigner() }, + save = save, + nowMillis = { now }, + tip = tip, + trustedFeeRate = { trustedFeeRate }, + ) + + private val interval = SparkExitDriver.REBUILD_INTERVAL.inWholeMilliseconds + + 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(tip = 2_000u).tick(record) + + assertEquals(listOf("n2", "n2"), chain.broadcasts.map { it.txid }) + assertEquals(2, record.broadcastLog.single().attempts) + // 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) + } + + @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 `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, builtAt = now - interval) + chain.outcome = SparkExitBroadcastOutcome.Rejected("insufficient fee, rejecting replacement") + 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(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 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( + 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 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)) + // 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) + + 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 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) + 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 + 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 `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 `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 `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 `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( + 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( + 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) + // 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) + 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") + } + + /** + * 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( + 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), + ), + ) + chain.confirmedTxids = setOf("n1") + + 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)))) + 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) + + // 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_136uL, 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) + + // 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 = 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 = 150uL), SparkExitFixtures.utxo("t2", value = 172uL)) + 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_136uL, 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 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, 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, 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. + 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, 1_000uL)) + record = driver(tip = 1_144u).tick(record) + assertEquals(1_144u, assertNotNull(record.leftoverSweep).checkedAtHeight) + assertEquals(1_000u, assertNotNull(record.leftoverSweep).waitingSince) + + 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) + // 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") + assertFalse(record.copy(isResultSeen = true).showsResult, "kept change blocks every later exit") + } + + @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) + val first = assertNotNull(record.leftoverSweep.txid) + chain.outcome = SparkExitBroadcastOutcome.InputsMissing("missing-inputs") + record = driver(tip = 1_001u).tick(record) + // 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) + 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 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_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) + } + + @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 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") + 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)) + 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( + 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 `a first build of only cooperative leaves the operators could not sign is kept and retried`() = test { + sdk.preparedResponse = SparkExitFixtures.prepared(funding = null) + val failed = listOf( + CooperativeRecoveryFailure("leaf-1", "o", 0u, CooperativeRecoveryError.OperatorsUnavailable("down")), + ) + sdk.builds += SparkExitFixtures.recovery(emptyList(), failed = failed) + + var record = driver(tip = 1_000u).tick(SparkExitFixtures.record(Phase.AwaitingFunding(0uL))) + + assertEquals(Phase.Running, record.phase) + assertEquals(1, record.failedLeafCount) + 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) + } + + @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", + 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.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) + } + + 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 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"))))) + .copy(leafIds = listOf("leaf-1", "leaf-2")) + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = listOf("leaf-1", "leaf-2")) + // Refused by the build at this rate. + sdk.recoverError = ladderRefusal("leaf-1") + chain.utxosByAddress[SparkExitFixtures.FUNDING_ADDRESS] = listOf(SparkExitFixtures.utxo("f0", value = 20_000uL)) + + 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-1", "leaf-2"), record.exitLeafIds) + 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 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"))))) + .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), + 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) + assertFalse(record.isAwaitingOwnPayment) + assertEquals( + listOf("f0", "bump"), + sdk.recoverRequests.single().fundingInputs.map { (it as CpfpInput.P2wpkh).txid } + ) + // The generation out there kept going while the payment confirmed. + assertEquals(listOf("n1", "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 `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)), + ) + // 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) + + 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 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"))) + 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) + .copy(isRebuilding = true) + sdk.preparedResponse = SparkExitFixtures.prepared(leaves = emptyList()) + + 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) + .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 `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) + .copy(isRebuilding = true) + sdk.preparedResponse = waiting(SkippedLeafReason.OperatorsUnavailable) + + val ticked = driver(tip = 1_000u).tick(record) + + assertEquals(Phase.Running, ticked.phase) + 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 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 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 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 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)) + 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")) + 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 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 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_003u).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( + 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) + } + + 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( + 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 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(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, valueSats)), + ) + } + + /** + * 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 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) }, + ) + + 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) + } + + @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 + fun `a refused minimum too big to scale asks for more than any cap`() { + val refusal = "mempool min fee not met, 450 < 10000000000000000000" + 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), + ) + // 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 + 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 + 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 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") + 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 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()) + 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 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 `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()) + val first = assertNotNull(record.leftoverSweep) + chain.nextBlockRate = 1_000uL + + record = driver(tip = 1_144u, trustedFeeRate = 1_000uL).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() + 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, + isRedoRebuild = true, + ) + 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 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 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) + 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) + 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 quote = sdk.prepareAll(SparkExitFixtures.prepareRequest(), lost = setOf("lost-1")) + + assertEquals(listOf(ExitLeafSelection.All), sdk.prepareRequests.map { it.selection }) + 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 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 = quote).quoteBlock) + assertEquals(listOf(100_000uL), quote.lostLeafSats) + } + + @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) + } + + /** + * 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 and never counts as a rejection`() = test { + var record = running(unpaidRecovery, builtAt = now - interval) + chain.outcome = UNPAID + repeat(3) { 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(1, record.stallRebuilds) + assertEquals(0, record.broadcastLog.single().rejections) + assertNull(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"))) + 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/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()) + } +} 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..ddc7ed36d2 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFixtures.kt @@ -0,0 +1,288 @@ +package to.bitkit.repositories + +import breez_sdk_spark.CheckRecoverFundsResponse +import breez_sdk_spark.CooperativeRecoveryFailure +import breez_sdk_spark.CpfpFundingKind +import breez_sdk_spark.CpfpFundingStrategy +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.ImportUnilateralExitStateResponse +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(), CpfpFundingStrategy.PER_BRANCH) }, + feeRateSatPerVbyte = 2uL, + destination = "bcrt1qdestination", + 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, + 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) + } + + /** 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)) +} + +class FakeSparkExitChain : SparkExitChain { + var tip = 1_000u + val utxosByAddress = mutableMapOf>() + 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 + val broadcasts = mutableListOf() + var onBroadcast: () -> Unit = {} + + 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() + } + + /** 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 + return txid !in unknownTxids + } + + 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() + + 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 + + var economyRate: ULong? = 1uL + + override suspend fun economyFeeRate(): ULong = economyRate ?: throw SparkExitChainError("No fee estimates") +} + +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 recovers throw, in order, before [recoverError]. */ + val recoverErrors = ArrayDeque() + + /** 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 preparedResponses.removeFirstOrNull() ?: preparedResponse + } + + override suspend fun recover(request: RecoverFundsRequest, signer: CpfpSigner?): RecoverFundsResponse { + recoverRequests += request + recoverErrors.removeFirstOrNull()?.let { throw it } + recoverError?.let { throw it } + return builds.removeFirst() + } + + override suspend fun check(recovery: RecoverFundsResponse): CheckRecoverFundsResponse { + 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): ImportUnilateralExitStateResponse { + imports += exitState + return ImportUnilateralExitStateResponse(0u, 0u, 0u, 17u) + } +} + +/** 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..ec062e76bc --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitFundingTest.kt @@ -0,0 +1,755 @@ +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 +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 +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 `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 `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 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 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 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)) + 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)) + 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)) + // 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 + fun `savings must cover the funding and its fee`() { + 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 + 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, with the input fee of the coin that pays it. + val paidShort = listOf(SparkExitFixtures.utxo("paid", value = 15_000uL)) + assertEquals( + SparkExitFundingState.Ask(5_136uL, 15_000uL, 20_136uL), + 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_136uL, 8_000uL, 20_136uL), + SparkExitMath.fundingState(record, partial) + ) + 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 `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 `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() + 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 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(SparkExitPartialFunding(8_000uL, 20_136uL, 12_136uL), 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_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_136uL, 294uL), ask.partial) + assertEquals( + SparkExitPartialFunding(19_932uL, 20_000uL, 294uL), + 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) + } + + @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)) + // 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)) + } + + @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( + 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))) + } + + @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 }) + } + + /** 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) + } + + @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/SparkExitRecordTest.kt b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt new file mode 100644 index 0000000000..efa5b2c6ae --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRecordTest.kt @@ -0,0 +1,369 @@ +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 org.lightningdevkit.ldknode.Network +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 + +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, + feeChainFailures = 2, + acceptedAtHeight = 1_000u, + ), + ), + claimableAtHeight = 2_100u, + leftover = listOf(SparkExitRecord.Leftover("change", 3u, 700uL)), + isRebuilding = true, + leafTotalSats = 90_112uL, + outsideSats = 14_167uL, + earlierCpfpTxids = listOf("child"), + 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")), + 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, + isFeeBumpPending = true, + feeBumpBuiltAtHeight = 1_004u, + earlierReceivedSats = mapOf("sweep-0" to 90_000uL), + ) + + 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) + listOf( + "stallRebuilds", + "stallConfirmedCount", + "unverifiedRebuiltAtHeight", + "stoppedLeafSince", + "retrySince", + "retriedAt", + "exitStateSnapshot", + "isRebuiltFromChain", + "isRedoRebuild", + "isFeeBumpPending", + "feeBumpBuiltAtHeight", + "earlierReceivedSats", + ).forEach { assertFalse(it in json, it) } + 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 `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))) + // 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 + fun `a salvaged record that had ended stays ended and one with nothing to rebuild from is not salvaged`() { + 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)) + } + + @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()) + + // An unreadable record counts as running until the repo salvages it, so an exit never disappears over it. + file.writeText("{") + assertTrue(store.isActive()) + assertEquals("{", store.loadText()) + store.setAside(42L) + // 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()) + } + + @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))) + } + + @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) + } +} 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..77d3f1f62e --- /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(checkNotNull(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..3307dd0d23 --- /dev/null +++ b/app/src/test/java/to/bitkit/repositories/SparkExitRepoTest.kt @@ -0,0 +1,1925 @@ +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.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 +import com.synonym.bitkitcore.PaymentType +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.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 kotlinx.coroutines.test.runCurrent +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.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 +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 +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.ext.create +import to.bitkit.models.FeeRate +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.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.Duration.Companion.days +import kotlin.time.Instant + +class SparkExitRepoTest : BaseUnitTest() { + @get:Rule + val tempFolder = TemporaryFolder() + + 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 sparkState + } + private val work = mock() + private val cacheStore = mock { on { data } doReturn flowOf(AppCacheData()) } + + @Before + fun setUp() { + Env.initAppStoragePath(tempFolder.root.absolutePath) + whenever { work.activeWalletIndex() }.thenReturn(0) + } + + private fun createSut( + sparkService: SparkService = mock(), + httpClient: HttpClient = mock(), + keychain: Keychain = mock(), + coreService: CoreService = mock(), + lightningRepo: LightningRepo = mock(), + activityRepo: ActivityRepo = mock(), + ) = SparkExitRepo( + work = work, + bgDispatcher = testDispatcher, + sparkService = sparkService, + sparkRepo = sparkRepo, + lightningRepo = lightningRepo, + transferRepo = transferRepo, + activityRepo = activityRepo, + coreService = coreService, + keychain = keychain, + httpClient = httpClient, + clock = object : Clock { + override fun now() = Instant.fromEpochSeconds(1_800_000_000) + }, + sparkExitTip = SparkExitTip(), + cacheStore = cacheStore, + ) + + 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) + + @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()) + } + + @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 `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 `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)) + 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, + refusalStatus: HttpStatusCode = HttpStatusCode.BadRequest, + ) = HttpClient( + 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, refusalStatus) + 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 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 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()) + 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 { + 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() + assertFalse(File(Env.sparkExitEarlierAddressesPath(0)).exists(), "the wiped wallet's addresses stayed") + } + + @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 `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))) + 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 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))) + 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.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) } } + // 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_239uL), 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))) + 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 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" + 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()) + } + + private val lightning = mock() + + private val funding = "bcrt1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080" + + /** 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 = 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) + 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) + } + + // 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.create { + dispatcher = testDispatcher + addHandler { request -> + 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'") + } + } + }, + ) { 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, + 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}""") + 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") + } + + 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") + 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" + 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" + 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)) + 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() + // 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 + 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) + } + + @OptIn(ExperimentalCoroutinesApi::class) + @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).awaitSpendsIdle() + 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) + // 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() + } + + @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() + } + + @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) + } + + @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 { + 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) + } + + @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") + } + + @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 `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 + 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 `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( + 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 { + 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(), + approvedMiningFeeSats = anyOrNull(), + ) + 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() + } + + @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() + 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() + } + + @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 `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(), any())) + .thenReturn(Result.success(1_000uL)) + whenever(lightning.getBalancesAsync()).thenReturn(Result.success(balances(100_000uL))) + + 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")) } + 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")) } + 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(), 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() + + verify(lightning).sendOnChain( + eq(funding), any(), anyOrNull(), anyOrNull(), eq(rates), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + // Savings never pays more fee than the one confirmed. + approvedMiningFeeSats = eq(300uL), + ) + } + + @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")) } + 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(), + approvedMiningFeeSats = anyOrNull(), + ) + } + + 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()) + // Nothing was paid: Spark keeps the balance it showed before the exit. + verify(sparkRepo).releaseExitHold() + verify(sparkRepo).setExiting(false, true) + } + + @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()) + } + + 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(), + approvedMiningFeeSats = anyOrNull(), + ) + assertEquals("again", assertNotNull(store.load()).fundingPaymentTxid) + assertFalse(sut.state.value.isSavingsPaymentRefused) + 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))) + 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) + verify(sparkRepo).releaseExitHold() + } + + @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 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( + any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), any(), anyOrNull(), + any(), any(), any(), any(), anyOrNull(), anyOrNull(), anyOrNull(), anyOrNull(), + paymentDeadlineAt = anyOrNull(), + contactPublicKey = anyOrNull(), + approvedMiningFeeSats = 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 `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 { + 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) + } + + @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) + } + + @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(), + // The total shown less the extra funding. + approvedMiningFeeSats = eq(400uL), + ) + } + + @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))) + 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) + + // 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/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/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) + } +} diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index ebbe0a2d18..1f3d8f7ec1 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 @@ -149,11 +150,15 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.listUnclaimedDeposits() }.thenReturn(emptyList()) whenever { sparkService.listPayments() }.thenReturn(emptyList()) whenever(sparkService.events).thenReturn(sparkEvents) - whenever { sparkService.connect(any()) }.thenReturn(true) + whenever { sparkService.connect(any(), any()) }.thenReturn(true) whenever { activityRepo.getActivity(any(), any()) }.thenReturn(Result.success(null)) 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 @@ -172,6 +177,29 @@ 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() + clearInvocations(sparkService) + 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 `a failed start is flagged until the next start begins`() = test { val retryConnects = CompletableDeferred() @@ -1072,6 +1100,19 @@ 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() + sut.start(0).getOrThrow() + assertEquals("state", sut.exitBackup().getOrThrow()?.exitState) + + SparkExitStore(File(Env.sparkExitRecordPath(0))).save(SparkExitFixtures.record()) + + assertNull(sut.exitBackup().getOrThrow()) + } + @Test fun `quotes a withdrawal to a Paykit contact as a route leg`() = test { val sut = readySpark(balanceSats = 50_000uL) @@ -2482,6 +2523,91 @@ 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") + } + + 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'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() + + 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 `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) @@ -2611,6 +2737,99 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any(), anyOrNull()) } + @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(), anyOrNull()) + 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(), anyOrNull()) }.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 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(), anyOrNull()) }.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) + 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(), anyOrNull()) + assertIs(error) + } + @Test fun `an expired invoice spark refuses is a typed refusal`() = test { whenever(sparkService.isConnected).thenReturn(true) @@ -2845,6 +3064,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) diff --git a/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WalletRepoTest.kt index 8af155152b..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 { @@ -143,7 +145,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() } @@ -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() diff --git a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt index e5e88d9be5..5919d4b41e 100644 --- a/app/src/test/java/to/bitkit/services/SparkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/SparkServiceTest.kt @@ -107,7 +107,7 @@ class SparkServiceTest { @Test fun `config turns off breez data sync, the lightning address server and default parsers 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") @@ -119,7 +119,8 @@ class SparkServiceTest { @Test fun `invoices carry no spark address on any network, so every payment is a lightning payment bitkit records`() { Network.entries.forEach { network -> - assertFalse(SparkService.configure(defaults(network), apiKey = null).preferSparkOverLightning, "$network") + val config = SparkService.configure(defaults(network), apiKey = null, isExiting = false) + assertFalse(config.preferSparkOverLightning, "$network") } } } 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 49f5ea24e1..7fad969d84 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 @@ -83,7 +83,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)) } @@ -172,7 +172,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/settings/appStatus/AppStatusViewModelTest.kt b/app/src/test/java/to/bitkit/ui/settings/appStatus/AppStatusViewModelTest.kt index dc5ff93a18..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 @@ -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,10 @@ 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 import to.bitkit.test.BaseUnitTest import kotlin.test.assertEquals @@ -25,6 +30,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 +50,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 +58,7 @@ class AppStatusViewModelTest : BaseUnitTest() { context = context, healthRepo = healthRepo, lightningRepo = lightningRepo, + sparkExitRepo = sparkExitRepo, cacheStore = cacheStore, ) } @@ -177,4 +185,69 @@ 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), 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 + 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) + 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, + 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 + } } 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..aa1ab4e150 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkExitViewModelTest.kt @@ -0,0 +1,323 @@ +package to.bitkit.ui.settings.lightning + +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.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 +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 +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 +import to.bitkit.repositories.SparkExitSavingsFunding +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 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(mock(), repo, sparkRepo) + 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(mock(), repo, sparkRepo) + + sut.onFundingShown() + + assertTrue(sut.uiState.value.showsFundingAddress) + sut.stopWatchingFundingAddress() + } + + @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. + sut.start() + + assertTrue(sut.uiState.value.isStarted) + sut.onStartShown() + 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 `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. + 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 `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)) + assertFalse(SparkExitUiState().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 + 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) + 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 + 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).apply { sharesNodeChain = { true } } + sut.loadFeeBump() + + sut.payHigherFee() + + verify(repo, times(2)).feeBumpOptions() + 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).apply { sharesNodeChain = { true } } + sut.loadFeeBump() + + sut.payHigherFee() + assertEquals(floored, sut.uiState.value.feeBump.selectedOption) + sut.payHigherFee() + + 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) + .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) + .copy(recovery = SparkExitFixtures.recovery(emptyList()), landedSweepTxid = "sweep") + 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)) + + assertEquals( + SparkExitFundingState.Ask(SparkExitMath.FUNDING_DUST_SATS), + SparkExitUiState(record = record).progressFunding, + ) + } + + /** 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(mock(), 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." + 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/ui/settings/lightning/SparkUiTest.kt b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt new file mode 100644 index 0000000000..d00e9bf478 --- /dev/null +++ b/app/src/test/java/to/bitkit/ui/settings/lightning/SparkUiTest.kt @@ -0,0 +1,41 @@ +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 + +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) + } + + @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") + } +} 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 fc954cd2a5..c304a46c48 100644 --- a/app/src/test/java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/sheets/BoostTransactionViewModelTest.kt @@ -118,7 +118,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 { @@ -134,13 +134,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 @@ -178,7 +178,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) @@ -192,7 +192,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) @@ -218,7 +218,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)) @@ -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) @@ -477,7 +477,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 { @@ -492,7 +492,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 { @@ -508,7 +508,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 { @@ -524,7 +524,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/usecases/DeriveBalanceStateUseCaseTest.kt b/app/src/test/java/to/bitkit/usecases/DeriveBalanceStateUseCaseTest.kt index 800be7030a..958ecf2d13 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,52 @@ 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 `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 diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 0fa434ff19..6f3ca362b5 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -220,6 +220,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.SparkWithdrawalOutcome import to.bitkit.repositories.SparkWithdrawalSettlement import to.bitkit.repositories.TransferRepo @@ -301,6 +303,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() @@ -408,6 +411,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 @@ -922,7 +945,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)) @@ -1007,6 +1030,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { widgetsRepo = widgetsRepo, pubkyRepo = pubkyRepo, timeSource = testDispatcher.scheduler.timeSource, + sparkExitRepo = sparkExitRepo, ) private suspend fun emitNodeEvent( @@ -7026,7 +7050,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() @@ -7727,13 +7751,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() @@ -7781,7 +7805,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() } @@ -7810,7 +7834,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)) @@ -15487,7 +15511,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( @@ -15524,7 +15548,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"))) @@ -15558,9 +15582,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( @@ -17749,7 +17773,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) @@ -17780,7 +17804,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() @@ -19763,7 +19787,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) 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/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. 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. diff --git a/docs/screens-map.md b/docs/screens-map.md index 837f3f1cf8..547b21ce62 100644 --- a/docs/screens-map.md +++ b/docs/screens-map.md @@ -318,6 +318,12 @@ Frame names are stable across handoff iterations; node ids are not, so the map l | LightningConnectionsScreen.kt | Settings > Advanced › Lightning Connections overview | | MoveToSparkScreen.kt | `todo` | | SparkDetailScreen.kt | `todo` | +| SparkExitConfirmScreen.kt | `todo` | +| SparkExitFeeBumpScreen.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 f7dd7c1387..2ccec967ac 100644 --- a/journeys/README.md +++ b/journeys/README.md @@ -200,6 +200,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` | 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 | diff --git a/journeys/settings/app-status-emergency-exit.xml b/journeys/settings/app-status-emergency-exit.xml new file mode 100644 index 0000000000..6173f75650 --- /dev/null +++ b/journeys/settings/app-status-emergency-exit.xml @@ -0,0 +1,22 @@ + + + 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. 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. 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. 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 + + 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 + +