Skip to content

fix: use spark send key in retry - #1415

Merged
ovitrif merged 23 commits into
masterfrom
fix/spark-send-keys
Nov 26, 2026
Merged

ovitrif merged 23 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 stays in doubt under any key: the SDK selects leaves again after an operator error, so the failure can follow a transfer the send committed. The hold keeps the node rail off the invoice and Paykit proofs and QuickPay charges pending until Spark settles the send or a sync after its invoice expires shows nothing went out. An invoice that expires, or a short balance Spark reports, during these retries ends them with the leaf failure, so neither reads as a send that never left. 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.
  • A send whose leaves Spark still can't select now shows Payment Pending until Spark settles it or its invoice expires, instead of failed: Spark may have committed its transfer, and a send shown failed would release its Paykit proof, allowance and QuickPay charge while it could still pay. The hold ends at the invoice's expiry with a failure, so Pending always resolves, and a retry over Spark goes out at once under the same key, which can't pay twice.
  • A payment Spark returns failed, as under a key it already failed when its failed list couldn't be read, is refused instead of read as submitted.
  • bug: restore log includes payment details bitkit-android#2024 and bug: paid spark send shows as failed after a storage error bitkit-android#2025 have no iOS twin: the restore logs print only counts, and the Spark send's settlement bookkeeping is kept in UserDefaults, whose writes can't fail.

Out of Scope

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 — an expiry under a reused key stays in doubt
  • added SparkSendKeyTests.swift — a new key waits while the earlier attempt is in doubt
  • added SparkSendKeyTests.swift — leaves Spark can't select keep the send in doubt under any key
  • added SparkSendKeyTests.swift — an invoice expiring during a leaf retry ends it with the leaf failure
  • added SparkSendKeyTests.swift — a short balance on a leaf retry ends it with the leaf failure
  • 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
  • added ChannelFreeRailTests.swift — a Spark send in doubt after a leaf failure ends at its invoice's expiry
  • added ChannelFreeRailTests.swift — a Spark retry of a send in doubt after a leaf failure goes out under its key
  • added ChannelFreeRailTests.swift — a Spark send in doubt Spark lists paid at its invoice's expiry reports no failure
  • added ChannelFreeRailTests.swift — a Spark retry of a send in doubt refused before it goes out stays pending
  • added ChannelFreeRailTests.swift — a Spark retry of a send in doubt over its fee limit stays pending
  • added ChannelFreeRailTests.swift — a Spark retry of a send in doubt stopped before submission stays pending
  • added ChannelFreeRailTests.swift — a move to Spark for a send in doubt under its key is refused as pending
  • added SparkSendKeyTests.swift — a failed payment Spark returns is refused
  • added SparkSendKeyTests.swift — a retry under the same key at another amount waits for the hold
  • added SparkSendKeyTests.swift — an expired send whose row already succeeded stays paid
  • added FailPendingLightningSendTests.swift — failing a pending send returns the row's status after it
  • added ChannelFreeRailTests.swift — an expired send Spark still lists pending is decided by that attempt
  • added ChannelFreeRailTests.swift — a send in doubt keeps its hold at expiry while a retry is in flight
  • added ChannelFreeRailTests.swift — a send in doubt keeps its hold, read as pending, when a retry starts as its expiry is recorded

Evidence

  • ran the unit suite with the CI test selection on an iOS 27 simulator at e280c95, and ChannelFreeRailTests, SparkSendKeyTests and swiftformat --lint on the changed files at HEAD: all pass.
  • device run at 3c465d3 on an iPhone 17 Pro simulator against the local regtest Spark stack: an invoice paid once, and opening it again returned the earlier payment without paying twice (QA comment).

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 found that the regtest operator build breez/spark@b54845c rejects 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

  • A send in doubt after a leaf failure shows Payment Pending until Spark settles it or, when nothing went out, until a sync after its invoice expires; a retry over Spark goes out at once under the same key at the same amount, and one at another amount waits for the hold.
  • A sync whose wallet step succeeded but whose history import failed can end a hold at expiry while the send has no row yet (bug: spark send shows failed at expiry, then pays #1463, needs an SDK signal).
  • 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.
  • The device run covered paying once and reopening a paid invoice; the cases with crashes mid-send and restores are covered by the regtest proof and unit tests. The leaf-selection retry was not run on an iOS device.

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 (reasoning: high)
  • Review rounds: 17

@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 thread Bitkit/Managers/SparkManager.swift Resolved
@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 thread BitkitTests/SparkSendKeyTests.swift Resolved
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 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.

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

ovitrif commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

@pwltr

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.

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.

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.

Fixed in 45950e2: a failed payment Spark returns for the key is now refused (checkSentPayment), so the send fails instead of returning the hash.

Low: BitkitTests/SparkSendKeyTests.swift:14 clears sparkSendAttempts from the hosted app's standard preferences before and after each test.

Fixed in 91da213: the tests snapshot and restore the saved attempts.

@ovitrif
ovitrif requested a review from pwltr November 25, 2026 18:59

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

ovitrif commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

@pwltr

Low: Retrying an amountless invoice at a different amount while its first Spark payment is pending can show the second amount as paid.

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.

Expiry currently treats a missing matching Lightning row as terminal failure when the Activity fallback returns without throwing.

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.

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.

Confirmed in spark-sdk 0.28.3:

  • send_payment writes the payment row only after the SSP call returns.
  • resume_pending_sends swallows its errors.
  • last_synced_at and last_sync_error follow the wallet sync alone, not the history import.
  • Synced carries no per-step result.

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.

Low: On regtest, a BOLT11 invoice containing a Spark address can be paid by direct Spark transfer.

Regtest only: SparkManager.prefersSpark is Env.network == .regtest. On mainnet a send always goes over Lightning, whose row the matching reads. No change.

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.

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

@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

@pwltr

Low: Two installations of the same wallet can approve different amounts for one amountless invoice and derive the same Spark key.

Out of scope: tracked in #1507, because it needs the same wallet paying on two devices before the first payment syncs to the second.

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.

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.

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.

@ovitrif

ovitrif commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

QA for 3c465d3:
Tested on iPhone 17 Pro simulator (iOS 27.0), local regtest Spark stack, Debug build of 3c465d3.

🟢 Pay an invoice once, Open the same invoice again
Pay 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.

rec-case1-pays-once2x.mp4


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.

rec-case2-same-invoice-again2x.mp4


@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Merging: approved, CI green, and the device run on 3c465d3 passed.

@ovitrif
ovitrif merged commit 1beaa69 into master Nov 26, 2026
24 checks passed
@ovitrif
ovitrif deleted the fix/spark-send-keys branch November 26, 2026 15:28
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

3 participants