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
6 changes: 6 additions & 0 deletions DashWallet.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@
2EFDEC7DCA624B16DBBB482D /* SwiftDashSDKWalletCreator.swift in Sources */ = {isa = PBXBuildFile; fileRef = B697D56A525CBF142F4401FE /* SwiftDashSDKWalletCreator.swift */; };
30C7DE2E26E849E0D76319FA /* PlatformAddressSyncCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6E56673B2BFED8EC0181A1F /* PlatformAddressSyncCoordinator.swift */; };
A1FA10C00000000000000002 /* AssetLockRecoveryService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1FA10C00000000000000001 /* AssetLockRecoveryService.swift */; };
UTR0B0002FA0000000000002 /* UnconfirmedTransactionRemover.swift in Sources */ = {isa = PBXBuildFile; fileRef = UTR0B0002FA0000000000001 /* UnconfirmedTransactionRemover.swift */; };
3116F910F54D310002090CBB /* PinPromptPresenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = D385FC174E5B887CF3398CCD /* PinPromptPresenter.swift */; };
35BFE3D1C0B8999FBC8AB180 /* PaymentRequestVerifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = A59D5720437F8A4137605940 /* PaymentRequestVerifier.swift */; };
3705C73F15BCD91AF70940B9 /* PlatformCreditsFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43C830DD6D63115525925F75 /* PlatformCreditsFormatter.swift */; };
Expand Down Expand Up @@ -930,6 +931,7 @@
8E3AF21ED19AEC0FD89A63FC /* IdentitiesScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 528594007157A56ABDEAD552 /* IdentitiesScreen.swift */; };
8EAA05FA797008525050A2A7 /* PlatformAddressSyncCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6E56673B2BFED8EC0181A1F /* PlatformAddressSyncCoordinator.swift */; };
A1FA10C00000000000000003 /* AssetLockRecoveryService.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1FA10C00000000000000001 /* AssetLockRecoveryService.swift */; };
UTR0B0002FA0000000000003 /* UnconfirmedTransactionRemover.swift in Sources */ = {isa = PBXBuildFile; fileRef = UTR0B0002FA0000000000001 /* UnconfirmedTransactionRemover.swift */; };
8F0B3AA027F569D8D2E1F900 /* PaymentRequestVerifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = A59D5720437F8A4137605940 /* PaymentRequestVerifier.swift */; };
8FCE113ECEA4B9781B24922C /* AuthenticationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EE3302C1C5DF898D1A0F915 /* AuthenticationService.swift */; };
908AB7EFCC69D3828BBD70A8 /* PaymentsLandingHostingController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B401E660599FEF6B18087F91 /* PaymentsLandingHostingController.swift */; };
Expand Down Expand Up @@ -3584,6 +3586,7 @@
E66B030D4B574621DA2C5816 /* PaymentProtocolWireFormat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PaymentProtocolWireFormat.swift; sourceTree = "<group>"; };
E6E56673B2BFED8EC0181A1F /* PlatformAddressSyncCoordinator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PlatformAddressSyncCoordinator.swift; sourceTree = "<group>"; };
A1FA10C00000000000000001 /* AssetLockRecoveryService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AssetLockRecoveryService.swift; sourceTree = "<group>"; };
UTR0B0002FA0000000000001 /* UnconfirmedTransactionRemover.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UnconfirmedTransactionRemover.swift; sourceTree = "<group>"; };
E7333F2D05D0DD2D4373FF9B /* StorageExplorerView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StorageExplorerView.swift; sourceTree = "<group>"; };
E735446F9E918618E97EDD38 /* PaymentsLandingScreen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PaymentsLandingScreen.swift; sourceTree = "<group>"; };
E83D8CEAFF69B6D666C02116 /* Pods-WatchApp.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-WatchApp.release.xcconfig"; path = "Target Support Files/Pods-WatchApp/Pods-WatchApp.release.xcconfig"; sourceTree = "<group>"; };
Expand Down Expand Up @@ -7124,6 +7127,7 @@
E6E56673B2BFED8EC0181A1F /* PlatformAddressSyncCoordinator.swift */,
UM00B0032FA0000000000001 /* UsernameMarketplaceService.swift */,
A1FA10C00000000000000001 /* AssetLockRecoveryService.swift */,
UTR0B0002FA0000000000001 /* UnconfirmedTransactionRemover.swift */,
51AA000D2F97000D005A000D /* ShieldedSyncMonitor.swift */,
43C830DD6D63115525925F75 /* PlatformCreditsFormatter.swift */,
44DCDC3A2B92601BB1E61FD9 /* PlatformSendExecutor.swift */,
Expand Down Expand Up @@ -10152,6 +10156,7 @@
85448D7537BBD0AE40682EC8 /* SwiftDashSDKSPVStatusScreen.swift in Sources */,
8EAA05FA797008525050A2A7 /* PlatformAddressSyncCoordinator.swift in Sources */,
A1FA10C00000000000000003 /* AssetLockRecoveryService.swift in Sources */,
UTR0B0002FA0000000000003 /* UnconfirmedTransactionRemover.swift in Sources */,
2D354A4D6053027CA27F02CB /* PlatformSyncStatusScreen.swift in Sources */,
51AA00222F970022005A0022 /* MasternodesScreen.swift in Sources */,
51AA00022F970002005A0002 /* SyncInfoMenuScreen.swift in Sources */,
Expand Down Expand Up @@ -11158,6 +11163,7 @@
87AC92AAD9DF8CBF271609AC /* SwiftDashSDKSPVStatusScreen.swift in Sources */,
30C7DE2E26E849E0D76319FA /* PlatformAddressSyncCoordinator.swift in Sources */,
A1FA10C00000000000000002 /* AssetLockRecoveryService.swift in Sources */,
UTR0B0002FA0000000000002 /* UnconfirmedTransactionRemover.swift in Sources */,
0308E777B29CC6DE1DB30FDD /* PlatformSyncStatusScreen.swift in Sources */,
51AA00212F970021005A0021 /* MasternodesScreen.swift in Sources */,
51AA00032F970003005A0003 /* SyncInfoMenuScreen.swift in Sources */,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
//
// UnconfirmedTransactionRemover.swift
// DashWallet
//
// Removes a never-accepted transaction from local wallet state — the
// tx-detail "Remove if not on Blockchain" action for a stuck asset
// lock the network keeps rejecting (rebroadcasts end "outcome
// uncertain", the tx is on no explorer, and the coins it tried to
// spend stay locked forever).
//
// There is no removal API at any FFI layer (verified against the
// pinned rust-dashcore/platform revs: key-wallet has no
// reorg/rollback/remove path at all, and `untrack_asset_lock` is
// `pub(crate)` + Built-only). What DOES exist is the restore path:
// on wallet load the Rust side rehydrates its entire core state from
// the SwiftData rows (`loadWalletList` → UTXO/tx-record restore
// buffers), and `spent_outpoints` is documented as "rebuilt from
// `transactions` during deserialization". So removal is performed on
// the persistence layer — delete the transaction row, un-mark the
// TXOs it spent, drop its asset-lock bookmark — followed by a full
// runtime reload, after which the Rust wallet has never heard of the
// transaction and its inputs are spendable again.
// TODO(sdk-remove-tx): replace the persistence surgery with a
// first-class SDK call once one exists upstream.
//
// Ordered safety rails:
// 1. The row must exist locally and be unconfirmed (mempool
// context, no block) — an IS/CL-locked or mined tx is never
// touched.
// 2. A block explorer is consulted first; if it KNOWS the tx, the
// removal is refused (the wallet just needs to catch up). If
// the explorer can't be reached, the removal is refused too —
// "if not on Blockchain" is a checked claim, never a guess.
// 3. After the reload, the wallet's compact-filter checkpoint is
// rewound past the transaction's first-seen time
// (`spvRescanFilters`), so if the explorer was wrong the
// rescan re-discovers the transaction on-chain and restores it.
//
// dashpay + dashwallet targets.
//

