diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 90f9ee1ef8..7ad1722597 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) @@ -475,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) } } @@ -620,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) { @@ -999,6 +1016,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 +1183,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..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 } } @@ -1093,6 +1094,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 +1914,69 @@ 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) + 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 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 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.