Skip to content

fix: recheck paykit request authorization at submission - #1493

Merged
ovitrif merged 8 commits into
masterfrom
fix/paykit-request-recheck
Nov 27, 2026
Merged

ovitrif merged 8 commits into
masterfrom
fix/paykit-request-recheck

Conversation

@ovitrif

@ovitrif ovitrif commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1455
Twin: synonymdev/bitkit-android#2070

Description

  • Fixes a Paykit payment request being paid after its contact is blocked while its Lightning or on-chain send is prepared. The request's authorization (ensurePaymentAllowed) ran once, before the send's last awaits.
  • The Lightning send takes a recheckBeforeSubmission closure, run after its last await before submission: in SparkManager.send before spends.run, and on the node right before submitPayment. Manual request sends (SendConfirmationView, LnurlPayConfirm) pass the request's authorization; a refusal there sends nothing and ends like a refusal up front (proof failed, private list released).
  • Allowance (automatic) payments pass it too, through PaykitAllowanceLivePayer.payLightning. Any failure of that recheck becomes requestUnavailable (an expired request stays requestExpired), which PaykitPaymentProofService treats as unsent, so the attempt ends and its reservation is released.
  • On-chain request sends recheck too. On the node, SendConfirmationView.sendOnchainPayment authorizes again after onAuthorized (which marks a manual allowance sending), right before the broadcast; a refusal fails the started proof before the send's guard is cleared and ends as OnchainSendAttemptError.preDispatch; a manual allowance already marked sending ends as failed first. On Spark, PaykitRouteService.payReportingAllowance authorizes again after markSending; a refusal ends as SparkWithdrawalNotSent and the allowance attempt fails.

Out of Scope

Design

N/A — no UI changes.

Preview

N/A — no user-visible changes.

QA Notes

Setup

Device run on 7905714 (#1493 (comment)): a Spark Lightning payment request and an on-chain payment request, both paid on a Debug build against bitkit-docker's local Spark stack and payment request fixture (regtest). The block itself lands inside a window a few awaits wide, 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 ChannelFreeRailTests.swift — a send refused at the recheck before submission leaves no hold
  • added PaykitAllowanceExecutorTests.swift — a failed allowance recheck ends as a refusal the proof treats as unsent
  • added PaykitPaymentRequestServiceTests.swift — a Lightning request send rechecks its authorization before submission, after its awaits
  • added PaykitPaymentRequestServiceTests.swift — an on-chain request send rechecks its authorization after its attempt is marked sending, and a refusal there fails the proof first
  • updated PaykitRouteTests.swift — a Spark on-chain payment authorizes again after markSending, and a refusal there sends nothing
  • updated PaykitPaymentProofServiceTests.swift — requestUnavailable at submission clears the proof as unsent; a rollback failure at the on-chain recheck keeps the matching attempt without a broadcast
  • added PaykitPaymentRequestServiceTests.swift — a Lightning recheck refusal of a retry still in doubt comes back pending and keeps its proof
  • added SparkSendKeyTests.swift — a Spark leaf-selection retry checks the request's authorization, then its deadline

Evidence

  • The on-chain tests fail with the second authorization or its rollback removed; the in-doubt retry test fails on 9f4bd27.
  • Local verification: the Paykit, send and Spark rail suites and swiftformat --lint on 7905714.

Gaps

  • The node path's recheck before submitPayment has no unit test: the node is nil in unit tests.

Models used

  • Planning/scoping: Not used
  • Implementation: Claude Opus 5.5 (reasoning: medium), Claude Sonnet 5.5 (reasoning: high)
  • Review: Gemini 4 Neon (reasoning: high)
  • Review rounds: 6

A payment request's Lightning send, manual or by an allowance, checks
its authorization again after its last await before submission: on
Spark right before spends.run, on the node right before its queue.
Refused there, nothing is sent and it ends like a refusal up front.

Verified: PaykitPaymentRequestServiceTests, ChannelFreeRailTests, PaykitPaymentProofServiceTests (new tests fail with the recheck off), unit test selection on the simulator, swiftformat --lint
Verified: PaykitPaymentRequestServiceTests, SendConfirmationViewTests, ChannelFreeRailTests, PaykitPaymentProofServiceTests, PaykitAllowanceExecutorTests; swiftformat --lint
Verified: PaykitAllowanceExecutorTests, ChannelFreeRailTests, PaykitPaymentProofServiceTests, PaykitPaymentRequestServiceTests, SendConfirmationViewTests; swiftformat --lint
@ovitrif ovitrif self-assigned this Nov 26, 2026
@ovitrif
ovitrif requested review from jvsena42 and pwltr November 26, 2026 13:13
@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-26T13:15:04.756777Z 8d42b27 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

Confidence Score: 3/5 · Fix the node's queued-submission race before merging.RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The change is limited to Paykit Lightning request payments across manual and allowance workflows.

Fix the node's queued-submission race before merging.

Findings

  1. P1 Security Blocked contacts can still receive ▶

Summary

Adds a late authorization check to manual and allowance Lightning payments.

  • Paykit Lightning sends check request authorization again before submission.

Acknowledged scope: ovitrif explicitly deferred identity switching and sign-out during a send because refusing then could leave allowance attempts stuck as sending.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Authorize request] --> B[Prepare payment]
    B --> C[Recheck authorization]
    C --> D{Payment path}
    D --> E[Spark spending check]
    E --> F[Send through Spark]
    D --> G[Wait for node queue]
    G --> H[Check deadline and admit attempt]
    H --> I[Send through node]
    J[Contact blocked during queue wait] -. Not rechecked .-> H
