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 @@ -191,13 +191,30 @@ public final class SwiftDashSDKSPVCoordinator: NSObject, ObservableObject {
// (a near-empty one-time scan for wallets that never used CoinJoin).
applyCoinJoinRecoveryGapIfNeeded(for: network)

// Pending birth-height chain resync: with the store deleted BEFORE
// startSpv, the client re-anchors at the restored (lowered) birth
// height and the armed rescan walks the recovered range. Must also
// run before startSpv so the delete never races the sync loop's
// segment writes. See `SPVChainResyncMarker` for why this only
// happens on the launch after the marker was armed.
let appliedChainResync = applyPendingChainResyncIfNeeded(
for: network, dataDir: dataDir, manager: manager)

do {
try manager.startSpv(config: config)
} catch {
Self.logger.error("🛰️ SPVCOORD :: startSpv failed: \(String(describing: error), privacy: .public)")
return .failure(StartError.spvClient(error))
}

// The resync marker survives a failed startSpv (the store is empty
// either way; the next launch simply re-applies), and is consumed
// only once the resynced client is actually running.
if appliedChainResync {
SPVChainResyncMarker.clear(for: network)
Self.logger.info("🛰️ SPVCOORD :: chain resync applied on \(network.rawValue, privacy: .public)")
}

runningNetwork = network
lastError = nil
subscribeToManagerProgress(manager: manager)
Expand Down Expand Up @@ -273,6 +290,56 @@ public final class SwiftDashSDKSPVCoordinator: NSObject, ObservableObject {
}
}

// MARK: - Pending chain resync application

/// Apply a pending birth-height chain resync (see `SPVChainResyncMarker`):
/// delete the network's SPV store so the upcoming `startSpv` re-anchors at
/// the restored birth height, and rewind the wallet's live filter
/// checkpoint to the marker height. The rewind is belt-and-suspenders for
/// the arming session having re-raised the persisted `syncedHeight` after
/// the arm (the arming save already rewound the row, which normally feeds
/// the restore); a rewind failure is logged but doesn't retain the marker.
///
/// Returns true when applied — the caller clears the marker once
/// `startSpv` succeeds. Returns false (marker retained) when there is
/// nothing pending, the marker was armed by this process (it must wait
/// for a launch that restores the lowered birth height into Rust), or
/// the store delete failed (retried next launch).
@MainActor
private func applyPendingChainResyncIfNeeded(
for network: Network,
dataDir: String,
manager: PlatformWalletManager
) -> Bool {
guard let pending = SPVChainResyncMarker.pending(for: network) else { return false }
guard !pending.armedByThisSession else {
Self.logger.info("🛰️ SPVCOORD :: chain resync armed this session — deferred to next launch")
return false
}

let dir = URL(fileURLWithPath: dataDir, isDirectory: true)
do {
if FileManager.default.fileExists(atPath: dir.path) {
try FileManager.default.removeItem(at: dir)
}
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
} catch {
Self.logger.error("🛰️ SPVCOORD :: chain resync store delete failed: \(String(describing: error), privacy: .public)")
return false
}

do {
try manager.spvRescanFilters(walletId: pending.walletId, fromHeight: pending.fromHeight)
} catch {
// The wallet may have been wiped since arming (nothing left to
// rescan; the store delete was the safe direction regardless).
Self.logger.error("🛰️ SPVCOORD :: chain resync rescan arm failed: \(String(describing: error), privacy: .public)")
}

Self.logger.info("🛰️ SPVCOORD :: chain store cleared for resync from height \(pending.fromHeight, privacy: .public)")
return true
}

/// After a widened recovery scan reaches `.synced`, mark recovery complete
/// so future launches revert to the fast default gap. One completed wide
/// scan is sufficient: the deep CoinJoin (4') UTXOs it discovered — and
Expand Down Expand Up @@ -457,3 +524,99 @@ public final class SwiftDashSDKSPVCoordinator: NSObject, ObservableObject {
var errorDescription: String? { "Platform SDK does not support \(network.rawValue)" }
}
}

// MARK: - Pending chain resync (birth-height repair)

