Repository navigation
feat: resume unfinished swaps until their claim confirms - #1386
coreyphillips wants to merge 7 commits into
Conversation
[Medium impact] The PR affects the Pubky Swaps payment workflow. Fix uncertain-send cleanup and foreground waits surviving a wipe before merging. FindingsSummarySaves unfinished Pubky swaps and their hold payments, then resumes them on wallet startup.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Commit swap] --> B[Save swap and hold payment]
B --> C[Send hold payment]
C -->|Returns| D[Wait for claim broadcast]
D --> E[Poll until claim confirms]
F[Wallet startup] --> E
E -->|Confirmed or failed| G[Forget swap]
C -->|Uncertain Spark error| H[Swap incorrectly forgotten]
I[Wallet wipe] --> J[Cancel background loops]
I --> K[Foreground wait remains active]
K --> E
Reviews (1) · Last reviewed commit: "feat: resume unfinished swaps until thei..." · Reviewed by Greptile |
talosmachina
left a comment
There was a problem hiding this comment.
1 finding (P2). Keeps committed and restored Pubky Swaps routes advancing across launches until the claim confirms, and stops a swap whose hold payment failed. Reviewed c049ace, full tier, static: an auto review never builds a Bitkit app branch, so this is read from the code and CI.
What I checked, and 5 candidates I ruled out
Read in full: PubkySwapsTracker.swift, the PubkySwapsRouteService.swift diff, the SendConfirmationView.swift swap send and driveSwapClaim, AppScene.startWallet and restorePubkySwaps, LightningService.send(bolt11:)
Traced into bitkit-core 0.8.0-rc15 (045c7ff): pubky_swaps_advance / advance_swap, claim::next_step, store::load (the NotFound that isUnknownSwap keys on)
CI: SwiftFormat, validate and Greptile green; Run Tests, Run Integration Tests and build-local still pending at the time of this review
Ruled out
- Unbounded background loop now that the hour cap is gone:
next_stepreportsFailedwhen no lockup appears by the timeout and when the lockup is spent without the preimage, so a swap whose claim never confirms still ends. - A resumed loop and the send flow's
awaitClaimadvancing one swap at once:resume()skips ids inclaiming, and bitkit-core serialisesadvance_swapper swap id withadvancing_lockanyway. - A wipe leaving a loop that re-tracks its swap:
awaitConfirmationreturns on cancellation beforestore.untrack, andresetForWipeclears both keys. - A swap bitkit-core does not know polling forever:
store::loadreturnsPubkySwapError::NotFoundfor a missing record, whichpollClaimrethrows and the loop untracks. - Stale Spark failure dropping a swap retried over a channel:
emitChannelFreeRailEventfiltersisStaleFailurebefore thepaymentFailedhandler indriveSwapClaimsees it.
Merge confidence: 4/5, one P2 on a narrow path, and the unit and integration runs had not finished.
Reviewer model: claude-opus-5-5
Reasoning effort: Unknown (the run metadata available to this review does not carry it)
| /// swaps returned leave it out. | ||
| func adoptRestored(restored: [String], known: [String]) -> (restored: [String], known: [String]) { | ||
| let known = known.filter { !committed.contains($0) && !dropped.contains($0) } | ||
| store.track(restored + known) |
There was a problem hiding this comment.
Restoring a swap saves its ID, but drops the link to its hold payment. Restore can pick up a pending hold, so if it later fails, the tracker keeps advancing the swap even after a relaunch. Could we keep the hold payment association for restored swaps too?
There was a problem hiding this comment.
Agreed, but the app can't make the link with today's bitkit-core: the restore report lists only swap IDs, and a swap rebuilt from a provider's listing keeps no hold invoice. bitkit-core can derive any swap's payment hash (record_payment_hash), so the fix is to return payment_hash_hex in PubkySwapRouteStatus; the tracker then records it on the first advance and checks the node's payment by hash (restore only adopts swaps whose payment the node sent). That needs a bitkit-core release, so it's tracked in synonymdev/bitkit-core#232. Leaving this open until it lands.
jvsena42
left a comment
There was a problem hiding this comment.
Code scan at c049ace: one LOW inline (dev-gated). No double-claim, wrong-address or lost-funds path beyond the threads already open.
Checked and clean:
- Double claim: bitkit-core serialises per swap (
advancing_lock), saves the claim before broadcasting and rebroadcasts only a saved tx that spends the found lockup.resume()skips ids inclaiming, andadvanceInBackgroundis one task per id. - Destination: the app store holds only swap ids and the hold payment. The address comes from the core record, and resume passes none.
- The hold-failure check returns true only when Spark reports
failedfor that invoice, or when the node lists it failed and Spark shows no send. A stopped node, an unconnected rail or a throwing rail all return false, and one swap sends its hold over one rail only. Failedfromnext_stepmeans no lockup at the timeout, a lockup spent without the preimage, or an unpublished claim too close to the timeout. A published claim is rebroadcast regardless, so untracking onfaileddoes not abandon a claimable swap.- Kill points (before and after
didCommit, mid-send, between the twountrackwrites) leave nothing harmful. Wipe clears both keys, and cancelled loops return beforeuntrack. - v3.1.1 has no Pubky Swaps code, so the two new UserDefaults keys have no earlier format.
- synonymdev/bitkit-core#190 (Boltz removal) does not touch
pubky_swaps. The neighbouringensureSwapUpdatesRunning()line may conflict textually.
Addendum to the open AppScene.swift:1195 thread: node starts that bypass startWallet (retryWalletStart :1364, NodeStateView.swift:63,71, AppStatusView.swift:60,68, SendFailure.swift:178) also skip resume(), so the fix there should cover them.
The Android twin (synonymdev/bitkit-android#1923, merged) has the same uncapped background loop.
perf: relevant (polling now runs for the app's whole foreground lifetime per unfinished swap). To measure: Electrum connections and requests per minute per swap, Spark status calls per minute for a Spark-paid hold, and time from relaunch to claim broadcast.
Device gate (partial): c049ace — not run yet; a relaunch with an unfinished swap on regtest and the request rates above. Result to follow.
Reviewer model: Opus 5.5 (claude-opus-5-5) coordinating and verifying; Fable 5.2 (claude-fable-5-2) primary review
Reasoning effort: Not exposed
jvsena42
left a comment
There was a problem hiding this comment.
Approving at c049ace with the one LOW open (no backoff when advance keeps throwing). Fix it here or in a follow-up issue, your choice; please reply on the thread with which.
Device gate: c049ace — manual tests: 1 passed (3 runs), 2 passed (both variants); perf: 1 advance per 30 s per unfinished swap = about 2 Electrum connections and 6 requests per minute; unreachable Electrum: an advance attempt every 30–31 s with no backoff (the LOW); l10n: no UI text changed
- Setup: debug build launched with
PUBKY_SWAPS_ROUTES, the bitkit-dockerpubky-swapprovider, a fixture issuer contact with only an on-chain endpoint, and the local regtest chain on an iPhone 17 Pro simulator. - Test 1 (force quit before the claim, mine, relaunch): three swaps claimed after relaunch, 10 s, 13 s and 15 s from launch to
claimBroadcast, and confirmed 25–30 s after the next block. On swap 1d3f7970, for example, claim aba71736… spends the lockup and pays exactly 20 000 sats to the issuer, and the provider logged "client claimed; hold invoice settled". Each swap was untracked afterwards (unfinishedPubkySwapsempty). - Test 2: the hold was made to fail with the provider paused after the commit, then
lncli cancelinvoice.- With the send still open, the app logged "Stopping Pubky Swaps route … after its hold payment failed" 3 s after the cancel, and logged nothing for that swap in the 80 s after relaunch.
- With the app closed, relaunch logged
holdFailed13 s after launch and emptied both keys. A second relaunch was silent for 85 s.
- Counted through a per-swap Electrum proxy:
- Each
awaitingLockupadvance is 1 connection and 3 requests. - The claiming advance is 2 connections and 6 requests.
- With the proxy down, 7 consecutive
Failed to advance Pubky Swaps route … Connection refusedlines came at 30–31 s intervals. The next tick after recovery claimed.
- Each
⚠️ Not verified: 5-minute count windows and a relaunch while Electrum is unreachable. On the second run the provider stopped answering quote requests after the first swap (iroh relay disconnects in its log), so tests 2 and 3 above come from the runbook author's run at this head.
CI at c049ace: green.
Reviewer model: Opus 5.5 (claude-opus-5-5) coordinating and verifying; Fable 5.2 (claude-fable-5-2) primary review and runbook (runbook effort: medium, run record); Sonnet 5.5 (claude-sonnet-5-5) device driver
Reasoning effort: Not exposed, except where noted
…hed-swaps # Conflicts: # Bitkit/AppScene.swift # Bitkit/Utilities/AppReset.swift
A hold payment whose send threw after Spark submitted it may still go out, so the swap now continues as paid: pending, with its claim driven and stopped if the hold payment fails. Only a refusal that proves nothing left the wallet drops the swap.
A wipe now ends a claim wait still running at its next step, and an answer that arrives after the wipe no longer restarts the background loop, which would advance the wiped wallet's swap with whatever seed is current.
The background loop now doubles its wait after each advance that failed in a row, up to 64 intervals (32 minutes at 30 seconds), and resets on any answer, so a swap whose Electrum server stays unreachable no longer retries every 30 seconds forever. A claim wait keeps its fixed interval. The test is jvsena42's.
Swaps resumed only after the launch's activity sync, which can throw after the node starts, and the automatic retries see a running node, so a paid swap could wait for the next launch. The wallet now resumes them on every node start, before anything that can throw.
The test target compiles its own copy of Errors.swift, so an unqualified AppError there is a type the app classifier does not recognize.
|
@jvsena42 could you re-approve when you get a chance? Since your approval I merged master ( |
Fixes #1262
Twin: synonymdev/bitkit-android#1923
Description
Out of Scope
paymentFailed.Design
N/A: no UI changes.
Preview
N/A
QA Notes
Setup
A regtest debug build with
PUBKY_SWAPS_ROUTESon, a reachable Pubky Swaps provider, and a contact with only an on-chain endpoint.Journeys
N/A: not drivable; see Manual Tests.
Manual Tests
Automated Checks
PubkySwapsTrackerTests.swift: a committed swap is kept for the next launch, resume advances until the claim confirms, transient failures keep it advancing, a failed, unknown or hold-failed swap is forgotten, restores leave this session's swaps to the send flow, and a wipe forgets every swap.Evidence
c049ace, iPhone 17 simulator, bitkit-core 0.8.0-rc15: SwiftFormat lint passes; the CI test selection passes (4,164 unit tests).Gaps