Repository navigation
fix: use spark send key in retry - #1415
Conversation
Verified: unit suite with the CI selection on an iOS simulator, swiftformat --lint on the changed files
The retry checked again through the send's admission, which already recorded the attempt, so it was refused and never ran; the admission now runs once. A send refused before reaching Spark puts back the attempt kept before it, so a retry refuses the same way instead of holding the invoice until it expires, and the attempt store is locked. Verified: unit suite with the CI selection (4320 tests, 0 failures), swiftformat --lint on the changed files
A send its caller refused before it left (an expired request, a duplicate payment) kept its attempt, so a retry counted the unused key as reused. The attempt is now kept after the caller's checks, and the attempt store reads under its lock. Verified: unit suite with the CI selection (0 failures), swiftformat --lint on the changed files
4751af3 to
e15f481
Compare
|
Ready for review: rebased on master after #1411 and #1418 merged, self-reviewed, and the unit suite passes at e15f481. The Android twin follows once synonymdev/bitkit-android#2017 merges. |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e15f481660
ℹ️ 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".
[Critical impact] The PR changes how Spark Lightning invoice payments are retried. The payment changes appear safe to merge, with a non-blocking test-isolation issue. Findings
SummaryAdds seed-derived Spark send keys and saved attempt numbers so retries can reuse the same payment.
Acknowledged limits from ovitrif: a fresh-key error after an internal SDK retry may follow a committed transfer; production duplicate rejection remains unverified beyond the test servers; restore retries can race sync; repeated sends may swap leaves; recovered sends can temporarily show a low balance; device and successful leaf-swap checks remain untested on the available stack. Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Prepare invoice payment] --> B[Read saved attempt and failed keys]
B --> C[Derive key from seed, hash, and attempt]
C --> D[Admit send and save attempt]
D --> E[Send with the same key]
E --> F{Leaf selection failed?}
F -->|Yes, retry allowed| E
F -->|No| G[Return payment or error]
F -->|Retries ended| H{Key reused?}
H -->|Yes| I[Keep payment uncertain]
H -->|No| J[Refuse and restore prior attempt]
Reviews (1) · Last reviewed commit: "fix: keep a spark send attempt only once..." · Reviewed by Greptile |
The tests cleared the attempts the simulator wallet saved; they now put them back after each test. Verified: SparkSendKeyTests on the simulator, swiftformat --lint on the changed file
talosmachina
left a comment
There was a problem hiding this comment.
No findings. Gives each Spark BOLT11 send a deterministic idempotency key (seed secret, payment hash, attempt number) so a retry gets back the transfer an earlier try committed, and retries briefly while Spark can't select leaves. Reviewed e15f481, full tier, static: an iOS branch is not built here, so this reads the code against CI and the spark-sdk 0.28.3 source.
What I checked, and 6 candidates I ruled out
Read in full: SparkSendKey.swift, the send(bolt11:) path and new helpers in SparkManager.swift, the rail branch of LightningService.send (admission, refusal and uncertain paths), SparkSendKeyTests.swift, the ChannelFreeRailTests change.
SDK source traced (breez/spark-sdk 0.28.3): orchestrate_send (idempotency lookup by get_payment_by_id(key) before the expiry check and any send), bolt11::send and pay_and_persist_lightning_invoice (key becomes the TransferId), Payment::from_lightning (payment id is transfer.id, so failedIds matches the key), select_leaves_with_retry (the matched message is raised after the balance check, before any operator call), with_leafs_spent_retry!.
Test vector: recomputed independently (HMAC-SHA256 of the label keyed with the BIP39 seed, UUIDv5 over secret, hash and big-endian attempt); secret and both keys match the asserted values.
CI: validate, SwiftFormat and Greptile green; unit tests, integration tests and build still running at review time.
Ruled out
- Key format mismatch with listed ids:
TransferIddisplays the hyphenated lowercase UUID, and the key is lowercased, so thefailedIdscomparison holds. - Admission run twice on a leaf-selection retry: the
didRecordAttemptguard skipsadmitSendon the re-check, and the outer deadline check still runs; covered by the newChannelFreeRailTestscase. - Refusal leaving a stale attempt: every refusal under a fresh key restores the earlier attempt, and one thrown before
setrestores the same value, so it is a no-op. - Key 0 read as new after a wipe and restore: the wipe clears the attempts, so a resend under the committed attempt 0's key has
isReusedKeyfalse and a short balance would be refused, butrefuseUnverifiedRestoredInvoicerefuses a pre-restore invoice the operators show as sent or pending before the send is reached. - Lost UserDefaults write after a crash:
next()re-derives the attempt by skipping listed failures, so a lost write lands on the same key; attempt 0 is the default anyway. - Leaf-selection failure after a transient operator error: refused under a fresh key though a commit could precede it; already named in the PR's Gaps.
Merge confidence: 4/5, the unit and integration suites had not finished in CI and the payment path was not built here.
Reviewer model: Claude Opus 5.5
Reasoning effort: Not exposed
Metadata note: the runner reports the model but not a reasoning setting.
The SDK selects leaves again when it retries a failed submission, so a short balance or leaves it can't select under a new key can follow a transfer it committed. Such a refusal now keeps the invoice's attempt and notes when it was refused, and the node holds off the invoice until Spark has synced since. A retry over Spark isn't held, as one under the same key can't pay twice. Verified: unit suite with the CI selection (4322 tests, 0 failures), swiftformat --lint on the changed files
Verified: ChannelFreeRailTests and SparkSendKeyTests on the simulator
pwltr
left a comment
There was a problem hiding this comment.
Reviewed e15f481.
Medium candidate: Bitkit/Managers/SparkManager.swift:772 treats a fresh-key leaf-selection error as proof that nothing went out and clears the cross-rail hold through Bitkit/Services/LightningService.swift:1239. The SDK can raise this error after a lost response to a committed send. If the app's same-key retries still surface the error, Spark history has yet to show the original payment, and the user retries once a channel can pay, the node can start a second payment for the invoice. A controlled run would establish whether both attempts can settle through this path. Existing discussion
Low: After ordinary history shows a failed Spark attempt, a transient failure of the separate failed-only read at Bitkit/Managers/SparkManager.swift:707 makes a retry reuse the failed key. The SDK returns the old failure without starting a new payment, and Bitkit/Managers/SparkManager.swift:746 returns the hash as if submission went ahead. The old failure cannot clear the new hold, so the unpaid invoice can show Pending and block another retry until expiry and a subsequent sync.
Low: BitkitTests/SparkSendKeyTests.swift:14 clears sparkSendAttempts from the hosted app's standard preferences before and after each test. On a test host with saved retry state, running the suite deletes that state. Existing discussion
Review details
Quick review
Model: Claude Opus 5.5
Reasoning effort: high
General review
Model: GPT-6.2 Sol
Reasoning effort: high
Cross-project review
Model: GPT-6.2 Sol
Reasoning effort: high
Combined review
Model: GPT-6.2 Sol
Reasoning effort: high
…t and quickpay Verified: PaykitPaymentProofServiceTests, QuickPayPaymentCoordinatorTests and ChannelFreeRailTests on the simulator
Paykit, QuickPay and private invoices read the rail's list, so a refusal that may have reached Spark reads pending over an earlier failure until a sync reached Spark since. A Spark retry still sends under the same key. Verified: ChannelFreeRailTests, SparkSendKeyTests, QuickPayPaymentCoordinatorTests and PaykitPaymentProofServiceTests on the simulator
Under a key Spark already failed, as when its failed list couldn't be read, Spark returns that failure and sends nothing, so the send is refused instead of read as submitted. Verified: SparkSendKeyTests on the simulator
A transfer the refused send committed can stay unlisted after a sync and still go out, so the refusal holds the node, a move to Spark ahead of a send and the rail's list until the invoice expires. A refusal made while the list is read counts too, and an invoice that expires during a leaf-selection retry ends it with the leaf failure. Verified: ChannelFreeRailTests, SparkSendKeyTests, QuickPayPaymentCoordinatorTests, PaykitPaymentProofServiceTests and MoveToSparkManagerTests on the simulator
Until the invoice expires the node send is refused with a refusal that may have reached Spark, instead of held pending with no event to resolve it, unless an earlier send reads pending or paid. Verified: none (ChannelFreeRailTests run next)
… expires A transfer committed before the expiry can settle after it, so the rail's list reads the refused send pending until Spark syncs past the expiry. A refusal noted while the earlier-attempt check reads Spark's list also counts. Verified: none (ChannelFreeRailTests run next)
Leaves Spark still can't select after its retries can follow a transfer the send committed, as the SDK selects them again after an operator error, so the send stays in doubt under any key until Spark settles it or its invoice expires, as any other unknown outcome does. This replaces the refusal marker, and the Paykit and QuickPay handling of a refusal that may have reached Spark, as the hold already keeps the node off the invoice and the proof, allowance and charge pending. Verified: none (suite on the simulator next)
A send whose leaves Spark can't select stays in doubt under any key, and a short balance or expiry on a leaf retry reads as that leaf failure. The hold reports the payment failed once a sync after the invoice's expiry ends it, and a retry over Spark goes out at once under the send's derived key, which can't pay twice. Verified: ChannelFreeRailTests and SparkSendKeyTests pass on the simulator.
A retry of a send in doubt that Spark refuses before it goes out reads as pending, as the earlier attempt may have paid, and an expiry under a reused key stays in doubt. The expiry reports a failure only when Spark lists none paid or pending, and a move to Spark for a send in doubt is refused as pending. Verified: ChannelFreeRailTests, SparkSendKeyTests and SendSheetLifecycleTests pass on the simulator.
A retry of a send in doubt stopped before it records its attempt, by its fee limit, a failed estimate or its caller's last check, leaves that send pending, as it may have paid. Verified: ChannelFreeRailTests and SparkSendKeyTests pass on the simulator; swiftformat lint passes.
A retry of a send in doubt whose attempt Spark lists failed waits for that failure to settle the hold before it takes a new key, so the earlier attempt's failure is never read as the new attempt's. Verified: ChannelFreeRailTests and SparkSendKeyTests pass on the simulator; swiftformat lint passes.
An expired send in doubt records the invoice's paid attempt whenever Spark dated it, so a paid send never reports a failure, and a new key waits whenever the send is in doubt. Verified: ChannelFreeRailTests and SparkSendKeyTests pass on the simulator; swiftformat lint passes.
Fixed in 0883b1c: that error now keeps the send in doubt under any key, so the node stays off the invoice until Spark settles the attempt or a sync after the invoice expires, which reports the failure.
Fixed in 45950e2: a failed payment Spark returns for the key is now refused (
Fixed in 91da213: the tests snapshot and restore the saved attempts. |
pwltr
left a comment
There was a problem hiding this comment.
Reviewed 0883b1c.
Low: Retrying an amountless invoice at a different amount while its first Spark payment is pending can show the second amount as paid. Bitkit/Services/LightningService.swift:1660 allows same-key replay and Bitkit/Managers/SparkManager.swift:718 reuses the key regardless of the new amount. Spark returns the original payment, while Bitkit/Views/Wallets/Send/SendSuccess.swift:38 displays the new draft amount.
Expiry currently treats a missing matching Lightning row as terminal failure when the Activity fallback returns without throwing. That can mistake a missing or stale history result for a payment outcome.
Medium candidate: For a provider-routed send whose response was lost, a post-expiry wallet sync can advance its timestamp even when pending-send recovery or payment-history import failed. If the accepted send still has no matching row, Bitkit/Services/LightningService.swift:1969 can release QuickPay or Paykit accounting for a payment that later settles. Can the provider-accepted send remain absent from that qualifying history read and surface as paid later?
Low: On regtest, a BOLT11 invoice containing a Spark address can be paid by direct Spark transfer. The completed row has Spark details, so Bitkit/Managers/SparkManager.swift:909, Bitkit/Managers/SparkManager.swift:2014 and Bitkit/Managers/SparkManager.swift:2186 miss it. The send can show Pending and then report failure at expiry even though the recipient was paid.
Low candidate: If Spark publishes a success after the expiry history snapshot, Activity can already show success while the app is still awaiting the success event. Bitkit/Services/CoreService.swift:1411 leaves the succeeded row alone, but Bitkit/Managers/SparkManager.swift:2004 treats that return as failure. The disputed ordering is whether expiry can take the hold between the Activity write and success delivery.
Review details
Quick review
Model: Claude Opus 5.5
Reasoning effort: high
General review
Model: GPT-6.2 Sol
Reasoning effort: high
Cross-project review
Model: GPT-6.2 Sol
Reasoning effort: high
Combined review
Model: GPT-6.2 Sol
Reasoning effort: high
A send Spark lists no attempt of at its invoice's expiry was read as failed whenever its stored row wasn't pending, a succeeded row too, so a success Spark published after the list was read could be reported as a failure. The stored row's status now decides: succeeded stays paid. A retry of an amountless invoice at another amount reused the held attempt's key, so Spark returned the first payment while the send showed the new amount. Each attempt now keeps its amount, and a same-key retry at another amount waits for the hold like a duplicate. Verified: ChannelFreeRailTests, SparkSendKeyTests and FailPendingLightningSendTests pass on the simulator; swiftformat lint passes.
At expiry a send's pending attempt could lose to a newer failed attempt or to the filter for attempts listed before the send, so a send Spark still ran was failed. A paid attempt, then a pending one, now decides it. A failed attempt's outcome also rereads the stored row, so a success saved since the list was read stays paid. Verified: ChannelFreeRailTests, SparkSendKeyTests and FailPendingLightningSendTests pass on the simulator; swiftformat lint passes.
At its invoice's expiry a send in doubt ended its hold and failed its row even while a retry under its key was in flight, so a retry refused before it went out left the send's waiters without an outcome. The hold now stays until that retry ends, and a later sync settles it. Verified: ChannelFreeRailTests, SparkSendKeyTests and FailPendingLightningSendTests pass on the simulator; swiftformat lint passes.
A retry under the send's key that started while the expired send's row was written could still lose its hold, and one that ended meanwhile was reported failed. The hold now ends only when no retry is in flight or started since the check, judged under the lock that starts retries. Verified: ChannelFreeRailTests, SparkSendKeyTests and FailPendingLightningSendTests pass on the simulator; swiftformat lint passes.
The expiry check reported a send settled even when it kept the hold for a retry, so a list read right after showed no pending send while the invoice was still held. It now reports settled only once the hold is gone. Verified: ChannelFreeRailTests, SparkSendKeyTests and FailPendingLightningSendTests pass on the simulator; swiftformat lint passes.
Fixed in 62a7f09. Each attempt keeps its amount, and a retry under the same key at another amount now waits for the hold, like a duplicate, instead of going out. The Android twin is synonymdev/bitkit-android#2071, which refuses that retry with an error.
A send Spark lists no attempt of, after a sync past its invoice's expiry, failing is the intended end of the hold: past expiry the payee no longer accepts it, and the hold has to end rather than stay Pending. The gap was that a row which wasn't pending, a succeeded one included, also read as failed. Fixed in 62a7f09: the stored row's status now decides, and a succeeded row stays paid.
Confirmed in spark-sdk 0.28.3:
The app can't tell such a sync from a complete one, so closing this needs a signal from the SDK. Filed as #1463, which covers the Android twin too. The window is one sync past expiry where the wallet sync succeeds and the import fails.
Regtest only:
Fixed in 62a7f09 and c5ea2db. A succeeded row is no longer failed at expiry, whether Spark lists no attempt or a failed one. A paid or pending attempt, whenever Spark dated it, decides the send. Since ac556ad, f758f5d and 3c465d3, the hold also stays while a retry under its key is in flight or started during the check, and reads as pending until a later sync settles it. |
pwltr
left a comment
There was a problem hiding this comment.
Reviewed 3c465d3.
Low: Two installations of the same wallet can approve different amounts for one amountless invoice and derive the same Spark key. If the first payment enters the second installation's SDK history after its earlier-payment check, SDK 0.28.3 returns that payment by key without comparing amounts. Bitkit/Managers/SparkManager.swift:766 accepts its completed status, and Bitkit/Views/Wallets/Send/SendSuccess.swift:38 displays the second installation's draft amount.
Expiry uses a payment snapshot to write Activity and release the send hold. A retry or settlement can advance while those operations are in progress.
Low candidate: Bitkit/Services/LightningService.swift:1969 can write Failed to Activity before the retry check at Bitkit/Services/LightningService.swift:1972 keeps the invoice Pending. This requires the expiry listing to miss the live attempt while its pending Activity row is still present. The overlapping-retry test could exercise this by checking the stored row as well as the hold.
Low candidate: Bitkit/Services/LightningService.swift:1978 can emit failure if the expiry snapshot misses a live send and Spark's success reaches Activity afterward. For a Paykit send, Bitkit/Services/PaykitPaymentProofService.swift:1378 can then delete the proof before the success callback attaches the preimage. The disputed ordering is whether a qualifying sync with successful history import can leave the attempt absent from that expiry snapshot and deliver success afterward.
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
Out of scope: tracked in #1507, because it needs the same wallet paying on two devices before the first payment syncs to the second.
Out of scope: both tracked in #1508, because both need the expiry listing to miss a live send, and the first corrects itself on the next sync. |
|
QA for 3c465d3: 🟢 Pay an invoice once, Open the same invoice againPay an invoice once A 10 000-sat invoice paid once: one Spark transfer and one provider send request of 10 000 sats plus a 42-sat fee, the receiver up 10 000, one Sent row in Activity.
Open the same invoice again Opening and confirming the same invoice again shows Bitcoin Sent without paying again: the app returns the earlier payment, the wallet balance, its Spark transfers and provider send requests stay unchanged, and Activity keeps one Sent row.
|
|
Merging: approved, CI green, and the device run on 3c465d3 passed. |
Closes #1412
Closes #1413
Twin: synonymdev/bitkit-android#2020
Refs: synonymdev/bitkit-android#2014
Description
SparkSendKey: each attempt's key is a UUIDv5 of a secret derived from the wallet seed, the payment hash and the attempt number, so a retry reuses its attempt's key and the Spark operators return the transfer it committed instead of sending again. A seed secret, not the bare hash, so no other wallet derives the same transfer id and the operators can't link the transfer to the invoice. Android derives the same keys (shared test vector), so a restore across apps keeps them.SparkSendAttempts, kept until the invoice expires, cleared with the wallet). A send moves to the next attempt only past keys Spark's local list shows failed, as a failed key can't send again.UserDefaults, whose writes can't fail.Out of Scope
LightningService.swift: the other rail holds stay as they are; the send's admission now runs once, as Spark checks the send again before each leaf-selection retry.Design
N/A — no UI changes.
Preview
N/A
QA Notes
Setup
N/A — no device testing required: the cases need crashes mid-send and restores, covered by the regtest proof and unit tests below.
Journeys
N/A — no user-visible behaviour change.
Manual Tests
N/A
Automated Checks
SparkSendKeyTests.swift— derives the shared test vector Android asserts tooSparkSendKeyTests.swift— a first attempt takes the first key, a retry reuses its attempt's key until Spark lists it failed, then takes the nextSparkSendKeyTests.swift— an expired invoice's attempt is droppedSparkSendKeyTests.swift— a short balance under a reused key stays in doubtSparkSendKeyTests.swift— an expiry under a reused key stays in doubtSparkSendKeyTests.swift— a new key waits while the earlier attempt is in doubtSparkSendKeyTests.swift— leaves Spark can't select keep the send in doubt under any keySparkSendKeyTests.swift— an invoice expiring during a leaf retry ends it with the leaf failureSparkSendKeyTests.swift— a short balance on a leaf retry ends it with the leaf failureSparkSendKeyTests.swift— a send retries while Spark can't select its leaves, stops once it can no longer go or after its last retry, and isn't retried for other failuresSparkSendKeyTests.swift— a refused attempt gives back the earlier oneChannelFreeRailTests.swift— a Spark send checked again before a retry goes outChannelFreeRailTests.swift— a Spark send in doubt after a leaf failure ends at its invoice's expiryChannelFreeRailTests.swift— a Spark retry of a send in doubt after a leaf failure goes out under its keyChannelFreeRailTests.swift— a Spark send in doubt Spark lists paid at its invoice's expiry reports no failureChannelFreeRailTests.swift— a Spark retry of a send in doubt refused before it goes out stays pendingChannelFreeRailTests.swift— a Spark retry of a send in doubt over its fee limit stays pendingChannelFreeRailTests.swift— a Spark retry of a send in doubt stopped before submission stays pendingChannelFreeRailTests.swift— a move to Spark for a send in doubt under its key is refused as pendingSparkSendKeyTests.swift— a failed payment Spark returns is refusedSparkSendKeyTests.swift— a retry under the same key at another amount waits for the holdSparkSendKeyTests.swift— an expired send whose row already succeeded stays paidFailPendingLightningSendTests.swift— failing a pending send returns the row's status after itChannelFreeRailTests.swift— an expired send Spark still lists pending is decided by that attemptChannelFreeRailTests.swift— a send in doubt keeps its hold at expiry while a retry is in flightChannelFreeRailTests.swift— a send in doubt keeps its hold, read as pending, when a retry starts as its expiry is recordedEvidence
ChannelFreeRailTests,SparkSendKeyTestsandswiftformat --linton the changed files at HEAD: all pass.Regtest proof of the SDK behaviour this relies on (spark-sdk 0.28.3 client; operator
breez/spark@b54845cand Breez's test SSP, see Gaps). Each "nothing sent" was checked on the operators' transfers, the SSP's send requests and the receiver's balance.On the SSP route a recovered transfer resumes its Lightning request, which the SSP keys by transfer id, so one key never pays twice; a second payment needs a new attempt's key.
Regtest repro of the leaf-selection failure (found by the swipe-to-pay review run J1 on synonymdev/bitkit-android#2017, local regtest, master at its base): a combined payment moved 29 602 sats to Spark, and Spark's send about 1 s later failed with
Tree service error: generic error: Failed to select leaves after all retries. Master treated that as an unknown outcome, so the payment went Pending and never resolved on Android ("Stopped polling ... until Spark syncs again"); the funds stayed in Spark and a retry paid. 0.28.3 raises it inselect_leaves_with_retryafter its balance check and before any operator call, so a send under the same key can be retried safely.The Android twin's case 1 run found that the regtest operator build
breez/spark@b54845crejects every leaf swap, so Spark there paid only amounts it could cover with leaves it already held (#1418's J1 hit the same failure at 50 000 sats). With the operators patched for leaf swaps (synonymdev/bitkit-docker#43), the Android twin's case 1 paid 50 000 sats after a move and 10 000 sats needing a leaf swap on the first send.Gaps
breez/spark@b54845c, Breez's test SSP), not the servers 0.28.3 pins or Lightspark's production SSP; their duplicate-transfer-id rejection and SSP dedup are proven on these builds only.Models used
Claude Opus 5.5(reasoning:medium)Claude Opus 5.5(reasoning:medium),Claude Sonnet 5.5(reasoning:high)Gemini 4 Neon(reasoning:high)