Loading

Reviews (1) · Last reviewed commit: "test: cover the allowance recheck refusa..." · Reviewed by Greptile

Comment thread Bitkit/Services/LightningService.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.

Adds a recheckBeforeSubmission closure to the Lightning send so a Paykit request's authorization (ensurePaymentAllowed) runs again after the send's last awaits: on Spark before spends.run, on the node before submitPayment, for manual sends (SendConfirmationView, LnurlPayConfirm) and allowance payments (PaykitAllowanceLivePayer.payLightning).

No findings. Reviewed head 8d42b27, full tier, static only: an iOS branch does not build on this Linux host, so nothing was built or run here. Run Tests and Run Integration Tests were still pending when this was posted.

Scope note: the PR says Closes #1455, but two of that issue's four bullets (on-chain via Spark in PaykitRouteService.payReportingAllowance, and on-chain via the node through beforeBroadcastAttempt then the LDK queue) are untouched here. If those are meant for a follow-up, say so in the body or change Closes to Refs so the issue stays open.

Merge confidence: 4/5, no findings, held below 5 by tests still pending on CI and no build or device run on this head.

What was checked
  • Spark path: SparkManager.send now rechecks after the quote and balance awaits, outside spends.run. A refusal there is a PaykitPaymentRequestError, not ChannelFreeRailSendRefused, so LightningService.send takes its generic catch with didRecordAttempt == false. That marks nothing uncertain and releases nothing, which is correct because nothing was recorded.
  • Node path: the recheck runs after the settledEarlierAttempt awaits and before ServiceQueue.background(.ldk). The queue wait after it is a window the recheck cannot cover, since beforeSubmission is sync on a dispatch queue. The code comment names that boundary, so I read it as deliberate and did not post it.
  • Manual sends: the recheck reuses the same authorize and onAuthorizationFailure, so a refusal fails the proof, sets definitePreBroadcastFailure, and in SendConfirmationView skips the !lightningPaymentSubmitted branch through lightningAuthorizationRefused, so it never lands on the pending screen. The outer catch still finishes the manual allowance attempt as .failed, because lightningPaymentSubmitted is false.
  • LnurlPayConfirm: setting lightningPaymentHash = nil in the failure callback skips the outer proof-failure branch, and the proof was already removed in the callback.
  • Allowance path: PaykitAllowanceLivePayer.recheckBeforeSubmission keeps requestExpired and maps every other error to requestUnavailable. PaykitPaymentProofService.failLightningPayment(paymentHash:submissionError:) now treats that as unsent, so the executor records .failed and releases the list, not .unknown. The live payer's ensurePaymentAllowed calls PaykitPaymentRequestService().ensurePaymentAllowed, which is free of side effects (deadline plus a linkedPeers read), so running it twice changes no state.
  • ensurePaymentAllowed on the manager (manual path) re-reads linkedPeers and checks stateGeneration and the identity on every call, so a block or sign-out between the two checks is seen. On refusal it drops the request from approvedPaymentRequestIds.
  • Other LightningService.send callers (QuickPay, swap hold invoice, transfer, move-to-spark) keep the default {} and are unchanged.
  • Tests read: testLightningSendRechecksAuthorizationBeforeSubmissionAfterItsAwaits blocks the peer inside send and asserts no send, one failure callback and the approval removed, for both routes.

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

@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Scope note: the PR says Closes #1455, but two of that issue's four bullets (on-chain via Spark in PaykitRouteService.payReportingAllowance, and on-chain via the node through beforeBroadcastAttempt then the LDK queue) are untouched here.

