diff --git a/Bitkit/Managers/SparkManager.swift b/Bitkit/Managers/SparkManager.swift index fa0ded4bc..b2c61e751 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 @@ -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?() @@ -691,18 +698,50 @@ 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 isReusedKey = previousAttempt == attempt + 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, 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, expiresAt: expiresAt) } + throw refusal } Logger.info("Sent Spark payment '\(response.payment.id)' with status '\(response.payment.status)'", context: "SparkManager") return invoiceDetails.paymentHash @@ -721,6 +760,51 @@ final class SparkManager: ChannelFreeLightningRail { return !overflow && total <= balanceSats } + /// 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 or leaves Spark can't select left nothing under a new key. Under a key an + /// earlier attempt used, either can hide the transfer that attempt committed: the send stays in doubt until Spark + /// syncs, rather than refused. + nonisolated static func bolt11SendFailure(_ error: Error, isReusedKey: Bool) -> Error { + if isReusedKey, case SdkError.InsufficientFunds = error { + return error + } + if isLeafSelectionFailure(error) { + return isReusedKey ? error : ChannelFreeRailSendRefused(reason: t("wallet__payment_failed_description"), underlying: 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. + 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 { + 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. diff --git a/Bitkit/Services/LightningService.swift b/Bitkit/Services/LightningService.swift index 78a1b612b..465384034 100644 --- a/Bitkit/Services/LightningService.swift +++ b/Bitkit/Services/LightningService.swift @@ -1217,6 +1217,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 { diff --git a/Bitkit/Services/SparkSendKey.swift b/Bitkit/Services/SparkSendKey.swift new file mode 100644 index 000000000..02bc95890 --- /dev/null +++ b/Bitkit/Services/SparkSendKey.swift @@ -0,0 +1,96 @@ +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 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 } + } + + /// Keeps `attempt` 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, expiresAt: UInt64, now: UInt64) { + lock.withLock { + var attempts = stored.filter { $0.value.expiresAt >= now } + attempts[paymentHash.lowercased()] = Attempt(attempt: attempt, expiresAt: expiresAt) + stored = attempts + } + } + + /// Puts back `attempt`, 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?, expiresAt: UInt64) { + lock.withLock { + var attempts = stored + attempts[paymentHash.lowercased()] = attempt.map { Attempt(attempt: $0, expiresAt: expiresAt) } + 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..4ff339477 100644 --- a/BitkitTests/ChannelFreeRailTests.swift +++ b/BitkitTests/ChannelFreeRailTests.swift @@ -1878,6 +1878,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 @@ -2307,6 +2316,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. @@ -2330,7 +2341,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/SparkSendKeyTests.swift b/BitkitTests/SparkSendKeyTests.swift new file mode 100644 index 000000000..4ce26eb33 --- /dev/null +++ b/BitkitTests/SparkSendKeyTests.swift @@ -0,0 +1,162 @@ +@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" + + override func setUp() { + super.setUp() + SparkSendAttempts.clear() + } + + override func tearDown() { + SparkSendAttempts.clear() + 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, 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, 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, expiresAt: 1500, now: 1000) + SparkSendAttempts.set(paymentHash: String(repeating: "ab", count: 32), attempt: 0, 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 testLeavesSparkCantSelectAreRefusedUnderANewKeyOnly() { + let reused = Bitkit.SparkManager.bolt11SendFailure(leafSelectionFailure, isReusedKey: true) + let fresh = Bitkit.SparkManager.bolt11SendFailure(leafSelectionFailure, isReusedKey: false) + + XCTAssertFalse(reused is Bitkit.ChannelFreeRailSendRefused, "\(reused)") + XCTAssertTrue(fresh is Bitkit.ChannelFreeRailSendRefused, "\(fresh)") + } + + 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, expiresAt: 2000, now: 1000) + SparkSendAttempts.set(paymentHash: paymentHash, attempt: 2, expiresAt: 2000, now: 1000) + + SparkSendAttempts.restore(paymentHash: paymentHash, attempt: 1, expiresAt: 2000) + XCTAssertEqual(SparkSendAttempts.latest(paymentHash: paymentHash), 1) + + SparkSendAttempts.restore(paymentHash: paymentHash, attempt: 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.