Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
187 commits
Select commit Hold shift + click to select a range
a92ee43
feat: spark emergency exit
ovitrif Nov 5, 2026
2ed4673
fix: rebuild a spark exit whose fee chain lost a race
ovitrif Nov 5, 2026
f541952
fix: alarm a spark exit stuck on an unpaid step
ovitrif Nov 5, 2026
0baad3f
fix: floor the spark exit funding ask at dust
ovitrif Nov 5, 2026
4df5c75
fix: name what a stopped spark exit leaves on spark
ovitrif Nov 5, 2026
8eac6db
fix: keep lost spark exit leaves out of later exits
ovitrif Nov 5, 2026
938cacc
chore: merge feat/breez-spark-lightning
ovitrif Nov 5, 2026
30f87e5
feat: spark exit uses bitkit electrs on mainnet
ovitrif Nov 5, 2026
a443f00
fix: spark exit stays line after a lost leaf
ovitrif Nov 5, 2026
3ca5e87
fix: keep the spark exit backup from before an exit
ovitrif Nov 5, 2026
f2c6f16
fix: open the spark exit from its notification
ovitrif Nov 5, 2026
4f74ed1
fix: spark exit rebuilds when it stops moving
ovitrif Nov 5, 2026
145da46
fix: spark exit shows a low fee rate when the mempool refuses it
ovitrif Nov 5, 2026
6c26968
chore: merge feat/breez-spark-lightning
ovitrif Nov 5, 2026
25213f7
feat: spark exit funds each step separately
ovitrif Nov 5, 2026
4ffbca9
fix: spark exit alarm names a low fee and keeps an ended exit's leftover
ovitrif Nov 5, 2026
b9460dd
fix: spark exit regtest test names its prepare arguments
ovitrif Nov 5, 2026
baefdf2
fix: spark exit retries leaves the operators moved on-chain
ovitrif Nov 5, 2026
fe94c07
feat: spark exit can pay a higher fee
ovitrif Nov 5, 2026
e515b73
fix: spark exit fee bump shows units and selects only what savings co…
ovitrif Nov 5, 2026
7ce4419
fix: spark exit sweeps fee change when network fees drop
ovitrif Nov 5, 2026
012c6cb
fix: spark exit asks nothing while a higher fee confirms
ovitrif Nov 5, 2026
0a41ffb
fix: spark exit rerun findings
ovitrif Nov 5, 2026
2a75eea
chore: resync this branch with its pull request
ovitrif Nov 5, 2026
623e6f0
fix: spark exit sends lone transactions as a package when the host re…
ovitrif Nov 5, 2026
41dbb0d
fix: spark exit retries a refused fee change sweep
ovitrif Nov 6, 2026
2bd7b6e
chore: merge feat/breez-spark-lightning
ovitrif Nov 6, 2026
d9d3c87
fix: spark exit notifies when it stops moving
ovitrif Nov 6, 2026
e367328
chore: merge feat/breez-spark-lightning
ovitrif Nov 6, 2026
882a9a3
chore: merge feat/breez-spark-lightning
ovitrif Nov 6, 2026
125fef1
chore: merge feat/breez-spark-lightning
ovitrif Nov 6, 2026
ec38baa
chore: merge feat/breez-spark-lightning
ovitrif Nov 6, 2026
74a95a9
chore: merge feat/breez-spark-lightning
ovitrif Nov 6, 2026
64004d7
fix: spark exit cancel, fee bump and sweep findings from review
ovitrif Nov 6, 2026
85aff1c
chore: merge feat/breez-spark-lightning
ovitrif Nov 6, 2026
b0affb2
fix: remind about an unfunded spark exit
ovitrif Nov 6, 2026
9ec9307
fix: spark exit bot review findings
ovitrif Nov 7, 2026
ee4393c
fix: spark exit second round of review findings
ovitrif Nov 7, 2026
3425c85
fix: count spark exit payouts only once confirmed
ovitrif Nov 7, 2026
ae29c95
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 9, 2026
6b345f5
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 9, 2026
4d19f45
fix: pay at most the confirmed exit funding from savings
ovitrif Nov 9, 2026
ba3ed06
fix: cap the refused leftover sweep rate at the next block's
ovitrif Nov 9, 2026
c554a01
feat: show the savings payment fee and total on exit confirm
ovitrif Nov 9, 2026
1fef357
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 9, 2026
ea47b00
fix: watch a higher fee paid after the spark exit ended
ovitrif Nov 9, 2026
3e16b69
fix: keep the spark exit transfer while failed leaves retry
ovitrif Nov 9, 2026
18d3a82
fix: watch a higher fee paid while the spark exit rebuilds
ovitrif Nov 9, 2026
b41334e
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 9, 2026
4babc07
fix: keep the spark exit transfer while failed leaves await retry
ovitrif Nov 9, 2026
ff79f74
fix: translate the spark exit savings payment rows
ovitrif Nov 9, 2026
a8e1462
fix: remind about the rest of a short spark exit savings payment
ovitrif Nov 9, 2026
d0a790d
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 9, 2026
efa22be
fix: retry spark exit leaves a partial build skipped
ovitrif Nov 9, 2026
6feee8e
fix: show the spark exit sweep version that confirmed
ovitrif Nov 9, 2026
1be3366
fix: keep the spark exit start going when its requote write fails
ovitrif Nov 9, 2026
ecae823
fix: translate the spark exit strings
ovitrif Nov 9, 2026
bd56cda
fix: price spark exit savings funding only from read fee rates
ovitrif Nov 9, 2026
0e90def
fix: hold spark exit ticks until its start settles
ovitrif Nov 9, 2026
c09763d
fix: take lost spark exit leaves out of the transfer
ovitrif Nov 9, 2026
34be64c
fix: fail the spark exit savings fee instead of a placeholder
ovitrif Nov 9, 2026
653a881
fix: ask for fee funding a skipped spark exit leaf's retry needs
ovitrif Nov 9, 2026
9b21c89
fix: pay a spark exit fee bump at the rates it was priced at
ovitrif Nov 9, 2026
194504d
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 9, 2026
f413c2d
fix: offer no spark exit fee bump at a placeholder savings fee
ovitrif Nov 9, 2026
b68bdea
fix: end an unfunded spark exit leaf retry after its week
ovitrif Nov 9, 2026
d27796f
fix: keep spark exit leaves skipped beside failed cooperative ones
ovitrif Nov 9, 2026
e790537
fix: count spark exit leaves let go after a week as left on spark
ovitrif Nov 9, 2026
559f372
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 9, 2026
c3f9368
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 9, 2026
397f14d
fix: post raw transactions as text/plain through the spark regtest proxy
ovitrif Nov 9, 2026
398b60e
feat: offer to pay a refused spark exit savings payment again
ovitrif Nov 9, 2026
e9c59c8
fix: keep watching unconfirmed spark exit funding beside dust
ovitrif Nov 9, 2026
c9b3354
fix: allow a higher spark exit fee once a failed-leaf retry built
ovitrif Nov 9, 2026
9224747
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 9, 2026
311caae
fix: keep a spark exit cancel out of its savings payment again
ovitrif Nov 9, 2026
49a93c5
fix: translate the refused spark exit savings payment line
ovitrif Nov 9, 2026
750dc52
fix: offer no spark exit fee rate a leaf can't pay its exit at
ovitrif Nov 9, 2026
c2a62da
fix: keep spark exit deadlines while a retry's steps confirm
ovitrif Nov 9, 2026
79a9b2a
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 9, 2026
80912ba
test: pass the fallback flag in the merged boost fee mocks
ovitrif Nov 9, 2026
df3420d
feat: emergency exit in app status
ovitrif Nov 9, 2026
5513084
chore: add changelog fragment
ovitrif Nov 9, 2026
0251035
fix: scroll app status and translate exit row
ovitrif Nov 10, 2026
6b761ec
fix: exit row funding step and progress navigation
ovitrif Nov 10, 2026
076d616
fix: leave exit progress once and reachable exit journey
ovitrif Nov 10, 2026
d498d4b
docs: exit journey without unreachable cancel
ovitrif Nov 10, 2026
ac7103e
fix: keep an interrupted exit start in its transfer
ovitrif Nov 10, 2026
639eb8a
fix: align exit screens with the explore cell and accents
ovitrif Nov 10, 2026
9184723
fix: match the exit screens across apps
ovitrif Nov 10, 2026
6cd48b7
fix: show a leftover sweep's txid once it is accepted
ovitrif Nov 10, 2026
0823f51
fix: exit progress ok returns to the screen that opened it
ovitrif Nov 10, 2026
14ae952
fix: savings-paid exit row reads in progress after cold start
ovitrif Nov 10, 2026
e47f7ad
fix: match exit spacing and dialogs across apps
ovitrif Nov 10, 2026
0f18690
Merge remote-tracking branch 'origin/feat/breez-spark-lightning' into…
ovitrif Nov 10, 2026
cdbe367
fix: keep the kept spark balance out of an exit
ovitrif Nov 10, 2026
42adfd7
test: match the exit funding stubs to the approved fee parameter
ovitrif Nov 10, 2026
17e525e
fix: ask again for saved exit confirmations after a reorg
ovitrif Nov 10, 2026
48f0723
fix: cap exit funding sends at the confirmed mining fee
ovitrif Nov 10, 2026
9ab94f1
fix: keep the kept spark balance after a cancelled exit
ovitrif Nov 10, 2026
36450df
chore: merge feat/breez-spark-lightning into feat/spark-emergency-exit
ovitrif Nov 10, 2026
4234458
fix: approve the refused savings fee on the next fee bump confirm
ovitrif Nov 10, 2026
1dcb54f
fix: approve the refused savings fee on the next exit start
ovitrif Nov 10, 2026
b8eb8e2
fix: forget the kept spark balance after an exit ends or a wipe
ovitrif Nov 10, 2026
065f5af
chore: merge feat/breez-spark-lightning into feat/spark-emergency-exit
ovitrif Nov 10, 2026
82a77e3
chore: merge feat/breez-spark-lightning into feat/spark-emergency-exit
ovitrif Nov 10, 2026
f6ac4e6
fix: cap the leftover sweep fee at bitkit's own rate
ovitrif Nov 10, 2026
52bac5d
fix: forget a savings payment only after three blocks unseen
ovitrif Nov 10, 2026
1a4450d
chore: merge feat/breez-spark-lightning into feat/spark-emergency-exit
ovitrif Nov 11, 2026
5ff9460
fix: finish a spark exit start its screen left
ovitrif Nov 11, 2026
ada28ad
fix: retry a spark exit rebuild of only failed cooperative leaves
ovitrif Nov 11, 2026
8e72a81
fix: keep a valid spark exit generation going while its rebuild waits
ovitrif Nov 11, 2026
2ce44ba
fix: refuse a spark send once an exit holds spark
ovitrif Nov 11, 2026
e4ce218
fix: open the spark exit from its notification once loaded
ovitrif Nov 11, 2026
318d4fe
fix: keep counting what stays on spark during an exit
ovitrif Nov 11, 2026
d5d098b
fix: stop the spark exit background job with no exit to drive
ovitrif Nov 11, 2026
379a5dc
fix: show spark exit funding amounts in bitcoin
ovitrif Nov 11, 2026
8931678
fix: show a confirmed spark exit leftover sweep as sent
ovitrif Nov 11, 2026
345d053
docs: point the exit journey at its ios twin
ovitrif Nov 11, 2026
66c5f70
test: order the spark exit imports of the app view model test
ovitrif Nov 11, 2026
dee1db5
fix: resume a valid spark exit generation after a killed rebuild
ovitrif Nov 11, 2026
7998af4
chore: merge feat/breez-spark-lightning into feat/spark-emergency-exit
ovitrif Nov 11, 2026
de2e53e
Merge remote-tracking branch 'origin/feat/spark-emergency-exit' into …
ovitrif Nov 11, 2026
72b8221
fix: refuse a spark exit start while a send is still active
ovitrif Nov 11, 2026
2d160e7
docs: record the ported ios spark exit journey
ovitrif Nov 11, 2026
c2a663f
fix: keep sending a valid spark exit generation while its rebuild ask…
ovitrif Nov 11, 2026
124d661
fix: leave lost leaves out of what stays on spark during an exit
ovitrif Nov 11, 2026
c92648e
fix: forget a spark exit start once its exit ends
ovitrif Nov 11, 2026
1eaf803
fix: keep a valid spark exit generation over a failed-only unverified…
ovitrif Nov 11, 2026
6bcd356
fix: read a spark exit step already in the utxo set as accepted
ovitrif Nov 11, 2026
f723f4e
fix: stop sending a spark exit generation that diverged during a top-up
ovitrif Nov 11, 2026
caa349d
fix: count left-behind leaves on spark, not in the exit transfer
ovitrif Nov 11, 2026
8de5af3
fix: keep the value of leaves the first spark exit build leaves behind
ovitrif Nov 11, 2026
d61eb02
fix: connect spark again for an exit whose reconnect failed
ovitrif Nov 11, 2026
4bcb750
fix: give a forgotten spark exit's funding address back
ovitrif Nov 11, 2026
496aaee
fix: pay from savings only what the spark exit funding address lacks
ovitrif Nov 11, 2026
e83afd5
fix: show kept spark exit fee change once with its recovery details
ovitrif Nov 11, 2026
b5b8227
fix: delete the spark exit record's copies on wipe
ovitrif Nov 11, 2026
018dd7b
fix: saturate the refused spark exit sweep rate on overflow
ovitrif Nov 11, 2026
3c8dde6
Merge remote-tracking branch 'origin/master' into HEAD
ovitrif Nov 11, 2026
35ad086
fix: keep kept fee change's recovery details reachable
ovitrif Nov 11, 2026
c671dfa
fix: refresh wallet balances when exit funding arrives
ovitrif Nov 11, 2026
72245e3
fix: keep the valid exit generation when funding an unverified rebuild
ovitrif Nov 11, 2026
e4ad61a
fix: drop an unverified rebuild's fee ask once its steps read again
ovitrif Nov 11, 2026
7c43beb
fix: cap a refused sweep rate so the exit record still loads
ovitrif Nov 11, 2026
81aaad7
fix: forget an earlier exit's funding reading when a quote loads
ovitrif Nov 11, 2026
8a9ac7b
fix: keep left-behind exit leaves in spending after a sync
ovitrif Nov 11, 2026
f9f30be
fix: keep a cancelled exit's start from opening progress
ovitrif Nov 11, 2026
4a555d2
fix: never drive a diverged exit generation from an unverified ask
ovitrif Nov 11, 2026
40662e5
test: round-trip the review's refused sweep rate
ovitrif Nov 11, 2026
f65a9c5
fix: ignore fee estimates no node would ask for
ovitrif Nov 11, 2026
d998ce8
fix: rebuild a diverged exit from its funding when a top-up is dropped
ovitrif Nov 11, 2026
523506d
feat: keep earlier spark exit addresses past their record
ovitrif Nov 11, 2026
aace83c
fix: let a new exit start after an earlier one kept its change
ovitrif Nov 11, 2026
3507f25
feat: watch a cancelled spark exit's address for a late payment
ovitrif Nov 11, 2026
4100dec
feat: show earlier spark exit addresses on spark details
ovitrif Nov 11, 2026
d916940
refactor: split the exit's funding build out of the tick
ovitrif Nov 11, 2026
223194e
fix: keep a loss alert posted when an exit's fee ask ends
ovitrif Nov 11, 2026
62d696a
fix: keep the valid exit generation over a rebuild that skips an unre…
ovitrif Nov 11, 2026
7fa31f7
Merge remote-tracking branch 'origin/master' into HEAD
ovitrif Nov 11, 2026
f1bbfe4
fix: refuse move to spark while an exit holds spark
ovitrif Nov 11, 2026
5b6da91
fix: keep the retry clock after a funded unverified rebuild
ovitrif Nov 11, 2026
20d4be0
fix: let a refused leftover sweep show once
ovitrif Nov 11, 2026
a8652b9
fix: read kept change at earlier exit addresses
ovitrif Nov 11, 2026
712ae34
docs: fix kept change comment
ovitrif Nov 11, 2026
52e5d34
fix: guard every rebuild over a valid exit generation
ovitrif Nov 11, 2026
4111d43
test: keep the valid generation after a leaf is left behind
ovitrif Nov 11, 2026
d350091
fix: pace a funded unverified resume once a block
ovitrif Nov 11, 2026
77b2d92
chore: order the earlier exit address strings
ovitrif Nov 11, 2026
be0fb11
fix: keep reading kept change at a reused address
ovitrif Nov 11, 2026
6b05083
fix: keep the valid generation over an unexitable leaf
ovitrif Nov 11, 2026
4f67dd8
fix: fund the exit from savings only on spark's chain
ovitrif Nov 11, 2026
3d4e52b
fix: keep the higher spark exit funding index on restore
ovitrif Nov 11, 2026
92d2404
fix: find the spark exit funding index after a restore without one
ovitrif Nov 11, 2026
ac75f59
fix: back up the earlier spark exit addresses
ovitrif Nov 11, 2026
46e4fb2
fix: watch earlier exits' funding that still holds coins after a restore
ovitrif Nov 11, 2026
648e730
chore: merge master into the spark exit branch
ovitrif Nov 11, 2026
79752a8
fix: build a kept fee bump at its rate
ovitrif Nov 11, 2026
24c5fed
fix: pay a higher fee from savings only on spark's chain
ovitrif Nov 11, 2026
cdb9f36
Merge pull request #1832 from synonymdev/feat/spark-exit-app-status
ovitrif Nov 12, 2026
1068574
Merge remote-tracking branch 'origin/master' into HEAD
ovitrif Nov 12, 2026
6bc1e3c
fix: keep an exit's earlier addresses when two writers update them at…
ovitrif Nov 12, 2026
126436b
fix: lightning connection reads using spark only outside an exit
ovitrif Nov 12, 2026
b2e809b
chore: changelog fragment for the exit lightning connection fix
ovitrif Nov 12, 2026
46c16d1
fix: find a restored wallet's exit funding past its backed-up index
ovitrif Nov 12, 2026
46cca49
Merge pull request #1880 from synonymdev/fix/spark-exit-using-spark
ovitrif Nov 12, 2026
d0f2a45
Merge remote-tracking branch 'origin/master' into HEAD
ovitrif Nov 12, 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
117 changes: 117 additions & 0 deletions app/src/androidTest/java/to/bitkit/services/SparkExitRegtestTest.kt
Original file line number Diff line number Diff line change
@@ -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)
}
}
9 changes: 9 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,15 @@
</intent-filter>
</receiver>

