Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,23 @@ final class SwiftDashSDKWalletRuntime: NSObject {
/// turn "Sync Now" into a real in-session recovery action after Stop or a
/// recover-time binding race.
func rearmPlatformSync() async {
let task = enqueueAwaitable { [weak self] in
await self?.refresh(trigger: .platformSyncRearm)
}
await task.value
await awaitRefresh(trigger: .platformSyncRearm)
}

/// Rebuild the shared runtime after the SwiftData rows it loaded from were
/// edited underneath it, and return once that rebuild has settled (started,
/// or failed back to a stopped runtime).
///
/// Runs the same serialized stop → load → start the lifecycle queue drives
/// for a network or wallet switch: on load the Rust wallet rehydrates its
/// tx set, UTXOs and `spent_outpoints` from the rows as they now are, and
/// dash-spv's mempool tracker restarts without the deleted transactions.
///
/// `.walletRowsChanged` is never elided by `shouldSkipRefresh`: a runtime
/// that still looks ready is precisely the one holding the pre-edit state
/// this call exists to discard.
func reloadAfterWalletRowsChanged() async {
await awaitRefresh(trigger: .walletRowsChanged)
Comment thread
llbartekll marked this conversation as resolved.
Resolved
}

/// Restart Core SPV to dial a fresh peer set ("sync too slow? change
Expand Down Expand Up @@ -393,6 +406,16 @@ final class SwiftDashSDKWalletRuntime: NSObject {
}
}

/// Awaiting sibling of `enqueueRefresh`: appends the same single
/// `refresh(trigger:)` op to the serial chain and returns only once it —
/// and every op queued ahead of it — has finished. Callers that must
/// observe the rebuilt runtime go through here.
private func awaitRefresh(trigger: RefreshTrigger) async {
await enqueueAwaitable { [weak self] in
await self?.refresh(trigger: trigger)
}.value
}