/// One-shot "clear the SPV chain store and rescan at the next launch"
/// marker, armed by the SPV Status screen when a wallet's birth height is
/// lowered and applied by `SwiftDashSDKSPVCoordinator.performStart`.
///
/// Why a next-launch marker instead of acting immediately: the running Rust
/// wallet's birth height is fed once from `PersistentWallet` when wallets
/// load and has no update FFI, and dash-spv never re-anchors an existing
/// header store (`initialize_genesis_block` returns early when any headers
/// exist). A lowered birth height can therefore only take effect on a launch
/// whose SPV start finds an EMPTY store: the client then anchors at the
/// freshly restored birth height and the filter scan can reach the recovered
/// range. Applying the marker in the session that armed it would delete the
/// store and immediately re-anchor at the stale in-memory birth height,
/// consuming the marker without repairing anything — hence the session guard.
///
/// UserDefaults-backed, per network, one wallet at a time (the repair is a
/// single-wallet diagnostic; arming again overwrites). Follows the
/// `CoinJoinRecovery` pre-start maintenance-flag pattern; lives in this file
/// because `performStart` is its consumer and the SPV Status screen its only
/// producer.
enum SPVChainResyncMarker {

private static let logger = Logger(
subsystem: "org.dashfoundation.dash",
category: "swift-sdk-migration.spv-chain-resync")

/// Stable for the lifetime of this process. A marker armed by this
/// process is only applied by a later one (see type doc).
private static let sessionId = UUID().uuidString

struct Pending {
let walletId: Data
let fromHeight: UInt32
let armedBySessionId: String

var armedByThisSession: Bool { armedBySessionId == SPVChainResyncMarker.sessionId }
}

private static func key(for network: Network) -> String {
"spvChainResync.v1.pending.\(network == .mainnet ? "mainnet" : "testnet")"
}

/// Arm the marker: `network`'s chain store is deleted before the first
/// `startSpv` of a later app session, and `walletId`'s filter checkpoint
/// is rewound to `fromHeight`. Overwrites any pending marker for the
/// network.
static func arm(walletId: Data, fromHeight: UInt32, network: Network) {
UserDefaults.standard.set(
[
"walletId": walletId.hexEncodedString(),
"fromHeight": NSNumber(value: fromHeight),
"sessionId": sessionId,
] as [String: Any],
forKey: key(for: network))
logger.info("🛰️ SPV-RESYNC :: armed for \(network.rawValue, privacy: .public) from height \(fromHeight, privacy: .public)")
}

/// Drop a pending marker for `walletId` (e.g. the birth height was
/// raised again before the resync ran, superseding it). No-op when the
/// pending marker belongs to a different wallet.
static func disarm(walletId: Data, network: Network) {
guard let p = pending(for: network), p.walletId == walletId else { return }
clear(for: network)
logger.info("🛰️ SPV-RESYNC :: disarmed for \(network.rawValue, privacy: .public)")
}

static func pending(for network: Network) -> Pending? {
guard let dict = UserDefaults.standard.dictionary(forKey: key(for: network)),
let walletIdHex = dict["walletId"] as? String,
let walletId = Data(hexString: walletIdHex),
let fromHeight = (dict["fromHeight"] as? NSNumber)?.uint32Value,
let armedBySessionId = dict["sessionId"] as? String else {
return nil
}
return Pending(
walletId: walletId,
fromHeight: fromHeight,
armedBySessionId: armedBySessionId)
}

static func clear(for network: Network) {
UserDefaults.standard.removeObject(forKey: key(for: network))
}

/// Clear pending markers on a wallet wipe: the rows and chain data they
/// reference are gone, so a stale marker would only wipe the next
/// wallet's fresh sync. Clears both networks, mirroring
/// `CoinJoinRecovery.resetForWipe`.
static func resetForWipe() {
clear(for: .mainnet)
clear(for: .testnet)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ final class SwiftDashSDKWalletWiper: NSObject {
CoinJoinRecovery.shared.resetForWipe()
CoinJoinWithdrawalStore.shared.resetForWipe()
ShieldedWithdrawalStore.shared.resetForWipe()
// Pending birth-height chain resyncs reference wallet rows and chain
// data this wipe destroys; a stale marker would only wipe the next
// wallet's fresh sync. UserDefaults-only, safe from this queue.
SPVChainResyncMarker.resetForWipe()
// CrowdNode state is per-wallet-keyed; the wipe destroys every wallet, so
// clear every wallet's keys (the CrowdNode singleton's own
// `DWWillWipeWallet` observer only resets the ACTIVE wallet's keys). Also
Expand Down
Loading
Loading