Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
101 commits
Select commit Hold shift + click to select a range
4ec9ece
fix: keep a spark retry held past an older failure
ovitrif Nov 17, 2026
a7349cf
fix: keep a move to spark running after its screen closes
ovitrif Nov 17, 2026
2c2b780
feat: show a move to spark in activity
ovitrif Nov 17, 2026
4c064ab
fix: back up spark exit state past an unimportable remote copy
ovitrif Nov 17, 2026
a894c89
chore: translate spark strings
ovitrif Nov 17, 2026
001af49
chore: tidy spark follow-ups for lint
ovitrif Nov 17, 2026
8b6dfd7
fix: keep staged exit data and a reopened move screen
ovitrif Nov 17, 2026
114f3a8
fix: match ios on move backup, exit set-aside and move rows
ovitrif Nov 17, 2026
97b31e1
fix: leave a held spark retry's row alone on an older failure
ovitrif Nov 17, 2026
f7184ed
fix: spark exit set-aside and retry hold match ios
ovitrif Nov 17, 2026
ab895d2
fix: spark retry start survives restart, unreadable exit data set aside
ovitrif Nov 17, 2026
daf1dfb
fix: spark retry hold survives process death and startup sync
ovitrif Nov 17, 2026
d57bde7
fix: older spark failure keeps an in-flight retry's hold
ovitrif Nov 17, 2026
ecbf41f
fix: older spark failure never releases a retry sent meanwhile
ovitrif Nov 17, 2026
8bb7e6c
fix: spark retry hold matches failures by earlier attempt ids
ovitrif Nov 17, 2026
328df0d
chore: wrap spark attempt kdoc lines
ovitrif Nov 17, 2026
802cad4
fix: drop the retained spark move on wallet wipe
ovitrif Nov 17, 2026
06e645b
fix: correct pt-br spark balance strings
ovitrif Nov 17, 2026
2c7290d
fix: end a held spark retry's activity row on expiry
ovitrif Nov 17, 2026
b00bb8b
fix: keep spark retry holds until their attempt settles
ovitrif Nov 17, 2026
3bc175c
fix: recheck a retained move's stored payment while waiting
ovitrif Nov 17, 2026
b188b6d
fix: report set-aside spark exit data as not restored
ovitrif Nov 17, 2026
2a378bb
fix: write an expired spark retry's row from the read that ends it
ovitrif Nov 17, 2026
037c771
fix: merge a replaced spark exit backup before uploading over it
ovitrif Nov 17, 2026
244833e
fix: keep a running spark retry's earlier attempt ids until it settles
ovitrif Nov 17, 2026
cd8412d
fix: keep move to spark reachable while its result is kept
ovitrif Nov 17, 2026
d93f61e
fix: keep spark retry holds and exit merges across failures
ovitrif Nov 17, 2026
9e9fe4a
fix: end an expired taken spark retry's row before dropping it
ovitrif Nov 17, 2026
61730cb
fix: report an expired taken spark retry's outcome
ovitrif Nov 18, 2026
215cc75
fix: report no outcome for a restored spark retry at expiry
ovitrif Nov 18, 2026
0337261
fix: hold a taken spark retry in every payment lookup
ovitrif Nov 18, 2026
d1ecf28
fix: report rejected spark exit data as not restored
ovitrif Nov 18, 2026
2979510
fix: roll back only the spark attempt a poll marked
ovitrif Nov 18, 2026
b34fa0d
fix: never hold a taken spark retry past its own failure
ovitrif Nov 18, 2026
a90f5e7
fix: collect spark events before a restore connects it
ovitrif Nov 18, 2026
76a7355
fix: keep a taken spark retry's payment id across restarts
ovitrif Nov 18, 2026
c796424
chore: merge spark follow-ups into the restore fix
ovitrif Nov 18, 2026
ae27cfd
fix: take back held spark sends before a restore's events
ovitrif Nov 18, 2026
705a102
fix: load held spark sends under the release lock
ovitrif Nov 18, 2026
0de9d04
test: keep a taken spark retry's expiry across a restart
ovitrif Nov 19, 2026
66e72bc
chore: merge master into spark follow-ups
ovitrif Nov 19, 2026
590373d
Merge pull request #1979 from synonymdev/fix/restore-rejected-exit-data
ovitrif Nov 19, 2026
2fc65a4
chore: merge the restore fix into spark follow-ups
ovitrif Nov 19, 2026
8fc1e90
fix: keep a taken spark retry's hold and entry, fail unread exit backups
ovitrif Nov 19, 2026
d1cd715
fix: own a spark send's entry by a random attempt id
ovitrif Nov 19, 2026
af32f2a
fix: bind spark retry expiry and reuse to its own attempt
ovitrif Nov 19, 2026
166c568
fix: keep each spark invoice's hold with the attempt its journal names
ovitrif Nov 19, 2026
a7301d5
fix: end an unlisted taken spark retry after a grace past expiry
ovitrif Nov 19, 2026
59eff9d
fix: finish a pending spark send's hold when its caller is cancelled
ovitrif Nov 19, 2026
6d271e3
fix: journal a taken spark send's id when its caller is cancelled
ovitrif Nov 19, 2026
640d72a
fix: hold an in-doubt spark retry past an older unlisted failure
ovitrif Nov 19, 2026
8935d0b
fix: end an unlisted taken spark retry only after a later sync
ovitrif Nov 19, 2026
e97db95
fix: keep a failed spark send's own amount against an earlier failure
ovitrif Nov 19, 2026
af08c09
fix: end a held spark send's row only while its hold stands
ovitrif Nov 19, 2026
df36745
Merge remote-tracking branch 'origin/master' into fix/spark-follow-ups
ovitrif Nov 19, 2026
9a672a0
fix: let a spark send's failed row take its own and later failures
ovitrif Nov 19, 2026
cb6529a
fix: keep a failed spark send row against a same-second earlier failure
ovitrif Nov 19, 2026
5094946
fix: spark send row ownership on retry and exit cleanup
ovitrif Nov 19, 2026
02fa00a
fix: spark retry row keeps its own failure past expiry
ovitrif Nov 19, 2026
c38c4f3
fix: spark row keeps its own fee correction after a refused retry
ovitrif Nov 20, 2026
e2f968e
fix: spark held row keeps its own writer when failed
ovitrif Nov 20, 2026
8f2d5e1
fix: spark held row checks kept earlier ids for its writer
ovitrif Nov 20, 2026
31cce5e
fix: spark row writer cleared only once its row was written over
ovitrif Nov 20, 2026
7d91612
fix: spark send row writer kept before its row
ovitrif Nov 20, 2026
56be692
fix: spark send row writer resolved by stamp after a cut write
ovitrif Nov 20, 2026
f329f08
fix: spark row without a writer keeps its stamp past a cut write
ovitrif Nov 20, 2026
c612226
fix: spark failed row write restores both writers
ovitrif Nov 20, 2026
ec4051d
fix: spark skips writes for an unchanged send row
ovitrif Nov 20, 2026
8e3da33
fix: spark keeps a retried send's row writer
ovitrif Nov 20, 2026
17286a8
fix: spark keeps new send row writers at the cap
ovitrif Nov 20, 2026
b61d121
fix: spark holds taken sends through the grace
ovitrif Nov 20, 2026
f4f847e
fix: spark keeps settled sends settled after a failed call
ovitrif Nov 20, 2026
baf9224
fix: spark returns a send outcome handled before its call failed
ovitrif Nov 20, 2026
ec5f4ef
fix: spark holds a retry in its send call past older failures
ovitrif Nov 20, 2026
0287a12
fix: spark max funding caps the claim fee at the swiped one
ovitrif Nov 20, 2026
db0142d
fix: pending send resolves an outcome handled before tracking
ovitrif Nov 20, 2026
618cc1a
fix: hold spark sends through their call and wipe
ovitrif Nov 20, 2026
cb20504
fix: spark orders two kept earlier attempts by date
ovitrif Nov 20, 2026
8ca2e45
fix: spark reports a send failure seen during its call
ovitrif Nov 20, 2026
73cc55e
fix: spark orders kept earlier attempts by send order
ovitrif Nov 20, 2026
3387208
fix: spark lets dates order kept attempts before send order
ovitrif Nov 20, 2026
1bf0780
fix: spark settles a failure seen as the send call hands over
ovitrif Nov 20, 2026
8a609f8
fix: spark reports a failure seen during its call once
ovitrif Nov 20, 2026
904e629
fix: spark holds retries of unresolved sends
ovitrif Nov 20, 2026
d8e1de5
fix: spark holds a taken send until it settles
ovitrif Nov 20, 2026
63135ae
fix: spark settles a cancelled send at expiry
ovitrif Nov 20, 2026
7444b24
fix: spark ignores an older attempt failure event
ovitrif Nov 20, 2026
d45d997
fix: spark keeps a send in flight until its result is handled
ovitrif Nov 20, 2026
50fae11
fix: spark restores saved holds under the send lock
ovitrif Nov 21, 2026
1ea4fdd
fix: spark settles a hold under the restore lock
ovitrif Nov 21, 2026
2c94820
fix: spark reports a send outcome once per payment
ovitrif Nov 21, 2026
a5094aa
fix: spark reports a settled send from the payment it read
ovitrif Nov 21, 2026
5306637
fix: spark keeps a settled failure off a retry in flight
ovitrif Nov 21, 2026
5f79ba2
fix: spark keeps a retry's saved send through the poll
ovitrif Nov 21, 2026
cc0cc6c
fix: spark failure event keeps a retry's hold
ovitrif Nov 21, 2026
d20d1c7
fix: spark failure event leaves a retry's screen alone
ovitrif Nov 21, 2026
2372752
fix: spark launch sync settles a held send it lists
ovitrif Nov 21, 2026
8573baf
fix: spark retry start clears earlier failures
ovitrif Nov 21, 2026
844626f
fix: spark sync settles only holds from before its list
ovitrif Nov 21, 2026
ff2687e
fix: unsynced spark refuses an operator-failed send
ovitrif Nov 21, 2026
33f1958
fix: spark retry success during a list read stays pending
ovitrif Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions app/src/main/java/to/bitkit/data/CacheStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,12 @@ class CacheStore internal constructor(
store.updateData { it.copy(sparkUncertainSends = it.sparkUncertainSends - hash) }
}

