Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
a2a5955
fix: move to spark row, re-check and kept hashes
ovitrif Nov 17, 2026
7936297
fix: spark claim poll, exit backup, retry hold and key check
ovitrif Nov 17, 2026
3c61996
fix: move to spark rows kept across restore, spark copy translated
ovitrif Nov 17, 2026
0f7b28c
fix: spark exit data kept on every rejection, retry hold safe from cl…
ovitrif Nov 17, 2026
c291ee9
fix: rejected spark exit data kept when another device replaced the b…
ovitrif Nov 17, 2026
abc9d3c
fix: rejected spark exit copies never overwrite each other
ovitrif Nov 17, 2026
6550469
fix: retry hold kept when a spark failure races the retry
ovitrif Nov 17, 2026
83ff4b2
fix: spark failure ends a retry's hold only by its own payment id
ovitrif Nov 17, 2026
874e471
fix: spark send activity settles when its hold expires
ovitrif Nov 17, 2026
2d84e2d
fix: expired spark hold retries its activity write until saved
ovitrif Nov 17, 2026
d7cefc6
fix: spark early claim capped at the approved fee
ovitrif Nov 17, 2026
72fe952
fix: spark exit backup from another device restored before replaced
ovitrif Nov 17, 2026
cb55e29
fix: spark retry and exit backup keep what they must recover
ovitrif Nov 17, 2026
f9fa2c2
fix: move to spark stays offered while a move awaits its result
ovitrif Nov 17, 2026
dffd284
fix: spark retry spark took holds the node until spark lists it
ovitrif Nov 18, 2026
4d5f4eb
fix: spark exit restore logs the data staged, not restored
ovitrif Nov 18, 2026
3364843
fix: startup sync keeps the hold on a retry spark took
ovitrif Nov 19, 2026
ee309f1
fix: app status opens spark's detail offline
ovitrif Nov 19, 2026
6c1c0ad
fix: an expired hold writes a live retry over a tied failure
ovitrif Nov 19, 2026
50e7c1c
fix: exit data network, move backup mark and exit expiry
ovitrif Nov 19, 2026
da75b3c
fix: release the early claim cap when the claim poll gives up
ovitrif Nov 19, 2026
b24d06c
fix: hold a taken spark retry by its own id
ovitrif Nov 19, 2026
ba074c9
fix: hold a send in doubt against a failure its list didn't name
ovitrif Nov 19, 2026
3ced5ab
fix: a send in doubt's own failure ends its hold again
ovitrif Nov 19, 2026
767c9cb
fix: end an unlisted taken retry only after a full sync
ovitrif Nov 19, 2026
2500d31
fix: keep a held spark send's row and hold until reconciled
ovitrif Nov 19, 2026
5b35eb6
fix: a failed spark row takes its own attempt's updates
ovitrif Nov 19, 2026
4b79feb
fix: a failed spark row keeps its attempt in a same-second tie
ovitrif Nov 19, 2026
a19bd85
fix: a held spark retry's own failure always takes its row
ovitrif Nov 19, 2026
059c82f
fix: settle a spark send in doubt only after a post-grace sync
ovitrif Nov 19, 2026
713a882
fix: keep exit data staged while a rejected copy is set aside
ovitrif Nov 19, 2026
eacd614
fix: keep a spark send's earlier attempts past its hold
ovitrif Nov 20, 2026
3c71588
fix: a spark row failed in place drops its attempt id
ovitrif Nov 20, 2026
843a182
fix: a held spark row failed in place takes its own attempt id
ovitrif Nov 20, 2026
352b311
fix: a spark row its earlier payment still owns keeps its writer
ovitrif Nov 20, 2026
8569ffd
fix: keep a spark row's writer before writing the row
ovitrif Nov 20, 2026
bc928fe
fix: a spark row resolves to its writer after a stop
ovitrif Nov 20, 2026
c67bb22
fix: spark keeps a retried send's row writer
ovitrif Nov 20, 2026
48d8662
fix: spark caps row writers of plain sends only
ovitrif Nov 20, 2026
254d8ce
fix: spark expiry sweeps queue the row update first
ovitrif Nov 20, 2026
c877bfb
fix: spark reads a held send as pending
ovitrif Nov 20, 2026
5d2569e
fix: spark ends a hold with its attempt record
ovitrif Nov 20, 2026
1525e18
fix: spark keeps a settled send settled
ovitrif Nov 20, 2026
41ac395
fix: spark reads a settled send's outcome
ovitrif Nov 20, 2026
349ea4d
fix: spark claims early only up to the shown fee
ovitrif Nov 20, 2026
9c92322
fix: spark orders a same-second retry past its hold
ovitrif Nov 20, 2026
c46a805
fix: spark orders two earlier attempts by date
ovitrif Nov 20, 2026
f5a0cce
fix: spark settles a send by its call's result
ovitrif Nov 20, 2026
a70b813
fix: spark orders kept attempts by send
ovitrif Nov 20, 2026
6450286
fix: spark dates decide between kept attempts
ovitrif Nov 20, 2026
496e01c
fix: spark replays a failure held during its send call
ovitrif Nov 20, 2026
081bfdc
fix: spark settles a held failure once
ovitrif Nov 20, 2026
a0ba3e1
fix: spark holds a retry until its send settles
ovitrif Nov 20, 2026
0bec176
fix: spark keeps the later failed attempt's row
ovitrif Nov 20, 2026
0ab63c1
fix: spark keeps an earlier failure off a retry not yet submitted
ovitrif Nov 21, 2026
b0e4767
fix: spark keeps a retry's hold when an earlier send settles
ovitrif Nov 21, 2026
ce17547
fix: spark keeps an earlier failure off a retry's screen
ovitrif Nov 21, 2026
af3eb29
fix: spark dates a retry after the failures it knows
ovitrif Nov 21, 2026
ffd8818
fix: spark dates a retry past now when it can't list
ovitrif Nov 21, 2026
e87975a
fix: spark refuses a send it can't date
ovitrif Nov 21, 2026
c99c294
fix: spark refuses an undated restored invoice as unverified
ovitrif Nov 21, 2026
7bfe23f
fix: spark retry success during a list read stays pending
ovitrif Nov 23, 2026
41ed0d3
fix: spark held send stays pending without its listed result
ovitrif Nov 23, 2026
befad53
fix: drop duplicate spark exit locale keys
ovitrif Nov 24, 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
2 changes: 1 addition & 1 deletion Bitkit.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if [ \"$CONFIGURATION\" = \"Release\" ] && [ -z \"$(echo \"${BREEZ_API_KEY}\" | tr -d ' ')\" ] && ! /usr/bin/security find-generic-password -a \"$USER\" -s BREEZ_API_KEY >/dev/null 2>&1; then\n echo \"error: BREEZ_API_KEY is empty. Store it in the keychain item BREEZ_API_KEY or set it in Secrets.xcconfig before a Release build or archive (Docs/RELEASE.md).\"\n exit 1\nfi\n";
shellScript = "# Reads the keychain value only to test it for blank, so a missing, blank or unreadable (locked) item fails here,\n# before the target compiles. The value is never printed.\nif [ \"$CONFIGURATION\" = \"Release\" ] && [ -z \"$(echo \"${BREEZ_API_KEY}\" | tr -d ' ')\" ] \\\n && [ -z \"$(/usr/bin/security find-generic-password -a \"$USER\" -s BREEZ_API_KEY -w 2>/dev/null | tr -d '[:space:]')\" ]; then\n echo \"error: BREEZ_API_KEY is empty. Store it in the keychain item BREEZ_API_KEY (unlocked, not blank) or set it in Secrets.xcconfig before a Release build or archive (Docs/RELEASE.md).\"\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
B17C0F1A2EAE000000000003 /* Breez API Key From Keychain */ = {
Expand Down
118 changes: 100 additions & 18 deletions Bitkit/Managers/MoveToSparkManager.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import BitkitCore
import Combine
import Foundation
import LDKNode

/// The amounts behind moving the channels' balance to Spark, kept apart so they can be tested without a node.
enum MoveToSparkMath {
/// The move invoice's description.
static let invoiceDescription = "Move to Spark"
/// Below this a move is not offered: what is left is about the routing fee.
static let minMoveSats: UInt64 = 1000
/// The fee guessed for the first quote of a full move, as a share of the amount in parts per million.
Expand Down Expand Up @@ -72,6 +76,15 @@ struct MoveToSparkQuote: Equatable {
let feeSats: UInt64
}

@MainActor
extension LightningActivity {
/// The channel send of a move to Spark, which Activity shows as a transfer rather than a payment. Known by its payment
/// hash, so a paid outside invoice that happens to carry the move's description stays a payment.
var isMoveToSpark: Bool {
txType == .sent && MoveToSparkPayments.contains(id)
}
}

enum MoveToSparkError: Error {
case nothingToMove
case sparkUnavailable
Expand All @@ -80,20 +93,91 @@ enum MoveToSparkError: Error {
}

/// The payments that move a channel balance to Spark, whose send and receive the app does not announce as payments.
/// Kept on disk until a wipe and in the metadata backup, so a move that settles after a relaunch, and its Activity row after
/// a restore, stay known as one.
@MainActor
enum MoveToSparkPayments {
private static var paymentHashes = Set<String>()
private static let storageKey = "moveToSparkPaymentHashes"
static var defaults: UserDefaults = .standard {
didSet { cached = nil }
}

/// Read once, as Activity asks for every row it draws.
private static var cached: [String: Double]?
/// Outside the main actor, so the backup observers can subscribe from anywhere.
nonisolated static var savedPublisher: AnyPublisher<Void, Never> {
MoveToSparkPaymentsSaved.subject.eraseToAnyPublisher()
}

static func insert(_ paymentHash: String, now: Date = Date()) {
var hashes = stored
hashes[paymentHash.lowercased()] = now.timeIntervalSince1970
save(hashes)
MoveToSparkPaymentsSaved.subject.send()
}

/// Sorted, so an unchanged store backs up byte for byte the same.
static func backupSnapshot() -> [String] {
stored.keys.sorted()
}

static func insert(_ paymentHash: String) {
paymentHashes.insert(paymentHash.lowercased())
/// Adds the restored hashes to any already known.
static func restore(_ paymentHashes: [String]?, now: Date = Date()) {
guard let paymentHashes, !paymentHashes.isEmpty else { return }
var hashes = stored
for hash in paymentHashes where hashes[hash.lowercased()] == nil {
hashes[hash.lowercased()] = now.timeIntervalSince1970
}
save(hashes)
}

static func contains(_ paymentHash: String?) -> Bool {
paymentHash.map { paymentHashes.contains($0.lowercased()) } ?? false
paymentHash.map { stored[$0.lowercased()] != nil } ?? false
}

private static func save(_ hashes: [String: Double]) {
defaults.set(hashes, forKey: storageKey)
cached = hashes
}

static func removeAll() {
paymentHashes.removeAll()
defaults.removeObject(forKey: storageKey)
cached = nil
}

private static var stored: [String: Double] {
if let cached {
return cached
}
let hashes = defaults.dictionary(forKey: storageKey) as? [String: Double] ?? [:]
cached = hashes
return hashes
}
}

private enum MoveToSparkPaymentsSaved {
static let subject = PassthroughSubject<Void, Never>()
}

/// What a move quote needs from Spark and the channels, apart so the quote can be tested without either.
protocol MoveToSparkServices {
@MainActor var isSparkUsable: Bool { get }
func receiveInvoice(description: String, expirySecs: UInt32) async throws -> String
/// The routing fee LDK estimates for paying `bolt11` with `amountSats` over the channels only.
func estimateChannelFee(bolt11: String, amountSats: UInt64) async throws -> UInt64
}

struct LiveMoveToSparkServices: MoveToSparkServices {
@MainActor var isSparkUsable: Bool {
MoveToSparkMath.isSparkUsable(SparkManager.shared)
}

func receiveInvoice(description: String, expirySecs: UInt32) async throws -> String {
try await SparkManager.shared.receive(amountSats: nil, description: description, expirySecs: expirySecs)
}

func estimateChannelFee(bolt11: String, amountSats: UInt64) async throws -> UInt64 {
try await LightningService.shared.estimateRoutingFees(bolt11: bolt11, amountSats: amountSats, channelsOnly: true)
}
}

Expand Down Expand Up @@ -134,7 +218,6 @@ final class MoveToSparkManager {
/// Shared so a move and its outcome outlive the screen, which is rebuilt when the app is unlocked.
static let shared = MoveToSparkManager()

private static let invoiceDescription = "Move to Spark"
private static let invoiceExpirySecs: UInt32 = 3600
private static let maxQuoteRounds = 4

Expand All @@ -147,12 +230,15 @@ final class MoveToSparkManager {
/// A swiped payment that has not settled yet; leaving the screen keeps it, so it is never quoted over.
private var isMoveInFlight = false

private let lightningService: LightningService
private let spark: SparkManager
/// A move is kept for its result, so its screen stays reachable while the channels have nothing left to move.
var keepsMoveForItsResult: Bool {
keepsOutcome || isMoveInFlight
}

private let services: any MoveToSparkServices

init() {
lightningService = .shared
spark = .shared
init(services: any MoveToSparkServices = LiveMoveToSparkServices()) {
self.services = services
}

/// Opens the screen: quotes a new move, unless a quote is still running or a move started earlier is still running
Expand Down Expand Up @@ -266,20 +352,16 @@ final class MoveToSparkManager {
guard wantedSats >= MoveToSparkMath.minMoveSats, MoveToSparkMath.hasMovableBalance(limitSats: limitSats) else {
throw MoveToSparkError.nothingToMove
}
guard MoveToSparkMath.isSparkUsable(spark) else { throw MoveToSparkError.sparkUnavailable }
guard services.isSparkUsable else { throw MoveToSparkError.sparkUnavailable }

let invoice = try await spark.receive(
amountSats: nil,
description: Self.invoiceDescription,
expirySecs: Self.invoiceExpirySecs
)
let invoice = try await services.receiveInvoice(description: MoveToSparkMath.invoiceDescription, expirySecs: Self.invoiceExpirySecs)
var amountSats = MoveToSparkMath.firstCandidate(wantedSats: wantedSats, limitSats: limitSats)
var fitting: MoveToSparkQuote?
// The first amount leaves room for a guessed fee; once the real fee is known, the amount grows to fit it.
for _ in 0 ..< Self.maxQuoteRounds where amountSats >= MoveToSparkMath.minMoveSats {
let estimateSats: UInt64
do {
estimateSats = try await lightningService.estimateRoutingFees(bolt11: invoice, amountSats: amountSats, channelsOnly: true)
estimateSats = try await services.estimateChannelFee(bolt11: invoice, amountSats: amountSats)
} catch {
if let fitting {
return fitting
Expand Down
Loading
Loading