Skip to content
Closed
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
23 changes: 18 additions & 5 deletions DashWallet/Sources/Models/CrowdNode/CrowdNode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,16 @@ public final class CrowdNode {
// MARK: Restoring state
extension CrowdNode {
func restoreState() {
// The pass scans the persisted history twice with identical arguments
// (`tryRestoreSignUp`, then `getApiAddressConfirmationTx`). On a wallet
// with thousands of transactions that is two full fetch+decode walks
// of the same rows, ~12s each on the calling thread — share one.
TransactionObserver.withSharedScan { performRestoreState() }
}

private func performRestoreState() {
checkAPY()

if signUpState > SignUpState.notStarted {
// Already started/restored
return
Expand Down Expand Up @@ -1049,10 +1057,15 @@ extension CrowdNode {
let filter = CoinsToAddressTxFilter(coins: CrowdNode.apiConfirmationDashAmount, address: nil) // account address is unknown at this point
let forwardedConfirmationFilter = CrowdNodeAPIConfirmationTxForwarded()
// Same floor the signup scan uses: an API-address confirmation is
// CrowdNode protocol traffic, so it cannot predate CrowdNode. Without
// it this walked and decoded the wallet's entire history on the main
// thread during restore — the more expensive of the restore's two
// scans, on a wallet that has no CrowdNode account at all.
// CrowdNode protocol traffic, so it cannot predate CrowdNode.
//
// TODO(crowdnode-restore-floor): the floor bounds `firstSeen`, which
// the SDK stamps from the device clock when it first observes a row —
// so on a restored wallet every row is "first seen" now and the floor
// admits the entire history regardless of its chain date. Bounding on
// `blockTimestamp` (falling back to `firstSeen` while unconfirmed)
// would restore the intent; it needs a SwiftData predicate change that
// has to be verified against the store rather than reasoned about.
let observed = TransactionObserver.fetchObserved(
firstSeenAtOrAfter: FullCrowdNodeSignUpTxSet.januaryFirst2022Epoch)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,76 @@ public final class TransactionObserver {
resolved = DispatchQueue.main.sync { MainActor.assumeIsolated { handles() } }
}
guard let resolved else { return [] }
return scan(
let key = SharedScanKey(
walletId: resolved.walletId,
network: resolved.network,
fetchLimit: fetchLimit,
firstSeenAtOrAfter: firstSeenAtOrAfter)
if let shared = sharedScanResult(for: key) { return shared }
let rows = scan(
container: resolved.container,
walletId: resolved.walletId,
network: resolved.network,
fetchLimit: fetchLimit,
firstSeenAtOrAfter: firstSeenAtOrAfter)
rememberSharedScan(rows, for: key)
return rows
}

// MARK: Per-pass scan sharing

/// Identity of one scan's result: the wallet and network it was read for,
/// plus the arguments that shaped the fetch.
private struct SharedScanKey: Hashable {
let walletId: Data
let network: Network
let fetchLimit: Int?
let firstSeenAtOrAfter: UInt64?
}

private static let sharedScanLock = NSLock()
private static var sharedScanDepth = 0
private static var sharedScanResults: [SharedScanKey: [ObservedTransaction]] = [:]

/// Serves identical `fetchObserved` calls made inside `body` from a single
/// fetch + decode.
///
/// A CrowdNode restore asks the same question twice — `tryRestoreSignUp`
/// and `getApiAddressConfirmationTx` scan with identical arguments — and
/// on a wallet with thousands of transactions each pass cost ~12s of fetch
/// and decode, paid inline by the caller's thread.
///
/// Scoped to the call rather than cached across passes on purpose: a row's
/// `context` / `blockHeight` change as it confirms without the row count
/// moving, so a longer-lived memo would answer `isChainAccepted` from
/// stale data.
static func withSharedScan<T>(_ body: () throws -> T) rethrows -> T {
sharedScanLock.lock()
sharedScanDepth += 1
sharedScanLock.unlock()
defer {
sharedScanLock.lock()
sharedScanDepth -= 1
if sharedScanDepth == 0 {
sharedScanResults.removeAll()
}
sharedScanLock.unlock()
}
return try body()
}
Comment on lines +168 to +197

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Scope shared scan results to one withSharedScan invocation.

sharedScanDepth and sharedScanResults are process-global. If two restore passes overlap, the second pass can reuse the first pass's result for the same key. A row can change between the passes, but the second pass then evaluates stale confirmation data.

Use an invocation-local scan scope. Nested calls in the same restore pass must share that scope. Concurrent restore passes must use separate scopes.

As per coding guidelines, comments must describe behavior that the code actually implements.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@DashWallet/Sources/Models/CrowdNode/Services/TransactionObserver.swift`
around lines 168 - 197, Replace the process-global
sharedScanDepth/sharedScanResults state with an invocation-local scope
propagated through withSharedScan, so nested calls reuse the same results while
concurrent restore passes remain isolated. Update the fetchObserved lookup path
to access the current scope, and revise the surrounding comments to describe the
implemented scope and behavior accurately.

Source: Coding guidelines


private static func sharedScanResult(for key: SharedScanKey) -> [ObservedTransaction]? {
sharedScanLock.lock()
defer { sharedScanLock.unlock() }
guard sharedScanDepth > 0 else { return nil }
return sharedScanResults[key]
}

private static func rememberSharedScan(_ rows: [ObservedTransaction], for key: SharedScanKey) {
sharedScanLock.lock()
defer { sharedScanLock.unlock() }
guard sharedScanDepth > 0 else { return }
sharedScanResults[key] = rows
}

/// Total persisted transaction count, or nil when the SDK host has no
Expand Down
35 changes: 35 additions & 0 deletions DashWallet/Sources/UI/Home/Views/HomeViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ class HomeViewModel: ObservableObject {
/// Tracks whether initial data load has completed (Fix #2)
private var hasCompletedInitialLoad: Bool = false

/// A full reload is running on `queue`. Main-thread-owned: every read and
/// write happens inside `reloadTxDataSource`'s main-actor hop or the
/// completion hop at the end of `performReload`.
private var reloadInFlight = false

/// A reload was requested while one was already running, so the running
/// pass's snapshot is already stale. Exactly one trailing pass is owed —
/// see `reloadTxDataSource`.
private var reloadRequestedWhileInFlight = false

/// Debounce timer for sync state changes to prevent excessive reloads (Fix #4)
private var syncStateDebounceWorkItem: DispatchWorkItem?
private let syncStateDebounceInterval: TimeInterval = 0.5
Expand Down Expand Up @@ -418,6 +428,21 @@ class HomeViewModel: ObservableObject {
// once up front, asynchronously, keeps the pass free-running.
let dispatch = { @MainActor [weak self] in
guard let self else { return }
// Coalesce, never queue. A pass costs seconds once the wallet has
// a few thousand transactions, while the trigger throttle upstream
// is one second — so enqueueing per trigger let `queue` accumulate
// a backlog that grew for as long as the sync wrote rows, each
// queued pass rebuilding a snapshot the next one already
// superseded. (A restore of a large wallet reached ~3.5 minutes of
// queue latency: the list rendered history that old.) At most one
// pass runs and at most one trailing pass is owed; the trailing
// pass reads the store fresh, so dropping the requests in between
// loses nothing.
guard !self.reloadInFlight else {
self.reloadRequestedWhileInFlight = true
return
}
self.reloadInFlight = true
// Pair each request with the filter selection that was live when
// it was made. Reading it inside the pass instead would let a pass
// triggered by one change render a selection the user made after
Expand Down Expand Up @@ -591,6 +616,16 @@ class HomeViewModel: ObservableObject {
if self.hasMasternodeHistory != hasMasternodes {
self.hasMasternodeHistory = hasMasternodes
}

// Release the coalescing gate only after this pass's results are
// on screen, then settle whatever changed while it ran. Ordering
// matters: clearing the request flag before re-entering keeps a
// trigger that lands during the trailing pass from being swallowed.
self.reloadInFlight = false
if self.reloadRequestedWhileInFlight {
self.reloadRequestedWhileInFlight = false
self.reloadTxDataSource()
}
}
}

Expand Down
Loading