From c049acec62c0035c1d28994428e0bb30b17742b5 Mon Sep 17 00:00:00 2001 From: coreyphillips Date: Fri, 20 Nov 2026 16:33:44 -0500 Subject: [PATCH] feat: resume unfinished swaps until their claim confirms --- Bitkit/AppScene.swift | 3 + Bitkit/Services/PubkySwapsRouteService.swift | 124 +++++---- Bitkit/Services/PubkySwapsTracker.swift | 245 ++++++++++++++++++ Bitkit/Utilities/AppReset.swift | 1 + .../Wallets/Send/SendConfirmationView.swift | 27 +- BitkitTests/PubkySwapsTrackerTests.swift | 217 ++++++++++++++++ 6 files changed, 549 insertions(+), 68 deletions(-) create mode 100644 Bitkit/Services/PubkySwapsTracker.swift create mode 100644 BitkitTests/PubkySwapsTrackerTests.swift diff --git a/Bitkit/AppScene.swift b/Bitkit/AppScene.swift index 0647db8fd0..732ea930f3 100644 --- a/Bitkit/AppScene.swift +++ b/Bitkit/AppScene.swift @@ -1191,6 +1191,9 @@ struct AppScene: View { // Open the swap updates stream so any pending LN -> onchain swaps resume // and auto-claim once their lockup confirms. Retries until the stream starts. wallet.ensureSwapUpdatesRunning() + if PubkySwapsRouteService.isEnabled { + await PubkySwapsRouteService.resumeUnfinishedSwaps() + } // Schedule full backup after wallet create/restore to prevent epoch dates in backup status await BackupService.shared.scheduleFullBackup() diff --git a/Bitkit/Services/PubkySwapsRouteService.swift b/Bitkit/Services/PubkySwapsRouteService.swift index e98da354cc..864f20c031 100644 --- a/Bitkit/Services/PubkySwapsRouteService.swift +++ b/Bitkit/Services/PubkySwapsRouteService.swift @@ -8,10 +8,11 @@ struct PaykitSwapRoute: Equatable { var providerName: String? } -/// How a swap's claim wait ended without a claim: bitkit-core failed the swap, or the wait ran out with the outcome -/// still open, when the provider may yet settle the hold invoice. +/// How a swap's claim wait ended without a claim: bitkit-core failed the swap, its hold payment failed so the provider +/// never funds it, or the wait ran out with the outcome still open, when the provider may yet settle the hold invoice. enum PubkySwapClaimError: Error { case failed(String) + case holdFailed case timedOut(Error) } @@ -20,12 +21,7 @@ enum PubkySwapClaimError: Error { /// the hold invoice from spending and bitkit-core claims the provider's lockup straight to the contact's address. enum PubkySwapsRouteService { private static let claimFeeRateSatVb: UInt64 = 2 - private static let pollInterval: Duration = .seconds(2) private static let claimTimeout: TimeInterval = 10 * 60 - /// How often a broadcast claim is advanced, so bitkit-core rebroadcasts it until it confirms. - private static let confirmationPollInterval: Duration = .seconds(30) - /// How long a swap is advanced in the background, after its claim broadcast or claim wait, before polling stops. - private static let confirmationTimeout: TimeInterval = 60 * 60 static var isEnabled: Bool { Env.isPubkySwapsRouteEnabled @@ -91,7 +87,7 @@ enum PubkySwapsRouteService { if !report.incompleteProviders.isEmpty { Logger.warn("Swap lists incomplete from \(report.incompleteProviders)", context: "PubkySwapsRoute") } - return (report.restored, report.known) + return await PubkySwapsTracker.shared.adoptRestored(restored: report.restored, known: report.known) } /// Providers come from the user's own graph: every contact is asked for its swap offer. bitkit-core caps the @@ -120,84 +116,82 @@ enum PubkySwapsRouteService { } } + /// Commits the quote and keeps its swap until its claim confirms or it fails, so a later start resumes it. static func commit(quoteId: String) async throws -> PubkySwapRoutePayment { let (mnemonic, passphrase) = try secrets() - return try await pubkySwapsCommitRoute( + let payment = try await pubkySwapsCommitRoute( quoteId: quoteId, electrumUrl: Env.electrumServerUrl, mnemonic: mnemonic, bip39Passphrase: passphrase ) + await PubkySwapsTracker.shared.didCommit(payment.swapId) + return payment + } + + /// Records the hold payment of a committed swap, so its failure stops the swap, also after a restart. + static func watchHold(swapId: String, paymentHash: String, invoice: String) async { + await PubkySwapsTracker.shared.watchHold(PubkySwapHoldPayment(paymentHash: paymentHash, invoice: invoice), swapId: swapId) + } + + /// Stops a swap whose hold payment failed or never went out: the provider never funds it. + static func dropFailedSwap(swapId: String) async { + Logger.info("Stopping Pubky Swaps route \(swapId) after its hold payment failed", context: "PubkySwapsRoute") + await PubkySwapsTracker.shared.drop(swapId) + } + + /// Advances each swap a closed app left unfinished until its claim confirms or it fails: the provider settles the + /// hold invoice once it sees the claim, so a claim that never confirms could leave the contact unpaid. + static func resumeUnfinishedSwaps() async { + await PubkySwapsTracker.shared.resume() + } + + static func resetForWipe() async { + await PubkySwapsTracker.shared.resetForWipe() } /// Advance the swap until bitkit-core broadcasts the claim to the contact, returning the claim txid. The provider /// settles the hold invoice once it sees the claim, so the payment is done; the claim is still advanced in the - /// background so bitkit-core rebroadcasts it until it confirms. + /// background until it confirms, so bitkit-core rebroadcasts it if it drops out of the mempool. /// A wait that runs out keeps advancing the swap in the background too, so it can still claim and settle the hold /// payment, and throws `PubkySwapClaimError.timedOut`. static func awaitClaim(swapId: String) async throws -> String { - do { - let txid = try await pollClaim(swapId: swapId, interval: pollInterval, timeout: claimTimeout, untilConfirmed: false) - advanceInBackground(swapId: swapId) - return txid - } catch let PubkySwapClaimError.timedOut(lastFailure) { - advanceInBackground(swapId: swapId) - throw PubkySwapClaimError.timedOut(lastFailure) - } + try await PubkySwapsTracker.shared.awaitClaim(swapId: swapId, timeout: claimTimeout) } - private static func advanceInBackground(swapId: String) { - Task.detached { - do { - let confirmed = try await pollClaim( - swapId: swapId, interval: confirmationPollInterval, timeout: confirmationTimeout, untilConfirmed: true - ) - Logger.info("Confirmed Pubky Swaps claim \(confirmed) for \(swapId)", context: "PubkySwapsRoute") - } catch { - Logger.warn("Failed to confirm Pubky Swaps claim for \(swapId): \(error)", context: "PubkySwapsRoute") - } - } + static func advance(swapId: String) async throws -> PubkySwapRouteState { + let (mnemonic, passphrase) = try secrets() + return try await pubkySwapsAdvance(swapId: swapId, mnemonic: mnemonic, bip39Passphrase: passphrase).state + } + + static func isUnknownSwap(_ error: Error) -> Bool { + guard case .NotFound? = error as? PubkySwapError else { return false } + return true } - private static func pollClaim( - swapId: String, - interval: Duration, - timeout: TimeInterval, - untilConfirmed: Bool - ) async throws -> String { - let deadline = Date().addingTimeInterval(timeout) - var lastFailure: Error = AppError(message: "Swap \(swapId) not claimed yet", debugMessage: nil) - while true { - try Task.checkCancellation() - let (mnemonic, passphrase) = try secrets() - let state: PubkySwapRouteState? - do { - state = try await pubkySwapsAdvance(swapId: swapId, mnemonic: mnemonic, bip39Passphrase: passphrase).state - } catch { - // A failed advance, such as a transient Electrum error, is retried: the swap is already funded. - Logger.warn("Failed to advance Pubky Swaps route \(swapId): \(error)", context: "PubkySwapsRoute") - lastFailure = error - state = nil - } - switch state { - case let .claimed(txid)?: - return txid - case let .claimBroadcast(txid)? where !untilConfirmed: - return txid - case let .failed(reason)?: - throw PubkySwapClaimError.failed(reason) - case let state?: - Logger.debug("Pubky Swaps route \(swapId): \(state)", context: "PubkySwapsRoute") - lastFailure = AppError(message: "Swap \(swapId) not claimed yet", debugMessage: "\(state)") - case nil: - break - } - guard Date() < deadline else { throw PubkySwapClaimError.timedOut(lastFailure) } - try await Task.sleep(for: interval) + /// Whether the hold payment failed. It goes out over the node or the channel-free rail, which shares its hash, and + /// the rail decides a send the node failed. While the rail can't be asked, it counts as not failed. + static func isHoldPaymentFailed(_ hold: PubkySwapHoldPayment) async -> Bool { + let lightning = LightningService.shared + let nodeStatus = await lightning.listPayments()?.first { payment in + guard case let .bolt11(hash, _, _, _, _) = payment.kind else { return false } + return hash.caseInsensitiveCompare(hold.paymentHash) == .orderedSame + }?.status + if let nodeStatus, nodeStatus != .failed { + return false + } + guard let rail = lightning.channelFreeRail ?? lightning.channelFreePaymentHistory else { + return await lightning.channelFreeRailSupported() ? false : nodeStatus == .failed + } + do { + guard let railStatus = try await rail.lightningSendStatus(bolt11: hold.invoice) else { return nodeStatus == .failed } + return railStatus == .failed + } catch { + return false } } - private static func secrets() throws -> (String, String?) { + static func secrets() throws -> (String, String?) { guard let mnemonic = try Keychain.loadString(key: .bip39Mnemonic(index: 0)) else { throw AppError(message: "Mnemonic not found", debugMessage: nil) } diff --git a/Bitkit/Services/PubkySwapsTracker.swift b/Bitkit/Services/PubkySwapsTracker.swift new file mode 100644 index 0000000000..9331744251 --- /dev/null +++ b/Bitkit/Services/PubkySwapsTracker.swift @@ -0,0 +1,245 @@ +import BitkitCore +import Foundation + +/// The hold payment of a committed swap: its hash, and its invoice, which the channel-free rail is asked about. +struct PubkySwapHoldPayment: Codable, Equatable { + let paymentHash: String + let invoice: String +} + +/// The swaps committed or restored whose claim has not confirmed, with the hold payment of each committed one, kept +/// across launches so each start resumes them. A wipe clears it with the rest of the app's defaults. +struct UnfinishedPubkySwapsStore { + static let swapIdsKey = "unfinishedPubkySwaps" + static let holdPaymentsKey = "pubkySwapHoldPayments" + + var defaults: UserDefaults = .standard + + var swapIds: [String] { + defaults.stringArray(forKey: Self.swapIdsKey) ?? [] + } + + func track(_ ids: [String]) { + var tracked = swapIds + for id in ids where !tracked.contains(id) { + tracked.append(id) + } + defaults.set(tracked, forKey: Self.swapIdsKey) + } + + func untrack(_ id: String) { + defaults.set(swapIds.filter { $0 != id }, forKey: Self.swapIdsKey) + var payments = holdPayments + payments[id] = nil + save(payments) + } + + func holdPayment(for id: String) -> PubkySwapHoldPayment? { + holdPayments[id] + } + + func setHoldPayment(_ payment: PubkySwapHoldPayment, for id: String) { + var payments = holdPayments + payments[id] = payment + save(payments) + } + + func clear() { + defaults.removeObject(forKey: Self.swapIdsKey) + defaults.removeObject(forKey: Self.holdPaymentsKey) + } + + private var holdPayments: [String: PubkySwapHoldPayment] { + guard let data = defaults.data(forKey: Self.holdPaymentsKey) else { return [:] } + return (try? JSONDecoder().decode([String: PubkySwapHoldPayment].self, from: data)) ?? [:] + } + + private func save(_ payments: [String: PubkySwapHoldPayment]) { + guard let data = try? JSONEncoder().encode(payments) else { return } + defaults.set(data, forKey: Self.holdPaymentsKey) + } +} + +/// Keeps each committed or restored swap advancing until its claim confirms or it fails, also after a restart: the +/// provider settles the hold invoice once it sees the claim, so a claim that never confirms could leave the contact +/// unpaid. +actor PubkySwapsTracker { + typealias Advance = @Sendable (_ swapId: String) async throws -> PubkySwapRouteState + typealias HoldPaymentCheck = @Sendable (PubkySwapHoldPayment) async -> Bool + + static let shared = PubkySwapsTracker( + advance: { try await PubkySwapsRouteService.advance(swapId: $0) }, + isHoldPaymentFailed: { await PubkySwapsRouteService.isHoldPaymentFailed($0) } + ) + + private let store: UnfinishedPubkySwapsStore + private let advance: Advance + private let isHoldPaymentFailed: HoldPaymentCheck + private let claimPollInterval: Duration + private let confirmationPollInterval: Duration + + /// Swaps a caller awaits the claim of, which no resume advances beside it. + private var claiming: Set = [] + /// The loop advancing each swap in the background, one per swap. + private var advancing: [String: Task] = [:] + /// Swaps this session committed, which the send flow drives, so a restore listing them leaves them alone. + private var committed: Set = [] + /// Swaps whose hold payment failed this session, which nothing advances again. + private var dropped: Set = [] + + init( + store: UnfinishedPubkySwapsStore = UnfinishedPubkySwapsStore(), + advance: @escaping Advance, + isHoldPaymentFailed: @escaping HoldPaymentCheck, + claimPollInterval: Duration = .seconds(2), + confirmationPollInterval: Duration = .seconds(30) + ) { + self.store = store + self.advance = advance + self.isHoldPaymentFailed = isHoldPaymentFailed + self.claimPollInterval = claimPollInterval + self.confirmationPollInterval = confirmationPollInterval + } + + var unfinishedSwapIds: [String] { + store.swapIds + } + + func isAdvancing(_ swapId: String) -> Bool { + advancing[swapId] != nil + } + + func didCommit(_ swapId: String) { + committed.insert(swapId) + store.track([swapId]) + } + + /// Recorded before the hold payment goes out, so a hold failing at any point stops the swap, also after a restart. + func watchHold(_ payment: PubkySwapHoldPayment, swapId: String) { + store.setHoldPayment(payment, for: swapId) + } + + /// Takes up the swaps a restore found. A swap committed or dropped this session is the send flow's, so the known + /// swaps returned leave it out. + func adoptRestored(restored: [String], known: [String]) -> (restored: [String], known: [String]) { + let known = known.filter { !committed.contains($0) && !dropped.contains($0) } + store.track(restored + known) + return (restored, known) + } + + /// Advances each swap a closed app left unfinished until its claim confirms or it fails. + func resume() { + for swapId in store.swapIds where !claiming.contains(swapId) { + advanceInBackground(swapId) + } + } + + /// Stops a swap whose hold payment failed or never went out: the provider never funds it, so advancing it would + /// only poll until bitkit-core gives up. + func drop(_ swapId: String) { + dropped.insert(swapId) + advancing.removeValue(forKey: swapId)?.cancel() + store.untrack(swapId) + } + + /// Stops the wiped wallet's swaps, so a wallet restored next starts from nothing. + func resetForWipe() { + advancing.values.forEach { $0.cancel() } + advancing.removeAll() + claiming.removeAll() + committed.removeAll() + dropped.removeAll() + store.clear() + } + + /// Advances the swap until bitkit-core broadcasts the claim, returning the claim txid, then keeps advancing it in the + /// background until the claim confirms. A wait that runs out, or a caller that stops waiting, leaves it advancing in + /// the background too, as the provider may still settle the hold payment. + func awaitClaim(swapId: String, timeout: TimeInterval) async throws -> String { + guard !dropped.contains(swapId) else { throw PubkySwapClaimError.holdFailed } + claiming.insert(swapId) + defer { claiming.remove(swapId) } + do { + let txid = try await pollClaim(swapId: swapId, interval: claimPollInterval, timeout: timeout, untilConfirmed: false) + advanceInBackground(swapId) + return txid + } catch let PubkySwapClaimError.timedOut(lastFailure) { + advanceInBackground(swapId) + throw PubkySwapClaimError.timedOut(lastFailure) + } catch is CancellationError { + advanceInBackground(swapId) + throw CancellationError() + } catch { + store.untrack(swapId) + throw error + } + } + + private func advanceInBackground(_ swapId: String) { + guard advancing[swapId] == nil, !dropped.contains(swapId) else { return } + advancing[swapId] = Task { await self.awaitConfirmation(swapId) } + } + + private func awaitConfirmation(_ swapId: String) async { + do { + let txid = try await pollClaim(swapId: swapId, interval: confirmationPollInterval, timeout: nil, untilConfirmed: true) + Logger.info("Confirmed Pubky Swaps claim \(txid) for \(swapId)", context: "PubkySwapsRoute") + } catch is CancellationError { + return + } catch { + if case PubkySwapClaimError.holdFailed = error { + dropped.insert(swapId) + } + Logger.warn("Failed to confirm Pubky Swaps claim for \(swapId): \(error)", context: "PubkySwapsRoute") + } + // A drop or a wipe that cancelled this loop already removed it. + guard !Task.isCancelled else { return } + advancing[swapId] = nil + store.untrack(swapId) + } + + private func pollClaim(swapId: String, interval: Duration, timeout: TimeInterval?, untilConfirmed: Bool) async throws -> String { + let deadline = timeout.map { Date().addingTimeInterval($0) } + var lastFailure: Error = AppError(message: "Swap \(swapId) not claimed yet", debugMessage: nil) + while true { + try Task.checkCancellation() + // A swap whose hold failed, also while the app was closed or over Spark, is never funded. + if dropped.contains(swapId) { + throw PubkySwapClaimError.holdFailed + } + if untilConfirmed, let hold = store.holdPayment(for: swapId), await isHoldPaymentFailed(hold) { + throw PubkySwapClaimError.holdFailed + } + let state: PubkySwapRouteState? + do { + state = try await advance(swapId) + } catch { + // A swap bitkit-core has no record of, as one carried over by a backup, never advances. + if PubkySwapsRouteService.isUnknownSwap(error) { + throw error + } + // A failed advance, such as a transient Electrum error, is retried: the swap is already funded. + Logger.warn("Failed to advance Pubky Swaps route \(swapId): \(error)", context: "PubkySwapsRoute") + lastFailure = error + state = nil + } + switch state { + case let .claimed(txid)?: + return txid + case let .claimBroadcast(txid)? where !untilConfirmed: + return txid + case let .failed(reason)?: + throw PubkySwapClaimError.failed(reason) + case let state?: + Logger.debug("Pubky Swaps route \(swapId): \(state)", context: "PubkySwapsRoute") + lastFailure = AppError(message: "Swap \(swapId) not claimed yet", debugMessage: "\(state)") + case nil: + break + } + if let deadline, Date() >= deadline { + throw PubkySwapClaimError.timedOut(lastFailure) + } + try await Task.sleep(for: interval) + } + } +} diff --git a/Bitkit/Utilities/AppReset.swift b/Bitkit/Utilities/AppReset.swift index de1529e881..2b0f0cdea3 100644 --- a/Bitkit/Utilities/AppReset.swift +++ b/Bitkit/Utilities/AppReset.swift @@ -85,6 +85,7 @@ final class AppReset: WipeStepExecutor { VssStoreIdProvider.shared.clearCache() OnChainHwService.shared.stopAllWatchers() MoveToSparkManager.shared.resetForWipe() + await PubkySwapsRouteService.resetForWipe() // Before the paired devices are wiped, so a reconnect still running cannot save one back. try await Self.bounded("hardware wallets") { await Self.hardwareWallets?.resetForWipe() } do { diff --git a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift index 72e9534ccf..88b8191fb4 100644 --- a/Bitkit/Views/Wallets/Send/SendConfirmationView.swift +++ b/Bitkit/Views/Wallets/Send/SendConfirmationView.swift @@ -1560,6 +1560,15 @@ struct SendConfirmationView: View { startedPresentationID != nil && startedPresentationID == activePresentationID && quoteId == activeQuoteId } + /// A failed hold payment cancels the claim wait, or ends it as `holdFailed` when the swap stopped first. + static func endedOnHoldPaymentFailure(_ error: Error) -> Bool { + if error is CancellationError { + return true + } + guard case PubkySwapClaimError.holdFailed = error else { return false } + return true + } + /// Only a swap bitkit-core failed ends a sent hold payment for sure; any other claim error leaves it open. static func isDefiniteSwapFailure(_ error: Error) -> Bool { guard case PubkySwapClaimError.failed = error else { return false } @@ -1582,10 +1591,13 @@ struct SendConfirmationView: View { ) } var createdMetadataPaymentId: String? + // A swap whose hold payment never went out is never funded, so a failure before then stops it. + var unpaidSwapId: String? do { // The quote must deliver the amount the user confirmed. guard quote.deliveredSat == wallet.sendAmountSats else { throw PaykitPaymentRequestError.amountMismatch } let payment = try await PubkySwapsRouteService.commit(quoteId: quote.quoteId) + unpaidSwapId = payment.swapId Logger.info("Committed Pubky Swaps route \(payment.swapId) to \(payment.destinationAddress)", context: "SendConfirmation") guard case let .lightning(holdInvoice) = try await decode(invoice: payment.invoice) else { throw AppError(message: t("common__error_body"), debugMessage: "Swap hold invoice is not a Lightning invoice") @@ -1593,8 +1605,11 @@ struct SendConfirmationView: View { let paymentHash = holdInvoice.paymentHash.hex createdMetadataPaymentId = paymentHash await createPreActivityMetadata(paymentId: paymentHash, paymentHash: paymentHash) + // Recorded before the payment goes out, so a hold failing at any point stops the swap. + await PubkySwapsRouteService.watchHold(swapId: payment.swapId, paymentHash: paymentHash, invoice: payment.invoice) // The hold invoice settles only after the claim reveals the preimage, so its payment stays pending until then. _ = try await LightningService.shared.send(bolt11: payment.invoice) + unpaidSwapId = nil // The hold payment's tags stay with it from here. createdMetadataPaymentId = nil // The provider settles the hold payment once it sees the claim, so the send waits on it like a pending @@ -1606,6 +1621,9 @@ struct SendConfirmationView: View { driveSwapClaim(payment, paymentHash: paymentHash, contactPaymentContext: contactPaymentContext, isSendCurrent: isSendCurrent) } catch { Logger.error("Pubky Swaps route payment failed: \(error)", context: "SendConfirmation") + if let swapId = unpaidSwapId { + await PubkySwapsRouteService.dropFailedSwap(swapId: swapId) + } if let paymentId = createdMetadataPaymentId { try? await CoreService.shared.activity.deletePreActivityMetadata(paymentId: paymentId) } @@ -1641,10 +1659,13 @@ struct SendConfirmationView: View { ) { let eventId = "swap-route-\(payment.swapId)" let claim = Task { try await PubkySwapsRouteService.awaitClaim(swapId: payment.swapId) } - // A failed hold payment ends the wait at once instead of polling the swap until the claim timeout. + // A failed hold payment stops the swap at once instead of polling it until the claim timeout. wallet.addOnEvent(id: eventId) { event in guard case let .paymentFailed(_, failedHash, _) = event, failedHash == paymentHash else { return } - claim.cancel() + Task { + await PubkySwapsRouteService.dropFailedSwap(swapId: payment.swapId) + claim.cancel() + } } Task { @MainActor in defer { wallet.removeOnEvent(id: eventId) } @@ -1655,7 +1676,7 @@ struct SendConfirmationView: View { await syncContactForActivity(paymentId: paymentHash, contactPaymentContext: contactPaymentContext) } catch { // A failed hold payment cancels the wait, and its tags go with it. - if error is CancellationError { + if Self.endedOnHoldPaymentFailure(error) { try? await CoreService.shared.activity.deletePreActivityMetadata(paymentId: paymentHash) } guard Self.isDefiniteSwapFailure(error) else { diff --git a/BitkitTests/PubkySwapsTrackerTests.swift b/BitkitTests/PubkySwapsTrackerTests.swift new file mode 100644 index 0000000000..ea205dacc8 --- /dev/null +++ b/BitkitTests/PubkySwapsTrackerTests.swift @@ -0,0 +1,217 @@ +@testable import Bitkit +import BitkitCore +import XCTest + +final class PubkySwapsTrackerTests: XCTestCase { + private var defaults: UserDefaults! + private var suiteName: String! + + override func setUp() { + super.setUp() + suiteName = "PubkySwapsTrackerTests.\(UUID().uuidString)" + defaults = UserDefaults(suiteName: suiteName) + } + + override func tearDown() { + defaults.removePersistentDomain(forName: suiteName) + super.tearDown() + } + + func testACommittedSwapIsKeptForTheNextLaunch() async { + let tracker = makeTracker(ScriptedAdvance([.success(.awaitingPayment)])) + await tracker.didCommit("swap") + XCTAssertEqual(store.swapIds, ["swap"]) + } + + func testResumeAdvancesUntilTheClaimConfirmsThenForgetsTheSwap() async throws { + let advance = ScriptedAdvance([.success(.claimBroadcast(txid: "tx")), .success(.claimBroadcast(txid: "tx")), .success(.claimed(txid: "tx"))]) + let tracker = makeTracker(advance) + store.track(["swap"]) + + await tracker.resume() + + try await waitUntilFinished(tracker, "swap") + let calls = await advance.calls + XCTAssertEqual(calls, 3) + } + + func testATransientAdvanceFailureKeepsAdvancing() async throws { + let advance = ScriptedAdvance([.failure(PubkySwapError.Transport(errorDetails: "offline")), .success(.claimed(txid: "tx"))]) + let tracker = makeTracker(advance) + store.track(["swap"]) + + await tracker.resume() + + try await waitUntilFinished(tracker, "swap") + let calls = await advance.calls + XCTAssertEqual(calls, 2) + } + + func testResumeForgetsAFailedSwapOrOneBitkitCoreDoesNotKnow() async throws { + let outcomes: [Result] = [ + .success(.failed(reason: "refunded")), + .failure(PubkySwapError.NotFound(errorDetails: "swap")), + ] + for outcome in outcomes { + let advance = ScriptedAdvance([outcome, .success(.claimed(txid: "tx"))]) + let tracker = makeTracker(advance) + store.track(["swap"]) + + await tracker.resume() + + try await waitUntilFinished(tracker, "swap") + let calls = await advance.calls + XCTAssertEqual(calls, 1) + } + } + + func testResumeStopsASwapWhoseHoldPaymentFailed() async throws { + let advance = ScriptedAdvance([.success(.awaitingLockup(confirmations: 0, required: 1))]) + let tracker = makeTracker(advance, isHoldPaymentFailed: { $0.paymentHash == "hash" }) + await tracker.didCommit("swap") + await tracker.watchHold(PubkySwapHoldPayment(paymentHash: "hash", invoice: "lnbcrt1"), swapId: "swap") + + await tracker.resume() + + try await waitUntilFinished(tracker, "swap") + XCTAssertNil(store.holdPayment(for: "swap")) + let calls = await advance.calls + XCTAssertEqual(calls, 0) + do { + _ = try await tracker.awaitClaim(swapId: "swap", timeout: 1) + XCTFail("A swap whose hold failed is not awaited") + } catch PubkySwapClaimError.holdFailed {} + } + + func testDropStopsAdvancingAndForgetsTheSwap() async { + let tracker = makeTracker(ScriptedAdvance([.success(.awaitingLockup(confirmations: 0, required: 1))])) + await tracker.didCommit("swap") + await tracker.resume() + let isAdvancing = await tracker.isAdvancing("swap") + XCTAssertTrue(isAdvancing) + + await tracker.drop("swap") + + let isStillAdvancing = await tracker.isAdvancing("swap") + XCTAssertFalse(isStillAdvancing) + XCTAssertEqual(store.swapIds, []) + await tracker.resume() + let isAdvancingAgain = await tracker.isAdvancing("swap") + XCTAssertFalse(isAdvancingAgain) + } + + func testAwaitClaimReturnsAtTheBroadcastAndKeepsAdvancingUntilConfirmed() async throws { + let advance = ScriptedAdvance([.success(.claimBroadcast(txid: "tx")), .success(.claimBroadcast(txid: "tx")), .success(.claimed(txid: "tx"))]) + let tracker = makeTracker(advance) + await tracker.didCommit("swap") + + let txid = try await tracker.awaitClaim(swapId: "swap", timeout: 5) + + XCTAssertEqual(txid, "tx") + XCTAssertEqual(store.swapIds, ["swap"]) + try await waitUntilFinished(tracker, "swap") + } + + func testAwaitClaimThatRunsOutKeepsAdvancing() async throws { + let tracker = makeTracker(ScriptedAdvance([.success(.awaitingLockup(confirmations: 0, required: 1))])) + await tracker.didCommit("swap") + + do { + _ = try await tracker.awaitClaim(swapId: "swap", timeout: 0) + XCTFail("The wait should run out") + } catch PubkySwapClaimError.timedOut {} + + let isAdvancing = await tracker.isAdvancing("swap") + XCTAssertTrue(isAdvancing) + XCTAssertEqual(store.swapIds, ["swap"]) + await tracker.resetForWipe() + } + + func testAwaitClaimForgetsAFailedSwap() async { + let tracker = makeTracker(ScriptedAdvance([.success(.failed(reason: "refunded"))])) + await tracker.didCommit("swap") + + do { + _ = try await tracker.awaitClaim(swapId: "swap", timeout: 5) + XCTFail("The swap failed") + } catch PubkySwapClaimError.failed {} catch { + XCTFail("Unexpected \(error)") + } + + XCTAssertEqual(store.swapIds, []) + let isAdvancing = await tracker.isAdvancing("swap") + XCTAssertFalse(isAdvancing) + } + + func testRestoreLeavesTheSwapsThisSessionCommittedOrDroppedToTheSendFlow() async { + let tracker = makeTracker(ScriptedAdvance([.success(.awaitingPayment)])) + await tracker.didCommit("committed") + await tracker.didCommit("dropped") + await tracker.drop("dropped") + + let adopted = await tracker.adoptRestored(restored: ["restored"], known: ["committed", "dropped", "known"]) + + XCTAssertEqual(adopted.restored, ["restored"]) + XCTAssertEqual(adopted.known, ["known"]) + XCTAssertEqual(Set(store.swapIds), ["committed", "restored", "known"]) + } + + func testWipeStopsAndForgetsEverySwap() async { + let tracker = makeTracker(ScriptedAdvance([.success(.awaitingLockup(confirmations: 0, required: 1))])) + await tracker.didCommit("swap") + await tracker.watchHold(PubkySwapHoldPayment(paymentHash: "hash", invoice: "lnbcrt1"), swapId: "swap") + await tracker.resume() + + await tracker.resetForWipe() + + let isAdvancing = await tracker.isAdvancing("swap") + XCTAssertFalse(isAdvancing) + XCTAssertEqual(store.swapIds, []) + XCTAssertNil(store.holdPayment(for: "swap")) + } + + // MARK: - Helpers + + private var store: UnfinishedPubkySwapsStore { + UnfinishedPubkySwapsStore(defaults: defaults) + } + + private func makeTracker( + _ advance: ScriptedAdvance, + isHoldPaymentFailed: @escaping @Sendable (PubkySwapHoldPayment) async -> Bool = { _ in false } + ) -> PubkySwapsTracker { + PubkySwapsTracker( + store: store, + advance: { _ in try await advance.next() }, + isHoldPaymentFailed: isHoldPaymentFailed, + claimPollInterval: .milliseconds(5), + confirmationPollInterval: .milliseconds(5) + ) + } + + private func waitUntilFinished(_ tracker: PubkySwapsTracker, _ swapId: String) async throws { + for _ in 0 ..< 400 { + let isAdvancing = await tracker.isAdvancing(swapId) + if !isAdvancing, !store.swapIds.contains(swapId) { + return + } + try await Task.sleep(for: .milliseconds(5)) + } + XCTFail("Swap \(swapId) still advancing") + } +} + +/// Answers each advance with the next scripted outcome, repeating the last one. +actor ScriptedAdvance { + private let outcomes: [Result] + private(set) var calls = 0 + + init(_ outcomes: [Result]) { + self.outcomes = outcomes + } + + func next() throws -> PubkySwapRouteState { + defer { calls += 1 } + return try outcomes[min(calls, outcomes.count - 1)].get() + } +}