Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
e2ac44a
fix: reuse a spark send's key across retries
ovitrif Nov 24, 2026
b7eb6f3
fix: retry a spark send whose leaves spark can't select
ovitrif Nov 25, 2026
e15f481
fix: keep a spark send attempt only once it is admitted
ovitrif Nov 25, 2026
91da213
test: keep the host app's spark send attempts
ovitrif Nov 25, 2026
f9d1105
fix: keep the node off a refused spark send until spark syncs
ovitrif Nov 25, 2026
d55ca61
test: cover the refusal of a spark send that may have reached spark
ovitrif Nov 25, 2026
bfd6edd
fix: keep a spark send that may have reached spark uncertain in payki…
ovitrif Nov 25, 2026
72c94fd
fix: show a refused spark send pending until spark syncs
ovitrif Nov 25, 2026
45950e2
fix: refuse a spark send whose payment comes back failed
ovitrif Nov 25, 2026
05cf2c1
fix: keep the node off a refused spark send until its invoice expires
ovitrif Nov 25, 2026
87e5a6d
fix: refuse a node send of an invoice a refused spark send may still pay
ovitrif Nov 25, 2026
a7f3a67
fix: keep a refused spark send pending until a sync after its invoice…
ovitrif Nov 25, 2026
e4d3ce5
fix: keep a spark send in doubt when spark can't select its leaves
ovitrif Nov 25, 2026
ec69f99
fix: end a held spark send at its invoice's expiry
ovitrif Nov 25, 2026
f5463f1
fix: keep a spark send in doubt through a retry that never goes out
ovitrif Nov 25, 2026
e280c95
fix: read any retry of a spark send in doubt that never left as pending
ovitrif Nov 25, 2026
7313885
fix: settle a spark send in doubt before a new key's retry
ovitrif Nov 25, 2026
0883b1c
fix: record a paid attempt when a spark send in doubt expires
ovitrif Nov 25, 2026
62a7f09
fix: keep a paid spark send paid at expiry
ovitrif Nov 26, 2026
c5ea2db
fix: let a pending spark attempt decide an expired send
ovitrif Nov 26, 2026
ac556ad
fix: keep a spark hold at expiry while its retry is in flight
ovitrif Nov 26, 2026
f758f5d
fix: keep a spark hold when a retry starts as its expiry is recorded
ovitrif Nov 26, 2026
3c465d3
fix: read a spark send held for its retry as pending
ovitrif Nov 26, 2026
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
203 changes: 186 additions & 17 deletions Bitkit/Managers/SparkManager.swift

Large diffs are not rendered by default.

11 changes: 7 additions & 4 deletions Bitkit/Services/CoreService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand Down
100 changes: 85 additions & 15 deletions Bitkit/Services/LightningService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<String> = []
/// 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] = [:]
Expand All @@ -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
Expand Down Expand Up @@ -1197,13 +1201,15 @@ 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
)
}
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"))
}
}
Expand All @@ -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 {
Expand All @@ -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
Expand All @@ -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
}
Expand Down Expand Up @@ -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] : []
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
}
}

Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -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 }
}
Expand Down
103 changes: 103 additions & 0 deletions Bitkit/Services/SparkSendKey.swift
Original file line number Diff line number Diff line change
@@ -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<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 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<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 }
}

/// 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)
}
}
}
}
Loading
Loading