Skip to content

fix: keep a savings payment the exit never saved - #1536

Merged
ovitrif merged 2 commits into
masterfrom
fix/spark-exit-unsaved-savings-payment
Nov 28, 2026
Merged

ovitrif merged 2 commits into
masterfrom
fix/spark-exit-unsaved-savings-payment

Conversation

@ovitrif

@ovitrif ovitrif commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1459
Closes #1462
Twin: synonymdev/bitkit-android#2146
Twin: synonymdev/bitkit-android#2155

Description

A force transfer's savings payment of its fees is now marked on the record before it goes out. A stop that loses the payment's txid no longer brings the ask back or lets the transfer be cancelled while that payment may still land:

  • Marked before sending. The start's payment, Pay from savings and a retry of a refused payment save the mark first; nothing goes out unless it is saved. While it holds, Progress shows the payment as awaited, asks for nothing and keeps Cancel off.
  • Kept from the send journal. On launch and on every tick, a payment the journal shows went out (accepted, or with no answer yet) is kept as the transfer's payment.
  • Forgotten when it never went out. The mark goes when the journal shows nothing of it was admitted, or a node refused it. After a restart it also goes when all of these hold, checked under the ticks' lock:
    • the journal is empty;
    • it belongs to the transfer's wallet;
    • the funding address never had a transaction, in a block or the mempool.
  • Expiry. Otherwise the mark expires 144 blocks after it started, as an unadopted own payment does, so the ask comes back.

Out of Scope

Design

N/A — no UI changes.

Preview

N/A — Progress shows the existing paid state while the payment may still land.

QA Notes

Setup

Local regtest with the Spark stack, debug build of this head. A Spark balance large enough to start a force transfer, and a savings balance to pay its fees from. Cases 1 and 2 need a local debug-only change that stops the app at the named point.

Journeys

N/A — not drivable; see Manual Tests.

Manual Tests

  • 1. start a force transfer paying the fees from savings, stop the app after the payment is broadcast and before the transfer saves it, relaunch → Progress holds the ask and Cancel stays off until the payment lands — process death mid-payment is not in Capabilities
  • 2. start a force transfer paying the fees from savings, stop the app after the mark is saved and before the payment is sent, relaunch → Progress asks for the fees again and Cancel is on, and nothing left savings — process death mid-payment is not in Capabilities

Automated Checks

  • added SparkExitSavingsSendTests.swift — an unsaved payment holds the ask, the cancel and the reminder until its 144-block wait ends; the journal keeps a payment that went out and forgets one that never did; after a restart an empty journal frees the ask only for the transfer's wallet and an unused address
  • updated SparkExitReviewTests.swift — a lost accepted payment is kept from the journal's attempt; a tick forgets an unsaved payment once its 144-block wait ends
  • ran SparkExitTests, SparkExitFundingReleaseTests, SparkExitFeeBumpTests, AppStatusExitTests and PaykitPaymentProofServiceTests

Evidence

The suites above pass on this head on an iOS simulator, and SwiftFormat lint is clean. A device run on this head follows.

Gaps

  • 144-block expiry: not run on a device, since regtest can't hold a payment unconfirmed that long; covered by SparkExitSavingsSendTests.swift.

Models used

  • Planning/scoping: Claude Opus 5.5 (reasoning: medium)
  • Implementation: Claude Opus 5.5 (reasoning: medium)
  • Review: Gemini 4 Neon (reasoning: high)
  • Review rounds: 2

Marks a savings payment of a force transfer's funding before it goes out, so a stop that loses its txid keeps the ask held and the exit uncancellable until the send journal shows the payment, shows it never went out (or the exit wallet's empty journal and an unused address do), or 144 blocks pass.

Verified: SparkExitSavingsSendTests, SparkExitReviewTests, SparkExitTests, SparkExitFundingReleaseTests, SparkExitFeeBumpTests, AppStatusExitTests and PaykitPaymentProofServiceTests pass on an iOS simulator; SwiftFormat lint clean
…payment