import Foundation
import OSLog
import SwiftDashSDK
import SwiftData

@MainActor
struct UnconfirmedTransactionRemover {

private static let logger = Logger(
subsystem: "org.dashfoundation.dash",
category: "swift-sdk-migration.unconfirmed-tx-remover")

enum RemovalError: LocalizedError {
case notReady
case transactionNotFound
case confirmedLocally
case transactionOnChain
case verificationUnavailable

var errorDescription: String? {
switch self {
case .notReady:
return NSLocalizedString("Wallet is not ready", comment: "DashPay")
case .transactionNotFound:
return NSLocalizedString("This transaction is not in the local wallet.", comment: "Remove never-accepted transaction: no local row")
case .confirmedLocally:
return NSLocalizedString("This transaction is confirmed and can't be removed.", comment: "Remove never-accepted transaction: local state says it's on-chain")
case .transactionOnChain:
return NSLocalizedString("Transaction is on the blockchain", comment: "Remove never-accepted transaction: refused because the explorer found it")
case .verificationUnavailable:
return NSLocalizedString("Couldn't reach a block explorer to verify the transaction isn't on the blockchain. Check your connection and try again.", comment: "Remove never-accepted transaction: explorer unreachable")
}
}
}

/// Compact-filter rescan window bounds, in blocks (~2.5 min each):
/// at least ~30 hours even for a fresh transaction, at most ~5 weeks
/// for a long-stuck one.
private static let minRescanBlocks: UInt32 = 720
private static let maxRescanBlocks: UInt32 = 20_000
/// Extra rewind margin below the transaction's first-seen height
/// estimate (~1 day), covering clock skew and variable block times.
private static let rescanMarginBlocks: UInt32 = 576

func remove(txidWire: Data) async throws {
guard let container = SwiftDashSDKHost.shared.modelContainer,
let network = WalletEnvironment.network,
let walletId = WalletEnvironment.activeWalletId(for: WalletEnvironment.networkKind) else {
throw RemovalError.notReady
}
let displayTxid = Transaction.displayHex(txidWire)

// 1. Local sanity — refuse anything the local store believes is
// past the mempool (context 0 = mempool; 1…3 = IS/inBlock/CL).
let context = container.mainContext
var descriptor = FetchDescriptor<PersistentTransaction>(
predicate: #Predicate { $0.txid == txidWire })
descriptor.fetchLimit = 1
guard let row = try context.fetch(descriptor).first else {
throw RemovalError.transactionNotFound
}
guard row.context == 0, row.blockHeight == 0 else {
throw RemovalError.confirmedLocally
}
let firstSeen: UInt64 = row.firstSeen

// 2. The claim in the button title is checked, not assumed: a
// transaction the explorer knows (mempool or mined) is never
// removed, and an unreachable explorer refuses the removal.
if try await Self.explorerKnowsTransaction(displayTxid: displayTxid, network: network) {
Self.logger.notice("🗑️ TX-REMOVE :: refused — explorer reports \(displayTxid, privacy: .public) on the network")
throw RemovalError.transactionOnChain
}

// 3. Persistence surgery. Inputs first: the `.nullify` inverse on
// `PersistentTransaction.inputs` only clears the relationship —
// the denormalized `isSpent` column must be flipped explicitly
// or the restore buffer would keep excluding these TXOs from
// the spendable set.
let unspentInputCount = row.inputs.count
for spent in row.inputs {
spent.isSpent = false
spent.spendingTransaction = nil
spent.spendingInputIndex = nil
spent.lastUpdated = Date()
}
// Deleting the row cascades its own outputs and unresolved
// pending-input placeholders.
context.delete(row)
// The asset-lock bookmark (any vout of this txid): the row that
// makes launch-time recovery re-track and re-broadcast the lock.
// Tiny table — fetch by wallet and filter in Swift, same as
// ShieldedTxLookup.
let lockPrefix = displayTxid.lowercased() + ":"
let locks = try context.fetch(FetchDescriptor<PersistentAssetLock>(
predicate: PersistentAssetLock.predicate(walletId: walletId)))
for lock in locks where lock.outPointHex.lowercased().hasPrefix(lockPrefix) {
context.delete(lock)
}
try context.save()
Self.logger.notice("🗑️ TX-REMOVE :: deleted \(displayTxid, privacy: .public) — \(unspentInputCount, privacy: .public) input(s) unspent")

// 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.
if let metadata = TransactionMetadataDAOImpl.shared.get(by: txidWire) {
TransactionMetadataDAOImpl.shared.delete(dto: metadata)
}

// 4. 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 tx.
await SwiftDashSDKWalletRuntime.shared.rearmPlatformSync()

// 5. Rescan recent compact filters, reaching back past the
// removed transaction's first appearance: if the explorer was
// wrong and the tx IS mined, the re-match finds it and the
// wallet state repairs itself. Best-effort — the removal
// already verified off-chain status; a failed arm is logged,
// not surfaced as a failed removal.
let tip = SwiftDashSDKSPVCoordinator.shared.tipHeight
if tip > 0, let manager = SwiftDashSDKHost.shared.manager {
let ageSeconds = max(0, Date().timeIntervalSince1970 - TimeInterval(firstSeen))
let ageBlocks = UInt32(clamping: Int(ageSeconds / 150)) + Self.rescanMarginBlocks
let blocksBack = min(Self.maxRescanBlocks, max(Self.minRescanBlocks, ageBlocks))
let fromHeight = tip > blocksBack ? tip - blocksBack : 1
do {
try manager.spvRescanFilters(walletId: walletId, fromHeight: fromHeight)
Self.logger.notice("🗑️ TX-REMOVE :: filter rescan armed from height \(fromHeight, privacy: .public) (tip \(tip, privacy: .public))")
} catch {
Self.logger.error("🗑️ TX-REMOVE :: filter rescan arm failed: \(String(describing: error), privacy: .public)")
}
} else {
Self.logger.error("🗑️ TX-REMOVE :: filter rescan skipped — SPV not running after reload")
}

// 6. App caches that mirror the deleted rows.
ShieldedTxLookup.shared.refresh()
}

/// One GET against the network's Insight API. 200 = the explorer
/// knows the tx (mempool or mined); 404 = it doesn't; anything else
/// (including transport failure) refuses the removal rather than
/// guessing.
private static func explorerKnowsTransaction(displayTxid: String, network: Network) async throws -> Bool {
let base = network == .mainnet
? "https://insight.dash.org/insight-api"
: "https://insight.testnet.networks.dash.org/insight-api"
guard let url = URL(string: "\(base)/tx/\(displayTxid)") else {
throw RemovalError.verificationUnavailable
}
var request = URLRequest(url: url)
request.timeoutInterval = 20
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
let http: HTTPURLResponse
do {
let (_, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw RemovalError.verificationUnavailable
}
http = httpResponse
} catch {
throw RemovalError.verificationUnavailable
}
switch http.statusCode {
case 200: return true
case 404: return false
default: throw RemovalError.verificationUnavailable
}
}
}
11 changes: 11 additions & 0 deletions DashWallet/Sources/Models/Transactions/Model/Transaction.swift
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,17 @@ class Transaction: TransactionDataItem, Identifiable {
return (1...3).contains(status)
}

/// The subset of pending identity fundings whose recovery lives in the
/// Join DashPay registration flow (types 0 registration / 3 invitation —
/// the ones `AssetLockRecoveryService` deliberately does NOT handle).
/// Only these get the home row's "tap to finish" routing into that flow;
/// a pending top-up (1/2) recovers from the tx detail sheet instead.
var isPendingIdentityRegistration: Bool {
guard isPendingIdentityFunding,
let type = identityFundingLockInfo?.fundingTypeRaw else { return false }
return type == 0 || type == 3
}

/// True when this incoming tx is the L1 payout of a Shielded → Core
/// withdrawal the app performed — matched by destination address via
/// `ShieldedWithdrawalStore` (the SDK's opaque withdraw call returns no
Expand Down
8 changes: 5 additions & 3 deletions DashWallet/Sources/UI/Home/Views/HomeView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -774,9 +774,11 @@ struct HomeViewContent<Content: View>: View {
subtitle: txItem.shortTimeString,
details: txItem.isPendingShieldedTransfer
? NSLocalizedString("Pending — tap to finish", comment: "InternalTransfer recovery")
: txItem.isPendingIdentityFunding
: txItem.isPendingIdentityRegistration
? NSLocalizedString("Pending — tap to finish", comment: "DashPay registration recovery")
: txItem.isPendingPlatformFunding
// A pending top-up has nothing to "finish" in another
// flow — it recovers from the tx detail sheet.
: txItem.isPendingIdentityFunding || txItem.isPendingPlatformFunding
? NSLocalizedString("Pending", comment: "")
: (metadata?.details?.isEmpty == false
? metadata?.details
Expand All @@ -795,7 +797,7 @@ struct HomeViewContent<Content: View>: View {
// instead of the read-only detail/gift-card sheets.
if txItem.isPendingShieldedTransfer {
self.pendingShieldedRecovery = txItem
} else if txItem.isPendingIdentityFunding {
} else if txItem.isPendingIdentityRegistration {
#if DASHPAY
delegate?.homeViewRequestUsername()
#else
Expand Down
5 changes: 5 additions & 0 deletions DashWallet/Sources/UI/Tx/Details/Model/TxDetailModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,11 @@ extension TxDetailModel {
? NSLocalizedString("Rebroadcast", comment: "Retry a stuck balance transfer whose transaction never confirmed")
: NSLocalizedString("Complete Transfer", comment: "Retry a stuck balance transfer whose transaction confirmed but whose Platform side never finished")
}

/// Local removal is offered only while the network has shown no
/// acceptance at all (built/broadcast). An IS/CL-locked lock is
/// proven on-chain — removing it locally could only corrupt state.
var supportsRemoval: Bool { statusRaw <= 1 }
}

/// Non-nil when this transaction is a funding asset lock parked in a
Expand Down
Loading
Loading