@talosmachina Right: this PR covers the Lightning paths only. Switched to Refs #1455 and added the on-chain paths under Out of Scope, so the issue stays open for them.

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

Low candidate: A late refusal can discard another request’s Lightning proof. Bitkit/Services/PaykitPaymentProofService.swift:1378 deletes every pending Lightning proof with the same hash. Manual BOLT11 (Bitkit/Views/Wallets/Send/SendConfirmationView.swift:2095), LNURL (Bitkit/Views/Wallets/Send/LnurlPayConfirm.swift:418), and allowance payments (Bitkit/Services/PaykitPaymentProofService.swift:1388) now reach that cleanup when the late authorization check refuses. If two requests share an invoice and the first is pending on LDK, refusing the second can erase the proof record the first needs to deliver its preimage. Scope late-refusal cleanup to the refused request and its payer identity.

Pre-existing Low candidates: A contact block can still land between authorization and dispatch. The peer check runs before the serial LDK queue wait (Bitkit/Services/LightningService.swift:1363) and before Spark’s main-actor spend admission (Bitkit/Managers/SparkManager.swift:703). If contact removal commits in either gap, a valid automatic request can still reach the rail SDK. The same gaps existed on the base.

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

Low candidate: A late refusal can discard another request’s Lightning proof.

@pwltr out of scope: tracked in #1510, because the hash-wide cleanup in failLightningPayment(paymentHash:) predates this PR: master's failure paths in SendConfirmationView and LnurlPayConfirm already clear by hash, and the recheck refusal reuses them.

An on-chain payment request checked its authorization once, then
awaited more before the send. The node send now checks it again after
its allowance attempt is marked sending, right before the broadcast,
and the Spark withdrawal after the same mark, right before Spark sends.
A refusal there sends nothing and releases the request.

Verified: PaykitRouteTests, PaykitPaymentRequestServiceTests, PaykitPaymentProofServiceTests, SendConfirmationViewTests, PaykitAllowanceExecutorTests, ChannelFreeRailTests; swiftformat --lint
@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Scope note: the PR says Closes #1455, but two of that issue's four bullets (on-chain via Spark in PaykitRouteService.payReportingAllowance, and on-chain via the node through beforeBroadcastAttempt then the LDK queue) are untouched here.

@talosmachina both on-chain paths are covered in 9f4bd27, so Closes #1455 holds: the node send authorizes again after onAuthorized, inside beforeBroadcastAttempt after the prepare and the LDK queue, and payReportingAllowance authorizes again after markSending.

@ovitrif
ovitrif requested a review from pwltr November 26, 2026 15:24
@talosmachina

Copy link
Copy Markdown
Contributor

@ovitrif checked against 9f4bd27. This answers both of your replies.

  • On-chain via Spark: covered. payReportingAllowance authorizes again after markSending (PaykitRouteService.swift:237-238). A refusal there is thrown inside beforeSend, so startJournaledWithdrawal closes the journal and throws SparkWithdrawalNotSent, and the allowance ends .failed. The hop into spends.run after that is the same boundary the Lightning Spark recheck stops at.
  • On-chain via the node: the onAuthorized half is covered. The second authorizeOrRollBack() runs inside beforeBroadcastAttempt (OnchainSendAttemptService.swift:802), after the prepare's LDK queue. A refusal there fails the proof before clearBeforeDispatch and ends as .preDispatch, which privatePaymentListOutcomeAfterFailure maps to definitePreBroadcastFailure.
  • One part of that bullet is still open: the queue wait for the broadcast itself. prepared.broadcast() (OnchainSendAttemptService.swift:819) enters ServiceQueue.background(.ldk) again (:64), and inside that closure only the wallet, the node and the deadline are rechecked, not the authorization. bug: paykit request send can go out on a stale authorization check #1455 names "the LDK queue wait" that follows the authorization, and this is that wait. It is the same sync-closure limit as LightningService.submitPayment on the Lightning node path, which Greptile's open P1 thread is about.

So Closes #1455 holds if that queue wait is the accepted boundary for both node rails. In that case I'd add one line to Out of Scope saying so, because the issue's Expected asks for a recheck after the last await before submission. If you want it covered, it needs an authorization the sync closure can read, for example a cached refusal flag that ensurePaymentAllowed sets. That is a bigger change and better as a follow-up.

@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

So Closes #1455 holds if that queue wait is the accepted boundary for both node rails. In that case I'd add one line to Out of Scope saying so

@talosmachina yes, it is the accepted boundary for both node rails, as on the Android twin. Out of Scope now says so, tracked in #1513.

@talosmachina

Copy link
Copy Markdown
Contributor

@ovitrif checked: Out of Scope now names the ServiceQueue.background(.ldk) wait as the boundary on both node rails and links #1513, which describes both the Lightning and on-chain cases. With that, Closes #1455 holds. Nothing further from me on the scope point.

…recheck

Verified: xcodebuild build-for-testing (arm64 simulator)
Verified: xcodebuild test of PaykitPaymentRequestService, PaykitPaymentProofService, SendConfirmationView, PaykitAllowanceExecutor, ChannelFreeRail and SparkSendKey tests (755 pass); the new test fails on the previous head
Verified: xcodebuild test of the same six test classes (755 pass), swiftformat --lint
Verified: xcodebuild test of PaykitPaymentRequestService, PaykitPaymentProofService, SendConfirmationView, PaykitAllowanceExecutor, ChannelFreeRail and SparkSendKey tests (756 pass), swiftformat --lint
@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master into this PR in 6e45af1 to resolve a conflict in SparkManager.swift: the recheck now runs after master's failed-attempt lookup, right before spends.run. The push is 7905714 and adds three fixes for how this PR meets master's in-doubt Spark retries (#1415):

  • 8b1e936: a recheck refusal now ends the payment only when the refusal itself comes back. A retry of a send still in doubt comes back pending and keeps its proof; before, the Send and LNURL screens dropped it first.
  • 45b5a3b: a Spark leaf-selection retry, which waits up to 3 × 2 s, checks the request's authorization and then its deadline before it resends.
  • 7905714: an on-chain refusal at the recheck after the send was marked started now ends as unsent instead of showing Pending, and keeps the proof when the allowance's failed outcome isn't recorded.

Also added an Out of Scope entry for retries from the pending screen: #1516.

@ovitrif

ovitrif commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

Device run on 7905714

Ran on an iPhone 17 Pro simulator (iOS 27.0), Debug build of 7905714 against bitkit-docker's local Spark stack and the Pubky marketplace testnet with the payment request fixture (E2E_BUILD, E2E_BACKEND=local, E2E_NETWORK=regtest, E2E_HOMESERVER_PUBKY, SPARK_LOCAL_CONFIG_B64, SPARK_LOCAL_CHAIN_URL). The installed app's binary matches the build. The app was linked as a contact with the fixture's issuer, which sent each request.

  • 1. Payment request paid over Lightning from Spending (Spark): a 5 000 sat request whose only endpoint is an LNURL-pay, served locally with invoices from the Spark stack's Lightning node. Swipe To Pay → Bitcoin Sent. Spark logged the send through the new send(…recheckBeforeSubmission:…) path, the payee's node received it, and the payment proof was queued. The issuer's record moved to ProofSubmitted with a preimage matching the payment hash, and the request left the pending list.

    case1-spark-ln-request2x.mp4

  • 2. Payment request paid on-chain from Savings: a 20 000 sat request with only the regtest address endpoint. Swipe To Pay → Bitcoin Sent; the transaction confirmed to the issuer's address, the proof was queued, and the issuer's record moved to ProofSubmitted with the txid. The request left the pending list; the activity shows it as Confirmed with the issuer as contact.

    case2-onchain-request2x.mp4

The PR lists no manual tests or journeys (QA Notes: N/A), so these two cases carry no PR IDs.

No refusal at submission was logged in either case. The refusal window itself is covered by the PR's unit tests (not rerun here).

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

Low: A definite Lightning refusal leaves no durable record that the attempt was unsent until the failed outcome is saved. The automatic path (Bitkit/Services/PaykitAllowanceExecutor.swift:1356) and manual BOLT11 path (Bitkit/Views/Wallets/Send/SendConfirmationView.swift:2103) both clear the proof and release the private payment list before recording failure. If the app stops before that write or the write fails, recovery sees a fresh invoice with no outbound payment and leaves the attempt open. The wallet can then hide the unpaid request or reject another attempt as already recorded. Persist the definite refusal in a form recovery can use before cleaning up either path.

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: A definite Lightning refusal leaves no durable record that the attempt was unsent until the failed outcome is saved.

@pwltr Agreed. I'm keeping it out of this PR so the approved head and its device run stand; it's tracked in #1522.

Merging: approved on 7905714, CI green, and the device run on this head is posted above.

@ovitrif
ovitrif merged commit af19cc1 into master Nov 27, 2026
23 of 24 checks passed
@ovitrif
ovitrif deleted the fix/paykit-request-recheck branch November 27, 2026 10:10
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.

bug: paykit request send can go out on a stale authorization check

3 participants