Skip to content

fix: use spark send key in retry - #1415

Open
ovitrif wants to merge 3 commits into
masterfrom
fix/spark-send-keys
Open

ovitrif wants to merge 3 commits into
masterfrom
fix/spark-send-keys

Conversation

@ovitrif

@ovitrif ovitrif commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1412
Closes #1413
Twin: synonymdev/bitkit-android#2020
Refs: synonymdev/bitkit-android#2014

Description

  • Fixes a Lightning invoice paid through Spark being paid twice when a send is retried after an outcome the app didn't learn (a crash, a timeout, a relaunch, a restore before Spark synced), because spark-sdk 0.28.3 dedupes only on the idempotency key and the BOLT11 send passed none.
  • Adds 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.
  • Adds the attempt number per invoice (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.
  • Keeps a send in doubt when Spark reports a short balance under a reused key: Spark picks leaves before the operators see the key, so that error can hide the committed transfer; the send stays held until Spark syncs instead of being refused, which would free the invoice for the node.
  • Retries a send briefly under the same key when Spark holds the balance but can't select leaves to spend ("Failed to select leaves after all retries"), as right after a move to Spark lands. Spark selects leaves before anything reaches the operators, so the retry can't pay twice. If it still fails, the send is refused under a never-used key and stays in doubt under a reused one, as a short balance is. The combined payment of feat: update spending balance modal #1373 sends through this path once it lands.
  • Keeps a send's attempt only once the send is admitted, and puts back the attempt kept before it when a send is refused before anything reached Spark's operators, so a Try Again is refused the same way instead of held in doubt until the invoice expires.

Out of Scope

  • On-chain withdrawals from Spark keep their random key: they have no payment hash and their own journal.
  • 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

  • added SparkSendKeyTests.swift — derives the shared test vector Android asserts too
  • added SparkSendKeyTests.swift — a first attempt takes the first key, a retry reuses its attempt's key until Spark lists it failed, then takes the next
  • added SparkSendKeyTests.swift — an expired invoice's attempt is dropped
  • added SparkSendKeyTests.swift — a short balance under a reused key stays in doubt
  • added SparkSendKeyTests.swift — leaves Spark can't select are refused under a new key only
  • added SparkSendKeyTests.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 failures
  • added SparkSendKeyTests.swift — a refused attempt gives back the earlier one
  • added ChannelFreeRailTests.swift — a Spark send checked again before a retry goes out

Evidence

  • ran the unit suite with the CI test selection on an iOS 27 simulator and swiftformat --lint on 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@b54845c and 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.

Case Route Observed
Same key after a committed send Spark, SSP The stored payment comes back; one transfer, receiver paid once
Same key after a wipe and restore, before sync Spark, SSP The committed transfer is recovered and written as a local row; nothing sent twice
Same key after a wipe and restore, after sync Spark, SSP Sync imports the payment under the key; the repeat returns it
Same key after a failure before commit Spark, SSP The retry sends once
Failed under attempt 0, then attempt 1 SSP Resending attempt 0 returns its failure and sends nothing; attempt 1 sends once
Failed under attempt 0, wipe and restore, resend attempt 0 SSP The failure comes back as a local Failed row; nothing paid
Same key after a restore with a balance below the amount Spark, SSP "Insufficient funds", no local row, nothing sent twice; the app keeps the send held until Spark syncs

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 in select_leaves_with_retry after 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

  • Leaf selection comes before the operators only on the SDK's first try: after an operator error it may retry (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.
  • The regtest operator and SSP are public and test builds (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.
  • Background sync was off in the "before sync" runs; on a real restore the retry races Spark's first sync.
  • A leaf swap during a repeated send could not run on this operator; on production it runs before the duplicate-id rejection (it moves leaves, it pays nothing).
  • After a recovered repeat, Spark's local balance reads low by the amount until its next sync.
  • No device run: the cases need crashes mid-send and restores, covered by the regtest proof and unit tests. The leaf-selection retry can't be shown passing on the local regtest stack, whose operator rejects leaf swaps.

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: 3

Metadata note: the Gemini self-review records the model only, not a reasoning setting.

@ovitrif ovitrif self-assigned this Nov 24, 2026
@ovitrif ovitrif changed the title fix: reuse a spark send's key across retries fix: use spark send key in retry Nov 25, 2026
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
@ovitrif
ovitrif force-pushed the fix/spark-send-keys branch from 4751af3 to e15f481 Compare November 25, 2026 11:36
@ovitrif
ovitrif marked this pull request as ready for review November 25, 2026 11:39
@ovitrif
ovitrif requested review from jvsena42 and pwltr November 25, 2026 11:39
@ovitrif

ovitrif commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 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-25T11:41:14.310287Z e15f481 Draft marked ready
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +771 to +772
if isLeafSelectionFailure(error) {
return isReusedKey ? error : ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description"), underlying: error)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[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

  1. P2 Tests erase saved retry numbers ▶

Summary

Adds seed-derived Spark send keys and saved attempt numbers so retries can reuse the same payment.

  • Spark invoice retries reuse the key for their current attempt.
  • Spark retries sends when it briefly cannot select leaves.

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]
Loading

Reviews (1) · Last reviewed commit: "fix: keep a spark send attempt only once..." · Reviewed by Greptile

Comment on lines +14 to +20
override func setUp() {
super.setUp()
SparkSendAttempts.clear()
}

override func tearDown() {
SparkSendAttempts.clear()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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 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. 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: TransferId displays the hyphenated lowercase UUID, and the key is lowercased, so the failedIds comparison holds.
  • Admission run twice on a leaf-selection retry: the didRecordAttempt guard skips admitSend on the re-check, and the outer deadline check still runs; covered by the new ChannelFreeRailTests case.
  • Refusal leaving a stale attempt: every refusal under a fresh key restores the earlier attempt, and one thrown before set restores 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 isReusedKey false and a short balance would be refused, but refuseUnverifiedRestoredInvoice refuses 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.

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: payment after a spark move stays pending fix: use spark send key in retry

2 participants