Skip to content
15 changes: 9 additions & 6 deletions app/src/main/java/to/bitkit/data/CacheStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
}
}

Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,14 @@ class PaykitAllowancePayer @Inject constructor(
): Result<String> = 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)

Expand Down Expand Up @@ -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
}
Expand All @@ -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
}
Expand Down
19 changes: 15 additions & 4 deletions app/src/main/java/to/bitkit/repositories/PaykitPaymentProofRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
14 changes: 14 additions & 0 deletions app/src/main/java/to/bitkit/repositories/SparkRepo.kt
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -673,6 +678,7 @@ class SparkRepo @Inject constructor(
cacheStore.setSparkSendAttempt(
paymentHash,
attempt,
sendSats,
expiresAt.toEpochSeconds(),
clock.now().epochSeconds,
)
Expand Down Expand Up @@ -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")
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}

private fun ensurePaymentDeadline(paymentDeadlineAt: Instant?) {
if (paymentDeadlineAt != null && clock.now() > paymentDeadlineAt) throw ServiceError.PaymentDeadlineExpired()
}
Expand Down
25 changes: 18 additions & 7 deletions app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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?)

/**
Expand Down Expand Up @@ -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(
Expand Down
12 changes: 6 additions & 6 deletions app/src/test/java/to/bitkit/data/CacheStoreTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>(0)] }
whenever(payer.canListLightningPayments()).thenAnswer { nodeListsPayments }
}
Expand Down Expand Up @@ -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())
}
Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading