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..474c4cdd56 100644 --- a/app/src/main/java/to/bitkit/repositories/BackupRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/BackupRepo.kt @@ -1341,6 +1341,7 @@ class BackupRepo @Inject constructor( cachedRates = emptyList(), moveToSparkHashes = emptyList(), sparkSendAttemptIds = emptyMap(), + sparkSendAttempts = emptyMap(), sparkUnsavedOwnFailures = emptySet(), ) Logger.debug("Restored caches: ${jsonLogOf(logged)}", TAG) diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt index 2bbeb986b4..6e0337e9e4 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 @@ -587,12 +593,11 @@ 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. + // 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() 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) { + when (local?.latestSend(paymentHash)?.status) { PaymentStatus.COMPLETED -> { Logger.info("Skipped Spark send of '$paymentHash', already paid", context = TAG) return@runSuspendCatching paymentHash @@ -600,6 +605,11 @@ class SparkRepo @Inject constructor( 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 (local == null && hasUnkeyedSend(paymentHash)) { + throw SparkError.SendRefused("Spark could not list its payments to check the invoice") + } } // A cancel, block or identity change can land while Spark prepares, so the last check runs right here. if (!onBeforeSend()) throw PaymentAbortedBeforeSend() @@ -609,11 +619,30 @@ 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 + + // A send refused before anything reached Spark's operators leaves its key unused, so a retry refuses + // the same way. + suspend fun forgetUnusedAttempt() { + 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) @@ -625,9 +654,10 @@ class SparkRepo @Inject constructor( }.onFailure { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) + forgetUnusedAttempt() throw it } - runSuspendCatching { sparkService.send(prepared, attemptId) } + sendRetryingLeafSelection(prepared, attemptId, paymentDeadlineAt) } } val payment = sent.getOrElse { @@ -635,14 +665,23 @@ class SparkRepo @Inject constructor( if (it.isInvoiceExpired()) { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) + forgetUnusedAttempt() 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) { + // Spark selects the leaves to spend before anything goes to the operators, so a short balance or + // leaves it can't select left nothing, for instance when an earlier send spent the balance after + // it 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 || it.isLeafSelectionFailure()) && !isReusedKey) { cacheStore.removeSparkUncertainSend(paymentHash) cacheStore.removeSparkSendHash(paymentHash) - throw SparkError.SendRefused("Spark balance can't cover the payment", it) + forgetUnusedAttempt() + val reason = if (it.isLeafSelectionFailure()) { + "Spark could not select leaves for the payment" + } else { + "Spark balance can't cover the payment" + } + throw SparkError.SendRefused(reason, it) } Logger.warn("Failed to learn the outcome of Spark send '$paymentHash'", it, context = TAG) settleUncertainSend(paymentHash, expiresAt, attemptId) @@ -657,8 +696,13 @@ class SparkRepo @Inject constructor( } // 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. + cacheStore.removeSparkSendHash(paymentHash) recordActivity(payment, isOwnAttempt = true) - if (reportedSendIds.add(payment.id)) payment.toNodeEvent()?.let { _nodeEvents.emit(it) } + // A retry under a key whose failure was already reported, as when Spark's list couldn't be read to + // move past it, gets that failure back and no event, so the result reports it. + if (!reportedSendIds.add(payment.id)) throw SparkError.SendRefused("Spark send failed earlier") + payment.toNodeEvent()?.let { _nodeEvents.emit(it) } } Logger.info("Sent Spark payment '${payment.id}' with status '${payment.status}'", context = TAG) paymentHash @@ -676,6 +720,43 @@ class SparkRepo @Inject constructor( } } + private suspend fun sendRetryingLeafSelection( + prepared: PrepareSendPaymentResponse, + attemptId: String, + paymentDeadlineAt: Instant?, + ): 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) + if (!canRetry()) return result + result = runSuspendCatching { sparkService.send(prepared, attemptId) } + } + return result + } + + 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 @@ -2655,6 +2736,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, before anything reaches the operators (`select_leaves_with_retry` in the 0.28.3 SDK's + * `spark-wallet/src/wallet.rs`). + */ +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/LightningRepoTest.kt b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt index 489f3bf8fb..64d680a55a 100644 --- a/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/LightningRepoTest.kt @@ -2115,6 +2115,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..0cb91e1b48 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()) } @@ -5059,8 +5064,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 +5086,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 +5121,205 @@ 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 whose leaves spark can't select is refused 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()) + assertFalse("hash" in store.data.first().sparkSendHashes) + assertFalse("hash" in store.data.first().sparkUncertainSends) + } + + @Test + fun `a spark send refused before reaching spark is refused again on retry`() = 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()) + 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 leafSelectionFailure() } + 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 held spark send spark never recorded reports its failure at expiry after a restart`() = test { val sentAt = now.epochSeconds @@ -5506,6 +5712,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.