Skip to content
Draft
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
2 changes: 1 addition & 1 deletion Bitkit.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -1303,7 +1303,7 @@
repositoryURL = "https://github.com/synonymdev/bitkit-core";
requirement = {
kind = exactVersion;
version = "0.8.0-rc15";
version = "0.8.0-swaps.12";
};
};
96E493A22C942FD1000E8BC2 /* XCRemoteSwiftPackageReference "swift-secp256k1" */ = {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion Bitkit/Managers/WakeManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,9 @@ enum WakeRetry {

extension WakeHandlerRegistry {
/// Background wakes the app delegate handles. Any other topic is acknowledged `noHandler`.
static let app = WakeHandlerRegistry([:])
static let app = WakeHandlerRegistry([
WakeTopics.swapClaimable: { _ in try await PubkySwapsRouteService.handleClaimableWake() },
])
}

/// Sends a registration unless the gateway already holds the same one, signed at a timestamp that only increases.
Expand Down
20 changes: 20 additions & 0 deletions Bitkit/Services/PubkySwapsRouteService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ enum PubkySwapClaimError: Error {
enum PubkySwapsRouteService {
private static let claimFeeRateSatVb: UInt64 = 2
private static let claimTimeout: TimeInterval = 10 * 60
/// Within the 30 seconds iOS gives a background push, leaving time to acknowledge the wake.
private static let claimableWakeTimeout: Duration = .seconds(18)
private static let claimableWakePollInterval: Duration = .seconds(3)

static var isEnabled: Bool {
Env.isPubkySwapsRouteEnabled
Expand Down Expand Up @@ -126,6 +129,10 @@ enum PubkySwapsRouteService {
bip39Passphrase: passphrase
)
await PubkySwapsTracker.shared.didCommit(payment.swapId)
// Never holds up or fails the send: without a wake, the wallet claims when it next runs.
Task.detached {
await PubkySwapsWakeGrants.shared.handOver(swapId: payment.swapId, providerTakesWake: payment.providerTakesWake)
}
return payment
}

Expand All @@ -148,6 +155,19 @@ enum PubkySwapsRouteService {

static func resetForWipe() async {
await PubkySwapsTracker.shared.resetForWipe()
await PubkySwapsWakeGrants.shared.resetForWipe()
}

/// Claims the swaps a `swap.claimable` wake stands for, from the app delegate. Throws when no claim went out and a
/// swap is still open, so the wake is acknowledged `failed`.
static func handleClaimableWake() async throws {
let isHandled = await PubkySwapsTracker.shared.advanceForClaimableWake(
timeout: claimableWakeTimeout,
interval: claimableWakePollInterval
)
guard isHandled else {
throw AppError(message: "No swap claim went out for the wake", debugMessage: nil)
}
}

/// Advance the swap until bitkit-core broadcasts the claim to the contact, returning the claim txid. The provider
Expand Down
69 changes: 65 additions & 4 deletions Bitkit/Services/PubkySwapsTracker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,19 @@ struct UnfinishedPubkySwapsStore {
actor PubkySwapsTracker {
typealias Advance = @Sendable (_ swapId: String) async throws -> PubkySwapRouteState
typealias HoldPaymentCheck = @Sendable (PubkySwapHoldPayment) async -> Bool
typealias Finished = @Sendable (_ swapId: String) async -> Void

static let shared = PubkySwapsTracker(
static let shared: PubkySwapsTracker = .init(
advance: { try await PubkySwapsRouteService.advance(swapId: $0) },
isHoldPaymentFailed: { await PubkySwapsRouteService.isHoldPaymentFailed($0) }
isHoldPaymentFailed: { await PubkySwapsRouteService.isHoldPaymentFailed($0) },
didFinish: { await PubkySwapsWakeGrants.shared.revoke(swapId: $0) }
)

private let store: UnfinishedPubkySwapsStore
private let advance: Advance
private let isHoldPaymentFailed: HoldPaymentCheck
/// Runs once a swap stops being tracked, so its wake grant is revoked.
private let didFinish: Finished
private let claimPollInterval: Duration
private let confirmationPollInterval: Duration

Expand All @@ -91,12 +95,14 @@ actor PubkySwapsTracker {
store: UnfinishedPubkySwapsStore = UnfinishedPubkySwapsStore(),
advance: @escaping Advance,
isHoldPaymentFailed: @escaping HoldPaymentCheck,
didFinish: @escaping Finished = { _ in },
claimPollInterval: Duration = .seconds(2),
confirmationPollInterval: Duration = .seconds(30)
) {
self.store = store
self.advance = advance
self.isHoldPaymentFailed = isHoldPaymentFailed
self.didFinish = didFinish
self.claimPollInterval = claimPollInterval
self.confirmationPollInterval = confirmationPollInterval
}
Expand Down Expand Up @@ -139,7 +145,7 @@ actor PubkySwapsTracker {
func drop(_ swapId: String) {
dropped.insert(swapId)
advancing.removeValue(forKey: swapId)?.cancel()
store.untrack(swapId)
finish(swapId)
}

/// Stops the wiped wallet's swaps, so a wallet restored next starts from nothing.
Expand Down Expand Up @@ -170,7 +176,7 @@ actor PubkySwapsTracker {
advanceInBackground(swapId)
throw CancellationError()
} catch {
store.untrack(swapId)
finish(swapId)
throw error
}
}
Expand All @@ -195,7 +201,52 @@ actor PubkySwapsTracker {
// A drop or a wipe that cancelled this loop already removed it.
guard !Task.isCancelled else { return }
advancing[swapId] = nil
finish(swapId)
}

private func finish(_ swapId: String) {
store.untrack(swapId)
let didFinish = didFinish
Task { await didFinish(swapId) }
}

/// A `swap.claimable` wake names no swap, and wakes on the topic collapse, so one may stand for several swaps. Every
/// unfinished swap is advanced until each has its claim broadcast or has ended, or `timeout` passes, and then keeps
/// advancing in the background. Returns whether a claim went out or no swap is left open.
func advanceForClaimableWake(timeout: Duration, interval: Duration) async -> Bool {
let run = ClaimableWakeRun(open: Set(store.swapIds))
_ = await withDeadline(timeout) { await self.advanceOpenSwaps(run, interval: interval) }
for swapId in store.swapIds where !claiming.contains(swapId) {
advanceInBackground(swapId)
}
return run.isClaimBroadcast || run.open.isEmpty
}

private func advanceOpenSwaps(_ run: ClaimableWakeRun, interval: Duration) async {
while !run.open.isEmpty, !Task.isCancelled {
for swapId in run.open.sorted() {
guard !Task.isCancelled else { return }
do {
switch try await advance(swapId) {
case .claimBroadcast:
run.isClaimBroadcast = true
run.open.remove(swapId)
case .claimed, .failed:
run.open.remove(swapId)
case .awaitingPayment, .awaitingLockup:
break
}
} catch {
if PubkySwapsRouteService.isUnknownSwap(error) {
run.open.remove(swapId)
} else {
Logger.warn("Failed to advance Pubky Swaps route \(swapId) for a wake: \(error)", context: "PubkySwapsRoute")
}
}
}
guard !run.open.isEmpty else { return }
try? await Task.sleep(for: interval)
}
}

private func pollClaim(swapId: String, interval: Duration, timeout: TimeInterval?, untilConfirmed: Bool) async throws -> String {
Expand Down Expand Up @@ -243,3 +294,13 @@ actor PubkySwapsTracker {
}
}
}

/// What a `swap.claimable` wake reached so far, read once its deadline passes.
private final class ClaimableWakeRun {
var open: Set<String>
var isClaimBroadcast = false

init(open: Set<String>) {
self.open = open
}
}
Loading