Skip to content
Open
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
104 changes: 94 additions & 10 deletions Bitkit/Managers/SparkManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = []
@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.
Expand Down Expand Up @@ -220,6 +222,7 @@ final class SparkManager: ChannelFreeLightningRail {
try? await sdk.disconnect()
}
sdk = nil
sendKeySecret = nil
listenerId = nil
do {
let generation = connectGeneration
Expand Down Expand Up @@ -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)
Expand All @@ -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()
Expand Down Expand Up @@ -603,6 +608,7 @@ final class SparkManager: ChannelFreeLightningRail {
}
}
sdk = nil
sendKeySecret = nil
listenerId = nil
refreshAgain = false
activitiesSynced = false
Expand All @@ -626,6 +632,7 @@ final class SparkManager: ChannelFreeLightningRail {
unsavedPayments = []
sentWithdrawalTxIds = []
preparedWithdrawal = nil
SparkSendAttempts.clear()
Self.pendingContactWithdrawal = nil
Self.contactWithdrawalTxIds = []
onStateChanged?()
Expand Down Expand Up @@ -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
Expand All @@ -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)
Comment on lines +771 to +772

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep potentially committed leaf-selection failures uncertain

If a first send commits a transfer but encounters an operator error, the SDK's internal with_leafs_spent_retry! can perform leaf selection again and fail—the scenario explicitly acknowledged in this commit's Gaps. Consequently, a leaf-selection error does not prove that a fresh key never reached the operators. Here isReusedKey remains false throughout that send and its retries, so the error becomes ChannelFreeRailSendRefused. LightningService.send then clears the uncertainty and releases the recorded attempt, allowing a subsequent payment over LDK before Spark sync exposes the committed transfer. Preserve the uncertain outcome unless there is proof that no operator submission occurred; the same-key retry alone does not protect a later send over another rail.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, this can happen in 0.28.3. If a submission's response is lost, with_leafs_spent_retry! retries it, can then get a leaves-spent error and refresh the leaves, and selecting again can fail after the first try committed. A short balance after such a retry has the same gap, and master already refuses that under a new key.

Holding every fresh-key leaf-selection failure in doubt brings back the endless Pending this change fixes (a payment right after a move to Spark). Holding only the node rail for that invoice until Spark syncs, while the send shows failed, keeps both cases safe. That needs a decision on the trade first; this thread stays open until then.

}
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<T>(
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.
Expand Down
2 changes: 2 additions & 0 deletions Bitkit/Services/LightningService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
96 changes: 96 additions & 0 deletions Bitkit/Services/SparkSendKey.swift
Original file line number Diff line number Diff line change
@@ -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<SHA256>.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<String>) -> 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)
}
}
}
}
15 changes: 14 additions & 1 deletion BitkitTests/ChannelFreeRailTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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
}
Expand Down
Loading
Loading