Skip to content

fix: recheck spark send authorization at submission - #2053

Merged
ovitrif merged 3 commits into
masterfrom
fix/spark-auth-recheck
Nov 26, 2026
Merged

ovitrif merged 3 commits into
masterfrom
fix/spark-auth-recheck

Conversation

@ovitrif

@ovitrif ovitrif commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #1962

Description

  • Fixes a Spark Lightning send going out on a stale authorization because the caller's check (onBeforeSend) ran before the send's journal writes (addSparkSendHash, setSparkSendAttempt, addSparkUncertainSend), which suspend. SparkRepo.payInvoice now runs it again right before sparkService.send, next to the deadline and exit checks.
  • A refusal there fails with ServiceError.PaymentStoppedAtSubmission, as the node rail does on its queue, and rolls the journal back the same way the late deadline and exit refusals do; a failed cleanup write there is logged and the refusal still reaches the caller. QuickPay already handles that error: it releases the payment and falls back to the confirm screen.
  • The second call reaches only LightningRepo's side-effect-free isAuthorizedAtSubmission, the same check Spark's leaf-selection retry already reruns. Only QuickPay passes one, so a manual send rechecks nothing at submission, on either rail, as before.
  • No iOS twin: on bitkit-ios master, SparkManager.send runs the beforeSubmission check synchronously inside spends.run, right before sdk.sendPayment, with no await between them.

Out of Scope

Design

N/A — no UI changes.

Preview

N/A — no user-visible changes.

QA Notes

Setup

N/A — no device testing required: the window is a few cache writes wide and needs an authorization change inside it, which unit tests reach and a device can't time.

Journeys

N/A — no user-visible behaviour change.

Manual Tests

N/A

Automated Checks

  • added SparkRepoTest.kt — a send whose authorization lapses while its journal is written never leaves, and the journal rolls back
  • updated SparkRepoTest.kt — the leaf-selection retry test counts the new check at submission

Evidence

  • The new test fails on master's SparkRepo.kt and passes with this change.
  • Local verification: just compile, just test, just lint; after the review fixes, SparkRepoTest, LightningRepoTest, QuickPayRepoTest and just lint.

Gaps

None.

Models used

  • Planning/scoping: Claude Opus 5.5 (reasoning: medium)
  • Implementation: Claude Opus 5.5 (reasoning: medium), Claude Sonnet 5.5 (reasoning: high)
  • Review: gemini-4-neon-high (reasoning: Not exposed)
  • Review rounds: 1

The review record names only the model id, with no separate reasoning setting.

Verified: just compile and just test before the review fixes; after them SparkRepoTest, LightningRepoTest, QuickPayRepoTest and just lint
@ovitrif ovitrif self-assigned this Nov 26, 2026
@ovitrif
ovitrif requested review from jvsena42 and pwltr November 26, 2026 02:19
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 26, 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-26T02:21:06.499628Z bd98bcb 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 26, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge.

Summary

Spark now checks payment authorization again after its journal writes, immediately before submission.

  • Spark rechecks payment authorization right before sending.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Initial authorization and admission] --> B[Write send journal]
  B --> C{Still authorized?}
  C -->|Yes| D[Check deadline and exit]
  D --> E[Submit Spark send]
  C -->|No| F[Clean up unsent attempt]
  F --> G[Return PaymentStoppedAtSubmission]
  G --> H[QuickPay returns to confirmation]
Loading

Reviews (1) · Last reviewed commit: "fix: recheck spark send authorization at..." · Reviewed by Greptile

@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. Adds a second authorization check right before sparkService.send, inside the spending block after the journal writes, so a QuickPay send whose authorization lapses while addSparkSendHash / setSparkSendAttempt / addSparkUncertainSend suspend fails with PaymentStoppedAtSubmission and rolls the journal back. Reviewed bd98bcb, full tier, static only: on bitkit-android an auto review never builds the branch, so this was reasoned from the code, and CI was still running when I read it.

