Repository navigation
fix: recheck paykit request authorization at submission - #2070
Conversation
A payment request's Lightning send checks its authorization once more right before submission, after the last journal write: on Spark in its late check and before a leaf-selection resend, on the node right before its queue. Refused before anything left, the request ends like a refusal before the send; a resend refused after an earlier try stays pending. Verified: AppViewModelSendFlowTest (new tests fail with the recheck or the guard off), LightningRepoTest, QuickPayRepoTest, just lint
Verified: none (changelog text only)
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
[Medium impact] This change appears safe to merge. SummaryRechecks Paykit request authorization after payment records are written and before Lightning submission.
Acknowledged scope: Reviews (1) · Last reviewed commit: "fix: recheck paykit request authorizatio..." · Reviewed by Greptile |
jvsena42
left a comment
There was a problem hiding this comment.
Approving at 97d305c with one LOW open, below. It's in the review body because the file isn't in the diff. Fix it here or in a follow-up, your choice; please reply with which.
LOW: changelog.d/next/1962.fixed.md still describes only QuickPay. At head it reads "QuickPay Lightning payments through Spark now stop if the wallet locks while the send is being prepared." It was narrowed in #2053 (3abdd06) because a Paykit request's authorization was still checked once. This PR fixes that on both rails and closes #1962, but the release notes would leave out the user-facing part: a request is no longer paid after its contact is blocked mid-send. Widen that same fragment rather than adding a second one for the issue, e.g. "Lightning payments now stop if QuickPay's wallet lock or a payment request's authorization lapses while the send is being prepared."
Checked and clean:
- Gate at submission, both rails. On Spark,
payInvoiceRecheckedAtSubmission→authorizeSendruns the fullonBeforeSend()after the last journal write (SparkRepo.kt:684) and before each leaf resend (:804). Only non-suspending checks follow beforesparkService.send. On the node, the recheck runs afteraddLdkSendHashand beforelightningService.send(LightningRepo.kt:1869-1872), and a refusal releases admission in thefinally. TheServiceQueue.LDKwait is the declared out-of-scope window. ensurePaymentAllowed(forExecution = true)is read-only. There's norunBlocking, and Spark holds no mutex across the recheck.- Wrong refusals: a late refusal on either rail happens before anything leaves, so it ends like a first-check refusal (toast or error screen, proof failed, allowance finished, no pending row). At a leaf resend it settles as
PaymentPendingExceptionwith cleanup skipped, so a refusal can't mark a dispatched send failed, and a retry can't double pay. - Callers: only the request send (
AppViewModel.kt:8815) is newly rechecked. QuickPay is unchanged. Allowance, swap hold, move-to-Spark and transfer keep their existing checks (allowance tracked in #2069). - Cancellation: the send runs in AppViewModel's
viewModelScope, so only finishing the activity can cancel the new suspending recheck. That leaves the same held-until-expiry state SparkRepo already documents for a cancel inside the send.
perf: marginal (one linkedPeers() read per request send and per leaf resend; background refreshes are refused admission during a submission), not measured.
Device gate: no device check needed — no UI change, and the window can't be timed on a device.
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
Regtest APKDownload bitkit-dev-debug universal APK (expires in 30 days). |
Verified: PaykitAllowancePayerTest, PaykitAllowanceExecutorTest, PaykitPaymentProofRepoTest, PaykitPaymentRequestRepoTest, LightningRepoTest, AppViewModelSendFlowTest
Verified: none (changelog text only)
Verified: just lint; just test passed before formatting
talosmachina
left a comment
There was a problem hiding this comment.
No findings. Runs a Paykit payment request's authorization again right before submission on both rails: inside Spark's late check and before a leaf-selection resend, and on the node after the send hash is written; a refusal there ends the request only when the result shows nothing went out. Reviewed 97d305c, full tier, static: an auto review on bitkit-android does not build the branch here, so this rests on the code and on CI.
What I checked, and 5 candidates I ruled out
Read in full: LightningRepo.payInvoiceChecked and payInvoiceWithLdk, SparkRepo.payInvoice and sendRetryingLeafSelection, AppViewModel.proceedWithLightningPayment and clearFailedLightningPayment, PaykitPaymentRequestRepo.ensurePaymentAllowed and hasCurrentExecutionContext, QuickPayRepo.dispatchBolt11.
Call sites traced: sendLightning has one caller; payInvoiceRecheckedAtSubmission is reached only when incomingPaymentRequest != null, whose check only sets authorizationError, so running it again has no side effect. The rechecks call the caller's onBeforeSend directly, not authorizeSend, so admission and rail recording still run once.
CI at review time: build-and-test, build-local and Greptile green; lint and two e2e suites still running.
Ruled out
- The
sentNothinggate drops an old cleanup case: before this PRauthorizationErrorwas set only by the pre-update check (same throwable, caught by===) or by the first check, whose refusal isPaymentAbortedBeforeSendon both rails and is not wrapped byexecuteOperation. Both still match. - A refusal with a result that is neither sent-nothing nor pending: a false resend check returns the earlier leaf-selection failure, which
SparkRepoalways turns intoPaymentPendingException, andclearFailedLightningPaymentkeeps that pending. No other path sets the error after something could have gone out. - The node refusal leaves its send hash and record behind: true, but
payInvoiceAuthorizedAtSubmissionalready stops after the same write.earlierNodeSendreadsrecordsBeforeper call and drops a hash the node does not list, so a later send of the invoice is not held by it. linkedPeers()waits on the Paykit operation lock inside Spark's journal window: only a process death during that wait leaves a hold, and the hold ends at the invoice's expiry. That needs an unlikely precondition.- A spurious refusal from the app's own state between the two checks: nothing on the send path between them touches request history, acceptance,
processingSubscriptionIdsorstateGeneration, andisCurrentStatecompares a generation read in the same call.
Merge confidence: 4/5. No findings, but I could not build the branch here and lint and two e2e suites had not finished.
Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed (this run's metadata does not report an effort setting)
Verified: PaykitAllowancePayerTest, PaykitAllowanceExecutorTest, PaykitPaymentRequestRepoTest; just lint
Drops the identity guard of 1af4c14: a refusal after an identity switch left the attempt stuck as sending, while master already sends in that case. Verified: PaykitAllowancePayerTest, PaykitAllowanceExecutorTest, PaykitPaymentRequestRepoTest; just lint
@jvsena42 Widened in 1d346e9: "Lightning payments now stop if QuickPay's wallet lock lapses, or a payment request's contact is blocked, while the send is being prepared." It's this PR's only fragment. |
|
7e234a5 also fixes #2069 here: an allowance's automatic Lightning payment now rechecks its request right before submission (expired request or blocked contact), and a stop at submission ends its attempt as unsent and releases the reservation. The description lists the new tests; an identity switch during a send stays out of scope, as on master. |
pwltr
left a comment
There was a problem hiding this comment.
Reviewed 7e234a5.
SparkRepo.kt:804 checks the payment deadline and exit hold before awaiting the new Paykit authorization lookup. Recheck both after the lookup and before resending. If either check fails, keep the earlier leaf-selection result so its outcome can still settle.
Medium: A Paykit payment can reach Spark after its deadline if the lookup waits across the cutoff. This can affect an automatic allowance payment or a manual payment whose reviewed quote expires while the invoice is still valid.
Low: An emergency exit can place Spark on hold while a retry waits for authorization. The retry still reaches Spark when the lookup returns, which can prolong the exit’s wait for in-flight spending.
Low candidate: If a Paykit lookup fails during an automatic payment and the subsequent failure report also fails, PaykitAllowanceExecutor.kt:998 can leave an unsent attempt in SENDING. Recovery has no rail result to clear it, so it may continue counting against the monthly allowance. Verify that recovery releases it after both failures and a relink.
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
Verified: SparkRepoTest, LightningRepoTest; just lint; the new test fails with the old check order
Fixed in 16cf317: a resend now runs the authorization check first, then reads the deadline and exit hold, and returns the earlier leaf-selection result if either fails. A new
Out of scope: tracked in #2115, because it predates this PR and applies to every refusal before send, not only this recheck. |
pwltr
left a comment
There was a problem hiding this comment.
Reviewed 16cf317.
Low: A Paykit payment stopped by the final LDK authorization check still leaves its invoice hash in the send cache (LightningRepo.kt:1869). If the same valid invoice is retried with enough Spark balance while LDK is unavailable, earlierNodeSend refuses it as a possible node payment (LightningRepo.kt:1736). Clear the record made by the refusal while preserving any record of an earlier real submission.
Low candidate: Spark can stop a retry at submission while keeping the earlier transfer's hold under the same key (SparkRepo.kt:653, SparkRepo.kt:683). If a separate same-invoice send becomes uncertain after the request resolves its endpoint and before the Lightning repository starts its checks, that refusal can clear the manual request's proof (AppViewModel.kt:8264) or clear the automatic proof and release the allowance reservation (PaykitPaymentProofRepo.kt:937, PaykitAllowanceExecutor.kt:998). If the original transfer then settles, the request may lose its receipt or allowance accounting. Verify that ordering and preserve the earlier transfer's pending outcome when refusing the retry.
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
Verified: just compile, just test, just lint
@pwltr fixed in 6e143c0: a refused node send drops only the record it made, so the invoice can be retried on Spark, and keeps any record another send of the same invoice made.
out of scope: tracked in #2124, because it needs a separate same-invoice send to turn uncertain inside the window between endpoint resolution and the repository's checks; it is listed under Out of Scope. |
pwltr
left a comment
There was a problem hiding this comment.
Reviewed 6e143c0 against 576ac14.
Medium: The new recheckBeforeSubmission parameter in LightningRepo.kt:2117 breaks four SparkExitRepoTest.kt verifications carried in from 576ac14 (base lines 1615, 1654, 1692 and 1853). Each still registers 19 matchers, and the merged call passes a twentieth argument as a default lambda. Add recheckBeforeSubmission = any() to all four on the merge candidate.
Medium candidate: A direct on-chain request checks contact authorization before retaining the signed receipt (LightningRepo.kt:2200–2206). If a contact deletion can commit during that write, the prepared transaction can still reach native broadcast (LightningService.kt:1144–1154). The confirmation sheet blocks ordinary navigation during submission. An independently running contact deletion that can commit during receipt retention would establish the user-facing trigger.
Low: A failed journal clear at SparkRepo.kt:1452 masks a withdrawal's definite authorization refusal. The send has never reached Spark, but AppViewModel.kt:8128–8165 can show it as unresolved and hold its proof, private list and allowance attempt for reconciliation. Preserve the definite refusal when the cleanup write fails.
Low candidate: At LightningRepo.kt:1868–1884, two LDK attempts for the same invoice can leave a send hash if both stop at the final check and the older attempt refuses first. The later refusal restores the older attempt's mark, and a Spark retry can be blocked until LDK can list its payments. This needs two separate request contexts that can get the same invoice past the proof and private-list guards.
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
Verified: just compile, just test, just lint
Verified: LightningRepoTest, SparkRepoTest, just lint
@pwltr fixed in 1f3440b: master is merged in and the four verifications take
out of scope: tracked in #2130, because it is the same node-side boundary as the Lightning queue wait: the block check suspends on the Paykit SDK and can't run inside the receipt write or the node queue. Out of Scope now names both.
Fixed in f045823: the journal closes best-effort, so the refusal reaches the caller even when that write fails.
No change: the record left behind fails safe. It only holds a Spark retry of that invoice until the node's payment listing shows no send and clears it, and nothing is sent twice. |
…recheck Verified: just compile, just test (AppViewModelSendFlowTest rerun after its fix), just lint
Verified: just test file AppViewModelSendFlowTest, detekt
|
Merged master into this PR in 79fc467 to resolve conflicts and pushed it with 6a08924:
Also added an Out of Scope entry for the hardware-wallet path: #2138. |
Device run on 6a08924Ran on an Android 15 emulator (API 35, arm64), dev debug build of
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). |
jvsena42
left a comment
There was a problem hiding this comment.
Re-approving at 6a08924. The changelog LOW from my last review is fixed in 1d346e9: the 1962 fragment now covers the request and allowance rechecks.
Delta since 97d305c checked and clean:
- Allowance recheck:
ensureAutomaticPaymentAllowedchecks only the deadline (the samepaymentDeadlineAtthe executor already passes) and aBLOCKEDlinked peer. AlinkedPeers()failure fails closed to MANUAL.linkedPeers()takesoperationLockatOrdered, which admission never refuses, and the executor holds no SDK lock atpayLightning, so there's no self-refusal or deadlock. Both refusal errors now count as unsent infailLightningPayment. - On-chain request recheck (
LightningRepo.kt:2197-2205): runs aftercheckApprovedSpendand beforeretainPreparedReceipt. A refusal releases the prepared tx and the attempt (OnchainSendNotDispatchedError), so a retry can't double pay or be blocked. - Node Lightning refusal rollback: a hash is dropped only when this send created it and nothing else holds it. I traced it against concurrent and earlier sends of the same key.
- Spark resend: authorization runs first, then the synchronous deadline and exit checks, with nothing suspending before
sparkService.send. - Withdrawal refusal with a failed journal close: the refusal surfaces as
PaymentStoppedAtSubmission, and a kept journal blocks further withdrawals withWithdrawalPendinguntil a sync drops it, so there's no double withdrawal. - Cancellation: the allowance runs under
NonCancellable; on-chain releases the prepared tx infinally; the withdraw journal closes underNonCancellable. - Merges: 1f3440b has no conflict resolutions; a0b84ee keeps the
sentNothinggate with master'srequestId.
perf: marginal (one or two extra linkedPeers() reads per allowance, on-chain request and withdrawal send), not measured.
Device gate: no device check needed — no UI change; the refusal windows can't be timed on a device.
Reviewer model: Opus 5.5 (claude-opus-5-5) coordinating; Fable 5.2 (claude-fable-5-2) delta review
Reasoning effort: Not exposed
|
Merging: approved on 6a08924, CI green, and the device run on this head passed both cases. |
Closes #1962
Closes #2069
Closes #2118
Twin: synonymdev/bitkit-ios#1493
Description
PaykitPaymentRequestRepo.ensurePaymentAllowed) ran once, before the send's journal writes, which suspend.LightningRepo.payInvoiceRecheckedAtSubmissionruns the caller's check again right before submission, for a check with no side effects: on Spark inSparkRepo.payInvoice's late check (added by fix: recheck spark send authorization at submission #2053) and before a leaf-selection resend; on the node after the send hash is written, right beforeLightningService.send. Refused there, nothing is sent and the result fails withServiceError.PaymentStoppedAtSubmission.PaykitAllowancePayer.payLightningrechecks withPaykitPaymentRequestRepo.ensureAutomaticPaymentAllowed, which refuses an expired request or a blocked contact.PaykitPaymentProofRepo.failLightningPaymentnow treats a stop at submission and an abort before send as unsent, so a refused allowance payment ends its attempt and releases its reservation.AppViewModelsends a manual payment request through it. The refusal ends the request as a refusal before the send does: the proof is failed, the private list released, no pending screen. That cleanup now runs only when the result shows nothing left, so a Spark resend refused after an earlier try that may have committed stays pending.LightningRepo.sendOnChaintakesrecheckBeforeSubmission, run after the transaction is prepared and its spend approved, before its receipt is kept; a refusal releases the prepared inputs and ends asOnchainSendNotDispatchedError, which the send flow treats as unsent. On Spark,SparkRepo.withdrawrechecks after its journal write and before the withdrawal goes out; a refusal closes the journal and fails withServiceError.PaymentStoppedAtSubmission, which the service-routed send ends as a refusal.Out of Scope
ServiceQueue.LDKand before an on-chain send keeps its prepared receipt, so a block landing during the queue wait or that write is not seen. The block check reads the Paykit SDK (linkedPeers()), which suspends and can't run on that queue; QuickPay's synchronous check still runs there: bug: a node send waiting in its queue pays a contact blocked meanwhile #2130, raised in fix: recheck paykit request authorization at submission #2070 (review)Design
N/A — no UI changes.
Preview
N/A — no user-visible changes.
QA Notes
Setup
Device run on 6a08924 (#2070 (comment)): a Spark Lightning payment request and an on-chain payment request, both paid on a dev build against bitkit-docker's local Spark stack and payment request fixture (regtest). The block itself lands inside a window a few cache writes 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
AppViewModelSendFlowTest.kt— a payment request blocked right before submission sends nothing and clears its proofAppViewModelSendFlowTest.kt— a payment request blocked before a Spark resend stays pending and keeps its proofLightningRepoTest.kt— a payment request's Spark send checks its authorization again right before sending, and its node send stops at submission when it lapsesPaykitAllowancePayerTest.kt— an allowance's Lightning payment checks its contact again right before submissionPaykitPaymentRequestRepoTest.kt— an automatic payment is refused once its contact is blocked or its request expiredAppViewModelSendFlowTest.kt— an on-chain payment request blocked while its send is prepared sends nothing, and a Spark leg refused at its last check releases the request proofLightningRepoTest.kt— an on-chain send refused at its recheck releases the prepared transaction; a refused node Lightning send keeps an earlier send's record and one a send started meanwhile made, and stays refused when dropping its own record failsSparkRepoTest.kt— a Spark withdrawal refused after its journal write sends nothing, closes the journal, and stays refused when closing it failsPaykitPaymentProofRepoTest.kt— a stop at submission or an abort before send clears the proof as unsentEvidence
{ true }and never rechecks.just compile,just test,just lint.Gaps
None.
Models used
Claude Opus 5.5(reasoning:medium),Claude Sonnet 5.5(reasoning:high)Gemini 4 Neon(reasoning:high)