Verified: SparkExitSavingsSendTests, SparkExitReviewTests (with a tick that forgets the payment after 144 blocks), SparkExitTests, SparkExitFundingReleaseTests, SparkExitFeeBumpTests, AppStatusExitTests and PaykitPaymentProofServiceTests pass on an iOS simulator; SwiftFormat lint clean
@ovitrif ovitrif self-assigned this Nov 27, 2026
@ovitrif
ovitrif requested review from jvsena42 and pwltr November 27, 2026 18:44
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 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-27T18:46:03.016393Z d6939ab 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.

@greptile-apps

greptile-apps Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5 · The PR appears safe to merge; no actionable issues were established.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable issues were established.

Summary

Keeps a force transfer’s savings payment marked on disk before sending it, so a restart cannot immediately bring back the fee request or enable Cancel.

  • Force transfers wait for savings fee payments that may still arrive.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Save payment-start mark] --> B[Send savings payment]
  B --> C[Save payment transaction ID]
  A --> D[App restarts before ID is saved]
  D --> E[Read send journal]
  E --> F{Payment outcome}
  F -->|Accepted or unanswered with ID| C
  F -->|Earlier attempt or rejected| G[Clear mark]
  F -->|Empty journal| H{Same wallet and unused address?}
  H -->|Yes| G
  H -->|No or unreadable| I[Keep waiting]
  F -->|Cannot recover outcome| I
  I --> J[Clear mark after 144 observed blocks]
Loading

Reviews (1) · Last reviewed commit: "fix: read the funding again when a backg..." · Reviewed by Greptile

@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.

Code scan at d6939ab: no findings.

