Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions app/src/main/java/to/bitkit/data/CacheStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand Down Expand Up @@ -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<String, String> = mapOf(),
/** The latest attempt at each invoice Spark sent, by hash, whose number picks the attempt's idempotency key. */
val sparkSendAttempts: Map<String, SparkSendAttempt> = 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.
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions app/src/main/java/to/bitkit/repositories/BackupRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
117 changes: 103 additions & 14 deletions app/src/main/java/to/bitkit/repositories/SparkRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -587,19 +593,23 @@ 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
}
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()
Expand All @@ -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)
Expand All @@ -625,24 +654,34 @@ 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 {
// 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)
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)
Expand All @@ -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
Expand All @@ -676,6 +720,43 @@ class SparkRepo @Inject constructor(
}
}

private suspend fun sendRetryingLeafSelection(
prepared: PrepareSendPaymentResponse,
attemptId: String,
paymentDeadlineAt: Instant?,
): Result<Payment> {
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<Payment>?): 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
Expand Down Expand Up @@ -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)
Expand Down
52 changes: 52 additions & 0 deletions app/src/main/java/to/bitkit/services/SparkSendKey.kt
Original file line number Diff line number Diff line change
@@ -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()
}
}
Loading