private func enqueueFullReset(lastError: String?, forWipe: Bool) {
enqueue { [weak self] in
await self?.fullReset(lastError: lastError, forWipe: forWipe)
Expand Down Expand Up @@ -468,6 +491,17 @@ final class SwiftDashSDKWalletRuntime: NSObject {
// bound so identity/banner consumers re-read destination
// state instead of the cleared transition mirror.
publishActiveWalletDidChange(reason: "network-changed")
} else if trigger == .walletRowsChanged {
// A rows-changed rebuild rebinds the wallet just like the
// two above, and it can resolve a network key that an
// interactive switch has ALREADY flipped while its own
// refresh is still queued behind this one. That switch's
// refresh then finds the destination runtime ready and
// elides, taking its "network-changed" publish with it —
// so publish here too, or consumers that listen only for
// this notification (SwiftDashSDKContactsService) keep a
// pre-switch snapshot.
publishActiveWalletDidChange(reason: "wallet-rows-changed")
}
} catch {
Self.logger.error("🧭 RUNTIME :: start failed: \(String(describing: error), privacy: .public)")
Expand Down Expand Up @@ -527,11 +561,14 @@ final class SwiftDashSDKWalletRuntime: NSObject {

private func shouldSkipRefresh(for network: Network, trigger: RefreshTrigger) -> Bool {
switch trigger {
case .walletMaterialChanged, .walletDidChange:
case .walletMaterialChanged, .walletDidChange, .walletRowsChanged:
// A runtime wallet switch always rebuilds — the active-wallet
// registry was repointed to a different wallet on the SAME
// network, so `currentNetwork == network` would otherwise wrongly
// elide the rebind.
// elide the rebind. A rows-changed rebuild always runs for the
// mirror-image reason: the SwiftData rows were edited behind a
// runtime that never stopped, so a runtime that looks ready is
// exactly the one still holding the pre-edit in-memory wallet.
return false
case .startIfReady, .networkDidChange, .platformSyncRearm:
return isRuntimeReady(for: network)
Expand Down Expand Up @@ -639,6 +676,7 @@ final class SwiftDashSDKWalletRuntime: NSObject {
case networkDidChange
case walletMaterialChanged
case walletDidChange
case walletRowsChanged
case platformSyncRearm
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,22 @@ struct UnconfirmedTransactionRemover {
subsystem: "org.dashfoundation.dash",
category: "swift-sdk-migration.unconfirmed-tx-remover")

/// What the removal achieved beyond deleting the rows. The rows are gone
/// in every case; the cases differ in how much of the recovery path behind
/// them ran, so a caller never has to claim more than actually happened.
enum RemovalOutcome {
/// Runtime reloaded and the recovery filter rescan is running.
case rescanArmed
/// Runtime reloaded, but the rescan did not arm (no chain tip to
/// anchor on, or the arm threw). Rescan Filters still works.
case rescanUnavailable
/// The reload took the runtime down and it did not come back: a BLAST
/// start failure makes `refresh` fall back to `fullReset`, which stops
/// the host and Core SPV too. Rescan Filters refuses while SPV is
/// stopped, so this case must NOT point the user at it.
case runtimeStopped
}

enum RemovalError: LocalizedError {
case notReady
case transactionNotFound
Expand Down Expand Up @@ -89,13 +105,13 @@ struct UnconfirmedTransactionRemover {
/// estimate (~1 day), covering clock skew and variable block times.
private static let rescanMarginBlocks: UInt32 = 576

/// - Returns: whether the recovery filter rescan was armed. `false`
/// means the removal itself succeeded but the rescan didn't start
/// (SPV not running / arm threw) — the caller should tell the user
/// to run Rescan Filters manually so the safety net isn't silently
/// skipped.
/// - Returns: how far past the row deletion the removal got. Anything
/// other than `.rescanArmed` means the safety net didn't start, and
/// `.runtimeStopped` additionally means the wallet runtime is down —
/// the caller must say so rather than pointing at Rescan Filters,
/// which refuses while SPV is stopped.
@discardableResult
func remove(txidWire: Data) async throws -> Bool {
func remove(txidWire: Data) async throws -> RemovalOutcome {
guard let container = SwiftDashSDKHost.shared.modelContainer,
let network = WalletEnvironment.network,
let walletId = WalletEnvironment.activeWalletId(for: WalletEnvironment.networkKind) else {
Expand Down Expand Up @@ -161,19 +177,19 @@ struct UnconfirmedTransactionRemover {
/// a dropped transaction that IS on the blockchain is re-matched and
/// restored by it. Nothing is sent to the network.
///
/// - Returns: how many transactions were dropped (0 = nothing to
/// drop; no reload or rescan runs, so `rescanArmed` is `false`),
/// and whether the recovery rescan was armed — `false` after a
/// non-zero drop means the caller must tell the user to run
/// Rescan Filters manually.
func dropAllUnconfirmedAndRescan() async throws -> (dropped: Int, rescanArmed: Bool) {
/// - Returns: how many transactions were dropped (0 = nothing to drop;
/// no reload or rescan runs, so the outcome is `.rescanUnavailable`),
/// and how far the removal tail got. `.runtimeStopped` after a
/// non-zero drop means the wallet runtime is down, so the caller must
/// not offer Rescan Filters as the remedy.
func dropAllUnconfirmedAndRescan() async throws -> (dropped: Int, outcome: RemovalOutcome) {
guard let container = SwiftDashSDKHost.shared.modelContainer,
let walletId = WalletEnvironment.activeWalletId(for: WalletEnvironment.networkKind) else {
throw RemovalError.notReady
}
let context = container.mainContext
let rows = try Self.unconfirmedRows(in: context, walletId: walletId)
guard !rows.isEmpty else { return (dropped: 0, rescanArmed: false) }
guard !rows.isEmpty else { return (dropped: 0, outcome: .rescanUnavailable) }

var oldestFirstSeen = UInt64.max
var displayTxids: [String] = []
Expand All @@ -188,9 +204,9 @@ struct UnconfirmedTransactionRemover {
try context.save()
Self.logger.notice("🗑️ TX-REMOVE :: bulk-dropped \(rows.count, privacy: .public) unconfirmed tx(s): \(displayTxids.joined(separator: ","), privacy: .public)")

let rescanArmed = await Self.finishRemoval(
let outcome = await Self.finishRemoval(
txidsWire: txidsWire, walletId: walletId, oldestFirstSeen: oldestFirstSeen)
return (dropped: rows.count, rescanArmed: rescanArmed)
return (dropped: rows.count, outcome: outcome)
}

/// The active wallet's unconfirmed (mempool-context, no block) rows —
Expand Down Expand Up @@ -250,13 +266,12 @@ struct UnconfirmedTransactionRemover {

/// Shared removal tail, after the rows are deleted and saved:
/// app-side metadata cleanup, full runtime reload, filter rescan,
/// and cache refresh. Returns whether the rescan was armed — the
/// rescan is the recovery step that restores a wrongly-removed
/// on-chain transaction, so callers surface `false` to the user
/// instead of claiming a complete recovery.
/// and cache refresh. The rescan is the recovery step that restores a
/// wrongly-removed on-chain transaction, so anything short of
/// `.rescanArmed` is surfaced instead of claiming a complete recovery.
private static func finishRemoval(
txidsWire: [Data], walletId: Data, oldestFirstSeen: UInt64
) async -> Bool {
) async -> RemovalOutcome {
// App-side metadata (tax category override) keyed by the same
// hash — a fresh install knows nothing about a removed tx, and
// neither should this one.
Expand All @@ -266,41 +281,73 @@ struct UnconfirmedTransactionRemover {
}
}

// How deep the recovery rescan reaches is decided HERE, before the
// reload, because the reload stops SPV and `resetPublishedState`
// zeroes the coordinator's `tipHeight`; the restarted client only
// re-seeds it on a later progress tick, so a post-reload read finds 0
// and arms nothing. Anchoring on the pre-reload tip is the safe
// direction — the tip only advances, so the older value rewinds
// deeper, never shallower.
//
// The window reaches back past the OLDEST removed transaction's first
// appearance — uncapped in depth, because this is the step that
// restores a removed tx that actually IS mined (the bulk path never
// explorer-checked, and the single path's explorer can be wrong). The
// SDK floors the rescan at the wallet's birth height and the locally
// stored chain data; a row with no usable first-seen time rescans from
// the floor.
let tip = SwiftDashSDKSPVCoordinator.shared.tipHeight
let rescanFromHeight: UInt32? = {
guard tip > 0 else { return nil }
let ageSeconds = max(0, Date().timeIntervalSince1970 - TimeInterval(oldestFirstSeen))
let ageBlocks = UInt32(clamping: Int(ageSeconds / 150)) + rescanMarginBlocks
let blocksBack = max(minRescanBlocks, ageBlocks)
return tip > blocksBack ? tip - blocksBack : 1
}()

// Full runtime reload — the same serialized stop → load → start
// lifecycle a network switch runs. The reloaded Rust wallet
// rebuilds its tx set, UTXOs and spent_outpoints from the rows as
// they now are, and dash-spv's mempool tracker (which kept
// rebroadcasting) restarts without the removed transactions.
await SwiftDashSDKWalletRuntime.shared.rearmPlatformSync()
await SwiftDashSDKWalletRuntime.shared.reloadAfterWalletRowsChanged()
Comment thread
llbartekll marked this conversation as resolved.
Resolved

// Rescan compact filters, reaching back past the OLDEST removed
// transaction's first appearance — uncapped in depth, because
// this is the step that restores a removed tx that actually IS
// mined (the bulk path never explorer-checked, and the single
// path's explorer can be wrong). The SDK floors the rescan at
// the wallet's birth height and the locally stored chain data;
// a row with no usable first-seen time rescans from the floor.
var rescanArmed = false
let tip = SwiftDashSDKSPVCoordinator.shared.tipHeight
if tip > 0, let manager = SwiftDashSDKHost.shared.manager {
let ageSeconds = max(0, Date().timeIntervalSince1970 - TimeInterval(oldestFirstSeen))
let ageBlocks = UInt32(clamping: Int(ageSeconds / 150)) + rescanMarginBlocks
let blocksBack = max(minRescanBlocks, ageBlocks)
let fromHeight = tip > blocksBack ? tip - blocksBack : 1
// Did the reload actually bring the runtime back? `refresh` starts
// Core SPV and then BLAST, and falls back to `fullReset` if EITHER
// throws — so a Platform outage, which has nothing to do with the
// Core-side row the user just repaired, stops the host and Core SPV
// as well. The rows are already deleted and stay deleted; what this
// decides is which remedy the caller can honestly offer, because
// Rescan Filters refuses while SPV is stopped.
let runtimeReady = WalletEnvironment.network
.map { SwiftDashSDKWalletRuntime.shared.isRuntimeReady(for: $0) } ?? false

let outcome: RemovalOutcome
if !runtimeReady {
outcome = .runtimeStopped
logger.error("🗑️ TX-REMOVE :: runtime did not come back after the reload — rows deleted, wallet stopped")
} else if let fromHeight = rescanFromHeight, let manager = SwiftDashSDKHost.shared.manager {
Comment thread
llbartekll marked this conversation as resolved.
Resolved
// Rewind the compact-filter checkpoint on the manager the reload
// just built — the previous instance died with the old runtime.
do {
try manager.spvRescanFilters(walletId: walletId, fromHeight: fromHeight)
rescanArmed = true
outcome = .rescanArmed
logger.notice("🗑️ TX-REMOVE :: filter rescan armed from height \(fromHeight, privacy: .public) (tip \(tip, privacy: .public))")
} catch {
outcome = .rescanUnavailable
logger.error("🗑️ TX-REMOVE :: filter rescan arm failed: \(String(describing: error), privacy: .public)")
}
} else if rescanFromHeight == nil {
outcome = .rescanUnavailable
logger.error("🗑️ TX-REMOVE :: filter rescan skipped — no chain tip when the removal started")
} else {
logger.error("🗑️ TX-REMOVE :: filter rescan skipped — SPV not running after reload")
outcome = .rescanUnavailable
logger.error("🗑️ TX-REMOVE :: filter rescan skipped — no manager after the reload")
}

// App caches that mirror the deleted rows.
await ShieldedTxLookup.shared.refresh(reason: "transaction-removal-completed")
return rescanArmed
return outcome
}

/// One GET against the network's Insight API. 200 = the explorer
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -594,13 +594,13 @@
Text(NSLocalizedString(
"Available only while SPV is running with a wallet bound.",
comment: "SPV diagnostics"))
.font(.system(size: 12))

Check warning on line 597 in DashWallet/Sources/UI/Menu/SyncInfo/SwiftDashSDKSPVStatusScreen.swift

View workflow job for this annotation

GitHub Actions / VoiceOver / Dynamic Type audit

A11Y007

Fixed font size ignores Dynamic Type: fixed point size with no relativeTo: — ignores the user's text size
.foregroundColor(Color.dash.secondaryText)
}

if let message = dropResultMessage {
Text(message)
.font(.system(size: 12))

Check warning on line 603 in DashWallet/Sources/UI/Menu/SyncInfo/SwiftDashSDKSPVStatusScreen.swift

View workflow job for this annotation

GitHub Actions / VoiceOver / Dynamic Type audit

A11Y007

Fixed font size ignores Dynamic Type: fixed point size with no relativeTo: — ignores the user's text size
.foregroundColor(dropResultIsError ? .red : .green)
.fixedSize(horizontal: false, vertical: true)
}
Expand Down Expand Up @@ -633,7 +633,7 @@
SwiftDashSDKWalletRuntime.stopCoreSPV()
}) {
Text("Stop")
.font(.system(size: 14, weight: .semibold))

Check warning on line 636 in DashWallet/Sources/UI/Menu/SyncInfo/SwiftDashSDKSPVStatusScreen.swift

View workflow job for this annotation

GitHub Actions / VoiceOver / Dynamic Type audit

A11Y007

Fixed font size ignores Dynamic Type: fixed point size with no relativeTo: — ignores the user's text size
.frame(maxWidth: .infinity)
.padding(.vertical, 12)
.background(Color.dash.gray300.opacity(0.3))
Expand Down Expand Up @@ -952,24 +952,40 @@
dropResultMessage = NSLocalizedString(
"No unconfirmed transactions to drop.",
comment: "SPV diagnostics")
} else if outcome.rescanArmed {
dropResultIsError = false
dropResultMessage = String(
format: NSLocalizedString(
"Dropped %d unconfirmed transaction(s) — rescanning filters, watch the Filters row.",
comment: "SPV diagnostics"),
outcome.dropped)
} else {
// The drop finished but the recovery rescan didn't
// arm — flag it instead of claiming the safety net ran.
dropResultIsError = true
dropResultMessage = String(
format: NSLocalizedString(
"Dropped %d unconfirmed transaction(s), but the filter rescan couldn't start — run Rescan Filters above.",
comment: "SPV diagnostics"),
outcome.dropped)
switch outcome.outcome {
case .rescanArmed:
dropResultIsError = false
dropResultMessage = String(
format: NSLocalizedString(
"Dropped %d unconfirmed transaction(s) — rescanning filters, watch the Filters row.",
comment: "SPV diagnostics"),
outcome.dropped)
case .rescanUnavailable:
// The drop finished but the recovery rescan didn't
// arm — flag it instead of claiming the safety net ran.
dropResultIsError = true
dropResultMessage = String(
format: NSLocalizedString(
"Dropped %d unconfirmed transaction(s), but the filter rescan couldn't start — run Rescan Filters above.",
comment: "SPV diagnostics"),
outcome.dropped)
case .runtimeStopped:
// Rescan Filters above is disabled while SPV is
// stopped, so restarting comes first — and it has to
// be followed by the rescan, which restarting does
// not replay. This path never explorer-checked, so
// that rescan is the only on-chain safety check the
// dropped transactions ever get.
dropResultIsError = true
dropResultMessage = String(
format: NSLocalizedString(
"Dropped %d unconfirmed transaction(s), but the wallet stopped and the filter rescan never ran. Restart the wallet (reopen the app, or Sync Now in Platform sync), then run Rescan Filters above.",
comment: "SPV diagnostics"),
outcome.dropped)
}
}
Self.logger.info("🛰️ SPV-STATUS :: bulk unconfirmed drop finished — \(outcome.dropped, privacy: .public) tx(s), rescanArmed=\(outcome.rescanArmed, privacy: .public)")
Self.logger.info("🛰️ SPV-STATUS :: bulk unconfirmed drop finished — \(outcome.dropped, privacy: .public) tx(s), outcome=\(String(describing: outcome.outcome), privacy: .public)")
} catch {
dropResultIsError = true
dropResultMessage = error.localizedDescription
Expand Down
Loading
Loading