Skip to content

fix: find exit funding past a restored counter - #1305

Merged
ovitrif merged 3 commits into
feat/breez-spark-lightningfrom
fix/spark-exit-restore-scan-forward
Nov 12, 2026
Merged

ovitrif merged 3 commits into
feat/breez-spark-lightningfrom
fix/spark-exit-restore-scan-forward

Conversation

@ovitrif

@ovitrif ovitrif commented Nov 12, 2026 •

Copy link
Copy Markdown
Collaborator

Twin: synonymdev/bitkit-android#1782

Description

  • After a restore, the emergency exit now scans the funding addresses forward from the restored funding counter as well as reading every address below it. The counter's backup can predate the last exit's funding, for example when the metadata backup didn't land before the device was lost. Before, an exit funded at the counter's own address stayed hidden after the restore: its coins weren't listed under the earlier exit addresses, and the next exit quoted that address again.
  • While a restore is pending, an exit quote now runs that scan before it picks its funding index. If the scan fails, the quote fails, so a quote taken right after a restore can't reuse a lost exit's address. A start never lowers a counter the scan moved.
  • A forgotten exit's funding address that got a late payment is listed again as kept change once the scan moves the counter past it, so it stays watched.
  • The forward scan reads up to its ceiling of addresses from where it starts, so a restored counter of 1,000 or more still looks forward.
  • The scan costs about 20 address reads, once per restore, and only when a restore is pending.
  • Same fix as the Android twin (46c16d103). The twin's second fix, which keeps the restore pending when listing an address fails, isn't needed here: recoverFunding already throws before it clears the pending flag.

Design

N/A — no UI changes.

Preview

N/A

QA Notes

Automated Checks

  • SparkExitFundingIndexTests.testARestoredCounterThatPredatesTheLastExitsFundingFindsItsCoins: with counter 3 restored and address 3 funded, address 3's coins are listed and the counter moves to 4.
  • testAQuoteWhileARestoreIsPendingScansPastTheRestoredCounterFirst and testAQuoteWhileARestoreIsPendingFailsWhenTheScanFails: a quote after the restore funds from address 4 and lists address 3's coins; a failed scan fails the quote and keeps the restore pending.
  • testARestoredCounterAtAForgottenExitsAddressListsItsLatePaymentAsKeptChange: a forgotten exit's address with a late payment becomes kept change.
  • testARestoredCounterPastTheScanCeilingStillScansForward: counter 1,000 restored, address 1,000's coins are found.
  • testARestoredCounterBringsBackTheFundingAddressesThatStillHoldCoins now expects the forward scan's reads, 3 to 22. testAFundingIndexRestoredFromTheBackupIsOnlyScannedForwardFrom (renamed) expects only the forward reads.
  • SwiftFormat 0.64.6 lint is clean locally; CI runs the unit tests.

Not tested

  • No device run: staging it needs a restore whose backup missed the last exit's counter. The unit tests cover both paths.

@ovitrif ovitrif self-assigned this Nov 12, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T10:55:44.314170Z f53eb9d PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@ovitrif ovitrif added this to the 3.2.0 milestone Nov 12, 2026
@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

Triage: milestone 3.2.0. This PR fixes the 3.2.0 Spark emergency exit after a restore and closes no issue, so it carries the milestone itself.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f53eb9dd92

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread Bitkit/Managers/SparkExitManager.swift Resolved
@greptile-apps

greptile-apps Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change reaches Spark exit recovery for wallets with a pending restore.

Hold merging until quotes wait for successful funding recovery.

Findings

  1. P1 Quotes can reuse old funding ▶
  2. P2 High counters skip recovery ▶

Summary

Adds a forward scan from the restored funding counter and a test for finding coins at that counter.

  • Spark exit recovery finds coins at addresses beyond a restored counter.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Restored funding counter] --> B[Recover funding]
    B --> C[Scan forward]
    C --> D[List addresses holding coins]
    D --> E[Save counter and clear pending]
    A --> F[Load quote independently]
    F --> G[Cache restored index]
    G --> H[Start exit with cached index]
Loading

Reviews (1) · Last reviewed commit: "fix: find a restored wallet's exit fundi..." · Reviewed by Greptile

Comment thread Bitkit/Managers/SparkExitManager.swift Resolved

