Repository navigation
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".
| if isLeafSelectionFailure(error) { | ||
| return isReusedKey ? error : ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description"), underlying: error) |
There was a problem hiding this comment.
Keep potentially committed leaf-selection failures uncertain
If a first send commits a transfer but encounters an operator error, the SDK's internal with_leafs_spent_retry! can perform leaf selection again and fail—the scenario explicitly acknowledged in this commit's Gaps. Consequently, a leaf-selection error does not prove that a fresh key never reached the operators. Here isReusedKey remains false throughout that send and its retries, so the error becomes ChannelFreeRailSendRefused. LightningService.send then clears the uncertainty and releases the recorded attempt, allowing a subsequent payment over LDK before Spark sync exposes the committed transfer. Preserve the uncertain outcome unless there is proof that no operator submission occurred; the same-key retry alone does not protect a later send over another rail.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, this can happen in 0.28.3. If a submission's response is lost, with_leafs_spent_retry! retries it, can then get a leaves-spent error and refresh the leaves, and selecting again can fail after the first try committed. A short balance after such a retry has the same gap, and master already refuses that under a new key.
Holding every fresh-key leaf-selection failure in doubt brings back the endless Pending this change fixes (a payment right after a move to Spark). Holding only the node rail for that invoice until Spark syncs, while the send shows failed, keeps both cases safe. That needs a decision on the trade first; this thread stays open until then.
[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 |
| override func setUp() { | ||
| super.setUp() | ||
| SparkSendAttempts.clear() | ||
| } | ||
|
|
||
| override func tearDown() { | ||
| SparkSendAttempts.clear() |
There was a problem hiding this comment.
Tests erase saved retry numbers
setUp() and tearDown() erase the host app's saved sparkSendAttempts. These are hosted tests, so UserDefaults.standard contains the simulator wallet's real preferences. Running this suite permanently removes its saved retry numbers, even when every test passes.
Inject an isolated defaults store, or snapshot this key before clearing it and restore it after cleanup.
Knowledge Base Used: Keep hardware transfer tests out of app preferences
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.
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.Out of Scope
LightningService.swift: the 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— leaves Spark can't select are refused under a new key onlySparkSendKeyTests.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 outEvidence
swiftformat --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 on the same regtest stack found that its operator build rejects every leaf swap, so Spark there pays only amounts it can cover with leaves it already holds (#1418's J1 hit the same failure at 50 000 sats).
Gaps
with_leafs_spent_retry!) and select again, so a short balance or a leaf-selection failure after such a retry could follow a committed transfer. Under a new key that path refuses the send, as it already did for a short balance.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-high(reasoning:Not exposed)Metadata note: the Gemini self-review records the model only, not a reasoning setting.