diff --git a/DashWallet.xcodeproj/project.pbxproj b/DashWallet.xcodeproj/project.pbxproj index c7cb77226f..ba04c2d735 100644 --- a/DashWallet.xcodeproj/project.pbxproj +++ b/DashWallet.xcodeproj/project.pbxproj @@ -1016,6 +1016,7 @@ 7A30002230A2000000000022 /* CrowdNodeOwnershipTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A30002130A2000000000021 /* CrowdNodeOwnershipTests.swift */; }; 7A31000230A2000000000002 /* CoinJoinMoveDestinationPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A31000130A2000000000001 /* CoinJoinMoveDestinationPolicyTests.swift */; }; 7A30001230A1000000000012 /* StuckAssetLockRetryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A30001130A1000000000011 /* StuckAssetLockRetryTests.swift */; }; + BABA1000000000000000001F /* AssetLockDiagnosticsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BABA1000000000000000001E /* AssetLockDiagnosticsTests.swift */; }; 7C1177A230A1000000000002 /* InternalTransferNoticeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C1177A130A1000000000001 /* InternalTransferNoticeTests.swift */; }; 727FF6515F1B4A62A03534AD /* CoreShieldedDrainStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4911E48CD7945E7B78664F7 /* CoreShieldedDrainStoreTests.swift */; }; 7C0DE5A1B2C34D5E6F708196 /* CoreShieldedDrainRecipientTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C0DE5A1B2C34D5E6F708195 /* CoreShieldedDrainRecipientTests.swift */; }; @@ -1059,6 +1060,7 @@ 95BBA0F4AB84110658BDB608 /* BIP70SendAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 379F0351A49BFB8CCA87926D /* BIP70SendAuthorizer.swift */; }; 973AD0F3986AFFDBA78ED560 /* CoinJoinWithdrawalStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B208A9A34D0FFEEC796752C /* CoinJoinWithdrawalStore.swift */; }; 7A30002230A1000000000022 /* AssetLockProbeStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A30002130A1000000000021 /* AssetLockProbeStore.swift */; }; + BABA1000000000000000001C /* AssetLockFailureStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = BABA1000000000000000001B /* AssetLockFailureStore.swift */; }; 97C1167F9600BF7E489A8545 /* SwapTransactionStatusHostingController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52B5469F5588395FA0668C4B /* SwapTransactionStatusHostingController.swift */; }; 97E0FFBBAFFB7394F6841B61 /* DWPreviewSeedPhraseModel+Mnemonic.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48D8BC6623C81DD3F008A668 /* DWPreviewSeedPhraseModel+Mnemonic.swift */; }; 926525A3134D15BF737BC355 /* RecoveryPhraseLength.swift in Sources */ = {isa = PBXBuildFile; fileRef = 210C818A8AAC76F91676AFF9 /* RecoveryPhraseLength.swift */; }; @@ -1992,6 +1994,7 @@ D5E6F7A8B9C0D1E2F3A4B5C6 /* TransferAmountView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1D2E3F4A5B6C7D8E9F01234 /* TransferAmountView.swift */; }; D60828F846490A6462E351E9 /* CoinJoinWithdrawalStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B208A9A34D0FFEEC796752C /* CoinJoinWithdrawalStore.swift */; }; 7A30002330A1000000000023 /* AssetLockProbeStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A30002130A1000000000021 /* AssetLockProbeStore.swift */; }; + BABA1000000000000000001D /* AssetLockFailureStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = BABA1000000000000000001B /* AssetLockFailureStore.swift */; }; D6C0C001D6C0C001D6C0C001 /* GiftCardDetailsInfoCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6C0B001D6C0B001D6C0B001 /* GiftCardDetailsInfoCard.swift */; }; D6C0C002D6C0C002D6C0C002 /* GiftCardDetailsMerchantHeader.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6C0B002D6C0B002D6C0B002 /* GiftCardDetailsMerchantHeader.swift */; }; D6C0C003D6C0C003D6C0C003 /* GiftCardPurchaseSelectionSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = D6C0B003D6C0B003D6C0B003 /* GiftCardPurchaseSelectionSheet.swift */; }; @@ -2257,6 +2260,7 @@ 080B9ECCDC82A7B7FF4039C6 /* ScriptAddressCodec.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ScriptAddressCodec.swift; sourceTree = ""; }; 0B208A9A34D0FFEEC796752C /* CoinJoinWithdrawalStore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CoinJoinWithdrawalStore.swift; sourceTree = ""; }; 7A30002130A1000000000021 /* AssetLockProbeStore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AssetLockProbeStore.swift; sourceTree = ""; }; + BABA1000000000000000001B /* AssetLockFailureStore.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AssetLockFailureStore.swift; sourceTree = ""; }; 0C1D2D397047E72188C90FAE /* DWAboutModel+MasternodeSync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = "DWAboutModel+MasternodeSync.swift"; sourceTree = ""; }; 0CE6B29178211061196A0936 /* Pods-WatchApp.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-WatchApp.debug.xcconfig"; path = "Target Support Files/Pods-WatchApp/Pods-WatchApp.debug.xcconfig"; sourceTree = ""; }; 0D2C8F8102C5C603DB63569F /* ShieldedTransferCoordinator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ShieldedTransferCoordinator.swift; sourceTree = ""; }; @@ -3309,6 +3313,7 @@ 7A30002130A2000000000021 /* CrowdNodeOwnershipTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CrowdNodeOwnershipTests.swift; sourceTree = ""; }; 7A31000130A2000000000001 /* CoinJoinMoveDestinationPolicyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoinJoinMoveDestinationPolicyTests.swift; sourceTree = ""; }; 7A30001130A1000000000011 /* StuckAssetLockRetryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StuckAssetLockRetryTests.swift; sourceTree = ""; }; + BABA1000000000000000001E /* AssetLockDiagnosticsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssetLockDiagnosticsTests.swift; sourceTree = ""; }; 7C1177A130A1000000000001 /* InternalTransferNoticeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InternalTransferNoticeTests.swift; sourceTree = ""; }; D4911E48CD7945E7B78664F7 /* CoreShieldedDrainStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreShieldedDrainStoreTests.swift; sourceTree = ""; }; 7C0DE5A1B2C34D5E6F708195 /* CoreShieldedDrainRecipientTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreShieldedDrainRecipientTests.swift; sourceTree = ""; }; @@ -7658,6 +7663,7 @@ 7A30002130A2000000000021 /* CrowdNodeOwnershipTests.swift */, 7A31000130A2000000000001 /* CoinJoinMoveDestinationPolicyTests.swift */, 7A30001130A1000000000011 /* StuckAssetLockRetryTests.swift */, + BABA1000000000000000001E /* AssetLockDiagnosticsTests.swift */, 7C1177A130A1000000000001 /* InternalTransferNoticeTests.swift */, D4911E48CD7945E7B78664F7 /* CoreShieldedDrainStoreTests.swift */, 7C0DE5A1B2C34D5E6F708195 /* CoreShieldedDrainRecipientTests.swift */, @@ -7724,6 +7730,7 @@ UM00B0032FA0000000000001 /* UsernameMarketplaceService.swift */, A1FA10C00000000000000001 /* AssetLockRecoveryService.swift */, 7A30002130A1000000000021 /* AssetLockProbeStore.swift */, + BABA1000000000000000001B /* AssetLockFailureStore.swift */, UTR0B0002FA0000000000001 /* UnconfirmedTransactionRemover.swift */, INSGT0001000000000000001 /* InsightExplorerAPI.swift */, 9F5A428A4E24408592C674A0 /* ShieldedBalanceController.swift */, @@ -10942,6 +10949,7 @@ C05FA6CE3DDE2D0327D334E5 /* CoinJoinRecovery.swift in Sources */, D60828F846490A6462E351E9 /* CoinJoinWithdrawalStore.swift in Sources */, 7A30002330A1000000000023 /* AssetLockProbeStore.swift in Sources */, + BABA1000000000000000001D /* AssetLockFailureStore.swift in Sources */, 950A3F8FA0D89530F227FE25 /* CoinJoinWithdrawalTxSet.swift in Sources */, 99FAE80A3A63E073A2EB5209 /* PaymentProtocolWireFormat.swift in Sources */, 4539AA3FC5C209480BA279AA /* PaymentProtocolMessages.swift in Sources */, @@ -11017,6 +11025,7 @@ 7A30002230A2000000000022 /* CrowdNodeOwnershipTests.swift in Sources */, 7A31000230A2000000000002 /* CoinJoinMoveDestinationPolicyTests.swift in Sources */, 7A30001230A1000000000012 /* StuckAssetLockRetryTests.swift in Sources */, + BABA1000000000000000001F /* AssetLockDiagnosticsTests.swift in Sources */, 7C1177A230A1000000000002 /* InternalTransferNoticeTests.swift in Sources */, 727FF6515F1B4A62A03534AD /* CoreShieldedDrainStoreTests.swift in Sources */, 7C0DE5A1B2C34D5E6F708196 /* CoreShieldedDrainRecipientTests.swift in Sources */, @@ -12065,6 +12074,7 @@ B66294BFAF57B052A74EE77D /* CoinJoinRecovery.swift in Sources */, 973AD0F3986AFFDBA78ED560 /* CoinJoinWithdrawalStore.swift in Sources */, 7A30002230A1000000000022 /* AssetLockProbeStore.swift in Sources */, + BABA1000000000000000001C /* AssetLockFailureStore.swift in Sources */, 931B18EAFD7F2563BFAAF21E /* CoinJoinWithdrawalTxSet.swift in Sources */, 2556F3C5C72D70A771C6C61A /* PaymentProtocolWireFormat.swift in Sources */, C1B995F0556113706D9CDA9A /* PaymentProtocolMessages.swift in Sources */, diff --git a/DashWallet/Sources/Categories/UIViewController+DashWallet.swift b/DashWallet/Sources/Categories/UIViewController+DashWallet.swift index 935abc72a6..751b213de3 100644 --- a/DashWallet/Sources/Categories/UIViewController+DashWallet.swift +++ b/DashWallet/Sources/Categories/UIViewController+DashWallet.swift @@ -87,14 +87,16 @@ extension UIViewController { // Zip the recent SwiftDashSDK log sessions off the main actor // first (blocking file I/O), then compose. App logs stay as // loose attachments — the support workflow already expects - // them — while the SDK sessions ride along as one zip. A - // failed/empty SDK export (e.g. first launch after the update - // that enabled file logging) just omits the zip. + // them — while the SDK sessions ride along as one zip. With no + // SDK session on disk (e.g. first launch after the update that + // enabled file logging) the zip still carries `summary.txt` when + // asset locks are tracked; a failed or empty export omits it. let network = SwiftDashSDKHost.shared.runningNetwork.map { String(describing: $0) } ?? "unknown" let short = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?" let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "?" let appVersion = "\(short) (\(build))" let currentSession = LoggingPreferences.currentSessionDirectory + let assetLocks = DiagnosticLogExporter.captureAssetLocks() Task { [weak self] in let sdkLogsZip = await Task.detached(priority: .userInitiated) { () -> URL? in @@ -102,7 +104,8 @@ extension UIViewController { network: network, appVersion: appVersion, currentSession: currentSession, - appLogFiles: []) + appLogFiles: [], + assetLocks: assetLocks) }.value self?.presentSupportEmailController(sdkLogsZip: sdkLogsZip) } diff --git a/DashWallet/Sources/Infrastructure/DiagnosticLogExporter.swift b/DashWallet/Sources/Infrastructure/DiagnosticLogExporter.swift index cb31249080..f54f0eef9d 100644 --- a/DashWallet/Sources/Infrastructure/DiagnosticLogExporter.swift +++ b/DashWallet/Sources/Infrastructure/DiagnosticLogExporter.swift @@ -14,7 +14,10 @@ // current one. // - The app's own CocoaLumberjack files (`DWLogger`) under // `app-logs/`, newest-first up to a byte cap. -// - A `summary.txt` of build/device context. +// - A `summary.txt` of build/device context, plus every tracked +// asset lock that is not consumed (ticket 32104: a stuck lock's +// txid, input count and last Platform error were nowhere in five +// exports). // // Nothing is uploaded — callers hand the returned zip to a share // sheet or mail composer and the user decides where it goes. @@ -27,8 +30,34 @@ // import Foundation +import SwiftData import SwiftDashSDK +/// One tracked asset lock as `summary.txt` reports it. A plain value so the +/// section's formatting is a pure function: captured on the main actor from +/// the SDK's `PersistentAssetLock` rows, formatted off it. +struct AssetLockDiagnosticRecord: Equatable, Sendable { + /// `PersistentAssetLock.outPointHex` as stored: `:`, + /// display order being the form a block explorer shows. Kept unparsed, so + /// a malformed row is printed as it is rather than with a made-up vout. + let outPointHex: String + let fundingTypeRaw: Int + let statusRaw: Int + let amountDuffs: Int64 + let createdAt: Date + let updatedAt: Date + /// Consensus-encoded transaction when the row carries it; empty after a + /// restore that only rebuilt the outpoint. + let transactionBytes: Data + let lastFailure: AssetLockFailureRecord? + + /// Whether `outPointHex` has the `:` shape the SDK writes. + var outPointIsWellFormed: Bool { + let parts = outPointHex.split(separator: ":", omittingEmptySubsequences: false) + return parts.count == 2 && !parts[0].isEmpty && UInt32(parts[1]) != nil + } +} + enum DiagnosticLogExportError: LocalizedError { case noLogsFound case zipFailed(String) @@ -79,11 +108,15 @@ struct DiagnosticLogExporter { /// - appLogFiles: `DWLogger.sharedInstance().logFiles()`, /// captured by the caller (the shared logger is main-thread /// app infrastructure). + /// - assetLocks: `captureAssetLocks()`, captured by the caller on + /// the main actor (SwiftData main context). `nil` is printed as + /// "unavailable", never as "no locks". static func export( network: String, appVersion: String, currentSession: URL?, - appLogFiles: [URL] + appLogFiles: [URL], + assetLocks: [AssetLockDiagnosticRecord]? ) throws -> URL { let fm = FileManager.default @@ -116,12 +149,16 @@ struct DiagnosticLogExporter { let selectedAppLogs = selectAppLogs(appLogFiles) - guard !selectedSessions.isEmpty || !selectedAppLogs.isEmpty else { + guard hasContentToExport( + sessionCount: selectedSessions.count, + appLogCount: selectedAppLogs.count, + assetLocks: assetLocks + ) else { throw DiagnosticLogExportError.noLogsFound } // Archive stamp: the newest included SDK session, or the - // export moment when only app logs exist. + // export moment when no SDK session is included. let stamp: String if let first = selectedSessions.first { stamp = first.url.lastPathComponent @@ -163,7 +200,8 @@ struct DiagnosticLogExporter { currentIsKnown: current != nil, totalSessionsOnDevice: onDisk.count, appLogCount: selectedAppLogs.count, - totalAppLogsOnDevice: appLogFiles.count + totalAppLogsOnDevice: appLogFiles.count, + assetLocks: assetLocks ) try summary.write( to: staging.appendingPathComponent("summary.txt"), @@ -179,6 +217,21 @@ struct DiagnosticLogExporter { return zipURL } + /// Whether an export has anything to carry. Tracked asset locks count on + /// their own: `summary.txt` reports them even when no log file exists, + /// and the support email attaches app logs loose, never inside the zip, + /// so that caller would otherwise lose the section whenever no SDK + /// session is on disk. An empty or unavailable lock list adds nothing a + /// support reader can use, so it does not make a log-less export worth + /// writing. + static func hasContentToExport( + sessionCount: Int, + appLogCount: Int, + assetLocks: [AssetLockDiagnosticRecord]? + ) -> Bool { + sessionCount > 0 || appLogCount > 0 || !(assetLocks ?? []).isEmpty + } + /// Main-actor entry point: captures the context that must be read on /// the main actor, then runs the blocking staging + zip detached. /// Shared by every caller that offers a log export (Tools menu row, @@ -195,6 +248,7 @@ struct DiagnosticLogExporter { // rollback or a stale future-dated directory. let currentSession = LoggingPreferences.currentSessionDirectory let appLogFiles = DWLogger.sharedInstance().logFiles() + let assetLocks = captureAssetLocks() return await Task.detached(priority: .userInitiated) { Result { @@ -202,12 +256,124 @@ struct DiagnosticLogExporter { network: network, appVersion: appVersion, currentSession: currentSession, - appLogFiles: appLogFiles + appLogFiles: appLogFiles, + assetLocks: assetLocks ) } }.value } + /// Every asset lock the active wallet tracks whose status is not + /// `Consumed`, joined with the app-side record of its last retry failure. + /// Reads the SwiftData main context, so main actor only. `nil` when no + /// wallet is running or the fetch fails — the summary then says so + /// rather than claiming there are no locks. + @MainActor + static func captureAssetLocks() -> [AssetLockDiagnosticRecord]? { + guard let walletId = SwiftDashSDKHost.shared.wallet?.walletId, + let container = SwiftDashSDKHost.shared.modelContainer + else { return nil } + return captureAssetLocks( + walletId: walletId, + context: container.mainContext, + failureStore: .shared) + } + + /// The capture over a given context and failure store, so a test runs the + /// real fetch, filter and join against an in-memory container. `nil` when + /// the fetch fails. + @MainActor + static func captureAssetLocks( + walletId: Data, + context: ModelContext, + failureStore: AssetLockFailureStore + ) -> [AssetLockDiagnosticRecord]? { + let descriptor = FetchDescriptor( + predicate: PersistentAssetLock.predicate(walletId: walletId), + sortBy: [SortDescriptor(\.createdAt)]) + guard let rows = try? context.fetch(descriptor) else { return nil } + let failures = failureStore.allFailures() + return rows.compactMap { row in + guard row.statusRaw != consumedAssetLockStatus else { return nil } + return AssetLockDiagnosticRecord( + outPointHex: row.outPointHex, + fundingTypeRaw: row.fundingTypeRaw, + statusRaw: row.statusRaw, + amountDuffs: row.amountDuffs, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + transactionBytes: row.transactionBytes, + lastFailure: failures[row.outPointHex]) + } + } + + /// `AssetLockStatus::Consumed` as it crosses the FFI — the one terminal + /// success, and the only status the section leaves out. + static let consumedAssetLockStatus = Int(ManagedAssetLockManager.AssetLockStatus.consumed.rawValue) + + /// The asset-lock section of `summary.txt`, one block per lock. Pure: + /// `nil` records means the capture could not run (no wallet, fetch + /// failed) and is reported as such, never as "no locks". + static func assetLockSection(_ records: [AssetLockDiagnosticRecord]?) -> [String] { + let iso = ISO8601DateFormatter() + var lines = ["Asset locks tracked by the active wallet (status other than Consumed):"] + guard let records else { + lines.append(" unavailable (no wallet running, or the asset-lock store could not be read)") + return lines + } + guard !records.isEmpty else { + lines.append(" none") + return lines + } + for record in records { + let outPointNote = record.outPointIsWellFormed ? "" : " (stored outpoint did not parse)" + lines.append( + " \(record.outPointHex)\(outPointNote) " + + "type=\(record.fundingTypeRaw) (\(fundingTypeName(record.fundingTypeRaw))) " + + "status=\(record.statusRaw) (\(assetLockStatusName(record.statusRaw))) " + + "amount=\(record.amountDuffs) duffs") + lines.append( + " created=\(iso.string(from: record.createdAt)) " + + "updated=\(iso.string(from: record.updatedAt))") + if record.transactionBytes.isEmpty { + lines.append(" inputs=? size=? (transaction bytes not stored locally)") + } else if let parsed = try? ParsedRawTransaction(data: record.transactionBytes) { + lines.append( + " inputs=\(parsed.inputs.count) outputs=\(parsed.outputs.count) " + + "size=\(record.transactionBytes.count) bytes") + } else { + lines.append( + " inputs=? size=\(record.transactionBytes.count) bytes " + + "(stored transaction bytes did not parse)") + } + if let failure = record.lastFailure { + lines.append( + " last failure (\(iso.string(from: failure.recordedAt))): " + + failure.logDescription) + } else { + lines.append(" last failure: none recorded") + } + } + return lines + } + + /// `AssetLockFundingType` discriminant → SDK case name; raw values the + /// linked SDK does not know stay numeric rather than being guessed. + static func fundingTypeName(_ raw: Int) -> String { + guard raw >= 0, let value = UInt32(exactly: raw), + let type = ManagedAssetLockManager.FundingType(rawValue: value) + else { return "unknown" } + return String(describing: type) + } + + /// `AssetLockStatus` discriminant → SDK case name. + static func assetLockStatusName(_ raw: Int) -> String { + guard raw >= 0, let value = UInt32(exactly: raw), + let status = ManagedAssetLockManager.AssetLockStatus(rawValue: value) + else { return "unknown" } + return String(describing: status) + } + /// Pure SDK-session selection policy, split out for unit testing. /// /// The current session (when known) is always first and always @@ -321,7 +487,8 @@ struct DiagnosticLogExporter { currentIsKnown: Bool, totalSessionsOnDevice: Int, appLogCount: Int, - totalAppLogsOnDevice: Int + totalAppLogsOnDevice: Int, + assetLocks: [AssetLockDiagnosticRecord]? ) -> String { let iso = ISO8601DateFormatter() let sizeFormatter = ByteCountFormatter() @@ -374,6 +541,8 @@ struct DiagnosticLogExporter { + "\(sizeFormatter.string(fromByteCount: Int64(maxSDKSessionBytes))) raw) and " + "\(appLogCount) of \(totalAppLogsOnDevice) app log file(s) under app-logs/ " + "(limit: \(sizeFormatter.string(fromByteCount: Int64(maxAppLogBytes)))).") + lines.append("") + lines.append(contentsOf: assetLockSection(assetLocks)) return lines.joined(separator: "\n") + "\n" } } diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockFailureStore.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockFailureStore.swift new file mode 100644 index 0000000000..6f0e676f45 --- /dev/null +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockFailureStore.swift @@ -0,0 +1,353 @@ +// +// AssetLockFailureStore.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Foundation +import OSLog +import SwiftDashSDK + +/// The last failure a tracked asset lock's retry produced, as the diagnostic +/// export prints it. +/// +/// Ticket 32104: a lock refused by Platform with a consensus error that cannot +/// change (too many inputs) looked identical to a lock waiting on the network +/// in every log export, because the error existed only in the alert the user +/// dismissed. Recording the typed error case next to the outpoint lets +/// `summary.txt` say why a lock is stuck without re-running the retry. +struct AssetLockFailureRecord: Codable, Equatable, Sendable { + /// The typed error case (`assetLockTooManyInputs`, `consensusRejection`, + /// `transferFailed`…) — the searchable part. + let errorCase: String + /// The error's own text: the SDK detail string, with the consensus code + /// in front when the rejection carried one. + let detail: String + let recordedAt: Date + + /// One log-line form: `case= detail=`. + var logDescription: String { + "case=\(errorCase) detail=\(detail)" + } + + /// Name the error by its typed case and keep its detail string, unwrapping + /// the coordinator's `transferFailed` envelope so a Platform rejection + /// reaches the log as `assetLockTooManyInputs` / `consensusRejection` + /// rather than as the envelope's name. + /// + /// Pure: callable from tests with any `Error`. + static func describe(_ error: Error, at date: Date = Date()) -> AssetLockFailureRecord { + if case ShieldedTransferCoordinator.CoordinatorError.transferFailed(let inner) = error { + return describe(inner, at: date) + } + // The recovery service reports a coordinator route's failure by its + // display text; the typed error it came from rides along. + if case AssetLockRecoveryService.RecoveryError.failed(_, let underlying?) = error { + return describe(underlying, at: date) + } + if let platformError = error as? PlatformWalletError { + var detail = platformError.errorDescription ?? String(describing: platformError) + if case .consensusRejection(let consensus, _) = platformError { + detail = "consensus code=\(consensus.code) kind=\(consensus.kind) \(detail)" + } + if let reason = platformError.failureReason { + detail += " reason=\(reason)" + } + return AssetLockFailureRecord( + errorCase: caseName(of: platformError) ?? String(describing: type(of: platformError)), + detail: detail, + recordedAt: date) + } + let typeName = String(describing: type(of: error)) + let errorCase = caseName(of: error).map { "\(typeName).\($0)" } ?? typeName + let detail = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription + return AssetLockFailureRecord(errorCase: errorCase, detail: detail, recordedAt: date) + } + + /// The enum case label without its payload. A payload-less case has no + /// mirror child, so its description is already the bare name. `nil` for + /// an error that is not an enum: a struct's first child is a stored + /// property (`URLError._nsError`), and an `NSError`'s description is its + /// whole `Error Domain=… UserInfo={…}` dump, neither of which names a case. + private static func caseName(of error: Error) -> String? { + let mirror = Mirror(reflecting: error) + guard mirror.displayStyle == .enum else { return nil } + if let label = mirror.children.first?.label { + return label + } + return String(describing: error) + } +} + +/// App-side memory of the last retry failure per tracked asset lock, keyed by +/// outpoint (`:`, the `PersistentAssetLock.outPointHex` +/// form) so the entry survives a restore that rebuilds the SDK row. +/// +/// Written only where the network call that tried the lock threw: the +/// transfer coordinator's resume calls and the recovery service's identity +/// top-up. A refusal before that call (no wallet, PIN timeout, wallet +/// switched) is logged but never stored, so it cannot overwrite the failure +/// that says why the lock is stuck. +/// +/// Advisory and bounded: the newest `limit` outpoints are kept, the oldest +/// recorded entries are evicted first. Losing it costs one line in a log +/// export, never money. `shared` is the production instance: the diagnostic +/// export reads it from a main-actor static with no owner to inject from, +/// while the coordinator and the service take it by injection, and tests +/// construct their own over a private `UserDefaults` suite. +final class AssetLockFailureStore { + + /// Outpoint key → last failure. Named so the decode site can spell the + /// type without a dictionary-literal expression. + typealias FailureMap = [String: AssetLockFailureRecord] + + static let shared = AssetLockFailureStore() + + /// Outpoints retained. Restored wallets routinely carry dozens of + /// `RecoveredFromChain` locks, so the cap is the bulk pass's working set + /// plus headroom, not a handful. + static let defaultLimit = 50 + + private let defaults: UserDefaults + private let limit: Int + private let lock = NSLock() + private let key = "assetLockFailure.v1.byOutPoint" + private var cache: [String: AssetLockFailureRecord]? + + init(defaults: UserDefaults = .standard, limit: Int = AssetLockFailureStore.defaultLimit) { + self.defaults = defaults + self.limit = max(1, limit) + } + + /// `:` — the same key `PersistentAssetLock.outPointHex` + /// carries, so the export can join the two without a byte-order step. + static func outPointKey(txidWire: Data, vout: UInt32) -> String { + displayHex(txidWire: txidWire) + ":\(vout)" + } + + /// Wire-order txid bytes as the display-order hex a block explorer shows. + static func displayHex(txidWire: Data) -> String { + txidWire.reversed().map { String(format: "%02x", $0) }.joined() + } + + /// Remember `error` as the last failure of the lock at `txidWire:vout`. + /// Thread-safe; evicts the oldest entries past the cap. + @discardableResult + func record(txidWire: Data, vout: UInt32, error: Error, at date: Date = Date()) -> AssetLockFailureRecord { + let failure = AssetLockFailureRecord.describe(error, at: date) + record(failure, forOutPointKey: Self.outPointKey(txidWire: txidWire, vout: vout)) + return failure + } + + func record(_ record: AssetLockFailureRecord, forOutPointKey key: String) { + lock.lock(); defer { lock.unlock() } + var all = loaded() + all[key] = record + all = Self.bounded(all, limit: limit) + cache = all + persist(all) + } + + /// The last recorded failure for an outpoint, if any. + func failure(txidWire: Data, vout: UInt32) -> AssetLockFailureRecord? { + failure(forOutPointKey: Self.outPointKey(txidWire: txidWire, vout: vout)) + } + + func failure(forOutPointKey key: String) -> AssetLockFailureRecord? { + lock.lock(); defer { lock.unlock() } + return loaded()[key] + } + + /// Every stored entry, for the diagnostic export's join. + func allFailures() -> [String: AssetLockFailureRecord] { + lock.lock(); defer { lock.unlock() } + return loaded() + } + + /// Full wipe: outpoints are gone with the wallets, so the whole map goes. + func resetForWipe() { + lock.lock(); defer { lock.unlock() } + defaults.removeObject(forKey: key) + cache = nil + } + + /// Keep the `limit` most recently recorded entries. Pure, so the eviction + /// order is testable without a `UserDefaults`. + static func bounded( + _ entries: [String: AssetLockFailureRecord], + limit: Int + ) -> [String: AssetLockFailureRecord] { + guard entries.count > limit else { return entries } + let kept = entries + .sorted { lhs, rhs in + if lhs.value.recordedAt != rhs.value.recordedAt { + return lhs.value.recordedAt > rhs.value.recordedAt + } + return lhs.key < rhs.key + } + .prefix(limit) + return Dictionary(uniqueKeysWithValues: kept.map { ($0.key, $0.value) }) + } + + private func loaded() -> [String: AssetLockFailureRecord] { + if let cache { return cache } + var decoded: [String: AssetLockFailureRecord] = [:] + if let data = defaults.data(forKey: key) { + let stored: [String: AssetLockFailureRecord]? = + try? JSONDecoder().decode(FailureMap.self, from: data) + decoded = stored ?? [:] + } + cache = decoded + return decoded + } + + private func persist(_ entries: [String: AssetLockFailureRecord]) { + guard let data = try? JSONEncoder().encode(entries) else { return } + defaults.set(data, forKey: key) + } +} + +/// The one format every asset-lock retry outcome is logged in, whichever +/// surface ran the retry (transaction details, the bulk pass, the transfer +/// sheet's resume). Lines go to os_log AND to `DWLogger`, whose files are what +/// a diagnostic export carries — os_log alone never reaches support. +enum AssetLockRetryLog { + static let lockRetryPrefix = "🔁 LOCK-RETRY ::" + static let shieldPrefix = "🛡️ SHIELD-TX ::" + + private static let logger = Logger( + subsystem: "org.dashfoundation.dash", + category: "swift-sdk-migration.asset-lock-retry") + + /// ` txid=: type= () + /// statusBefore= () `. Pure, so the format is pinned by + /// a test. + static func line( + prefix: String, + event: String, + txidWire: Data, + vout: UInt32, + fundingTypeRaw: Int, + statusBeforeRaw: Int?, + result: String + ) -> String { + let outPoint = AssetLockFailureStore.outPointKey(txidWire: txidWire, vout: vout) + let type = "\(fundingTypeRaw) (\(DiagnosticLogExporter.fundingTypeName(fundingTypeRaw)))" + let status = statusBeforeRaw + .map { "\($0) (\(DiagnosticLogExporter.assetLockStatusName($0)))" } ?? "unknown" + return "\(prefix) \(event) txid=\(outPoint) type=\(type) statusBefore=\(status) \(result)" + } + + /// ` bulk count= `: a line about a bulk pass as a whole, + /// for an outcome no single lock produced (the pass's one PIN prompt). + /// Pure, so the format is pinned by a test. + static func bulkLine(count: Int, result: String) -> String { + "\(lockRetryPrefix) bulk count=\(count) \(result)" + } + + /// Log a pass-level outcome. Never touches the failure store: nothing in + /// it is a failure of one lock. + static func logBulkOutcome(_ result: String, count: Int) { + write(bulkLine(count: count, result: result), isFailure: false) + } + + /// Write a finished line to both sinks. + static func write(_ line: String, isFailure: Bool) { + if isFailure { + logger.error("\(line, privacy: .public)") + } else { + logger.info("\(line, privacy: .public)") + } + DWLogger.log(line) + } + + /// Log a non-failure outcome (`result` is e.g. `outcome=completed`). + static func logOutcome( + _ result: String, + prefix: String = lockRetryPrefix, + event: String, + txidWire: Data, + vout: UInt32, + fundingTypeRaw: Int, + statusBeforeRaw: Int? + ) { + write( + line(prefix: prefix, event: event, txidWire: txidWire, vout: vout, + fundingTypeRaw: fundingTypeRaw, statusBeforeRaw: statusBeforeRaw, result: result), + isFailure: false) + } + + /// Log a failed retry with its typed case and detail. Log only: the + /// surfaces that call this (transaction details, the bulk pass) see every + /// failure, including refusals that never reached Platform, and storing + /// those would overwrite the failure that says why the lock is stuck. + static func logFailure( + _ error: Error, + prefix: String = lockRetryPrefix, + event: String, + txidWire: Data, + vout: UInt32, + fundingTypeRaw: Int, + statusBeforeRaw: Int? + ) { + write( + line(prefix: prefix, event: event, txidWire: txidWire, vout: vout, + fundingTypeRaw: fundingTypeRaw, statusBeforeRaw: statusBeforeRaw, + result: "FAILED \(AssetLockFailureRecord.describe(error).logDescription)"), + isFailure: true) + } + + /// The network call that tried the lock threw: store `error` as the + /// lock's last failure, then log it. Called only at that call. + @discardableResult + static func recordFailure( + _ error: Error, + prefix: String = lockRetryPrefix, + event: String, + txidWire: Data, + vout: UInt32, + fundingTypeRaw: Int, + statusBeforeRaw: Int?, + store: AssetLockFailureStore + ) -> AssetLockFailureRecord { + let record = store.record(txidWire: txidWire, vout: vout, error: error) + write( + line(prefix: prefix, event: event, txidWire: txidWire, vout: vout, + fundingTypeRaw: fundingTypeRaw, statusBeforeRaw: statusBeforeRaw, + result: "FAILED \(record.logDescription)"), + isFailure: true) + return record + } + + /// The attempt stopped before its network call (no wallet, PIN timeout, + /// drain recipient unknown…): logged as an outcome with its typed case, + /// never stored, because it says nothing about why the lock is stuck. + static func logRefusal( + _ error: Error, + prefix: String = lockRetryPrefix, + event: String, + txidWire: Data, + vout: UInt32, + fundingTypeRaw: Int, + statusBeforeRaw: Int? + ) { + write( + line(prefix: prefix, event: event, txidWire: txidWire, vout: vout, + fundingTypeRaw: fundingTypeRaw, statusBeforeRaw: statusBeforeRaw, + result: "outcome=refused \(AssetLockFailureRecord.describe(error).logDescription)"), + isFailure: true) + } +} diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockRecoveryService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockRecoveryService.swift index 5f7d9faf29..6679c19df6 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockRecoveryService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockRecoveryService.swift @@ -33,6 +33,14 @@ import SwiftData @MainActor struct AssetLockRecoveryService { + /// Where an identity top-up whose network call threw records the error, + /// and what the coordinator routes are handed for theirs. + private let failureStore: AssetLockFailureStore + + init(failureStore: AssetLockFailureStore = .shared) { + self.failureStore = failureStore + } + private static let logger = Logger( subsystem: "org.dashfoundation.dash", category: "swift-sdk-migration.asset-lock-recovery") @@ -41,7 +49,10 @@ struct AssetLockRecoveryService { case notReady case noIdentity case unsupportedRoute - case failed(String) + /// A coordinator route's terminal failure: the text it showed, and + /// the typed error behind it (`coordinator.lastFailure`) so the log + /// and the failure store can name the case. + case failed(String, underlying: Error? = nil) var errorDescription: String? { switch self { @@ -51,7 +62,7 @@ struct AssetLockRecoveryService { return NSLocalizedString("This wallet has no identity to top up.", comment: "Asset-lock retry: identity top-up with no identity") case .unsupportedRoute: return NSLocalizedString("This transfer can't be retried from here.", comment: "Asset-lock retry: unsupported funding route") - case .failed(let message): + case .failed(let message, _): return message } } @@ -148,7 +159,7 @@ struct AssetLockRecoveryService { // terminal phase rather than throwing, so the resume call and // the phase check stay one pair — a future route added here // can't forget the check. - let coordinator = ShieldedTransferCoordinator() + let coordinator = ShieldedTransferCoordinator(failureStore: failureStore) if fundingTypeRaw == 4 { let recipientAmountDuffs = try Self.coreToPlatformRecipientAmountDuffs( txidWire: txidWire, @@ -206,6 +217,8 @@ struct AssetLockRecoveryService { let txidWire: Data let vout: UInt32 let fundingTypeRaw: Int + /// Status when the pass picked the lock up, for the outcome log line. + let statusRaw: Int } /// What a bulk pass ended up doing. @@ -312,7 +325,8 @@ struct AssetLockRecoveryService { return PendingRecovery( txidWire: txidWire, vout: entry.info.vout, - fundingTypeRaw: entry.info.fundingTypeRaw) + fundingTypeRaw: entry.info.fundingTypeRaw, + statusRaw: entry.info.statusRaw) } } @@ -337,6 +351,7 @@ struct AssetLockRecoveryService { try await DWIdentityAuthorizer().authorize() } catch DWIdentityAuthorizer.AuthError.cancelled { outcome.cancelled = true + AssetLockRetryLog.logBulkOutcome("outcome=cancelled before the first lock", count: pending.count) return outcome } catch { // Authentication can also time out or fail outright. Reporting @@ -366,8 +381,7 @@ struct AssetLockRecoveryService { DWLogger.log("LOCK-RETRY bulk start count=\(pending.count)") for (index, item) in pending.enumerated() { - let txidDisplay = String(Data(item.txidWire.reversed()) - .map { String(format: "%02x", $0) }.joined().prefix(16)) + let event = "bulk \(index + 1)/\(pending.count)" do { let result = try await retry( fundingTypeRaw: item.fundingTypeRaw, @@ -384,19 +398,37 @@ struct AssetLockRecoveryService { case .submittedAwaitingSync: step = .awaitingSync } Self.apply(step, to: &outcome, consecutiveFailures: &consecutiveFailures) - DWLogger.log("LOCK-RETRY bulk \(index + 1)/\(pending.count) \(txidDisplay)… -> \(result)") + AssetLockRetryLog.logOutcome( + "outcome=\(result)", + event: event, + txidWire: item.txidWire, + vout: item.vout, + fundingTypeRaw: item.fundingTypeRaw, + statusBeforeRaw: item.statusRaw) } catch DWIdentityAuthorizer.AuthError.cancelled { Self.apply(.cancelled, to: &outcome, consecutiveFailures: &consecutiveFailures) - DWLogger.log("LOCK-RETRY bulk cancelled at \(index + 1)/\(pending.count)") + AssetLockRetryLog.logOutcome( + "outcome=cancelled", + event: event, + txidWire: item.txidWire, + vout: item.vout, + fundingTypeRaw: item.fundingTypeRaw, + statusBeforeRaw: item.statusRaw) return outcome } catch { let message = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription let stop = Self.apply(.failed(message), to: &outcome, consecutiveFailures: &consecutiveFailures) // File logger, not just OSLog: a bulk pass that fails is - // exactly what a diagnostic export needs to carry. - DWLogger.log("LOCK-RETRY bulk \(index + 1)/\(pending.count) \(txidDisplay)… FAILED: \(message)") - Self.logger.error("🔁 LOCK-RETRY :: bulk item failed: \(String(describing: error), privacy: .public)") + // exactly what a diagnostic export needs to carry, with the + // typed error case so a consensus refusal is searchable. + AssetLockRetryLog.logFailure( + error, + event: event, + txidWire: item.txidWire, + vout: item.vout, + fundingTypeRaw: item.fundingTypeRaw, + statusBeforeRaw: item.statusRaw) if stop { DWLogger.log("LOCK-RETRY bulk stopped after \(consecutiveFailures) consecutive failures") @@ -478,10 +510,18 @@ struct AssetLockRecoveryService { throw RecoveryError.noIdentity } try await DWIdentityAuthorizer().authorize() - _ = try await wallet.resumeTopUpWithAssetLock( - identityId: identityId, - outPointTxid: txidWire, - outPointVout: vout) + do { + _ = try await wallet.resumeTopUpWithAssetLock( + identityId: identityId, + outPointTxid: txidWire, + outPointVout: vout) + } catch { + // The top-up call itself tried the lock, so its error is the + // lock's last failure. The refusals above are not stored: they say + // nothing about the lock. The caller logs the outcome line. + failureStore.record(txidWire: txidWire, vout: vout, error: error) + throw error + } DWCurrentUserIdentityInfo.shared.refreshFromSDK() } @@ -496,6 +536,6 @@ struct AssetLockRecoveryService { case .authCancelled = failure { throw DWIdentityAuthorizer.AuthError.cancelled } - throw RecoveryError.failed(message) + throw RecoveryError.failed(message, underlying: coordinator.lastFailure) } } diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift index 8f539831fb..0bd03f559d 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift @@ -334,6 +334,7 @@ final class SwiftDashSDKWalletWiper: NSObject { CoinJoinWithdrawalStore.shared.resetForWipe() ShieldedWithdrawalStore.shared.resetForWipe() AssetLockProbeStore.shared.resetForWipe() + AssetLockFailureStore.shared.resetForWipe() SPVChainResyncMarker.resetForWipe() // Marker files behind their own lock; safe on this queue too. SPVChainStoreRebuild.clearAll() diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedTransferCoordinator.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedTransferCoordinator.swift index 1da26dc246..898cc9096b 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedTransferCoordinator.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedTransferCoordinator.swift @@ -271,6 +271,15 @@ final class ShieldedTransferCoordinator: ObservableObject { private let authorizer = DWIdentityAuthorizer() private var assetLockPollingTask: Task? + /// Where a resume whose network call threw records the error as the + /// lock's last failure. Injected so a test reads what it wrote without + /// touching the shared store. + private let failureStore: AssetLockFailureStore + + init(failureStore: AssetLockFailureStore = .shared) { + self.failureStore = failureStore + } + /// Outpoint (wire-order txid + vout) of the asset lock observed during the /// most recent in-flight `performAssetLock`, captured from polling so a /// failed attempt's "Try again" can RESUME the existing lock instead of @@ -780,12 +789,60 @@ final class ShieldedTransferCoordinator: ObservableObject { ) async { guard beginTransfer() else { return } Self.logger.info("🛡️ SHIELD-TX :: resume asset-lock vout=\(outPointVout) external=\(recipientOverride != nil)") + // Read before the resume moves it, for the outcome lines below. + let statusBeforeRaw = ShieldedTxLookup.shared + .info(forTxidHex: AssetLockFailureStore.displayHex(txidWire: outPointTxidWire))?.statusRaw + + // Every attempt past the single-flight gate leaves one outcome line. + // The confirm sheets, the recovery sheet and the CoinJoin move call + // this directly, with no service-level logger behind them, so a + // refusal before the resume call is logged here too. Only an error + // from the resume call itself is stored as the lock's last failure: a + // refusal (no wallet, PIN timeout, wallet switched) says nothing about + // the lock and must not overwrite the failure that does. A cancelled + // PIN prompt is an outcome, not a failure. + func logResumeOutcome(_ result: String) { + AssetLockRetryLog.logOutcome( + result, + prefix: AssetLockRetryLog.shieldPrefix, + event: "resume", + txidWire: outPointTxidWire, + vout: outPointVout, + fundingTypeRaw: Self.shieldedAssetLockFundingType, + statusBeforeRaw: statusBeforeRaw) + } + func recordResumeFailure(_ error: Error) { + AssetLockRetryLog.recordFailure( + error, + prefix: AssetLockRetryLog.shieldPrefix, + event: "resume", + txidWire: outPointTxidWire, + vout: outPointVout, + fundingTypeRaw: Self.shieldedAssetLockFundingType, + statusBeforeRaw: statusBeforeRaw, + store: failureStore) + } + func failBeforeResume(_ error: Error) { + if case CoordinatorError.authCancelled = error { + logResumeOutcome("outcome=cancelled") + } else { + AssetLockRetryLog.logRefusal( + error, + prefix: AssetLockRetryLog.shieldPrefix, + event: "resume", + txidWire: outPointTxidWire, + vout: outPointVout, + fundingTypeRaw: Self.shieldedAssetLockFundingType, + statusBeforeRaw: statusBeforeRaw) + } + handleFailure(error) + } let env: Environment do { env = try resolveEnvironment() } catch { - handleFailure(error) + failBeforeResume(error) return } @@ -800,7 +857,7 @@ final class ShieldedTransferCoordinator: ObservableObject { outPointTxidWire: outPointTxidWire, vout: outPointVout, walletId: env.walletId, in: env.modelContainer) else { - handleFailure(CoordinatorError.drainRecipientUnavailable) + failBeforeResume(CoordinatorError.drainRecipientUnavailable) return } Self.logger.info("🛡️ SHIELD-TX :: resume drain row=\(String(describing: row), privacy: .public)") @@ -812,15 +869,15 @@ final class ShieldedTransferCoordinator: ObservableObject { case .external(let raw43): resolved = raw43 case .refuse: Self.logger.error("🛡️ SHIELD-TX :: resume refused — drain recipient unknown") - handleFailure(CoordinatorError.drainRecipientUnknown) + failBeforeResume(CoordinatorError.drainRecipientUnknown) return case .retryLater: - handleFailure(CoordinatorError.drainRecipientUnavailable) + failBeforeResume(CoordinatorError.drainRecipientUnavailable) return } if let recipientOverride, recipientOverride != (resolved ?? env.shieldedRecipient) { Self.logger.error("🛡️ SHIELD-TX :: resume refused — caller recipient disagrees with the drain marker") - handleFailure(CoordinatorError.drainRecipientUnknown) + failBeforeResume(CoordinatorError.drainRecipientUnknown) return } recipientRaw43 = resolved @@ -830,13 +887,13 @@ final class ShieldedTransferCoordinator: ObservableObject { do { try await authorize() } catch { - handleFailure(error) + failBeforeResume(error) return } guard isStillBound(binding, env: env) else { Self.logger.error("🛡️ SHIELD-TX :: resume refused — the active wallet changed") - handleFailure(CoordinatorError.noWallet) + failBeforeResume(CoordinatorError.noWallet) return } @@ -844,7 +901,7 @@ final class ShieldedTransferCoordinator: ObservableObject { do { _ = try CoreShieldedDrainService().manager(for: drainContext) } catch { - handleFailure(error) + failBeforeResume(error) return } } @@ -865,11 +922,20 @@ final class ShieldedTransferCoordinator: ObservableObject { outPointVout: outPointVout, recipients: [recipient]) terminalPhase = .success + logResumeOutcome("outcome=completed") } catch { guard let mappedPhase = Self.alreadyConsumedAssetLockResumePhase(for: error) else { + // `shieldedSpendUnconfirmed` was accepted by relay, so it is + // not a failure of this lock and is not stored as one. + if case PlatformWalletError.shieldedSpendUnconfirmed = error { + logResumeOutcome("outcome=submittedUnconfirmed") + } else { + recordResumeFailure(error) + } handleSpendError(error, manager: env.manager) return } + logResumeOutcome("outcome=alreadyConsumed") // A DAPI endpoint reported this exact outpoint as consumed, but // rejection responses are not quorum-authenticated. Rust retains // the ChainLock proof and records nonterminal consumption-unknown @@ -1407,12 +1473,23 @@ final class ShieldedTransferCoordinator: ObservableObject { // The lock is already on-chain; only the funding ST remains. phase = .broadcasting + let statusBeforeRaw = ShieldedTxLookup.shared + .platformFundingInfo(forTxidHex: AssetLockFailureStore.displayHex(txidWire: outPointTxidWire))?.statusRaw do { try await PlatformAddressSyncCoordinator.shared.resumeFundFromCore( outPointTxid: outPointTxidWire, outPointVout: outPointVout, recipientAmountDuffs: recipientAmountDuffs) } catch { + AssetLockRetryLog.recordFailure( + error, + prefix: AssetLockRetryLog.shieldPrefix, + event: "resume core→platform", + txidWire: outPointTxidWire, + vout: outPointVout, + fundingTypeRaw: Self.addressAssetLockFundingType, + statusBeforeRaw: statusBeforeRaw, + store: failureStore) handleFailure(CoordinatorError.transferFailed(error)) return } diff --git a/DashWallet/Sources/UI/Tx/Details/TxDetailViewController.swift b/DashWallet/Sources/UI/Tx/Details/TxDetailViewController.swift index e0d9fc197a..c0fccdcf4e 100644 --- a/DashWallet/Sources/UI/Tx/Details/TxDetailViewController.swift +++ b/DashWallet/Sources/UI/Tx/Details/TxDetailViewController.swift @@ -299,6 +299,13 @@ extension TXDetailViewController { fundingTypeRaw: retry.fundingTypeRaw, txidWire: txidWire, vout: retry.vout) + AssetLockRetryLog.logOutcome( + "outcome=\(outcome)", + event: "single", + txidWire: txidWire, + vout: retry.vout, + fundingTypeRaw: retry.fundingTypeRaw, + statusBeforeRaw: retry.statusRaw) switch outcome { case .completed: toast = (NSLocalizedString("Transfer completed", comment: "Asset-lock retry finished"), .success) @@ -316,8 +323,25 @@ extension TXDetailViewController { } } catch DWIdentityAuthorizer.AuthError.cancelled { // Backing out of the PIN prompt is not an error state. + AssetLockRetryLog.logOutcome( + "outcome=cancelled", + event: "single", + txidWire: txidWire, + vout: retry.vout, + fundingTypeRaw: retry.fundingTypeRaw, + statusBeforeRaw: retry.statusRaw) } catch { failure = error + // The alert shows only the text; the log keeps the typed case. + // The failure store is written where the network call threw, + // not here, so a refusal cannot overwrite the stored reason. + AssetLockRetryLog.logFailure( + error, + event: "single", + txidWire: txidWire, + vout: retry.vout, + fundingTypeRaw: retry.fundingTypeRaw, + statusBeforeRaw: retry.statusRaw) } guard let self else { return } diff --git a/DashWalletTests/AssetLockDiagnosticsTests.swift b/DashWalletTests/AssetLockDiagnosticsTests.swift new file mode 100644 index 0000000000..af047e6d84 --- /dev/null +++ b/DashWalletTests/AssetLockDiagnosticsTests.swift @@ -0,0 +1,469 @@ +// +// AssetLockDiagnosticsTests.swift +// DashWalletTests +// +// What a diagnostic export says about tracked asset locks, and what the app +// remembers about a lock's last failed retry. Ticket 32104: a CoinJoin → +// Shielded lock with 121 inputs was refused by Platform on every retry +// (consensus 10534, too many inputs), and five log exports contained no line +// about it — the txid, the input count and the error reached support only +// when the user pasted the alert text. +// + +import Foundation +import SwiftData +import SwiftDashSDK +import XCTest +@testable import dashpay + +@MainActor +final class AssetLockDiagnosticsTests: XCTestCase { + + private var suiteName: String! + private var defaults: UserDefaults! + + override func setUp() { + super.setUp() + suiteName = "AssetLockDiagnosticsTests.\(UUID().uuidString)" + defaults = UserDefaults(suiteName: suiteName) + } + + override func tearDown() { + defaults.removePersistentDomain(forName: suiteName) + defaults = nil + suiteName = nil + super.tearDown() + } + + // MARK: fixtures + + /// Wire-order txid 0x01, 0x02, … 0x20 — display order is the reverse. + private let txidWire = Data((1...32).map { UInt8($0) }) + private var txidDisplay: String { + (1...32).reversed().map { String(format: "%02x", $0) }.joined() + } + + /// A consensus-encoded DIP-2 type-8 (asset lock) transaction with + /// `inputCount` inputs, one output and a two-byte payload. + private func assetLockTransaction(inputCount: UInt8) -> Data { + var bytes = Data() + let versionField: UInt32 = 3 | (8 << 16) + withUnsafeBytes(of: versionField.littleEndian) { bytes.append(contentsOf: $0) } + bytes.append(inputCount) // varint < 0xfd + for index in 0.. AssetLockDiagnosticRecord { + AssetLockDiagnosticRecord( + outPointHex: outPointHex ?? "\(txidDisplay):0", + fundingTypeRaw: fundingTypeRaw, + statusRaw: statusRaw, + amountDuffs: 250_000_000, + createdAt: Date(timeIntervalSince1970: 1_755_820_800), // 2025-08-22T00:00:00Z + updatedAt: Date(timeIntervalSince1970: 1_755_907_200), // 2025-08-23T00:00:00Z + transactionBytes: transactionBytes, + lastFailure: lastFailure) + } + + // MARK: summary section + + func testSectionSaysUnavailableWhenTheCaptureCouldNotRun() { + let lines = DiagnosticLogExporter.assetLockSection(nil) + XCTAssertEqual(lines.count, 2) + // "Unavailable" must never read as "this wallet has no stuck locks". + XCTAssertTrue(lines[1].contains("unavailable")) + XCTAssertFalse(lines[1].contains("none")) + } + + func testSectionSaysNoneWhenNothingIsTracked() { + XCTAssertEqual(DiagnosticLogExporter.assetLockSection([]).last, " none") + } + + func testRestoredLockPrintsExplorerTxidStatusNameInputsSizeAndLastFailure() { + let transaction = assetLockTransaction(inputCount: 121) + let failure = AssetLockFailureRecord( + errorCase: "assetLockTooManyInputs", + detail: "too many inputs: 121 (max 100)", + recordedAt: Date(timeIntervalSince1970: 1_761_782_400)) // 2025-10-30T00:00:00Z + let text = DiagnosticLogExporter + .assetLockSection([record(transactionBytes: transaction, lastFailure: failure)]) + .joined(separator: "\n") + + // Display order: what a block explorer shows and support searches for. + XCTAssertTrue(text.contains("\(txidDisplay):0")) + XCTAssertFalse(text.contains(txidWire.map { String(format: "%02x", $0) }.joined())) + XCTAssertTrue(text.contains("type=5 (assetLockShieldedAddressTopUp)")) + // RecoveredFromChain (a restore) is in the section, by number and name. + XCTAssertTrue(text.contains("status=5 (recoveredFromChain)")) + XCTAssertTrue(text.contains("amount=250000000 duffs")) + XCTAssertTrue(text.contains("created=2025-08-22T00:00:00Z")) + XCTAssertTrue(text.contains("updated=2025-08-23T00:00:00Z")) + XCTAssertTrue(text.contains("inputs=121 outputs=1 size=\(transaction.count) bytes")) + XCTAssertTrue(text.contains( + "last failure (2025-10-30T00:00:00Z): case=assetLockTooManyInputs detail=too many inputs: 121 (max 100)")) + } + + func testMissingTransactionBytesAreReportedAsUnknownNotZero() { + let text = DiagnosticLogExporter.assetLockSection([record()]).joined(separator: "\n") + XCTAssertTrue(text.contains("inputs=? size=? (transaction bytes not stored locally)")) + XCTAssertFalse(text.contains("inputs=0")) + XCTAssertTrue(text.contains("last failure: none recorded")) + } + + func testUnparseableTransactionBytesKeepTheirSizeButNoInputCount() { + let garbage = Data([0x03, 0x00]) + let text = DiagnosticLogExporter + .assetLockSection([record(transactionBytes: garbage)]) + .joined(separator: "\n") + XCTAssertTrue(text.contains("inputs=? size=2 bytes (stored transaction bytes did not parse)")) + } + + func testEveryLockGetsItsOwnBlock() { + let lines = DiagnosticLogExporter.assetLockSection([ + record(statusRaw: 2, fundingTypeRaw: 1), + record(statusRaw: 3, fundingTypeRaw: 4), + ]) + // Header + four lines per lock. + XCTAssertEqual(lines.count, 1 + 2 * 4) + XCTAssertTrue(lines[1].contains("type=1 (identityTopUp)")) + XCTAssertTrue(lines[1].contains("status=2 (instantSendLocked)")) + XCTAssertTrue(lines[5].contains("type=4 (assetLockAddressTopUp)")) + XCTAssertTrue(lines[5].contains("status=3 (chainLocked)")) + } + + func testUnknownDiscriminantsStayNumericAndAreNotGuessed() { + XCTAssertEqual(DiagnosticLogExporter.assetLockStatusName(99), "unknown") + XCTAssertEqual(DiagnosticLogExporter.assetLockStatusName(-1), "unknown") + XCTAssertEqual(DiagnosticLogExporter.fundingTypeName(42), "unknown") + XCTAssertEqual(DiagnosticLogExporter.assetLockStatusName(6), "drainCompleted") + } + + func testMalformedStoredOutPointIsPrintedAsStoredNeverWithAMadeUpVout() { + for malformed in [txidDisplay, "\(txidDisplay):x", ":3", "\(txidDisplay):1:2"] { + let line = DiagnosticLogExporter.assetLockSection([record(outPointHex: malformed)])[1] + XCTAssertTrue( + line.hasPrefix(" \(malformed) (stored outpoint did not parse) "), + "unexpected line for \(malformed): \(line)") + } + let wellFormed = DiagnosticLogExporter.assetLockSection([record(outPointHex: "\(txidDisplay):4")])[1] + XCTAssertTrue(wellFormed.hasPrefix(" \(txidDisplay):4 type=")) + } + + // MARK: capture from the SDK store + + /// In-memory, without CloudKit: the dashpay host's iCloud entitlement + /// otherwise turns the default configuration into a CloudKit store that + /// refuses the schema (see `PlatformBalanceReaderTests`). + private func makeContainer() throws -> ModelContainer { + let configuration = ModelConfiguration( + schema: DashModelContainer.schema, + isStoredInMemoryOnly: true, + cloudKitDatabase: .none) + return try ModelContainer(for: DashModelContainer.schema, configurations: [configuration]) + } + + func testCaptureReturnsTheRestoredLockWithItsStoredFailure() throws { + let container = try makeContainer() + let context = container.mainContext + let walletId = Data(repeating: 0xA1, count: 32) + let otherWalletId = Data(repeating: 0xB2, count: 32) + let restoredOutPoint = "\(txidDisplay):0" + func lock(_ outPointHex: String, wallet: Data, statusRaw: Int) -> PersistentAssetLock { + PersistentAssetLock( + outPointHex: outPointHex, + walletId: wallet, + transactionBytes: Data(), + fundingTypeRaw: 5, + identityIndexRaw: -1, + amountDuffs: 250_000_000, + statusRaw: statusRaw) + } + context.insert(lock(restoredOutPoint, wallet: walletId, statusRaw: 5)) + context.insert(lock("\(String(repeating: "ab", count: 32)):1", wallet: walletId, statusRaw: 4)) + context.insert(lock("\(String(repeating: "cd", count: 32)):0", wallet: otherWalletId, statusRaw: 1)) + try context.save() + + let store = AssetLockFailureStore(defaults: defaults) + let failure = store.record( + txidWire: txidWire, + vout: 0, + error: PlatformWalletError.assetLockTooManyInputs("too many inputs: 121 (max 100)")) + + let captured = try XCTUnwrap(DiagnosticLogExporter.captureAssetLocks( + walletId: walletId, context: context, failureStore: store)) + + // The consumed row and the other wallet's row are left out. + XCTAssertEqual(captured.map(\.outPointHex), [restoredOutPoint]) + XCTAssertEqual(captured.first?.statusRaw, 5) + XCTAssertEqual(captured.first?.lastFailure, failure) + } + + func testConsumedIsTheStatusTheSectionLeavesOut() { + XCTAssertEqual(DiagnosticLogExporter.consumedAssetLockStatus, 4) + } + + // MARK: describing a failure + + func testPlatformErrorIsNamedByItsTypedCase() { + let record = AssetLockFailureRecord.describe( + PlatformWalletError.assetLockTooManyInputs("too many inputs: 121 (max 100)")) + XCTAssertEqual(record.errorCase, "assetLockTooManyInputs") + XCTAssertEqual(record.detail, "too many inputs: 121 (max 100)") + } + + func testConsensusRejectionCarriesItsCodeIntoTheDetail() { + let error = PlatformWalletError.consensusRejection( + PlatformConsensusError(code: 10534, kind: .basic), + "asset lock transaction has too many inputs") + let record = AssetLockFailureRecord.describe(error) + XCTAssertEqual(record.errorCase, "consensusRejection") + // "10534" is what support greps for. + XCTAssertTrue(record.detail.contains("code=10534"), record.detail) + XCTAssertTrue(record.detail.contains("asset lock transaction has too many inputs")) + } + + func testCoordinatorEnvelopeIsUnwrappedToThePlatformError() { + let error = ShieldedTransferCoordinator.CoordinatorError.transferFailed( + PlatformWalletError.assetLockTooManyInputs("too many inputs: 121 (max 100)")) + XCTAssertEqual(AssetLockFailureRecord.describe(error).errorCase, "assetLockTooManyInputs") + } + + func testRecoveryServiceFailureIsUnwrappedThroughBothEnvelopes() { + // What the tx-detail and bulk retries actually catch for a type-5 lock: + // the service's text-only failure, carrying the coordinator's typed one. + let error = AssetLockRecoveryService.RecoveryError.failed( + "Couldn't complete the transfer", + underlying: ShieldedTransferCoordinator.CoordinatorError.transferFailed( + PlatformWalletError.assetLockTooManyInputs("too many inputs: 121 (max 100)"))) + let record = AssetLockFailureRecord.describe(error) + XCTAssertEqual(record.errorCase, "assetLockTooManyInputs") + XCTAssertEqual(record.detail, "too many inputs: 121 (max 100)") + } + + func testAppErrorIsNamedByTypeAndCase() { + let record = AssetLockFailureRecord.describe(AssetLockRecoveryService.RecoveryError.notReady) + XCTAssertEqual(record.errorCase, "RecoveryError.notReady") + XCTAssertEqual(record.detail, "Wallet is not ready") + + let bare = AssetLockFailureRecord.describe( + AssetLockRecoveryService.RecoveryError.failed("Network unreachable")) + XCTAssertEqual(bare.errorCase, "RecoveryError.failed") + XCTAssertEqual(bare.detail, "Network unreachable") + } + + /// A Swift struct error: its first mirror child is the stored property + /// `code`, which is not a case name. + private struct SampleStructError: LocalizedError { + let code: Int + var errorDescription: String? { "sample failure \(code)" } + } + + func testNonEnumErrorsAreNamedByTheirTypeAlone() { + let structError = AssetLockFailureRecord.describe(SampleStructError(code: 7)) + XCTAssertEqual(structError.errorCase, "SampleStructError") + XCTAssertEqual(structError.detail, "sample failure 7") + + // An NSError's description is its whole domain/userInfo dump; it + // belongs in the detail, never in the searchable case. + let nsError = NSError( + domain: NSURLErrorDomain, + code: NSURLErrorNotConnectedToInternet, + userInfo: [NSLocalizedDescriptionKey: "The Internet connection appears to be offline."]) + let record = AssetLockFailureRecord.describe(nsError) + XCTAssertEqual(record.errorCase, "NSError") + XCTAssertEqual(record.detail, "The Internet connection appears to be offline.") + } + + // MARK: failure store + + func testOutPointKeyMatchesThePersistentAssetLockForm() { + // `PersistentAssetLock.outPointHex` is `:`. + XCTAssertEqual(AssetLockFailureStore.outPointKey(txidWire: txidWire, vout: 3), "\(txidDisplay):3") + } + + func testRecordedFailureSurvivesANewStoreInstance() { + let date = Date(timeIntervalSince1970: 1_761_782_400) + AssetLockFailureStore(defaults: defaults).record( + txidWire: txidWire, vout: 0, + error: PlatformWalletError.assetLockTooManyInputs("too many inputs: 121 (max 100)"), + at: date) + + // The summary reads it on a later launch, without re-running a retry. + let reloaded = AssetLockFailureStore(defaults: defaults) + let stored = reloaded.failure(txidWire: txidWire, vout: 0) + XCTAssertEqual(stored?.errorCase, "assetLockTooManyInputs") + XCTAssertEqual(stored?.recordedAt, date) + XCTAssertEqual(reloaded.allFailures().keys.sorted(), ["\(txidDisplay):0"]) + XCTAssertNil(reloaded.failure(txidWire: txidWire, vout: 1)) + } + + func testLaterFailureReplacesTheEarlierOneForTheSameLock() { + let store = AssetLockFailureStore(defaults: defaults) + store.record(txidWire: txidWire, vout: 0, error: AssetLockRecoveryService.RecoveryError.notReady, + at: Date(timeIntervalSince1970: 1)) + store.record(txidWire: txidWire, vout: 0, + error: PlatformWalletError.assetLockTooManyInputs("too many inputs"), + at: Date(timeIntervalSince1970: 2)) + XCTAssertEqual(store.allFailures().count, 1) + XCTAssertEqual(store.failure(txidWire: txidWire, vout: 0)?.errorCase, "assetLockTooManyInputs") + } + + func testStoreKeepsOnlyTheNewestEntriesPastItsLimit() { + let store = AssetLockFailureStore(defaults: defaults, limit: 3) + for index in 0..<5 { + store.record( + AssetLockFailureRecord(errorCase: "unknown", detail: "\(index)", + recordedAt: Date(timeIntervalSince1970: TimeInterval(index))), + forOutPointKey: "lock\(index):0") + } + XCTAssertEqual(store.allFailures().keys.sorted(), ["lock2:0", "lock3:0", "lock4:0"]) + // The cap holds on disk too, not only in the cache. + XCTAssertEqual(AssetLockFailureStore(defaults: defaults, limit: 3).allFailures().count, 3) + } + + func testDefaultLimitCoversARestoredWalletsWorkingSet() { + XCTAssertEqual(AssetLockFailureStore.defaultLimit, 50) + } + + func testBoundedLeavesASmallMapUntouched() { + let one = ["a:0": AssetLockFailureRecord(errorCase: "x", detail: "y", recordedAt: Date())] + XCTAssertEqual(AssetLockFailureStore.bounded(one, limit: 50), one) + } + + func testWipeForgetsEveryFailure() { + let store = AssetLockFailureStore(defaults: defaults) + store.record(txidWire: txidWire, vout: 0, error: AssetLockRecoveryService.RecoveryError.notReady) + store.resetForWipe() + XCTAssertTrue(store.allFailures().isEmpty) + XCTAssertTrue(AssetLockFailureStore(defaults: defaults).allFailures().isEmpty) + } + + // MARK: export content rule + + func testTrackedLocksAloneMakeAnExportWorthWriting() { + // The support email attaches app logs loose, so with no SDK session + // on disk the summary is the only thing its zip can carry. + XCTAssertTrue(DiagnosticLogExporter.hasContentToExport( + sessionCount: 0, appLogCount: 0, assetLocks: [record()])) + XCTAssertTrue(DiagnosticLogExporter.hasContentToExport( + sessionCount: 1, appLogCount: 0, assetLocks: nil)) + XCTAssertTrue(DiagnosticLogExporter.hasContentToExport( + sessionCount: 0, appLogCount: 1, assetLocks: [])) + } + + func testNoLogsAndNoLocksIsStillNothingToExport() { + XCTAssertFalse(DiagnosticLogExporter.hasContentToExport( + sessionCount: 0, appLogCount: 0, assetLocks: [])) + XCTAssertFalse(DiagnosticLogExporter.hasContentToExport( + sessionCount: 0, appLogCount: 0, assetLocks: nil)) + } + + // MARK: coordinator resume + + func testRefusalBeforeTheResumeCallKeepsTheStoredPlatformFailure() async { + // A random outpoint has no SDK row, so whatever the test host's wallet + // state, the resume stops before the PIN prompt: no manager/wallet, or + // no drain-row identity for the lock. + let store = AssetLockFailureStore(defaults: defaults) + let coordinator = ShieldedTransferCoordinator(failureStore: store) + let txid = Data((0..<32).map { _ in UInt8.random(in: 0...255) }) + let platformFailure = store.record( + txidWire: txid, + vout: 7, + error: PlatformWalletError.assetLockTooManyInputs("too many inputs: 121 (max 100)"), + at: Date(timeIntervalSince1970: 1_755_820_800)) + + await coordinator.resumeAssetLock(outPointTxidWire: txid, outPointVout: 7) + + guard case .failed = coordinator.phase, coordinator.lastFailure != nil else { + return XCTFail("expected a refused resume, got \(coordinator.phase)") + } + // The refusal says nothing about the lock, so the reason it is stuck + // stays what Platform said. + XCTAssertEqual(store.failure(txidWire: txid, vout: 7), platformFailure) + } + + func testRefusalBeforeTheResumeCallStoresNothingForAnUntriedLock() async { + let store = AssetLockFailureStore(defaults: defaults) + let coordinator = ShieldedTransferCoordinator(failureStore: store) + let txid = Data((0..<32).map { _ in UInt8.random(in: 0...255) }) + + await coordinator.resumeAssetLock(outPointTxidWire: txid, outPointVout: 2) + + guard case .failed = coordinator.phase else { + return XCTFail("expected a refused resume, got \(coordinator.phase)") + } + XCTAssertNil(store.failure(txidWire: txid, vout: 2)) + XCTAssertTrue(store.allFailures().isEmpty) + } + + func testRecordFailureStoresTheErrorForTheOutPoint() { + let store = AssetLockFailureStore(defaults: defaults) + let recorded = AssetLockRetryLog.recordFailure( + PlatformWalletError.assetLockTooManyInputs("too many inputs: 121 (max 100)"), + event: "resume", + txidWire: txidWire, + vout: 0, + fundingTypeRaw: 5, + statusBeforeRaw: 5, + store: store) + XCTAssertEqual(store.failure(txidWire: txidWire, vout: 0), recorded) + XCTAssertEqual(recorded.errorCase, "assetLockTooManyInputs") + } + + // MARK: retry log line + + func testRetryLogLineCarriesTxidTypeStatusAndResult() { + let line = AssetLockRetryLog.line( + prefix: AssetLockRetryLog.lockRetryPrefix, + event: "single", + txidWire: txidWire, + vout: 0, + fundingTypeRaw: 5, + statusBeforeRaw: 5, + result: "FAILED case=assetLockTooManyInputs detail=too many inputs: 121 (max 100)") + XCTAssertEqual( + line, + "🔁 LOCK-RETRY :: single txid=\(txidDisplay):0 " + + "type=5 (assetLockShieldedAddressTopUp) statusBefore=5 (recoveredFromChain) " + + "FAILED case=assetLockTooManyInputs detail=too many inputs: 121 (max 100)") + } + + func testBulkPassLineCarriesTheCountAndOutcome() { + XCTAssertEqual( + AssetLockRetryLog.bulkLine(count: 3, result: "outcome=cancelled before the first lock"), + "🔁 LOCK-RETRY :: bulk count=3 outcome=cancelled before the first lock") + } + + func testRetryLogLineSaysUnknownWhenTheStatusBeforeWasNotRead() { + let line = AssetLockRetryLog.line( + prefix: AssetLockRetryLog.shieldPrefix, + event: "resume", + txidWire: txidWire, + vout: 1, + fundingTypeRaw: 5, + statusBeforeRaw: nil, + result: "outcome=completed") + XCTAssertTrue(line.hasPrefix("🛡️ SHIELD-TX :: resume txid=\(txidDisplay):1 ")) + XCTAssertTrue(line.contains("statusBefore=unknown outcome=completed")) + } +}