diff --git a/app/src/main/java/to/bitkit/data/CacheStore.kt b/app/src/main/java/to/bitkit/data/CacheStore.kt index 296fc3798f..6fe9a1aded 100644 --- a/app/src/main/java/to/bitkit/data/CacheStore.kt +++ b/app/src/main/java/to/bitkit/data/CacheStore.kt @@ -200,6 +200,27 @@ 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. + */ + suspend fun setSparkSendAttempt(paymentHash: String, attempt: Int, 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))) + } + } + + /** Puts back [previous], the attempt kept before a send whose key never reached Spark, or drops the invoice's. */ + suspend fun restoreSparkSendAttempt(paymentHash: String, previous: SparkSendAttempt?) { + val hash = paymentHash.lowercase() + store.updateData { + val attempts = it.sparkSendAttempts - hash + it.copy(sparkSendAttempts = if (previous == null) attempts else attempts + (hash to previous)) + } + } + suspend fun addSparkUnsavedOwnFailure(paymentId: String) { if (paymentId in store.data.first().sparkUnsavedOwnFailures) return store.updateData { it.copy(sparkUnsavedOwnFailures = it.sparkUnsavedOwnFailures + paymentId) } @@ -413,6 +434,8 @@ data class AppCacheData( * only its own outcome settles it. A hold without one waits for a paid attempt or its invoice's expiry. */ val sparkSendAttemptIds: Map = mapOf(), + /** The latest attempt at each invoice Spark sent, by hash, whose number picks the attempt's idempotency key. */ + val sparkSendAttempts: Map = mapOf(), /** * Payment ids of Spark send attempts whose own failure a failed Activity write still has to save over an earlier * attempt's row, kept across a restart until it saves. @@ -463,6 +486,10 @@ 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]. */ +@Serializable +data class SparkSendAttempt(val attempt: Int, val expiresAt: Long) + @Serializable data class CachedUsdtBalance( val address: String, diff --git a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt index 14acac1874..d65a80d3ec 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -42,6 +42,7 @@ import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import to.bitkit.R import to.bitkit.async.appScope +import to.bitkit.data.AppCacheData import to.bitkit.data.AppDb import to.bitkit.data.CacheStore import to.bitkit.data.HwWalletStore @@ -1336,14 +1337,7 @@ class BackupRepo @Inject constructor( } runCatching { restoreSparkExitEarlierAddresses(parsed.sparkExitEarlierAddresses) } .onFailure { Logger.warn("Failed to restore the earlier Spark exit addresses", it, context = TAG) } - // Payment history and Spark attempt ids stay out of the log, as support requests attach it. - val logged = parsed.cache.copy( - cachedRates = emptyList(), - moveToSparkHashes = emptyList(), - sparkSendAttemptIds = emptyMap(), - sparkUnsavedOwnFailures = emptySet(), - ) - Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) + Logger.debug("Restored caches: ${jsonLogOf(parsed.cache.withoutPaymentDetails())}", TAG) onCacheRestored() val persisted = preActivityMetadataRepo.upsertPreActivityMetadata(parsed.tagMetadata) .onFailure { Logger.warn("Failed to restore pre-activity metadata", it, context = TAG) } @@ -1720,3 +1714,35 @@ internal fun Throwable.isTemporaryBackupFailure(): Boolean = isPaykitTemporarily -> true else -> false } + +/** + * The cache as the restore log shows it: without the addresses, invoices, payment hashes, payment and activity ids, + * transaction ids and comments that identify a payment, as support requests attach the log. + */ +internal fun AppCacheData.withoutPaymentDetails() = copy( + cachedRates = emptyList(), + onchainAddress = "", + bolt11 = "", + bolt11PaymentHash = "", + bip21 = "", + usdtDisplayBalance = null, + deletedActivities = emptyList(), + detachedActivityContacts = emptySet(), + pendingBoostActivities = emptyList(), + backgroundReceive = null, + quickPayLedger = quickPayLedger?.copy(records = emptyList()), + pendingLightningMessages = emptyMap(), + pendingSparkWithdrawal = null, + sentSparkWithdrawals = emptyList(), + unfinishedPubkySwaps = emptyList(), + pubkySwapHoldHashes = emptyMap(), + sparkSendHashes = emptyList(), + sparkSendExpiries = emptyMap(), + sparkUncertainSends = emptyMap(), + sparkSendAttemptIds = emptyMap(), + sparkSendAttempts = emptyMap(), + sparkUnsavedOwnFailures = emptySet(), + moveToSparkHashes = emptyList(), + ldkSendHashes = emptyList(), + ldkSendExpiries = emptyMap(), +) diff --git a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt index 7c7a9f88d5..fccd22e2d6 100644 --- a/app/src/main/java/to/bitkit/repositories/LightningRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/LightningRepo.kt @@ -1630,7 +1630,12 @@ class LightningRepo @Inject constructor( var isAdmitted = false var isRefused = false var railBefore: LightningRail? = null - val authorizeSend: suspend () -> Boolean = { + var isChecked = false + val authorizeSend: suspend () -> Boolean = authorize@{ + // Spark's retry of a send whose leaves it couldn't select keeps the send's admission and rechecks only + // the caller's check at submission, which has no side effects. + if (isChecked) return@authorize isAuthorizedAtSubmission?.invoke() ?: true + isChecked = true val isAuthorized = onBeforeSend().also { if (it) requireWalletRestoreComplete() } if (isAuthorized) { isAdmitted = admitSend(key, LightningRail.Spark) { diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 2bbeb986b4..5e2cb5ba80 100644 --- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt @@ -132,6 +132,11 @@ class SparkRepo @Inject constructor( private val SETTLE_RETRY_INTERVAL = 30.seconds + /** Sends again under the same key while Spark can't select the leaves, as after a move to Spark lands. */ + private const val LEAF_SELECTION_RETRIES = 3 + + private val LEAF_SELECTION_RETRY_DELAY = 2.seconds + /** Seconds a withdrawal quote must still hold to be reused, so it can't expire mid-send. */ private const val QUOTE_EXPIRY_MARGIN_SECS = 30uL } @@ -530,7 +535,8 @@ class SparkRepo @Inject constructor( /** * Pays [bolt11] and returns its payment hash, the id ldk-node payments use, so the send flow can match it. * Fails with [SparkError.SendRefused] when nothing left the wallet: Spark was not connected, could not prepare the - * payment or list its payments, or its fee was over [maxTotalFeeMsat]; with [SparkError.InvoiceExpired], a + * payment, could not list its payments while an older build's send of the invoice is kept, or its fee was over + * [maxTotalFeeMsat]; with [SparkError.InvoiceExpired], a * [SparkError.SendRefused], when Spark refuses an expired invoice at prepare or send; and with * [ServiceError.PaymentDeadlineExpired] past [paymentDeadlineAt]. A failure inside the send is a * [PaymentPendingException], as the payment may have been @@ -575,8 +581,10 @@ class SparkRepo @Inject constructor( Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) return@runSuspendCatching paymentHash } + // A send held in doubt under this build's key is sent again under that key, which can't pay twice: + // the operators return the transfer it committed, if any. is SparkLightningSend.Found if earlier.status == PaymentStatus.PENDING -> - throw PaymentPendingException(paymentHash) + if (!isKeyedHold(paymentHash)) throw PaymentPendingException(paymentHash) // Spark's list, synced or unreadable, can lack a send it made before the restore, as on the node's // path, so the operators decide. Before Spark syncs, its list can lack an earlier attempt they show // failed, so that one is refused too. @@ -587,19 +595,16 @@ class SparkRepo @Inject constructor( isFailedUnsent = canList, ) } - // A list that can't be read may hide a payment of the invoice, which Spark would pay again under a new - // key. It is read again here: the local one before Spark's first sync, else the synced one. - if (earlier == SparkLightningSend.Unavailable) { - val local = runSuspendCatching { listPayments() }.getOrNull() - ?: throw SparkError.SendRefused("Spark could not list its payments to check the invoice") - when (local.latestSend(paymentHash)?.status) { - PaymentStatus.COMPLETED -> { - Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) - return@runSuspendCatching paymentHash - } - PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) - else -> Unit - } + // Spark's local list picks the attempt's key and, before Spark's first sync, shows the invoice's earlier + // sends, as the synced list did above. + val local = runSuspendCatching { listPayments() }.getOrNull() + // Past the checks above, a pending send is a held one this build's key retries, whose outcome Spark's local + // list may already show. + val isKeyedRetry = earlier is SparkLightningSend.Found && earlier.status == PaymentStatus.PENDING + val readsLocally = earlier == SparkLightningSend.Unavailable || isKeyedRetry + if (readsLocally && isPaidLocally(paymentHash, local, isKeyedRetry)) { + Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) + return@runSuspendCatching paymentHash } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() @@ -609,11 +614,39 @@ class SparkRepo @Inject constructor( if (!isEntered) throw PaymentPendingException(paymentHash) // Kept in flight until its result is handled, so a sync meanwhile never takes back its saved hold. try { - // Spark keeps the key as this attempt's payment id, so only its own outcome settles the send. - val attemptId = UUID.randomUUID().toString() + // Spark keeps the key as this attempt's payment id, so only its own outcome settles the send. A retry + // keeps the latest attempt's key, so Spark returns that attempt's payment instead of paying again, and + // moves past each attempt Spark's list shows failed, as a failed key can't send again. + // The key's secret comes with Spark's connection, so a send that lost it is refused before it goes. + val (attempt, attemptId) = runSuspendCatching { + nextSendAttempt(paymentHash, local).let { it to sparkService.sendKey(paymentHash, it) } + }.getOrElse { throw SparkError.SendRefused("Spark is not connected", it) } + val previousAttempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()] + val isReusedKey = previousAttempt?.attempt == attempt + val wasHeld = sendHold(paymentHash.lowercase()) != null + // 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) + + // 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 + // transfer. Under a new key every earlier attempt failed, so a hold one of them left ends too. + suspend fun dropUnsentSend() { + if (isReusedKey && wasHeld) return + uncertainSends.remove(paymentHash.lowercase()) + cacheStore.removeSparkUncertainSend(paymentHash) + cacheStore.removeSparkSendHash(paymentHash) + if (!isReusedKey) cacheStore.restoreSparkSendAttempt(paymentHash, previousAttempt) + } val sent = run { sendRecordedAt[paymentHash.lowercase()] = sendRecords.incrementAndGet() cacheStore.addSparkSendHash(paymentHash, expiresAt.toEpochSeconds()) + cacheStore.setSparkSendAttempt( + paymentHash, + attempt, + expiresAt.toEpochSeconds(), + clock.now().epochSeconds, + ) spending { // Kept until the call returns, so a send cut off by process death or cancellation stays held. cacheStore.addSparkUncertainSend(paymentHash, clock.now().epochSeconds, attemptId) @@ -623,27 +656,30 @@ class SparkRepo @Inject constructor( ensurePaymentDeadline(paymentDeadlineAt) ensureNotExiting() }.onFailure { - cacheStore.removeSparkUncertainSend(paymentHash) - cacheStore.removeSparkSendHash(paymentHash) + dropUnsentSend() throw it } - runSuspendCatching { sparkService.send(prepared, attemptId) } + sendRetryingLeafSelection(prepared, attemptId, paymentDeadlineAt, onBeforeSend) } } val payment = sent.getOrElse { // The SDK checks the expiry again before anything goes out, so an expired invoice left nothing. - if (it.isInvoiceExpired()) { - cacheStore.removeSparkUncertainSend(paymentHash) - cacheStore.removeSparkSendHash(paymentHash) + // Under a key an earlier attempt used, that attempt may have committed a transfer before the + // expiry, so the send stays held. + if (it.isInvoiceExpired() && !isReusedKey) { + dropUnsentSend() throw SparkError.InvoiceExpired(it) } // Spark selects the leaves to spend before anything goes to the operators, so a short balance left - // nothing, for instance when an earlier send spent it after the balance was read. - if (it is SdkException.InsufficientFunds) { - cacheStore.removeSparkUncertainSend(paymentHash) - cacheStore.removeSparkSendHash(paymentHash) + // nothing, for instance when an earlier send spent it after the balance was read. Under a key an + // earlier attempt used, it can hide the transfer that attempt committed, so that send stays held. + if (it is SdkException.InsufficientFunds && !isReusedKey) { + dropUnsentSend() throw SparkError.SendRefused("Spark balance can't cover the payment", it) } + // Leaves Spark still can't select after its retries can follow a transfer it committed, as the SDK + // selects them again after an operator error, so that send stays held until Spark settles it or its + // invoice expires, as any other unknown outcome does. Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) settleUncertainSend(paymentHash, expiresAt, attemptId) throw PaymentPendingException(paymentHash) @@ -653,12 +689,7 @@ class SparkRepo @Inject constructor( if (payment.status == PaymentStatus.PENDING) { settleUncertainSend(paymentHash, expiresAt, attemptId) } else { - cacheStore.removeSparkUncertainSend(paymentHash) - } - // Spark's failure event during its send call was left to this result, so the result reports it. - if (payment.status == PaymentStatus.FAILED) { - recordActivity(payment, isOwnAttempt = true) - if (reportedSendIds.add(payment.id)) payment.toNodeEvent()?.let { _nodeEvents.emit(it) } + settleSentResult(paymentHash, payment, wasHeld) } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash @@ -676,22 +707,126 @@ class SparkRepo @Inject constructor( } } + /** + * Whether Spark's [local] list shows the send of [paymentHash] paid; throws while it shows the send pending, or, + * unless it is a [isKeyedRetry], while the list can't be read and an older build sent the invoice. + */ + private suspend fun isPaidLocally(paymentHash: String, local: List?, isKeyedRetry: Boolean): Boolean { + when (local?.latestSend(paymentHash)?.status) { + PaymentStatus.COMPLETED -> return true + PaymentStatus.PENDING -> throw PaymentPendingException(paymentHash) + else -> Unit + } + // A retry reuses its attempt's key, so Spark never pays an invoice twice under it, but an older build sent + // under a random key, which a list that can't be read may hide. + if (!isKeyedRetry && local == null && hasUnkeyedSend(paymentHash)) { + throw SparkError.SendRefused("Spark could not list its payments to check the invoice") + } + return false + } + + /** + * Ends the hold of a send whose call returned its settled [payment]: a retry of a send held in doubt settles that + * hold with its own result, which callers waiting on the held send learn from its event, as Spark may not report a + * transfer it returned for the key again. A failed one is refused. + */ + private suspend fun settleSentResult(paymentHash: String, payment: Payment, wasHeld: Boolean) { + uncertainSends.remove(paymentHash.lowercase()) + bestEffort("end the hold of Spark send '$paymentHash'") { + cacheStore.removeSparkUncertainSend(paymentHash) + } + if (wasHeld && reportedSendIds.add(payment.id)) { + recordActivity(payment, isOwnAttempt = true) + payment.toNodeEvent()?.let { _nodeEvents.emit(it) } + } + // Spark's failure event during its send call was left to this result, so the result reports it. + if (payment.status == PaymentStatus.FAILED) { + // This attempt paid nothing, as when its outcome settles, so a retry isn't held as pending. + bestEffort("drop the hash of Spark send '$paymentHash'") { + cacheStore.removeSparkSendHash(paymentHash) + } + if (!wasHeld) recordActivity(payment, isOwnAttempt = true) + // The caller subscribes to events only once this returns, so the result reports the failure, once: + // marked reported, Spark's event for it is not reported again, as a second error would be. + reportedSendIds.add(payment.id) + throw SparkError.SendRefused("Spark send failed") + } + } + + private suspend fun sendRetryingLeafSelection( + prepared: PrepareSendPaymentResponse, + attemptId: String, + paymentDeadlineAt: Instant?, + onBeforeSend: suspend () -> Boolean, + ): Result { + var result = runSuspendCatching { sparkService.send(prepared, attemptId) } + val canRetry = { + runCatching { + ensurePaymentDeadline(paymentDeadlineAt) + ensureNotExiting() + }.isSuccess + } + repeat(LEAF_SELECTION_RETRIES) { + if (result.exceptionOrNull()?.isLeafSelectionFailure() != true || !canRetry()) return result + Logger.info("Retrying Spark send '$attemptId' as Spark could not select its leaves", context = TAG) + delay(LEAF_SELECTION_RETRY_DELAY) + // A cancel, block or identity change can land during the delay, so each resend is checked again. + if (!canRetry() || !onBeforeSend()) return result + val retried = runSuspendCatching { sparkService.send(prepared, attemptId) } + // A failed try can have committed a transfer before Spark selected leaves again, so a short balance or an + // expiry on a retry, which would read as nothing sent, ends with the earlier leaf failure instead. + val error = retried.exceptionOrNull() + if (error is SdkException.InsufficientFunds || error?.isInvoiceExpired() == true) return result + result = retried + } + return result + } + + /** Logs a failed cache write on a send's settlement path, so a storage error never changes the send's outcome. */ + private suspend fun bestEffort(what: String, write: suspend () -> Unit) { + runSuspendCatching { write() }.onFailure { Logger.warn("Failed to $what", it, context = TAG) } + } + + private suspend fun nextSendAttempt(paymentHash: String, listing: List?): Int { + var attempt = cacheStore.data.first().sparkSendAttempts[paymentHash.lowercase()]?.attempt ?: 0 + val failed = listing?.filter { it.status == PaymentStatus.FAILED }?.mapTo(HashSet()) { it.id } + ?: return attempt + while (sparkService.sendKey(paymentHash, attempt) in failed) attempt++ + return attempt + } + + private suspend fun hasUnkeyedSend(paymentHash: String): Boolean { + val hash = paymentHash.lowercase() + val cache = cacheStore.data.first() + if (hash in cache.sparkSendAttempts) return false + return hash in cache.sparkSendHashes || hash in cache.sparkUncertainSends + } + private suspend fun settleUncertainSend(paymentHash: String, expiresAt: ULong, attemptId: String) { val failedAt = clock.now().epochSeconds - val startedAt = cacheStore.data.first().sparkUncertainSends[paymentHash.lowercase()] ?: failedAt - uncertainSends[paymentHash.lowercase()] = UncertainSend(attemptId, failedAt.toULong(), expiresAt) - cacheStore.addSparkUncertainSend(paymentHash, startedAt, attemptId) + val startedAt = runSuspendCatching { cacheStore.data.first().sparkUncertainSends[paymentHash.lowercase()] } + .onFailure { Logger.warn("Failed to read the hold of Spark send '$paymentHash'", it, context = TAG) } + .getOrNull() ?: failedAt + val hold = UncertainSend(attemptId, failedAt.toULong(), expiresAt) + uncertainSends[paymentHash.lowercase()] = hold + // Its caller now waits on the hold, so its outcome is reported, also when an earlier send under the key was. + reportedSendIds.remove(attemptId) + // Held in memory meanwhile, and the hash kept before the send still holds the invoice after a restart. + bestEffort("keep the hold of Spark send '$paymentHash'") { + cacheStore.addSparkUncertainSend(paymentHash, startedAt, attemptId) + } scope.launch { // The send screen tracks the hash as pending only once the send returns, and resolves tracked ones. withTimeoutOrNull(PENDING_TRACK_WAIT) { pendingPaymentRepo.state.first { paymentHash in it.pendingPayments } } repeat(SETTLE_ATTEMPTS) { - // A send its own payment event settled meanwhile needs no sync. - if (!uncertainSends.containsKey(paymentHash.lowercase())) return@launch + // A send its own payment event settled meanwhile needs no sync, and a later hold of it polls on + // its own. + if (uncertainSends[paymentHash.lowercase()] !== hold) return@launch runSuspendCatching { sparkService.syncWallet() } .onFailure { Logger.warn("Failed to sync Spark after send '$paymentHash'", it, context = TAG) } - if (trySettleUncertainSend(paymentHash)) return@launch + if (trySettleUncertainSend(paymentHash, held = hold)) return@launch delay(SETTLE_RETRY_INTERVAL) } // Spark's next sync settles it, as a send it resumes then ends with its own payment event. @@ -733,7 +868,8 @@ class SparkRepo @Inject constructor( if (!isSettled) return false // A send Spark settled while the app was closed updates its row only, as nobody waits for it now. Its marker // stays until its payment is claimed, so Spark's event for it meanwhile claims it too. - val isReported = takeUncertainSend(paymentHash, uncertain, send) ?: return true + // A hold left to a retry in flight under its key stays polled, as the retry may leave it held. + val isReported = takeUncertainSend(paymentHash, uncertain, send) ?: return uncertainSends[key] !== uncertain when (send) { // A send Spark never recorded settles only at its expiry, so it is reported, as a caller may wait for it. SparkLightningSend.NotFound -> { @@ -807,9 +943,13 @@ class SparkRepo @Inject constructor( // invoice again clears its marker under the same lock, so it either sees the hold and gets its report, or // finds it settled. return holdRestoreMutex.withLock { + // A retry in flight under the send's key settles the hold with its own outcome. + if (sendsInFlight.containsKey(key)) return@withLock null if (!uncertainSends.remove(key, uncertain)) return@withLock null - cacheStore.removeSparkUncertainSend(paymentHash) - if (isFailed && !sendsInFlight.containsKey(key)) cacheStore.removeSparkSendHash(paymentHash) + bestEffort("end the hold of Spark send '$paymentHash'") { cacheStore.removeSparkUncertainSend(paymentHash) } + if (isFailed) { + bestEffort("drop the hash of Spark send '$paymentHash'") { cacheStore.removeSparkSendHash(paymentHash) } + } key !in restoredAtStart } } @@ -1688,6 +1828,15 @@ class SparkRepo @Inject constructor( if (isHeld) SparkLightningSend.Found(PaymentStatus.PENDING, null) else send } + /** Whether [paymentHash] is pending only by a hold on a send under this build's key, which a retry can reuse. */ + private suspend fun isKeyedHold(paymentHash: String): Boolean { + val hash = paymentHash.lowercase() + if (sendsInFlight.containsKey(hash) || sendHold(hash) == null) return false + if (hash !in cacheStore.data.first().sparkSendAttempts) return false + val listed = listedLightningSend(paymentHash) + return listed !is SparkLightningSend.Found || listed.status != PaymentStatus.PENDING + } + /** The hold on the send of [hash] whose outcome Spark didn't report, null when none. */ private suspend fun sendHold(hash: String): SendHold? { uncertainSends[hash]?.let { return SendHold(it.attemptId) } @@ -2131,8 +2280,10 @@ class SparkRepo @Inject constructor( if (isFailed && isHeldFrom(payment)) return@withLock true uncertainSends.remove(hash.lowercase()) if (restoredAtStart.remove(hash.lowercase())) reportedSendIds.add(payment.id) - cacheStore.removeSparkUncertainSend(hash) - if (isReleased) cacheStore.removeSparkSendHash(hash) + bestEffort("end the hold of Spark send '$hash'") { cacheStore.removeSparkUncertainSend(hash) } + if (isReleased) { + bestEffort("drop the hash of Spark send '$hash'") { cacheStore.removeSparkSendHash(hash) } + } false } } ?: false @@ -2655,6 +2806,14 @@ internal fun SdkException.InvalidInput.isBelowMinimum(): Boolean = internal fun Throwable.isWithdrawalFeeRise(): Boolean = this is SdkException.InvalidInput && v1.contains("onchain fee rose to", ignoreCase = true) +/** + * Spark fails a send with this error when it holds the balance but can't select leaves to spend, for instance right + * after a move to Spark lands (`select_leaves_with_retry` in the 0.28.3 SDK's `spark-wallet/src/wallet.rs`). The SDK + * selects leaves again after an operator error, so the error can follow a transfer the send committed. + */ +internal fun Throwable.isLeafSelectionFailure(): Boolean = + this is SdkException.SparkException && v1.contains("Failed to select leaves after all retries", ignoreCase = true) + /** Spark refuses an expired Lightning invoice with this input error, at prepare and again at send. */ internal fun Throwable.isInvoiceExpired(): Boolean = this is SdkException.InvalidInput && v1.contains("invoice has expired", ignoreCase = true) diff --git a/app/src/main/java/to/bitkit/services/SparkSendKey.kt b/app/src/main/java/to/bitkit/services/SparkSendKey.kt new file mode 100644 index 0000000000..bd9911cbe5 --- /dev/null +++ b/app/src/main/java/to/bitkit/services/SparkSendKey.kt @@ -0,0 +1,52 @@ +package to.bitkit.services + +import to.bitkit.ext.fromHex +import java.nio.ByteBuffer +import java.security.MessageDigest +import java.util.UUID +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +/** + * The idempotency key of a Spark send of an invoice. Spark makes one transfer per key, so a retry under the same key + * never pays the invoice twice: it gets back the transfer an earlier try committed, or sends when none did. A key + * whose payment failed can't send again, so the next attempt takes the next key. + * + * Keys derive from the wallet seed, the payment hash and the attempt number, so a restored wallet derives the same + * keys, no other wallet can, and the operators can't link a transfer to its invoice. iOS derives the same keys. + */ +object SparkSendKey { + private val NAMESPACE = UUID.fromString("794acd96-39bc-4fd1-a09f-02b269a4a34d") + private val LABEL = "bitkit spark send key".encodeToByteArray() + private const val HMAC = "HmacSHA256" + private const val UUID_BYTES = 16 + + /** The secret all send keys derive from: an HMAC-SHA256 of a fixed label, keyed with the BIP39 [seed]. */ + fun secret(seed: ByteArray): ByteArray = Mac.getInstance(HMAC).run { + init(SecretKeySpec(seed, HMAC)) + doFinal(LABEL) + } + + /** + * The key of attempt [attempt] at paying the invoice with [paymentHash]: a UUIDv5 of [secret], the hash's 32 bytes + * and [attempt] as 4 bytes big-endian. + */ + fun key(secret: ByteArray, paymentHash: String, attempt: Int): String { + require(attempt >= 0) { "Attempt '$attempt' is negative" } + val name = secret + paymentHash.fromHex() + ByteBuffer.allocate(Int.SIZE_BYTES) + .putInt(attempt) + .array() + val namespace = ByteBuffer.allocate(UUID_BYTES) + .putLong(NAMESPACE.mostSignificantBits) + .putLong(NAMESPACE.leastSignificantBits) + .array() + val hash = MessageDigest.getInstance("SHA-1").run { + update(namespace) + digest(name) + } + hash[6] = (hash[6].toInt() and 0x0f or 0x50).toByte() + hash[8] = (hash[8].toInt() and 0x3f or 0x80).toByte() + val bytes = ByteBuffer.wrap(hash, 0, UUID_BYTES) + return UUID(bytes.long, bytes.long).toString() + } +} diff --git a/app/src/main/java/to/bitkit/services/SparkService.kt b/app/src/main/java/to/bitkit/services/SparkService.kt index 0ac2092c48..21564fa141 100644 --- a/app/src/main/java/to/bitkit/services/SparkService.kt +++ b/app/src/main/java/to/bitkit/services/SparkService.kt @@ -44,6 +44,7 @@ import breez_sdk_spark.SendPaymentRequest import breez_sdk_spark.SyncWalletRequest import breez_sdk_spark.defaultConfig import breez_sdk_spark.parseSparkConfig +import com.synonym.bitkitcore.mnemonicToSeed import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow @@ -153,9 +154,15 @@ class SparkService @Inject constructor( } private val mutex = Mutex() + + @Volatile private var sdk: BreezSdk? = null private var listenerId: String? = null + /** The connected wallet's [SparkSendKey.secret], derived once at connect. */ + @Volatile + private var sendKeySecret: ByteArray? = null + private val _events = MutableSharedFlow(extraBufferCapacity = 64) val events: SharedFlow = _events.asSharedFlow() @@ -190,6 +197,7 @@ class SparkService @Inject constructor( val network = sparkNetwork() ?: throw SparkError.Unsupported() val mnemonic = keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name) ?: throw ServiceError.MnemonicNotFound() val passphrase = keychain.loadString(Keychain.Key.BIP39_PASSPHRASE.name) + val secret = SparkSendKey.secret(mnemonicToSeed(mnemonic, passphrase)) val config = configure(defaultConfig(network), Env.breezApiKey, isExiting) val storageDir = File(Env.sparkStoragePath(walletIndex)).apply { mkdirs() }.path val apiType = configureLocalSpark(config, Env.localSparkSettings) @@ -208,6 +216,8 @@ class SparkService @Inject constructor( } }, ) + // The secret comes first, so a send that sees the wallet connected can derive its key. + sendKeySecret = secret sdk = connected val chain = chainServiceUrl ?: "default" Logger.info("Connected Spark wallet on '$network' with chain '$chain' and exit '$isExiting'", context = TAG) @@ -223,6 +233,7 @@ class SparkService @Inject constructor( } finally { sdk = null listenerId = null + sendKeySecret = null } } @@ -278,6 +289,12 @@ class SparkService @Inject constructor( ), ) + /** The idempotency key of attempt [attempt] at paying the invoice with [paymentHash], see [SparkSendKey]. */ + fun sendKey(paymentHash: String, attempt: Int): String { + val secret = checkNotNull(sendKeySecret) { "Spark is not connected" } + return SparkSendKey.key(secret, paymentHash, attempt) + } + /** Sends [prepared]; Spark makes one payment per [idempotencyKey], a UUID that becomes the payment's id. */ suspend fun send(prepared: PrepareSendPaymentResponse, idempotencyKey: String? = null): Payment { val options = when (prepared.paymentMethod) { diff --git a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt index a80c36f49c..619d6b0df5 100644 --- a/app/src/test/java/to/bitkit/data/CacheStoreTest.kt +++ b/app/src/test/java/to/bitkit/data/CacheStoreTest.kt @@ -32,6 +32,21 @@ class CacheStoreTest : BaseUnitTest() { @After fun tearDown() = runBlocking { sut.reset() } + @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) + + assertEquals(mapOf("hash" to SparkSendAttempt(1, 3_000)), sut.data.first().sparkSendAttempts) + + sut.restoreSparkSendAttempt("HASH", SparkSendAttempt(0, 3_000)) + assertEquals(0, sut.data.first().sparkSendAttempts["hash"]?.attempt) + + sut.restoreSparkSendAttempt("hash", null) + assertFalse("hash" in sut.data.first().sparkSendAttempts) + } + @Test fun `invalidateReceiveLightningInvoice preserves a replacement invoice`() = test { val replacement = AppCacheData( diff --git a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt index 8ebe2f287b..54c7b00ab5 100644 --- a/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/BackupRepoTest.kt @@ -51,6 +51,7 @@ import to.bitkit.R import to.bitkit.data.AppCacheData import to.bitkit.data.AppDb import to.bitkit.data.CacheStore +import to.bitkit.data.CachedUsdtBalance import to.bitkit.data.HwWalletData import to.bitkit.data.HwWalletStore import to.bitkit.data.PaykitOutboundDeliveryStore @@ -58,6 +59,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.WalletConnectionRecovery import to.bitkit.data.WatchOnlyAccountAllocationState import to.bitkit.data.WatchOnlyAccountBackupSnapshot @@ -101,6 +103,7 @@ import to.bitkit.services.SparkError import to.bitkit.test.BaseUnitTest import to.bitkit.test.connectionRecoveryFixture import to.bitkit.utils.AppError +import to.bitkit.utils.jsonLogOf import java.io.File import java.security.MessageDigest import java.util.concurrent.CountDownLatch @@ -3866,6 +3869,34 @@ class BackupRepoTest : BaseUnitTest() { connectionRecovery = connectionRecoveryFixture(settingsStore, keychain), ) + @Test + fun `the restore log leaves out every payment detail`() { + val id = "PAYMENT_DETAIL" + val cache = AppCacheData( + onchainAddress = id, + bolt11 = id, + bolt11PaymentHash = id, + bip21 = id, + usdtDisplayBalance = CachedUsdtBalance(address = id, network = "regtest", balance = 1u), + deletedActivities = listOf(id), + detachedActivityContacts = setOf(id), + pendingLightningMessages = mapOf(id to id), + unfinishedPubkySwaps = listOf(id), + pubkySwapHoldHashes = mapOf(id to id), + sparkSendHashes = listOf(id), + sparkSendExpiries = mapOf(id to 1), + sparkUncertainSends = mapOf(id to 1), + sparkSendAttemptIds = mapOf(id to id), + sparkSendAttempts = mapOf(id to SparkSendAttempt(0, 1)), + sparkUnsavedOwnFailures = setOf(id), + moveToSparkHashes = listOf(id), + ldkSendHashes = listOf(id), + ldkSendExpiries = mapOf(id to 1), + ) + + assertFalse(id in jsonLogOf(cache.withoutPaymentDetails())) + } + private class BackupRepoTestError(message: String) : AppError(message) private companion object { diff --git a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 018e16b1bf..f016afbfd5 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -1249,6 +1249,25 @@ class LightningRepoTest : BaseUnitTest() { verify(sparkRepo).payInvoice(eq("invoice"), eq(1_000uL), eq(deadline), eq(10_000uL), any()) } + @Test + fun `a spark retry rechecks only the payment's authorization`() = test { + startNodeForTesting() + whenever(sparkRepo.canSend(1_000uL)).thenReturn(true) + val checks = mutableListOf() + whenever(sparkRepo.payInvoice(any(), anyOrNull(), anyOrNull(), anyOrNull(), any())).doSuspendableAnswer { + val authorize = it.getArgument Boolean>(4) + repeat(2) { checks += authorize() } + Result.success("hash") + } + var submissionChecks = 0 + + val result = sut.payInvoiceAuthorizedAtSubmission("invoice", 1_000uL, { ++submissionChecks > 0 }) { true } + + assertEquals("hash", result.getOrThrow()) + assertEquals(listOf(true, true), checks) + assertEquals(1, submissionChecks) + } + @Test fun `a node send checks its authorization again where it is submitted`() = test { startNodeForTesting() @@ -2143,6 +2162,7 @@ class LightningRepoTest : BaseUnitTest() { val sparkService = mock() whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.sendKey(any(), any())).thenReturn("key") val details = mock { on { paymentHash } doReturn "hash" } val prepared = PrepareSendPaymentResponse( paymentMethod = SendPaymentMethod.Bolt11Invoice(details, null, 1uL), diff --git a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt index fc2beaaaab..c89de7c0be 100644 --- a/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/SparkRepoTest.kt @@ -80,6 +80,7 @@ import to.bitkit.data.MAX_SPARK_SEND_HASHES import to.bitkit.data.SettingsData import to.bitkit.data.SettingsStore import to.bitkit.data.SparkPayoutChain +import to.bitkit.data.SparkSendAttempt import to.bitkit.env.Env import to.bitkit.ext.create import to.bitkit.ext.scopedActivityId @@ -172,6 +173,9 @@ class SparkRepoTest : BaseUnitTest() { whenever { activityRepo.upsertActivity(any()) }.thenReturn(Result.success(Unit)) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.networkName).thenReturn("regtest") + whenever(sparkService.sendKey(any(), any())).thenAnswer { + "${it.getArgument(0)}-${it.getArgument(1)}" + } whenever { sparkService.lightningSendStatus(any()) }.thenAnswer { sendStatus() } whenever { cacheStore.update(any()) }.thenAnswer { val transform = it.getArgument<(AppCacheData) -> AppCacheData>(0) @@ -4337,7 +4341,8 @@ class SparkRepoTest : BaseUnitTest() { argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } ) assertNull(sut.earlierLightningSend("lnbc1", "hash")) - whenever(sparkService.send(any(), anyOrNull())).thenReturn(sentPayment(fees = 0)) + val sent = sentPayment(fees = 0) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sent) sut.payInvoice("lnbc1", 100uL) verify(sparkService, times(2)).send(any(), anyOrNull()) } @@ -4436,7 +4441,7 @@ class SparkRepoTest : BaseUnitTest() { whenever { sparkService.send(any(), anyOrNull()) }.thenReturn(earlier) val sut = createSut(store) sut.start(0).getOrThrow() - sut.payInvoice("lnbc1", 100uL).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) whenever { sparkService.listPayments() }.thenReturn(listOf(earlier)) advanceUntilIdle() @@ -4965,7 +4970,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send its call returns as failed reports its failure`() = test { + fun `a spark send its call returns as failed reports its failure once by its result`() = test { whenever(sparkService.isConnected).thenReturn(true) val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) @@ -4982,10 +4987,11 @@ class SparkRepoTest : BaseUnitTest() { backgroundScope.launch { sut.nodeEvents.collect { events += it } } runCurrent() - sut.payInvoice("lnbc1", 100uL) + val result = sut.payInvoice("lnbc1", 100uL) advanceUntilIdle() - assertEquals(1, events.count { it is Event.PaymentFailed }, "quickpay never learned the send failed") + assertIs(result.exceptionOrNull()) + assertTrue(events.none { it is Event.PaymentFailed }, "the failure was reported twice") verify(activityRepo).upsertActivity( argThat { this is Activity.Lightning && v1.id == "hash" && v1.status == PaymentState.FAILED } ) @@ -5059,8 +5065,9 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send is refused before it goes out while spark's synced list can't be read`() = test { - val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + fun `an older build's spark send refuses a retry while spark's synced list can't be read`() = test { + // An older build sent the invoice under a random key, which a retry's key can't match. + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendHashes = listOf("hash"))), clock) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) @@ -5080,14 +5087,15 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send is refused before spark's first sync while its list can't be read`() = test { + fun `an older build's spark send refuses a retry before the first sync while the list can't be read`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData(sparkSendHashes = listOf("hash"))), clock) whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) // No wallet sync has succeeded yet, and Spark's local list can't be read either. whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) val prepared = unexpiredPrepared() whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) - val sut = createSut() + val sut = createSut(store) sut.start(0).getOrThrow() advanceUntilIdle() whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } @@ -5114,6 +5122,465 @@ class SparkRepoTest : BaseUnitTest() { verify(sparkService, never()).send(any(), anyOrNull()) } + @Test + fun `a spark send goes out under its first attempt's key while spark's list can't be read`() = test { + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + whenever(sparkService.isConnected).thenReturn(true) + // No wallet sync has succeeded yet, as right after a restore, and Spark's local list can't be read either. + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sent = sentPayment(fees = 0) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sent) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + + // A payment an earlier attempt committed under this key comes back from Spark instead of paying again. + assertEquals("hash-0", sentKey()) + assertEquals(0, store.data.first().sparkSendAttempts["hash"]?.attempt) + } + + @Test + fun `a spark retry that gets back a failure already reported is refused`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val failed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(failed) + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + whenever(sparkService.listPayments()).thenAnswer { throw SdkException.Generic("storage") } + sut.payInvoice("lnbc1", 100uL) + + // Spark's list still can't be read, so the retry keeps the failed attempt's key and gets its failure back. + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + } + + @Test + fun `a spark retry reuses its attempt's key until spark lists that attempt failed`() = test { + val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(1, now.epochSeconds + 3_600))) + val store = CacheStore(InMemoryDataStore(kept), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sent = sentPayment(fees = 0) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sent) + // The first attempt failed; the second one's outcome isn't listed. + 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(1, store.data.first().sparkSendAttempts["hash"]?.attempt) + } + + @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))) + val store = CacheStore(InMemoryDataStore(kept), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sent = sentPayment(fees = 0) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sent) + 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() + + // A failed key can't send again, so the retry takes a new one. + assertEquals("hash-1", sentKey()) + assertEquals(1, store.data.first().sparkSendAttempts["hash"]?.attempt) + } + + @Test + fun `a short balance under a reused spark key keeps the send held`() = test { + val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) + val store = CacheStore(InMemoryDataStore(kept), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + // Spark picks leaves before the operators see the key, so the earlier attempt's transfer can't come back. + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.InsufficientFunds(null) } + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertEquals("hash-0", sentKey()) + assertTrue("hash" in store.data.first().sparkSendHashes, "the node could pay the invoice again") + assertTrue("hash" in store.data.first().sparkUncertainSends) + } + + @Test + fun `a spark send retries under its key while spark can't select its leaves`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val sent = sentPayment(fees = 0) + var sends = 0 + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { + if (++sends == 1) throw leafSelectionFailure() else sent + } + val sut = createSut() + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + + val keys = argumentCaptor().apply { verify(sparkService, times(2)).send(any(), capture()) }.allValues + assertEquals(listOf("hash-0", "hash-0"), keys) + } + + @Test + fun `a spark send stops retrying its leaves once its deadline passes`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val deadline = now + 1.minutes + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { + now = deadline + 1.minutes + throw leafSelectionFailure() + } + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + sut.start(0).getOrThrow() + advanceUntilIdle() + + val result = sut.payInvoice("lnbc1", 100uL, paymentDeadlineAt = deadline) + + assertIs(result.exceptionOrNull()) + + verify(sparkService, times(1)).send(any(), anyOrNull()) + } + + @Test + fun `a spark send stops retrying its leaves once the payment is no longer allowed`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + sut.start(0).getOrThrow() + advanceUntilIdle() + var checks = 0 + + val result = sut.payInvoice("lnbc1", 100uL, onBeforeSend = { ++checks == 1 }) + + assertIs(result.exceptionOrNull()) + verify(sparkService, times(1)).send(any(), anyOrNull()) + assertEquals(2, checks) + } + + @Test + fun `a spark send whose leaves spark can't select is held under a new key`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, times(4)).send(any(), anyOrNull()) + assertTrue("hash" in store.data.first().sparkUncertainSends) + } + + @Test + fun `a spark send held after a leaf failure keeps the node off its invoice after a sync`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = null)) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + + // The SDK may have selected leaves again after a committed transfer, which can stay unlisted after a sync. + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong() + 1u)) + whenever(sparkService.listPayments()).thenReturn(emptyList()) + sut.start(0).getOrThrow() + advanceUntilIdle() + assertEquals(EarlierSend.Pending("hash"), sut.earlierLightningSend("lnbc1280n1send", "hash")) + } + + @Test + fun `a paid spark send stays paid when its hold can't be removed from storage`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenReturn(sentPayment(fees = 0)) + whenever(cacheStore.removeSparkUncertainSend(any())).thenAnswer { throw IOException("disk full") } + val sut = createSut() + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + } + + @Test + fun `a spark send refused before reaching spark is refused again on retry`() = test { + whenever(sparkService.isConnected).thenReturn(true) + whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.InsufficientFunds(null) } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + assertFalse("hash" in store.data.first().sparkSendAttempts) + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + assertFalse("hash" in store.data.first().sparkUncertainSends) + } + + @Test + fun `a refused spark retry keeps the attempt spark listed failed before it`() = test { + val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) + val store = CacheStore(InMemoryDataStore(kept), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + val firstFailed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(firstFailed)) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw SdkException.InsufficientFunds(null) } + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertEquals("hash-1", sentKey()) + assertEquals(0, store.data.first().sparkSendAttempts["hash"]?.attempt) + } + + @Test + fun `leaves spark can't select under a reused spark key keep the send held`() = test { + val kept = AppCacheData(sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600))) + val store = CacheStore(InMemoryDataStore(kept), clock) + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + whenever(sparkService.send(any(), anyOrNull())).thenAnswer { throw leafSelectionFailure() } + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertTrue("hash" in store.data.first().sparkSendHashes, "the node could pay the invoice again") + assertTrue("hash" in store.data.first().sparkUncertainSends) + } + + @Test + fun `a short balance on a leaf retry keeps a new key's send held`() = test { + whenever(sparkService.isConnected).thenReturn(true) + val prepared = unexpiredPrepared() + whenever(sparkService.prepareSend(any(), anyOrNull(), anyOrNull())).thenReturn(prepared) + var sends = 0 + // The first try may have committed a transfer that spent the leaves the retry then lacks. + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { + if (++sends == 1) throw leafSelectionFailure() + throw SdkException.InsufficientFunds(null) + } + val store = CacheStore(InMemoryDataStore(AppCacheData()), clock) + val sut = createSut(store) + sut.start(0).getOrThrow() + advanceUntilIdle() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertTrue("hash" in store.data.first().sparkUncertainSends) + } + + @Test + fun `a spark send held after a leaf failure reports its failure at its invoice's expiry`() = 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())).thenAnswer { throw leafSelectionFailure() } + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.start(0).getOrThrow() + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + advanceUntilIdle() + assertTrue(events.none { it is Event.PaymentFailed }, "a transfer the send committed can still go out") + + now += 2.hours + sparkEvents.emit(SdkEvent.Synced) + advanceUntilIdle() + + assertEquals("hash", assertIs(events.single()).paymentHash) + } + + @Test + fun `a spark retry of a send held after a leaf failure pays under its key`() = 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) + var sends = 0 + whenever(sparkService.send(any(), anyOrNull())).doSuspendableAnswer { + if (++sends <= 4) throw leafSelectionFailure() + sentPayment(fees = 0).copy(id = it.getArgument(1)) + } + val sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + val events = mutableListOf() + backgroundScope.launch { sut.nodeEvents.collect { events += it } } + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + assertEquals("hash", sut.payInvoice("lnbc1", 100uL).getOrThrow()) + runCurrent() + + val keys = argumentCaptor().apply { verify(sparkService, times(5)).send(any(), capture()) }.allValues + assertEquals(List(5) { "hash-0" }, keys) + // A caller still waiting on the held send learns it paid. + assertEquals(1, events.count { it is Event.PaymentSuccessful }) + } + + @Test + fun `a spark retry of a held send stopped by its deadline 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()) + + val retry = sut.payInvoice( + "lnbc1", + 100uL, + paymentDeadlineAt = now + 1.minutes, + onBeforeSend = { + // The deadline passes while the retry is checked, so it never goes out. + now += 2.minutes + true + }, + ) + + assertIs(retry.exceptionOrNull()) + assertTrue("hash" in store.data.first().sparkUncertainSends) + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + } + + @Test + fun `a spark retry stopped by its deadline keeps a hold only saved before a restart`() = test { + val store = CacheStore( + InMemoryDataStore( + AppCacheData( + sparkSendHashes = listOf("hash"), + sparkSendExpiries = mapOf("hash" to now.epochSeconds + 3_600), + sparkUncertainSends = mapOf("hash" to now.epochSeconds), + sparkSendAttemptIds = mapOf("hash" to "hash-0"), + sparkSendAttempts = mapOf("hash" to SparkSendAttempt(0, now.epochSeconds + 3_600)), + ) + ), + clock, + ) + 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) + val sut = createSut(store) + sut.start(0).getOrThrow() + + val retry = sut.payInvoice( + "lnbc1", + 100uL, + paymentDeadlineAt = now + 1.minutes, + onBeforeSend = { + now += 2.minutes + true + }, + ) + + assertIs(retry.exceptionOrNull()) + verify(sparkService, never()).send(any(), anyOrNull()) + assertTrue("hash" in store.data.first().sparkUncertainSends) + assertTrue("hash" in store.data.first().sparkSendHashes) + } + + @Test + fun `a spark retry of a held send spark lists failed never takes a new key before the hold settles`() = 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 sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + sut.start(0).getOrThrow() + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + val failed = sentPayment(fees = 0).copy(id = "hash-0", status = PaymentStatus.FAILED) + whenever(sparkService.listPayments()).thenReturn(listOf(failed)) + + assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) + + verify(sparkService, never()).send(any(), eq("hash-1")) + } + + @Test + fun `keyed retries of a held spark send keep one poll of spark per interval`() = 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 sut = createSut(CacheStore(InMemoryDataStore(AppCacheData()), clock)) + sut.start(0).getOrThrow() + repeat(3) { assertIs(sut.payInvoice("lnbc1", 100uL).exceptionOrNull()) } + // Past the wait for the send screen to track the send, every poll started. + advanceTimeBy(11.seconds) + clearInvocations(sparkService) + + advanceTimeBy(30.seconds) + + verify(sparkService, times(1)).syncWallet() + } + @Test fun `a held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds @@ -5391,7 +5858,7 @@ class SparkRepoTest : BaseUnitTest() { } @Test - fun `a spark send that returns failed reports it when keeping its unsaved failure fails too`() = test { + fun `a spark send that returns failed is refused when keeping its unsaved failure fails too`() = test { whenever(sparkService.isSupported).thenReturn(true) whenever(sparkService.isConnected).thenReturn(true) whenever(sparkService.getInfo()).thenReturn(info(0uL).copy(lastSyncedAt = now.epochSeconds.toULong())) @@ -5407,10 +5874,11 @@ class SparkRepoTest : BaseUnitTest() { backgroundScope.launch { sut.nodeEvents.collect { events += it } } sut.start(0).getOrThrow() - sut.payInvoice("lnbc1", 100uL) + val result = sut.payInvoice("lnbc1", 100uL) advanceUntilIdle() - assertEquals("hash", assertIs(events.single()).paymentHash) + assertIs(result.exceptionOrNull()) + assertTrue(events.none { it is Event.PaymentFailed }) } @Test @@ -5506,6 +5974,9 @@ class SparkRepoTest : BaseUnitTest() { ) } + private fun leafSelectionFailure() = + SdkException.SparkException("Tree service error: generic error: Failed to select leaves after all retries") + /** The idempotency key of the latest Spark send, which Spark keeps as that attempt's payment id. */ private suspend fun sentKey(): String = argumentCaptor().apply { verify(sparkService, atLeastOnce()).send(any(), capture()) }.lastValue diff --git a/app/src/test/java/to/bitkit/services/SparkSendKeyTest.kt b/app/src/test/java/to/bitkit/services/SparkSendKeyTest.kt new file mode 100644 index 0000000000..b3abfdc089 --- /dev/null +++ b/app/src/test/java/to/bitkit/services/SparkSendKeyTest.kt @@ -0,0 +1,45 @@ +package to.bitkit.services + +import org.junit.Test +import to.bitkit.ext.fromHex +import to.bitkit.ext.toHex +import kotlin.test.assertEquals +import kotlin.test.assertNotEquals + +class SparkSendKeyTest { + private companion object { + /** The BIP39 seed of `abandon … about` with passphrase `TREZOR`, from the BIP39 test vectors. */ + const val SEED = "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e534955" + + "31f09a6987599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04" + + /** Bytes 0 to 31. */ + const val PAYMENT_HASH = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + } + + // iOS's SparkSendKeyTests asserts the same vector, so a wallet restored on the other app derives the same keys. + @Test + fun `derives the shared test vector`() { + val secret = SparkSendKey.secret(SEED.fromHex()) + + assertEquals("577ceb10411255cef07e3f49bd7e5239de07586c7457f65ee72ee53737361a98", secret.toHex()) + assertEquals("8d92d8bf-76f3-56fe-8958-8e440acb64fc", SparkSendKey.key(secret, PAYMENT_HASH, 0)) + assertEquals("712dea1f-8268-5e52-a280-aac86bc60b59", SparkSendKey.key(secret, PAYMENT_HASH, 1)) + } + + @Test + fun `reads the payment hash in either case`() { + val secret = SparkSendKey.secret(SEED.fromHex()) + + assertEquals( + SparkSendKey.key(secret, PAYMENT_HASH, 0), + SparkSendKey.key(secret, PAYMENT_HASH.uppercase(), 0), + ) + } + + @Test + fun `another seed derives other keys`() { + val other = SparkSendKey.secret(ByteArray(64)) + + assertNotEquals("8d92d8bf-76f3-56fe-8958-8e440acb64fc", SparkSendKey.key(other, PAYMENT_HASH, 0)) + } +} diff --git a/changelog.d/next/2019.fixed.md b/changelog.d/next/2019.fixed.md new file mode 100644 index 0000000000..e306939073 --- /dev/null +++ b/changelog.d/next/2019.fixed.md @@ -0,0 +1 @@ +Fixed a Lightning invoice paid through Spark being paid twice when the app retried it after an interrupted send, and a payment made right after moving funds to Spark staying pending.