From 3ac4a6c5cd108c06baa2dabff3d8ea200ce78bc4 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 27 Nov 2026 22:33:34 +0100 Subject: [PATCH 1/3] fix: record a refused lightning paykit payment before its cleanup When the recheck before submission refuses a Lightning payment of a Paykit request, the automatic and manual paths now move the journal entry back to submitted before the proof is cleared and the payment list released. Recovery after a kill in between, or after a failed ledger write, then finds an unsent attempt and records it as failed instead of leaving it open. Verified: ./gradlew testDevDebugUnitTest for PaykitAllowanceExecutorTest, PaykitPaymentProofRepoTest, PaykitAllowancePayerTest and AppViewModelSendFlowTest; ./gradlew detekt --- .../repositories/PaykitAllowanceExecutor.kt | 23 ++++++++++ .../repositories/PaykitAllowanceRepo.kt | 2 + .../repositories/PaykitPaymentProofRepo.kt | 14 ++++-- .../java/to/bitkit/viewmodels/AppViewModel.kt | 1 + .../PaykitAllowanceExecutorTest.kt | 46 +++++++++++++++++++ .../viewmodels/AppViewModelSendFlowTest.kt | 4 ++ 6 files changed, 86 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 90f9ee1ef8..981e05e5c5 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt @@ -132,6 +132,9 @@ class PaykitAllowancePayer @Inject constructor( requestId: PaykitPaymentRequestId, ): Boolean = paymentProofRepo.failLightningPayment(paymentHash, error, requestId) + /** Whether [error] proves the payment never left. */ + fun submissionSentNothing(error: Throwable): Boolean = paymentProofRepo.submissionSentNothing(error) + suspend fun discardLightningProof(paymentHash: String, requestId: PaykitPaymentRequestId) = paymentProofRepo.failLightningPayment(paymentHash, requestId) @@ -999,6 +1002,13 @@ class PaykitAllowanceExecutor @Inject constructor( ).onFailure { // Only an error that proves the payment never left releases the reservation; anything else stays open, // and the node's payment event records its outcome. + if (payer.submissionSentNothing(it)) { + // Saved before the cleanup, so recovery after a kill in between ends the attempt as unsent. + updateJournalEntry(attemptId, identity) { + val settled = it.stage == Stage.SUCCEEDED || it.stage == Stage.FAILED + if (settled) it else it.copy(stage = Stage.SUBMITTED) + } + } if (payer.failLightningPayment(paymentHash, it, request.id)) { failUnsent(attemptId, identity) throw it @@ -1159,6 +1169,19 @@ class PaykitAllowanceExecutor @Inject constructor( } } + /** + * Called when the recheck before submission refuses a manual Lightning payment, before its proof is cleared, so + * recovery after a kill reads the attempt as unsent once the node has no payment for it. + */ + suspend fun manualLightningPaymentRefused(attemptId: String) { + val identity = activeIdentity ?: return + withContext(ioDispatcher) { + updateJournalEntry(attemptId, identity) { + if (it.stage == Stage.SUCCEEDED || it.stage == Stage.FAILED) it else it.copy(stage = Stage.SUBMITTED) + } + } + } + suspend fun finishManualPayment( attemptId: String, outcome: PaymentOutcome, diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt index 054c7566e6..02adad975e 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceRepo.kt @@ -789,6 +789,8 @@ class PaykitAllowanceRepo @Inject constructor( suspend fun manualLightningPaymentSent(attemptId: String, paymentHash: String) = executor.manualLightningPaymentSent(attemptId, paymentHash) + suspend fun manualLightningPaymentRefused(attemptId: String) = executor.manualLightningPaymentRefused(attemptId) + /** [succeeded] null = outcome unknown (pending). */ suspend fun finishManualPayment(attemptId: String, succeeded: Boolean?, transactionId: String? = null) { val outcome = when (succeeded) { diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index 557f84aac8..3498a7baf2 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -968,13 +968,20 @@ class PaykitPaymentProofRepo @Inject constructor( submissionError: Throwable, requestId: PaykitPaymentRequestId? = null, ): Boolean { + if (!submissionSentNothing(submissionError)) return false + failLightningPayment(paymentHash, requestId) + return true + } + + /** Whether [submissionError] proves the payment never left. */ + fun submissionSentNothing(submissionError: Throwable): Boolean { val error = generateSequence(submissionError) { it.cause } .firstOrNull { it is ServiceError.PaymentDeadlineExpired || it is SparkError.SendRefused || it is ServiceError.PaymentStoppedAtSubmission || it is PaymentAbortedBeforeSend } ?: submissionError.asNodeException() ?: submissionError - when (error) { + return when (error) { is SparkError.SendRefused, is ServiceError.PaymentStoppedAtSubmission, is PaymentAbortedBeforeSend, @@ -986,10 +993,9 @@ class PaykitPaymentProofRepo @Inject constructor( is NodeException.NotRunning, is NodeException.InvalidInvoice, is NodeException.InvalidAmount, - is NodeException.PaymentSendingFailed -> failLightningPayment(paymentHash, requestId) - else -> return false + is NodeException.PaymentSendingFailed -> true + else -> false } - return true } suspend fun retainHardwareOnchainCandidate( diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index a19961687c..c6acc620e3 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8376,6 +8376,7 @@ class AppViewModel @Inject constructor( error.isStoppedAtSubmission() } == true authorizationError?.takeIf { sentNothing }?.let { + allowanceAttemptId?.let { paykitAllowanceRepo.manualLightningPaymentRefused(it) } paykitPaymentProofRepo.failLightningPayment(paymentHash, incomingPaymentRequest?.id) releasePrivatePaymentListIfNeeded(contactPaymentContext) cancelPaymentProofPreparation(proofRequest) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt index 042a00a7fa..6e82404396 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt @@ -1093,6 +1093,25 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { verify(payer).failLightningPayment(eq(PAYMENT_HASH), any(), eq(secondRequest.id)) } + @Test + fun `a refused lightning payment is journaled unsent before its proof is cleared`() = test { + sut.activate(identity) + whenever( + payer.payLightning(any(), any(), anyOrNull(), anyOrNull(), any()) + ).thenReturn(Result.failure(TestAllowanceError("refused"))) + whenever(payer.submissionSentNothing(any())).thenReturn(true) + var stageAtCleanup: Stage? = null + whenever(payer.failLightningPayment(any(), any(), any())).doSuspendableAnswer { + stageAtCleanup = sut.localState(identity).journal.single().stage + true + } + + sut.autoPay(fixtures.paymentRequest(), listOf(fixtures.allowance()), identity) + + // Recovery after a kill here finds an unsent attempt and fails it. + assertEquals(Stage.SUBMITTED, stageAtCleanup) + } + @Test fun `a payment list given back by a failed send stays given back after the node's failure event`() = test { sut.activate(identity) @@ -1894,6 +1913,33 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { ) } + @Test + fun `recovery fails a refused manual lightning payment whose outcome was not recorded`() = test { + sut.activate(identity) + val attemptId = checkNotNull( + sut.beginManualPayment(fixtures.paymentRequest(), fixtures.lightningIdentifier, PAYMENT_HASH).getOrThrow(), + ) + sut.manualLightningPaymentSent(attemptId, PAYMENT_HASH) + + // Killed after the refusal cleared the proof, before the failure reached the ledger. + sut.manualLightningPaymentRefused(attemptId) + accountingState = fixtures.accountingState( + occurrences = listOf(occurrence(attemptId, PaymentExecutionStatus.SUBMITTED)), + ) + recordedOutcomes.clear() + val restarted = PaykitAllowanceExecutor( + ioDispatcher = testDispatcher, + paykitSdkService = sdk, + store = PaykitAllowanceStore(keychain), + payer = payer, + clock = clock, + accountingAmount = { _, _ -> fixtures.accountingAmount("0.00001") }, + ) + restarted.recover(identity) + + assertEquals(listOf(PaymentOutcomeReport(attemptId, PaymentOutcome.FAILED)), recordedOutcomes) + } + @Test fun `recovery settles a manual lightning payment restored from a backup taken before the send`() = test { sut.activate(identity) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index b0f0c8bab3..675af5a28f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -24367,6 +24367,10 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) verify(paykitAllowanceRepo).finishManualPayment("refused-attempt", false, null) + // Journaled unsent before the cleanup, so recovery after a kill in between fails the attempt. + val order = inOrder(paykitAllowanceRepo, paykitPaymentProofRepo) + order.verify(paykitAllowanceRepo).manualLightningPaymentRefused("refused-attempt") + order.verify(paykitPaymentProofRepo).failLightningPayment(paymentHash, request.id) } @Test From 2484af16f5417fff40f8be1cdba26b832defd2f0 Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Fri, 27 Nov 2026 23:01:00 +0100 Subject: [PATCH 2/3] chore: add changelog fragment Verified: none (changelog fragment only) --- changelog.d/next/2176.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/2176.fixed.md diff --git a/changelog.d/next/2176.fixed.md b/changelog.d/next/2176.fixed.md new file mode 100644 index 0000000000..41958e8bd0 --- /dev/null +++ b/changelog.d/next/2176.fixed.md @@ -0,0 +1 @@ +A contact payment request refused just before sending is no longer left open if the app closes before the refusal is saved. From 249f54e9c67d9fcf3e4e0f30fae3fdcbe26b983b Mon Sep 17 00:00:00 2001 From: Ovi Trif Date: Sat, 28 Nov 2026 07:38:38 +0100 Subject: [PATCH 3/3] fix: discard the started proof when recovery fails an unsent payment Recovery of a refusal killed between its unsent journal save and the proof cleanup recorded the attempt as failed but kept the proof, which hid the request from the pending list. Recovery now discards the Lightning proof of an attempt the node never saw before it fails it, and leaves the attempt open when the discard cannot be saved. Verified: ./gradlew testDevDebugUnitTest for PaykitAllowanceExecutorTest, PaykitPaymentProofRepoTest, PaykitAllowancePayerTest and AppViewModelSendFlowTest; ./gradlew detekt --- .../repositories/PaykitAllowanceExecutor.kt | 18 ++++++++- .../PaykitAllowanceExecutorTest.kt | 37 +++++++++++++++++++ 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 981e05e5c5..7ad1722597 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt @@ -478,9 +478,12 @@ class PaykitAllowanceExecutor @Inject constructor( entry?.let { journalOutcome(it) } ?: PaymentOutcome.UNKNOWN.takeIf { attempt.status == PaymentExecutionStatus.SUBMITTED } } - outcome?.let { record(attempt.attemptId, it, identity) } + // Left open when the proof could not be discarded, so the next recovery tries again. + val settles = outcome != PaymentOutcome.FAILED || + discardUnsentLightningProof(attempt.attemptId, identity) + if (settles) outcome?.let { record(attempt.attemptId, it, identity) } // One that paid nothing gives the payee's list back, as a live failure does. - if (outcome == PaymentOutcome.FAILED && entry?.isAutomatic == true) { + if (settles && outcome == PaymentOutcome.FAILED && entry?.isAutomatic == true) { releasePaymentList(entry, identity) } } @@ -623,6 +626,17 @@ class PaykitAllowanceExecutor @Inject constructor( entry.paymentHash != null && !payer.canListLightningPayments() + /** + * A failed payment has no proof to deliver, and a started proof left in place hides its request from the pending + * list. Discarded before the outcome is saved, so a kill in between leaves the attempt open for the next recovery. + */ + private suspend fun discardUnsentLightningProof(attemptId: String, identity: String): Boolean { + val entry = localState(identity).journal.firstOrNull { it.attemptId == attemptId } ?: return true + if (entry.stage == Stage.SUCCEEDED || entry.stage == Stage.FAILED) return true + val paymentHash = entry.paymentHash ?: return true + return payer.discardLightningProof(paymentHash, entry.requestId).isSuccess + } + private suspend fun record(attemptId: String, outcome: PaymentOutcome, identity: String) { paykitSdkService.recordPaymentOutcome(PaymentOutcomeReport(attemptId, outcome)) val stage = when (outcome) { diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt index 6e82404396..7c80a1d110 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt @@ -250,6 +250,7 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { payer.payLightning(any(), any(), anyOrNull(), anyOrNull(), any()) ).thenReturn(Result.success(PAYMENT_HASH)) whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true) + whenever(payer.discardLightningProof(any(), any())).thenReturn(Result.success(Unit)) whenever(payer.lightningPaymentStatus(any())).thenAnswer { nodeStatuses[it.getArgument(0)] } whenever(payer.canListLightningPayments()).thenAnswer { nodeListsPayments } } @@ -1938,6 +1939,42 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { restarted.recover(identity) assertEquals(listOf(PaymentOutcomeReport(attemptId, PaymentOutcome.FAILED)), recordedOutcomes) + val order = inOrder(sdk, payer) + order.verify(payer).discardLightningProof(eq(PAYMENT_HASH), any()) + order.verify(sdk).recordPaymentOutcome(PaymentOutcomeReport(attemptId, PaymentOutcome.FAILED)) + } + + @Test + fun `recovery discards the started proof of a refused automatic payment`() = test { + val request = fixtures.paymentRequest() + // Killed after the refusal was journaled as unsent, before its started proof was discarded. + seedJournal(journalEntry(AUTOMATIC_ATTEMPT_ID, request, Stage.SUBMITTED, PAYMENT_HASH)) + accountingState = fixtures.accountingState( + occurrences = listOf(occurrence(AUTOMATIC_ATTEMPT_ID, PaymentExecutionStatus.SUBMITTED)), + ) + + sut.recover(identity) + + assertEquals(listOf(PaymentOutcomeReport(AUTOMATIC_ATTEMPT_ID, PaymentOutcome.FAILED)), recordedOutcomes) + val order = inOrder(sdk, payer) + order.verify(payer).discardLightningProof(PAYMENT_HASH, request.id) + order.verify(sdk).recordPaymentOutcome(PaymentOutcomeReport(AUTOMATIC_ATTEMPT_ID, PaymentOutcome.FAILED)) + } + + @Test + fun `recovery leaves a refused payment open when its proof cannot be discarded`() = test { + val request = fixtures.paymentRequest() + seedJournal(journalEntry(AUTOMATIC_ATTEMPT_ID, request, Stage.SUBMITTED, PAYMENT_HASH)) + accountingState = fixtures.accountingState( + occurrences = listOf(occurrence(AUTOMATIC_ATTEMPT_ID, PaymentExecutionStatus.SUBMITTED)), + ) + whenever(payer.discardLightningProof(any(), any())).thenReturn(Result.failure(TestAllowanceError("store"))) + + sut.recover(identity) + + // The next recovery discards the proof and fails the attempt. + assertEquals(emptyList(), recordedOutcomes) + assertEquals(listOf(Stage.SUBMITTED), sut.localState(identity).journal.map { it.stage }) } @Test