Skip to content

fix: use spark send key in retry - #2020

Merged
ovitrif merged 23 commits into
masterfrom
fix/spark-send-keys
Nov 25, 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 #2019
Closes #2021
Closes #2024
Closes #2025
Twin: synonymdev/bitkit-ios#1415
Refs: #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 each attempt passed a new random one.
  • 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. iOS 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). 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 held 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. Under a new key a short balance is refused, as on master.
  • 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. Each retry keeps the send's admission and checks again a caller's submission check (QuickPay's), which has no side effects; the send screen's Paykit check runs once, as its failure releases the request's proof and allowance, which a held send keeps. If it still fails, the send stays held under any key, as master holds that error: 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, allowances and QuickPay charges pending until Spark settles the send or its invoice expires, and then reports its failure.
  • A send refused before anything reached Spark's operators puts back the attempt kept before it, so a Try Again is refused the same way instead of held Pending until the invoice expires. A send whose own result comes back failed releases its invoice, as when its outcome settles, and the send returns that failure, as the send screen subscribes to its events only once the send returns.
  • 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.
  • Leaves every payment detail out of the restore log's copy of the app cache (addresses, invoices, payment hashes, payment and activity ids, transaction ids, comments), as support requests attach the log.
  • Makes the cache writes on a Spark send's settlement path best-effort, so a storage error is logged and never turns a paid send into a failure.

Guards:

  • The refusal while Spark's list can't be read (fix: close spark retry hold gaps #2014): relaxed to invoices an older build sent under a random key, since a retry under this build's key can't pay twice.
  • refuseUnverifiedRestoredInvoice: kept, as it covers sends by older builds and the node rail, which have no derived key.
  • The send holds and the in-flight gate: kept, as they decide what the send screen shows while an attempt is unresolved.
  • The fix: spark retry follow-ups #2007 attempt identity: kept, as the derived key is still the attempt's payment id.

Out of Scope

  • On-chain withdrawals from Spark keep their random key: they have no payment hash and their own journal.
  • fix: close spark retry hold gaps #2014's open case of an invoice another device paid before this one's first sync is covered once both devices run this change.

Design

N/A — no UI changes.

Preview

N/A

QA Notes

Setup

  • Case 1: bitkit-docker regtest with Spark (operators and SSP), a dev build of this branch, a channel to the LSP node with a balance, and a Spark balance that covers the payment only with the channel balance.
  • The key-reuse cases need crashes mid-send and restores; they are covered by the regtest proof and unit tests below, not by device tests.

Journeys

N/A — the combined payment has no journey yet; case 1 covers it.

Manual Tests

  • 1. Local regtest, a wallet with a channel balance and some Spark balance: pay an invoice only the two together cover, so the app moves the channels to Spark first. Expected: the payment completes once the move lands; it never shows Payment Pending that doesn't resolve.

Automated Checks

  • added SparkSendKeyTest.kt — derives the shared test vector iOS asserts too
  • added SparkRepoTest.kt — a send goes out under its first attempt's key while Spark's list can't be read
  • added SparkRepoTest.kt — a retry reuses its attempt's key until Spark lists that attempt failed
  • added SparkRepoTest.kt — a retry takes the next attempt's key once Spark lists its attempt failed
  • added SparkRepoTest.kt — a short balance under a reused key keeps the send held
  • added SparkRepoTest.kt — a send retries under its key while Spark can't select its leaves
  • added SparkRepoTest.kt — leaves Spark can't select keep the send held under a new key and a reused one
  • added SparkRepoTest.kt — a send held after a leaf failure keeps the node off its invoice after a sync
  • added SparkRepoTest.kt — a send held after a leaf failure reports its failure at its invoice's expiry
  • added SparkRepoTest.kt — a Spark retry of a send held after a leaf failure pays under its key and reports it to callers waiting on the held send
  • added SparkRepoTest.kt — a Spark retry of a held send stopped by its deadline keeps the send held
  • added SparkRepoTest.kt — keyed retries of a held send keep one poll of Spark per interval
  • added SparkRepoTest.kt — a Spark retry stopped by its deadline keeps a hold only saved before a restart
  • added SparkRepoTest.kt — a Spark retry of a held send Spark lists failed never takes a new key before the hold settles
  • added SparkRepoTest.kt — a send refused before reaching Spark is refused again on retry
  • added SparkRepoTest.kt — a refused retry keeps the attempt Spark listed failed before it
  • added SparkRepoTest.kt — a retry that gets back a failure already reported is refused
  • added SparkRepoTest.kt — a send stops retrying its leaves once its deadline passes
  • added SparkRepoTest.kt — a send stops retrying its leaves once the payment is no longer allowed
  • added LightningRepoTest.kt — a Spark retry rechecks only the payment's authorization
  • added SparkRepoTest.kt — a paid send stays paid when its hold can't be removed from storage
  • added CacheStoreTest.kt — a send attempt drops expired ones and restores the earlier one
  • added BackupRepoTest.kt — the restore log leaves out every payment detail
  • updated SparkRepoTest.kt — the unreadable-list refusal applies to an older build's send
  • updated LightningRepoTest.kt — stubs the send key

Evidence

  • ran just compile, just test and just lint 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 #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 ("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.

Case 1 on local regtest with Spark, operators patched for leaf swaps (synonymdev/bitkit-docker#43), Breez's test SSP, emulator, build of a157e8967:

Case Wallet Amount Result
1a channel 32 000, Spark 30 000 50 000 (moves the channel to Spark first) Bitcoin Sent in about 17 s, fee 202; the channel's remainder swept to savings
1c Spark 30 000 only 10 000 (needs a leaf swap) Bitcoin Sent in about 8 s, fee 42

Both paid on the first send, with no leaf-selection retries and no Payment Pending; the operators completed every swap. On the unpatched operator (breez/spark@b54845c), which rejects every leaf swap, the same amounts failed at a157e8967 after retries under one key, with the funds left in Spark. At this head that path shows Payment Pending until the invoice expires, then Payment Failed.

Gaps

  • A send held 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.
  • 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.
  • While Spark's payment list can't be read, a retry reuses the latest key without knowing its outcome; a retry that then fails under that key, or a send whose failed result returns before the send screen subscribes to its events, can leave the screen on Pending. This needs a storage failure in Spark's list and is not covered by tests.
  • The key-reuse cases need crashes mid-send and restores; they are covered by the regtest proof and unit tests above, not by device tests.

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

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

@ovitrif ovitrif self-assigned this Nov 24, 2026
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Regtest APK

Built from 868ab19 (run).

Download bitkit-dev-debug universal APK (expires in 30 days).

@ovitrif ovitrif changed the title fix: reuse a spark send's key across retries fix: use spark send key in retry Nov 25, 2026
@ovitrif
ovitrif force-pushed the fix/spark-send-keys branch from 9de4067 to a80d84b Compare November 25, 2026 09:49
Derive each Spark send's idempotency key from the seed, the payment hash
and an attempt number, so a retry reuses its attempt's key and Spark never
pays an invoice twice. The attempt moves on only past keys Spark lists as
failed. A short balance under a reused key keeps the send held, as it can
hide the transfer an earlier attempt committed. The refusal while Spark's
list can't be read now applies only to an invoice an older build sent
under a random key.

Verified: just compile, just test, just lint
Verified: just compile, just test, just lint
A send refused before anything reached Spark's operators (a short balance
or leaves Spark can't select under a never-used key, an expired invoice, a
deadline or exit) kept its attempt as the invoice's latest, so a retry
counted that unused key as reused and held the invoice pending until it
expired. The refusal now puts back the attempt kept before it.

Verified: just compile, just test, just lint (after the last edit: lint and test)
A retry under a key whose failure this process already reported, as when
Spark's list couldn't be read to move past it, got the failure back with
no event, leaving the send screen waiting; it is now refused. A send that
lost Spark's key secret is refused instead of throwing, the leaf-selection
refusal says so, and the restored cache log leaves out send attempts.

Verified: just compile, just test, just lint
A send whose own result came back failed kept the invoice's send hash, so
a retry while Spark's list couldn't be read showed it pending; the failed
attempt paid nothing, so the hash goes, as when its outcome settles. The
leaf-selection retry checks the deadline and exit before it waits, and a
connection keeps the send key's secret before it reports connected.

Verified: just compile, just test, just lint
Also publishes Spark's connection to other threads with the send key's
secret already set, and drops a needless suspend from the retry check.

Verified: just compile, just test, just lint
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 notes when it happened, and the
node holds off the invoice until Spark has synced since, so Spark's list
shows any transfer the send committed. A retry over Spark isn't held, as
one under the same key can't pay twice.

Verified: just compile, just test, just lint
The restore log's copy of the app cache drops every address, invoice, payment hash, payment and activity id, transaction id and comment, as support requests attach the log.

Closes #2024

Verified: detekt, compileDevDebugKotlin, BackupRepoTest and SparkRepoTest
Cache writes on the Spark send's settlement path are best-effort: a storage error is logged and never turns a completed send into a failure.

Closes #2025

Verified: detekt, compileDevDebugKotlin, BackupRepoTest and SparkRepoTest
…t of the restore log

Verified: detekt, lint and the unit suite
@ovitrif
ovitrif force-pushed the fix/spark-send-keys branch from 521a8d7 to 7c7023c Compare November 25, 2026 14:27
@ovitrif
ovitrif marked this pull request as ready for review November 25, 2026 14:37
@ovitrif
ovitrif requested review from jvsena42 and pwltr November 25, 2026 14:37
@ovitrif

ovitrif commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto master after #2017 merged, and ready for review at 7c7023c:

@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-25T14:41:12.906739Z 7c7023c 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.

@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Critical impact] The PR changes how Spark invoice payments and node fallbacks behave across the app.

Fix the early release of refused Spark sends before merging, since it can let the node pay the same invoice again.

Findings

  1. P1 Invoice can be paid twice ▶

Summary

The PR gives Spark invoice sends stable keys derived from the wallet seed, payment hash, and attempt number.

  • Spark invoice retries reuse the same key for each attempt.
  • Spark retries leaf-selection failures and holds invoices when a send may have landed.
  • Restore logs leave out payment details from the app cache.

Acknowledged by ovitrif:

  • A refused send may appear failed until Spark later lists it as sent.
  • Production deduplication behavior and leaf swaps during repeated sends were not proven by the supplied regtest runs.
  • Restore retries can race the first sync, and recovered repeats can temporarily show a low balance.
  • An unreadable Spark list or an early failure event can leave the send screen pending.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Prepare invoice send] --> B[Choose saved attempt or skip failed keys]
    B --> C[Derive key and save holds]
    C --> D[Send through Spark]
    D --> E{Result}
    E -->|Leaf selection error| F[Retry briefly with same key]
    F --> D
    E -->|Unknown outcome| G[Keep hold until settled]
    E -->|New-key refusal| H[Save refusal and remove old holds]
    H --> I[Wait for later sync and read list]
    I -->|Missing or failed row| J[Clear refusal]
    J --> K[Node may pay invoice]
    E -->|Settled| L[Best-effort cleanup]
Loading

Reviews (1) · Last reviewed commit: "fix: keep spark settlement writes best-e..." · Reviewed by Greptile

@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: 7c7023cbd3

ℹ️ 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".

A transfer the refused send committed can stay unlisted after a sync and still go out, as an unknown send's can, so the refusal holds the node until the invoice expires. A failed result Spark returns is reported as a failure, as the caller subscribes to events only once the send returns.

Verified: detekt, SparkRepoTest and CacheStoreTest

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

SparkRepo.kt:675 treats an exhausted fresh-key leaf-selection error as a definite refusal and discards the journal for that attempt. If Spark accepted the transfer before surfacing the error, the app has lost the information it uses to reconcile an uncertain send.

Medium candidate: SparkRepo.kt:1884 clears the cross-rail hold after one newer sync if the list is empty or shows a failed payment. A successful sync can leave an interrupted transfer hidden, and an older failure says nothing about this attempt. If a channel becomes usable and the user retries before expiry, LightningRepo.kt:1813 can admit a second payment. The duplicate debit depends on Spark later completing the hidden transfer and both rails being able to settle the invoice. Keep the hold until there is evidence about the refused attempt itself or the invoice expires.

Medium candidate: A late success after refusal cleanup can arrive after AppViewModel.kt:8197 and PaykitAllowanceExecutor.kt:990 have deleted the Paykit proof. The automatic flow also records the attempt as failed, so the later success cannot settle it. QuickPayRepo.kt:570 releases the daily spend reservation in the same situation and cannot restore the charge on success. Keep the proof, allowance attempt and QuickPay charge pending while Spark's outcome is unknown.

Low: SparkRepo.kt:1850 can put an LDK retry into Payment Pending when the earlier Spark attempt failed before submission. The retry starts no LDK payment, and once the uncertain journal is gone, an empty sync or expiry produces no event to resolve the screen.

Low: SparkRepo.kt:752 resubmits after the leaf-selection delay without rechecking manual Paykit execution authorization. If sign-in state changes during the delay, Android still hands the same invoice to the SDK even though the guard at AppViewModel.kt:8167 would now reject it. Recheck authorization at each actual submission while retaining the original rail admission.

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

@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. Derives each Spark send's idempotency key from the wallet seed, the payment hash and a per-invoice attempt number, so a retry reuses its attempt's key instead of a random one, and keeps the node rail off an invoice whose Spark send was refused after it may have reached the operators. Reviewed 7c7023cb, full tier (key derivation from the seed is a security path), static: Android branches are not built here, so this rests on reading the code and on CI.

What I checked, and 5 candidates I ruled out

Read in full: SparkSendKey.kt, the payInvoice send path, sendRetryingLeafSelection, nextSendAttempt, hasUnkeyedSend, earlierLightningSend, hasSyncedSince, the new CacheStore writers, SparkService.connect/sendKey, withoutPaymentDetails.
Key derivation: recomputed the shared vector independently (HMAC-SHA256 of the label keyed with the seed, then UUIDv5 over secret, hash and a 4-byte big-endian attempt); it gives 577ceb10…, 8d92d8bf-76f3-56fe-8958-8e440acb64fc and 712dea1f-8268-5e52-a280-aac86bc60b59, as the test asserts. The twin's SparkSendKey.swift at e15f4816 uses the same namespace, label, UInt32 big-endian attempt and version/variant bits, so keys survive a restore across apps.
SDK match: Failed to select leaves after all retries is the TreeServiceError::Generic that select_leaves_with_retry returns in spark-sdk 0.28.3 crates/spark-wallet/src/wallet.rs, before any transfer is built, so a same-key retry on it cannot pay twice.
CI: green (build-and-test, detekt, compose-ui, all e2e-tests-local suites).

Ruled out

  • Retry under a key Spark already failed while the list can't be read: nextSendAttempt keeps the cached attempt, Spark hands back the failed payment, and reportedSendIds turns a second report into SendRefused; nothing is sent twice.
  • Refused-send hold dropped too early: it is cleared only when Spark synced after refusedAt and lists no send or a failed one; a transfer the refused attempt committed lists as pending or completed and keeps the hold.
  • Short balance under a reused key: deliberately left held (falls through to settleUncertainSend), since it can hide the committed transfer.
  • Secret missing after disconnect: sendKey fails before the hold writes and is mapped to SendRefused; the secret is published before sdk, so a connected wallet always has it.
  • Restore log: withoutPaymentDetails blanks both new maps along with the existing payment fields.

Merge confidence: 4/5. No findings and the key paths are covered by SparkSendKeyTest.kt and SparkRepoTest.kt, but it is a security path and the branch was not built here.

Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed (the run metadata available to this reviewer names the model but no effort setting)

A refusal that may follow a committed transfer keeps the Paykit proof, the
allowance attempt and the QuickPay charge open. A node send of its invoice is
refused instead of held pending, and each leaf-selection retry rechecks that
the payment is still allowed.

Verified: SparkRepoTest, QuickPayRepoTest, PaykitPaymentProofRepoTest, LightningRepoTest
… settle

A Spark retry of leaves it couldn't select keeps its rail admission and
rechecks only the payment's authorization. A Pubky swap's hold payment waits on
its claim, a Paykit request shows failed but keeps its proof and private list,
and QuickPay shows failed but keeps its charge. The hold read on the uncertain
path is best-effort.

Verified: SparkRepoTest, QuickPayRepoTest, PaykitPaymentProofRepoTest, LightningRepoTest
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 held under any key until Spark settles it or its invoice expires, as
any other unknown outcome does. A short balance under a new key is refused, as
on master. This replaces the refusal marker and the Paykit, QuickPay and swap
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. A leaf retry
rechecks only the caller's side-effect-free check at submission.

Verified: SparkRepoTest, LightningRepoTest, CacheStoreTest, BackupRepoTest
A send held in doubt under this build's key is sent again under that key, which
can't pay twice, instead of refused as pending, and its result settles the hold.

Verified: SparkRepoTest, LightningRepoTest
A short balance or an expiry on a leaf retry can follow a transfer the failed
try committed, so the send ends with the leaf failure and stays held. An expiry
under a reused key keeps the send held too. A failed result Spark returns is
reported once, by the refusal, not also by an event.

Verified: SparkRepoTest, LightningRepoTest, QuickPayRepoTest
A same-key retry of a held send that its deadline or an exit stops before it
sends keeps the earlier attempt's hold, which may have committed a transfer.
A new key's refusal also ends a hold an earlier, failed attempt left in
memory, and a keyed retry reads Spark's local list for the send's outcome.

Verified: SparkRepoTest passes.
A same-key retry stopped before it sends keeps the earlier hold also when it
is saved only on disk, as before Spark's first sync after a restart. A send
held under a key whose earlier result was already reported reports its own
outcome again, so its caller's Pending resolves.

Verified: SparkRepoTest passes.
A retry of a held send whose attempt Spark lists failed stays pending until
the next listing settles the hold, so the send after it goes through the
restore checks a new key needs. A hold is never settled under a retry in
flight under its key, and a held send whose retry fails at once reports the
failure to the callers waiting on it.

Verified: SparkRepoTest passes.
A retry of a held send whose call returns it paid or failed reports that
result as the send's event, as Spark may not report a transfer it returned
for the key again, so callers still waiting on the held send resolve. A hold
left to a retry in flight stays polled.

Verified: SparkRepoTest and detekt pass.
Verified: none (one-line poll condition; the gate runs next)
@ovitrif

ovitrif commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

@pwltr

SparkRepo.kt:675 treats an exhausted fresh-key leaf-selection error as a definite refusal and discards the journal for that attempt.

Fixed in 9468eda: that error now keeps the send held under any key, with its journal, until Spark settles the attempt or the invoice expires.

Medium candidate: SparkRepo.kt:1884 clears the cross-rail hold after one newer sync if the list is empty or shows a failed payment.

Fixed in 9468eda: the separate refusal hold is removed. The send's own hold ends only on Spark's result for its attempt or at a sync after the invoice expires.

Medium candidate: A late success after refusal cleanup can arrive after AppViewModel.kt:8197 and PaykitAllowanceExecutor.kt:990 have deleted the Paykit proof.

Fixed in 9468eda: the send now returns Payment Pending, so the proof, allowance attempt and QuickPay charge stay pending until Spark settles it or the invoice expires, which reports the failure. A retry over Spark goes out at once under the same key.

Low: SparkRepo.kt:1850 can put an LDK retry into Payment Pending when the earlier Spark attempt failed before submission.

A Spark send refused before submission now drops its hold and puts back the earlier attempt, so no hold is left for a retry to wait on.

Low: SparkRepo.kt:752 resubmits after the leaf-selection delay without rechecking manual Paykit execution authorization.

A retry keeps the send's admission and rechecks the caller's submission check where it has one (QuickPay's). The send screen's Paykit check runs once: rechecking it sets the authorization error whose handling releases the request's proof and allowance, which a held send must keep. The retry runs within seconds of the check, under the same key.

@ovitrif
ovitrif requested a review from pwltr November 25, 2026 17:46

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Code scan at 9468eda61 (including the 11 commits since 7c7023cbd): one LOW inline (stacked Spark sync pollers on keyed retries), reproduced with a failing unit test. Nothing HIGH or MEDIUM.

Checked and fine: the key (UUIDv5(HMAC(seed, label) ‖ hash ‖ attempt)) is derived inside connect, only the derived id is logged or backed up; a new key is refused while the old one's hold is live (:629), and the node rail still sees a held send as Pending through earlierLightningSend; a leaf-selection failure now always takes an uncertain hold that ends after expiry and a later sync; cancellation during the send or the 2 s retry delay leaves the cache marker, so the invoice stays held; v3.1.1 holds none of this state.

perf: payInvoice now calls an unbounded listPayments() on every Spark send (:598), where it ran only when the synced list was unavailable before. ⚠️ Not measured; worth timing confirm-to-send on a wallet with a few thousand Spark payments.

Device gate: ⚠️ not run yet. The PR's case 1 evidence is from a157e8967, and its "Payment Failed" line for the unpatched operator describes the old behaviour; at head that path ends in Pending until expiry. Pending on the local Spark stack: leaf failure shows Pending and a node send of the same invoice is refused; a retry goes out under the same key; Pending resolves after expiry; case 1 on the patched operator.

Reviewer model: claude-fable-5-2 (primary, delta review), claude-opus-5-5 (verifier, coordinator)
Reasoning effort: medium (delta review), Unknown (first primary pass; not recorded in its reply), low (verifier), Not exposed (coordinator)

Each poll of a held send stops once a later hold replaces it, so keyed
retries that end held keep one Spark sync per interval.

Verified: SparkRepoTest and detekt pass.
@ovitrif

ovitrif commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

@jvsena42

perf: payInvoice now calls an unbounded listPayments() on every Spark send (:598), where it ran only when the synced list was unavailable before.

It picks the attempt's key: the send moves past each key Spark's list shows failed. It reads the SDK's local store, with no network call. Not timed on a large wallet yet.

Device gate: ⚠️ not run yet. The PR's case 1 evidence is from a157e8967, and its "Payment Failed" line for the unpatched operator describes the old behaviour; at head that path ends in Pending until expiry.

Corrected in the description: at this head that path shows Pending until the invoice expires, then Payment Failed.

@ovitrif
ovitrif requested a review from jvsena42 November 25, 2026 19:20

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving at 868ab1902: nothing above LOW. The one LOW (stacked Spark sync pollers) is fixed in 868ab1902 with the change that made the reproduction pass.

Device gate (Gate_Throwaway emulator, local Spark stack from bitkit-docker's spark profile, operators switched between breez/spark@b54845c unpatched and patched with synonymdev/bitkit-docker#43; devDebug arm64 build of 9468eda61):

  • a. Leaf-selection failure (unpatched): three Retrying Spark send '813a9834-…' lines under one key, then "Payment Pending". A node send of the same invoice is refused as Pending with no LDK send. Nothing reached the payee: pass.
  • b. Retrying the pending invoice: the retry goes out under the same key 813a9834-… (unpatched: Pending again; patched: Sent Spark payment '813a9834-…', one PaymentSuccessful, "Bitcoin Sent"). The payee received 40,000 once, with one operator transfer: pass.
  • c. A 150 s invoice left Pending resolves to PaymentFailed 21 s after expiry, on the poller's sync; balance unchanged: pass. ⚠️ "Node send allowed after expiry" can't be driven: the app refuses the expired invoice at decode.
  • d. PR case 1 on the patched operator (Spark 25,374 plus channel 30,775, invoice 50,000): channel move, then Sent Spark payment '17ce3e19-…', "Bitcoin Sent", no retries: pass.
  • Force-stop 1 s after the send returned PENDING: after relaunch a Pending row, a retry refused as Pending, one debit once the payee claimed: pass.
  • ⚠️ 868ab1902 itself was not run on device; its change is limited to the poller and is unit-tested.

Observed, not attributed (no reproduction on master):

  • After the force-stop case settled, Spending read 3,702 sats high (53,928 against 50,226 on the operators) for 3 minutes across three syncs, then corrected itself. The excess equals the small leaves that send spent.
  • A send held after a leaf-selection failure has no Activity row (findActivityByPaymentId error in the log); only the Pending sheet shows it until it settles.

Device gate: cases a, b, c, d and the force-stop variant pass at 9468eda61; ⚠️ the node send after expiry is not driveable and 868ab1902 is unit-tested only. perf: ⚠️ not measured; payInvoice lists all Spark payments on every send.

Reviewer model: claude-fable-5-2 (primary, delta review, device runbook), claude-opus-5-5 (verifier, coordinator)
Reasoning effort: medium (delta review), low (verifier), Not exposed (primary, device runbook, coordinator)

@jvsena42

Copy link
Copy Markdown
Member

Out of scope for this PR, seen during the device gate at 9468eda61: paying 10,000 again on an invoice already paid in the same session pays nothing (Skipped duplicate processed payment) but leaves Confirm on its spinner for at least 20 s, until Back. That path runs through AppViewModel, which this PR does not change.

@ovitrif

ovitrif commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

@jvsena42

Out of scope for this PR, seen during the device gate at 9468eda61: paying 10,000 again on an invoice already paid in the same session pays nothing (Skipped duplicate processed payment) but leaves Confirm on its spinner for at least 20 s, until Back.

Filed as #2048, with a second path to the same stuck spinner (a failed send, Back, then a new link) and its cause. It's on master too.

@ovitrif

ovitrif commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

Merging at 868ab19: approved on this head, CI green.

@ovitrif
ovitrif merged commit 1ffad41 into master Nov 25, 2026
23 checks passed
@ovitrif
ovitrif deleted the fix/spark-send-keys branch November 25, 2026 20:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

4 participants