Merge confidence: 4/5, CI had not finished at review time, and the only test is a unit test with mocks (the new SparkRepoTest.kt case), which can't show a device timing.

What I checked, and 5 candidates I ruled out

Read in full: SparkRepo.payInvoice, sendRetryingLeafSelection and spending; LightningRepo.payInvoiceChecked and its authorizeSend wrapper; QuickPayRepo.dispatchBolt11, fallBackBeforeDispatch and tryMarkDispatched.
Call sites traced: sparkRepo.payInvoice has one caller (LightningRepo.kt:1660), so the second onBeforeSend call always lands on the isChecked branch, which calls only isAuthorizedAtSubmission (null means true). The onBeforeSend lambdas with side effects (QuickPay's tryMarkDispatched, the Paykit and AppViewModel callers) still run once.
QuickPay path: the first check marks the op dispatched, then the refusal at submission comes back as PaymentStoppedAtSubmission. isAuthorizationLapsed is still false, so isStoppedAtSubmission() routes to fallBackBeforeDispatch(isMarkedDispatched = true), which matches current.dispatched, releases the spend and falls back to confirm. LightningRepo's onFailure puts back the earlier rail because isAdmitted is true and the error is not PaymentPendingException.

Ruled out

  • runCatching to runSuspendCatching lets a cancellation skip dropUnsentSend: in practice the new call does not suspend. Past the first check, authorizeSend only invokes the non-suspending () -> Boolean, so no cancellation can arrive between the journal writes and the send. A cancellation anywhere else keeps the hold, as intended.
  • A keyed retry of a held send is refused but keeps its hold (isReusedKey && wasHeld returns early): the deadline and exit refusals at the same point already behave this way, and keeping the hold is deliberate, since an earlier attempt under that key may have committed a transfer.
  • sendRecordedAt is bumped before the check and not rolled back: this was already the case for the deadline and exit refusals, and admitSend keeps same-invoice sends exclusive, so only one that overlaps the refused one sees it.
  • The leaf-selection retry now counts three checks instead of two: it still reruns only the side-effect-free check, and the updated test asserts the new count.
  • Manual sends: isAuthorizedAtSubmission is null, so the new check returns true and nothing changes for them.

Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed (the run's metadata does not report an effort setting)

@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Regtest APK

Built from 3abdd06 (run).

Download bitkit-dev-debug universal APK (expires in 30 days).

@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 bd98bcb. Spark now rechecks QuickPay authorization after writing the send journal and before calling the SDK.

Low: If the wallet locks during journaling and a cleanup write then fails, SparkRepo.kt:662 lets the storage exception replace PaymentStoppedAtSubmission. QuickPay can show the payment as pending and keep its spending reservation even though Spark never submitted it. Preserve the typed refusal when cleanup fails so QuickPay can release the reservation and return to swipe confirmation.

Review details

Quick review
Model: Claude Opus 5.5
Reasoning effort: high

General review
Model: GPT-6.2 Sol
Reasoning effort: high

Combined review
Model: GPT-6.2 Sol
Reasoning effort: high

A refusal at submission now reaches the caller even when dropping the
unsent send's journal entries fails, so QuickPay falls back instead of
showing a send that never left as pending.

Verified: SparkRepoTest (new test fails before the change), just lint
@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Low: If the wallet locks during journaling and a cleanup write then fails, SparkRepo.kt:662 lets the storage exception replace PaymentStoppedAtSubmission.

@pwltr Fixed in 3c593c8: a failed cleanup write after the late refusal is now logged and PaymentStoppedAtSubmission still reaches QuickPay, with a test where the cleanup write throws. The rollback's separate writes, and the same cleanup on the expired-invoice and insufficient-funds refusals, predate this PR and are tracked in #2060.

@ovitrif
ovitrif requested a review from pwltr November 26, 2026 09:01
jvsena42
jvsena42 previously approved these changes Nov 26, 2026

@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 3c593c8 with one LOW open, inline. Fix it here or move it to a follow-up issue, your choice; please reply on the thread with which, and the issue link if it's a follow-up.

Checked and clean:

  • Callers: SparkRepo.payInvoice has one production caller (LightningRepo.kt:1660, always with authorizeSend). QuickPay is the only payInvoice* caller that sets isAuthorizedAtSubmission, and its recheck is real. Node-only paths (payInvoiceWithNode, payInvoiceOverLdk) never reach Spark; withdrawAll/withdraw are untouched.
  • TOCTOU: from the recheck at SparkRepo.kt:658 to sparkService.send there's no suspension, mutex or queue, and the second authorizeSend call cannot suspend.
  • Amount and fee: the send uses the same prepared object whose fee was checked against maxTotalFeeMsat. Nothing is re-quoted in between.
  • Side effects run once: isChecked is set before onBeforeSend(), so tryMarkDispatched, ensurePaymentAllowed, admitSend and recordSendRail don't run twice.
  • Refusal path: spendsInFlight/sendsInFlight are released, the earlier rail is restored, and there's no fallback to the node. QuickPay emits FallBackToConfirm with isMarkedDispatched = true. A later attempt reuses the unsent attempt key, so there's no double pay.
  • 3c593c8: bestEffort { dropUnsentSend() } uses runSuspendCatching and keeps the original refusal.

perf: not relevant (one extra non-suspending lambda call per Spark send).
Device gate: no device check needed — no UI change, and the window the recheck closes can't be timed on a device.
CI is still running at this head; this approval assumes it goes green.

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

Comment thread changelog.d/next/1962.fixed.md Resolved

@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 3c593c8. Spark now rechecks the wallet-lock authorization before submitting QuickPay.

Low: changelog.d/next/1962.fixed.md:1 describes the fix as applying to Spark Lightning payments generally. Manual Paykit requests still run ensurePaymentAllowed before journaling and supply no submission check (AppViewModel.kt:8250, LightningRepo.kt:1603). Scope the changelog to QuickPay and change Closes #1962 to Part of #1962 so the Paykit case stays open.

Review details

Quick review
Model: Claude Opus 5.5
Reasoning effort: high

General review
Model: GPT-6.2 Sol
Reasoning effort: high

Combined review
Model: GPT-6.2 Sol
Reasoning effort: high

Only QuickPay's wallet-lock check runs again at submission; a Paykit
request's authorization is still checked once, so the entry says so.

Verified: none (changelog text only)
@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Low: changelog.d/next/1962.fixed.md:1 describes the fix as applying to Spark Lightning payments generally. [...] Scope the changelog to QuickPay and change Closes #1962 to Part of #1962 so the Paykit case stays open.

@pwltr Done in 3abdd06: the changelog is scoped to QuickPay and the wallet lock, and this PR is now Part of #1962, with the Paykit request path listed under Out of Scope.

@ovitrif
ovitrif requested review from jvsena42 and pwltr November 26, 2026 09:57

@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 3abdd06. Spark rechecks QuickPay’s wallet-lock authorization after writing the send journal and before calling the SDK. If the wallet locks during those writes, QuickPay releases the reservation and returns to swipe confirmation. The changelog now describes that behavior, and #1962 remains open for the Paykit case. No findings.

Review details

Quick review
Model: Claude Opus 5.5
Reasoning effort: high

General review
Model: GPT-6.2 Sol
Reasoning effort: high

Combined review
Model: GPT-6.2 Sol
Reasoning effort: high

@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Merged: approved by @pwltr on 3abdd06, checks green, every review thread answered. #1962 stays open for the Paykit request path.

@ovitrif
ovitrif merged commit ad8a24b into master Nov 26, 2026
23 checks passed
@ovitrif
ovitrif deleted the fix/spark-auth-recheck branch November 26, 2026 10:50
ovitrif added a commit that referenced this pull request Nov 26, 2026
The late authorization refusal from #2053 now rolls back through
dropSparkUnsentSend, which is already best effort.

Verified: SparkRepoTest, CacheStoreTest, LightningRepoTest, just lint
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