Repository navigation
fix: skip quickpay node wait when spark covers - #2036
Conversation
The QuickPay check passes the amount to the channel wait, so a payment Spark covers alone does not wait for the node to start. Spark covering the amount means no update is needed for any channel state, and the rail is still picked at send time. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Regtest APKDownload bitkit-dev-debug universal APK (expires in 30 days). |
A Spark send refused until the node lists its earlier sends waits for a starting node and starts over once, so it no longer fails where QuickPay used to wait. An amountless invoice keeps the channel wait, and the tests cover the update invariant the skip relies on. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The held Spark send waits until the node runs and lists its payments, also while it stops with a start queued and across a start retry or stale-graph restart. It ends at once when the start fails, the node stops with no start coming, or the wallet was wiped meanwhile. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A listing that fails during the hold is asked again, so the send returns its failure. The wait reads the start count and the node state when woken instead of as a pair, counts a restart from its stop, no longer ends on a failed start while another start is pending, and ends when a wipe begins. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The wait decides on the state that woke it, so a node that left Running since is waited for again instead of ending the hold. An RGS server change counts its start from its stop, like the Electrum one. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
[Medium impact] The PR appears safe to merge; no new blocking issue was found. SummaryQuickPay skips the channel wait when Spark alone covers the payment. A Spark send held for the node’s payment history waits, then retries once with a fresh choice of payment rail.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Check QuickPay amount] --> B{Spark covers amount?}
B -->|Yes| C[Skip waiting for usable channels]
B -->|No or amountless| D[Keep channel wait]
C --> E[Check update and QuickPay limits]
D --> E
E --> F[Choose payment rail]
F --> G{Spark held for node history?}
G -->|No| H[Continue guarded send]
G -->|Yes| I[Wait for running node and payment list]
I -->|Ready, same wallet| J[Choose rail again once]
I -->|Failure, wipe, or timeout| K[Return original error]
J --> H
Reviews (9) · Last reviewed commit: "Merge remote-tracking branch 'origin/mas..." · Reviewed by Greptile |
talosmachina
left a comment
There was a problem hiding this comment.
No findings. Passes the amount into QuickPay's channel wait so Spark-covered payments skip the node wait, and retries a Spark send once, after the node runs and lists its payments, when earlierNodeSend held it with NodeNotStarted. Reviewed 229581d, full tier, statically: per this repo's track rules the branch was not built here, so this rests on the code and CI.
What I checked, and 6 candidates I ruled out
Read in full: the LightningRepo.kt diff with payInvoiceChecked, earlierNodeSend, awaitNodeListing, refreshChannelsAndPeers, restartNode, the server-change and recovery blocks; AppViewModel.kt waitForUsableChannels, handleQuickPayIfApplicable and the bolt11, LNURL and unified callers
Call sites traced: waitForUsableChannels (all five callers), start/startNode/restartNode (WalletViewModel, AppViewModel, LightningNodeService), SparkRepo.canSend
CI: build-and-test, build, lint, detekt, compose-ui green at this head; e2e shards still running
Ruled out
- Retry sends twice or bypasses authorization: the hold returns before
authorizeSendandadmitSend, the retry re-runsshouldPayWithSparkandearlierNodeSend, andisRetryAfterNodeStartstops a second hold. - Amount 0 counted as covered: QuickPay passes
takeIf { it > 0uL }(null keeps the wait) and the bolt11 path now usescoerceAtLeast(1u)like the LNURL and unified paths. - A start not counted in
pendingStartCount: every path intostartNodefrom outside goes throughstart,restartNodeor recovery, all insidewhileStartPending; the two innerstartNodecalls sit understart. - Wait stuck on a stopped node:
Stoppedwith no pending start failscanStillRun, so the wait ends at once with the original error. - Wallet change during the wait:
wipeCountis read before the hold and checked after waking, after the listing and after the channel refresh. - Update fee skipped when the wait is skipped:
needsUpdateToSendstill runs, and an amountSparkRepo.canSendcovers alone never needs it, whichMoveToSparkRepoTest.ktpins.
Merge confidence: 4/5, a payment send path whose restart holds (node restart, Electrum/RGS change, recovery) have no test, as the body's Gaps say, and the branch was not built here.
Reviewer model: claude-opus-5-5
Reasoning effort: Unknown (the session does not report it)
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: full PR diff against its merge base, at 229581d1d.
1 actionable finding — resolve or provide an evidence-backed rebuttal.
Passing the invoice amount into QuickPay's waitForUsableChannels check (AppViewModel.kt) and retrying held Spark sends once after the node runs and lists its payments (LightningRepo.kt) are sound on the normal Spark-covered payment, timeout, cancellation, start-failure, and wipe paths. One actionable issue was found on the held-send retry path for QuickPay when the node already paid the invoice earlier (Manual Test 7): QuickPayRepo does not handle EarlierSend.Paid returning Result.success(hash) without an incoming payment event, so QuickPay would wait an extra 10 s and dead-end on the pending screen rather than surfacing QuickPayAlreadyPaidError.
Cross-platform parity: Compared against synonymdev/bitkit-ios@edce3cdee (PaymentNavigationHelper.swift, SendSheet.swift, QuickPayPaymentCoordinator.swift, LightningService.swift, WalletViewModel.swift). iOS already skips the node/channel wait when Spark covers QuickPay (SendSheet.swift), so Change 1 aligns Android with iOS. On iOS, LightningService.settledEarlierAttempt does not wait/retry for a starting node, and WalletViewModel.finishWatchSendIfRailAlreadySettled checks lightningService.nodePayments() so a QuickPay send returning an already-paid node hash settles immediately instead of timing out into Pending.
Validation & limitations: CI at 229581d1d passed build-and-test, compose-ui / ui-tests, detekt, and lint; e2e-tests-local - send and e2e-tests-local - onchain_boost_receive_widgets were still in progress during this review. Local Gradle unit tests could not be executed in this review environment (no Android SDK configured). Coverage gap: QuickPayRepoTest.kt has no regression test for payInvoiceAuthorizedAtSubmission returning Result.success(hash) from EarlierSend.Paid without invoking onBeforeSend.
Recommended before device testing
- Fix the QuickPay
EarlierSend.Paidhandling and add a regression test inQuickPayRepoTest.kt. - Wait for
e2e-tests-local - sendande2e-tests-local - onchain_boost_receive_widgetsto finish green. - Exercise the unrun mixed-balance cases (Manual Tests 4, 6, and 7) on a build with both a channel and Spark balance.
Suggested additional test cases
- Android (mixed channel + Spark balance, QuickPay on, PIN/biometric lock enabled): Trigger Manual Test 7 (or a held Spark QuickPay while the node is starting), then lock the phone or dismiss the QuickPay sheet while it is waiting for the node to start. Expected: after the node starts, no payment is sent, the QuickPay daily spend reservation is released, and locking falls back to the swipe review screen rather than dispatching.
- Android (mixed channel + Spark balance, QuickPay on): In Manual Test 7, tap the already-paid fixed-amount
lightning:tag from the background and verify it resolves promptly to the already-paid error (not a 10 s wait followed by the Pending screen) and does not reduce the remaining QuickPay daily spend cap.
Device testing: not performed in this review. The author's evidence at 229581d1d reports passes for Manual Tests 1, 2, 3, 5, and 8 across Spark-only phone and channel-only emulator runs, while mixed-balance cases 4, 6, and 7 remain unrun.
Findings
- [MEDIUM] Resolve already-paid held QuickPay retries instead of hanging into Pending — inline at
app/src/main/java/to/bitkit/repositories/LightningRepo.kt:1656.
Reviewer model: gemini-4-neon
Reasoning effort: high
There was a problem hiding this comment.
Verdict: ⛔️ Request changes — an already-paid QuickPay retry dead-ends on Payment Pending.
Findings: One existing MEDIUM finding confirmed: already-paid held QuickPay retries enter Pending, at LightningRepo.kt:1656. The retry can return an already-paid hash without dispatch or a fresh payment event; QuickPay marks it submitted and times out into Pending rather than reporting already paid and refunding the fresh reservation. No duplicate payment is sent.
QA for 229581d:
QuickPay and held-send regression tests ✅ The four focused test classes passed.
Built devDebug from this head and ran AppViewModelSendFlowTest, LightningRepoTest, MoveToSparkRepoTest and QuickPayRepoTest. The run covers the Spark-covered scan paths, amountless waits, update guard, held-send retry, duplicate protection, cancellation, timeout and wipe checks.
Combined balance requires review ✅ A warm background request opened confirmation with the update fee and sent nothing automatically.
With Spark at 5,000 sats and usable channel capacity at 1,500 sats, opened a 5,500-sat lightning: request from the background. The app waited for usable channels, showed confirmation with a 3-sat update fee and Swipe To Pay. No QuickPay dispatch followed; the recipient invoice remained unpaid (PENDING).
case4-warm2x.2x.mp4
Spark pays while both balances cover ✅ QuickPay started before the node and Spark paid once, with a 6-sat fee.
From a warm background session, opened a fresh 1,000-sat lightning: invoice with Spark at 6,007 sats and usable channel capacity at 1,500 sats. Logs place Using QuickPay before Node started and identify the Spark send. The recipient settled exactly one 1,000-sat HTLC. Activity shows Successful, Payment 1,000 and Fee 6.
Activity recording (ordering and the single settlement were checked in the logs and recipient record):
case6-details2x.2x.mp4
The successful run used the local Spark-invoice/logging hook described below; no stop delay was armed.
Paid invoice stays paid after a stopped node starts ❌ The already-paid retry waited for the node, then reached Payment Pending.
On the reviewed APK, the replay logged Using QuickPay, then Refused a Spark send ... until the node lists its earlier send, then Node started. The channel had 1,500 sats available and Spark covered the repeated 2,000-sat invoice. The recipient still held exactly the original settled 2,000-sat HTLC; no second payment was sent. The UI reached Payment Pending instead of the already-paid error.
case7a2x.2x.mp4
Paid invoice stays paid while the node stops ❌ A controlled stopping-tail retry also reached Payment Pending.
A local timing hook held the repository in Stopping for 20 seconds after the native node stopped and its handle was cleared. The background replay started QuickPay during that hold and logged the refused Spark send. It then waited through the queued node start before reaching Payment Pending. The recipient retained exactly the original settled 2,000-sat HTLC, checked in its invoice record. This exercises the stop tail with an unavailable node handle, rather than the duration of the native stop call.
case7b-late-stop2x.2x.mp4
An already-paid retry releases the QuickPay reserve ❌ A focused regression probe emitted Pending and retained the fresh reservation.
This is a unit-test reproduction of the existing review, not a device result. It returns the same already-paid success that EarlierSend.Paid supplies, without authorization/dispatch or a new payment event. QuickPayRepo emits Pending after its completion timeout. The test ledger still holds the fresh reservation in SUBMITTED, so the expected already-paid error/refund assertion fails.
Temporary regression test, not pushed
diff --git a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt
index af3c71bde..890801e64 100644
--- a/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt
+++ b/app/src/test/java/to/bitkit/repositories/QuickPayRepoTest.kt
@@ -876,6 +876,32 @@ class QuickPayRepoTest : BaseUnitTest() {
assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty())
}
+ @Test
+ fun `already paid held retry refunds a fresh reserve and emits already paid`() = test {
+ val (bolt11, hash) = testInvoice()
+ whenever {
+ lightningRepo.payInvoiceAuthorizedAtSubmission(any(), anyOrNull(), any(), any())
+ }.doSuspendableAnswer {
+ // Matches EarlierSend.Paid: no new authorization, dispatch or payment event.
+ Result.success(hash)
+ }
+ paymentRows = listOf(succeededRow(hash).copy(paymentId = hash))
+ val session = QuickPaySession()
+
+ sut.attach(session).test {
+ sut.payNow(session, QuickPayPayRequest.Bolt11(bolt11 = bolt11, amountSats = 500u))
+ val event = awaitItem()
+ val error = assertIs<QuickPaySessionEvent.Error>(
+ event,
+ "Already-paid return produced $event; ledger=${cacheStore.data.first().quickPayLedger}",
+ )
+ assertIs<QuickPayAlreadyPaidError>(error.error)
+ }
+ assertEquals(0L, spentCents())
+ assertTrue(cacheStore.data.first().quickPayLedger!!.records.isEmpty())
+ verify(pendingPaymentRepo, never()).track(any())
+ }
+
@Test
fun `re-pay of a settled hash does not double-count`() = test {
val (bolt11, hash) = testInvoice()Relied on the exact-head device evidence in the PR description for cases 1, 2, 3, 5 and 8. Physical NFC was not repeated; these mixed-balance runs used lightning: links. The suggested lock/biometric and dismissal-during-hold device cases were not driven; cancellation was checked in the focused unit suites. Native restart/server-change interleavings remain covered by source review rather than device runs.
Local fixture hooks, not pushed
Case 6 used a debug provider argument to receive Spark funds despite available channel inbound capacity, plus filtered Spark leaf-selection logging. The stop marker was absent in that case. Case 7b used the one-shot 20-second stop-tail hook shown below, gated to debug E2E builds and armed by a local marker file. Send, retry and QuickPay logic remained at the reviewed head. Case 7a used the original reviewed APK without these hooks.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa144..fdc5a60d8 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -14,6 +14,7 @@ import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import to.bitkit.async.ServiceQueue
import to.bitkit.models.msatCeilOf
+import to.bitkit.repositories.SparkRepo
import to.bitkit.repositories.LightningRepo
import to.bitkit.repositories.ProbeOutcome
import to.bitkit.utils.Logger
@@ -32,6 +33,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun sparkRepo(): SparkRepo
}
private val deps: Dependencies by lazy {
@@ -50,7 +52,18 @@ class DevToolsProvider : ContentProvider() {
}.toBundle()
}
- override fun onCreate() = true
+ override fun onCreate(): Boolean {
+ runCatching {
+ breez_sdk_spark.initLogging(null, object : breez_sdk_spark.Logger {
+ override fun log(l: breez_sdk_spark.LogEntry) {
+ if (l.line.contains("Failed to select leaves")) {
+ android.util.Log.w("SparkLeafProbe", l.line)
+ }
+ }
+ }, "error")
+ }
+ return true
+ }
override fun getType(uri: Uri): String? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun delete(uri: Uri, sel: String?, args: Array<String>?) = 0
@@ -80,10 +93,18 @@ private sealed interface DevCommand {
}
@Serializable
- data class Args(val amount: ULong? = null, val description: String = "dev-invoice")
+ data class Args(
+ val amount: ULong? = null,
+ val description: String = "dev-invoice",
+ val useSpark: Boolean = false,
+ )
override suspend fun execute(deps: DevToolsProvider.Dependencies) =
- deps.lightningRepo().createInvoice(args.amount, args.description).fold(
+ (if (args.useSpark) {
+ deps.sparkRepo().createInvoice(args.amount, args.description, to.bitkit.env.Defaults.bolt11ExpirySec)
+ } else {
+ deps.lightningRepo().createInvoice(args.amount, args.description)
+ }).fold(
onSuccess = { DevResult.Invoice(it) },
onFailure = {
Logger.error("Failed to create invoice", it, context = TAG)
diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt
index 67c75123f..a023cf8a9 100644
--- a/app/src/main/java/to/bitkit/services/LightningService.kt
+++ b/app/src/main/java/to/bitkit/services/LightningService.kt
@@ -633,6 +633,12 @@ class LightningService internal constructor(
}
this@LightningService.node = null
}
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E &&
+ java.io.File(Env.logDir.parentFile, "review-hold-stop").delete()
+ ) {
+ Logger.warn("Review fixture: holding node stop for 20 seconds", context = TAG)
+ delay(20_000)
+ }
// A stop can leave tasks detached, e.g. a VSS write that keeps retrying. ldk-node keeps their runtime
// alive until they end, but the release returns before that, so a rebuilt node could run while the old
// node's work still runs. Building the next node waits up to 60 s for the old node's VSS writes inFull review of 2d3b1a4..229581d, including lifecycle/restart scopes, cancellation, wallet-wipe identity checks, rail selection, send admission and sibling scan paths. Lifecycle interleavings beyond the planned device cases were checked in code and unit tests.
Twin: no matching iOS PR was linked or found. At iOS snapshot edce3cd, SendSheet.waitsForNode already skips the wait when Spark can pay, and PaymentNavigationHelper.swift has the same spending-update guard. No iOS device run was performed.
The advice transcript records its model but no separate reasoning setting.
Reviewed by gpt-6.1-sol-high
Pull request was converted to draft
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: changes since 229581d1d, including affected code paths, at 601576235. Baseline: previous review (inherited unchanged surfaces: QuickPay and Lightning scan channel-wait gating, held Spark send retry and node lifecycle/listing wait, and the changelog fragment).
1 actionable finding — resolve or provide an evidence-backed rebuttal.
The follow-up change in QuickPayRepo.onInvoiceAccepted cleanly handles an already-paid invoice returned without dispatching: it releases the fresh daily-spend reserve, emits QuickPayAlreadyPaidError, removes the in-flight op so awaitCompletionOrPending returns immediately without tracking pending or waiting SEND_LN_TIMEOUT, and is covered by the new unit test in QuickPayRepoTest.kt. However, the sibling undispatched PaymentPendingException path (when earlierNodeSend or Spark finds an earlier non-QuickPay send still pending) still routes through QuickPayRepo.settleAmbiguousLocked into SendErrorScreen with title "Instant Payment Failed" and the raw English message "Payment pending" instead of SendPendingScreen.
Validation and limitations: Local Gradle test execution could not run because no Android SDK (ANDROID_HOME) is provisioned in this review environment. On 601576235, CI passed build-and-test, compose-ui / ui-tests, detekt, and lint; e2e-tests-local shards were still in progress at inspection time.
Platform parity: Compared Bitkit/Utilities/QuickPayPaymentCoordinator.swift on synonymdev/bitkit-ios at 3623e527d. iOS sets op.dispatched = true before submit(...) and routes non-hard-reject pending dispatch failures to emitPending(op) rather than the failure screen; Android differs on the undispatched PaymentPendingException path noted in F1.
Recommended before device testing: Address the undispatched PaymentPendingException handling in QuickPayRepo with a matching unit test in QuickPayRepoTest.kt, and wait for the in-progress e2e-tests-local CI run on 601576235 to complete.
Device testing: Not performed in this review. The author's recorded device evidence in the PR body covers 229581d1d (before 601576235) and did not exercise mixed-balance manual cases 4, 6, or 7.
Suggested additional test cases:
- Android (QuickPay re-scan while earlier manual LDK send is pending): Setup: wallet with both an LDK channel and a Spark balance covering 1,000 sats, QuickPay on ($5 threshold). Start a manual (Swipe-to-Pay) 1,000-sat payment to a fixed-amount invoice that remains
PENDINGon LDK (e.g., hold invoice or delayed route). Background Bitkit until the node stops, then re-open Bitkit with the same invoice via NFC orlightning:link. Expected: QuickPay waits for the node to list its payments, sends no second payment, releases its temporary QuickPay daily-spend reserve, and navigates toSendPendingScreen(notSendErrorScreenshowing "Instant Payment Failed" /"Payment pending").
Earlier findings reconciled at this revision: 1 verified fixed.
Findings
- [MEDIUM] Route undispatched PaymentPendingException to Pending instead of Instant Payment Failed error screen — Trigger: On a wallet where both an LDK channel and Spark cover the invoice amount, an earlier non-QuickPay payment of an invoice (for example, a manual Swipe-to-Pay send over LDK) is still
PENDINGin LDK (not inQuickPayRepo.opsByKeyorQuickPaySpendStore). The user backgrounds Bitkit until the node stops and then taps or scans the same invoice again with QuickPay enabled.
Mechanism: Because AppViewModel.kt:6793 now skips waitForUsableChannels when Spark covers the amount, QuickPayRepo.dispatchBolt11 (QuickPayRepo.kt:437) enters LightningRepo.payInvoiceChecked (LightningRepo.kt:1643-1669) with shouldPayWithSpark returning true. earlierNodeSend throws ServiceError.NodeNotStarted, and awaitNodeListing (LightningRepo.kt:1732-1759) waits for the node to run and list payments, then performs a single immediate refreshChannelsAndPeers() (LightningRepo.kt:2854-2864) without waiting for peers to reconnect (isUsable == true). On retry while channels are still reconnecting, shouldPayWithSpark (LightningRepo.kt:1499-1505) remains true (totalNextOutboundHtlcLimitSats() filters by isUsable), so earlierNodeSend (LightningRepo.kt:1815) returns EarlierSend.Pending(hash) -> Result.failure(PaymentPendingException(hash)) without invoking onBeforeSend (op.dispatched stays false). In QuickPayRepo, dispatchBolt11 (QuickPayRepo.kt:442-449) passes this failure to onInvoiceRejected -> handleDispatchError, where classifyDispatchError (QuickPayRepo.kt:1091-1106) classifies PaymentPendingException as AMBIGUOUS (duplicate = false). settleAmbiguousLocked (QuickPayRepo.kt:612-618) then hits if (!duplicate && op != null && !op.dispatched), releases the reserve, and emits QuickPaySessionEvent.Error(PaymentPendingException("Payment pending"), paymentRequest). QuickPayViewModel.toUiFailure (QuickPayViewModel.kt:86-102) has no branch for PaymentPendingException, so Throwable.toSendFailureMessage (PaymentFailureReasonExt.kt:51-69) passes through the raw English message "Payment pending" from PaymentPendingException : AppError("Payment pending") (PendingPaymentRepo.kt:55), and SendSheet.kt:780-790, 1088-1091 opens SendErrorScreen titled wallet__send_instant_failed ("Instant Payment Failed") with a Retry button and without calling pendingPaymentRepo.track(hash).
Consequence: This path would mislead the user with an "Instant Payment Failed" error screen showing the unlocalized English text "Payment pending" and a Retry button instead of tracking the live payment on SendPendingScreen. No funds are lost, no duplicate payment is dispatched, and the fresh QuickPay spend reserve is released.
Expected behavior: When payInvoiceAuthorizedAtSubmission returns PaymentPendingException without dispatching (!op.dispatched), QuickPayRepo should release the fresh non-dispatched spend reserve, emit QuickPaySessionEvent.Pending (tracking the hash via pendingPaymentRepo.track), and remove the op — matching the pending UX of manual sends (AppViewModel.kt:8202, 8345) and LDK DuplicatePayment (QuickPayRepo.kt:625-629) without charging QuickPay's daily spend for the earlier non-QuickPay payment. Add a regression test in QuickPayRepoTest.kt alongside the new undispatched already-paid test.
Evidence basis: Source analysis at 601576235 (not exercised on a device or via local Gradle run).
Source. Summary placement: QuickPayRepo.settleAmbiguousLocked (line 613) and onInvoiceRejected (line 514) are outside the PR diff hunks, while this PR's channel-wait skip and held-send retry newly route mixed-balance background QuickPay re-scans to this undispatched PaymentPendingException path.
Reviewer model: gemini-4-neon
Reasoning effort: high
There was a problem hiding this comment.
Verdict: ⛔️ Request changes — a pending manual payment can still be shown as failed on QuickPay replay.
Findings:
- MEDIUM — Pending payment shown as failed. The existing pending-payment finding is reproduced on device at
6015762. A manual Lightning payment remains pending; Spark also covers its amount. Reopening the same invoice while the node reconnects reaches an undispatchedPaymentPendingException. QuickPayRepo.kt:613 refunds the fresh reserve but emits Error, producing Payment Failed / Payment pending / Try Again instead of Pending. No duplicate payment was sent. Route this existing-pending result to Pending while refunding the fresh reserve.
The already-paid finding is fixed by 6015762: both stopped and stopping replays now report already paid and release only the fresh reservation. The pending-payment finding is a sibling full-PR path, unchanged by this latest delta.
QA for 6015762: reviewed commit
QuickPay already-paid and real-send regressions ✅ Both focused test classes passed.
Built devDebug and ran QuickPayRepoTest and LightningRepoTest. The new regression verifies the already-paid error, original payment request, refunded fresh reserve, empty ledger and absence of Pending tracking. Genuine submissions on both rails still call the dispatch callback first.
Already-paid invoice after the node stops ✅ The held replay reports already paid after the node starts.
The recording shows the warm replay and its already-paid result. App logs confirm the earlier-send hold; cache checks show the fresh reserve refunded while the original spend remains, and the recipient still has one settled 2,000-sat HTLC.
7a2x.2x.mp4
Debug setup patch (not pushed)
Not pushed. This replay and the pending-payment replay below used the head plus the following debug setup additions. The stop marker was absent and neither setup command ran in either case; payment and completion decisions were unchanged.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa144..81a668935 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -6,6 +6,12 @@ import android.net.Uri
import android.os.Binder
import android.os.Bundle
import android.os.Process
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import to.bitkit.data.CacheStore
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
@@ -32,6 +38,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun cacheStore(): CacheStore
}
private val deps: Dependencies by lazy {
@@ -41,6 +48,15 @@ class DevToolsProvider : ContentProvider() {
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" }
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E && method == "reviewRestartNode") {
+ CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { deps.lightningRepo().restartNodeDetached() }
+ return Bundle().apply { putString("result", "restart queued") }
+ }
+
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E && method == "reviewForgetListing") {
+ runBlocking { deps.cacheStore().update { it.copy(ldkSendHashesSeeded = false) } }
+ return Bundle().apply { putString("result", "listing marked unknown") }
+ }
return runCatching {
val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" }
ServiceQueue.LDK.blocking { command.execute(deps) }
diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt
index 67c75123f..e99b855bc 100644
--- a/app/src/main/java/to/bitkit/services/LightningService.kt
+++ b/app/src/main/java/to/bitkit/services/LightningService.kt
@@ -633,6 +633,12 @@ class LightningService internal constructor(
}
this@LightningService.node = null
}
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E &&
+ java.io.File(Env.logDir.parentFile, "review-hold-stop").delete()
+ ) {
+ Logger.warn("Review fixture: holding node stop tail for 30 seconds", context = TAG)
+ delay(30_000)
+ }
// A stop can leave tasks detached, e.g. a VSS write that keeps retrying. ldk-node keeps their runtime
// alive until they end, but the release returns before that, so a rebuilt node could run while the old
// node's work still runs. Building the next node waits up to 60 s for the old node's VSS writes inAlready-paid invoice while the node stops ✅ A replay during the controlled stop tail reports already paid.
The explicit test barrier holds the stop tail after the native handle is cleared. The replay enters while Stopping; the device’s Lightning-peer connection stays unavailable through listing so Spark remains the candidate rail. After explicit release and startup, it reports already paid. Cache and recipient checks confirm a refunded fresh reserve and only the original settled HTLC.
7b-explicit2x.2x.mp4
Explicit stop barrier used for stopping, dismissal and locking
Not pushed. This debug-only barrier keeps the cleared node handle unavailable until the tester removes its marker. Debug commands restart the real node and mark its send history unknown; native payment results and QuickPay decisions are unchanged.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa144..d5e51a6eb 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -6,6 +6,12 @@ import android.net.Uri
import android.os.Binder
import android.os.Bundle
import android.os.Process
+import kotlinx.coroutines.CoroutineScope // test hook
+import kotlinx.coroutines.Dispatchers // test hook
+import kotlinx.coroutines.SupervisorJob // test hook
+import kotlinx.coroutines.launch // test hook
+import kotlinx.coroutines.runBlocking // test hook
+import to.bitkit.data.CacheStore // test hook
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
@@ -32,6 +38,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun cacheStore(): CacheStore // test hook
}
private val deps: Dependencies by lazy {
@@ -41,6 +48,15 @@ class DevToolsProvider : ContentProvider() {
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" }
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E && method == "reviewRestartNode") { // test hook
+ CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { deps.lightningRepo().restartNodeDetached() } // test hook
+ return Bundle().apply { putString("result", "restart queued") } // test hook
+ } // test hook
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E && method == "reviewForgetListing") { // test hook
+ runBlocking { deps.cacheStore().update { it.copy(ldkSendHashesSeeded = false) } } // test hook
+ return Bundle().apply { putString("result", "listing marked unknown") } // test hook
+ } // test hook
+
return runCatching {
val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" }
ServiceQueue.LDK.blocking { command.execute(deps) }
diff --git a/app/src/main/java/to/bitkit/services/LightningService.kt b/app/src/main/java/to/bitkit/services/LightningService.kt
index 67c75123f..c2104480c 100644
--- a/app/src/main/java/to/bitkit/services/LightningService.kt
+++ b/app/src/main/java/to/bitkit/services/LightningService.kt
@@ -633,6 +633,13 @@ class LightningService internal constructor(
}
this@LightningService.node = null
}
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E && // test hook
+ java.io.File(Env.logDir.parentFile, "review-hold-stop").exists() // test hook
+ ) { // test hook
+ Logger.warn("Test hook: node handle cleared; waiting for stop-tail release", context = TAG) // test hook
+ while (java.io.File(Env.logDir.parentFile, "review-hold-stop").exists()) delay(50) // test hook
+ Logger.warn("Test hook: stop-tail released", context = TAG) // test hook
+ } // test hook
// A stop can leave tasks detached, e.g. a VSS write that keeps retrying. ldk-node keeps their runtime
// alive until they end, but the release returns before that, so a rebuilt node could run while the old
// node's work still runs. Building the next node waits up to 60 s for the old node's VSS writes in7b-explicit:
WARN [LightningService.kt:639] Test hook: node handle cleared; waiting for stop-tail release - LightningService
INFO [AppViewModel.kt:6802] Using QuickPay for '2000' sats - AppViewModel
WARN [LightningRepo.kt:1782] Refused a Spark send of 'd9f3bcfeeaaf0b6b68bfc224b22319fb5b02f8a93d77445372df0bff24ffa2de' until the node lists its earlier send - LightningRepo
WARN [LightningService.kt:641] Test hook: stop-tail released - LightningService
INFO [LightningService.kt:650] Node stopped - LightningService
INFO [LightningService.kt:533] Node started - LightningService
Cache: spentCents 121 -> 242 reserved -> 121; records empty. Recipient: SETTLED, one 2000-sat HTLC.
dismiss-explicit:
WARN [LightningService.kt:639] Test hook: node handle cleared; waiting for stop-tail release - LightningService
INFO [AppViewModel.kt:6802] Using QuickPay for '2000' sats - AppViewModel
WARN [LightningRepo.kt:1786] Refused a Spark send until the node lists its earlier payments once - LightningRepo
WARN [LightningService.kt:641] Test hook: stop-tail released - LightningService
INFO [LightningService.kt:650] Node stopped - LightningService
INFO [LightningService.kt:533] Node started - LightningService
Back dismissed the held sheet before release. Cache: spentCents 121; records empty. After startup recipient: OPEN, zero HTLCs.
lock-final:
WARN [LightningService.kt:639] Test hook: node handle cleared; waiting for stop-tail release - LightningService
INFO [AppViewModel.kt:6802] Using QuickPay for '4000' sats - AppViewModel
WARN [LightningRepo.kt:1786] Refused a Spark send until the node lists its earlier payments once - LightningRepo
DEBUG [AppViewModel.kt:9580] Locked app on background - AppViewModel
WARN [LightningService.kt:641] Test hook: stop-tail released - LightningService
INFO [LightningService.kt:650] Node stopped - LightningService
INFO [LightningService.kt:533] Node started - LightningService
After startup, Confirm was shown behind PIN; after unlock Swipe To Pay remained required. Cache: spentCents 121; records empty. Recipient: OPEN, zero HTLCs.
Dismiss QuickPay while the send waits ✅ Dismissing the held sheet cancels the send.
With payment history unavailable, QuickPay reserves the amount and waits. Back dismisses it before the stop barrier is released. Logs and cache after startup confirm the reserve cleared; the recipient invoice remains OPEN with zero HTLCs.
dismiss-explicit2x.2x.mp4
Rescan an earlier manual payment still pending ❌ QuickPay shows Payment Failed for the earlier pending payment.
The recording first shows a manual 1,000-sat send on Pending, then its QuickPay replay on Payment Failed with “Payment pending” and Try Again. Before backgrounding, the channel still had 2,000 sats outbound and Spark covered the invoice. Only the device’s Lightning-peer connection was held unavailable during relaunch to keep the reconnect state; Spark and chain access remained available. The recipient retained exactly one ACCEPTED HTLC, and cache checks confirm the fresh QuickPay reserve was refunded.
earlier-pending2x.2x.mp4
Lock the wallet while the send waits ✅ Locking during the hold prevents automatic dispatch.
The recording shows a held 4,000-sat QuickPay, the background lock, and confirmation after unlock. Logs confirm the lock happened before explicit barrier release. The node started while locked, the fresh reserve was refunded, and the attempt fell back to Confirm. After unlock, Swipe To Pay was still required; recipient checks show OPEN with zero HTLCs.
lock-final2x.2x.mp4
Relied on the author’s device report at 229581d for manual cases 1, 2, 3, 5 and 8, and the previous review’s passing recordings for cases 4 and 6. Those successful-dispatch paths are unchanged by this delta. Physical NFC was not repeated.
Reviewed contiguous 229581d..6015762, the prior already-paid finding, both dispatch callbacks, ledger cleanup, cancellation, and the newly posted pending-payment finding. Device cases cover the completion change; the test-only change was exercised by the focused test run.
Twin: no matching iOS PR was linked or found. At iOS snapshot 1beaa69, Spark-covered sends skip the node wait and the send watcher handles an earlier paid node result without waiting for another event. No iOS device run was performed.
Reviewed by gpt-6.1-sol-high
|
@jvsena42 please resolve conflicts. |
Pull request was converted to draft
Pull request was converted to draft
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Re the QA review at 1abe3bf:
|
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: changes since 1abe3bf, including affected code paths, at 668f8a9. Baseline: previous review. The base and merge base are unchanged (5cb372f). Coverage of the QuickPay dispatch guarding, node-wait routing, held Spark send retry, node lifecycle tracking, changelog and the earlier iOS parity check is inherited from that baseline.
No new actionable code findings.
The update lets LightningRepo.settledSparkSendEvent also report a node (LDK) send that failed. It does this only when the payment is listed as failed and no retry is live on either rail. Callers that keep the default (AppViewModel.resolveSettledPendingSend and QuickPayRepo.resolveSettledEarlierSend) now resolve as failed a pending send whose node failure event was handled before the send was tracked. Before, such a send stayed pending. The failure reason is null, which matches the existing Spark path. sendLightning opts out with includeNodeFailure = false, so it still waits for the node's failure event, which carries the reason. If that event was missed, the send falls back to pending after SEND_LN_TIMEOUT (10 s) and then resolves as failed. I compared this path with the event path in handlePaymentFailed. The settled path repeats its pending-only side effects (releasing the swap hold, clearing the contact context, resolving the pending payment). A retry admitted after the second liveness check, or a listed failure seen before the node event arrives, has the same timing as the existing failure-event, success and Spark paths, so the change does not introduce it. Minor, non-blocking: the comment at QuickPayRepo.kt:671 still says node sends settle only once they succeed.
Validation: I read the 4 new LightningRepoTest cases (failed with nothing live; a retry in flight; a retry that ends while payments are listed; the opt-out flag) and the updated AppViewModelSendFlowTest stub matchers. The QuickPayRepoTest stubs still match the default argument. No AppViewModelSendFlowTest case covers the settled read returning a node PaymentFailed on the pending path; that path is covered only at the repository level. I did not run any tests locally because no Gradle dependency cache was available. At review time, CI build-and-test and the local e2e jobs for this head were still running. The earlier CI run was cancelled because it was superseded, not because anything failed.
Parity: I looked at bitkit-ios 676956b only briefly. It tracks pending sends differently (pendingPaymentHashes, failPendingPayment with a nil reason). I did not trace an equivalent of this race on iOS, so iOS parity for the delta is an evidence gap.
Device testing: not performed in this review.
Suggested additional test cases
- Android: with usable channels, pay a Lightning invoice that will fail to route, timed so that the node's failure lands before the pending screen starts tracking the send (for example, background the app during the send). Expected: the pending screen resolves to the send error screen instead of staying pending, and no second payment-failed toast appears.
Earlier findings reconciled at this revision: 1 verified fixed.
Reviewer model: claude-opus-5-5
Reasoning effort: high
Pull request was converted to draft
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Verdict: ⛔️ Request changes — the requested missed-completion recovery still leaves a failed payment on Payment Pending.
The PR moved to 57bdfe0 after this run; these results are for 668f8a9.
Reviewed 668f8a9. The PR moved to 57bdfe0 during the final case; this report does not certify that newer head.
Findings: No new code defect in the reviewed delta. The undispatched-reserve refund and stale-operation guards hold, and the new node-failure lookup correctly returns PaymentFailed.
The failing device cases expose a separate, pre-existing Pending delivery bug. A dismissed Pending screen's collector remains active, consumes PendingPaymentRepo.lastResolutions, and receives the recovered result before the replacement Pending viewmodel initializes. That replacement misses both the non-replaying broadcast and the consumed cache. PendingPaymentRepo, SendPendingViewModel, SendPendingScreen, SendSheet and SheetHost are unchanged by this PR. The repository fix works; the end-to-end recovery case does not. The replacement screen must retain access to its recovered completion.
QA for 668f8a9:
QuickPay and held-send regressions ✅ The pristine head builds and the four focused suites pass.
Built devDebug and ran QuickPayRepoTest, LightningRepoTest, AppViewModelSendFlowTest and MoveToSparkRepoTest. The new failed-node/no-live-attempt checks, retry-liveness checks, opt-out flag, refund and stale-dispatch regressions passed.
Earlier node payment fails before Pending is tracked ❌ The lookup recovers the real failure and refunds the reserve, but the replacement screen stays Pending.
Regtest, Android 15 emulator, Spark 20,000 sats plus a usable channel. Sent a real 1,000-sat LND hold invoice manually, closed Pending, enabled QuickPay at $5, then replayed the same invoice through a fixed-amount LNURL from the background. Peer access alone was unavailable during reconnection; Spark and chain access remained available.
Paused QuickPay before its row lookup, cancelled the recipient invoice, restored peer access and observed the real RECIPIENT_REJECTED event before releasing the lookup. The new lookup returned PaymentFailed; the fresh reserve became zero with no ledger records. An earlier observer consumed the recovered Failure before the new Pending viewmodel initialized. The screen stayed Pending with no later event left to resolve it. The recipient retained exactly one cancelled HTLC.
Reproduced after both system Back and the visible Close button on the original Pending screen. The recording below is the Close-button confirmation; event ordering, the refund and single HTLC were checked in logs/cache and the recipient record.
failure-confirm2x.2x.mp4
Debug controls, not pushed
Holds the first row lookup until explicit release, logs settlement and Pending observer/initialization ordering, and permits Spark funding through the debug invoice provider. Payment results and send decisions remain unchanged. The success-event marker was absent in this failure case.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa1441..6d6698c763 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -32,6 +32,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun sparkRepo(): to.bitkit.repositories.SparkRepo // test hook
}
private val deps: Dependencies by lazy {
@@ -80,10 +81,11 @@ private sealed interface DevCommand {
}
@Serializable
- data class Args(val amount: ULong? = null, val description: String = "dev-invoice")
+ data class Args(val amount: ULong? = null, val description: String = "dev-invoice", val useSpark: Boolean = false) // test hook
override suspend fun execute(deps: DevToolsProvider.Dependencies) =
- deps.lightningRepo().createInvoice(args.amount, args.description).fold(
+ (if (args.useSpark) deps.sparkRepo().createInvoice(args.amount, args.description, to.bitkit.env.Defaults.bolt11ExpirySec) // test hook
+ else deps.lightningRepo().createInvoice(args.amount, args.description)).fold(
onSuccess = { DevResult.Invoice(it) },
onFailure = {
Logger.error("Failed to create invoice", it, context = TAG)
diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
index f7f5882187..10be9d2c20 100644
--- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
@@ -436,6 +436,7 @@ class QuickPayRepo @Inject constructor(
}
private suspend fun dispatchBolt11(invoice: ResolvedInvoice, op: InFlightOp, canDispatch: () -> Boolean) {
+ reviewLookupBarrier("before-dispatch") // test hook
var isAuthorizationLapsed = false
lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) {
isAuthorizationLapsed = !canDispatch()
@@ -598,7 +599,9 @@ class QuickPayRepo @Inject constructor(
QuickPayDispatchClass.DUPLICATE_PAYMENT,
QuickPayDispatchClass.AMBIGUOUS,
-> {
+ reviewLookupBarrier("before-rows") // test hook
val rows = loadPaymentRows()
+ reviewLookupBarrier("after-rows") // test hook
val isEarlierSendTracked = mutex.withLock {
if (isSupersededLocked(op)) return@withLock false
settleAmbiguousLocked(
@@ -670,6 +673,7 @@ class QuickPayRepo @Inject constructor(
private suspend fun resolveSettledEarlierSend(invoiceHash: String) {
// Settled only when confirmed: a node send once it succeeded, a Spark send once no attempt of it is live.
val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull()
+ Logger.warn("Test hook: earlier settlement lookup '${event?.javaClass?.simpleName}'", context = TAG) // test hook
val resolution = when (event) {
is Event.PaymentSuccessful if event.paymentHash == invoiceHash ->
PendingPaymentResolution.Success(invoiceHash)
@@ -677,9 +681,19 @@ class QuickPayRepo @Inject constructor(
PendingPaymentResolution.Failure(invoiceHash, event.reason)
else -> return
}
+ Logger.warn("Test hook: found earlier settlement '${resolution.javaClass.simpleName}' pending='${pendingPaymentRepo.isPending(invoiceHash)}'", context = TAG) // test hook
if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution)
}
+ private suspend fun reviewLookupBarrier(name: String) { // test hook
+ if (!to.bitkit.BuildConfig.DEBUG || !to.bitkit.BuildConfig.E2E) return // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-$name") // test hook
+ if (!marker.exists()) return // test hook
+ Logger.warn("Test hook: waiting at '$name'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ Logger.warn("Test hook: released '$name'", context = TAG) // test hook
+ } // test hook
+
private fun isEarlierSendPaid(invoiceHash: String, rows: List<QuickPayReconcileRow>): Boolean = rows.any {
it.isOutboundBolt11 && it.status == QuickPayReconcileRow.Status.SUCCEEDED &&
it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true)
@@ -724,6 +738,7 @@ class QuickPayRepo @Inject constructor(
}
if (success && op != null && !op.dispatched) {
// QuickPay sent nothing yet, so the success is an earlier send's: the invoice is paid, and not by QuickPay.
+ Logger.warn("Test hook: refund earlier success, undispatched op", context = TAG) // test hook
spend.release(record.invoicePaymentHash)
emitErrorLocked(op, QuickPayAlreadyPaidError(), op.paymentRequest)
removeOpLocked(op)
diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
index c32f08e225..643b2b9886 100644
--- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
+++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
@@ -102,6 +102,7 @@ fun SendPendingScreen(
val txid = paymentHash.takeIf { isOnchain && it.matches(Regex("[0-9a-fA-F]{64}")) }
LaunchedEffect(Unit) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) to.bitkit.utils.Logger.warn("Test hook: pending screen id='${System.identityHashCode(viewModel)}' hash='$paymentHash' observe='$observeResolution'", context = "SendPendingScreen") // test hook
if (isOnchain) {
viewModel.initOnchain(txid, amount, walletId)
} else if (observeResolution) {
diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
index f6e6c71921..3e10740aaf 100644
--- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
+++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
@@ -56,6 +56,7 @@ class SendPendingViewModel @Inject constructor(
private var isInitialized = false
fun init(paymentHash: String, amount: Long) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending init id='${System.identityHashCode(this)}' hash='$paymentHash' initialized='$isInitialized'", context = TAG) // test hook
if (isInitialized) return
isInitialized = true
pendingPaymentRepo.setActiveHash(paymentHash)
@@ -299,6 +300,7 @@ class SendPendingViewModel @Inject constructor(
}
override fun onCleared() {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending cleared id='${System.identityHashCode(this)}'", context = TAG) // test hook
recoveryApproval?.cancel()
pendingPaymentRepo.setActiveHash(null)
}
@@ -323,6 +325,7 @@ class SendPendingViewModel @Inject constructor(
pendingPaymentRepo.resolution
.filter { it.paymentHash == paymentHash }
.collect { resolution ->
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending observer id='${System.identityHashCode(this)}' consumes '${resolution::class.simpleName}' hash='$paymentHash'", context = TAG) // test hook
pendingPaymentRepo.consumeResolution(paymentHash)
Logger.info(
"Received payment resolution '${resolution::class.simpleName}' for '$paymentHash'",
diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
index 6b1eed9af1..85e1c5d99d 100644
--- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
+++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
@@ -3291,6 +3291,11 @@ class AppViewModel @Inject constructor(
}
private suspend fun handlePaymentSuccessful(event: Event.PaymentSuccessful) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-success-event") // test hook
+ if (marker.exists()) Logger.warn("Test hook: holding real success event", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
val paymentHash = event.paymentHash
viewModelScope.launch {
paykitPaymentProofRepo.completeLightningPayment(paymentHash, event.paymentPreimage)QuickPayRepo: found earlier settlement 'Failure' pending='true'
SendPendingViewModel: pending observer id='100098050' consumes 'Failure'
[76 ms later]
SendPendingViewModel: pending init id='93264342' initialized='false'
Ledger: spentCents=0, records=[]
Recipient: CANCELED, one HTLC
Earlier node payment succeeds before Pending is tracked ❌ Lookup-only recovery leaves Pending; releasing the late real success event then reaches Bitcoin Sent.
Repeated with another real 1,000-sat manual LDK hold invoice. Paused after QuickPay captured its pending-row snapshot, settled the recipient, and held the real success handler so the post-track lookup had to recover the outcome itself. That lookup returned PaymentSuccessful and refunded the fresh reserve, but the older observer consumed the result before the new Pending viewmodel initialized. The replacement remained Pending.
Releasing the real success handler afterwards did reach Bitcoin Sent. This is a failed lookup-delivery check, not a claim that the success screen remains stuck after the late event is delivered. The recipient settled exactly one HTLC; the fresh QuickPay ledger stayed at zero with no records. These accounting and ordering claims were checked in logs/cache and the recipient record.
success-before-track2x.2x.mp4
Debug controls, not pushed
Uses the same debug controls. The after-rows and real-success-handler barriers isolate recovery from a stale pending snapshot; both are explicitly released. No SDK result is replaced.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa1441..6d6698c763 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -32,6 +32,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun sparkRepo(): to.bitkit.repositories.SparkRepo // test hook
}
private val deps: Dependencies by lazy {
@@ -80,10 +81,11 @@ private sealed interface DevCommand {
}
@Serializable
- data class Args(val amount: ULong? = null, val description: String = "dev-invoice")
+ data class Args(val amount: ULong? = null, val description: String = "dev-invoice", val useSpark: Boolean = false) // test hook
override suspend fun execute(deps: DevToolsProvider.Dependencies) =
- deps.lightningRepo().createInvoice(args.amount, args.description).fold(
+ (if (args.useSpark) deps.sparkRepo().createInvoice(args.amount, args.description, to.bitkit.env.Defaults.bolt11ExpirySec) // test hook
+ else deps.lightningRepo().createInvoice(args.amount, args.description)).fold(
onSuccess = { DevResult.Invoice(it) },
onFailure = {
Logger.error("Failed to create invoice", it, context = TAG)
diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
index f7f5882187..10be9d2c20 100644
--- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
@@ -436,6 +436,7 @@ class QuickPayRepo @Inject constructor(
}
private suspend fun dispatchBolt11(invoice: ResolvedInvoice, op: InFlightOp, canDispatch: () -> Boolean) {
+ reviewLookupBarrier("before-dispatch") // test hook
var isAuthorizationLapsed = false
lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) {
isAuthorizationLapsed = !canDispatch()
@@ -598,7 +599,9 @@ class QuickPayRepo @Inject constructor(
QuickPayDispatchClass.DUPLICATE_PAYMENT,
QuickPayDispatchClass.AMBIGUOUS,
-> {
+ reviewLookupBarrier("before-rows") // test hook
val rows = loadPaymentRows()
+ reviewLookupBarrier("after-rows") // test hook
val isEarlierSendTracked = mutex.withLock {
if (isSupersededLocked(op)) return@withLock false
settleAmbiguousLocked(
@@ -670,6 +673,7 @@ class QuickPayRepo @Inject constructor(
private suspend fun resolveSettledEarlierSend(invoiceHash: String) {
// Settled only when confirmed: a node send once it succeeded, a Spark send once no attempt of it is live.
val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull()
+ Logger.warn("Test hook: earlier settlement lookup '${event?.javaClass?.simpleName}'", context = TAG) // test hook
val resolution = when (event) {
is Event.PaymentSuccessful if event.paymentHash == invoiceHash ->
PendingPaymentResolution.Success(invoiceHash)
@@ -677,9 +681,19 @@ class QuickPayRepo @Inject constructor(
PendingPaymentResolution.Failure(invoiceHash, event.reason)
else -> return
}
+ Logger.warn("Test hook: found earlier settlement '${resolution.javaClass.simpleName}' pending='${pendingPaymentRepo.isPending(invoiceHash)}'", context = TAG) // test hook
if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution)
}
+ private suspend fun reviewLookupBarrier(name: String) { // test hook
+ if (!to.bitkit.BuildConfig.DEBUG || !to.bitkit.BuildConfig.E2E) return // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-$name") // test hook
+ if (!marker.exists()) return // test hook
+ Logger.warn("Test hook: waiting at '$name'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ Logger.warn("Test hook: released '$name'", context = TAG) // test hook
+ } // test hook
+
private fun isEarlierSendPaid(invoiceHash: String, rows: List<QuickPayReconcileRow>): Boolean = rows.any {
it.isOutboundBolt11 && it.status == QuickPayReconcileRow.Status.SUCCEEDED &&
it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true)
@@ -724,6 +738,7 @@ class QuickPayRepo @Inject constructor(
}
if (success && op != null && !op.dispatched) {
// QuickPay sent nothing yet, so the success is an earlier send's: the invoice is paid, and not by QuickPay.
+ Logger.warn("Test hook: refund earlier success, undispatched op", context = TAG) // test hook
spend.release(record.invoicePaymentHash)
emitErrorLocked(op, QuickPayAlreadyPaidError(), op.paymentRequest)
removeOpLocked(op)
diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
index c32f08e225..643b2b9886 100644
--- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
+++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
@@ -102,6 +102,7 @@ fun SendPendingScreen(
val txid = paymentHash.takeIf { isOnchain && it.matches(Regex("[0-9a-fA-F]{64}")) }
LaunchedEffect(Unit) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) to.bitkit.utils.Logger.warn("Test hook: pending screen id='${System.identityHashCode(viewModel)}' hash='$paymentHash' observe='$observeResolution'", context = "SendPendingScreen") // test hook
if (isOnchain) {
viewModel.initOnchain(txid, amount, walletId)
} else if (observeResolution) {
diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
index f6e6c71921..3e10740aaf 100644
--- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
+++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
@@ -56,6 +56,7 @@ class SendPendingViewModel @Inject constructor(
private var isInitialized = false
fun init(paymentHash: String, amount: Long) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending init id='${System.identityHashCode(this)}' hash='$paymentHash' initialized='$isInitialized'", context = TAG) // test hook
if (isInitialized) return
isInitialized = true
pendingPaymentRepo.setActiveHash(paymentHash)
@@ -299,6 +300,7 @@ class SendPendingViewModel @Inject constructor(
}
override fun onCleared() {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending cleared id='${System.identityHashCode(this)}'", context = TAG) // test hook
recoveryApproval?.cancel()
pendingPaymentRepo.setActiveHash(null)
}
@@ -323,6 +325,7 @@ class SendPendingViewModel @Inject constructor(
pendingPaymentRepo.resolution
.filter { it.paymentHash == paymentHash }
.collect { resolution ->
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending observer id='${System.identityHashCode(this)}' consumes '${resolution::class.simpleName}' hash='$paymentHash'", context = TAG) // test hook
pendingPaymentRepo.consumeResolution(paymentHash)
Logger.info(
"Received payment resolution '${resolution::class.simpleName}' for '$paymentHash'",
diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
index 6b1eed9af1..85e1c5d99d 100644
--- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
+++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
@@ -3291,6 +3291,11 @@ class AppViewModel @Inject constructor(
}
private suspend fun handlePaymentSuccessful(event: Event.PaymentSuccessful) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-success-event") // test hook
+ if (marker.exists()) Logger.warn("Test hook: holding real success event", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
val paymentHash = event.paymentHash
viewModelScope.launch {
paykitPaymentProofRepo.completeLightningPayment(paymentHash, event.paymentPreimage)AppViewModel: holding real success event
QuickPayRepo: found earlier settlement 'Success' pending='true'
SendPendingViewModel: pending observer id='255955367' consumes 'Success'
[80 ms later]
SendPendingViewModel: pending init id='91647000' initialized='false'
Ledger: spentCents=0, records=[]
Recipient: SETTLED, one HTLC
After releasing the real event: Bitcoin Sent
Carried QA for 1abe3bf: These recorded paths are unchanged by 1abe3bf..668f8a9, which adds the failed-node lookup and its immediate-watcher opt-out.
Earlier manual success refunds the fresh QuickPay allowance ✅ The earlier success reports Already Paid and refunds the undispatched reserve.
At 1abe3bf, a real earlier success during the held row lookup produced Already Paid. Cache checks show the fresh reservation refunded to zero with no records; the recipient held one settled HTLC.
carried-earlier-success-cap2x.2x.mp4
Debug controls, not pushed
Holds the first row lookup and logs the undispatched success/refund. The other timing markers are absent in this case. These controls stage timing and observe real SDK events; they do not replace results.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa144..6d6698c76 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -32,6 +32,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun sparkRepo(): to.bitkit.repositories.SparkRepo // test hook
}
private val deps: Dependencies by lazy {
@@ -80,10 +81,11 @@ private sealed interface DevCommand {
}
@Serializable
- data class Args(val amount: ULong? = null, val description: String = "dev-invoice")
+ data class Args(val amount: ULong? = null, val description: String = "dev-invoice", val useSpark: Boolean = false) // test hook
override suspend fun execute(deps: DevToolsProvider.Dependencies) =
- deps.lightningRepo().createInvoice(args.amount, args.description).fold(
+ (if (args.useSpark) deps.sparkRepo().createInvoice(args.amount, args.description, to.bitkit.env.Defaults.bolt11ExpirySec) // test hook
+ else deps.lightningRepo().createInvoice(args.amount, args.description)).fold(
onSuccess = { DevResult.Invoice(it) },
onFailure = {
Logger.error("Failed to create invoice", it, context = TAG)
diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
index f7f588218..10be9d2c2 100644
--- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
@@ -436,6 +436,7 @@ class QuickPayRepo @Inject constructor(
}
private suspend fun dispatchBolt11(invoice: ResolvedInvoice, op: InFlightOp, canDispatch: () -> Boolean) {
+ reviewLookupBarrier("before-dispatch") // test hook
var isAuthorizationLapsed = false
lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) {
isAuthorizationLapsed = !canDispatch()
@@ -598,7 +599,9 @@ class QuickPayRepo @Inject constructor(
QuickPayDispatchClass.DUPLICATE_PAYMENT,
QuickPayDispatchClass.AMBIGUOUS,
-> {
+ reviewLookupBarrier("before-rows") // test hook
val rows = loadPaymentRows()
+ reviewLookupBarrier("after-rows") // test hook
val isEarlierSendTracked = mutex.withLock {
if (isSupersededLocked(op)) return@withLock false
settleAmbiguousLocked(
@@ -670,6 +673,7 @@ class QuickPayRepo @Inject constructor(
private suspend fun resolveSettledEarlierSend(invoiceHash: String) {
// Settled only when confirmed: a node send once it succeeded, a Spark send once no attempt of it is live.
val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull()
+ Logger.warn("Test hook: earlier settlement lookup '${event?.javaClass?.simpleName}'", context = TAG) // test hook
val resolution = when (event) {
is Event.PaymentSuccessful if event.paymentHash == invoiceHash ->
PendingPaymentResolution.Success(invoiceHash)
@@ -677,9 +681,19 @@ class QuickPayRepo @Inject constructor(
PendingPaymentResolution.Failure(invoiceHash, event.reason)
else -> return
}
+ Logger.warn("Test hook: found earlier settlement '${resolution.javaClass.simpleName}' pending='${pendingPaymentRepo.isPending(invoiceHash)}'", context = TAG) // test hook
if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution)
}
+ private suspend fun reviewLookupBarrier(name: String) { // test hook
+ if (!to.bitkit.BuildConfig.DEBUG || !to.bitkit.BuildConfig.E2E) return // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-$name") // test hook
+ if (!marker.exists()) return // test hook
+ Logger.warn("Test hook: waiting at '$name'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ Logger.warn("Test hook: released '$name'", context = TAG) // test hook
+ } // test hook
+
private fun isEarlierSendPaid(invoiceHash: String, rows: List<QuickPayReconcileRow>): Boolean = rows.any {
it.isOutboundBolt11 && it.status == QuickPayReconcileRow.Status.SUCCEEDED &&
it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true)
@@ -724,6 +738,7 @@ class QuickPayRepo @Inject constructor(
}
if (success && op != null && !op.dispatched) {
// QuickPay sent nothing yet, so the success is an earlier send's: the invoice is paid, and not by QuickPay.
+ Logger.warn("Test hook: refund earlier success, undispatched op", context = TAG) // test hook
spend.release(record.invoicePaymentHash)
emitErrorLocked(op, QuickPayAlreadyPaidError(), op.paymentRequest)
removeOpLocked(op)
diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
index c55d255cd..6b27272df 100644
--- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
+++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
@@ -3291,6 +3291,11 @@ class AppViewModel @Inject constructor(
}
private suspend fun handlePaymentSuccessful(event: Event.PaymentSuccessful) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-success-event") // test hook
+ if (marker.exists()) Logger.warn("Test hook: holding real success event", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
val paymentHash = event.paymentHash
viewModelScope.launch {
paykitPaymentProofRepo.completeLightningPayment(paymentHash, event.paymentPreimage)A stale QuickPay attempt leaves its retry alone ✅ The later reservation survives the old callback and its own Already Paid result refunds it.
At 1abe3bf, the earlier success ended the first attempt while its dispatch was still suspended. A later same-invoice attempt registered its own reservation. Releasing the old callback left that reservation and live operation intact; releasing the later attempt produced Already Paid and refunded it. Cache checks show zero spent cents and no records; the recipient retained one settled HTLC.
carried-stale-retry2x.2x.mp4
Debug controls, not pushed
Holds the old row lookup and the later before-dispatch point separately, with explicit releases. Submission/operation-identity checks remain those of the reviewed code.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa144..6d6698c76 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -32,6 +32,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun sparkRepo(): to.bitkit.repositories.SparkRepo // test hook
}
private val deps: Dependencies by lazy {
@@ -80,10 +81,11 @@ private sealed interface DevCommand {
}
@Serializable
- data class Args(val amount: ULong? = null, val description: String = "dev-invoice")
+ data class Args(val amount: ULong? = null, val description: String = "dev-invoice", val useSpark: Boolean = false) // test hook
override suspend fun execute(deps: DevToolsProvider.Dependencies) =
- deps.lightningRepo().createInvoice(args.amount, args.description).fold(
+ (if (args.useSpark) deps.sparkRepo().createInvoice(args.amount, args.description, to.bitkit.env.Defaults.bolt11ExpirySec) // test hook
+ else deps.lightningRepo().createInvoice(args.amount, args.description)).fold(
onSuccess = { DevResult.Invoice(it) },
onFailure = {
Logger.error("Failed to create invoice", it, context = TAG)
diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
index f7f588218..10be9d2c2 100644
--- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
@@ -436,6 +436,7 @@ class QuickPayRepo @Inject constructor(
}
private suspend fun dispatchBolt11(invoice: ResolvedInvoice, op: InFlightOp, canDispatch: () -> Boolean) {
+ reviewLookupBarrier("before-dispatch") // test hook
var isAuthorizationLapsed = false
lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) {
isAuthorizationLapsed = !canDispatch()
@@ -598,7 +599,9 @@ class QuickPayRepo @Inject constructor(
QuickPayDispatchClass.DUPLICATE_PAYMENT,
QuickPayDispatchClass.AMBIGUOUS,
-> {
+ reviewLookupBarrier("before-rows") // test hook
val rows = loadPaymentRows()
+ reviewLookupBarrier("after-rows") // test hook
val isEarlierSendTracked = mutex.withLock {
if (isSupersededLocked(op)) return@withLock false
settleAmbiguousLocked(
@@ -670,6 +673,7 @@ class QuickPayRepo @Inject constructor(
private suspend fun resolveSettledEarlierSend(invoiceHash: String) {
// Settled only when confirmed: a node send once it succeeded, a Spark send once no attempt of it is live.
val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull()
+ Logger.warn("Test hook: earlier settlement lookup '${event?.javaClass?.simpleName}'", context = TAG) // test hook
val resolution = when (event) {
is Event.PaymentSuccessful if event.paymentHash == invoiceHash ->
PendingPaymentResolution.Success(invoiceHash)
@@ -677,9 +681,19 @@ class QuickPayRepo @Inject constructor(
PendingPaymentResolution.Failure(invoiceHash, event.reason)
else -> return
}
+ Logger.warn("Test hook: found earlier settlement '${resolution.javaClass.simpleName}' pending='${pendingPaymentRepo.isPending(invoiceHash)}'", context = TAG) // test hook
if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution)
}
+ private suspend fun reviewLookupBarrier(name: String) { // test hook
+ if (!to.bitkit.BuildConfig.DEBUG || !to.bitkit.BuildConfig.E2E) return // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-$name") // test hook
+ if (!marker.exists()) return // test hook
+ Logger.warn("Test hook: waiting at '$name'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ Logger.warn("Test hook: released '$name'", context = TAG) // test hook
+ } // test hook
+
private fun isEarlierSendPaid(invoiceHash: String, rows: List<QuickPayReconcileRow>): Boolean = rows.any {
it.isOutboundBolt11 && it.status == QuickPayReconcileRow.Status.SUCCEEDED &&
it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true)
@@ -724,6 +738,7 @@ class QuickPayRepo @Inject constructor(
}
if (success && op != null && !op.dispatched) {
// QuickPay sent nothing yet, so the success is an earlier send's: the invoice is paid, and not by QuickPay.
+ Logger.warn("Test hook: refund earlier success, undispatched op", context = TAG) // test hook
spend.release(record.invoicePaymentHash)
emitErrorLocked(op, QuickPayAlreadyPaidError(), op.paymentRequest)
removeOpLocked(op)
diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
index c55d255cd..6b27272df 100644
--- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
+++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
@@ -3291,6 +3291,11 @@ class AppViewModel @Inject constructor(
}
private suspend fun handlePaymentSuccessful(event: Event.PaymentSuccessful) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-success-event") // test hook
+ if (marker.exists()) Logger.warn("Test hook: holding real success event", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
val paymentHash = event.paymentHash
viewModelScope.launch {
paykitPaymentProofRepo.completeLightningPayment(paymentHash, event.paymentPreimage)An earlier pending payment fails after QuickPay tracks it ✅ A failure delivered after tracking reaches Payment Failed and leaves no fresh allowance spent.
At 1abe3bf, QuickPay tracked the earlier payment and refunded its fresh reservation. Cancelling the recipient afterwards delivered the real node failure and reached Payment Failed. Cache checks show zero spent cents and no records; the recipient held one cancelled HTLC. This future-event path is distinct from the two pre-track lookup cases above.
carried-earlier-pending-failure2x.2x.mp4
Debug controls, not pushed
Uses the same setup/logging build; no row or success-event timing marker was armed for the after-tracking cancellation.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa144..6d6698c76 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -32,6 +32,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun sparkRepo(): to.bitkit.repositories.SparkRepo // test hook
}
private val deps: Dependencies by lazy {
@@ -80,10 +81,11 @@ private sealed interface DevCommand {
}
@Serializable
- data class Args(val amount: ULong? = null, val description: String = "dev-invoice")
+ data class Args(val amount: ULong? = null, val description: String = "dev-invoice", val useSpark: Boolean = false) // test hook
override suspend fun execute(deps: DevToolsProvider.Dependencies) =
- deps.lightningRepo().createInvoice(args.amount, args.description).fold(
+ (if (args.useSpark) deps.sparkRepo().createInvoice(args.amount, args.description, to.bitkit.env.Defaults.bolt11ExpirySec) // test hook
+ else deps.lightningRepo().createInvoice(args.amount, args.description)).fold(
onSuccess = { DevResult.Invoice(it) },
onFailure = {
Logger.error("Failed to create invoice", it, context = TAG)
diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
index f7f588218..10be9d2c2 100644
--- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
@@ -436,6 +436,7 @@ class QuickPayRepo @Inject constructor(
}
private suspend fun dispatchBolt11(invoice: ResolvedInvoice, op: InFlightOp, canDispatch: () -> Boolean) {
+ reviewLookupBarrier("before-dispatch") // test hook
var isAuthorizationLapsed = false
lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) {
isAuthorizationLapsed = !canDispatch()
@@ -598,7 +599,9 @@ class QuickPayRepo @Inject constructor(
QuickPayDispatchClass.DUPLICATE_PAYMENT,
QuickPayDispatchClass.AMBIGUOUS,
-> {
+ reviewLookupBarrier("before-rows") // test hook
val rows = loadPaymentRows()
+ reviewLookupBarrier("after-rows") // test hook
val isEarlierSendTracked = mutex.withLock {
if (isSupersededLocked(op)) return@withLock false
settleAmbiguousLocked(
@@ -670,6 +673,7 @@ class QuickPayRepo @Inject constructor(
private suspend fun resolveSettledEarlierSend(invoiceHash: String) {
// Settled only when confirmed: a node send once it succeeded, a Spark send once no attempt of it is live.
val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull()
+ Logger.warn("Test hook: earlier settlement lookup '${event?.javaClass?.simpleName}'", context = TAG) // test hook
val resolution = when (event) {
is Event.PaymentSuccessful if event.paymentHash == invoiceHash ->
PendingPaymentResolution.Success(invoiceHash)
@@ -677,9 +681,19 @@ class QuickPayRepo @Inject constructor(
PendingPaymentResolution.Failure(invoiceHash, event.reason)
else -> return
}
+ Logger.warn("Test hook: found earlier settlement '${resolution.javaClass.simpleName}' pending='${pendingPaymentRepo.isPending(invoiceHash)}'", context = TAG) // test hook
if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution)
}
+ private suspend fun reviewLookupBarrier(name: String) { // test hook
+ if (!to.bitkit.BuildConfig.DEBUG || !to.bitkit.BuildConfig.E2E) return // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-$name") // test hook
+ if (!marker.exists()) return // test hook
+ Logger.warn("Test hook: waiting at '$name'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ Logger.warn("Test hook: released '$name'", context = TAG) // test hook
+ } // test hook
+
private fun isEarlierSendPaid(invoiceHash: String, rows: List<QuickPayReconcileRow>): Boolean = rows.any {
it.isOutboundBolt11 && it.status == QuickPayReconcileRow.Status.SUCCEEDED &&
it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true)
@@ -724,6 +738,7 @@ class QuickPayRepo @Inject constructor(
}
if (success && op != null && !op.dispatched) {
// QuickPay sent nothing yet, so the success is an earlier send's: the invoice is paid, and not by QuickPay.
+ Logger.warn("Test hook: refund earlier success, undispatched op", context = TAG) // test hook
spend.release(record.invoicePaymentHash)
emitErrorLocked(op, QuickPayAlreadyPaidError(), op.paymentRequest)
removeOpLocked(op)
diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
index c55d255cd..6b27272df 100644
--- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
+++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
@@ -3291,6 +3291,11 @@ class AppViewModel @Inject constructor(
}
private suspend fun handlePaymentSuccessful(event: Event.PaymentSuccessful) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-success-event") // test hook
+ if (marker.exists()) Logger.warn("Test hook: holding real success event", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
val paymentHash = event.paymentHash
viewModelScope.launch {
paykitPaymentProofRepo.completeLightningPayment(paymentHash, event.paymentPreimage)Relied on the author's device evidence at 229581d for manual cases 1, 2, 3, 5 and 8; the first review's recordings for cases 4 and 6; and the 6015762 review for both already-paid case-7 variants, dismissal and locking. Those demonstrated paths are unchanged. Physical NFC was not repeated; these additional cases used deep links on an emulator.
Reviewed contiguous 0ba85013..668f8a92 plus earlier open findings and reached callers. Live-retry exclusion and the immediate-watcher failure-reason opt-out were isolated in focused tests, not separate device cases. Restart/server-change interleavings remain source/unit coverage.
Twin: no matching iOS fix PR was linked or found. The adjacent nearby-payment twin is synonymdev/bitkit-ios#1302; its QuickPay flow already skips the Spark-covered node wait and marks its operation dispatched before submission, so its completion accounting differs. No iOS device run.
Reviewed by gpt-6.1-sol-high
|
@jvsena42 please resolve conflicts. |
|
Opened #2161 for the pre-existing Spark |
Pull request was converted to draft
…ode-wait-spark # Conflicts: # app/src/main/java/to/bitkit/repositories/LightningRepo.kt
|
@piotr-iohk conflicts resolved in d953045 (merge of master).
|
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: full PR at d953045d9, re-reviewed after the comparison base changed from 5cb372f to 64670db and that base update touches the QuickPay wait and held-send files.
No new actionable code findings.
No new actionable code findings. QuickPay passes a positive amount into the existing Spark-covered channel wait, a held Spark send retries once after the node lists its payments, and an undispatched earlier success or pending send refunds the fresh reserve. A failed node send with nothing live resolves through settledSparkSendEvent; the live send path still waits for the node event that carries the reason. Compared with bitkit-ios@9b6dbac: SendSheet.waitsForNode already skips the sync overlay when Spark can pay a positive amount. This was a scoped comparison of that wait, not a review of the iOS app.
Existing concerns, both still present and outside this diff's new defects: #2161 (a Spark SendRefused before dispatch leaves the QuickPay daily reserve counted until the next day; the same pre-dispatch path as master) and #2162 (a replacement Pending screen can miss a resolution an earlier Pending collector already consumed). The ovi review reported that miss on a device at 668f8a9; this review did not re-run it. PendingPaymentRepo and SendPendingViewModel are unchanged in this diff.
Device testing: not performed in this review. The author's phone and emulator runs are at 229581d1d and cover manual cases 1, 2, 3, 5, and 8. Cases 4, 6, and 7 still need a wallet with both a Spark balance and channel capacity. This review did not run unit tests.
Suggested additional test cases:
- Android, regtest, QuickPay on. Fail an earlier Lightning send of an invoice, then open that invoice again with QuickPay while the first Pending screen is still alive. The replacement Pending screen should show the failure rather than stay on Pending.
Reviewer model: grok-4.7
Reasoning effort: xhigh
There was a problem hiding this comment.
Verdict: 💬 Comment — no new merge finding; the two missed-completion checks reproduce the deferred Pending-screen issue.
Findings: None in the reviewed delta. The Electrum/RGS change and recovery retain their pending-start scopes across the merged retry logic. The remaining screen-delivery failure is synonymdev/bitkit-android#2162, now explicitly out of scope here and triaged to 3.3.0. The lookup and fresh-reservation refunds work; the resolved finding stays closed.
QA for d953045: Regtest, Android 15 emulator.
QuickPay, node wait and server change regressions ✅ The pristine head builds and the four focused suites pass.
Built devDebug and ran QuickPayRepoTest, LightningRepoTest, AppViewModelSendFlowTest and MoveToSparkRepoTest. This includes server-change retries, cancellation and stop precedence, held-send bounds, failed-node settlement, reservation refunds and stale-operation guards. XML results confirm execution.
A held QuickPay waits through the Electrum change gap ✅ The stopped-node replay waits, reports Already Paid after restart and refunds its fresh reservation.
Paused a real Electrum change after stop, before its new start. The log records Stopped with one pending start. Reopened the already-paid 1,000-sat BOLT11 invoice: QuickPay reached the held-send listing wait in that gap. After release, the node restarted, the server change succeeded and QuickPay showed “This invoice has already been paid.”
The recipient still has exactly one settled HTLC. Cache checks show the temporary reservation refunded to the prior 60-cent spend, with no ledger records. The recording shows the wait and result; node state, accounting and the single HTLC were checked in logs/cache and the recipient record.
held-electrum-change2x.2x.mp4
Debug controls, not pushed
The debug provider starts the real Electrum change; an explicit barrier pauses it after stop. The send, listing, rail selection and authorization remain the reviewed code. Other timing markers were absent.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa144..364c40ebd 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -10,6 +10,7 @@ import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
+import kotlinx.coroutines.launch // test hook
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import to.bitkit.async.ServiceQueue
@@ -32,6 +33,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun sparkRepo(): to.bitkit.repositories.SparkRepo // test hook
}
private val deps: Dependencies by lazy {
@@ -41,6 +43,19 @@ class DevToolsProvider : ContentProvider() {
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" }
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E && method == "reviewRefreshChannels") { // test hook
+ kotlinx.coroutines.runBlocking { deps.lightningRepo().refreshChannelsAndPeers() } // test hook
+ return Bundle().apply { putString("result", "channels refreshed") } // test hook
+ } // test hook
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E && method == "reviewElectrumChange") { // test hook
+ kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO).launch { // test hook
+ deps.lightningRepo().restartWithElectrumServer("tcp://127.0.0.1:60001").fold( // test hook
+ onSuccess = { Logger.warn("Test hook: Electrum change succeeded", context = TAG) }, // test hook
+ onFailure = { Logger.warn("Test hook: Electrum change failed", it, context = TAG) }, // test hook
+ ) // test hook
+ } // test hook
+ return Bundle().apply { putString("result", "Electrum change queued") } // test hook
+ } // test hook
return runCatching {
val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" }
ServiceQueue.LDK.blocking { command.execute(deps) }
@@ -80,10 +95,11 @@ private sealed interface DevCommand {
}
@Serializable
- data class Args(val amount: ULong? = null, val description: String = "dev-invoice")
+ data class Args(val amount: ULong? = null, val description: String = "dev-invoice", val useSpark: Boolean = false) // test hook
override suspend fun execute(deps: DevToolsProvider.Dependencies) =
- deps.lightningRepo().createInvoice(args.amount, args.description).fold(
+ (if (args.useSpark) deps.sparkRepo().createInvoice(args.amount, args.description, to.bitkit.env.Defaults.bolt11ExpirySec) // test hook
+ else deps.lightningRepo().createInvoice(args.amount, args.description)).fold(
onSuccess = { DevResult.Invoice(it) },
onFailure = {
Logger.error("Failed to create invoice", it, context = TAG)
diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
index 1d3acb5bd..c3ff06a08 100644
--- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
@@ -1084,6 +1084,12 @@ class LightningRepo @Inject constructor(
// A stop requested from here on, during the change's first build included, wins over every start.
stopRequests = stopRequestCount.get()
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-config-gap") // test hook
+ if (marker.exists()) Logger.warn("Test hook: Electrum stopped gap starts='${pendingStartCount.value}' lifecycle='${_lightningState.value.nodeLifecycleState}'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
+
Logger.debug("Starting node with new electrum server: '$newServerUrl'", context = TAG)
startConfigChange(stopRequests = stopRequests, customServerUrl = newServerUrl)
@@ -1843,6 +1849,7 @@ class LightningRepo @Inject constructor(
* wallet was wiped since [wipesBefore], as the node that runs next can be another wallet's.
*/
private suspend fun awaitNodeListing(wipesBefore: Long): Boolean {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: held send awaiting listing starts='${pendingStartCount.value}' lifecycle='${_lightningState.value.nodeLifecycleState}'", context = TAG) // test hook
val isWiped = { isWiping || wipeCount.get() != wipesBefore }
// The two flows only wake the wait. What it decides on is read then, the count before the state: read as a
// pair they can show a failed start beside a count another start has left since, which never was the case.
diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
index 0363f244d..f829aae9b 100644
--- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
@@ -436,6 +436,7 @@ class QuickPayRepo @Inject constructor(
}
private suspend fun dispatchBolt11(invoice: ResolvedInvoice, op: InFlightOp, canDispatch: () -> Boolean) {
+ reviewLookupBarrier("before-dispatch") // test hook
var isAuthorizationLapsed = false
lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) {
isAuthorizationLapsed = !canDispatch()
@@ -598,7 +599,9 @@ class QuickPayRepo @Inject constructor(
QuickPayDispatchClass.DUPLICATE_PAYMENT,
QuickPayDispatchClass.AMBIGUOUS,
-> {
+ reviewLookupBarrier("before-rows") // test hook
val rows = loadPaymentRows()
+ reviewLookupBarrier("after-rows") // test hook
val isEarlierSendTracked = mutex.withLock {
if (isSupersededLocked(op)) return@withLock false
settleAmbiguousLocked(
@@ -670,6 +673,7 @@ class QuickPayRepo @Inject constructor(
private suspend fun resolveSettledEarlierSend(invoiceHash: String) {
// Settled only when confirmed: once it succeeded, or once it failed with no attempt of it live on either rail.
val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull()
+ Logger.warn("Test hook: earlier settlement lookup '${event?.javaClass?.simpleName}'", context = TAG) // test hook
val resolution = when (event) {
is Event.PaymentSuccessful if event.paymentHash == invoiceHash ->
PendingPaymentResolution.Success(invoiceHash)
@@ -677,9 +681,19 @@ class QuickPayRepo @Inject constructor(
PendingPaymentResolution.Failure(invoiceHash, event.reason)
else -> return
}
+ Logger.warn("Test hook: found earlier settlement '${resolution.javaClass.simpleName}' pending='${pendingPaymentRepo.isPending(invoiceHash)}'", context = TAG) // test hook
if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution)
}
+ private suspend fun reviewLookupBarrier(name: String) { // test hook
+ if (!to.bitkit.BuildConfig.DEBUG || !to.bitkit.BuildConfig.E2E) return // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-$name") // test hook
+ if (!marker.exists()) return // test hook
+ Logger.warn("Test hook: waiting at '$name'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ Logger.warn("Test hook: released '$name'", context = TAG) // test hook
+ } // test hook
+
private fun isEarlierSendPaid(invoiceHash: String, rows: List<QuickPayReconcileRow>): Boolean = rows.any {
it.isOutboundBolt11 && it.status == QuickPayReconcileRow.Status.SUCCEEDED &&
it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true)
@@ -724,6 +738,7 @@ class QuickPayRepo @Inject constructor(
}
if (success && op != null && !op.dispatched) {
// QuickPay sent nothing yet, so the success is an earlier send's: the invoice is paid, and not by QuickPay.
+ Logger.warn("Test hook: refund earlier success, undispatched op", context = TAG) // test hook
spend.release(record.invoicePaymentHash)
emitErrorLocked(op, QuickPayAlreadyPaidError(), op.paymentRequest)
removeOpLocked(op)
diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
index 54ed7ad60..e3816947d 100644
--- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
+++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
@@ -103,6 +103,7 @@ fun SendPendingScreen(
val txid = paymentHash.takeIf { isOnchain && it.matches(Regex("[0-9a-fA-F]{64}")) }
LaunchedEffect(Unit) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) to.bitkit.utils.Logger.warn("Test hook: pending screen id='${System.identityHashCode(viewModel)}' hash='$paymentHash' observe='$observeResolution'", context = "SendPendingScreen") // test hook
if (isOnchain) {
viewModel.initOnchain(txid, amount, walletId)
} else if (observeResolution) {
diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
index 23045fea8..9b3a6ff37 100644
--- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
+++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
@@ -56,6 +56,7 @@ class SendPendingViewModel @Inject constructor(
private var isInitialized = false
fun init(paymentHash: String, amount: Long) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending init id='${System.identityHashCode(this)}' hash='$paymentHash' initialized='$isInitialized'", context = TAG) // test hook
if (isInitialized) return
isInitialized = true
pendingPaymentRepo.setActiveHash(paymentHash)
@@ -303,6 +304,7 @@ class SendPendingViewModel @Inject constructor(
}
override fun onCleared() {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending cleared id='${System.identityHashCode(this)}'", context = TAG) // test hook
recoveryApproval?.cancel()
pendingPaymentRepo.setActiveHash(null)
}
@@ -327,6 +329,7 @@ class SendPendingViewModel @Inject constructor(
pendingPaymentRepo.resolution
.filter { it.paymentHash == paymentHash }
.collect { resolution ->
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending observer id='${System.identityHashCode(this)}' consumes '${resolution::class.simpleName}' hash='$paymentHash'", context = TAG) // test hook
pendingPaymentRepo.consumeResolution(paymentHash)
Logger.info(
"Received payment resolution '${resolution::class.simpleName}' for '$paymentHash'",
diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
index fc06b3200..a228806ec 100644
--- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
+++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
@@ -3309,6 +3309,11 @@ class AppViewModel @Inject constructor(
}
private suspend fun handlePaymentSuccessful(event: Event.PaymentSuccessful) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-success-event") // test hook
+ if (marker.exists()) Logger.warn("Test hook: holding real success event", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
val paymentHash = event.paymentHash
viewModelScope.launch {
paykitPaymentProofRepo.completeLightningPayment(paymentHash, event.paymentPreimage)Test hook: Electrum stopped gap starts='1' lifecycle='Stopped' - LightningRepo
Test hook: held send awaiting listing starts='1' lifecycle='Stopped' - LightningRepo
Node started - LightningService
Test hook: Electrum change succeeded - DevToolsProvider
Earlier node payment fails before Pending is tracked ❌ The lookup recovers the failure and refunds the reserve, but the replacement screen remains Pending.
Sent a real 1,000-sat LND hold invoice manually, closed Pending, enabled QuickPay and replayed it through fixed-amount LNURL. Paused QuickPay before its row lookup, cancelled the recipient and delivered the real RECIPIENT_REJECTED event before releasing the lookup.
The lookup then returned PaymentFailed and refunded the fresh reserve to zero with no records. The old observer consumed the recovered Failure before the replacement Pending viewmodel initialized, so the replacement stayed Pending. The recipient retained one cancelled HTLC. Ordering, refund and single-HTLC claims were checked in logs/cache and the recipient record. This reproduces the unchanged, deferred issue linked above.
failure-before-track2x.2x.mp4
Debug controls, not pushed
An explicit barrier holds the first row lookup; logs identify the settlement and Pending observers. The debug invoice provider permits Spark funding. No SDK result or payment decision is replaced; the success-event and Electrum-gap markers were absent.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa144..96710befe 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -10,6 +10,7 @@ import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
+import kotlinx.coroutines.launch // test hook
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import to.bitkit.async.ServiceQueue
@@ -32,6 +33,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun sparkRepo(): to.bitkit.repositories.SparkRepo // test hook
}
private val deps: Dependencies by lazy {
@@ -41,6 +43,15 @@ class DevToolsProvider : ContentProvider() {
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" }
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E && method == "reviewElectrumChange") { // test hook
+ kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO).launch { // test hook
+ deps.lightningRepo().restartWithElectrumServer("tcp://127.0.0.1:60001").fold( // test hook
+ onSuccess = { Logger.warn("Test hook: Electrum change succeeded", context = TAG) }, // test hook
+ onFailure = { Logger.warn("Test hook: Electrum change failed", it, context = TAG) }, // test hook
+ ) // test hook
+ } // test hook
+ return Bundle().apply { putString("result", "Electrum change queued") } // test hook
+ } // test hook
return runCatching {
val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" }
ServiceQueue.LDK.blocking { command.execute(deps) }
@@ -80,10 +91,11 @@ private sealed interface DevCommand {
}
@Serializable
- data class Args(val amount: ULong? = null, val description: String = "dev-invoice")
+ data class Args(val amount: ULong? = null, val description: String = "dev-invoice", val useSpark: Boolean = false) // test hook
override suspend fun execute(deps: DevToolsProvider.Dependencies) =
- deps.lightningRepo().createInvoice(args.amount, args.description).fold(
+ (if (args.useSpark) deps.sparkRepo().createInvoice(args.amount, args.description, to.bitkit.env.Defaults.bolt11ExpirySec) // test hook
+ else deps.lightningRepo().createInvoice(args.amount, args.description)).fold(
onSuccess = { DevResult.Invoice(it) },
onFailure = {
Logger.error("Failed to create invoice", it, context = TAG)
diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
index 1d3acb5bd..c3ff06a08 100644
--- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
@@ -1084,6 +1084,12 @@ class LightningRepo @Inject constructor(
// A stop requested from here on, during the change's first build included, wins over every start.
stopRequests = stopRequestCount.get()
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-config-gap") // test hook
+ if (marker.exists()) Logger.warn("Test hook: Electrum stopped gap starts='${pendingStartCount.value}' lifecycle='${_lightningState.value.nodeLifecycleState}'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
+
Logger.debug("Starting node with new electrum server: '$newServerUrl'", context = TAG)
startConfigChange(stopRequests = stopRequests, customServerUrl = newServerUrl)
@@ -1843,6 +1849,7 @@ class LightningRepo @Inject constructor(
* wallet was wiped since [wipesBefore], as the node that runs next can be another wallet's.
*/
private suspend fun awaitNodeListing(wipesBefore: Long): Boolean {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: held send awaiting listing starts='${pendingStartCount.value}' lifecycle='${_lightningState.value.nodeLifecycleState}'", context = TAG) // test hook
val isWiped = { isWiping || wipeCount.get() != wipesBefore }
// The two flows only wake the wait. What it decides on is read then, the count before the state: read as a
// pair they can show a failed start beside a count another start has left since, which never was the case.
diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
index 0363f244d..f829aae9b 100644
--- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
@@ -436,6 +436,7 @@ class QuickPayRepo @Inject constructor(
}
private suspend fun dispatchBolt11(invoice: ResolvedInvoice, op: InFlightOp, canDispatch: () -> Boolean) {
+ reviewLookupBarrier("before-dispatch") // test hook
var isAuthorizationLapsed = false
lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) {
isAuthorizationLapsed = !canDispatch()
@@ -598,7 +599,9 @@ class QuickPayRepo @Inject constructor(
QuickPayDispatchClass.DUPLICATE_PAYMENT,
QuickPayDispatchClass.AMBIGUOUS,
-> {
+ reviewLookupBarrier("before-rows") // test hook
val rows = loadPaymentRows()
+ reviewLookupBarrier("after-rows") // test hook
val isEarlierSendTracked = mutex.withLock {
if (isSupersededLocked(op)) return@withLock false
settleAmbiguousLocked(
@@ -670,6 +673,7 @@ class QuickPayRepo @Inject constructor(
private suspend fun resolveSettledEarlierSend(invoiceHash: String) {
// Settled only when confirmed: once it succeeded, or once it failed with no attempt of it live on either rail.
val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull()
+ Logger.warn("Test hook: earlier settlement lookup '${event?.javaClass?.simpleName}'", context = TAG) // test hook
val resolution = when (event) {
is Event.PaymentSuccessful if event.paymentHash == invoiceHash ->
PendingPaymentResolution.Success(invoiceHash)
@@ -677,9 +681,19 @@ class QuickPayRepo @Inject constructor(
PendingPaymentResolution.Failure(invoiceHash, event.reason)
else -> return
}
+ Logger.warn("Test hook: found earlier settlement '${resolution.javaClass.simpleName}' pending='${pendingPaymentRepo.isPending(invoiceHash)}'", context = TAG) // test hook
if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution)
}
+ private suspend fun reviewLookupBarrier(name: String) { // test hook
+ if (!to.bitkit.BuildConfig.DEBUG || !to.bitkit.BuildConfig.E2E) return // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-$name") // test hook
+ if (!marker.exists()) return // test hook
+ Logger.warn("Test hook: waiting at '$name'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ Logger.warn("Test hook: released '$name'", context = TAG) // test hook
+ } // test hook
+
private fun isEarlierSendPaid(invoiceHash: String, rows: List<QuickPayReconcileRow>): Boolean = rows.any {
it.isOutboundBolt11 && it.status == QuickPayReconcileRow.Status.SUCCEEDED &&
it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true)
@@ -724,6 +738,7 @@ class QuickPayRepo @Inject constructor(
}
if (success && op != null && !op.dispatched) {
// QuickPay sent nothing yet, so the success is an earlier send's: the invoice is paid, and not by QuickPay.
+ Logger.warn("Test hook: refund earlier success, undispatched op", context = TAG) // test hook
spend.release(record.invoicePaymentHash)
emitErrorLocked(op, QuickPayAlreadyPaidError(), op.paymentRequest)
removeOpLocked(op)
diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
index 54ed7ad60..e3816947d 100644
--- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
+++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
@@ -103,6 +103,7 @@ fun SendPendingScreen(
val txid = paymentHash.takeIf { isOnchain && it.matches(Regex("[0-9a-fA-F]{64}")) }
LaunchedEffect(Unit) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) to.bitkit.utils.Logger.warn("Test hook: pending screen id='${System.identityHashCode(viewModel)}' hash='$paymentHash' observe='$observeResolution'", context = "SendPendingScreen") // test hook
if (isOnchain) {
viewModel.initOnchain(txid, amount, walletId)
} else if (observeResolution) {
diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
index 23045fea8..9b3a6ff37 100644
--- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
+++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
@@ -56,6 +56,7 @@ class SendPendingViewModel @Inject constructor(
private var isInitialized = false
fun init(paymentHash: String, amount: Long) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending init id='${System.identityHashCode(this)}' hash='$paymentHash' initialized='$isInitialized'", context = TAG) // test hook
if (isInitialized) return
isInitialized = true
pendingPaymentRepo.setActiveHash(paymentHash)
@@ -303,6 +304,7 @@ class SendPendingViewModel @Inject constructor(
}
override fun onCleared() {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending cleared id='${System.identityHashCode(this)}'", context = TAG) // test hook
recoveryApproval?.cancel()
pendingPaymentRepo.setActiveHash(null)
}
@@ -327,6 +329,7 @@ class SendPendingViewModel @Inject constructor(
pendingPaymentRepo.resolution
.filter { it.paymentHash == paymentHash }
.collect { resolution ->
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending observer id='${System.identityHashCode(this)}' consumes '${resolution::class.simpleName}' hash='$paymentHash'", context = TAG) // test hook
pendingPaymentRepo.consumeResolution(paymentHash)
Logger.info(
"Received payment resolution '${resolution::class.simpleName}' for '$paymentHash'",
diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
index fc06b3200..a228806ec 100644
--- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
+++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
@@ -3309,6 +3309,11 @@ class AppViewModel @Inject constructor(
}
private suspend fun handlePaymentSuccessful(event: Event.PaymentSuccessful) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-success-event") // test hook
+ if (marker.exists()) Logger.warn("Test hook: holding real success event", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
val paymentHash = event.paymentHash
viewModelScope.launch {
paykitPaymentProofRepo.completeLightningPayment(paymentHash, event.paymentPreimage)Test hook: pending observer id='214678677' consumes 'Failure' hash='aebf6acc93360e9505c912f79afb848faff73f852d83a2220786cdab79cbac04' - SendPendingViewModel
Test hook: found earlier settlement 'Failure' pending='true' - QuickPayRepo
Test hook: pending init id='46366567' hash='aebf6acc93360e9505c912f79afb848faff73f852d83a2220786cdab79cbac04' initialized='false' - SendPendingViewModel
Earlier node payment succeeds before Pending is tracked ❌ Lookup-only recovery leaves Pending; the later real event then reaches Bitcoin Sent.
Repeated with a fresh real 1,000-sat manual hold invoice. Disconnected only its Lightning peer and refreshed the real channel state so the replay selected Spark. Paused after the pending-row snapshot, settled the recipient, restored peer access and held the real success handler. A foreground Electrum restart also completed while the lookup remained paused.
On release, the post-track lookup recovered PaymentSuccessful and refunded the fresh 60-cent reservation to the prior 60-cent spend, with no records. The older observer consumed Success before the replacement initialized; the replacement remained Pending. Releasing the real success handler afterwards reached Bitcoin Sent. The recipient retained exactly one settled HTLC. Accounting and event ordering were checked in logs/cache and the recipient record. This is the same deferred Pending-delivery issue, not a new lookup defect.
success-before-track-final2x.2x.mp4
Debug controls, not pushed
Explicit after-rows and success-handler barriers isolate the real recovered outcome from its delayed event. A debug command re-reads actual channels after peer disconnect. The Electrum-gap marker was absent. No SDK result is replaced.
diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa144..364c40ebd 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -10,6 +10,7 @@ import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
+import kotlinx.coroutines.launch // test hook
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import to.bitkit.async.ServiceQueue
@@ -32,6 +33,7 @@ class DevToolsProvider : ContentProvider() {
@InstallIn(SingletonComponent::class)
interface Dependencies {
fun lightningRepo(): LightningRepo
+ fun sparkRepo(): to.bitkit.repositories.SparkRepo // test hook
}
private val deps: Dependencies by lazy {
@@ -41,6 +43,19 @@ class DevToolsProvider : ContentProvider() {
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" }
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E && method == "reviewRefreshChannels") { // test hook
+ kotlinx.coroutines.runBlocking { deps.lightningRepo().refreshChannelsAndPeers() } // test hook
+ return Bundle().apply { putString("result", "channels refreshed") } // test hook
+ } // test hook
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E && method == "reviewElectrumChange") { // test hook
+ kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + kotlinx.coroutines.Dispatchers.IO).launch { // test hook
+ deps.lightningRepo().restartWithElectrumServer("tcp://127.0.0.1:60001").fold( // test hook
+ onSuccess = { Logger.warn("Test hook: Electrum change succeeded", context = TAG) }, // test hook
+ onFailure = { Logger.warn("Test hook: Electrum change failed", it, context = TAG) }, // test hook
+ ) // test hook
+ } // test hook
+ return Bundle().apply { putString("result", "Electrum change queued") } // test hook
+ } // test hook
return runCatching {
val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" }
ServiceQueue.LDK.blocking { command.execute(deps) }
@@ -80,10 +95,11 @@ private sealed interface DevCommand {
}
@Serializable
- data class Args(val amount: ULong? = null, val description: String = "dev-invoice")
+ data class Args(val amount: ULong? = null, val description: String = "dev-invoice", val useSpark: Boolean = false) // test hook
override suspend fun execute(deps: DevToolsProvider.Dependencies) =
- deps.lightningRepo().createInvoice(args.amount, args.description).fold(
+ (if (args.useSpark) deps.sparkRepo().createInvoice(args.amount, args.description, to.bitkit.env.Defaults.bolt11ExpirySec) // test hook
+ else deps.lightningRepo().createInvoice(args.amount, args.description)).fold(
onSuccess = { DevResult.Invoice(it) },
onFailure = {
Logger.error("Failed to create invoice", it, context = TAG)
diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
index 1d3acb5bd..c3ff06a08 100644
--- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt
@@ -1084,6 +1084,12 @@ class LightningRepo @Inject constructor(
// A stop requested from here on, during the change's first build included, wins over every start.
stopRequests = stopRequestCount.get()
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-config-gap") // test hook
+ if (marker.exists()) Logger.warn("Test hook: Electrum stopped gap starts='${pendingStartCount.value}' lifecycle='${_lightningState.value.nodeLifecycleState}'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
+
Logger.debug("Starting node with new electrum server: '$newServerUrl'", context = TAG)
startConfigChange(stopRequests = stopRequests, customServerUrl = newServerUrl)
@@ -1843,6 +1849,7 @@ class LightningRepo @Inject constructor(
* wallet was wiped since [wipesBefore], as the node that runs next can be another wallet's.
*/
private suspend fun awaitNodeListing(wipesBefore: Long): Boolean {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: held send awaiting listing starts='${pendingStartCount.value}' lifecycle='${_lightningState.value.nodeLifecycleState}'", context = TAG) // test hook
val isWiped = { isWiping || wipeCount.get() != wipesBefore }
// The two flows only wake the wait. What it decides on is read then, the count before the state: read as a
// pair they can show a failed start beside a count another start has left since, which never was the case.
diff --git a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
index 0363f244d..f829aae9b 100644
--- a/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/QuickPayRepo.kt
@@ -436,6 +436,7 @@ class QuickPayRepo @Inject constructor(
}
private suspend fun dispatchBolt11(invoice: ResolvedInvoice, op: InFlightOp, canDispatch: () -> Boolean) {
+ reviewLookupBarrier("before-dispatch") // test hook
var isAuthorizationLapsed = false
lightningRepo.payInvoiceAuthorizedAtSubmission(invoice.bolt11, sats = null, canDispatch) {
isAuthorizationLapsed = !canDispatch()
@@ -598,7 +599,9 @@ class QuickPayRepo @Inject constructor(
QuickPayDispatchClass.DUPLICATE_PAYMENT,
QuickPayDispatchClass.AMBIGUOUS,
-> {
+ reviewLookupBarrier("before-rows") // test hook
val rows = loadPaymentRows()
+ reviewLookupBarrier("after-rows") // test hook
val isEarlierSendTracked = mutex.withLock {
if (isSupersededLocked(op)) return@withLock false
settleAmbiguousLocked(
@@ -670,6 +673,7 @@ class QuickPayRepo @Inject constructor(
private suspend fun resolveSettledEarlierSend(invoiceHash: String) {
// Settled only when confirmed: once it succeeded, or once it failed with no attempt of it live on either rail.
val event = runSuspendCatching { lightningRepo.settledSparkSendEvent(invoiceHash) }.getOrNull()
+ Logger.warn("Test hook: earlier settlement lookup '${event?.javaClass?.simpleName}'", context = TAG) // test hook
val resolution = when (event) {
is Event.PaymentSuccessful if event.paymentHash == invoiceHash ->
PendingPaymentResolution.Success(invoiceHash)
@@ -677,9 +681,19 @@ class QuickPayRepo @Inject constructor(
PendingPaymentResolution.Failure(invoiceHash, event.reason)
else -> return
}
+ Logger.warn("Test hook: found earlier settlement '${resolution.javaClass.simpleName}' pending='${pendingPaymentRepo.isPending(invoiceHash)}'", context = TAG) // test hook
if (pendingPaymentRepo.isPending(invoiceHash)) pendingPaymentRepo.resolve(resolution)
}
+ private suspend fun reviewLookupBarrier(name: String) { // test hook
+ if (!to.bitkit.BuildConfig.DEBUG || !to.bitkit.BuildConfig.E2E) return // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-$name") // test hook
+ if (!marker.exists()) return // test hook
+ Logger.warn("Test hook: waiting at '$name'", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ Logger.warn("Test hook: released '$name'", context = TAG) // test hook
+ } // test hook
+
private fun isEarlierSendPaid(invoiceHash: String, rows: List<QuickPayReconcileRow>): Boolean = rows.any {
it.isOutboundBolt11 && it.status == QuickPayReconcileRow.Status.SUCCEEDED &&
it.invoicePaymentHash.equals(invoiceHash, ignoreCase = true)
@@ -724,6 +738,7 @@ class QuickPayRepo @Inject constructor(
}
if (success && op != null && !op.dispatched) {
// QuickPay sent nothing yet, so the success is an earlier send's: the invoice is paid, and not by QuickPay.
+ Logger.warn("Test hook: refund earlier success, undispatched op", context = TAG) // test hook
spend.release(record.invoicePaymentHash)
emitErrorLocked(op, QuickPayAlreadyPaidError(), op.paymentRequest)
removeOpLocked(op)
diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
index 54ed7ad60..e3816947d 100644
--- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
+++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingScreen.kt
@@ -103,6 +103,7 @@ fun SendPendingScreen(
val txid = paymentHash.takeIf { isOnchain && it.matches(Regex("[0-9a-fA-F]{64}")) }
LaunchedEffect(Unit) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) to.bitkit.utils.Logger.warn("Test hook: pending screen id='${System.identityHashCode(viewModel)}' hash='$paymentHash' observe='$observeResolution'", context = "SendPendingScreen") // test hook
if (isOnchain) {
viewModel.initOnchain(txid, amount, walletId)
} else if (observeResolution) {
diff --git a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
index 23045fea8..9b3a6ff37 100644
--- a/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
+++ b/app/src/main/java/to/bitkit/ui/screens/wallets/send/SendPendingViewModel.kt
@@ -56,6 +56,7 @@ class SendPendingViewModel @Inject constructor(
private var isInitialized = false
fun init(paymentHash: String, amount: Long) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending init id='${System.identityHashCode(this)}' hash='$paymentHash' initialized='$isInitialized'", context = TAG) // test hook
if (isInitialized) return
isInitialized = true
pendingPaymentRepo.setActiveHash(paymentHash)
@@ -303,6 +304,7 @@ class SendPendingViewModel @Inject constructor(
}
override fun onCleared() {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending cleared id='${System.identityHashCode(this)}'", context = TAG) // test hook
recoveryApproval?.cancel()
pendingPaymentRepo.setActiveHash(null)
}
@@ -327,6 +329,7 @@ class SendPendingViewModel @Inject constructor(
pendingPaymentRepo.resolution
.filter { it.paymentHash == paymentHash }
.collect { resolution ->
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) Logger.warn("Test hook: pending observer id='${System.identityHashCode(this)}' consumes '${resolution::class.simpleName}' hash='$paymentHash'", context = TAG) // test hook
pendingPaymentRepo.consumeResolution(paymentHash)
Logger.info(
"Received payment resolution '${resolution::class.simpleName}' for '$paymentHash'",
diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
index fc06b3200..a228806ec 100644
--- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
+++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
@@ -3309,6 +3309,11 @@ class AppViewModel @Inject constructor(
}
private suspend fun handlePaymentSuccessful(event: Event.PaymentSuccessful) {
+ if (to.bitkit.BuildConfig.DEBUG && to.bitkit.BuildConfig.E2E) { // test hook
+ val marker = java.io.File(to.bitkit.env.Env.logDir.parentFile, "review-success-event") // test hook
+ if (marker.exists()) Logger.warn("Test hook: holding real success event", context = TAG) // test hook
+ while (marker.exists()) kotlinx.coroutines.delay(50) // test hook
+ } // test hook
val paymentHash = event.paymentHash
viewModelScope.launch {
paykitPaymentProofRepo.completeLightningPayment(paymentHash, event.paymentPreimage)Test hook: holding real success event - AppViewModel
Test hook: found earlier settlement 'Success' pending='true' - QuickPayRepo
Test hook: pending observer id='49404851' consumes 'Success' hash='c0065472426830e2832f019995525d3b1754762618420e5cbccb7061e3f9ac17' - SendPendingViewModel
Test hook: pending init id='19612324' hash='c0065472426830e2832f019995525d3b1754762618420e5cbccb7061e3f9ac17' initialized='false' - SendPendingViewModel
Passing device evidence retained for unchanged paths:
- Device evidence at 229581d: manual cases 1, 2, 3, 5 and 8.
- 229581d review: cases 4 and 6.
- 6015762 review: both case-7 already-paid variants, dismissal and locking.
- 668f8a9 review: the unchanged early-success refund, stale-callback retry and failure-after-tracking recordings at 1abe3bf. Its two failing pre-track cases were re-driven above.
Physical NFC was not repeated; the new cases use deep links. RGS and recovery retry/stop interleavings were checked in source and focused unit tests, without separate device cases. The other merged master features were outside this PR's effective diff.
Reviewed contiguous 57bdfe07..d953045d, its LightningRepo conflict resolution, reached send/lifecycle paths and the earlier findings. The remaining failure matches the declared follow-up rather than a defect introduced by this merge.
Twin: no matching fix PR is linked. The adjacent nearby-payment twin is synonymdev/bitkit-ios#1302; at 3c26e98 its QuickPay coordinator marks dispatch before submission, so its completion accounting differs. No iOS device run.
Reviewed by gpt-6.1-sol-high
piotr-iohk
left a comment
There was a problem hiding this comment.
Device QA passed on d953045d on an Android 13 emulator using regtest.
- The recipient accepted and canceled a real 1,000-sat Lightning HTLC. Quick Pay left Pending and showed Payment Failed with the recipient-rejection message. The same result was visible 28 seconds later.
- With Spark online and LDK reconnecting, a second real rejection also moved Quick Pay from Pending to Payment Failed once LDK delivered the failure.
- After the failure was visible, I closed the screen and reopened the same canceled invoice through Quick Pay. It showed Payment Failed again.
The local regtest build used a test-only lookup pause to control the first replay. All required CI checks, including E2E, passed.
Fixes #2028
This PR stops QuickPay from waiting for the Lightning node when Spark alone covers the amount.
Description
lightning:tag) and Spark covers the amount.Cause: before deciding on QuickPay, a scan waits for usable channels whenever the node is starting or its channels are reconnecting, so the check for the spending balance update reads real channel balances. That wait was called without the amount, so the existing rule that skips the node when Spark covers the amount never applied.
Change 1, the QuickPay check passes the amount to the wait, as the other send paths already do:
Change 2, the held Spark send: a Spark send is refused with "node not started" while the node cannot list its payments and the invoice has an earlier node send on record, the node never listed its payments on this install, or a restore is not reconciled yet. The removed wait hid this for QuickPay, because the node was running by the time it paid. Now the send waits until the node runs and lists its payments (the same 1 minute bound other node operations use), publishes its channels and starts over once: the rail is picked again and the earlier node send is looked up.
Behaviour change to be aware of:
Why skipping the wait is safe:
Out of Scope
A Spark
SendRefusedbefore dispatch keeps the QuickPay reserve until the next day (pre-existing on master; raised in QA review): QuickPay keeps the daily spend reserved when Spark refuses before dispatch #2161.A Pending screen can miss its resolution when an earlier Pending screen for the same hash consumes it (unchanged code; raised in QA review): Pending screen can miss its resolution when an earlier Pending screen consumes it #2162.
QuickPay with QuickPay off, a payment already open in the QuickPay ledger, or a stopped node: unchanged, none of them waited.
Rail preference while the node starts: keeping the channels as the first choice from the background would need the wait back. Not changed here.
A state change that returns to an equal state between two reads can leave the wait unwoken until the next change or its 1 minute bound. Not handled here.
A held Spark send that arrives while the node is stopped and before the app has called its start still fails with "node not started". There is no signal that a start is about to be called; the app calls it when it returns to the foreground.
Design
N/A — no UI changes.
Preview
N/A
QA Notes
Setup
Regtest
devDebugbuild of this branch on a phone with NFC. Wallet with a Spark spending balance, QuickPay on with the $5 threshold. Cases 3, 4, 6 and 7 also need a channel with outbound balance. A second phone or an NFC tag supplies the request.Journeys
N/A — not drivable; see Manual Tests.
Manual Tests
lightning:NFC tag → same result — NFC tap not in CapabilitiesWaiting for node to load channels before sending payment, then QuickPay pays over the channel — NFC tap not in Capabilitieslightning:tag over the channel, then from the background tap the same tag again with Spark covering the amount → QuickPay waits for the node to start, no second payment of that invoice goes out, and no "node not started" error shows. Run it twice: after the node has fully stopped, and 5–30 s after backgrounding while the node is still stopping — NFC tap not in CapabilitiesAutomated Checks
AppViewModelSendFlowTest.kt— a scan while the node starts uses QuickPay with no channel wait when Spark covers the amount, for a bolt11 invoice, a fixed-amount LNURL and a unified invoiceAppViewModelSendFlowTest.kt— a scan with unusable channels publishes them without waiting when Spark covers the amountAppViewModelSendFlowTest.kt— the wait is kept when Spark covers less than the amount, and for an amountless invoice when Spark is ready with no balanceAppViewModelSendFlowTest.kt— a payment that needs the update is not sent by QuickPay when the wait is skippedMoveToSparkRepoTest.kt— an amount Spark can send alone never needs the update, for any channels, also while Spark is not ready or exitingLightningRepoTest.kt— a held Spark send is retried once after the starting node runs and lists its payments, also when it was held while the node stops and a start is queuedLightningRepoTest.kt— it fails with the original error on timeout, when the node cannot run, when the node stops with no start coming, when the start fails, when a wipe begins, and when the wallet is wiped during the waitLightningRepoTest.kt— it keeps waiting through a failed start when another start is queued, and through a restart's stop (see Gaps: the restart test does not prove the restart holds)LightningRepoTest.kt— a listing that fails during the wait returns the hold's failure instead of throwingLightningRepoTest.kt— a caller cancelled during the wait sends nothingLightningRepoTest.kt— the retry pays over the node when its channels cover the amount, and sends nothing when the node lists its earlier send as pending or paidQuickPayRepoTest.kt— a return without a dispatch refunds the reserve and shows already paid, or pending when an earlier send of the invoice may still be in flight; an earlier send resolved before it was tracked is resolved againQuickPayRepoTest.kt— an earlier send's success before QuickPay dispatches refunds the reserve and stops the send, also when it arrives during the row lookupQuickPayRepoTest.kt— a stale dispatch left after an early success does not mark, release or emit for a later pay of the same invoiceLightningRepoTest.kt— an earlier node send that failed settles as failed once no attempt of it is live, and settles nothing while a retry is sent or ends during the listing, or for a caller still waiting on the node's eventEvidence
Phone run on
229581d1d, regtestdevDebugon both phones: a Xiaomi (Android 13) paying a Pixel's Receive (Spending, ₿ 1,000 each). Spark balance 40,881 on the payer, no channel on either phone, QuickPay on with the $5 threshold. Times are seconds after the payer received the request.Using QuickPayCOMPLETEDlightning:link, background with the node stoppedlightning:NFC tag, background with the node stoppedbca0fa0ba) started QuickPay at +9.5 s in the same background case and +0.9 s in the foreground.Waiting for node to load channelsline in any case, no refused Spark send, no "node not started" error, no crash. One payment per case: the payer's balance moved 1,005 and the payee's 1,000 each time, and the node rail was never used.Case 1, phone-to-phone tap (payer):
c1a-xi.mp4
Case 2,
lightning:tag (payer):c2b-xi.mp4
Device run on
229581d1d, emulator (API 35), regtestdevDebug, Spending 157,056 in a channel, Spark balance 0, QuickPay on with the $5 threshold. Times are seconds after the app received the request.Using QuickPayat +17.2 s, paid once over the channelUsing QuickPayat +0.7 s, paid once, no node waitlightning:deep link in place of the NFC tap, and an emulator, whose node start is slower than a phone's.Case 3:
c3.mp4
Case 5:
c5.mp4
Run locally on
229581d1d, no device:./gradlew testDevDebugUnitTest --rerunforAppViewModelSendFlowTest,LightningRepoTest,MoveToSparkRepoTestandQuickPayRepoTest— 800, 300, 61 and 83 tests, 0 failures./gradlew detekt --rerun-tasks,./gradlew lintDevDebug— passedAppViewModel.ktandLightningRepo.ktatmaster(run on646a152a3): 10 of the tests added up to that commit fail, the five no-wait and amountless cases and five held-send cases.LightningRepo.ktat646a152a3(run on8f47458aa): 6 of the tests added since fail (stop with a queued start, stop with no start coming, start failure, wipe, the listing wait, and the bound while the node cannot list).bb59960e3): the failing-listing test and the wipe-begins test fail. The queued-start-after-a-failed-start test failed while the wait read the start count and the node state as a pair, which is what led to reading them when woken.Gaps
awaitNodeId, used to tell an own invoice from another's) before it reaches the QuickPay check, so QuickPay still starts about 10 s after the request.Models used
claude-opus-5-5(reasoning:medium)claude-fable-5-2(reasoning:medium)claude-fable-5-2(reasoning:Unknown)Metadata note: all review rounds used the same model, as reported by the coordinating session; their reasoning effort was not passed on.
🤖 Generated with Claude Code