diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index fa0ded4bc..ff36d2f07 100644 --- a/Bitkit/Managers/SparkManager.swift +++ b/Bitkit/Managers/SparkManager.swift @@ -103,6 +103,8 @@ final class SparkManager: ChannelFreeLightningRail { /// Payments whose activity failed to save, written again at the next refresh. @ObservationIgnored private var unsavedPayments: Set = [] @ObservationIgnored private var sdk: BreezSdk? + /// The connected wallet's `SparkSendKey.secret`, derived once at connect. + @ObservationIgnored private var sendKeySecret: Data? /// Whether a wallet sync ended since this run connected, so the SDK's sync error describes this run. @ObservationIgnored private var syncedThisRun = false /// The last withdrawal quote, which the withdrawal reuses while it holds. @@ -220,6 +222,7 @@ final class SparkManager: ChannelFreeLightningRail { try? await sdk.disconnect() } sdk = nil + sendKeySecret = nil listenerId = nil do { let generation = connectGeneration @@ -429,7 +432,7 @@ final class SparkManager: ChannelFreeLightningRail { // Registered before the first refresh marks Spark ready, so Lightning calls never see it ready while they // still go to LDK, even when that refresh or the activity sync fails. An emergency exit keeps it out. LightningService.shared.channelFreePaymentHistory = self - LightningService.shared.railSendExpired = { [weak self] hash in await self?.recordExpiredSend(paymentHash: hash) ?? false } + LightningService.shared.railSendExpired = { [weak self] hash in await self?.recordExpiredSend(paymentHash: hash) } if !isExiting { LightningService.shared.channelFreeRail = self } @@ -477,6 +480,7 @@ final class SparkManager: ChannelFreeLightningRail { throw CustomServiceError.mnemonicNotFound } let passphrase = try Keychain.loadString(key: .bip39Passphrase(index: walletIndex)) + let secret = try SparkSendKey.secret(seed: mnemonicToSeed(mnemonicPhrase: mnemonic, passphrase: passphrase)) var config = Self.sdkConfig(network: network, apiKey: Env.breezApiKey, isExiting: isExiting) let chainAPI = try Self.configureLocalSpark(&config) let storageDir = Env.sparkStorage(walletIndex: walletIndex) @@ -497,6 +501,7 @@ final class SparkManager: ChannelFreeLightningRail { await self?.onSdkEvent(event) }) sdk = connected + sendKeySecret = secret Logger.info("Connected Spark wallet on '\(network)'", context: "SparkManager") await importRestoredExitState(walletIndex: walletIndex) Self.notifyExitStateChanged() @@ -603,6 +608,7 @@ final class SparkManager: ChannelFreeLightningRail { } } sdk = nil + sendKeySecret = nil listenerId = nil refreshAgain = false activitiesSynced = false @@ -626,6 +632,7 @@ final class SparkManager: ChannelFreeLightningRail { unsavedPayments = [] sentWithdrawalTxIds = [] preparedWithdrawal = nil + SparkSendAttempts.clear() Self.pendingContactWithdrawal = nil Self.contactWithdrawalTxIds = [] onStateChanged?() @@ -645,6 +652,10 @@ final class SparkManager: ChannelFreeLightningRail { // MARK: ChannelFreeLightningRail + nonisolated func hasKeyedSend(paymentHash: String) -> Bool { + SparkSendAttempts.latest(paymentHash: paymentHash) != nil + } + nonisolated func receive(amountSats: UInt64?, description: String, expirySecs: UInt32) async throws -> String { let method = ReceivePaymentMethod.bolt11Invoice( description: description, @@ -691,23 +702,84 @@ final class SparkManager: ChannelFreeLightningRail { } // The fee limit is checked on the quote that is sent, not only on the earlier estimate. try Self.checkSendFee(feeSats, maxFeeSats: maxFeeSats) + guard let secret = await sendKeySecret else { + throw ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) + } + // 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 lists failed, as a failed key can't send again. A list that can't be read + // keeps the latest key, which can't pay twice either. + let failed = try? await sdk.listPayments(request: ListPaymentsRequest(typeFilter: [.send], statusFilter: [.failed])) + let paymentHash = invoiceDetails.paymentHash + let attempt = SparkSendAttempts.next( + paymentHash: paymentHash, + secret: secret, + failedIds: Set(failed?.payments.map(\.id) ?? []) + ) + let idempotencyKey = SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: attempt) + let previousAttempt = SparkSendAttempts.latest(paymentHash: paymentHash) + let previousAmountSats = SparkSendAttempts.latestAmountSats(paymentHash: paymentHash) + let isReusedKey = previousAttempt == attempt + // A send in doubt whose attempt Spark lists failed is settled by that failure first, so its hold can't be taken + // for this new attempt's. + let isInDoubt = LightningService.shared.railSendHolds[paymentHash.lowercased()] != nil + if Self.waitsForHold( + isReusedKey: isReusedKey, + isInDoubt: isInDoubt, + changesAmount: previousAmountSats.map { $0 != amountSats } ?? false + ) { + throw ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) + } + let (sum, overflows) = invoiceDetails.timestamp.addingReportingOverflow(invoiceDetails.expiry) + let expiresAt = overflows ? UInt64.max : sum // An exit that started while the quote was prepared refuses it here, before its hash is recorded. - let response: SendPaymentResponse = try await spends.run { - // A deadline that passed while the quote was prepared stops the payment here, before anything leaves. - try beforeSubmission() - do { - return try await sdk.sendPayment(request: SendPaymentRequest( - prepareResponse: prepared, - options: Self.bolt11SendOptions - )) - } catch { - throw Self.sendPaymentFailure(error) + let response: SendPaymentResponse + do { + response = try await spends.run { + // A deadline that passed while the quote was prepared stops the payment here, before anything leaves. + try beforeSubmission() + // Kept once the send is admitted, so a send refused before it leaves keeps the earlier attempt. + SparkSendAttempts.set( + paymentHash: paymentHash, attempt: attempt, amountSats: amountSats, expiresAt: expiresAt, now: Self.nowSecs() + ) + do { + return try await Self.sendRetryingLeafSelection(canRetry: { (try? beforeSubmission()) != nil }) { + try await sdk.sendPayment(request: SendPaymentRequest( + prepareResponse: prepared, + options: Self.bolt11SendOptions, + idempotencyKey: idempotencyKey + )) + } + } catch { + throw Self.bolt11SendFailure(error, isReusedKey: isReusedKey) + } + } + } catch let refusal as ChannelFreeRailSendRefused { + // A refused attempt never reached Spark's operators, so its key stays unused and a retry refuses the same way. + if !isReusedKey { + SparkSendAttempts.restore( + paymentHash: paymentHash, attempt: previousAttempt, amountSats: previousAmountSats, expiresAt: expiresAt + ) } + throw refusal } Logger.info("Sent Spark payment '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") + try Self.checkSentPayment(response.payment.status) return invoiceDetails.paymentHash } + /// Whether a send must wait for the hold of the invoice's earlier attempt to settle: before it takes a new key, or + /// when it would reuse that attempt's key at another amount, as Spark would return the earlier payment for it. + nonisolated static func waitsForHold(isReusedKey: Bool, isInDoubt: Bool, changesAmount: Bool) -> Bool { + isReusedKey ? changesAmount : isInDoubt + } + + /// A failed payment, as Spark returns under a key it already failed when its failed list couldn't be read to move + /// past it, paid nothing, so the send is refused instead of read as submitted. + nonisolated static func checkSentPayment(_ status: BreezSdkSpark.PaymentStatus) throws { + guard status == .failed else { return } + throw ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description")) + } + nonisolated static func checkSendFee(_ feeSats: UInt64, maxFeeSats: UInt64?) throws { guard let maxFeeSats, feeSats > maxFeeSats else { return } Logger.info("Spark fee of \(feeSats) sats exceeds the limit of \(maxFeeSats) sats", context: "SparkManager") @@ -721,6 +793,66 @@ final class SparkManager: ChannelFreeLightningRail { return !overflow && total <= balanceSats } + nonisolated static func isShortBalance(_ error: Error) -> Bool { + if case SdkError.InsufficientFunds = error { + return true + } + return false + } + + /// What a failure inside the BOLT11 `sendPayment` means for the caller. Spark picks the leaves to spend before the + /// operators see the key, so a short balance left nothing under a new key; under a key an earlier attempt used, it + /// can hide the transfer that attempt committed, so the send stays in doubt until Spark settles it. Leaves Spark + /// still can't select after its retries keep the send in doubt under any key, as the SDK selects them again after an + /// operator error, so the failure can follow a transfer this send committed. + nonisolated static func bolt11SendFailure(_ error: Error, isReusedKey: Bool) -> Error { + if isReusedKey, isShortBalance(error) || expiredInvoiceRefusal(error) != nil { + return error + } + if isLeafSelectionFailure(error) { + return error + } + return sendPaymentFailure(error) + } + + /// Sends again under the same key while Spark can't select the leaves to spend, as right after a move to Spark lands. + /// Spark selects them before anything reaches the operators, so a retry under the key can't pay twice. `canRetry` + /// is checked before each retry, which otherwise ends with the last failure. An invoice that expires or a short balance + /// on a retry ends it with the leaf failure, which may follow a committed transfer, so neither reads as a send that + /// never left. + nonisolated static func sendRetryingLeafSelection( + retryDelay: Duration = .seconds(2), + canRetry: () -> Bool, + _ send: () async throws -> T + ) async throws -> T { + var retries = 0 + while true { + do { + return try await send() + } catch { + // A failed try can have committed a transfer before Spark selected leaves again, so an expiry or a + // short balance on a retry, which would read as nothing sent, ends with the leaf failure instead. + if retries > 0, expiredInvoiceRefusal(error) != nil || Self.isShortBalance(error) { + throw SdkError.SparkError("Failed to select leaves after all retries") + } + guard isLeafSelectionFailure(error), retries < leafSelectionRetries else { throw error } + retries += 1 + Logger.info("Retrying a Spark send as Spark could not select its leaves", context: "SparkManager") + try? await Task.sleep(for: retryDelay) + guard !Task.isCancelled, canRetry() else { throw error } + } + } + } + + nonisolated static let leafSelectionRetries = 3 + + /// Spark fails a send with this error when it holds the balance but can't select leaves to spend, before anything + /// reaches the operators (`select_leaves_with_retry` in the 0.28.3 SDK's `spark-wallet/src/wallet.rs`). + nonisolated static func isLeafSelectionFailure(_ error: Error) -> Bool { + guard case let SdkError.SparkError(message) = error else { return false } + return message.localizedCaseInsensitiveContains("Failed to select leaves after all retries") + } + /// What a failure inside `sendPayment` means for the caller. nonisolated static func sendPaymentFailure(_ error: Error) -> Error { // The SDK checks the expiry again before sending, so an invoice that expired on the confirm screen left nothing. @@ -1864,14 +1996,51 @@ final class SparkManager: ChannelFreeLightningRail { } /// Writes the Activity row of a send Spark never settled once its invoice expired: Spark's own attempt of it, not one - /// listed before it went out, or a failure of the stored pending send when Spark lists none. Returns whether it was saved. - private func recordExpiredSend(paymentHash: String) async -> Bool { - guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return false } + /// listed before it went out, or a failure of the stored pending send when Spark lists none. Returns the status saved, + /// nil when it wasn't. + private func recordExpiredSend(paymentHash: String) async -> LDKNode.PaymentStatus? { + guard let payments = try? await requireSdk().listPayments(request: ListPaymentsRequest()).payments else { return nil } let isEarlierAttempt = { LightningService.shared.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } - if let own = Self.expiredSendAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) { - return await recordActivity(own) + if let own = Self.expiredSendDecidingAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) { + guard await recordActivity(own) else { return nil } + switch own.status { + case .completed: return .succeeded + case .pending: return .pending + case .failed: + // A success saved since the list was read keeps its row, and stays paid. + do { + return try await Self.expiredSendStatus(stored: CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) + } catch { + return nil + } + } + } + do { + return try await Self.expiredSendStatus(stored: CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) + } catch { + return nil + } + } + + /// The outcome of a send Spark lists no attempt of once its invoice expired, by its stored row: paid when it already + /// succeeded, as Spark's success can land after the list was read, and failed otherwise. + nonisolated static func expiredSendStatus(stored: PaymentState?) -> LDKNode.PaymentStatus { + stored == .succeeded ? .succeeded : .failed + } + + /// The attempt that decides a send whose invoice expired: a paid one, then a pending one, whenever Spark dated them, + /// as either can still settle the invoice, else the latest attempt not listed before the send went out. + nonisolated static func expiredSendDecidingAttempt( + _ payments: [Payment], + paymentHash: String, + isEarlierAttempt: (_ hash: String, _ createdAt: UInt64) -> Bool + ) -> Payment? { + for status in [BreezSdkSpark.PaymentStatus.completed, .pending] { + if let live = expiredSendAttempt(payments.filter { $0.status == status }, paymentHash: paymentHash, isEarlierAttempt: { _, _ in false }) { + return live + } } - return await (try? CoreService.shared.activity.failPendingLightningSend(id: paymentHash)) != nil + return expiredSendAttempt(payments, paymentHash: paymentHash, isEarlierAttempt: isEarlierAttempt) } /// The latest of Spark's attempts of a send whose invoice expired, none when Spark lists only attempts before it. diff --git a/Bitkit/Services/CoreService.swift b/Bitkit/Services/CoreService.swift index 0129fa61f..a55ba0b4e 100644 --- a/Bitkit/Services/CoreService.swift +++ b/Bitkit/Services/CoreService.swift @@ -1407,16 +1407,19 @@ class ActivityService { } /// Marks the stored Lightning send `id` failed while it is still pending, read, checked and written in one core-queue - /// operation, so a change saved meanwhile isn't overwritten. - func failPendingLightningSend(id: String) async throws { + /// operation, so a change saved meanwhile isn't overwritten. Returns the send's status after it, nil when none is stored. + @discardableResult + func failPendingLightningSend(id: String) async throws -> PaymentState? { try await ServiceQueue.background(.core) { guard case let .lightning(activity) = try getActivityById(walletId: WalletScope.default, activityId: id), - activity.txType == .sent, activity.status == .pending - else { return } + activity.txType == .sent + else { return nil } + guard activity.status == .pending else { return activity.status } var failed = activity failed.status = .failed try updateActivity(activityId: id, activity: .lightning(failed)) self.activitiesChangedSubject.send() + return .failed } } diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 78a1b612b..53f974d3b 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -26,6 +26,8 @@ protocol ChannelFreeLightningRail: AnyObject { func lightningSendStatus(bolt11: String) async throws -> PaymentStatus? /// Whether this app would have paid `bolt11` by a direct Spark transfer, which `lightningSendStatus` can't see. func mayPayBySparkTransfer(bolt11: String, sats: UInt64?) async throws -> Bool + /// Whether this build sent the invoice with `paymentHash` under a derived key, so a retry under that key can't pay twice. + func hasKeyedSend(paymentHash: String) -> Bool } @MainActor @@ -208,6 +210,8 @@ class LightningService: NodeLifecycleService { private var attemptRails: [String: LightningPaymentRail] = [:] /// Payment hashes inside a rail send, which Spark lists only once it returns. private var railSendsInFlight: Set = [] + /// How many rail sends of each invoice started, so a check can tell one started since it read. + private var railSendStarts: [String: Int] = [:] /// Per payment hash, the latest time Spark dated a failed attempt of it, from its list or its events, so a send's /// start is saved after it and that failure never reads as the send's own. private var railFailureCreatedAt: [String: UInt64] = [:] @@ -224,8 +228,8 @@ class LightningService: NodeLifecycleService { /// Lightning: an invoice Spark paid or is paying is never paid again over a channel. weak var channelFreePaymentHistory: ChannelFreeLightningRail? /// Writes the Activity row of a rail send Spark never settled once its invoice expired: from Spark's own attempt of it - /// when listed, otherwise by failing the stored pending row. Returns whether the row was saved. - var railSendExpired: ((String) async -> Bool)? + /// when listed, otherwise by failing the stored pending row. Returns the status saved, nil when the row wasn't. + var railSendExpired: ((String) async -> PaymentStatus?)? var onchainTransactionConfirmed: (@Sendable (String) async -> Void)? var onchainTransactionReceived: (@Sendable (String) async -> Void)? typealias OnchainActivityCompletion = @MainActor () async -> Void @@ -1197,6 +1201,7 @@ class LightningService: NodeLifecycleService { feeSats = try await rail.estimateRoutingFees(bolt11: bolt11, amountSats: sats) } catch { Logger.warn("Spark fee estimate failed: \(error)", context: "LightningService") + try throwPendingIfInDoubt(paymentHash: paymentHash) throw error as? ChannelFreeRailSendRefused ?? ChannelFreeRailSendRefused( reason: t("wallet__payment_failed_description"), underlying: error @@ -1204,6 +1209,7 @@ class LightningService: NodeLifecycleService { } guard feeSats * 1000 <= maxFeeMsat else { Logger.info("Spark routing fee of \(feeSats) sats exceeds the limit of \(maxFeeMsat / 1000) sats", context: "LightningService") + try throwPendingIfInDoubt(paymentHash: paymentHash) throw ChannelFreeRailSendRefused(reason: t("wallet__max_possible_fee_rate")) } } @@ -1217,6 +1223,8 @@ class LightningService: NodeLifecycleService { ?? Self.paymentAmountSats(bolt11: bolt11, sats: sats).map(Self.defaultMaxFeeSats), beforeSubmission: { [weak self] in try beforeSubmission() + // Spark checks again before it retries the same attempt, which is already admitted. + guard !didRecordAttempt else { return } do { try self?.admitSend(paymentHash: paymentHash, on: .channelFree, since: mark) } catch { @@ -1241,6 +1249,7 @@ class LightningService: NodeLifecycleService { endRailSendUncertainty(paymentHash: paymentHash) releaseRailAttempt(paymentHash: paymentHash, unlessInFlight: false) } + try throwPendingIfInDoubt(paymentHash: paymentHash) throw refusal } catch where isRefusedAtAdmission { // Nothing of this send left. Refused for a Spark send recorded since the checks, its caller gets that @@ -1257,6 +1266,8 @@ class LightningService: NodeLifecycleService { // failed before it recorded its attempt never reached Spark. if let paymentHash, didRecordAttempt { markRailSendUncertain(paymentHash: paymentHash, since: mark) + } else { + try throwPendingIfInDoubt(paymentHash: paymentHash) } throw error } @@ -1610,7 +1621,8 @@ class LightningService: NodeLifecycleService { sats: UInt64?, invoiceCreatedAt: UInt64?, invoiceExpiresAt: Int?, - sendsOverRail: Bool = false + sendsOverRail: Bool = false, + retriesKeyedSend: Bool = true ) async throws -> PaymentHash? { guard let paymentHash else { return nil } var statuses: [PaymentStatus] = rails.contains(.channelFree) && isRailSendInFlight(paymentHash: paymentHash) ? [.pending] : [] @@ -1645,10 +1657,16 @@ class LightningService: NodeLifecycleService { if let payments = await readableRailPayments() { let live = keepRailAttempts(from: payments, since: mark) let payment = ChannelFreeRailPayment.latestOutboundAttempt(payments, paymentHash: paymentHash) - if let payment { + // A send in doubt under its derived key goes out again under that key over Spark, which can't pay twice: + // the operators return the transfer it committed, if any. + let isKeyedRetry = payment?.status != .succeeded + && isKeyedRailSendInDoubt(paymentHash: paymentHash, sendsOverRail: sendsOverRail && retriesKeyedSend) + if let payment, !isKeyedRetry { statuses.append(payment.status) } - if payment == nil || payment?.status == .failed { + if isKeyedRetry { + Logger.info("Retrying '\(paymentHash)' over Spark under its earlier key", context: "LightningService") + } else if payment == nil || payment?.status == .failed { if live.contains(paymentHash.lowercased()) || isRailSendInFlight(paymentHash: paymentHash) { statuses.append(.pending) } else if await !railSyncedSinceUncertainSend(paymentHash: paymentHash) { @@ -1758,6 +1776,16 @@ class LightningService: NodeLifecycleService { Int(clamping: invoiceCreatedAt ?? 0) < restoredAt && invoiceExpiresAt.map { now < $0 } ?? true } + /// Whether a send of `paymentHash` this build made under a derived key is in doubt and none is in flight, so a send + /// over Spark may go out again under that key. + private func isKeyedRailSendInDoubt(paymentHash: String, sendsOverRail: Bool) -> Bool { + guard sendsOverRail, !isRailSendInFlight(paymentHash: paymentHash), + channelFreeRail?.hasKeyedSend(paymentHash: paymentHash) == true + else { return false } + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { uncertainRailSendFailedAt()[hash] != nil } + } + /// Nil while the rail's payments can't be read: listing them failed, or the rail runs here but isn't connected. private func readableRailPayments() async -> [ChannelFreeRailPayment]? { try? await channelFreeRailPayments() @@ -1871,17 +1899,21 @@ class LightningService: NodeLifecycleService { /// Ends the send held since `startedAt` only: once it ended, a retry may hold the invoice again, and that retry stays /// held. - private func endRailSendUncertainty(paymentHash: String, startedAt: Int) { + @discardableResult + private func endRailSendUncertainty(paymentHash: String, startedAt: Int) -> Bool { endRailSendUncertainty(paymentHash: paymentHash) { $0 == startedAt } } - private func endRailSendUncertainty(paymentHash: String, where isEnded: (Int) -> Bool) { + /// Returns whether it ended a hold. + @discardableResult + private func endRailSendUncertainty(paymentHash: String, where isEnded: (Int) -> Bool) -> Bool { let hash = paymentHash.lowercased() - eventCallbackLock.withLock { + return eventCallbackLock.withLock { var uncertain = uncertainRailSendFailedAt() - guard let startedAt = uncertain[hash], isEnded(startedAt) else { return } + guard let startedAt = uncertain[hash], isEnded(startedAt) else { return false } uncertain.removeValue(forKey: hash) railAttemptsStore.set(uncertain, forKey: Self.uncertainRailSendsKey) + return true } } @@ -1927,12 +1959,26 @@ class LightningService: NodeLifecycleService { guard let rail = channelFreeRail ?? channelFreePaymentHistory, await rail.hasSynced(after: UInt64(max(uncertain.startedAt, expiresAt))) else { return false } + // A retry under the send's key, in flight or started since, settles it by its own outcome, or leaves the hold to + // a later sync. + let starts = eventCallbackLock.withLock { railSendsInFlight.contains(hash) ? nil : railSendStarts[hash] ?? 0 } + guard let starts else { return false } // Its Activity row is written first, so a stop in between finds the send held and writes it again. - if let record = railSendExpired, await !record(hash) { - return false + var status = PaymentStatus.failed + if let record = railSendExpired { + guard let recorded = await record(hash) else { return false } + status = recorded } - endRailSendUncertainty(paymentHash: hash, startedAt: uncertain.startedAt) - return true + let didEnd = endRailSendUncertainty(paymentHash: hash) { + $0 == uncertain.startedAt && !railSendsInFlight.contains(hash) && railSendStarts[hash] ?? 0 == starts + } + // Reported as failed, so a send screen left on Pending resolves; a retry in flight reports its own outcome, and + // a send Spark lists paid or pending reports by Spark's own event. + if didEnd, status == .failed, !isRailSendInFlight(paymentHash: hash) { + deliverChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil)) + } + // A hold kept for a retry, or a retry's own, still holds the invoice. + return didEnd || eventCallbackLock.withLock { uncertainRailSendFailedAt()[hash] == nil } } /// Ends the sends Spark never settled whose invoice expired since, once a sync after the grace reached Spark. @@ -1955,17 +2001,30 @@ class LightningService: NodeLifecycleService { sats: sats, invoiceCreatedAt: invoice?.secondsSinceEpoch(), invoiceExpiresAt: expiresAt, - sendsOverRail: true + sendsOverRail: true, + retriesKeyedSend: false ) != nil } + /// A retry of a send still in doubt that never went out leaves that send pending, not failed, as it may have paid: + /// a failure would release its Paykit proof, allowance and QuickPay charge. + private func throwPendingIfInDoubt(paymentHash: String?) throws { + guard let paymentHash, eventCallbackLock.withLock({ uncertainRailSendFailedAt()[paymentHash.lowercased()] != nil }) else { return } + throw Self.pendingDuplicate(paymentHash: paymentHash) + } + private static func pendingDuplicate(paymentHash: String?) -> NodeError { .DuplicatePayment(message: "An earlier attempt to pay '\(paymentHash ?? "")' is still pending") } func beginRailSend(paymentHash: String?) -> Bool { guard let paymentHash else { return true } - return eventCallbackLock.withLock { railSendsInFlight.insert(paymentHash.lowercased()).inserted } + let hash = paymentHash.lowercased() + return eventCallbackLock.withLock { + guard railSendsInFlight.insert(hash).inserted else { return false } + railSendStarts[hash, default: 0] += 1 + return true + } } /// The last check before a send leaves on `rail`, under the same lock that marks the other rail's sends in flight, @@ -2616,6 +2675,17 @@ extension LightningService { callback?(event) } + /// Passes `event` to the app without settling any hold, as for a send whose hold already ended. + private func deliverChannelFreeRailEvent(_ event: Event) { + let callback = eventCallbackLock.withLock { + if storedEventCallback == nil { + pendingChannelFreeRailEvents.append(event) + } + return storedEventCallback + } + callback?(event) + } + func noteAttempt(on rail: LightningPaymentRail, paymentHash: String) { eventCallbackLock.withLock { attemptRails[paymentHash.lowercased()] = rail } } diff --git a/Bitkit/Services/SparkSendKey.swift b/Bitkit/Services/SparkSendKey.swift new file mode 100644 index 000000000..aa09e31e2 --- /dev/null +++ b/Bitkit/Services/SparkSendKey.swift @@ -0,0 +1,103 @@ +import CryptoKit +import Foundation + +/// 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. Android derives the same keys. +enum SparkSendKey { + private static let namespace = UUID(uuidString: "794acd96-39bc-4fd1-a09f-02b269a4a34d")! + private static let label = Data("bitkit spark send key".utf8) + + /// The secret all send keys derive from: an HMAC-SHA256 of a fixed label, keyed with the BIP39 `seed`. + static func secret(seed: Data) -> Data { + Data(HMAC.authenticationCode(for: label, using: SymmetricKey(data: seed))) + } + + /// 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. + static func key(secret: Data, paymentHash: String, attempt: UInt32) -> String { + var name = secret + paymentHash.hexaData + withUnsafeBytes(of: attempt.bigEndian) { name.append(contentsOf: $0) } + var sha1 = Insecure.SHA1() + withUnsafeBytes(of: namespace.uuid) { sha1.update(bufferPointer: $0) } + sha1.update(data: name) + var bytes = Array(sha1.finalize().prefix(16)) + bytes[6] = bytes[6] & 0x0F | 0x50 + bytes[8] = bytes[8] & 0x3F | 0x80 + let uuid = bytes.withUnsafeBytes { $0.loadUnaligned(as: uuid_t.self) } + return UUID(uuid: uuid).uuidString.lowercased() + } +} + +/// The latest attempt at each invoice Spark sent, by payment hash, whose number picks the attempt's `SparkSendKey`. +enum SparkSendAttempts { + private static let storageKey = "sparkSendAttempts" + private static let lock = NSLock() + + private struct Attempt: Codable { + let attempt: UInt32 + let expiresAt: UInt64 + /// The amount the attempt sent; nil for one kept before amounts were. + var amountSats: UInt64? + } + + /// The attempt whose key pays the invoice with `paymentHash`: the latest kept one, past each whose key is in + /// `failedIds`, the ids of the payments Spark lists as failed, as a failed key can't send again. An attempt Spark + /// may still commit keeps its key, so a retry gets back its payment instead of paying again. + static func next(paymentHash: String, secret: Data, failedIds: Set) -> UInt32 { + var attempt = lock.withLock { stored[paymentHash.lowercased()]?.attempt } ?? 0 + while failedIds.contains(SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: attempt)) { + attempt += 1 + } + return attempt + } + + /// The latest attempt kept for the invoice with `paymentHash`, nil before its first. + static func latest(paymentHash: String) -> UInt32? { + lock.withLock { stored[paymentHash.lowercased()]?.attempt } + } + + /// The amount the latest attempt at the invoice with `paymentHash` sent, nil when none was kept with one. + static func latestAmountSats(paymentHash: String) -> UInt64? { + lock.withLock { stored[paymentHash.lowercased()]?.amountSats } + } + + /// Keeps `attempt`, sending `amountSats`, as the latest at the invoice with `paymentHash`, which expires at + /// `expiresAt`, and drops the attempts of invoices expired before `now`, both in epoch seconds. + static func set(paymentHash: String, attempt: UInt32, amountSats: UInt64, expiresAt: UInt64, now: UInt64) { + lock.withLock { + var attempts = stored.filter { $0.value.expiresAt >= now } + attempts[paymentHash.lowercased()] = Attempt(attempt: attempt, expiresAt: expiresAt, amountSats: amountSats) + stored = attempts + } + } + + /// Puts back `attempt` and its `amountSats`, the latest kept before a send whose key never reached Spark, or drops + /// the invoice's entry when it had none. + static func restore(paymentHash: String, attempt: UInt32?, amountSats: UInt64?, expiresAt: UInt64) { + lock.withLock { + var attempts = stored + attempts[paymentHash.lowercased()] = attempt.map { Attempt(attempt: $0, expiresAt: expiresAt, amountSats: amountSats) } + stored = attempts + } + } + + static func clear() { + lock.withLock { UserDefaults.standard.removeObject(forKey: storageKey) } + } + + private static var stored: [String: Attempt] { + get { + UserDefaults.standard.data(forKey: storageKey) + .flatMap { try? JSONDecoder().decode([String: Attempt].self, from: $0) } ?? [:] + } + set { + if let data = try? JSONEncoder().encode(newValue) { + UserDefaults.standard.set(data, forKey: storageKey) + } + } + } +} diff --git a/BitkitTests/ChannelFreeRailTests.swift b/BitkitTests/ChannelFreeRailTests.swift index 76aaab435..637155ce5 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -693,6 +693,203 @@ extension ChannelFreeRailTests { await assertReachesTheNode() } + /// A Spark send whose leaves Spark still can't select after its retries, which may follow a committed transfer. + private func sendInDoubtAfterALeafFailure() async throws { + let expiresAt = try Self.invoiceExpiresAt() + Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt - 600) } + rail.balanceSats = 100_000 + rail.errorAfterSubmission = Bitkit.SparkManager.bolt11SendFailure( + SdkError.SparkError("Tree service error: generic error: Failed to select leaves after all retries"), + isReusedKey: false + ) + do { + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTFail("Expected the send to stay in doubt") + } catch { + XCTAssertFalse(error is Bitkit.ChannelFreeRailSendRefused, "\(error)") + } + rail.errorAfterSubmission = nil + } + + func testASparkSendInDoubtAfterALeafFailureEndsAtItsInvoicesExpiry() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + final class Calls: @unchecked Sendable { var count = 0 } + let calls = Calls() + service.railSendExpired = { _ in + calls.count += 1 + return .failed + } + final class Failures: @unchecked Sendable { var hashes: [String] = [] } + let failures = Failures() + service.setEventCallback { event in + if case let .paymentFailed(_, paymentHash?, _) = event { + failures.hashes.append(paymentHash) + } + } + try await sendInDoubtAfterALeafFailure() + rail.syncedAfter = { _ in true } + + await service.endExpiredRailSendUncertainties() + XCTAssertEqual(calls.count, 0, "a transfer the send committed can still go out") + XCTAssertNotNil(service.railSendHolds[hash]) + + let expiresAt = try Self.invoiceExpiresAt() + service.now = { Date(timeIntervalSince1970: expiresAt) } + await service.endExpiredRailSendUncertainties() + + XCTAssertEqual(calls.count, 1) + XCTAssertNil(service.railSendHolds[hash]) + XCTAssertEqual(failures.hashes, [hash], "a send screen left on Pending never resolves") + } + + func testASparkSendInDoubtSparkListsPaidAtItsInvoicesExpiryReportsNoFailure() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + service.railSendExpired = { _ in .succeeded } + final class Failures: @unchecked Sendable { var hashes: [String] = [] } + let failures = Failures() + service.setEventCallback { event in + if case let .paymentFailed(_, paymentHash?, _) = event { + failures.hashes.append(paymentHash) + } + } + try await sendInDoubtAfterALeafFailure() + rail.syncedAfter = { _ in true } + service.now = { try! Date(timeIntervalSince1970: Self.invoiceExpiresAt()) } + + await service.endExpiredRailSendUncertainties() + + XCTAssertNil(service.railSendHolds[hash]) + XCTAssertEqual(failures.hashes, [], "a paid send was reported failed") + } + + func testASparkSendInDoubtKeepsItsHoldAtExpiryWhileARetryIsInFlight() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + final class Calls: @unchecked Sendable { var count = 0 } + let calls = Calls() + service.railSendExpired = { _ in + calls.count += 1 + return .failed + } + try await sendInDoubtAfterALeafFailure() + rail.syncedAfter = { _ in true } + service.now = { try! Date(timeIntervalSince1970: Self.invoiceExpiresAt()) } + XCTAssertTrue(service.beginRailSend(paymentHash: hash)) + defer { service.endRailSend(paymentHash: hash) } + + await service.endExpiredRailSendUncertainties() + + XCTAssertEqual(calls.count, 0, "the send's row was failed under its retry") + XCTAssertNotNil(service.railSendHolds[hash], "the hold ended under its retry") + } + + func testASparkSendInDoubtKeepsItsHoldWhenARetryStartsAsItsExpiryIsRecorded() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + let service = Bitkit.LightningService.shared + let previousRecord = service.railSendExpired + defer { service.railSendExpired = previousRecord } + service.railSendExpired = { hash in + XCTAssertTrue(service.beginRailSend(paymentHash: hash)) + service.endRailSend(paymentHash: hash) + return .failed + } + final class Failures: @unchecked Sendable { var hashes: [String] = [] } + let failures = Failures() + service.setEventCallback { event in + if case let .paymentFailed(_, paymentHash?, _) = event { + failures.hashes.append(paymentHash) + } + } + try await sendInDoubtAfterALeafFailure() + rail.syncedAfter = { _ in true } + service.now = { try! Date(timeIntervalSince1970: Self.invoiceExpiresAt()) } + + await service.endExpiredRailSendUncertainties() + + XCTAssertNotNil(service.railSendHolds[hash], "the hold ended under the retry") + XCTAssertEqual(failures.hashes, [], "the retry was reported failed") + let payments = try await service.channelFreeRailPayments().filter { $0.paymentHash == hash } + XCTAssertTrue(payments.contains { $0.status == .pending }, "the held send read as settled") + } + + func testASparkRetryOfASendInDoubtRefusedBeforeItGoesOutStaysPending() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + try await sendInDoubtAfterALeafFailure() + rail.keyedSends.insert(hash.lowercased()) + rail.refusal = Bitkit.ChannelFreeRailSendRefused(reason: "short") + + do { + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + XCTFail("Expected the retry to fail") + } catch { + XCTAssertFalse(error is Bitkit.ChannelFreeRailSendRefused, "a refusal releases the held send's proof: \(error)") + } + XCTAssertNotNil(Bitkit.LightningService.shared.railSendHolds[hash]) + } + + func testASparkRetryOfASendInDoubtOverItsFeeLimitStaysPending() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + try await sendInDoubtAfterALeafFailure() + rail.keyedSends.insert(hash.lowercased()) + rail.routingFeeSats = 5 + let limit = RouteParametersConfig( + maxTotalRoutingFeeMsat: 1000, maxTotalCltvExpiryDelta: 1008, maxPathCount: 10, maxChannelSaturationPowerOfHalf: 2 + ) + + do { + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice, params: limit) + XCTFail("Expected the retry to fail") + } catch { + XCTAssertFalse(error is Bitkit.ChannelFreeRailSendRefused, "a refusal releases the held send's proof: \(error)") + } + XCTAssertNotNil(Bitkit.LightningService.shared.railSendHolds[hash]) + } + + func testASparkRetryOfASendInDoubtStoppedBeforeSubmissionStaysPending() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + try await sendInDoubtAfterALeafFailure() + rail.keyedSends.insert(hash.lowercased()) + + do { + _ = try await Bitkit.LightningService.shared.send( + bolt11: Self.invoice, + beforeSubmission: { throw NSError(domain: "request", code: 1) } + ) + XCTFail("Expected the retry to fail") + } catch { + XCTAssertNotEqual((error as NSError).domain, "request", "a request error releases the held send's proof: \(error)") + } + XCTAssertNotNil(Bitkit.LightningService.shared.railSendHolds[hash]) + } + + func testAMoveToSparkForASendInDoubtUnderItsKeyIsRefusedAsPending() async throws { + let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) + try await sendInDoubtAfterALeafFailure() + rail.keyedSends.insert(hash.lowercased()) + + do { + _ = try await Bitkit.LightningService.shared.hasSettledEarlierAttempt(bolt11: Self.invoice, sats: nil) + XCTFail("Expected the move to be refused while the send is in doubt") + } catch {} + } + + func testASparkRetryOfASendInDoubtAfterALeafFailureGoesOutUnderItsKey() async throws { + try await sendInDoubtAfterALeafFailure() + try rail.keyedSends.insert(String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()).lowercased()) + + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + + XCTAssertEqual(rail.sends, 1) + } + func testAnUnknownSparkSendMissingAfterAFreshSyncIsHeldUntilItsInvoiceExpires() async throws { let expiresAt = try Self.invoiceExpiresAt() Bitkit.LightningService.shared.now = { Date(timeIntervalSince1970: expiresAt - 600) } @@ -1738,7 +1935,7 @@ extension ChannelFreeRailTests { service.emitChannelFreeRailEvent(.paymentFailed(paymentId: hash, paymentHash: hash, reason: nil), paymentCreatedAt: Self.sparkNow()) service.now = { Date(timeIntervalSince1970: expiresAt + 5) } try? await sendOverSpark() - return true + return .failed } await service.endExpiredRailSendUncertainties() @@ -1878,6 +2075,15 @@ extension ChannelFreeRailTests { XCTAssertTrue(payments.contains { $0.status == .pending }, "the retry read as A's failure") } + func testASparkSendCheckedAgainBeforeARetryGoesOut() async throws { + rail.balanceSats = 100_000 + rail.submissionChecks = 2 + + _ = try await Bitkit.LightningService.shared.send(bolt11: Self.invoice) + + XCTAssertEqual(rail.sends, 1) + } + func testASparkSendFailingBeforeItRecordsItsAttemptTakesNoHold() async throws { let hash = try String(Bolt11Invoice.fromStr(invoiceStr: Self.invoice).paymentHash()) let service = Bitkit.LightningService.shared @@ -1910,7 +2116,7 @@ extension ChannelFreeRailTests { let calls = Calls() service.railSendExpired = { _ in calls.count += 1 - return true + return .failed } let expiresAt = try Self.invoiceExpiresAt() service.now = { Date(timeIntervalSince1970: expiresAt) } @@ -1959,7 +2165,7 @@ extension ChannelFreeRailTests { written.attempt = SparkManager.expiredSendAttempt( [Self.sparkPayment(hash: hash, status: .failed, timestamp: startedAt - 5)], paymentHash: hash ) { service.isEarlierRailAttempt(paymentHash: $0, createdAt: $1) } - return true + return .failed } let expiresAt = try Self.invoiceExpiresAt() service.now = { Date(timeIntervalSince1970: expiresAt) } @@ -1974,6 +2180,16 @@ extension ChannelFreeRailTests { ) } + func testAnExpiredSendSparkStillListsPendingIsDecidedByThatAttempt() { + let hash = String(repeating: "cd", count: 32) + let pending = Self.sparkPayment(hash: hash, status: .pending, timestamp: 100) + let failed = Self.sparkPayment(hash: hash, status: .failed, timestamp: 200) + + let deciding = SparkManager.expiredSendDecidingAttempt([pending, failed], paymentHash: hash) { _, _ in true } + + XCTAssertEqual(deciding?.status, .pending) + } + func testAnEarlierFailureWhileARetryEntersSparksSendCallStaysOffItsScreen() async throws { let invoice = try Bolt11Invoice.fromStr(invoiceStr: Self.invoice) let hash = String(invoice.paymentHash()) @@ -2307,6 +2523,8 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { var onSend: (() -> Void)? /// Runs as a send is about to be submitted, before `beforeSubmission`. var beforeSubmit: (() -> Void)? + /// How often the send checks `beforeSubmission`, as Spark does again before each retry of the same attempt. + var submissionChecks = 1 /// Thrown after the send was submitted, as when the connection drops inside Spark's send. var errorAfterSubmission: Error? /// Whether the rail's last sync reached it, after the given seconds when there are any. @@ -2319,6 +2537,12 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { /// Whether the invoice carries a Spark address a Spark-preferring send pays directly. var paysBySparkTransfer: Result = .success(false) var sparkTransferChecks = 0 + /// The payment hashes sent under a derived key. + var keyedSends: Set = [] + + func hasKeyedSend(paymentHash: String) -> Bool { + keyedSends.contains(paymentHash.lowercased()) + } func receive(amountSats: UInt64?, description: String, expirySecs: UInt32) async throws -> String { "lnbcrt1fake" @@ -2330,7 +2554,9 @@ private final class FakeRail: Bitkit.ChannelFreeLightningRail { throw refusal } beforeSubmit?() - try beforeSubmission() + for _ in 0 ..< submissionChecks { + try beforeSubmission() + } if let refusalAfterSubmission { throw refusalAfterSubmission } diff --git a/BitkitTests/FailPendingLightningSendTests.swift b/BitkitTests/FailPendingLightningSendTests.swift index da301ad77..8f93ebaaf 100644 --- a/BitkitTests/FailPendingLightningSendTests.swift +++ b/BitkitTests/FailPendingLightningSendTests.swift @@ -37,9 +37,15 @@ final class FailPendingLightningSendTests: XCTestCase { ))) } + var returned: [String: PaymentState?] = [:] for row in rows { - try await activity.failPendingLightningSend(id: row.id) + returned[row.id] = try await activity.failPendingLightningSend(id: row.id) } + XCTAssertEqual(returned["paid-send"], .succeeded) + XCTAssertEqual(returned["pending-send"], .failed) + XCTAssertEqual(returned["pending-receive"], .some(nil)) + let missing = try await activity.failPendingLightningSend(id: "missing") + XCTAssertNil(missing) let expected: [String: PaymentState] = [ "pending-send": .failed, "paid-send": .succeeded, "failed-send": .failed, "pending-receive": .pending, diff --git a/BitkitTests/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift new file mode 100644 index 000000000..a1c6fd1f4 --- /dev/null +++ b/BitkitTests/SparkSendKeyTests.swift @@ -0,0 +1,237 @@ +@testable import Bitkit +import BreezSdkSpark +import XCTest + +final class SparkSendKeyTests: XCTestCase { + /// The BIP39 seed of `abandon … about` with passphrase `TREZOR`, from the BIP39 test vectors. + private let seed = ( + "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a6987599d18264c1e1c92f2c" + + "f141630c7a3c4ab7c81b2f001698e7463b04" + ).hexaData + /// Bytes 0 to 31. + private let paymentHash = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + + /// The host app's saved attempts, put back after each test. + private var savedAttempts: Data? + + override func setUp() { + super.setUp() + savedAttempts = UserDefaults.standard.data(forKey: "sparkSendAttempts") + SparkSendAttempts.clear() + } + + override func tearDown() { + UserDefaults.standard.set(savedAttempts, forKey: "sparkSendAttempts") + super.tearDown() + } + + /// The same vector is asserted by Android's `SparkSendKeyTest`, so a wallet restored on the other app derives the + /// same keys. + func testDerivesTheSharedTestVector() { + let secret = SparkSendKey.secret(seed: seed) + + XCTAssertEqual(secret.hex, "577ceb10411255cef07e3f49bd7e5239de07586c7457f65ee72ee53737361a98") + XCTAssertEqual(SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: 0), "8d92d8bf-76f3-56fe-8958-8e440acb64fc") + XCTAssertEqual(SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: 1), "712dea1f-8268-5e52-a280-aac86bc60b59") + } + + func testReadsThePaymentHashInEitherCase() { + let secret = SparkSendKey.secret(seed: seed) + + XCTAssertEqual( + SparkSendKey.key(secret: secret, paymentHash: paymentHash.uppercased(), attempt: 0), + SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: 0) + ) + } + + func testAFirstAttemptTakesTheFirstKey() { + let secret = SparkSendKey.secret(seed: seed) + + XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: []), 0) + } + + func testARetryReusesItsAttemptsKeyUntilSparkListsThatAttemptFailed() { + let secret = SparkSendKey.secret(seed: seed) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 1, amountSats: 1000, expiresAt: 2000, now: 1000) + let firstFailed: Set = [SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: 0)] + + XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: firstFailed), 1) + } + + func testARetryTakesTheNextKeyOnceSparkListsItsAttemptFailed() { + let secret = SparkSendKey.secret(seed: seed) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 0, amountSats: 1000, expiresAt: 2000, now: 1000) + let failed = Set([0, 1].map { SparkSendKey.key(secret: secret, paymentHash: paymentHash, attempt: $0) }) + + XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: failed), 2) + } + + func testAnExpiredInvoicesAttemptIsDropped() { + let secret = SparkSendKey.secret(seed: seed) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 3, amountSats: 1000, expiresAt: 1500, now: 1000) + SparkSendAttempts.set(paymentHash: String(repeating: "ab", count: 32), attempt: 0, amountSats: 1000, expiresAt: 3000, now: 2000) + + XCTAssertEqual(SparkSendAttempts.next(paymentHash: paymentHash, secret: secret, failedIds: []), 0) + } + + func testAShortBalanceUnderAReusedKeyStaysInDoubt() { + let shortBalance = SdkError.InsufficientFunds(tokenIdentifier: nil) + + // An earlier attempt under the key may have committed a transfer, which Spark returns once it can pick leaves. + let reused = Bitkit.SparkManager.bolt11SendFailure(shortBalance, isReusedKey: true) + let fresh = Bitkit.SparkManager.bolt11SendFailure(shortBalance, isReusedKey: false) + + XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") + XCTAssertTrue(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") + } + + func testLeavesSparkCantSelectKeepTheSendInDoubtUnderAnyKey() { + // The SDK selects leaves again after an operator error, so the failure can follow a committed transfer. + let reused = Bitkit.SparkManager.bolt11SendFailure(leafSelectionFailure, isReusedKey: true) + let fresh = Bitkit.SparkManager.bolt11SendFailure(leafSelectionFailure, isReusedKey: false) + + XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") + XCTAssertFalse(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") + } + + func testAnExpiryUnderAReusedKeyKeepsTheSendInDoubt() { + // The attempt that used the key may have committed a transfer before the invoice expired. + let expired = SdkError.InvalidInput("invoice has expired") + + let reused = Bitkit.SparkManager.bolt11SendFailure(expired, isReusedKey: true) + let fresh = Bitkit.SparkManager.bolt11SendFailure(expired, isReusedKey: false) + + XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") + XCTAssertTrue(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") + } + + func testANewKeyWaitsWhileTheEarlierAttemptIsInDoubt() { + XCTAssertTrue(Bitkit.SparkManager.waitsForHold(isReusedKey: false, isInDoubt: true, changesAmount: false)) + XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: true, isInDoubt: true, changesAmount: false)) + XCTAssertFalse(Bitkit.SparkManager.waitsForHold(isReusedKey: false, isInDoubt: false, changesAmount: false)) + } + + func testAReusedKeyAtAnotherAmountWaits() { + XCTAssertTrue(Bitkit.SparkManager.waitsForHold(isReusedKey: true, isInDoubt: true, changesAmount: true)) + } + + func testAnExpiredSendAlreadyPaidStaysPaid() { + XCTAssertEqual(Bitkit.SparkManager.expiredSendStatus(stored: .succeeded), .succeeded) + XCTAssertEqual(Bitkit.SparkManager.expiredSendStatus(stored: .failed), .failed) + XCTAssertEqual(Bitkit.SparkManager.expiredSendStatus(stored: nil), .failed) + } + + func testAFailedPaymentSparkReturnsIsRefused() { + XCTAssertThrowsError(try Bitkit.SparkManager.checkSentPayment(.failed)) { + XCTAssertTrue($0 is Bitkit.ChannelFreeRailSendRefused, "\($0)") + } + XCTAssertNoThrow(try Bitkit.SparkManager.checkSentPayment(.pending)) + XCTAssertNoThrow(try Bitkit.SparkManager.checkSentPayment(.completed)) + } + + func testAnInvoiceExpiringDuringALeafRetryEndsWithTheLeafFailure() async { + var sends = 0 + + do { + _ = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { true }) { + sends += 1 + if sends == 1 { + throw leafSelectionFailure + } + throw SdkError.InvalidInput("invoice has expired") + } + XCTFail("Expected the send to fail") + } catch { + XCTAssertTrue(Bitkit.SparkManager.isLeafSelectionFailure(error), "\(error)") + } + } + + func testAShortBalanceOnALeafRetryEndsWithTheLeafFailure() async { + var sends = 0 + + do { + _ = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { true }) { + sends += 1 + if sends == 1 { + throw leafSelectionFailure + } + throw SdkError.InsufficientFunds(tokenIdentifier: nil) + } + XCTFail("Expected the send to fail") + } catch { + XCTAssertTrue(Bitkit.SparkManager.isLeafSelectionFailure(error), "\(error)") + } + } + + func testASendRetriesWhileSparkCantSelectItsLeaves() async throws { + var sends = 0 + + let sent = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { true }) { + sends += 1 + if sends == 1 { + throw leafSelectionFailure + } + return "sent" + } + + XCTAssertEqual(sent, "sent") + XCTAssertEqual(sends, 2) + } + + func testASendStopsRetryingOnceItCanNoLongerGo() async { + var sends = 0 + + do { + _ = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { false }) { + sends += 1 + throw leafSelectionFailure + } + XCTFail("the send went out") + } catch { + XCTAssertTrue(Bitkit.SparkManager.isLeafSelectionFailure(error), "\(error)") + } + XCTAssertEqual(sends, 1) + } + + func testASendStopsRetryingAfterItsLastRetry() async { + var sends = 0 + + do { + _ = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { true }) { + sends += 1 + throw leafSelectionFailure + } + XCTFail("the send went out") + } catch { + XCTAssertTrue(Bitkit.SparkManager.isLeafSelectionFailure(error), "\(error)") + } + XCTAssertEqual(sends, 1 + Bitkit.SparkManager.leafSelectionRetries) + } + + func testASendIsNotRetriedForOtherFailures() async { + var sends = 0 + + do { + _ = try await Bitkit.SparkManager.sendRetryingLeafSelection(retryDelay: .zero, canRetry: { true }) { + sends += 1 + throw SdkError.InsufficientFunds(tokenIdentifier: nil) + } + XCTFail("the send went out") + } catch {} + XCTAssertEqual(sends, 1) + } + + func testARefusedAttemptGivesBackTheEarlierOne() { + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 1, amountSats: 1000, expiresAt: 2000, now: 1000) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 2, amountSats: 2000, expiresAt: 2000, now: 1000) + + SparkSendAttempts.restore(paymentHash: paymentHash, attempt: 1, amountSats: 1000, expiresAt: 2000) + XCTAssertEqual(SparkSendAttempts.latest(paymentHash: paymentHash), 1) + XCTAssertEqual(SparkSendAttempts.latestAmountSats(paymentHash: paymentHash), 1000) + + SparkSendAttempts.restore(paymentHash: paymentHash, attempt: nil, amountSats: nil, expiresAt: 2000) + XCTAssertNil(SparkSendAttempts.latest(paymentHash: paymentHash)) + } + + private let leafSelectionFailure = SdkError.SparkError("Tree service error: generic error: Failed to select leaves after all retries") +} diff --git a/changelog.d/next/1412.fixed.md b/changelog.d/next/1412.fixed.md new file mode 100644 index 000000000..e30693907 --- /dev/null +++ b/changelog.d/next/1412.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.