suspend fun addMoveToSparkHash(paymentHash: String) {
val hash = paymentHash.lowercase()
if (hash in store.data.first().moveToSparkHashes) return
store.updateData { it.copy(moveToSparkHashes = it.moveToSparkHashes + hash) }
}

/** Keeps [paymentHash] with its invoice's expiry in epoch seconds, [expiresAt], when known. */
suspend fun addLdkSendHash(paymentHash: String, expiresAt: Long? = null) {
val hash = paymentHash.lowercase()
Expand Down Expand Up @@ -369,6 +375,11 @@ data class AppCacheData(
* never reads a retry's earlier failed attempt as its outcome.
*/
val sparkUncertainSends: Map<String, Long> = mapOf(),
/**
* Payment hashes of the moves to Spark, kept across restarts so neither leg of a move is announced as a payment and
* Activity shows the move as one.
*/
val moveToSparkHashes: List<String> = listOf(),
/** Hashes of the Lightning sends the node started, so Spark holds off while the node can't list them. */
val ldkSendHashes: List<String> = listOf(),
/** Invoice expiry in epoch seconds of the [ldkSendHashes] that know it. */
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/to/bitkit/ext/Activities.kt
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ fun Activity.matchesPaymentId(paymentHashOrTxId: String): Boolean = when (this)

fun Activity.isTransfer() = this is Activity.Onchain && this.v1.isTransfer

/** Whether this is the channel send of a move to Spark, one of [moveHashes], which Activity shows as a move. */
fun Activity.isMoveToSpark(moveHashes: Set<String>) = this is Activity.Lightning &&
v1.txType == PaymentType.SENT && v1.id.lowercase() in moveHashes

fun Activity.doesExist() = this is Activity.Onchain && this.v1.doesExist

fun Activity.isReplacedSentTransaction(txIdsInBoostTxIds: Set<String>): Boolean =
Expand Down
33 changes: 33 additions & 0 deletions app/src/main/java/to/bitkit/models/BackupPayloads.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,18 @@ import com.synonym.bitkitcore.IBtInfo
import com.synonym.bitkitcore.IBtOrder
import com.synonym.bitkitcore.IcJitEntry
import com.synonym.bitkitcore.PreActivityMetadata
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonDecoder
import kotlinx.serialization.json.JsonPrimitive
import to.bitkit.data.AppCacheData
import to.bitkit.data.SettingsData
import to.bitkit.data.WatchOnlyAccountAllocationState
Expand Down Expand Up @@ -44,8 +54,31 @@ data class MetadataBackupV1(
* `sparkExitNextFundingIndexes`. Null in envelopes written before this field.
*/
val sparkExitEarlierAddresses: Map<String, List<SparkExitEarlierAddressBackupV1>>? = null,
/**
* The payment hashes of moves to Spark, lowercase hex and sorted, which Activity shows as moves. Null in envelopes
* written before this field or with none; a value that is not a list of strings reads as none.
*/
@OptIn(ExperimentalSerializationApi::class)
@EncodeDefault(EncodeDefault.Mode.NEVER)
@Serializable(with = LenientStringListSerializer::class)
val moveToSparkPaymentHashes: List<String>? = null,
)

/** Reads a list of strings, or an empty list for any other value, so one unreadable field keeps the rest. */
internal object LenientStringListSerializer : KSerializer<List<String>> {
private val delegate = ListSerializer(String.serializer())
override val descriptor = delegate.descriptor

override fun serialize(encoder: Encoder, value: List<String>) = delegate.serialize(encoder, value)

override fun deserialize(decoder: Decoder): List<String> {
val element = (decoder as? JsonDecoder)?.decodeJsonElement() ?: return delegate.deserialize(decoder)
val items = (element as? JsonArray)?.map { it as? JsonPrimitive } ?: return emptyList()
if (items.any { it == null || !it.isString }) return emptyList()
return items.map { requireNotNull(it).content }
}
}

/**
* 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.
Expand Down
100 changes: 95 additions & 5 deletions app/src/main/java/to/bitkit/repositories/BackupRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ import to.bitkit.models.toLdkNetwork
import to.bitkit.services.CoreService
import to.bitkit.services.LightningService
import to.bitkit.services.PaykitSdkService
import to.bitkit.services.SparkError
import to.bitkit.ui.shared.toast.ToastEventBus
import to.bitkit.utils.AppError
import to.bitkit.utils.Logger
Expand Down Expand Up @@ -716,11 +717,15 @@ class BackupRepo @Inject constructor(
* read, so a failed or skipped restore never loses the stored exit data.
*/
private suspend fun uploadSparkExitBackup(): Result<Unit> = runSuspendCatching {
val staged = sparkRepo.importStagedExitState()
if (staged is StagedExitImport.Rejected) {
setAsideRejectedExitBackup(rejectedStagedExitCopy(staged))
sparkRepo.discardStagedExitState(staged.exitState)
}
// Dropping a rejected staged copy asks for the stored backup to be merged again, until a merge succeeds.
if (!sparkRepo.hasMergedRemoteExitState) {
sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred()
val remote = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value
?.let { json.decodeFromString<SparkExitBackupV1>(String(it)) }
sparkRepo.mergeRemoteExitBackup(remote).getOrThrow()
mergeStoredExitBackup()
}
val backup = sparkRepo.exitBackup().getOrThrow() ?: throw SparkExitBackupDeferred()
vssBackupClient.putObject(
Expand All @@ -729,6 +734,56 @@ class BackupRepo @Inject constructor(
).getOrThrow()
}

/**
* Merges the stored exit backup into Spark. One Spark can't import is set aside, and replaced only when it is still
* the stored one after that, so exit data another device stored meanwhile is merged first.
*/
private suspend fun mergeStoredExitBackup() {
var stored = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value
repeat(EXIT_MERGE_ATTEMPTS) {
val remote = stored?.let { bytes ->
runCatching { json.decodeFromString<SparkExitBackupV1>(String(bytes)) }.getOrNull()
}
val merged = if (stored != null && remote == null) {
Result.failure(SparkError.ExitStateUnimportable())
} else {
sparkRepo.mergeRemoteExitBackup(remote)
}
val error = merged.exceptionOrNull() ?: return
val unimportable = stored
if (error !is SparkError.ExitStateUnimportable || unimportable == null) throw error
setAsideRejectedExitBackup(unimportable)
val current = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value
if (current.contentEquals(unimportable)) {
sparkRepo.skipUnimportableRemoteExitState(remote?.exitState)
return
}
stored = current
}
throw SparkExitBackupChanged()
}

private suspend fun rejectedStagedExitCopy(staged: StagedExitImport.Rejected): ByteArray {
val stored = vssBackupClient.getObject(BackupCategory.SPARK_EXIT.name).getOrThrow()?.value
val remote = stored?.let { bytes ->
runCatching { json.decodeFromString<SparkExitBackupV1>(String(bytes)) }.getOrNull()
}
if (stored != null && remote?.exitState == staged.exitState) return stored
val copy = SparkExitBackupV1(
createdAt = currentTimeMillis(),
network = remote?.network ?: staged.network,
exitState = staged.exitState,
)
return json.encodeToString(copy).toByteArray()
}

private suspend fun setAsideRejectedExitBackup(data: ByteArray) {
val key = rejectedExitKey(data)
if (vssBackupClient.getObject(key).getOrThrow() != null) return
vssBackupClient.putObject(key = key, data = data).getOrThrow()
Logger.warn("Set Spark exit data Spark can't import aside as '$key'", context = TAG)
}

suspend fun persistWalletBackup(): Result<Unit> =
withContext(ioDispatcher) {
walletBackupMutex.withLock { uploadWalletBackup() }
Expand Down Expand Up @@ -921,6 +976,8 @@ class BackupRepo @Inject constructor(
pubkyContactProfileOverrides = pubkyContactProfileOverrides,
hwWalletNames = hwWalletNames,
sparkExitEarlierAddresses = sparkExitEarlierAddressesBackup(),
moveToSparkPaymentHashes = cacheData.moveToSparkHashes.map { it.lowercase() }.distinct().sorted()
.takeIf { it.isNotEmpty() },
)

json.encodeToString(payload).toByteArray()
Expand Down Expand Up @@ -1131,7 +1188,13 @@ class BackupRepo @Inject constructor(
connectionSession.replay()
// Before the slower categories, so the exit data is staged before Spark connects and syncs.
performRestore(BackupCategory.SPARK_EXIT, failedCategories) { dataBytes ->
val parsed = json.decodeFromString<SparkExitBackupV1>(String(dataBytes))
val parsed = runCatching { json.decodeFromString<SparkExitBackupV1>(String(dataBytes)) }
.getOrElse {
// A layout this app can't read never becomes readable here, so it is kept for one that can,
// and the restore reports the exit data as not restored, its backup status untouched.
if (it is IllegalArgumentException) setAsideRejectedExitBackup(dataBytes)
throw it
}
sparkRepo.restoreExitBackup(parsed, backupWalletIndex()).getOrThrow()
parsed.createdAt
}
Expand Down Expand Up @@ -1265,11 +1328,20 @@ class BackupRepo @Inject constructor(
// The exit then looks once for funding addresses that still hold coins and nothing watches: each one
// below the index, and those a scan forward from it finds used, which also moves the index past them.
sparkExitFundingRecoveryPending = it.sparkExitFundingRecoveryPending + restoredIndexKeys,
// Both apps back the moves up beside the cache; the device's own stay.
moveToSparkHashes = (
it.moveToSparkHashes + cleanCache.moveToSparkHashes + parsed.moveToSparkPaymentHashes.orEmpty()
).map { hash -> hash.lowercase() }.distinct(),
)
}
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)
// Payment history stays out of the log, as support requests attach it.
val logged = parsed.cache.copy(
cachedRates = emptyList(),
moveToSparkHashes = emptyList(),
)
Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG)
onCacheRestored()
val persisted = preActivityMetadataRepo.upsertPreActivityMetadata(parsed.tagMetadata)
.onFailure { Logger.warn("Failed to restore pre-activity metadata", it, context = TAG) }
Expand Down Expand Up @@ -1555,9 +1627,25 @@ class BackupRepo @Inject constructor(
private const val MINUTE_IN_MS = 60_000
private const val BACKUP_DEBOUNCE = 5000L // 5 seconds

/**
* The remote key of exit data Spark can never import, shared with bitkit-ios. A later, different copy goes
* under this key plus `_` and the first 16 hex digits of its SHA-256; an existing copy is never replaced.
*/
internal const val SPARK_EXIT_REJECTED_KEY = "SPARK_EXIT_REJECTED"
private const val REJECTED_DIGEST_HEX_DIGITS = 16

/** Where exit data Spark can't import is kept: one key per copy, so none replaces another. */
internal fun rejectedExitKey(data: ByteArray): String {
val digest = MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) }
return SPARK_EXIT_REJECTED_KEY + "_" + digest.take(REJECTED_DIGEST_HEX_DIGITS)
}

/** Spark's exit data can reach several MB and changes with every payment, so its uploads are spaced out. */
private const val SPARK_EXIT_BACKUP_DEBOUNCE = 60_000L

/** How many times the exit backup merges stored data another device replaced meanwhile before it gives up. */
private const val EXIT_MERGE_ATTEMPTS = 3

/** Maximum captures before deferring a changing wallet to the next scheduled backup. */
private const val WALLET_SNAPSHOT_ATTEMPTS = 3

Expand Down Expand Up @@ -1588,6 +1676,8 @@ internal class WalletBackupSnapshotChanged : AppError("Private payment state cha

internal class SparkExitBackupDeferred : AppError("Spark has not connected and synced yet")

internal class SparkExitBackupChanged : AppError("Stored Spark exit backup kept changing while it was merged")

private class PublicAddressRestoreFailed(cause: Throwable) : AppError(
"Failed to retain public address exclusion during restore",
cause,
Expand Down
Loading