Android rules (synonymdev/bitkit-android#2146, synonymdev/bitkit-android#2155) on iOS:

  • The hold is released only when the journal read succeeds and holds no attempt: present. keepSavingsSend (SparkExitManager.swift:664-669) returns the record unchanged on a throwing read.
  • The journal must be the exit wallet's: present. The wallet index is read before (:662) and after (:708) the journal read. The iOS journal is one keychain slot whose attempts carry their walletId, so the check is stricter than iOS needs.
  • The funding address must never have been used: present (:708-710, chain plus mempool). An unreadable address or a missing chain host keeps the mark.
  • The reduced fee request and the notification while funding covers the fees: absent. Both are declared in Out of Scope and tracked in #1528.

Checked and clean:

  • Every clear path:
    • sentNothing is only preDispatch, blocked or duplicate; any other broadcast error becomes .unknown(txid) and is kept as paid.
    • "Only the earlier attempt in the journal" means the new send was never admitted, since admit replaces the single slot.
    • The journal goes empty for a dispatched attempt only after acceptance, which the address read sees, because the txid is saved (:807) before any broadcast.
  • Stop points: before admit, before the txid save, during broadcast and after broadcast. A stop before dispatch leaves no refusal, so Progress asks only for outside funding.
  • All three sites save the mark with try before sending (:462, :624, :1464). A failed save sends nothing. The mark cannot stick: every awaitingFunding tick runs noteOwnPayment, so it expires 144 ticked blocks later, background runs included.
  • Every keepSavingsSend caller holds isTicking on the main actor. Progress buttons run in an unstructured Task, so leaving the screen doesn't cancel a payment.
  • Authorization is unchanged. The Progress retry's authorize still checks authorizePayAgain, with exit built from the record before the mark.
  • With #1518 (the merge base): a release needs an inactive exit or no shortfall, and a held mark needs an active awaitingFunding exit, so the two never meet. mayPayAgain refuses while the record reads .paid(nil).
  • v3.1.1 has no Spark exit code. The new field is optional and currentVersion is unchanged. A locked keychain (AfterFirstUnlockThisDeviceOnly) keeps the mark.

perf: one extra GET /address/{addr} per load and tick, only while a mark is on record with an empty journal. A launch-time read holds the tick lock, so a foreground tick in that window is skipped.

Device gate (partial): d6939ab — not run yet; manual cases 1–2 (stop mid-payment on the local Spark stack, relaunch). Result to follow. CI was still pending at review time.

Reviewer model: Opus 5.5 (claude-opus-5-5) coordinating; Fable 5.2 (claude-fable-5-2) primary review
Reasoning effort: Not exposed

@ovitrif

ovitrif commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

QA for d6939ab:
Tested on iPhone 17 Pro (iOS 27 simulator), local regtest. A local debug-only change stopped the app once at the point each case names; the relaunch ran this head unchanged.

🟢 1. The app stops after the savings payment went out, before the transfer saves it
1. The app stops after the savings payment went out, before the transfer saves it The force transfer paid its 7 623 sats of emergency fees from savings, and the app stopped with the payment in the mempool and the transfer still marked, without its txid. On relaunch the transfer took the payment back from the send journal: Progress showed no fee ask and no Cancel transfer. One block later the payment confirmed as the transfer's only funding (one output of 7 623 sats at its address), and the transfer published its next transaction.
case1-stop-after-send2x.mp4

🟢 2. The app stops after the mark is saved, before the payment is sent
2. The app stops after the mark is saved, before the payment is sent The app stopped right after the transfer was marked, before any payment went out. On relaunch the transfer dropped the mark: Progress asked for the 7 623 sats again at its funding address, with Cancel transfer on. Savings stayed at 300 000 sats and the funding address held nothing. Cancel transfer then worked and the Spark balance came back.
case2-stop-before-send2x.mp4

@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. Marks a force transfer's savings fee payment on the record before it goes out, keeps or forgets it from the send journal on launch, tick and cancel, and expires the mark after 144 blocks. Reviewed d6939ab, full tier, static: iOS does not build on this box, so nothing was run here.

What I checked, and 5 candidates I ruled out

Read: the whole diff; SparkExitManager start, paySavingsRefusal, retrySavingsPayment, cancel, tick, the background run and launch; SparkExitDriver.noteOwnPayment; SparkExitFundingRelease.exitNoLongerNeeds / mayPayAgain; SparkExitFunding.reminders / fundingState; OnchainSendAttemptService.send, admit, currentAttempt, clearBeforeDispatch.
Call sites traced: isAwaitingOwnPayment (driver, release, reminders, isSavingsSendLanding), every .paid match (views, AppStatusHelper, currentFundingState, mayPayAgain).
CI: SwiftFormat, validate and Greptile green; Run Tests, Integration Tests and build-local still pending at review time.

Ruled out

  • .paid(txid: nil) dropped by currentFundingState: with no txid saved, record.fundingPaymentTxid != txid compares nil with nil, and isAwaitingOwnPayment is true while the mark holds, so the stored state survives.
  • Send Pending paying the exit again while the mark holds: mayPayAgain maps .paid to isOwnPaid, which is false with no txid, so a retry from Send is refused until the mark is kept or cleared.
  • Retry path marked with earlierAttemptId: nil: a stop between the mark and the re-dispatch leaves the refused attempt in the journal as .rejected, so keepingSavingsSend clears the mark and the refusal offer comes back.
  • Admitted but never prepared, then a stop: currentAttempt drops a pending attempt with no txid and no recovery context after a restart, so the journal reads empty and only the wallet and unused-address check can free the ask, as the body says.
  • Mark never aging out: withSavingsSendLooked runs inside noteOwnPayment on every awaiting-funding tick and stamps atHeight from the first tip; testATickForgetsAnUnsavedSavingsPaymentOnceItsWaitEnds covers both ticks.

Merge confidence: 4/5, not built or run here and the test jobs were still pending.

@pwltr pwltr 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.

Reviewed d6939ab.

Low: Restart cleanup can hide a real funding shortfall for 144 blocks. If a savings send stops after unsigned admission and a partial external payment reaches the funding address before relaunch, OnchainSendAttemptService.swift:1133 deletes the unsent attempt. SparkExitManager.swift:669 then sees an empty journal and an address with history, so Progress hides the remaining fee request and suppresses the reminder even though the savings payment could never have gone out.

Low: Send Pending can offer Retry original payment and then refuse it. If launch recovery finds the prepared payment but the exit-record replacement fails, SparkExitManager.swift:679 keeps the txid only in memory. The retry reads the old file, and SparkExitFundingRelease.swift:52 cannot match the journaled payment to the hold because the stored txid is missing. On an underfunded address, authorization then refuses the same-input retry the screen just offered.

Low (Pre-existing): A rejected savings fee payment retried from Send Pending can still lead to a fresh external fee request after a restart. SendPendingScreen.swift:440 retries without recording a hold on the exit. A stop after dispatch starts at OnchainSendAttemptService.swift:952 and before the outcome is saved leaves the original rejection on disk, so Progress can show the funding address and ask again while the retry may still arrive.

Review details

Quick review: Claude Opus 5.5, high reasoning effort
General review: GPT-6.2 Sol, high reasoning effort
Verification: GPT-6.2 Sol, high reasoning effort

@ovitrif

ovitrif commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator Author

Low: Restart cleanup can hide a real funding shortfall for 144 blocks.
Low: Send Pending can offer Retry original payment and then refuse it.
Low (Pre-existing): A rejected savings fee payment retried from Send Pending can still lead to a fresh external fee request after a restart.

@pwltr out of scope: tracked in #1537, because each needs a stop or a failed write at a narrow point and none pays twice, and this patch stays at the smallest diff for the next release candidate.

@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.

Approving at d6939ab. No findings in the code scan, and both manual cases passed on the device.

Device gate: d6939ab — manual tests: 1 passed (in-flight broadcast and broadcast without an answer), 2 passed, plus a control; perf: launch → keep/forget decision logged in 1.2–1.7 s; l10n: no UI text changed

  • Debug build of this head with the local Spark stack and an Electrum proxy that can hold a broadcast or drop its answer, on an iPhone 17 Pro Max simulator. Stops were made from outside with simctl terminate or SIGKILL, since the app has no debug stop hook.
  • Case 1, broadcast held: terminated 3 s after the payment started, with the record holding the mark and no txid and the mempool empty.
    • On relaunch, Keeping the Spark exit funding bafa94dd… the record lost was logged 1.7 s after launch, and the mark was replaced by fundingPaymentTxid.
    • Progress showed SparkExitSavingsUnresolved, with no ask, no Cancel and no Retry.
    • The app did not rebroadcast within 73 s, so I sent the held raw transaction by hand. The exit then went to running with one funding output, spent by the fan-out. Savings went 300 000 → 290 669 (ask 8 909 + fee 422).
  • Case 1, broadcast reached the network but its answer was dropped: the same Keeping… decision 1.2 s after relaunch, no ask and no Cancel. The fan-out was accepted 2 s after the next block, with one payment.
  • Case 2, killed 1 ms after the mark reached the record file and before any broadcast: Forgetting the started Spark exit savings payment the journal never sent 1.6 s after relaunch.
    • Progress asked for ₿ 8 909 again and offered Cancel transfer.
    • Cancel worked. Savings stayed at 300 000, the funding address was 0/0 and the mempool empty.
  • Control: the same kill, then 1 000 sats sent to the funding address from outside before relaunch. The mark was kept, with no Cancel and no ask, so the clear in case 2 depended on the address showing nothing.
  • ⚠️ Not verified: the 144-block expiry (the PR's declared gap), a slow Esplora host at launch, and a stop during a Progress retry (#1537).

CI at d6939ab: green except one check still pending.

Reviewer model: Opus 5.5 (claude-opus-5-5) coordinating; Fable 5.2 (claude-fable-5-2) primary review and device run (device effort: medium, run record)
Reasoning effort: Not exposed, except where noted

@ovitrif

ovitrif commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator Author

Merging: approved at d6939ab, both manual cases passed on a device at this head, and CI is green.

@ovitrif
ovitrif merged commit db2ebf0 into master Nov 28, 2026
26 of 27 checks passed
@ovitrif
ovitrif deleted the fix/spark-exit-unsaved-savings-payment branch November 28, 2026 00:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

4 participants