Repository navigation
Conversation
Moves the Spark balance on-chain without the Spark operators: quote, fee funding from Savings or another wallet, swipe to start, then a driver that builds, broadcasts and checks the SDK's recovery until it lands in Savings, after restarts and from background tasks too. Lost leaves are given up, fee funding left over is swept to Savings, and Spark stops sending, receiving and optimizing leaves while the exit runs.
This was referenced Nov 5, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Twin: synonymdev/bitkit-android#1782
Stacked on #1128
This PR adds Emergency exit, Spark's unilateral exit, so users can move their Spark balance to Savings on-chain without the Spark operators. It builds on the Spark wallet in #1128, which already backs up Spark's exit data to VSS as
SPARK_EXIT.Description
Screens and flow
prepareRecoverFundsat its fastest recommended rate: amount, network fees, what arrives, fee funding, what stays on Spark. Continue is off when nothing is recoverable or the fees exceed the value;SPARK_EXITtransfer to Savings: Home and Savings show it in transfer with the countdown from its timelock, settled when the sweep reaches Savings. While it runs, Spark neither sends nor receives Lightning, Spark reconnects with leaf optimization off so no swap hands an exiting leaf to someone else, and its balance counts only as in transfer. The result lists what stayed on Spark: leaves too small to exit and cooperative leaves the operators did not sign.Building and broadcasting
m/84'/{coin}'/7797'/0/{i}, with a fresh index for each exit kept in its record (older records use 0), an account no Bitkit wallet uses, so ldk-node never spends the funding UTXO or the CPFP change chained to it;singleKeyCpfpSignersigns with it. The exit builds only once the funding UTXO confirms, read from the SDK's own chain host.POST /api/v1/txs/packageas a JSON array, others toPOST /api/tx, on the hosts the SDK reads from (mempool.space then blockstream.info on mainnet, Spark's regtest mempool on dev). Node answers are classified: already known counts as accepted, missing inputs and non-final are retried, anything else is shown after 3 refusals.check-recover-fundsreads it too. ARedoverdict is saved first and rebuilds a new generation; the old one is never sent again.min relay fee not met, 0 < 17) whilecheckRecoverFundsstill answers Valid. Before broadcasting, the exit looks up each of its children that a pending step builds on and whose node is confirmed. When no chain host has that child, the exit rebuilds from the same funding and never sends the dead chain again. As a fallback, a step whose parents are confirmed and whose fee chain fails 3 times in a row (min relay fee not met, 0 <or missing inputs) rebuilds the exit once, and those failures don't count as refusals until then.non-BIP68-finalis never counted as a refusal. A step whose own input another transaction spent is not sent again until the next SDK check rebuilds.Background run
BGAppRefreshTask(to.bitkit.spark-exit, 25 s budget, earliest 15 minutes) and aBGProcessingTaskthat needs the network (to.bitkit.spark-exit.processing, 4 minute budget, earliest 30 minutes) run the same step from a cold launch with no UI: load the record, send the stored, already signed steps whose parents confirmed without the SDK, start the Spark SDK alone (never ldk-node) within the time left, then check, sign a build or rebuild, broadcast, save and resubmit both tasks.Info.plistpermits both identifiers and thefetchandprocessingbackground modes.Notifications
Funding and the leftover sweep
InsufficientCpfpFundsnames the total all inputs must hold, so the shortfall is that total less what the inputs hold at the funding address now: the unspent inputs and the CPFP change chained from them, this generation's and earlier ones'. Several small payments that together cover it are all adopted, and Payment seen counts only new funding. In a regtest run, the exit had asked for 9,085 more when 50 were missing.Lost leaves and the fee ladder
prepareRecoverFundswithAll, which can't abort: a leaf that can't pay its refund's fee at the chosen rate, such as a fee-ladder leaf, is listed underskippedasFeeExceedsValueand stays on Spark.Specificwith the exit's leaves, which aborts as a whole when one anchorless fee-ladder leaf can't pay its own refund, with an untypedSparkErrornaming the leaf. The app drops that leaf from the exit and prepares again, and falls back toRecoverableOnlywhen the error names no leaf.Out of Scope
SPARK_EXITexit data backup: in feat: add spark via breez sdk #1128.Risks for review
Allselection, which the exit uses so it can take leaves still in the balance, for when the operators are unreachable or refuse to serve; with healthy operators, Transfer to Savings stays the cheaper way out, and the explainer says so.Design
N/A — no design available.
Preview
Emergency exit on aa01843 against Spark's hosted regtest, with notifications denied. Pay from savings: explainer, the quote naming the 9,789 sats it can't exit, Pay from savings, the permission prompt, Confirm with the notifications note, then Progress showing the payment as paid with its transaction ID and no QR, and Cancel exit (on dev that payment goes to Bitkit's staging chain, so it never confirms on Spark's). Fund from another wallet: the faucet pays the funding address, Payment seen, then Progress waits for it with its transaction ID until it confirms, and the exit builds 28 transactions and starts publishing; the wait for the faucet is cut.
e1-exit-start2x.mp4
e2-cut2x.mp4
A full exit at 030de21 on the local Spark regtest stack (iOS 26.5): the start, paid from Savings, and the end, where the timelock counts down and the sweep lands 91,288 sats in Savings. This build predates the fixes above, so after paying it still shows the QR.
q1-exit-start2x.mp4
q2-exit-end2x.mp4
UI pass on an iPhone SE (375 pt), rendered with stubbed state by a local hook that is not in this PR: the Start exit? headline was cut to one line, and the exit quote's note was in the all-caps caption style. Content now scrolls above the buttons, and the notes read as body text.
The funding address view scrolls its QR on the SE, and Start exit? on an iPhone 17.
Screens
Every exit screen, on an iPhone 17 simulator in Bitkit's dark theme, rendered with stubbed state by a local hook that is not in this PR.
QA Notes
Setup
regtest/localsetup (the last public operator), with bitcoind, 3 operators, the SSP, electrs and mempool, mined on demand. Two patches make SDK 0.27.2 work with that operator: the operator skips theRETURNEDstatus filter it does not know, and the wallet turns fee ladders off, so every leaf there is an anchored leaf.prepareRecoverFundswithAll, thenSpecificon a rebuild,recoverFundswith a single-key CPFP signer,checkRecoverFunds, package broadcast through mempool), each step a separate process resuming from storage.Journeys
N/A — iOS has no exit journey; the exit needs Spark's regtest faucet and hours of blocks, which the journey environment lacks.
Manual Tests
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"to.bitkit.spark-exit"], continue → the log showsSpark exit background run: connected=truewith the time per step; repeat withto.bitkit.spark-exit.processing, then once more followed by_simulateExpirationForTaskWithIdentifier:→ the run stops, and the next run sends nothing already accepted. Turn Background App Refresh off for Bitkit → Progress shows the note; Low Power Mode on → its note — the simulator has noBGTaskScheduler.non-BIP68-finalnever counts toward the 3-refusal alert — same.Automated Checks
SparkExitTests.swift— the background entry point from a cold start sends stored steps and then checks with the SDK only, signs a build once funding confirmed, stays keyless when Spark does not connect or time is short, and after an expiry mid-broadcast leaves a whole record from which the next run sends nothing twice; reminders are planned at each unpublished timelock plus the grace, dropped once a step is published, sent at once for fee funding and repeated refusals, and after a stall while steps wait for parents; the record round-trips with every status, error and input variant; the recovery is written in spark-sdk's serde shape and a CLI-written one reads back; an unknown version is refused; the driver waits for a confirmed funding UTXO, saves before broadcasting, broadcasts ready steps once until due, surfaces repeated refusals, finishes on Done with the leftover read, rebuilds a new generation on Redo after saving it, asks only for what the inputs lack onInsufficientCpfpFunds, adopts several small payments together and ignores CPFP change at the funding address, resumes after a restart without repeating broadcasts, retries cooperative leaves the operators could not sign, and broadcasts without the SDK only steps whose parents confirmed and timelocks matured; a leaf whose refund two rebuilds reproduce after its input was spent is lost, alone or with every leaf (the exit stops); a rebuild leaves behind a leaf that cannot pay its refund and retries, falls back toRecoverableOnlywhen the error names no leaf, and stops when none is left; the quote math, funding states, funding key path, the package and single broadcasts, path and host fallback, and the node answer classifierSparkExitSweepTests.swift— the leftover sweep spends every UTXO at the funding address to Savings less its fee, each input's signature verifies against its BIP143 digest with libsecp256k1, a leftover under dust after the fee is skipped, output scripts for every address type, an ended exit keeps its result reachable until the sweep confirms, and a background run sweeps without starting SparkSparkExitRegtestTests.swift— opt-in (TEST_RUNNER_SPARK_EXIT_REGTEST=1): a fresh wallet on Spark's hosted regtest connects and quotes an empty exit, the chain host serves the tip and funding UTXOs, a fake parent and child package reaches the live node and is read as retry later, and the background entry point runs from a cold start over an exit of the live run's shapeSparkExitTests.swiftalso covers a fee chain that lost a race, with the operators down and the check answering Valid (rebuilt from the same funding, the dead chain never resent), a child still in the mempool, the safety net's single rebuild before the step's refusals surface, the chain host's not-found lookup, and the needs-funding amount never under the 294-sat dust limit, and a replay of a single-leaf exit an older state claimed, which across its rebuilds delivers only the lost notificationSparkConfigTests.swift— leaf optimization is on, and off while an exit runsTest results
QA:
Tested on an iPhone 17 Pro simulator (iOS 27.0) against Spark's hosted regtest, and on an iPhone 17 Pro simulator (iOS 26.5) against a local Spark regtest stack (QA Notes, Setup).
Device tests skipped⚠️ :
BGTaskScheduler(4).🟢 Exit paid from savings, Exit funded from another wallet
Exit paid from savings
1 and 5 at aa01843: the quote read 90,112 to exit, 7,969 in fees, about 82,143 received, 8,257 of fee funding and 9,789 staying on Spark, named as balance it can't exit; Pay from savings sent 8,679 from Savings, and Progress showed it as paid with its transaction ID and no QR, with the notifications note after permission was denied; recording under Preview.
Exit funded from another wallet
6, and 2 up to publishing, at aa01843: the faucet paid 8,257 to the funding address; Funding showed Payment seen, Progress waited for it with its transaction ID, and once it confirmed the exit built 28 transactions and published the first two; recording under Preview.
🟢 Full exit to Savings, Resume after a kill
Full exit to Savings
On the local stack at 030de21, with the operators running: a 100,000 sat Spark balance quoted 90,112 to exit, 4,855 in fees and 6,031 of fee funding; Pay from savings sent 6,453 (the funding plus its fee). The app published each refund once the 1,900-block timelock matured, before the operators' 1,950-block version, and sweep
02c28284…confirmed at height 9,246, paying 91,288 sats to Savings (90,112 − 4,855 + 6,031). The result read "Exit complete. Your funds are in savings. 18 small amounts stayed on Spark."; recordings under Preview. That build still asked to send the funding after paying it, which 169ff91 fixes.Resume after a kill
Bitkit terminated at 6 of 22 transactions with one block mined while closed reconnected on relaunch and broadcast the next packages.
🟢 Rerun on the fixes, Failed exit
Rerun on the fixes
On the local stack at 674f0da, one simulator wallet, two exits, leaf optimization off in the test build:
Failed exit
At 41d8569: a single-leaf exit (32,768, received straight from a previous owner) with the operators down, where the previous owner's older refund won while the app was closed. About 16 minutes after relaunch the app dropped the leaf, swept the 626 leftover to Savings and showed two notifications. Emergency exit kept the result until it was opened once ("Exit stopped", "₿ 32,768 was claimed on-chain by an older owner of these funds and can't be recovered", and the leftover line); the next opening showed the fresh intro.
🟢 Operators stopped, Operators broadcast first, Funding short, Stale state
Headless runs through the harness, all at 2 sat/vB, each wallet funded with a 100,000 sat deposit (99,865 after the claim fee), which the SSP splits into 17 power-of-two leaves.
Operators stopped
With all 3 operators stopped, SDK 0.27.2 connected in 29 ms, quoted from local storage in 0.1 s and built 25 transactions (1 fan-out, 19 node packages, 4 refunds with a 1,900-block CSV, 1 sweep); every package was accepted. 4 leaves (90,112 sats) went out, 13 leaves (9,753 sats) were skipped as
FeeExceedsValue, and 91,680 sats reached the destination (90,112 plus 1,568 unused funding through the sweep) over 1,961 blocks, about 13.6 days on mainnet.Operators broadcast first
With the app asleep 60 blocks past maturity, the operators' watchtower broadcast its own refunds (1,950-block CSV, fee from the leaf); the next check returned
Redo(OnChainStateDiverged), theSpecificrebuild of the same 4 leaves needed no funding, and the exit reached Done with 85,749 sats. The 5,035 sats of first-generation change it left behind are what the leftover sweep now sends to Savings.Funding short
With 9,035 sats over 5 UTXOs against a 8,541 quote,
recoverFundsfailed withInsufficientCpfpFundsasking for 9,085 in total; a 1,000 sat top-up was adopted with the earlier UTXOs, and the exit reached Done. The app now asks for the 50 missing instead of 9,085.Stale state
A previous owner broadcast its older refund for a 16,384 sat leaf once it matured, 100 blocks after the current owner's, while the current owner slept, and swept it. The current owner's check returned
Redo, and each rebuild reproduced refundbe4def69…, refused asbad-txns-inputs-missingorspent. The app now drops such a leaf after two identical rebuilds (Rerun on the fixes). With the operators down, the 100 blocks after each maturity are the hard deadline, about 16 hours on mainnet.Evidence
5d18a238: the exit tests and the unit tests (CI's selection) pass on an iPhone 16 simulator (iOS 27.0); SwiftFormat passes.46ae7556: the exit tests and the unit suite (CI's selection) pass on an iPhone 16 simulator (iOS 27.0); SwiftFormat passes.174d9ed7: the exit tests and the unit suite (CI's selection) pass on an iPhone 17 Pro simulator (iOS 27.0); SwiftFormat and the translation check pass.022d3ed2: the exit tests and the unit suite pass on an iPhone 17 simulator (iOS 27.0).335182af: the unit suite and the exit tests pass on an iPhone 17 simulator (iOS 27.0). Against Spark's hosted regtest, the background entry point from a cold start, over a stored exit of 30 steps: keyless pass 1.03 s (7.00 s before status reads ran concurrently), SDK connect 0.03 s (before the SDK's own sync),checkRecoverFundson one real step 0.55 s (0.17 s warm), one package broadcast to the live node 0.17 s,prepareRecoverFunds0.55 s, whole run 1.26 s against a 25 s refresh budget; the process footprint grew by about 2 MB (25 to 27 MB, in a test host with no UI).f6d639cb:SparkExitRegtestTestspasses against Spark's hosted regtest (empty-wallet quote, chain reads, a live package answer).Open
BGTaskScheduleron a real device. The simulator has noBGTaskScheduler, so the OS granting and expiring the exit's tasks is not exercised (4).