@talosmachina talosmachina left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings. After a restore, recoverFunding now scans the exit funding addresses forward from the restored counter (20-address gap) as well as reading every address below it, so an exit funded at or past a stale counter is listed as kept change and the counter moves past it. Reviewed f53eb9d, full tier, static: no build, because iOS does not build on this reviewer's Linux host.

What I checked, and 4 candidates I ruled out

Read in full: recoverFunding, nextFundingIndex(_:now:), refreshEarlierAddresses, loadQuote, useQuote, runWhileActive in SparkExitManager.swift; scanNextFundingIndex and nextFundingIndex(counter:record:) in SparkExitFunding.swift; the restore tests in SparkExitFundingIndexTests.swift
Call sites traced: recoverFunding (refreshEarlierAddresses, nextFundingIndex), refreshEarlierAddresses (runWhileActive, the Spark connection screen's .task and .refreshable)
CI: SwiftFormat and Greptile green; Run Tests still running at review time

Ruled out

  • Counter moving backwards: the scan starts at the restored index, so scanned >= restored, and the write still takes max with the stored value.
  • The active exit's funding listed as kept change: watched includes record.funding addresses, so a forward-scanned address the stored record owns is skipped.
  • Greptile's P2, counters of 1000 or more: reaching it takes a thousand exits on one wallet, each a multi-day unilateral exit.
  • Greptile's P1, a quote reusing the old address: nextFundingIndex(_:now:) returns a kept counter without checking the pending flag, so while recovery has not yet succeeded loadQuote can still pick the restored index. That path is the same before this diff, which only changes what a successful recovery finds; it is not introduced here. The Spark connection screen, where the exit starts, already starts recovery in its .task.

Merge confidence: 4/5, no findings, but the unit-test job had not finished when I reviewed; testARestoredCounterThatPredatesTheLastExitsFundingFindsItsCoins covers the change.

Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed (the runtime does not report it)

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No new findings; I added a refinement on Greptile's "Quotes can reuse old funding" thread.

Matches Android synonymdev/bitkit-android#1782 (46c16d103):

  • same scanNextFundingIndex(from:);
  • same 0..<kept + used candidates;
  • same max on the counter write.

The second Android fix isn't needed: try recovery.earlierAddressStore.add(...) (:1277) and every chain read throw before removeObject(pendingKey) (:1280), so a failure keeps the restore pending. Other properties:

  • The counter can't move backwards in recovery.
  • used only holds indexes at or above the restored one.
  • watched keeps the active exit's funding out of kept change.

Device gate: no device check needed: only an extra row under earlier exit addresses after a restore, which needs a backup that missed the last counter; the unit test covers it. perf: 20+ sequential Esplora reads, only while a restore is pending, repeated per foreground if Esplora keeps failing. CI: Run Tests still pending at f53eb9dd9.

Reviewer model: Claude Fable 5.2 (claude-fable-5-2), Claude Opus 5.5 (claude-opus-5-5)
Reasoning effort: not exposed

@coreyphillips coreyphillips left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two independent reviews, nothing blocking a merge.

worth doing, does not block

  • A quote taken before the pending recovery finishes still reuses the counter's address (Bitkit/Managers/SparkExitManager.swift:1230-1236)
  • Forward scan skips past a forgotten exit's address that received a late payment (Bitkit/Managers/SparkExitManager.swift:1271-1279)
  • Forward scans stop at absolute index 1000 (Bitkit/Services/SparkExit/SparkExitFunding.swift:591-594)

nits

  • Restore comment still says the exit only looks below the counter (Bitkit/Services/SparkExit/SparkExitFunding.swift:749). SparkExitFundingIndexes.restore says "The exit then looks once for funding addresses below it that still hold coins and nothing watches." With this change it also scans forward from the counter and can move the counter.

Comment thread Bitkit/Managers/SparkExitManager.swift Resolved
Comment thread Bitkit/Managers/SparkExitManager.swift Resolved
@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

@coreyphillips

Restore comment still says the exit only looks below the counter

Updated in 38447fb, along with your three "worth doing" points (answered in their threads). The description now covers them.

The Android twin has the same three paths on master since synonymdev/bitkit-android#1782 merged. I'm fixing them there in a follow-up PR.

Re-review is needed only because of this push: f53eb9d...38447fb

@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

The Android fixes are up in synonymdev/bitkit-android#1887.

@coreyphillips coreyphillips left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rechecked after 1 new commit (38447fb). Nothing blocking remains.

addressed

  • A quote taken before the pending recovery finishes still reuses the counter's address (Bitkit/Managers/SparkExitManager.swift:1230-1236). Fixed: SparkExitManager.nextFundingIndex(_:now:) (SparkExitManager.swift:1232-1235) now awaits recoverFunding before it reads the counter. recoverFunding runs while pendingKey is set (:1248) and throws before clearing it (:1279-1282), so loadQuote (:896) either gets 4 or fails. start() also writes the counter with max (:980). I ran SparkExitFundingIndexTests at 38447fb on a simulator and all 20 passed, testAQuoteWhileARestoreIsPendingScansPastTheRestoredCounterFirst among them.
  • Forward scan skips past a forgotten exit's address that received a late payment (Bitkit/Managers/SparkExitManager.swift:1271-1279). Fixed: watched now leaves out .cancelledFunding entries (SparkExitManager.swift:1272-1273). A forgotten exit's address that the forward scan finds used and holding coins gets added as .keptChange. SparkExitEarlierAddressStore.add (SparkExitEarlierAddresses.swift:119-126) replaces the cancelled entry with it, so the address is watched for good. testARestoredCounterAtAForgottenExitsAddressListsItsLatePaymentAsKeptChange passed in my local run.
  • Restore comment still says the exit only looks below the counter (Bitkit/Services/SparkExit/SparkExitFunding.swift:749). Fixed: The comment at SparkExitFunding.swift:751-752 now describes both reads: each funding address below the counter, and the forward scan that can move the counter.
  • Forward scans stop at absolute index 1000 (Bitkit/Services/SparkExit/SparkExitFunding.swift:591-594). Fixed: The scan's limit is now start + fundingScanMaxAddresses (SparkExitFunding.swift:594-596). I compiled the loop on its own: with start 1000 and address 1000 used, it returns 1001. testARestoredCounterPastTheScanCeilingStillScansForward passed in my local run.

new since the last review

worth doing, does not block

  • Funding scan still traps when the restored counter is near UInt32.max (Bitkit/Services/SparkExit/SparkExitFunding.swift:594-596)

@coreyphillips coreyphillips left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rechecked after 1 new commit (0f9f29c). Nothing blocking remains.

addressed

  • Funding scan still traps when the restored counter is near UInt32.max (Bitkit/Services/SparkExit/SparkExitFunding.swift:594-596). Fixed: In SparkExitFunding.swift:595-596, both loop bounds are now computed in UInt64, and limit is capped at UInt32.max. Since index < limit, neither next = index + 1 nor index += 1 can overflow. I compiled the loop verbatim at -Onone with overflow checks on and ran it from UInt32.max, max - 1, max - 5, max - 25, max - 500 and max - 1500, with every address used, none used, and mixed. None of them trapped. From max - 5 with every address used it returns UInt32.max after 5 reads. Starts of 0 and 3 give the same next index and reads as the existing tests expect. The new test asserts that case. One related path is left, but it is older than this PR: Array(0 ..< $0) at SparkExitManager.swift:1269 still sizes itself by the restored counter. It needs the same corrupt backup, so I am not raising it here.

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-approving at 0f9f29c18. The scan bounds now use 64-bit arithmetic, min(start + fundingScanMaxAddresses, UInt32.max). A counter near the top of the range ends the scan instead of overflowing, and index < limit <= UInt32.max keeps next = index + 1 in range. My earlier note on the quote path stands on the Greptile thread.

@ovitrif

ovitrif commented Nov 12, 2026

Copy link
Copy Markdown
Collaborator Author

Merging into feat/breez-spark-lightning: @coreyphillips and @jvsena42 approved 0f9f29c, unit tests (rerun after an unrelated USDT UI test flake) and SwiftFormat pass, and no review thread is open.

@ovitrif
ovitrif merged commit fe3505b into feat/breez-spark-lightning Nov 12, 2026
12 of 13 checks passed
@ovitrif
ovitrif deleted the fix/spark-exit-restore-scan-forward branch November 12, 2026 13:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants