Repository navigation
fix: use spark send key in retry - #2020
Conversation
Regtest APKDownload bitkit-dev-debug universal APK (expires in 30 days). |
9de4067 to
a80d84b
Compare
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
Verified: detekt and SparkRepoTest
…t of the restore log Verified: detekt, lint and the unit suite
521a8d7 to
7c7023c
Compare
|
Rebased onto master after #2017 merged, and ready for review at 7c7023c:
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
[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
SummaryThe PR gives Spark invoice sends stable keys derived from the wallet seed, payment hash, and attempt number.
Acknowledged by ovitrif:
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]
Reviews (1) · Last reviewed commit: "fix: keep spark settlement writes best-e..." · Reviewed by Greptile |
There was a problem hiding this comment.
💡 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
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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:
nextSendAttemptkeeps the cached attempt, Spark hands back the failed payment, andreportedSendIdsturns a second report intoSendRefused; nothing is sent twice. - Refused-send hold dropped too early: it is cleared only when Spark synced after
refusedAtand 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:
sendKeyfails before the hold writes and is mapped toSendRefused; the secret is published beforesdk, so a connected wallet always has it. - Restore log:
withoutPaymentDetailsblanks 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)
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.
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.
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.
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.
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. |
jvsena42
left a comment
There was a problem hiding this comment.
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.
Device gate: 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.
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.
Corrected in the description: at this head that path shows Pending until the invoice expires, then Payment Failed. |
jvsena42
left a comment
There was a problem hiding this comment.
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-…', onePaymentSuccessful, "Bitcoin Sent"). The payee received 40,000 once, with one operator transfer: pass. - c. A 150 s invoice left Pending resolves to
PaymentFailed21 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.
⚠️ 868ab1902itself 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 (
findActivityByPaymentIderror 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; 868ab1902 is unit-tested only. perf: 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)
|
Out of scope for this PR, seen during the device gate at |
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. |
|
Merging at 868ab19: approved on this head, CI green. |
Closes #2019
Closes #2021
Closes #2024
Closes #2025
Twin: synonymdev/bitkit-ios#1415
Refs: #2014
Description
SparkSendKey: each attempt's key is a UUIDv5 of a secret derived from the wallet seed, the payment hash and the attempt number, so a retry reuses its attempt's key and the Spark operators return the transfer it committed instead of sending again. A seed secret, not the bare hash, so no other wallet derives the same transfer id and the operators can't link the transfer to the invoice. iOS derives the same keys (shared test vector), so a restore across apps keeps them.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.Guards:
refuseUnverifiedRestoredInvoice: kept, as it covers sends by older builds and the node rail, which have no derived key.Out of Scope
Design
N/A — no UI changes.
Preview
N/A
QA Notes
Setup
Journeys
N/A — the combined payment has no journey yet; case 1 covers it.
Manual Tests
Automated Checks
SparkSendKeyTest.kt— derives the shared test vector iOS asserts tooSparkRepoTest.kt— a send goes out under its first attempt's key while Spark's list can't be readSparkRepoTest.kt— a retry reuses its attempt's key until Spark lists that attempt failedSparkRepoTest.kt— a retry takes the next attempt's key once Spark lists its attempt failedSparkRepoTest.kt— a short balance under a reused key keeps the send heldSparkRepoTest.kt— a send retries under its key while Spark can't select its leavesSparkRepoTest.kt— leaves Spark can't select keep the send held under a new key and a reused oneSparkRepoTest.kt— a send held after a leaf failure keeps the node off its invoice after a syncSparkRepoTest.kt— a send held after a leaf failure reports its failure at its invoice's expirySparkRepoTest.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 sendSparkRepoTest.kt— a Spark retry of a held send stopped by its deadline keeps the send heldSparkRepoTest.kt— keyed retries of a held send keep one poll of Spark per intervalSparkRepoTest.kt— a Spark retry stopped by its deadline keeps a hold only saved before a restartSparkRepoTest.kt— a Spark retry of a held send Spark lists failed never takes a new key before the hold settlesSparkRepoTest.kt— a send refused before reaching Spark is refused again on retrySparkRepoTest.kt— a refused retry keeps the attempt Spark listed failed before itSparkRepoTest.kt— a retry that gets back a failure already reported is refusedSparkRepoTest.kt— a send stops retrying its leaves once its deadline passesSparkRepoTest.kt— a send stops retrying its leaves once the payment is no longer allowedLightningRepoTest.kt— a Spark retry rechecks only the payment's authorizationSparkRepoTest.kt— a paid send stays paid when its hold can't be removed from storageCacheStoreTest.kt— a send attempt drops expired ones and restores the earlier oneBackupRepoTest.kt— the restore log leaves out every payment detailSparkRepoTest.kt— the unreadable-list refusal applies to an older build's sendLightningRepoTest.kt— stubs the send keyEvidence
just compile,just testandjust lintat HEAD: all pass.Regtest proof of the SDK behaviour this relies on (spark-sdk 0.28.3 client; operator
breez/spark@b54845cand Breez's test SSP, see Gaps). Each "nothing sent" was checked on the operators' transfers, the SSP's send requests and the receiver's balance.On the SSP route a recovered transfer resumes its Lightning request, which the SSP keys by transfer id, so one key never pays twice; a second payment needs a new attempt's key.
Regtest repro of the leaf-selection failure (found by the swipe-to-pay review run J1 on #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 inselect_leaves_with_retryafter 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:
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
breez/spark@b54845c, Breez's test SSP), not the servers 0.28.3 pins or Lightspark's production SSP; their duplicate-transfer-id rejection and SSP dedup are proven on these builds only.Models used
Claude Opus 5.5(reasoning:medium)Claude Opus 5.5(reasoning:medium),Claude Sonnet 5.5(reasoning:high)gemini-4-neon-high(reasoning:Not exposed)Metadata note: the Gemini self-review records the model only, not a reasoning setting.