<receiver
android:name=".repositories.SparkExitReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>

<provider
android:name="androidx.startup.InitializationProvider"
android:authorities="${applicationId}.androidx-startup"
Expand Down
5 changes: 5 additions & 0 deletions app/src/main/java/to/bitkit/App.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import to.bitkit.appwidget.AppWidgetRefreshReason
import to.bitkit.appwidget.AppWidgetRefreshScheduler
import to.bitkit.env.Env
import to.bitkit.repositories.HwWalletRepo
import to.bitkit.repositories.SparkExitWork
import to.bitkit.services.BluetoothInit
import to.bitkit.services.PubkyAuthHandlerRegistrar
import to.bitkit.utils.Crypto
Expand All @@ -43,6 +44,9 @@ internal open class App : Application(), Configuration.Provider {
@Inject
lateinit var subscriptionClockOffsetSync: SubscriptionClockOffsetSync

@Inject
lateinit var sparkExitWork: SparkExitWork

/** Resolved only once the process changes foreground state, so startup does not build the wallet graph. */
@Inject
lateinit var hwWalletRepo: Lazy<HwWalletRepo>
Expand All @@ -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()
Expand Down
16 changes: 16 additions & 0 deletions app/src/main/java/to/bitkit/data/CacheStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, String> = 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<String, Int> = 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<String> = 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. */
Expand Down
3 changes: 3 additions & 0 deletions app/src/main/java/to/bitkit/data/dao/TransferDao.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
20 changes: 20 additions & 0 deletions app/src/main/java/to/bitkit/env/Env.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
4 changes: 4 additions & 0 deletions app/src/main/java/to/bitkit/ext/Context.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
17 changes: 17 additions & 0 deletions app/src/main/java/to/bitkit/models/BackupPayloads.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,23 @@ data class MetadataBackupV1(
val pubkyContactProfileOverrides: Map<String, PubkyProfileData>? = null,
/** User-set hardware wallet names, keyed by wallet id. Null in envelopes written before this field. */
val hwWalletNames: Map<String, String>? = 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<String, List<SparkExitEarlierAddressBackupV1>>? = 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
Expand Down
7 changes: 5 additions & 2 deletions app/src/main/java/to/bitkit/models/TransferType.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
39 changes: 39 additions & 0 deletions app/src/main/java/to/bitkit/repositories/BackupRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<String, List<SparkExitEarlierAddressBackupV1>>? {
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<String, List<SparkExitEarlierAddressBackupV1>>?) {
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
Expand Down Expand Up @@ -1213,6 +1242,7 @@ class BackupRepo @Inject constructor(
)
val parsed = decodeBackup<MetadataBackupV1>(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 {
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/to/bitkit/repositories/HealthRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/java/to/bitkit/repositories/LightningRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2434,6 +2434,8 @@ class LightningRepo @Inject constructor(
speed: TransactionSpeed? = null,
utxosToSpend: List<SpendableUtxo>? = 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<ULong> = withContext(bgDispatcher) {
runCatching {
val transactionSpeed = speed ?: settingsStore.data.first().defaultTransactionSpeed
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ object MoveToSparkMath {
fun movableSats(channels: List<ChannelDetails>?): 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<ChannelDetails>?, spark: SparkState): Boolean =
Expand Down
Loading
Loading