diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 9c1e7c366c..50b1bb94bf 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -202,14 +202,14 @@ class CacheStore internal constructor( } /** - * Keeps [attempt] as the latest attempt at paying the invoice with [paymentHash], which expires at [expiresAt], - * and drops the attempts of invoices expired before [now], both in epoch seconds. + * Keeps [attempt], sending [amountSats], as the latest attempt at paying the invoice with [paymentHash], which + * expires at [expiresAt], and drops the attempts of invoices expired before [now], both in epoch seconds. */ - suspend fun setSparkSendAttempt(paymentHash: String, attempt: Int, expiresAt: Long, now: Long) { + suspend fun setSparkSendAttempt(paymentHash: String, attempt: Int, amountSats: ULong, expiresAt: Long, now: Long) { val hash = paymentHash.lowercase() store.updateData { val live = it.sparkSendAttempts.filterValues { kept -> kept.expiresAt >= now } - it.copy(sparkSendAttempts = live + (hash to SparkSendAttempt(attempt, expiresAt))) + it.copy(sparkSendAttempts = live + (hash to SparkSendAttempt(attempt, expiresAt, amountSats))) } } @@ -521,9 +521,12 @@ data class AppCacheData( fun invalidateReceiveOnchainAddress() = copy(bip21 = "", onchainAddress = "") } -/** An attempt at paying an invoice through Spark, the [attempt]th, of an invoice that expires at [expiresAt]. */ +/** + * An attempt at paying an invoice through Spark, the [attempt]th, of an invoice that expires at [expiresAt], sending + * [amountSats] (null for one kept before amounts were). + */ @Serializable -data class SparkSendAttempt(val attempt: Int, val expiresAt: Long) +data class SparkSendAttempt(val attempt: Int, val expiresAt: Long, val amountSats: ULong? = null) @Serializable data class CachedUsdtBalance( diff --git a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt index 642eb194b4..c24e9b6841 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitAllowanceExecutor.kt @@ -119,10 +119,14 @@ class PaykitAllowancePayer @Inject constructor( ): Result = lightningRepo.payInvoice(bolt11, sats, paymentDeadlineAt, maxTotalRoutingFeeMsat) { true } /** Clears the proof when [error] proves the payment never left; returns whether it did. */ - suspend fun failLightningPayment(paymentHash: String, error: Throwable): Boolean = - paymentProofRepo.failLightningPayment(paymentHash, error) + suspend fun failLightningPayment( + paymentHash: String, + error: Throwable, + requestId: PaykitPaymentRequestId, + ): Boolean = paymentProofRepo.failLightningPayment(paymentHash, error, requestId) - suspend fun discardLightningProof(paymentHash: String) = paymentProofRepo.failLightningPayment(paymentHash) + suspend fun discardLightningProof(paymentHash: String, requestId: PaykitPaymentRequestId) = + paymentProofRepo.failLightningPayment(paymentHash, requestId) suspend fun cancelProofPreparation(request: PaykitPaymentRequest) = paymentProofRepo.cancelPreparation(request) @@ -970,7 +974,7 @@ class PaykitAllowanceExecutor @Inject constructor( } runSuspendCatching { setStage(Stage.SENDING, attemptId, identity) }.onFailure { - payer.discardLightningProof(paymentHash) + payer.discardLightningProof(paymentHash, request.id) failUnsent(attemptId, identity) throw it } @@ -987,7 +991,7 @@ 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.failLightningPayment(paymentHash, it)) { + if (payer.failLightningPayment(paymentHash, it, request.id)) { failUnsent(attemptId, identity) throw it } diff --git a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt index b8fe69b490..20ee9882df 100644 --- a/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt @@ -930,11 +930,22 @@ class PaykitPaymentProofRepo @Inject constructor( completed } - suspend fun failLightningPayment(paymentHash: String) = removeProofs { - it.kind == PaykitPaymentProofKind.Lightning && it.paymentIdentifier.equals(paymentHash, ignoreCase = true) + /** + * Clears the Lightning proofs of [paymentHash], only those of [requestId] when given, so a request that sent + * nothing leaves another request's proof of the same invoice. + */ + suspend fun failLightningPayment(paymentHash: String, requestId: PaykitPaymentRequestId? = null) = removeProofs { + it.kind == PaykitPaymentProofKind.Lightning && + it.paymentIdentifier.equals(paymentHash, ignoreCase = true) && + (requestId == null || it.requestId == requestId) } - suspend fun failLightningPayment(paymentHash: String, submissionError: Throwable): Boolean { + /** Clears the proofs as above when [submissionError] proves the payment never left; returns whether it did. */ + suspend fun failLightningPayment( + paymentHash: String, + submissionError: Throwable, + requestId: PaykitPaymentRequestId? = null, + ): Boolean { val error = generateSequence(submissionError) { it.cause } .firstOrNull { it is ServiceError.PaymentDeadlineExpired || it is SparkError.SendRefused } ?: submissionError.asNodeException() ?: submissionError @@ -948,7 +959,7 @@ class PaykitPaymentProofRepo @Inject constructor( is NodeException.NotRunning, is NodeException.InvalidInvoice, is NodeException.InvalidAmount, - is NodeException.PaymentSendingFailed -> failLightningPayment(paymentHash) + is NodeException.PaymentSendingFailed -> failLightningPayment(paymentHash, requestId) else -> return false } return true diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 851cb52a40..a66ba4b345 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -1,6 +1,7 @@ package to.bitkit.repositories import breez_sdk_spark.AutoOptimizationEvent +import breez_sdk_spark.Bolt11InvoiceDetails import breez_sdk_spark.ClaimDeferredReason import breez_sdk_spark.ClaimDepositOutcome import breez_sdk_spark.FeePolicy @@ -51,6 +52,7 @@ import to.bitkit.async.appScope import to.bitkit.data.CacheStore import to.bitkit.data.SettingsStore import to.bitkit.data.SparkPayoutChain +import to.bitkit.data.SparkSendAttempt import to.bitkit.di.BgDispatcher import to.bitkit.env.Defaults import to.bitkit.env.Env @@ -655,6 +657,9 @@ class SparkRepo @Inject constructor( // A held send whose attempt Spark lists failed is settled by the next listing, and a send after that // goes through the restore checks above, as a new key's send must. if (isKeyedRetry && !isReusedKey) throw PaymentPendingException(paymentHash) + // Spark returns the earlier attempt's payment for its key, so a retry at another amount is refused. + val sendSats = sendAmountSats(amountSats, invoice) + if (isReusedKey) ensureKeptAmount(previousAttempt, sendSats) // A send refused before anything went out is taken as not having used its key, so a retry refuses the // same way. The hold of an earlier attempt under the same key stays, as it may have committed a @@ -673,6 +678,7 @@ class SparkRepo @Inject constructor( cacheStore.setSparkSendAttempt( paymentHash, attempt, + sendSats, expiresAt.toEpochSeconds(), clock.now().epochSeconds, ) @@ -1022,6 +1028,14 @@ class SparkRepo @Inject constructor( return info.lastSyncError == null && syncedAt != null && (seconds == null || syncedAt > seconds) } + private fun sendAmountSats(amountSats: ULong?, invoice: Bolt11InvoiceDetails): ULong = + amountSats ?: invoice.amountMsat?.div(MSATS_PER_SAT) ?: 0uL + + private fun ensureKeptAmount(previous: SparkSendAttempt?, sendSats: ULong) { + val keptSats = previous?.amountSats ?: return + if (keptSats != sendSats) throw SparkError.SendRefused("An earlier attempt at '$keptSats' sats may still pay") + } + private fun ensurePaymentDeadline(paymentDeadlineAt: Instant?) { if (paymentDeadlineAt != null && clock.now() > paymentDeadlineAt) throw ServiceError.PaymentDeadlineExpired() } diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index 6150b44e24..8e6b636c12 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -8284,7 +8284,7 @@ class AppViewModel @Inject constructor( onFailure = { Result.failure(it) }, ) authorizationError?.let { - paykitPaymentProofRepo.failLightningPayment(paymentHash) + paykitPaymentProofRepo.failLightningPayment(paymentHash, incomingPaymentRequest?.id) releasePrivatePaymentListIfNeeded(contactPaymentContext) cancelPaymentProofPreparation(proofRequest) finishManualAllowancePayment(allowanceAttemptId, succeeded = false) @@ -8309,14 +8309,16 @@ class AppViewModel @Inject constructor( ) lnurlComment?.let { activityRepo.setLightningMessageIfEmpty(paymentHash, it) } }.onFailure { error -> - if (!clearFailedLightningPayment(paymentHash, error, incomingPaymentRequest != null, updateFailed)) { + if (!clearFailedLightningPayment(paymentHash, error, incomingPaymentRequest?.id, updateFailed)) { val pendingHash = (error as? PaymentPendingException)?.paymentHash ?: paymentHash proofRequest = null Logger.info("Lightning payment pending", context = TAG) pendingPaymentRepo.track(pendingHash) preserveContactPaymentContext(pendingHash) if (incomingPaymentRequest != null) refreshIncomingPaykitPaymentRequests() - setSendEffect(SendEffect.NavigateToPending(pendingHash, displayAmountSats.toLong())) + // A repeat of a pending payment shows what that payment sends, also when its amount was typed. + val pendingSats = earlierLightningSendSats(pendingHash) ?: displayAmountSats + setSendEffect(SendEffect.NavigateToPending(pendingHash, pendingSats.toLong())) lnurlComment?.let { activityRepo.setLightningMessageIfEmpty(paymentHash, it) } resolveSettledPendingSend(pendingHash) return@onFailure @@ -8343,6 +8345,15 @@ class AppViewModel @Inject constructor( } } + private suspend fun earlierLightningSendSats(paymentHash: String): ULong? { + val sent = (activityRepo.getActivity(paymentHash).getOrNull() as? Activity.Lightning)?.v1 + ?.takeIf { it.txType == PaymentType.SENT && it.status != PaymentState.FAILED } + if (sent != null) return sent.value + val hash = paymentHash.lowercase() + val cache = cacheStore.data.first() + return cache.sparkSendAttempts[hash]?.amountSats?.takeIf { hash in cache.sparkUncertainSends } + } + private class LightningRepeat(val paymentHash: String, val bolt11: String, val earlierSentSats: ULong?) /** @@ -8482,17 +8493,17 @@ class AppViewModel @Inject constructor( private suspend fun clearFailedLightningPayment( paymentHash: String, error: Throwable, - isPaymentRequest: Boolean, + requestId: PaykitPaymentRequestId?, updateFailed: Boolean, ): Boolean = when (error) { is PaymentPendingException -> false - else if !isPaymentRequest -> true + else if requestId == null -> true // Any failed spending balance update happens before the invoice is paid, so nothing was sent. else if updateFailed || error is LightningPaymentFailedError -> { - paykitPaymentProofRepo.failLightningPayment(paymentHash) + paykitPaymentProofRepo.failLightningPayment(paymentHash, requestId) true } - else -> paykitPaymentProofRepo.failLightningPayment(paymentHash, error) + else -> paykitPaymentProofRepo.failLightningPayment(paymentHash, error, requestId) } private suspend fun prepareContactPayment( diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index aff40d2dd4..bc0673fce4 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -37,11 +37,11 @@ class CacheStoreTest : BaseUnitTest() { @Test fun `a spark send attempt drops expired ones and restores the earlier one`() = test { - sut.setSparkSendAttempt("OLD", attempt = 2, expiresAt = 1_500, now = 1_000) - sut.setSparkSendAttempt("hash", attempt = 0, expiresAt = 3_000, now = 1_000) - sut.setSparkSendAttempt("hash", attempt = 1, expiresAt = 3_000, now = 2_000) + sut.setSparkSendAttempt("OLD", attempt = 2, amountSats = 100uL, expiresAt = 1_500, now = 1_000) + sut.setSparkSendAttempt("hash", attempt = 0, amountSats = 100uL, expiresAt = 3_000, now = 1_000) + sut.setSparkSendAttempt("hash", attempt = 1, amountSats = 100uL, expiresAt = 3_000, now = 2_000) - assertEquals(mapOf("hash" to SparkSendAttempt(1, 3_000)), sut.data.first().sparkSendAttempts) + assertEquals(mapOf("hash" to SparkSendAttempt(1, 3_000, 100uL)), sut.data.first().sparkSendAttempts) sut.dropSparkUnsentSend("HASH", restoresAttempt = true, previous = SparkSendAttempt(0, 3_000)) assertEquals(0, sut.data.first().sparkSendAttempts["hash"]?.attempt) @@ -53,7 +53,7 @@ class CacheStoreTest : BaseUnitTest() { @Test fun `dropping an unsent spark send clears its hold and hash and keeps a reused attempt`() = test { sut.addSparkSendHash("hash", expiresAt = 3_000) - sut.setSparkSendAttempt("hash", attempt = 1, expiresAt = 3_000, now = 1_000) + sut.setSparkSendAttempt("hash", attempt = 1, amountSats = 100uL, expiresAt = 3_000, now = 1_000) sut.addSparkUncertainSend("hash", startedAt = 1_000, attemptId = "id") sut.dropSparkUnsentSend("HASH", restoresAttempt = false, previous = null) @@ -71,7 +71,7 @@ class CacheStoreTest : BaseUnitTest() { val store = FailingDataStore(InMemoryDataStore(AppCacheData())) val cache = CacheStore(store) cache.addSparkSendHash("hash", expiresAt = 3_000) - cache.setSparkSendAttempt("hash", attempt = 1, expiresAt = 3_000, now = 1_000) + cache.setSparkSendAttempt("hash", attempt = 1, amountSats = 100uL, expiresAt = 3_000, now = 1_000) cache.addSparkUncertainSend("hash", startedAt = 1_000, attemptId = "id") val held = cache.data.first() diff --git a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt index 050b8b5bb3..15ac13a291 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitAllowanceExecutorTest.kt @@ -247,7 +247,7 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { whenever(payer.prepareProof(any(), any(), any(), anyOrNull())).thenReturn(Result.success(Unit)) whenever(payer.associateLightningPayment(any(), any(), any(), any())).thenReturn(Result.success(Unit)) whenever(payer.payLightning(any(), anyOrNull(), anyOrNull(), any())).thenReturn(Result.success(PAYMENT_HASH)) - whenever(payer.failLightningPayment(any(), any())).thenReturn(true) + whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true) whenever(payer.lightningPaymentStatus(any())).thenAnswer { nodeStatuses[it.getArgument(0)] } whenever(payer.canListLightningPayments()).thenAnswer { nodeListsPayments } } @@ -1056,12 +1056,13 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { @Test fun `unsaved sending stage releases the payment list and never sends`() = test { failSave = { "SENDING" in it } + val request = fixtures.paymentRequest() - val result = sut.autoPay(fixtures.paymentRequest(), listOf(fixtures.allowance()), identity) + val result = sut.autoPay(request, listOf(fixtures.allowance()), identity) assertEquals(PaykitAllowanceAutoPayResult.MANUAL, result) assertEquals(listOf(PaymentOutcomeReport(AUTOMATIC_ATTEMPT_ID, PaymentOutcome.FAILED)), recordedOutcomes) - verify(payer).discardLightningProof(PAYMENT_HASH) + verify(payer).discardLightningProof(PAYMENT_HASH, request.id) verify(payer).releasePaymentList(any(), any(), any()) verify(payer, never()).payLightning(any(), anyOrNull(), anyOrNull(), any()) } @@ -1071,10 +1072,12 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { whenever( payer.payLightning(any(), anyOrNull(), anyOrNull(), any()) ).thenReturn(Result.failure(TestAllowanceError("send"))) - whenever(payer.failLightningPayment(any(), any())).thenReturn(true, false) + whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true, false) - val first = sut.autoPay(fixtures.paymentRequest(id = "request-1"), listOf(fixtures.allowance()), identity) - val second = sut.autoPay(fixtures.paymentRequest(id = "request-2"), listOf(fixtures.allowance()), identity) + val firstRequest = fixtures.paymentRequest(id = "request-1") + val secondRequest = fixtures.paymentRequest(id = "request-2") + val first = sut.autoPay(firstRequest, listOf(fixtures.allowance()), identity) + val second = sut.autoPay(secondRequest, listOf(fixtures.allowance()), identity) assertEquals(PaykitAllowanceAutoPayResult.MANUAL, first) // An uncertain send stays with the node, whose payment event records the outcome. @@ -1084,6 +1087,8 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { recordedOutcomes.map { it.outcome }, ) assertEquals(Stage.UNKNOWN, sut.localState(identity).journal.single().stage) + verify(payer).failLightningPayment(eq(PAYMENT_HASH), any(), eq(firstRequest.id)) + verify(payer).failLightningPayment(eq(PAYMENT_HASH), any(), eq(secondRequest.id)) } @Test @@ -1092,7 +1097,7 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { whenever( payer.payLightning(any(), anyOrNull(), anyOrNull(), any()) ).thenReturn(Result.failure(TestAllowanceError("send"))) - whenever(payer.failLightningPayment(any(), any())).thenReturn(true) + whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true) // The node's failure event lands during the failed send's release; a repeated release is owner-checked. var isSettling = false @@ -1247,7 +1252,7 @@ class PaykitAllowanceExecutorTest : BaseUnitTest() { sut.lightningPaymentSettled(PAYMENT_HASH, succeeded = false) Result.failure(TestAllowanceError("send")) } - whenever(payer.failLightningPayment(any(), any())).thenReturn(true) + whenever(payer.failLightningPayment(any(), any(), any())).thenReturn(true) sut.autoPay(fixtures.paymentRequest(), listOf(fixtures.allowance()), identity) diff --git a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt index 428c884fbb..efeb2fd6e4 100644 --- a/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PaykitPaymentProofRepoTest.kt @@ -1501,6 +1501,20 @@ class PaykitPaymentProofRepoTest : BaseUnitTest(StandardTestDispatcher()) { } } + @Test + fun `refused submission for one request keeps another request's proof of the same invoice`() = test { + val first = paymentRequest(MethodId.Bolt11.rawValue) + val second = paymentRequest(MethodId.Bolt11.rawValue, paymentRequestId = "second-request") + val repo = paymentProofRepo() + for (request in listOf(first, second)) { + repo.prepare(request, MethodId.Bolt11.rawValue, "bitkit", PaykitPaymentProofKind.Lightning).getOrThrow() + repo.associateLightningPayment(request, PAYMENT_HASH, MethodId.Bolt11.rawValue, "bitkit").getOrThrow() + } + + assertTrue(repo.failLightningPayment(PAYMENT_HASH, SparkError.SendRefused("refused"), second.id)) + assertEquals(listOf(first.id), storedProofs.map { it.requestId }) + } + @Test fun `onchain proof uses selected endpoint and transaction id`() = test { val txid = "ab".repeat(32) diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index fc75c8aa1b..229837f4ea 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -5467,6 +5467,67 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(1, store.data.first().sparkSendAttempts["hash"]?.attempt) } + @Test + fun `a spark retry under the same key at another amount is refused`() = test { + val attempt = SparkSendAttempt(0, now.epochSeconds + 3_600, 50uL) + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendAttempts = mapOf("hash" to attempt))), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, never()).send(any(), anyOrNull()) + assertEquals(50uL, store.data.first().sparkSendAttempts["hash"]?.amountSats) + } + + @Test + fun `a spark retry under the same key is refused when the invoice's amount differs from the kept one`() = test { + val attempt = SparkSendAttempt(0, now.epochSeconds + 3_600, 50uL) + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendAttempts = mapOf("hash" to attempt))), clock) + whenever(sparkService.isConnected).thenReturn(true) + val details = mock { + on { paymentHash } doReturn "hash" + on { timestamp }.thenAnswer { now.epochSeconds } + on { expiry }.thenAnswer { 3_600L } + on { amountMsat } doReturn 100_000uL + } + val prepared = prepared(feeSats = 0uL).copy(paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, 0uL)) + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", null).exceptionOrNull()) + + verify(sparkService, never()).send(any(), anyOrNull()) + } + + @Test + fun `a spark retry at another amount goes out under the next key once spark lists its attempt failed`() = test { + val attempt = SparkSendAttempt(0, now.epochSeconds + 3_600, 50uL) + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendAttempts = mapOf("hash" to attempt))), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sentPayment(fees = 0)) + val failed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + sut.payInvoice("lnbc1", 100uL).getOrThrow() + + assertEquals("hash-1", sentKey()) + assertEquals(100uL, store.data.first().sparkSendAttempts["hash"]?.amountSats) + } + @Test fun `a spark retry takes the next attempt's key once spark lists its attempt failed`() = test { val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) @@ -5754,6 +5815,28 @@ class SparkRepoTest : BaseUnitTest() { assertEquals(1, events.count { it is Event.PaymentSuccessful }) } + @Test + fun `a spark retry of a held send at another amount is refused and keeps the send held`() = test { + whenever(sparkService.isSupported).thenReturn(true) + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenAnswer { info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong()) } + whenever(sparkService.listPayments()).thenReturn(emptyList()) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { throw leafSelectionFailure() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + clearInvocations(sparkService) + + assertIs(sut.payInvoice("lnbc1", 200uL).exceptionOrNull()) + + verify(sparkService, never()).send(any(), anyOrNull()) + assertTrue("hash" in store.data.first().sparkUncertainSends) + assertEquals(100uL, store.data.first().sparkSendAttempts["hash"]?.amountSats) + } + @Test fun `a spark retry of a held send stopped by its deadline keeps the send held`() = test { whenever(sparkService.isSupported).thenReturn(true) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 64bd471763..0b0ecb562f 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -121,6 +121,7 @@ import to.bitkit.data.PrivatePaykitReservationData import to.bitkit.data.PrivatePaykitReservationStore import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore +import to.bitkit.data.SparkSendAttempt import to.bitkit.data.UsdtPreference import to.bitkit.data.WalletConnectionRecovery import to.bitkit.data.dto.PlatformDetails @@ -12176,7 +12177,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals("Already paid", error.failure.message) } verify(lightningRepo, times(1)).payInvoice(any(), anyOrNull(), anyOrNull(), any()) - verify(paykitPaymentProofRepo, never()).failLightningPayment(any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) } @Test @@ -12351,6 +12352,133 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(BitkitActivity.Lightning(earlier))) } + @Test + fun `repaying an amountless invoice still pending with another amount shows the pending amount`() = test { + val bolt11 = "lnbcrt1amountlesspending" + val invoice = lightningInvoice(bolt11, 0u) + val paymentHash = invoice.paymentHash.toHex() + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + val earlier = mock { + on { value } doReturn 1_000u + on { txType } doReturn PaymentType.SENT + on { status } doReturn PaymentState.PENDING + } + whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(BitkitActivity.Lightning(earlier))) + val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) + + sut.sendEffect.test { + setSendState(state.copy(amount = 2_000u)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + val pending = assertIs(expectMostRecentItem()) + assertEquals(1_000L, pending.amount) + } + } + + @Test + fun `repaying an amountless invoice held by spark without activity shows the held amount`() = test { + val bolt11 = "lnbcrt1amountlessheld" + val invoice = lightningInvoice(bolt11, 0u) + val paymentHash = invoice.paymentHash.toHex() + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(null)) + val attempt = SparkSendAttempt(attempt = 0, expiresAt = Long.MAX_VALUE, amountSats = 1_000u) + val cache = AppCacheData( + sparkSendAttempts = mapOf(paymentHash to attempt), + sparkUncertainSends = mapOf(paymentHash to 0L), + ) + whenever(cacheStore.data).thenReturn(flowOf(cache)) + val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) + + sut.sendEffect.test { + setSendState(state.copy(amount = 2_000u)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + val pending = assertIs(expectMostRecentItem()) + assertEquals(1_000L, pending.amount) + } + } + + @Test + fun `repaying an amountless invoice after a failed spark attempt without activity shows the new amount`() = test { + val bolt11 = "lnbcrt1amountlessdropped" + val invoice = lightningInvoice(bolt11, 0u) + val paymentHash = invoice.paymentHash.toHex() + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(null)) + val attempt = SparkSendAttempt(attempt = 1, expiresAt = Long.MAX_VALUE, amountSats = 6_000u) + whenever(cacheStore.data).thenReturn(flowOf(AppCacheData(sparkSendAttempts = mapOf(paymentHash to attempt)))) + val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) + + sut.sendEffect.test { + setSendState(state.copy(amount = 2_000u)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + val pending = assertIs(expectMostRecentItem()) + assertEquals(2_000L, pending.amount) + } + } + + @Test + fun `repaying an amountless invoice held by spark after a failed row shows the held amount`() = test { + val bolt11 = "lnbcrt1amountlessheldfailed" + val invoice = lightningInvoice(bolt11, 0u) + val paymentHash = invoice.paymentHash.toHex() + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + val failed = mock { + on { value } doReturn 5_000u + on { txType } doReturn PaymentType.SENT + on { status } doReturn PaymentState.FAILED + } + whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(BitkitActivity.Lightning(failed))) + val attempt = SparkSendAttempt(attempt = 1, expiresAt = Long.MAX_VALUE, amountSats = 6_000u) + val cache = AppCacheData( + sparkSendAttempts = mapOf(paymentHash to attempt), + sparkUncertainSends = mapOf(paymentHash to 0L), + ) + whenever(cacheStore.data).thenReturn(flowOf(cache)) + val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) + + sut.sendEffect.test { + setSendState(state.copy(amount = 2_000u)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + val pending = assertIs(expectMostRecentItem()) + assertEquals(6_000L, pending.amount) + } + } + + @Test + fun `repaying an amountless invoice whose earlier payment failed shows the new amount as pending`() = test { + val bolt11 = "lnbcrt1amountlessfailed" + val invoice = lightningInvoice(bolt11, 0u) + val paymentHash = invoice.paymentHash.toHex() + whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = 2_000u)) + .thenReturn(Result.failure(PaymentPendingException(paymentHash))) + val earlier = mock { + on { value } doReturn 1_000u + on { txType } doReturn PaymentType.SENT + on { status } doReturn PaymentState.FAILED + } + whenever(activityRepo.getActivity(paymentHash)).thenReturn(Result.success(BitkitActivity.Lightning(earlier))) + val failedAttempt = SparkSendAttempt(attempt = 0, expiresAt = Long.MAX_VALUE, amountSats = 1_000u) + val cache = AppCacheData(sparkSendAttempts = mapOf(paymentHash to failedAttempt)) + whenever(cacheStore.data).thenReturn(flowOf(cache)) + val state = SendUiState(address = bolt11, payMethod = SendMethod.LIGHTNING, decodedInvoice = invoice) + + sut.sendEffect.test { + setSendState(state.copy(amount = 2_000u)) + sut.setSendEvent(SendEvent.PayConfirmed) + advanceUntilIdle() + val pending = assertIs(expectMostRecentItem()) + assertEquals(2_000L, pending.amount) + } + } + @Test fun `a payment shown by its event during the swipe shows its success once`() = test { val bolt11 = "lnbcrt1eventfirst" @@ -16411,13 +16539,13 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) if (preparationSucceeds) { verify(paykitPaymentRequestRepo).accept(request) - verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash, request.id) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) } else { verify(paykitPaymentRequestRepo, never()).accept(request) verify(privatePaykitRepo, never()).consumePrivatePaymentList(any(), any()) verify(paykitPaymentProofRepo, never()).associateLightningPayment(any(), any(), any(), eq("bitkit")) - verify(paykitPaymentProofRepo, never()).failLightningPayment(any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) } clearInvocations(lightningRepo, paykitPaymentProofRepo, paykitPaymentRequestRepo, privatePaykitRepo) } @@ -16476,7 +16604,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { ) verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) } - verify(paykitPaymentProofRepo, never()).failLightningPayment(any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) verify(paykitPaymentProofRepo, never()).cancelPreparation(any()) verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) } @@ -16508,7 +16636,8 @@ class AppViewModelSendFlowTest : BaseUnitTest() { .thenReturn(Result.success(Unit)) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) .thenReturn(Result.failure(error)) - whenever(paykitPaymentProofRepo.failLightningPayment(invoicePaymentHash, error)).thenReturn(true) + whenever(paykitPaymentProofRepo.failLightningPayment(eq(invoicePaymentHash), eq(error), eq(request.id))) + .thenReturn(true) setActiveContactPaymentContext(testPublicKey, privateContext, request) setSendState( SendUiState( @@ -16535,7 +16664,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { "bitkit", ) verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) - verify(paykitPaymentProofRepo).failLightningPayment(invoicePaymentHash, error) + verify(paykitPaymentProofRepo).failLightningPayment(invoicePaymentHash, error, request.id) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(paykitPaymentProofRepo).cancelPreparation(request) } @@ -16636,7 +16765,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever(privatePaykitRepo.consumePrivatePaymentList(testPublicKey, privateContext)) .thenReturn(Result.success(Unit)) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)).thenReturn(Result.failure(error)) - whenever(paykitPaymentProofRepo.failLightningPayment(paymentHash, error)).thenReturn(false) + whenever(paykitPaymentProofRepo.failLightningPayment(eq(paymentHash), eq(error), anyOrNull())).thenReturn(false) setActiveContactPaymentContext(testPublicKey, privateContext, request) setSendState( SendUiState( @@ -16654,7 +16783,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertEquals(SendEffect.NavigateToPending(paymentHash, request.amount.atomic.toLong()), awaitItem()) } verify(pendingPaymentRepo).track(paymentHash) - verify(paykitPaymentProofRepo, never()).failLightningPayment(any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) verify(paykitPaymentProofRepo, never()).cancelPreparation(any()) verify(privatePaykitRepo, never()).releasePrivatePaymentList(any(), any()) } @@ -18902,7 +19031,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.setSendEvent(SendEvent.PayConfirmed) advanceUntilIdle() - verify(paykitPaymentProofRepo).failLightningPayment("010203") + verify(paykitPaymentProofRepo).failLightningPayment("010203", request.id) verify(paykitPaymentProofRepo).cancelPreparation(request) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) @@ -20039,7 +20168,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { balanceState.value = BalanceState(maxSendLightningSats = 100_000u) whenever(lightningRepo.payInvoice(bolt11 = bolt11, sats = null)) .thenReturn(Result.failure(NodeException.PaymentSendingFailed("no route"))) - whenever(paykitPaymentProofRepo.failLightningPayment(any())).doSuspendableAnswer { + whenever( + paykitPaymentProofRepo.failLightningPayment(any(), anyOrNull()) + ).doSuspendableAnswer { cleanup.await() Result.success(Unit) } @@ -20056,7 +20187,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { sut.setSendEvent(SendEvent.PayConfirmed) advanceUntilIdle() assertTrue(awaitItem() is SendEffect.NavigateToError) - verify(paykitPaymentProofRepo, never()).failLightningPayment(any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(any(), anyOrNull()) verify(lightningRepo).payInvoice(bolt11 = bolt11, sats = null) } } finally { @@ -23294,7 +23425,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(awaitItem() is SendEffect.NavigateToError) } verify(pendingPaymentRepo, never()).track(any()) - verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash, request.id) verify(paykitPaymentProofRepo).cancelPreparation(request) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) @@ -23396,7 +23527,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { val error = NodeException.InsufficientFunds("refused") whenever(moveToSparkRepo.updateToSend(any(), any(), eq(request.amount.atomic), any())) .thenReturn(Result.failure(error)) - whenever(paykitPaymentProofRepo.failLightningPayment(paymentHash, error)).thenReturn(false) + whenever(paykitPaymentProofRepo.failLightningPayment(eq(paymentHash), eq(error), anyOrNull())).thenReturn(false) setActiveContactPaymentContext(testPublicKey, privateContext, request) setSendState( SendUiState( @@ -23416,9 +23547,9 @@ class AppViewModelSendFlowTest : BaseUnitTest() { assertTrue(awaitItem() is SendEffect.NavigateToError) } verify(pendingPaymentRepo, never()).track(any()) - verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash, request.id) verify(paykitPaymentProofRepo).cancelPreparation(request) - verify(paykitPaymentProofRepo, never()).failLightningPayment(eq(paymentHash), any()) + verify(paykitPaymentProofRepo, never()).failLightningPayment(eq(paymentHash), any(), anyOrNull()) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) verify(paykitAllowanceRepo).finishManualPayment("node-error-attempt", false, null) @@ -23561,7 +23692,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(moveToSparkRepo, never()).updateToSend(any(), any(), any(), any()) verify(closeChannelUseCase, never()).closeEmptiedByMove(any(), anyOrNull()) verify(pendingPaymentRepo, never()).track(any()) - verify(paykitPaymentProofRepo).failLightningPayment(paymentHash) + verify(paykitPaymentProofRepo).failLightningPayment(paymentHash, request.id) verify(paykitPaymentProofRepo).cancelPreparation(request) verify(privatePaykitRepo).releasePrivatePaymentList(testPublicKey, privateContext) verify(lightningRepo, never()).payInvoice(any(), anyOrNull()) diff --git a/changelog.d/next/2071.fixed.md b/changelog.d/next/2071.fixed.md new file mode 100644 index 0000000000..e8638d5a4f --- /dev/null +++ b/changelog.d/next/2071.fixed.md @@ -0,0 +1 @@ +A repeat of an invoice at another amount than its earlier Spark payment is refused, and a repeat of a pending payment shows the amount that payment sends.