diff --git a/.github/workflows/core-drain-tests.yml b/.github/workflows/core-drain-tests.yml index c7f8b1f658..ec5793ef90 100644 --- a/.github/workflows/core-drain-tests.yml +++ b/.github/workflows/core-drain-tests.yml @@ -3,12 +3,19 @@ name: Core Shielded Max recovery on: pull_request: paths: - - 'DashWallet/Sources/UI/Payments/InternalTransfer/**' - - 'DashWallet/Sources/Infrastructure/SwiftDashSDK/DurableFileStorage.swift' - - 'DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKWalletWiper.swift' + - 'DashWallet/Sources/UI/Payments/**' + - 'DashWallet/Sources/UI/Home/Views/CoinJoinMoveFunds/CoinJoinMoveFundsViewModel.swift' + - 'DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift' + - 'DashWallet/Sources/Infrastructure/SwiftDashSDK/**' - 'DashWalletTests/CoreShieldedDrainStoreTests.swift' - 'scripts/test_core_drain.py' - 'scripts/core_drain_recovery_harness.py' + - 'scripts/test_platform_preparation.py' + - 'scripts/test_asset_lock_recovery.py' + - 'scripts/test_identity_top_up_compatibility.py' + - 'scripts/test_internal_transfer_confirmation.py' + - 'scripts/test_core_to_shielded_fee_cache.py' + - 'scripts/fixtures/**' - '.github/workflows/core-drain-tests.yml' workflow_dispatch: @@ -24,3 +31,10 @@ jobs: persist-credentials: false - name: Test durable markers and form recovery run: python3 scripts/test_core_drain.py + - name: Test preparation and transfer recovery + run: | + python3 scripts/test_platform_preparation.py + python3 scripts/test_asset_lock_recovery.py + python3 scripts/test_identity_top_up_compatibility.py + python3 scripts/test_internal_transfer_confirmation.py + python3 scripts/test_core_to_shielded_fee_cache.py diff --git a/.platform-ref b/.platform-ref index e83c9fe002..73d0ebaae0 100644 --- a/.platform-ref +++ b/.platform-ref @@ -1 +1 @@ -5b89fe8b529c66d5e972880196545c902285258b +48490f211b2004e27e656019a41b14fbb4c56815 diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockProbeStore.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockProbeStore.swift index f2b941ff49..211e3455cf 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockProbeStore.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockProbeStore.swift @@ -19,55 +19,38 @@ import Foundation -/// Funding asset locks we have already asked Platform about and been told are -/// already spent. -/// -/// The SDK deliberately does NOT advance such a lock's status: the -/// already-consumed report arrives as a plain rejection from one DAPI node, not -/// as a quorum-authenticated proof, and stamping `Consumed` on an unverified -/// negative would permanently hide a lock that may still be recoverable -/// (`rs-platform-wallet` records it as "consumption unknown" instead). -/// -/// That is the right call for the *status*, but it leaves the answer itself -/// nowhere: the coordinator's phase dies with the sheet, so the next launch -/// looks exactly like the first — "Completion unknown" and a live retry action -/// on every restored transfer. A wallet restored with a hundred shielded -/// transfers then shows a hundred permanently unfinished-looking rows. -/// -/// This store records the weaker, honest fact — *we asked, and the network said -/// spent* — without claiming the transfer is proven complete. It is app-owned -/// and advisory: losing it costs one redundant probe, never money. -/// -/// Superseded by a proved read of Platform's `SpentAssetLockTransactions` tree, -/// which would settle consumption authoritatively and let the status advance on -/// its own. Until that query exists client-side, this is the honest middle. +/// Wallet-scoped, unverified consumption reports for exact asset-lock outpoints. +/// Automatic recovery skips these reports; an explicit authenticated user action +/// can recheck the same lock. A report never proves success or authorizes a new lock. final class AssetLockProbeStore { static let shared = AssetLockProbeStore() - private let defaults = UserDefaults.standard + private let defaults: UserDefaults private let lock = NSLock() - /// Scoped per wallet (`_`) exactly as + /// V1 reports have no output index and cannot safely be migrated to a + /// specific outpoint. Leave them unused until wallet cleanup; never turn + /// them into a report about every output in their transaction. + /// Scoped per wallet (`_`) exactly as /// `CoinJoinWithdrawalStore` is: an outpoint probed while wallet A was /// active says nothing about wallet B. The bare key is the no-active-wallet /// fallback. private let legacyKey = "assetLockProbe.v1.alreadySpentTxids" + private let storageKey = "assetLockProbe.v2.alreadySpentOutpoints" private var cacheKey: String? private var cache: Set? - private init() {} - - private func resolvedKey() -> String { - key(forWalletIdHex: WalletEnvironment.activeWalletIdHex as String?) + init(defaults: UserDefaults = .standard) { + self.defaults = defaults } /// The storage key for an EXPLICIT wallet. Callers that suspend before /// writing must resolve their wallet up front and pass it here: the active - /// wallet can change mid-flight, and `resolvedKey()` would then file the + /// wallet can change mid-flight, and using the active wallet would then file the /// result under whichever wallet happens to be active at write time. private func key(forWalletIdHex walletIdHex: String?) -> String { - guard let walletIdHex, !walletIdHex.isEmpty else { return legacyKey } - return "\(legacyKey)_\(walletIdHex)" + guard let walletIdHex, !walletIdHex.isEmpty else { return storageKey } + return "\(storageKey)_\(walletIdHex)" } /// Hex id of the wallet a probe should be filed under, captured BEFORE the @@ -85,30 +68,40 @@ final class AssetLockProbeStore { return set } - private func loaded() -> Set { loaded(key: resolvedKey()) } + private func outpointKey(_ txid: Data, vout: UInt32) -> Data { + var index = vout.littleEndian + return txid + withUnsafeBytes(of: &index) { Data($0) } + } - /// Record that `txid` (WIRE order) was probed and reported already spent. + /// Record that `(txid, vout)` (WIRE order) was reported already spent. /// Idempotent and thread-safe. /// `walletIdHex` is the wallet the probe belongs to, captured before the /// network round-trip that produced it — passing it explicitly is what /// keeps a wallet switch during that round-trip from filing the result /// under the wrong wallet. - func record(txid: Data, walletIdHex: String?) { + func record(txid: Data, vout: UInt32, walletIdHex: String?) { + let outpoint = outpointKey(txid, vout: vout) let key = key(forWalletIdHex: walletIdHex) lock.lock(); defer { lock.unlock() } var set = loaded(key: key) - guard !set.contains(txid) else { return } - set.insert(txid) + guard !set.contains(outpoint) else { return } + set.insert(outpoint) cacheKey = key cache = set defaults.set(Array(set), forKey: key) } - /// Whether `txid` (WIRE order, e.g. `Transaction.txHashData`) has already - /// been probed and answered "already spent". Thread-safe; cheap. - func contains(_ txid: Data) -> Bool { + /// Whether this exact outpoint (WIRE-order txid) was reported already spent. + /// Thread-safe; cheap. This report is not proof of consumption. + func contains(_ txid: Data, vout: UInt32) -> Bool { + contains(txid, vout: vout, walletIdHex: Self.currentWalletIdHex()) + } + + /// Explicit-wallet lookup for work that has already captured its runtime. + func contains(_ txid: Data, vout: UInt32, walletIdHex: String?) -> Bool { + let key = key(forWalletIdHex: walletIdHex) lock.lock(); defer { lock.unlock() } - return loaded().contains(txid) + return loaded(key: key).contains(outpointKey(txid, vout: vout)) } /// Clear a SINGLE wallet's probes (per-wallet Remove flow — the removed @@ -117,8 +110,9 @@ final class AssetLockProbeStore { func clearForWallet(walletIdHex: String) { guard !walletIdHex.isEmpty else { return } lock.lock(); defer { lock.unlock() } - let key = "\(legacyKey)_\(walletIdHex)" + let key = "\(storageKey)_\(walletIdHex)" defaults.removeObject(forKey: key) + defaults.removeObject(forKey: "\(legacyKey)_\(walletIdHex)") if cacheKey == key { cacheKey = nil cache = nil @@ -131,7 +125,8 @@ final class AssetLockProbeStore { func resetForWipe() { lock.lock(); defer { lock.unlock() } for key in defaults.dictionaryRepresentation().keys - where key == legacyKey || key.hasPrefix("\(legacyKey)_") { + where key == legacyKey || key.hasPrefix("\(legacyKey)_") + || key == storageKey || key.hasPrefix("\(storageKey)_") { defaults.removeObject(forKey: key) } cacheKey = nil diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockRecoveryService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockRecoveryService.swift index 5f7d9faf29..74663ebf99 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockRecoveryService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockRecoveryService.swift @@ -132,11 +132,8 @@ struct AssetLockRecoveryService { func retry(fundingTypeRaw: Int, txidWire: Data, vout: UInt32, - refreshLookup: Bool = true) async throws -> Outcome { - // Resolved before the resume suspends: a wallet switch during the - // round-trip must not file this probe under whatever wallet is active - // when the answer arrives. - let originatingWalletIdHex = AssetLockProbeStore.currentWalletIdHex() + refreshLookup: Bool = true, + retryUnverifiedConsumption: Bool = true) async throws -> Outcome { Self.logger.info("🔁 LOCK-RETRY :: type=\(fundingTypeRaw, privacy: .public) vout=\(vout, privacy: .public)") let outcome: Outcome switch fundingTypeRaw { @@ -158,7 +155,8 @@ struct AssetLockRecoveryService { outPointVout: vout, recipientAmountDuffs: recipientAmountDuffs) } else { - await coordinator.resumeAssetLock(outPointTxidWire: txidWire, outPointVout: vout) + await coordinator.resumeAssetLock(outPointTxidWire: txidWire, outPointVout: vout, + retryUnverifiedConsumption: retryUnverifiedConsumption) } try Self.checkTerminalPhase(coordinator) // Branch on the coordinator's typed report, NOT on @@ -177,13 +175,9 @@ struct AssetLockRecoveryService { // settles it. Reporting `.completed` would be worse still. outcome = .submittedAwaitingSync } else if coordinator.lastResumeReport == .alreadyConsumed { - // Platform reported this outpoint already spent. The SDK keeps - // the lock at `RecoveredFromChain` (the report is not - // quorum-authenticated), so record the probe here — otherwise - // the answer dies with this call and every later launch offers - // the same futile retry. Recorded at the service layer so the - // single-row and bulk callers share it. - AssetLockProbeStore.shared.record(txid: txidWire, walletIdHex: originatingWalletIdHex) + // The coordinator records the advisory probe for its captured + // wallet, including calls made directly by the recovery sheet. + // Rust retains the nonterminal lock and its recovery proof. outcome = .completionUnconfirmed } else { outcome = .completed @@ -290,8 +284,8 @@ struct AssetLockRecoveryService { /// Every tracked funding lock still worth retrying: a status that is not a /// finished transfer, a route this service handles, and no recorded - /// already-spent probe. This is the same predicate the per-transaction - /// action uses, applied to the whole snapshot. + /// already-spent probe. Explicit per-transaction recovery can recheck a + /// previously reported outpoint; bulk recovery skips it to avoid loops. /// /// Restoring a wallet turns every shielded funding lock into /// `RecoveredFromChain` at once, so this is routinely dozens of entries — @@ -307,7 +301,7 @@ struct AssetLockRecoveryService { entry.info.fundingTypeRaw == bulkFundingTypeRaw, bulkStatusAllowsRecovery(entry.info.statusRaw), let txidWire = txidWire(fromDisplayHex: entry.txidHex), - !AssetLockProbeStore.shared.contains(txidWire) + !AssetLockProbeStore.shared.contains(txidWire, vout: entry.info.vout) else { return nil } return PendingRecovery( txidWire: txidWire, @@ -376,7 +370,7 @@ struct AssetLockRecoveryService { // One refresh for the pass, in `recoverAll`. Per item it is // a full lookup rebuild on top of the one `resumeAssetLock` // already does, and nothing between iterations reads it. - refreshLookup: false) + refreshLookup: false, retryUnverifiedConsumption: false) let step: BulkStep switch result { case .completed: step = .completed diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationBridge.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationBridge.swift index d985dd6236..74ff097332 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationBridge.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationBridge.swift @@ -259,6 +259,14 @@ public final class DWIdentityRegistrationBridge: NSObject { public func startCreateUsername( _ username: String, completion: @escaping (String?, NSError?) -> Void + ) { + startCreateUsername(username, preparation: nil, completion: completion) + } + + func startCreateUsername( + _ username: String, + preparation: SwiftDashSDKHost.PlatformPreparation?, + completion: @escaping (String?, NSError?) -> Void ) { let source = preferredFundingSource let temporaryUsername = sanitizedTemporaryUsername(for: username) @@ -272,7 +280,7 @@ public final class DWIdentityRegistrationBridge: NSObject { fundingSource: source, temporaryUsername: temporaryUsername, verificationURL: verificationURL, - authorizedTopUpDuffs: authorizedTopUpDuffs) + authorizedTopUpDuffs: authorizedTopUpDuffs, preparation: preparation) let hex = identityId.map { String(format: "%02x", $0) }.joined() completion(hex, nil) } catch { diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift index 6863d74972..1bb4de801b 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift @@ -538,6 +538,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { case shieldedPoolTooSmall(currentNotes: UInt64) case noShieldedFallbackAddress case shieldedCreateUnconfirmed + case platformWriteUnconfirmed case missingInvitation case alreadyInFlight case invalidTemporaryUsername @@ -620,6 +621,10 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { return NSLocalizedString("No Platform address is available yet for the shielded registration fallback. Try again after the wallet finishes syncing.", comment: "DashPay") case .shieldedCreateUnconfirmed: return NSLocalizedString("The registration was submitted but its result couldn't be confirmed. Wait a minute for the wallet to sync, then try again — don't resubmit immediately.", comment: "DashPay") + case .platformWriteUnconfirmed: + return NSLocalizedString( + "The operation may have been submitted, but its result could not be confirmed. Wait for the wallet to sync and check your identity and balances before continuing. Do not fund another identity or repeat the payment.", + comment: "DashPay registration or purchase result unknown") case .missingInvitation: return NSLocalizedString("This invitation link is not valid.", comment: "DashPay Invitations") case .alreadyInFlight: @@ -713,7 +718,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { verificationURL: URL? = nil, /// The most an existing identity's top-up may move without a new /// confirmation: what the confirmation sheet showed. nil = none shown. - authorizedTopUpDuffs: UInt64? = nil + authorizedTopUpDuffs: UInt64? = nil, + preparation: SwiftDashSDKHost.PlatformPreparation? = nil ) async throws -> Identifier { Self.logger.info("🪪 IDENT-COORD :: startCreateUsername username=\(username) funding=\(fundingSource.logLabel) temporary=\(temporaryUsername ?? "none")") // An overlapping start is rejected before it touches the attempt's @@ -757,6 +763,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { } let identitySnapshot = DWCurrentUserIdentityInfo.shared.refreshedSnapshot() guard !identitySnapshot.isLoading else { throw CoordinatorError.noWallet } + let preparation = try preparation ?? SwiftDashSDKHost.shared.preparePlatformOperation() + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) return try await UsernameRegistrationRecoveryFlow.route( identityId: identitySnapshot.identityId, resume: { identityId in @@ -765,21 +773,22 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { try await self.resumeUsernameRegistration( identityId: identityId, username: username, temporaryUsername: temporaryUsername, topUpSource: fundingSource == .invitation ? nil : fundingSource, - authorizedTopUpDuffs: authorizedTopUpDuffs) + authorizedTopUpDuffs: authorizedTopUpDuffs, preparation: preparation) }, create: { try await self.createIdentityAndUsername( username, fundingSource: fundingSource, invitationURI: invitationURI, temporaryUsername: temporaryUsername, wallet: wallet, network: network, modelContainer: modelContainer, - authorizedTopUpDuffs: authorizedTopUpDuffs) + authorizedTopUpDuffs: authorizedTopUpDuffs, preparation: preparation) }) } private func createIdentityAndUsername( _ username: String, fundingSource: DWIdentityFundingSource, invitationURI: String?, temporaryUsername: String?, wallet: ManagedPlatformWallet, - network: Network, modelContainer: ModelContainer, authorizedTopUpDuffs: UInt64? = nil + network: Network, modelContainer: ModelContainer, authorizedTopUpDuffs: UInt64? = nil, + preparation: SwiftDashSDKHost.PlatformPreparation ) async throws -> Identifier { let recoveryLock = lookupRegistrationRecoveryLock( walletId: wallet.walletId, @@ -865,6 +874,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { do { try validateRegistrationContext(walletId: wallet.walletId, network: network) + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) } catch { newController.enterFailed(error.localizedDescription) throw error @@ -924,7 +934,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { IdentityCreationContext(wallet: wallet, network: network, modelContainer: modelContainer, signer: signer, pubkeys: pubkeys, fundingSource: fundingSource, username: username, invitationURI: invitationURI, - requiredIdentityFundingDuffs: requiredIdentityFundingDuffs), + requiredIdentityFundingDuffs: requiredIdentityFundingDuffs, + preparation: preparation), recoveryLock: recoveryLock) Self.logger.info("🪪 IDENT-COORD :: identity created, id=\(identityId.map { String(format: "%02x", $0) }.joined().prefix(8))…") } catch { @@ -954,7 +965,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { return try await finishUsernameRegistration( identityId: identityId, username: username, temporaryUsername: temporaryUsername, wallet: wallet, network: network, signer: signer, newController: newController, - contestFundCredits: contestFundCredits, topUp: topUp) + preparation: preparation, contestFundCredits: contestFundCredits, topUp: topUp) } /// Inputs captured before authorization; helpers never resolve a new wallet. @@ -968,10 +979,12 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { let username: String let invitationURI: String? let requiredIdentityFundingDuffs: UInt64 + let preparation: SwiftDashSDKHost.PlatformPreparation } /// Submit only the selected funding route when no paid lock or identity exists. private func createFundedIdentity(_ context: IdentityCreationContext) async throws -> Identifier { + try SwiftDashSDKHost.shared.validatePlatformOperation(context.preparation) let wallet = context.wallet let modelContainer = context.modelContainer let signer = context.signer @@ -982,12 +995,14 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { let identityId: Identifier switch context.fundingSource { case .core: - let result = try await wallet.registerIdentityWithFunding( - amountDuffs: requiredIdentityFundingDuffs, - accountIndex: Self.defaultAccountIndex, - identityIndex: Self.pinnedIdentityIndex, - identityPubkeys: pubkeys, - signer: signer) + let result = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: context.preparation) { + try await wallet.registerIdentityWithFunding( + amountDuffs: requiredIdentityFundingDuffs, + accountIndex: Self.defaultAccountIndex, + identityIndex: Self.pinnedIdentityIndex, + identityPubkeys: pubkeys, + signer: signer) + } identityId = result.0 case .platformPayment: @@ -1000,13 +1015,15 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { targetCredits: targetCredits) Self.logger.info("🪪 IDENT-COORD :: PP inputs=\(inputs.count) targetCredits=\(targetCredits)") do { - let created = try await wallet.registerIdentityFromAddresses( - inputs: inputs, - output: nil, - identityIndex: Self.pinnedIdentityIndex, - identityPubkeys: pubkeys, - identitySigner: signer, - addressSigner: signer) + let created = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: context.preparation) { + try await wallet.registerIdentityFromAddresses( + inputs: inputs, + output: nil, + identityIndex: Self.pinnedIdentityIndex, + identityPubkeys: pubkeys, + identitySigner: signer, + addressSigner: signer) + } identityId = created.identityId } catch { guard Self.isPlatformAddressInsufficientFunds(error) else { @@ -1026,7 +1043,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { walletId: wallet.walletId, modelContainer: modelContainer, pubkeys: pubkeys, - signer: signer) + signer: signer, + preparation: context.preparation) case .invitation: // DIP-13 claim: register the invitee's identity funded @@ -1036,12 +1054,14 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { guard let invitationURI else { throw CoordinatorError.missingInvitation } - let managed = try await wallet.claimInvitation( - uri: invitationURI, - identityIndex: Self.pinnedIdentityIndex, - identityPubkeys: pubkeys, - signer: signer, - nowUnix: UInt32(Date().timeIntervalSince1970)) + let managed = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: context.preparation) { + try await wallet.claimInvitation( + uri: invitationURI, + identityIndex: Self.pinnedIdentityIndex, + identityPubkeys: pubkeys, + signer: signer, + nowUnix: UInt32(Date().timeIntervalSince1970)) + } identityId = try managed.getId() // The voucher is spent now, whatever happens to the username // next: from here on this is an ordinary "identity exists, @@ -1104,12 +1124,15 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { ]) } Self.logger.info("🪪 IDENT-COORD :: recovery — resuming original asset lock vout=\(outPoint.vout)") - let result = try await wallet.resumeIdentityWithAssetLock( - outPointTxid: outPoint.txidWire, - outPointVout: outPoint.vout, - identityIndex: Self.pinnedIdentityIndex, - identityPubkeys: pubkeys, - signer: signer) + try SwiftDashSDKHost.shared.validatePlatformOperation(context.preparation) + let result = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: context.preparation) { + try await wallet.resumeIdentityWithAssetLock( + outPointTxid: outPoint.txidWire, + outPointVout: outPoint.vout, + identityIndex: Self.pinnedIdentityIndex, + identityPubkeys: pubkeys, + signer: signer) + } identityId = result.0 } } else { @@ -1119,13 +1142,24 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { } /// Preserve payment/creation failure phases independently of funding dispatch. + private func preservingUnconfirmedOutcome(_ error: Error) -> Error { + switch error { + case PlatformWalletError.transactionBroadcastUnconfirmed: + return CoordinatorError.platformWriteUnconfirmed + default: + return error + } + } + private func reportIdentityCreationFailure( _ error: Error, controller: DWIdentityRegistrationController ) -> Error { + let error = preservingUnconfirmedOutcome(error) if let coordError = error as? CoordinatorError { - if case .shieldedCreateUnconfirmed = coordError { + switch coordError { + case .shieldedCreateUnconfirmed, .platformWriteUnconfirmed: failedAtPhase = .creatingID - } else { + default: failedAtPhase = .processingPayment } lastErrorMessage = coordError.localizedDescription @@ -1153,7 +1187,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { username: String, temporaryUsername: String? = nil, topUpSource: DWIdentityFundingSource? = nil, - authorizedTopUpDuffs: UInt64? = nil + authorizedTopUpDuffs: UInt64? = nil, + preparation: SwiftDashSDKHost.PlatformPreparation? = nil ) async throws -> Identifier { guard !isAttemptActive else { throw CoordinatorError.alreadyInFlight @@ -1174,6 +1209,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { throw CoordinatorError.invalidTemporaryUsername } } + let preparation = try preparation ?? SwiftDashSDKHost.shared.preparePlatformOperation() + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) resetState() currentUsername = username registrationWalletId = wallet.walletId @@ -1204,6 +1241,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { } do { try validateRegistrationContext(walletId: wallet.walletId, network: network) + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) // Restore signing material after seed recovery. Use this identity's // recorded derivation index, never assume the selected identity is 0. guard let index = try wallet.managedIdentity(identityId: identityId).getIdentityIndex() else { @@ -1219,7 +1257,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { return try await finishUsernameRegistration( identityId: identityId, username: username, temporaryUsername: temporaryUsername, wallet: wallet, network: network, signer: KeychainSigner(modelContainer: container), - newController: newController, contestFundCredits: contestFundCredits, + newController: newController, preparation: preparation, contestFundCredits: contestFundCredits, topUp: topUpSource.map { IdentityTopUpPlan(source: $0, modelContainer: container, authorizedDuffs: authorizedTopUpDuffs) }) @@ -1313,6 +1351,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { identityId: Identifier, username: String, temporaryUsername: String?, wallet: ManagedPlatformWallet, network: Network, signer: KeychainSigner, newController: DWIdentityRegistrationController, + preparation: SwiftDashSDKHost.PlatformPreparation, authorize: () async throws -> Void = {}, contestFundCredits: UInt64?, topUp: IdentityTopUpPlan? = nil @@ -1322,7 +1361,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { return try await registerNames( identityId: identityId, username: username, temporaryUsername: temporaryUsername, wallet: wallet, network: network, signer: signer, newController: newController, - authorize: authorize, contestFundCredits: contestFundCredits, topUp: topUp) + preparation: preparation, authorize: authorize, contestFundCredits: contestFundCredits, topUp: topUp) } catch DWIdentityAuthorizer.AuthError.cancelled { throw DWIdentityAuthorizer.AuthError.cancelled } catch { @@ -1373,7 +1412,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { identityId: Identifier, username: String, temporaryUsername: String?, plan: IdentityTopUpPlan, contestFundCredits: UInt64, wallet: ManagedPlatformWallet, network: Network, - signer: KeychainSigner, newController: DWIdentityRegistrationController + signer: KeychainSigner, newController: DWIdentityRegistrationController, + preparation: SwiftDashSDKHost.PlatformPreparation ) async throws { let requiredCredits = Self.requiredRegistrationCredits( username: username, temporaryUsername: temporaryUsername, @@ -1405,6 +1445,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { newController.enterInFlight() do { try validateRegistrationContext(walletId: wallet.walletId, network: network) + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) switch plan.source { case .core: let spendableDuffs = SwiftDashSDKWalletState.shared.feeAwareMaxSendable() @@ -1456,6 +1497,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { identityId: Identifier, username: String, temporaryUsername: String?, wallet: ManagedPlatformWallet, network: Network, signer: KeychainSigner, newController: DWIdentityRegistrationController, + preparation: SwiftDashSDKHost.PlatformPreparation, authorize: () async throws -> Void, contestFundCredits: UInt64?, topUp: IdentityTopUpPlan? @@ -1524,11 +1566,14 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { temporaryUsername: temporaryUsername, plan: topUp, contestFundCredits: maxContestFund ?? 0, wallet: wallet, network: network, signer: signer, - newController: newController) + newController: newController, preparation: preparation) + } + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) + _ = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: preparation) { + try await wallet.registerDpnsName( + identityId: identityId, name: username, signer: signer, + maxContestFund: maxContestFund) } - _ = try await wallet.registerDpnsName( - identityId: identityId, name: username, signer: signer, - maxContestFund: maxContestFund) }) Self.logger.info("🪪 IDENT-COORD :: DPNS name registered: \(username)") // A request for another name is now on Platform: an earlier one's @@ -1555,7 +1600,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { // step-2.9 bookmark would report a contest that does not exist. withdrawPrematureBookmark( username, isContested: isContestedSubmission, network: network, wallet: wallet) - throw CoordinatorError.dpnsRegistration(error) + throw CoordinatorError.dpnsRegistration(preservingUnconfirmedOutcome(error)) } if !isContestedSubmission || nameState == .owned { @@ -1631,8 +1676,11 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { temporaryUsername, identityId: identityId, wallet: wallet) }, register: { - _ = try await wallet.registerDpnsName( - identityId: identityId, name: temporaryUsername, signer: signer) + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) + _ = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: preparation) { + try await wallet.registerDpnsName( + identityId: identityId, name: temporaryUsername, signer: signer) + } }) DWCurrentUserIdentityInfo.persistConfirmedUsername( temporaryUsername, identityId: identityId, walletId: wallet.walletId, container: registrationContainer) @@ -1779,14 +1827,15 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { username: String, invitationURI: String, temporaryUsername: String? = nil, - verificationURL: URL? = nil + verificationURL: URL? = nil, + preparation: SwiftDashSDKHost.PlatformPreparation? = nil ) async throws -> Identifier { try await startCreateUsername( username, fundingSource: .invitation, invitationURI: invitationURI, temporaryUsername: temporaryUsername, - verificationURL: verificationURL) + verificationURL: verificationURL, preparation: preparation) } /// Credits a buyer identity must hold: the sale price plus the same @@ -1816,7 +1865,10 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { /// writes (a purchase never writes a contested bookmark, so the /// deferral branch in `handlePhaseChange` cannot trigger). @discardableResult - func startPurchaseUsername(name: String, priceCredits: UInt64) async throws -> Identifier { + func startPurchaseUsername( + name: String, priceCredits: UInt64, + preparation: SwiftDashSDKHost.PlatformPreparation? = nil + ) async throws -> Identifier { Self.logger.info("🪪 IDENT-COORD :: startPurchaseUsername name=\(name) priceCredits=\(priceCredits)") guard let wallet = SwiftDashSDKHost.shared.wallet else { @@ -1838,6 +1890,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { let identitySnapshot = DWCurrentUserIdentityInfo.shared.refreshedSnapshot() guard !identitySnapshot.isLoading else { throw CoordinatorError.noWallet } let selectedIdentityId = identitySnapshot.identityId + let preparation = try preparation ?? SwiftDashSDKHost.shared.preparePlatformOperation() + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) // Single-flight — same rationale as `startCreateUsername`: the // funding FFI calls race to their terminal even if we stop @@ -1874,6 +1928,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { do { try validatePurchaseContext(walletId: wallet.walletId, network: network, identityId: selectedIdentityId) + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) } catch { newController.enterFailed(error.localizedDescription) throw error @@ -1896,10 +1951,12 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { let shortfallDuffs = Self.purchaseTopUpDuffs(priceCredits: priceCredits, heldCredits: heldCredits) if shortfallDuffs > 0 { Self.logger.info("🪪 IDENT-COORD :: purchase top-up shortfallDuffs=\(shortfallDuffs)") - _ = try await wallet.topUpIdentityWithFunding( + _ = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: preparation) { + try await wallet.topUpIdentityWithFunding( identityId: existingId, amountDuffs: shortfallDuffs, accountIndex: Self.defaultAccountIndex) + } } } else { // Fresh identity, funded with the full purchase amount. @@ -1918,20 +1975,24 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { network: network)) newController.enterInFlight() let fundingDuffs = (requiredCredits + 999) / 1_000 - let result = try await wallet.registerIdentityWithFunding( - amountDuffs: fundingDuffs, - accountIndex: Self.defaultAccountIndex, - identityIndex: Self.pinnedIdentityIndex, - identityPubkeys: pubkeys, - signer: signer) + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) + let result = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: preparation) { + try await wallet.registerIdentityWithFunding( + amountDuffs: fundingDuffs, + accountIndex: Self.defaultAccountIndex, + identityIndex: Self.pinnedIdentityIndex, + identityPubkeys: pubkeys, + signer: signer) + } identityId = result.0 } } catch { Self.logger.error("🪪 IDENT-COORD :: purchase funding failed: \(String(describing: error))") failedAtPhase = assetLockStatus < 2 ? .processingPayment : .creatingID - lastErrorMessage = error.localizedDescription - newController.enterFailed(error.localizedDescription) - throw CoordinatorError.identityRegistration(error) + let reportedError = preservingUnconfirmedOutcome(error) + lastErrorMessage = reportedError.localizedDescription + newController.enterFailed(reportedError.localizedDescription) + throw CoordinatorError.identityRegistration(reportedError) } // The purchase itself — exact-price: the SDK pre-flights the @@ -1940,11 +2001,13 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { // index keys on the normalized label. do { try validatePurchaseContext(walletId: wallet.walletId, network: network, identityId: selectedIdentityId) - _ = try await wallet.purchaseDpnsName( + _ = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: preparation) { + try await wallet.purchaseDpnsName( purchaserIdentityId: identityId, name: normalizedName, expectedPriceCredits: priceCredits, signer: signer) + } Self.logger.info("🪪 IDENT-COORD :: purchased \(name) for \(priceCredits) credits") // Bought now: an earlier lost contest for it no longer hides it. // The label as asked for; the store matches DPNS-normalized forms. @@ -1953,7 +2016,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { } catch { Self.logger.error("🪪 IDENT-COORD :: purchase failed: \(String(describing: error))") failedAtPhase = .registrationUsername - let coordError = CoordinatorError.purchase(error) + let coordError = CoordinatorError.purchase(preservingUnconfirmedOutcome(error)) lastErrorMessage = coordError.localizedDescription newController.enterFailed(lastErrorMessage ?? "") throw coordError @@ -2937,7 +3000,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { walletId: Data, modelContainer: ModelContainer, pubkeys: [ManagedPlatformWallet.IdentityPubkey], - signer: KeychainSigner + signer: KeychainSigner, + preparation: SwiftDashSDKHost.PlatformPreparation ) async throws -> Identifier { guard let manager = SwiftDashSDKHost.shared.manager else { throw CoordinatorError.noSDK @@ -2976,18 +3040,20 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { Self.logger.info("🪪 IDENT-COORD :: shielded create denomination=\(denomination) contested=\(contested)") do { - let identityId = try await manager.shieldedIdentityCreateFromPool( - walletId: walletId, - // Per-operation Orchard spend authority (seedless - // shielded bind) — same pattern as the app's other - // shielded spends in `ShieldedTransferCoordinator`. - resolver: MnemonicResolver(), - account: 0, - identityIndex: Self.pinnedIdentityIndex, - identityPubkeys: pubkeys, - denomination: denomination, - sendToAddressOnCreationFailure: fallbackAddressBytes, - identitySigner: signer) + let identityId = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: preparation) { + try await manager.shieldedIdentityCreateFromPool( + walletId: walletId, + // Per-operation Orchard spend authority (seedless + // shielded bind) — same pattern as the app's other + // shielded spends in `ShieldedTransferCoordinator`. + resolver: MnemonicResolver(), + account: 0, + identityIndex: Self.pinnedIdentityIndex, + identityPubkeys: pubkeys, + denomination: denomination, + sendToAddressOnCreationFailure: fallbackAddressBytes, + identitySigner: signer) + } PlatformAddressSyncCoordinator.shared .refreshShieldedBalanceAfterSpend(using: manager) return identityId diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift index ded23dfd9a..c81b26c705 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift @@ -350,6 +350,7 @@ final class SwiftDashSDKHost { private(set) var modelContainer: ModelContainer? private(set) var runningNetwork: Network? private let modelContainerCache = ProcessNetworkValueCache() + private var runtimeID = UUID() private let storeLifetimes = WalletLocalStoreLifetimeBarrier() /// Monotonic for this process. Native destroy may leave storage workers /// alive, including SPV workers without a Swift persistence callback. @@ -457,6 +458,64 @@ final class SwiftDashSDKHost { } } + struct PlatformPreparation { + fileprivate let sdk: SDK + fileprivate let runtimeID: UUID + fileprivate let walletID: Data + fileprivate let network: Network + fileprivate let protocolVersion: UInt32 + } + + /// Bind a displayed quote to the actual wallet/runtime and operation version. + /// The status and generation of informational checks are deliberately ignored. + func preparePlatformOperation() throws -> PlatformPreparation { + let selectedWalletID = WalletEnvironment.activeWalletId(for: WalletEnvironment.networkKind) + guard let sdk, let network = runningNetwork, network == WalletEnvironment.network, + let walletID = wallet?.walletId, + selectedWalletID == nil || selectedWalletID == walletID else { + throw WalletOperationPreparationError.unavailable("The active wallet is not ready") + } + return PlatformPreparation( + sdk: sdk, + runtimeID: runtimeID, + walletID: walletID, + network: network, + protocolVersion: try sdk.protocolVersionInfo().effectiveVersion) + } + + /// Refresh only the Platform leg of an already committed asset lock. + /// Its original wallet/runtime must still be active; this is not a new quote. + func preparePlatformRecoveryOperation(matching preparation: PlatformPreparation) throws -> PlatformPreparation { + let current = try preparePlatformOperation() + guard current.runtimeID == preparation.runtimeID, + current.sdk === preparation.sdk, + current.walletID == preparation.walletID, + current.network == preparation.network else { + throw WalletOperationPreparationError.expired("Wallet session changed; reopen recovery for this transfer") + } + return current + } + + func validatePlatformOperation(_ preparation: PlatformPreparation) throws { + let selectedWalletID = WalletEnvironment.activeWalletId(for: WalletEnvironment.networkKind) + guard preparation.runtimeID == runtimeID, preparation.sdk === sdk, + preparation.network == runningNetwork, + runningNetwork == WalletEnvironment.network, + preparation.walletID == wallet?.walletId, + selectedWalletID == nil || selectedWalletID == preparation.walletID, + preparation.protocolVersion == (try preparation.sdk.protocolVersionInfo()).effectiveVersion else { + throw WalletOperationPreparationError.expired("Wallet or operation version changed; review and confirm again") + } + } + + func withPlatformOperation( + preparation: PlatformPreparation, + operation: () async throws -> T + ) async throws -> T { + try validatePlatformOperation(preparation) + return try await operation() + } + // MARK: - Wallet presence /// True when at least one SDK wallet mnemonic is persisted in @@ -1289,6 +1348,7 @@ final class SwiftDashSDKHost { /// invariant doesn't hold here. @discardableResult func stopAsync() async -> PlatformWalletShutdownMetrics? { + runtimeID = UUID() protocolCompatibility.detach() let drainWatch = contactCryptoDrainWatch contactCryptoDrainWatch = nil @@ -1329,6 +1389,7 @@ final class SwiftDashSDKHost { // MARK: - Runtime bootstrap private func buildRuntime(for network: Network) async throws -> RuntimeHandles { + runtimeID = UUID() if manager != nil { await stopAsync() } @@ -2163,3 +2224,13 @@ enum GeneratedWalletIdentityMarker { defaults.removeObject(forKey: key(walletId: walletId)) } } + +enum WalletOperationPreparationError: LocalizedError { + case unavailable(String) + case expired(String) + var errorDescription: String? { + switch self { + case .unavailable(let message), .expired(let message): return message + } + } +} diff --git a/DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift b/DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift index b00788c25b..f5f368b2c2 100644 --- a/DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift +++ b/DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift @@ -539,18 +539,23 @@ final class IdentityTopUpViewModel: ObservableObject { @Published var isProcessing = false @Published var errorMessage: String? + @Published private(set) var submittedUnconfirmed = false /// User-visible progress for the shielded route's two steps. @Published var stepLabel: String? - private let authorizer = DWIdentityAuthorizer() enum TopUpError: LocalizedError { case noPlatformReceiveAddress + case movedToPlatform(Error) var errorDescription: String? { switch self { case .noPlatformReceiveAddress: return NSLocalizedString("No Platform receive address is available yet — wait for the Platform sync to finish and try again.", comment: "Identity top-up sheet — missing unshield destination") + case .movedToPlatform(let error): + return NSLocalizedString( + "Dash was moved to your Platform balance. Finish the top-up from Platform after reviewing the amount again.", + comment: "Identity top-up stopped after successful unshield") + " " + error.localizedDescription } } } @@ -596,7 +601,10 @@ final class IdentityTopUpViewModel: ObservableObject { } /// nil = cancelled or failed (errorMessage carries the failure). - func topUp(identityId: Data, amountDuffs: UInt64, source: FundingSource) async -> UInt64? { + func topUp( + identityId: Data, amountDuffs: UInt64, source: FundingSource, + preparation: SwiftDashSDKHost.PlatformPreparation? = nil + ) async -> UInt64? { guard !isProcessing else { return nil } guard let wallet = SwiftDashSDKHost.shared.wallet, let modelContainer = SwiftDashSDKHost.shared.modelContainer else { @@ -604,10 +612,19 @@ final class IdentityTopUpViewModel: ObservableObject { return nil } isProcessing = true + submittedUnconfirmed = false defer { isProcessing = false stepLabel = nil } + let confirmedPreparation: SwiftDashSDKHost.PlatformPreparation + do { + confirmedPreparation = try preparation ?? SwiftDashSDKHost.shared.preparePlatformOperation() + try validatePreparation(confirmedPreparation, walletId: wallet.walletId) + } catch { + errorMessage = error.localizedDescription + return nil + } do { try await authorizer.authorize() } catch { @@ -615,12 +632,15 @@ final class IdentityTopUpViewModel: ObservableObject { return nil } do { + try validatePreparation(confirmedPreparation, walletId: wallet.walletId) switch source { case .transparent: - return try await wallet.topUpIdentityWithFunding( - identityId: identityId, - amountDuffs: amountDuffs, - accountIndex: 0) + return try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: confirmedPreparation) { + try await wallet.topUpIdentityWithFunding( + identityId: identityId, + amountDuffs: amountDuffs, + accountIndex: 0) + } case .platform: let credits = amountDuffs * PlatformPaymentIdentityFundingPolicy.creditsPerDuff @@ -631,18 +651,28 @@ final class IdentityTopUpViewModel: ObservableObject { candidates: candidates, targetCredits: credits) let signer = KeychainSigner(modelContainer: modelContainer) - return try await wallet.topUpFromAddresses( - identityId: identityId, - inputs: inputs, - addressSigner: signer) + return try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: confirmedPreparation) { + try await wallet.topUpFromAddresses( + identityId: identityId, + inputs: inputs, + addressSigner: signer) + } case .shielded: return try await topUpFromShielded( identityId: identityId, amountDuffs: amountDuffs, wallet: wallet, - modelContainer: modelContainer) + modelContainer: modelContainer, + preparation: confirmedPreparation) } + } catch PlatformWalletError.transactionBroadcastUnconfirmed, + PlatformWalletError.shieldedSpendUnconfirmed { + submittedUnconfirmed = true + errorMessage = NSLocalizedString( + "The transfer may have been submitted, but its result could not be confirmed. Wait for the wallet to sync and check your balances and history before making another transfer.", + comment: "Identity transfer result unknown") + return nil } catch let error as PlatformPaymentIdentityFundingPolicy.PlanningError { if case .insufficient(let required, let available) = error { errorMessage = String.localizedStringWithFormat( @@ -659,13 +689,23 @@ final class IdentityTopUpViewModel: ObservableObject { } } + private func validatePreparation( + _ preparation: SwiftDashSDKHost.PlatformPreparation, walletId: Data + ) throws { + guard SwiftDashSDKHost.shared.wallet?.walletId == walletId else { + throw WalletOperationPreparationError.expired("The selected wallet changed; review and confirm again") + } + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) + } + /// The privacy-default two-step: Shielded → own Platform address → /// identity credits. private func topUpFromShielded( identityId: Data, amountDuffs: UInt64, wallet: ManagedPlatformWallet, - modelContainer: ModelContainer + modelContainer: ModelContainer, + preparation: SwiftDashSDKHost.PlatformPreparation ) async throws -> UInt64 { guard let manager = SwiftDashSDKHost.shared.manager else { throw SwiftDashSDKContactsService.ServiceError.noWallet @@ -686,12 +726,15 @@ final class IdentityTopUpViewModel: ObservableObject { // destination when it returns; the unshield's own fee comes from // the shielded side on top of `credits`. stepLabel = NSLocalizedString("Step 1 of 2 — moving Dash out of your Shielded balance…", comment: "Identity top-up sheet — shielded route progress") - try await manager.shieldedUnshield( - walletId: wallet.walletId, - resolver: MnemonicResolver(), - account: 0, - toPlatformAddress: destination, - amount: credits) + try validatePreparation(preparation, walletId: wallet.walletId) + try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: preparation) { + try await manager.shieldedUnshield( + walletId: wallet.walletId, + resolver: MnemonicResolver(), + account: 0, + toPlatformAddress: destination, + amount: credits) + } // Same post-spend refreshes the transfer coordinator schedules — // BLAST stays the source of truth for the persisted balances. PlatformAddressSyncCoordinator.shared.refreshShieldedBalanceAfterSpend(using: manager) @@ -709,10 +752,33 @@ final class IdentityTopUpViewModel: ObservableObject { hash: Data(storageBytes.dropFirst()), credits: claim) let signer = KeychainSigner(modelContainer: modelContainer) - let newBalance = try await wallet.topUpFromAddresses( - identityId: identityId, - inputs: [input], - addressSigner: signer) + do { + try validatePreparation(preparation, walletId: wallet.walletId) + } catch { + throw TopUpError.movedToPlatform(error) + } + let newBalance: UInt64 + do { + newBalance = try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: preparation) { + try await wallet.topUpFromAddresses( + identityId: identityId, + inputs: [input], + addressSigner: signer) + } + } catch { + // An unknown second-leg result may already have credited the + // identity. Keep its diagnostic instead of suggesting a new top-up. + if case PlatformWalletError.transactionBroadcastUnconfirmed = error { + throw error + } + if case PlatformWalletError.shieldedSpendUnconfirmed = error { + throw error + } + if error is CancellationError { + throw error + } + throw TopUpError.movedToPlatform(error) + } Task { await PlatformAddressSyncCoordinator.shared.syncNow() } return newBalance } @@ -902,7 +968,7 @@ struct IdentityTopUpSheet: View { .cornerRadius(12) } } - .disabled(viewModel.isProcessing || effectiveDuffs == nil) + .disabled(viewModel.isProcessing || viewModel.submittedUnconfirmed || effectiveDuffs == nil) .opacity(effectiveDuffs == nil ? 0.55 : 1) .padding(.horizontal, 20) .padding(.top, 20) @@ -924,7 +990,9 @@ struct IdentityTopUpSheet: View { .background(Color.dash.primaryBackground) .interactiveDismissDisabled(viewModel.isProcessing) .alert( - NSLocalizedString("Error", comment: ""), + viewModel.submittedUnconfirmed + ? NSLocalizedString("Confirmation pending", comment: "Identity transfer result unknown") + : NSLocalizedString("Error", comment: ""), isPresented: Binding( get: { viewModel.errorMessage != nil }, set: { if !$0 { viewModel.errorMessage = nil } }) diff --git a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift index 972dd22df0..1d707859bd 100644 --- a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift +++ b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift @@ -1391,6 +1391,12 @@ struct CreateUsernameView: View { /// Continue's routing. The paying source is settled later, in /// `performSubmit` (asked there when the form picked it itself). private func beginContinue() { + do { + try viewModel.prepareConfirmation() + } catch { + refuseSubmission(error.localizedDescription) + return + } if viewModel.hasUnfinishedCoreTopUp( source: payingSource(agreed: nil), nameCount: 1, isPurchase: viewModel.canPurchaseListedNameDirectly) { @@ -1879,4 +1885,3 @@ private struct InstantUsernameForm: View { .scrollDismissesKeyboard(.interactively) } } - diff --git a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift index 841cfa069a..aecba8797a 100644 --- a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift +++ b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift @@ -59,6 +59,25 @@ class CreateUsernameViewModel: ObservableObject { private(set) var submittedRegistrationUsername: String? private var didNotifyRegistrationStarted = false private var onRegistrationStarted: (@MainActor () -> Void)? + private var confirmationPreparation: SwiftDashSDKHost.PlatformPreparation? + + + /// Capture before presenting the contested-name or purchase confirmation. + func prepareConfirmation() throws { + confirmationPreparation = nil + confirmationPreparation = try SwiftDashSDKHost.shared.preparePlatformOperation() + } + + func clearConfirmation() { confirmationPreparation = nil } + + private func takeConfirmationPreparation() throws -> SwiftDashSDKHost.PlatformPreparation { + defer { confirmationPreparation = nil } + guard let preparation = confirmationPreparation else { + throw WalletOperationPreparationError.expired("Review and confirm the registration again") + } + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) + return preparation + } /// In-flight DPNS availability check. Cancelled and replaced when /// the typed label changes, so only the newest input hits the network. private var availabilityCheckTask: Task? @@ -806,6 +825,12 @@ class CreateUsernameViewModel: ObservableObject { temporaryUsername: String? = nil, onRegistrationStarted: @escaping @MainActor () -> Void = {} ) async -> UsernameRegistrationOutcome { + let preparation: SwiftDashSDKHost.PlatformPreparation + do { + preparation = try takeConfirmationPreparation() + } catch { + return .failure(error.localizedDescription) + } // The cached ceiling tracks the balance publisher, which is enough for // per-keystroke validation. Submission spends real UTXOs, so re-derive // it once here from the live set: one FFI walk on an explicit user @@ -889,7 +914,7 @@ class CreateUsernameViewModel: ObservableObject { // accepted link is held on the bridge; this path skips the // bridge, so it has to fetch the link itself. verificationURL: DWIdentityRegistrationBridge.shared - .verificationURL(forSubmissionOf: submittedUsername)) + .verificationURL(forSubmissionOf: submittedUsername), preparation: preparation) // This path never REFERENCES `DWIdentityRegistrationBridge.shared`, // so on an invitation-first launch that singleton may never be // constructed, and then never observes the coordinator's phases @@ -944,7 +969,9 @@ class CreateUsernameViewModel: ObservableObject { DWIdentityRegistrationBridge.shared.pendingTemporaryUsername = temporaryUsername return await withCheckedContinuation { (continuation: CheckedContinuation) in - DWIdentityRegistrationBridge.shared.startCreateUsername(submittedUsername) { [weak self] _, error in + DWIdentityRegistrationBridge.shared.startCreateUsername( + submittedUsername, preparation: preparation + ) { [weak self] _, error in Task { @MainActor in self?.submittedRegistrationUsername = nil self?.didNotifyRegistrationStarted = false @@ -987,9 +1014,10 @@ class CreateUsernameViewModel: ObservableObject { return .failure(NSLocalizedString("This username is not for sale.", comment: "Username marketplace")) } do { + let preparation = try takeConfirmationPreparation() _ = try await DWIdentityRegistrationCoordinator.shared.startPurchaseUsername( name: name, - priceCredits: credits) + priceCredits: credits, preparation: preparation) return .success } catch let error as DWIdentityRegistrationCoordinator.CoordinatorError where error.isCompletedPurchase { diff --git a/DashWallet/Sources/UI/Home/Views/CoinJoinMoveFunds/CoinJoinMoveFundsViewModel.swift b/DashWallet/Sources/UI/Home/Views/CoinJoinMoveFunds/CoinJoinMoveFundsViewModel.swift index ad1cecf9c4..9ac4cf4ed5 100644 --- a/DashWallet/Sources/UI/Home/Views/CoinJoinMoveFunds/CoinJoinMoveFundsViewModel.swift +++ b/DashWallet/Sources/UI/Home/Views/CoinJoinMoveFunds/CoinJoinMoveFundsViewModel.swift @@ -103,6 +103,10 @@ final class CoinJoinMoveFundsViewModel: ObservableObject { /// runs its own PIN/biometric gate, so this is the flow's single prompt. func moveToShielded() async { guard !isInFlight else { return } + if coordinator.lastAssetLockOutPoint != nil { + await retryShielded() + return + } stage = .shielding // A prior failed attempt leaves the coordinator terminal; reset so // `beginTransfer()` doesn't silently bail. @@ -120,11 +124,10 @@ final class CoinJoinMoveFundsViewModel: ObservableObject { /// left the CoinJoin account untouched. func retryShielded() async { guard !isInFlight else { return } - if let op = coordinator.lastAssetLockOutPoint { + if coordinator.lastAssetLockOutPoint != nil { stage = .shielding - coordinator.reset() - // Resume re-authorizes on its own (fresh user action). - await coordinator.resumeAssetLock(outPointTxidWire: op.txidWire, outPointVout: op.vout) + // Keep the same lock and wallet context through failure or PIN cancellation. + await coordinator.retryLastAssetLock() finishFromCoordinatorPhase() return } @@ -149,7 +152,7 @@ final class CoinJoinMoveFundsViewModel: ObservableObject { // auth-cancel handling). Message-compare against the same // localized source the coordinator maps the cancel to. if message == ShieldedTransferCoordinator.CoordinatorError.authCancelled.errorDescription { - coordinator.reset() + // Preserve any committed lock; the next action resumes it. stage = .choice } else { stage = .failed(message: message, destination: .shielded) diff --git a/DashWallet/Sources/UI/Menu/Tools/Evonode Status/EvonodeStatusViewModel.swift b/DashWallet/Sources/UI/Menu/Tools/Evonode Status/EvonodeStatusViewModel.swift index 804b0721c7..9f58b58c2a 100644 --- a/DashWallet/Sources/UI/Menu/Tools/Evonode Status/EvonodeStatusViewModel.swift +++ b/DashWallet/Sources/UI/Menu/Tools/Evonode Status/EvonodeStatusViewModel.swift @@ -138,6 +138,7 @@ final class EvonodeStatusViewModel: ObservableObject { case .invalidParameter(let detail), .invalidState(let detail), .protocolError(let detail), .cryptoError(let detail), .notFound(let detail), .notImplemented(let detail), .internalError(let detail), .unknown(let detail), + .stateTransitionResultUnconfirmed(let detail), .consensusRejection(_, let detail): return .failed( title: NSLocalizedString("Couldn't get the evonode's status.", comment: "Evonode status"), diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferConfirmSheet.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferConfirmSheet.swift index ddbbb73e57..1ff259c524 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferConfirmSheet.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferConfirmSheet.swift @@ -55,6 +55,7 @@ struct InternalTransferConfirmSheet: View { coreShieldedDrain: CoreShieldedDrainConfirmation? = nil, identityTopUp: IdentityTopUpTransfer? = nil, identityWithdrawal: IdentityWithdrawalTransfer? = nil, + preparation: Result, onCancel: @escaping () -> Void, onSubmitted: @escaping () -> Void, onPlatformShieldCapacityChanged: @escaping (UInt64?, Bool) -> Void @@ -74,7 +75,8 @@ struct InternalTransferConfirmSheet: View { isFullPlatformWithdrawal: isFullPlatformWithdrawal, isFullShieldedSweep: isFullShieldedSweep, platformShieldAmountWasMax: platformShieldAmountWasMax, - coreShieldedDrain: coreShieldedDrain)) + coreShieldedDrain: coreShieldedDrain, + preparation: preparation)) self.onCancel = onCancel self.onSubmitted = onSubmitted self.onPlatformShieldCapacityChanged = onPlatformShieldCapacityChanged @@ -158,9 +160,13 @@ struct InternalTransferConfirmSheet: View { guard !isSubmitting else { return } isSubmitting = true Task { - let handedOff = await viewModel.confirm() + let outcome = await viewModel.confirm() isSubmitting = false - if handedOff { onSubmitted() } + switch outcome { + case .started, .busy: onSubmitted() + case .rejected: onCancel() + case .notAuthorized: break + } } } @@ -215,6 +221,7 @@ private func confirmSheetSample( platformShieldAmountWasMax: false, identityTopUp: identityTopUp, identityWithdrawal: identityWithdrawal, + preparation: .failure(WalletOperationPreparationError.unavailable("Preview")), onCancel: {}, onSubmitted: {}, onPlatformShieldCapacityChanged: { _, _ in }) diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferConfirmViewModel.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferConfirmViewModel.swift index 6a8d589986..721ea9ae2a 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferConfirmViewModel.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferConfirmViewModel.swift @@ -60,6 +60,7 @@ final class InternalTransferConfirmViewModel: ObservableObject { @Published private(set) var platformShieldCapacityChange: InternalTransferRunner.PlatformShieldCapacityChange? + private let preparation: Result private let runner: InternalTransferRunner private var cancellables = Set() @@ -79,6 +80,7 @@ final class InternalTransferConfirmViewModel: ObservableObject { isFullShieldedSweep: Bool, platformShieldAmountWasMax: Bool, coreShieldedDrain: CoreShieldedDrainConfirmation? = nil, + preparation: Result, runner: InternalTransferRunner = .shared ) { // Precedence matches what the view did before: an identity transfer @@ -112,6 +114,7 @@ final class InternalTransferConfirmViewModel: ObservableObject { self.networkFeeCredits = networkFeeCredits self.totalDuffs = totalDuffs self.runner = runner + self.preparation = preparation // `dropFirst` because the runner is shared: whatever a previous // transfer left in this property is already there at subscribe time, @@ -174,14 +177,12 @@ final class InternalTransferConfirmViewModel: ObservableObject { // MARK: - Actions - /// Runs the auth gate, then hands the transfer off. Returns whether the - /// sheet has finished with the user: it stays open when the PIN prompt was - /// backed out of, so Confirm can simply be tapped again — everything else, - /// including a refusal because another transfer is still running, is - /// announced by a toast on the surface behind it. - func confirm() async -> Bool { - guard case .transfer(let request) = mode else { return false } - return await runner.start(request) != .notAuthorized + /// Preserve the runner outcome so the sheet can distinguish submission, + /// cancelled authorization, and a stale confirmation. A rejected snapshot + /// dismisses only the sheet; Continue on the amount form captures a fresh one. + func confirm() async -> InternalTransferRunner.StartOutcome { + guard case .transfer(let request) = mode else { return .rejected } + return await runner.start(request, preparation: preparation) } // MARK: - Request accessors diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferRunner.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferRunner.swift index b642615c26..c3fefc6eb1 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferRunner.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferRunner.swift @@ -69,8 +69,7 @@ final class InternalTransferRunner: ObservableObject { static let shared = InternalTransferRunner() /// The one lifecycle callers render from, whichever executor is running. - /// `submittedUnconfirmed` is route-only — no identity transition lands in - /// that state. + /// `submittedUnconfirmed` also covers identity transfers with an unknown outcome. enum Phase: Equatable { case idle case inFlight @@ -95,6 +94,7 @@ final class InternalTransferRunner: ObservableObject { /// The user backed out of the PIN prompt, or it failed. Not an error /// state — the caller returns to what it was showing. case notAuthorized + case rejected } @Published private(set) var phase: Phase = .idle @@ -127,8 +127,7 @@ final class InternalTransferRunner: ObservableObject { /// like Confirm did nothing. case busy case succeeded - /// Accepted by the network but not yet confirmed — a shielded spend - /// whose receipt has not landed. + /// A submitted transfer whose execution result could not be confirmed. case submitted case drainPending case failed(String) @@ -197,12 +196,23 @@ final class InternalTransferRunner: ObservableObject { /// leaving it to them meant the sheet closed first and the user met the /// prompt on whatever screen they landed on. `preauthorized` below is what /// keeps that inner gate from asking a second time. - func start(_ request: InternalTransferRequest) async -> StartOutcome { + func start( + _ request: InternalTransferRequest, + preparation: Result + ) async -> StartOutcome { guard phase != .inFlight, !isAwaitingAuthorization else { notice = .busy return .busy } + do { + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation.get()) + } catch { + phase = .failed(error.localizedDescription) + notice = .failed(error.localizedDescription) + return .rejected + } + // Claimed BEFORE the gate, not after. `phase` only becomes `.inFlight` // once an executor is running, and the PIN prompt sits in between — // three entry points build a transfer screen against this one shared @@ -220,12 +230,21 @@ final class InternalTransferRunner: ObservableObject { return .notAuthorized } + do { + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation.get()) + } catch { + phase = .failed(error.localizedDescription) + notice = .failed(error.localizedDescription) + return .rejected + } + // Clear what the previous transfer left, so this one is not read // through its outcome. self.request = request phase = .idle platformShieldCapacityChange = nil coordinator.reset() + coordinator.bindConfirmationPreparation(preparation) // Claimed here, not inside the task `run` schedules: `defer` clears // `isAwaitingAuthorization` the moment this returns, and until the @@ -234,7 +253,7 @@ final class InternalTransferRunner: ObservableObject { // guards and started a second transfer behind the first. phase = .inFlight notice = .started - run(request) + run(request, preparation: preparation) return .started } @@ -267,12 +286,15 @@ final class InternalTransferRunner: ObservableObject { isCoreDrainRecovery = true defer { isCoreDrainRecovery = false } coordinator.reset() + coordinator.bindConfirmationPreparation(Result { + try SwiftDashSDKHost.shared.preparePlatformOperation() + }) phase = .inFlight attemptedResume = true await DWIdentityAuthorizer.preauthorized { await coordinator.resumeAssetLock( outPointTxidWire: outpoint.txidWire, outPointVout: outpoint.vout, - expectedDrainContext: context) + expectedDrainContext: context, retryUnverifiedConsumption: true) } let status = try await service.status(for: pending.operation) if status.state == .completed { @@ -312,16 +334,25 @@ final class InternalTransferRunner: ObservableObject { /// held the gate open for this exact transfer. Without it the user would /// be asked for the PIN twice: once on the sheet, once again from inside /// the coordinator. - private func run(_ request: InternalTransferRequest) { + private func run(_ request: InternalTransferRequest, preparation: Result) { Task { + let prepared: SwiftDashSDKHost.PlatformPreparation + do { + prepared = try preparation.get() + try SwiftDashSDKHost.shared.validatePlatformOperation(prepared) + } catch { + phase = .failed(error.localizedDescription) + notice = .failed(error.localizedDescription) + return + } await DWIdentityAuthorizer.preauthorized { switch request.kind { case .route(let route): await runRoute(route, request) case .identityTopUp(let topUp): - await runTopUp(topUp, request) + await runTopUp(topUp, request, preparation: prepared) case .identityWithdrawal(let withdrawal): - await runWithdrawal(withdrawal, request) + await runWithdrawal(withdrawal, request, preparation: prepared) } } } @@ -364,26 +395,32 @@ final class InternalTransferRunner: ObservableObject { /// Both identity executors report the same three outcomes, so they reduce /// the same way: a result is success, a message is failure, and a bare /// nil is neither — the executor declined without anything to say. - private func runTopUp(_ topUp: IdentityTopUpTransfer, _ request: InternalTransferRequest) async { + private func runTopUp(_ topUp: IdentityTopUpTransfer, _ request: InternalTransferRequest, + preparation: SwiftDashSDKHost.PlatformPreparation) async { phase = .inFlight let newBalance = await topUpExecutor.topUp( identityId: topUp.identityId, amountDuffs: request.amountDuffsUnsigned, - source: .init(spending: topUp.source)) - phase = outcome(succeeded: newBalance != nil, message: consume(&topUpExecutor.errorMessage)) + source: .init(spending: topUp.source), + preparation: preparation) + phase = topUpExecutor.submittedUnconfirmed ? .submittedUnconfirmed + : outcome(succeeded: newBalance != nil, message: consume(&topUpExecutor.errorMessage)) announce(phase) } private func runWithdrawal( _ withdrawal: IdentityWithdrawalTransfer, - _ request: InternalTransferRequest + _ request: InternalTransferRequest, + preparation: SwiftDashSDKHost.PlatformPreparation ) async { phase = .inFlight let succeeded = await withdrawExecutor.withdraw( identityId: withdrawal.identityId, amountCredits: request.creditsAmount, - target: withdrawal.target) - phase = outcome(succeeded: succeeded, message: consume(&withdrawExecutor.errorMessage)) + target: withdrawal.target, + preparation: preparation) + phase = withdrawExecutor.submittedUnconfirmed ? .submittedUnconfirmed + : outcome(succeeded: succeeded, message: consume(&withdrawExecutor.errorMessage)) announce(phase) } @@ -395,7 +432,8 @@ final class InternalTransferRunner: ObservableObject { case .success: notice = .succeeded case .failed(let message): notice = .failed(message) case .idle: notice = nil - case .inFlight, .submittedUnconfirmed: break + case .submittedUnconfirmed: notice = .submitted + case .inFlight: break } } diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferToastModifier.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferToastModifier.swift index 7464d4331a..444e16a7ac 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferToastModifier.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/Confirm/InternalTransferToastModifier.swift @@ -63,7 +63,7 @@ private struct InternalTransferToastModifier: ViewModifier { .animation(.easeInOut(duration: 0.3), value: runner.notice) .task(id: runner.notice) { guard let remaining = runner.notice?.remainingDisplayTime( - raisedAt: runner.noticeRaisedAt, now: Date(), duration: Self.duration) + raisedAt: runner.noticeRaisedAt, now: Date(), duration: runner.notice == .submitted ? 8 : Self.duration) else { return } guard remaining > 0 else { @@ -90,8 +90,8 @@ private struct InternalTransferToastModifier: ViewModifier { private func style(for notice: InternalTransferRunner.Notice) -> ToastStyle { switch notice { case .started: return .loading - case .busy, .drainPending: return .warning - case .succeeded, .submitted: return .success + case .busy, .drainPending, .submitted: return .warning + case .succeeded: return .success case .failed: return .error } } @@ -112,8 +112,8 @@ private struct InternalTransferToastModifier: ViewModifier { comment: "") case .submitted: return NSLocalizedString( - "Transfer sent — waiting for the network to confirm it", - comment: "Internal transfer accepted but not yet confirmed") + "Transfer result unconfirmed. Don't resend it; wait for the wallet to sync and check its status.", + comment: "The transfer may have reached the network; avoid sending twice") case .drainPending: return NSLocalizedString( "Transfer status is pending. Open Core to Shielded and tap Max to check or resume it.", diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/IdentityWithdrawViewModel.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/IdentityWithdrawViewModel.swift index 9f82b5eb70..56a6eca1fc 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/IdentityWithdrawViewModel.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/IdentityWithdrawViewModel.swift @@ -38,6 +38,7 @@ final class IdentityWithdrawViewModel: ObservableObject { @Published var isProcessing = false @Published var errorMessage: String? + @Published private(set) var submittedUnconfirmed = false private let authorizer = DWIdentityAuthorizer() @@ -127,7 +128,8 @@ final class IdentityWithdrawViewModel: ObservableObject { func withdraw( identityId: Data, amountCredits: UInt64, - target: IdentityWithdrawalTarget + target: IdentityWithdrawalTarget, + preparation: SwiftDashSDKHost.PlatformPreparation? = nil ) async -> Bool { guard !isProcessing else { return false } guard let wallet = SwiftDashSDKHost.shared.wallet, @@ -136,8 +138,17 @@ final class IdentityWithdrawViewModel: ObservableObject { return false } isProcessing = true + submittedUnconfirmed = false defer { isProcessing = false } + let confirmedPreparation: SwiftDashSDKHost.PlatformPreparation + do { + confirmedPreparation = try preparation ?? SwiftDashSDKHost.shared.preparePlatformOperation() + try SwiftDashSDKHost.shared.validatePlatformOperation(confirmedPreparation) + } catch { + errorMessage = error.localizedDescription + return false + } do { try await authorizer.authorize() } catch { @@ -146,6 +157,10 @@ final class IdentityWithdrawViewModel: ObservableObject { } do { + guard SwiftDashSDKHost.shared.wallet?.walletId == wallet.walletId else { + throw WalletOperationPreparationError.expired("The selected wallet changed; review and confirm again") + } + try SwiftDashSDKHost.shared.validatePlatformOperation(confirmedPreparation) let signer = KeychainSigner(modelContainer: modelContainer) switch target { case .transparent: @@ -153,20 +168,29 @@ final class IdentityWithdrawViewModel: ObservableObject { !address.isEmpty else { throw WithdrawError.noCoreReceiveAddress } - try await wallet.withdrawCredits( - identityId: identityId, - amount: amountCredits, - toAddress: address, - signer: signer) + try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: confirmedPreparation) { + try await wallet.withdrawCredits( + identityId: identityId, + amount: amountCredits, + toAddress: address, + signer: signer) + } case .platform: try await transferToOwnPlatformAddress( identityId: identityId, amountCredits: amountCredits, wallet: wallet, - signer: signer) + signer: signer, + preparation: confirmedPreparation) } return true + } catch PlatformWalletError.transactionBroadcastUnconfirmed { + submittedUnconfirmed = true + errorMessage = NSLocalizedString( + "The transfer may have been submitted, but its result could not be confirmed. Wait for the wallet to sync and check your balances and history before making another transfer.", + comment: "Identity transfer result unknown") + return false } catch { errorMessage = Self.userFacingMessage(for: error) return false @@ -199,7 +223,8 @@ final class IdentityWithdrawViewModel: ObservableObject { identityId: Data, amountCredits: UInt64, wallet: ManagedPlatformWallet, - signer: KeychainSigner + signer: KeychainSigner, + preparation: SwiftDashSDKHost.PlatformPreparation ) async throws { guard let destination = PlatformAddressSyncCoordinator.shared .derivedAddresses.nextReceiveAddress?.address, @@ -214,10 +239,12 @@ final class IdentityWithdrawViewModel: ObservableObject { addressType: storageBytes[storageBytes.startIndex], hash: Data(storageBytes.dropFirst()), credits: amountCredits) - try await wallet.transferCreditsToAddresses( - fromIdentityId: identityId, - recipients: [recipient], - signer: signer) + try await SwiftDashSDKHost.shared.withPlatformOperation(preparation: preparation) { + try await wallet.transferCreditsToAddresses( + fromIdentityId: identityId, + recipients: [recipient], + signer: signer) + } Task { await PlatformAddressSyncCoordinator.shared.syncNow() } } } diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferScreen.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferScreen.swift index 748b02e7c0..1c654e6005 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferScreen.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferScreen.swift @@ -11,6 +11,7 @@ import DashUIKit /// rewrite the amount already presented for confirmation. private struct InternalTransferConfirmation: Identifiable { let id = UUID() + let preparation: Result /// Balance-to-balance route; `nil` exactly when one of the identity /// transfers below is set. let route: InternalTransferRoute? @@ -198,6 +199,7 @@ struct InternalTransferScreen: View { coreShieldedDrain: submission.coreShieldedDrain, identityTopUp: submission.identityTopUp, identityWithdrawal: submission.identityWithdrawal, + preparation: submission.preparation, onCancel: { confirmation = nil }, onSubmitted: { leavesAfterConfirmation = true @@ -274,6 +276,7 @@ struct InternalTransferScreen: View { let identityWithdrawal = viewModel.identityWithdrawalTransfer let isIdentityTransfer = identityTopUp != nil || identityWithdrawal != nil confirmation = InternalTransferConfirmation( + preparation: Result { try viewModel.platformPreparationForConfirmation() }, route: isIdentityTransfer ? nil : viewModel.route, dashDuffs: viewModel.dashDuffs, amountDuffsUnsigned: viewModel.dashDuffsUnsigned, diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferViewModel.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferViewModel.swift index fc6122149b..25bf10e7b4 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferViewModel.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferViewModel.swift @@ -120,21 +120,38 @@ enum CoreToShieldedAmountPolicy { /// (50_000 duffs) × 1000 credits/duff. static let assetLockBaseCostCredits: UInt64 = 50_000_000 - /// Estimated on every read, not cached: the fee follows the running - /// manager's protocol version, which differs between networks (see - /// `SwiftDashSDKHost.platformVersion(for:)`) and rises in place on an - /// auto-detected network once a proof shows a newer one. The estimate is a - /// local computation in the SDK with no network round-trip, read per - /// render like `CoreToPlatformAmountPolicy.currentReserveCredits`. + /// Reuse the quote only while its native preparation remains valid. + /// A changed effective version or runtime invalidates it even when + /// the amount form remains open across that change. + private static var cachedPoolFee: ( + preparation: SwiftDashSDKHost.PlatformPreparation, credits: UInt64? + )? + static var poolFeeCredits: UInt64? { - poolFeeCredits(addingBaseCostTo: try? SwiftDashSDKHost.shared.manager?.estimateShieldedFee( + let host = SwiftDashSDKHost.shared + if let cached = cachedPoolFee { + if (try? host.validatePlatformOperation(cached.preparation)) != nil { + return cached.credits + } + cachedPoolFee = nil + } + guard let preparation = try? host.preparePlatformOperation(), + let shieldedFee = try? host.manager?.estimateShieldedFee( kind: .transfer, - numActions: 2)) + numActions: 2), + (try? host.validatePlatformOperation(preparation)) != nil + else { + // Not cached: a failed estimate is a transient FFI condition, and + // caching it would keep the screen permanently unusable. + return nil + } + + let value = poolFeeCredits(addingBaseCostTo: shieldedFee) + cachedPoolFee = (preparation, value) + return value } - /// A ShieldFromAssetLock pool fee from the shielded fee for the fixed - /// `(transfer, 2)` shape: that fee plus the asset-lock base cost; nil - /// when there is no estimate or the sum overflows, so callers fail closed. + /// Pure fee arithmetic shared with the current develop regression tests. static func poolFeeCredits(addingBaseCostTo shieldedFeeCredits: UInt64?) -> UInt64? { guard let shieldedFeeCredits else { return nil } let (total, overflow) = shieldedFeeCredits.addingReportingOverflow(assetLockBaseCostCredits) @@ -1147,7 +1164,18 @@ final class InternalTransferViewModel: ObservableObject { } private func routeDidChange() { + withdrawalPreflightTask?.cancel() + withdrawalPreflightTask = nil + withdrawalPreflight = nil + withdrawalPreflightFailed = false + cancelPlatformShieldPreflight() + shieldedSpendCeilingCredits = nil + platformIdentityFundableDuffs = nil + platformPreparation = nil clearMaxSelection() + guard let preparation = try? SwiftDashSDKHost.shared.preparePlatformOperation() + else { return } + platformPreparation = preparation refreshShieldedSpendCeiling() refreshIdentityPlatformCeiling() @@ -1240,7 +1268,7 @@ final class InternalTransferViewModel: ObservableObject { #if DEBUG if isPreviewInstance { return } #endif - guard isIdentityDestination, source == .platform else { + guard hasCurrentPlatformPreparation, isIdentityDestination, source == .platform else { platformIdentityFundableDuffs = nil return } @@ -1248,8 +1276,8 @@ final class InternalTransferViewModel: ObservableObject { platformIdentityFundableDuffs = nil return } - platformIdentityFundableDuffs = - PlatformPaymentIdentityFundingPolicy.maxFundableDuffs(candidates: candidates) + let ceiling = PlatformPaymentIdentityFundingPolicy.maxFundableDuffs(candidates: candidates) + platformIdentityFundableDuffs = hasCurrentPlatformPreparation ? ceiling : nil } /// Net payout of the full-balance (Max) Platform → Core withdrawal, in @@ -1325,8 +1353,26 @@ final class InternalTransferViewModel: ObservableObject { /// the sync monitor singleton. @Published private(set) var isChainSynced = false + /// The same wallet/runtime and operation version cover quotes and confirmation. + private var platformPreparation: SwiftDashSDKHost.PlatformPreparation? + + func platformPreparationForConfirmation() throws -> SwiftDashSDKHost.PlatformPreparation { + guard let platformPreparation else { + throw WalletOperationPreparationError.expired("Review the amount and confirm again") + } + try SwiftDashSDKHost.shared.validatePlatformOperation(platformPreparation) + return platformPreparation + } + + private var hasCurrentPlatformPreparation: Bool { + #if DEBUG + if isPreviewInstance { return true } + #endif + return (try? platformPreparationForConfirmation()) != nil + } private var cancellables = Set() + #if DEBUG /// Stands in for `DWGlobalOptions.isResyncingWallet` in a canvas. private var previewIsResyncingWallet: Bool? @@ -1426,6 +1472,7 @@ final class InternalTransferViewModel: ObservableObject { // picker lists the identity's balance alongside the other three, so // the number has to be there before the destination is selected. refreshIdentitySnapshot() + routeDidChange() } #if DEBUG @@ -1550,11 +1597,12 @@ final class InternalTransferViewModel: ObservableObject { /// Recomputes `shieldedSpendCeilingCredits` from the current note set. /// Cached rather than computed per keystroke — it reads SwiftData. private func refreshShieldedSpendCeiling() { - guard let feeKind = activeShieldedFeeKind else { + guard hasCurrentPlatformPreparation, let feeKind = activeShieldedFeeKind else { shieldedSpendCeilingCredits = nil return } - shieldedSpendCeilingCredits = ShieldedTransferCoordinator.spendCeilingCredits(feeKind: feeKind) + let ceiling = ShieldedTransferCoordinator.spendCeilingCredits(feeKind: feeKind) + shieldedSpendCeilingCredits = hasCurrentPlatformPreparation ? ceiling : nil } /// The raw numeric value the user has typed, with locale comma normalised @@ -1895,6 +1943,7 @@ final class InternalTransferViewModel: ObservableObject { comment: "Internal transfer fee estimate unavailable") var canContinue: Bool { + guard hasCurrentPlatformPreparation else { return false } if isCoreShieldedDrain { return route == .coreToShielded && !isIdentitySource && !isIdentityDestination && isChainSynced && !isCoreDrainLoading && !coreDrainPending @@ -2247,6 +2296,11 @@ final class InternalTransferViewModel: ObservableObject { /// Source-aware Max fill. Keeps the same unit semantics — DASH or fiat — /// but draws the upper bound from whichever bucket the user picked. func fillMaxFromWallet() { + guard hasCurrentPlatformPreparation else { + clearMaxSelection() + maxNotice = Self.feeEstimateUnavailableMessage + return + } if route == .coreToShielded, !isIdentitySource, !isIdentityDestination { clearMaxSelection() isCoreShieldedDrain = true @@ -2477,11 +2531,19 @@ final class InternalTransferViewModel: ObservableObject { /// of `routeDidChange` so Max can retry a preflight that failed, instead of /// leaving the route stuck at 0 until the user toggles the route. private func startWithdrawalPreflightIfNeeded() { - guard route == .platformToCore, withdrawalPreflightTask == nil else { return } + guard !isIdentitySource, !isIdentityDestination, + route == .platformToCore, withdrawalPreflightTask == nil, + let preparation = try? platformPreparationForConfirmation() else { return } + withdrawalPreflight = nil withdrawalPreflightFailed = false withdrawalPreflightTask = Task { [weak self] in let result = try? await PlatformAddressSyncCoordinator.shared.preflightWithdrawal() guard let self, !Task.isCancelled else { return } + guard (try? SwiftDashSDKHost.shared.validatePlatformOperation(preparation)) != nil else { + self.withdrawalPreflight = nil + self.withdrawalPreflightTask = nil + return + } self.withdrawalPreflight = result self.withdrawalPreflightFailed = result == nil self.withdrawalPreflightTask = nil @@ -2521,7 +2583,9 @@ final class InternalTransferViewModel: ObservableObject { private func refreshPlatformShieldPreflight( after event: PlatformShieldAmountPolicy.PreflightRefreshEvent = .other ) { - guard route == .platformToShielded, + guard !isIdentitySource, !isIdentityDestination, + route == .platformToShielded, + let preparation = try? platformPreparationForConfirmation(), PlatformShieldAmountPolicy.shouldRefreshPreflight( after: event, awaitingPlatformResync: awaitingPlatformShieldResync) @@ -2549,6 +2613,7 @@ final class InternalTransferViewModel: ObservableObject { self.platformShieldPreflightGeneration == generation else { return } + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) let capacity = PlatformShieldCapacity(result) self.platformShieldCapacity = capacity self.isPlatformShieldPreflightLoading = false diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedRecoverySheet.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedRecoverySheet.swift index c1d9f7d9cb..d9a039803b 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedRecoverySheet.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedRecoverySheet.swift @@ -176,7 +176,8 @@ final class ShieldedRecoveryViewModel: ObservableObject { // report both land on unconfirmed rather than false success. await coordinator.resumeAssetLock( outPointTxidWire: outPoint.txidWire, - outPointVout: outPoint.vout) + outPointVout: outPoint.vout, + retryUnverifiedConsumption: true) // The shield consumed the lock; refresh so the history row flips // pending → completed without waiting for the next sync pass. diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedSubmittedUnconfirmedView.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedSubmittedUnconfirmedView.swift index d983170cc1..7ca71492ca 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedSubmittedUnconfirmedView.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedSubmittedUnconfirmedView.swift @@ -25,7 +25,7 @@ struct ShieldedSubmittedUnconfirmedView: View { .foregroundColor(.dash.primaryText) Text(NSLocalizedString( - "Your transfer was broadcast and is confirming on the network. Don't resend it — it will appear once the network confirms it.", + "Your transfer may have reached the network, but its result is not confirmed yet. Don't resend it. Wait for the wallet to sync and check its status.", comment: "InternalTransfer")) .font(.callout) .foregroundColor(.dash.secondaryText) diff --git a/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedTransferCoordinator.swift b/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedTransferCoordinator.swift index ff0fc8493e..46cf990014 100644 --- a/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedTransferCoordinator.swift +++ b/DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedTransferCoordinator.swift @@ -268,6 +268,19 @@ final class ShieldedTransferCoordinator: ObservableObject { /// Consumed) without burning CPU. private static let assetLockPollInterval: TimeInterval = 0.5 + private var confirmationPreparation: Result? + private var operationPreparation: SwiftDashSDKHost.PlatformPreparation? + + init(confirmationPreparation: Result? = nil) { + self.confirmationPreparation = confirmationPreparation + } + + /// The shared runner binds the already quoted generation before handing off. + func bindConfirmationPreparation(_ preparation: Result) { + guard case .idle = phase else { return } + confirmationPreparation = preparation + } + private let authorizer = DWIdentityAuthorizer() private var assetLockPollingTask: Task? @@ -513,6 +526,13 @@ final class ShieldedTransferCoordinator: ObservableObject { guard SyncingActivityMonitor.shared.state == .syncDone else { throw CoreShieldedDrainService.ServiceError.requiresSync } + // The status lookup above can suspend while the host replaces its + // runtime or changes the effective operation version. Recheck the + // user's confirmation before persisting a new drain operation. + guard let operationPreparation else { + throw WalletOperationPreparationError.expired("Review and confirm the operation again") + } + try SwiftDashSDKHost.shared.validatePlatformOperation(operationPreparation) env = try resolveEnvironment() operation = try service.prepare(confirmation.context) } catch { @@ -655,15 +675,19 @@ final class ShieldedTransferCoordinator: ObservableObject { // Unreachable: the entry guard derives it for every .bip44. throw CoordinatorError.shieldedPoolFeeUnavailable } - try await env.manager.shieldedFundFromAssetLock( - walletId: env.walletId, - fundingAccountIndex: 0, - amountDuffs: lockValueDuffs, - recipients: [recipient]) + try await performPrepared { + try await env.manager.shieldedFundFromAssetLock( + walletId: env.walletId, + fundingAccountIndex: 0, + amountDuffs: lockValueDuffs, + recipients: [recipient]) + } case .coinJoinDrain: - try await env.manager.shieldedFundFromCoinJoinDrain( - walletId: env.walletId, - recipients: [recipient]) + try await performPrepared { + try await env.manager.shieldedFundFromCoinJoinDrain( + walletId: env.walletId, + recipients: [recipient]) + } } } catch { stopAssetLockPolling() @@ -702,7 +726,7 @@ final class ShieldedTransferCoordinator: ObservableObject { /// /// Used by both confirm sheets' "Try again" (in-session) and the /// home-screen recovery sheet (after relaunch). - func resumeAssetLock(outPointTxidWire: Data, outPointVout: UInt32, recipientRaw43 recipientOverride: Data? = nil, expectedDrainContext: CoreShieldedDrainContext? = nil) async { + func resumeAssetLock(outPointTxidWire: Data, outPointVout: UInt32, recipientRaw43 recipientOverride: Data? = nil, expectedDrainContext: CoreShieldedDrainContext? = nil, retryUnverifiedConsumption: Bool = false) async { guard beginTransfer() else { return } Self.logger.info("🛡️ SHIELD-TX :: resume asset-lock vout=\(outPointVout) external=\(recipientOverride != nil)") @@ -714,6 +738,17 @@ final class ShieldedTransferCoordinator: ObservableObject { return } + // Capture the runtime's wallet before any suspension. Both the recovery + // sheet and the bulk service enter here; neither may lose this advisory + // result when its presenter closes or file it under a newly active wallet. + let probeWalletIdHex = env.walletId.map { String(format: "%02x", $0) }.joined() + if !retryUnverifiedConsumption, + AssetLockProbeStore.shared.contains(outPointTxidWire, vout: outPointVout, walletIdHex: probeWalletIdHex) { + lastResumeReport = .alreadyConsumed + phase = .submittedUnconfirmed + return + } + do { try await authorize() } catch { @@ -740,11 +775,13 @@ final class ShieldedTransferCoordinator: ObservableObject { let recipient = ShieldedFundFromAssetLockRecipient( recipientRaw43: recipientOverride ?? env.shieldedRecipient, credits: nil) - try await env.manager.shieldedResumeFundFromAssetLock( - walletId: env.walletId, - outPointTxid: outPointTxidWire, - outPointVout: outPointVout, - recipients: [recipient]) + try await performPrepared { + try await env.manager.shieldedResumeFundFromAssetLock( + walletId: env.walletId, + outPointTxid: outPointTxidWire, + outPointVout: outPointVout, + recipients: [recipient]) + } terminalPhase = .success } catch { guard let mappedPhase = Self.alreadyConsumedAssetLockResumePhase(for: error) else { @@ -754,9 +791,11 @@ final class ShieldedTransferCoordinator: ObservableObject { // 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 - // state, so suppress retries without claiming verified success. + // state, so suppress bulk retries without claiming verified success. + // A later explicit action can authorize another probe of this outpoint. terminalPhase = mappedPhase lastResumeReport = .alreadyConsumed + AssetLockProbeStore.shared.record(txid: outPointTxidWire, vout: outPointVout, walletIdHex: probeWalletIdHex) Self.logger.info("🛡️ SHIELD-TX :: resume found asset lock reported consumed — completion remains unconfirmed") } @@ -871,7 +910,7 @@ final class ShieldedTransferCoordinator: ObservableObject { return } } catch { - handleFailure(CoordinatorError.transferFailed(error)) + handlePlatformSpendError(error) return } @@ -890,20 +929,24 @@ final class ShieldedTransferCoordinator: ObservableObject { do { if let recipientRaw43 { - try await env.manager.shieldedShieldToRecipient( - walletId: env.walletId, - shieldedAccount: 0, - paymentAccount: 0, - recipientRaw43: recipientRaw43, - amount: amountCredits, - addressSigner: signer) + try await performPrepared { + try await env.manager.shieldedShieldToRecipient( + walletId: env.walletId, + shieldedAccount: 0, + paymentAccount: 0, + recipientRaw43: recipientRaw43, + amount: amountCredits, + addressSigner: signer) + } } else { - try await env.manager.shieldedShield( - walletId: env.walletId, - shieldedAccount: 0, - paymentAccount: 0, - amount: amountCredits, - addressSigner: signer) + try await performPrepared { + try await env.manager.shieldedShield( + walletId: env.walletId, + shieldedAccount: 0, + paymentAccount: 0, + amount: amountCredits, + addressSigner: signer) + } } } catch { if case PlatformWalletError.shieldedInsufficientBalance = error { @@ -1003,15 +1046,17 @@ final class ShieldedTransferCoordinator: ObservableObject { phase = .proving do { - try await env.manager.shieldedWithdraw( - walletId: env.walletId, - // Per-operation Orchard spend authority (seedless shielded - // bind, platform #4125/#4126); the SDK holds the resolver - // alive across the FFI call via withExtendedLifetime. - resolver: MnemonicResolver(), - account: 0, - toCoreAddress: coreAddress, - amount: submittedAmount) + try await performPrepared { + try await env.manager.shieldedWithdraw( + walletId: env.walletId, + // Per-operation Orchard spend authority (seedless shielded + // bind, platform #4125/#4126); the SDK holds the resolver + // alive across the FFI call via withExtendedLifetime. + resolver: MnemonicResolver(), + account: 0, + toCoreAddress: coreAddress, + amount: submittedAmount) + } } catch { // shieldedSpendUnconfirmed means the spend may already be on // chain (non-retryable), so its payout can still arrive — tag @@ -1108,13 +1153,15 @@ final class ShieldedTransferCoordinator: ObservableObject { phase = .proving do { - try await env.manager.shieldedUnshield( - walletId: env.walletId, - // Per-operation Orchard spend authority — see above. - resolver: MnemonicResolver(), - account: 0, - toPlatformAddress: platformAddress, - amount: submittedAmount) + try await performPrepared { + try await env.manager.shieldedUnshield( + walletId: env.walletId, + // Per-operation Orchard spend authority — see above. + resolver: MnemonicResolver(), + account: 0, + toPlatformAddress: platformAddress, + amount: submittedAmount) + } } catch { // The transition may already have credited our Platform address. // There is no proof height on this ambiguous path, so never invent @@ -1191,9 +1238,11 @@ final class ShieldedTransferCoordinator: ObservableObject { fundingType: Self.addressAssetLockFundingType) do { - try await PlatformAddressSyncCoordinator.shared.fundFromCore( - recipientAmountDuffs: recipientAmountDuffs, - lockValueDuffs: lockValueDuffs) + try await performPrepared { + try await PlatformAddressSyncCoordinator.shared.fundFromCore( + recipientAmountDuffs: recipientAmountDuffs, + lockValueDuffs: lockValueDuffs) + } } catch { stopAssetLockPolling() captureLatestAssetLockOutPoint( @@ -1201,7 +1250,7 @@ final class ShieldedTransferCoordinator: ObservableObject { modelContainer: env.modelContainer, since: startTime, fundingType: Self.addressAssetLockFundingType) - handleFailure(CoordinatorError.transferFailed(error)) + handlePlatformSpendError(error) return } @@ -1246,12 +1295,14 @@ final class ShieldedTransferCoordinator: ObservableObject { phase = .broadcasting do { - try await PlatformAddressSyncCoordinator.shared.resumeFundFromCore( - outPointTxid: outPointTxidWire, - outPointVout: outPointVout, - recipientAmountDuffs: recipientAmountDuffs) + try await performPrepared { + try await PlatformAddressSyncCoordinator.shared.resumeFundFromCore( + outPointTxid: outPointTxidWire, + outPointVout: outPointVout, + recipientAmountDuffs: recipientAmountDuffs) + } } catch { - handleFailure(CoordinatorError.transferFailed(error)) + handlePlatformSpendError(error) return } @@ -1307,15 +1358,19 @@ final class ShieldedTransferCoordinator: ObservableObject { do { if fullBalance { - try await PlatformAddressSyncCoordinator.shared.withdrawAllToCore(address: coreAddress) + try await performPrepared { + try await PlatformAddressSyncCoordinator.shared.withdrawAllToCore(address: coreAddress) + } } else { - try await PlatformAddressSyncCoordinator.shared.withdrawToCore( - amountCredits: amountCredits, - address: coreAddress, - feeHeadroomCredits: feeHeadroomCredits) + try await performPrepared { + try await PlatformAddressSyncCoordinator.shared.withdrawToCore( + amountCredits: amountCredits, + address: coreAddress, + feeHeadroomCredits: feeHeadroomCredits) + } } } catch { - handleFailure(CoordinatorError.transferFailed(error)) + handlePlatformSpendError(error) return } @@ -1376,13 +1431,15 @@ final class ShieldedTransferCoordinator: ObservableObject { phase = .proving do { - try await env.manager.shieldedTransfer( - walletId: env.walletId, - // Per-operation Orchard spend authority — see `performWithdraw`. - resolver: MnemonicResolver(), - account: 0, - recipientRaw43: recipientRaw43, - amount: submittedAmount) + try await performPrepared { + try await env.manager.shieldedTransfer( + walletId: env.walletId, + // Per-operation Orchard spend authority — see `performWithdraw`. + resolver: MnemonicResolver(), + account: 0, + recipientRaw43: recipientRaw43, + amount: submittedAmount) + } } catch { handleSpendError(error, manager: env.manager) return @@ -1412,11 +1469,13 @@ final class ShieldedTransferCoordinator: ObservableObject { phase = .broadcasting do { - try await PlatformSendExecutor.shared.transfer( - destination: destination, - amount: amountCredits) + try await performPrepared { + try await PlatformSendExecutor.shared.transfer( + destination: destination, + amount: amountCredits) + } } catch { - handleFailure(CoordinatorError.transferFailed(error)) + handlePlatformSpendError(error) return } @@ -1425,6 +1484,40 @@ final class ShieldedTransferCoordinator: ObservableObject { schedulePlatformResync() } + /// Explicit retry of the same committed lock and recipient. Refresh the + /// operation version only within the original wallet/runtime, then use the + /// normal authorization and post-authorization validation in resumeAssetLock. + func retryLastAssetLock(recipientRaw43: Data? = nil) async { + guard case .failed = phase, let outpoint = lastAssetLockOutPoint else { return } + do { + guard let original = try confirmationPreparation?.get() ?? operationPreparation else { + throw WalletOperationPreparationError.expired("Review and confirm the operation again") + } + let current = try SwiftDashSDKHost.shared.preparePlatformRecoveryOperation(matching: original) + reset() + confirmationPreparation = .success(current) + // Keep the committed lock through another refusal or cancelled PIN. + // A later retry must never fall back to building a replacement. + lastAssetLockOutPoint = outpoint + await resumeAssetLock( + outPointTxidWire: outpoint.txidWire, + outPointVout: outpoint.vout, + recipientRaw43: recipientRaw43, + retryUnverifiedConsumption: true) + } catch { + handleFailure(error) + } + } + + /// A rejected local snapshot needs a fresh quote and user confirmation. + var requiresFreshConfirmation: Bool { + guard let lastFailure else { return false } + if case CoordinatorError.transferFailed(let cause) = lastFailure { + return cause is WalletOperationPreparationError + } + return lastFailure is WalletOperationPreparationError + } + /// Reset to `.idle` so the user can retry from a `.failed` state. /// Keeps no in-flight observers — the FFI calls themselves are /// uncancellable, so this just resets UI state. @@ -1433,6 +1526,7 @@ final class ShieldedTransferCoordinator: ObservableObject { lastAssetLockOutPoint = nil lastFailure = nil lastResumeReport = nil + operationPreparation = nil phase = .idle } @@ -1507,6 +1601,15 @@ final class ShieldedTransferCoordinator: ObservableObject { Self.logger.info("🛡️ SHIELD-TX :: begin refused phase=\(String(describing: self.phase), privacy: .public)") return false } + do { + let preparation = try confirmationPreparation?.get() + ?? SwiftDashSDKHost.shared.preparePlatformOperation() + try SwiftDashSDKHost.shared.validatePlatformOperation(preparation) + operationPreparation = preparation + } catch { + handleFailure(error) + return false + } lastFailure = nil lastResumeReport = nil phase = .signing @@ -1524,6 +1627,18 @@ final class ShieldedTransferCoordinator: ObservableObject { } catch { throw CoordinatorError.authFailed } + if let operationPreparation { + try SwiftDashSDKHost.shared.validatePlatformOperation(operationPreparation) + } + } + + /// Recheck the user's wallet/runtime and operation version before submission. + private func performPrepared(_ operation: () async throws -> T) async throws -> T { + guard let operationPreparation else { + throw WalletOperationPreparationError.expired("Review and confirm the operation again") + } + return try await SwiftDashSDKHost.shared.withPlatformOperation( + preparation: operationPreparation, operation: operation) } private func handleFailure(_ error: Error) { @@ -1550,6 +1665,21 @@ final class ShieldedTransferCoordinator: ObservableObject { phase = .submittedUnconfirmed scheduleShieldedResync(manager: manager) } else { + handlePlatformSpendError(error) + } + } + + /// An ambiguous broadcast cannot prove the dispatch did not execute. + /// Keep the submitted state so this sheet never offers a fresh payment. + private func handlePlatformSpendError(_ error: Error) { + switch error { + case PlatformWalletError.transactionBroadcastUnconfirmed: + phase = .submittedUnconfirmed + schedulePlatformResync() + if let manager = SwiftDashSDKHost.shared.manager { + scheduleShieldedResync(manager: manager) + } + default: handleFailure(CoordinatorError.transferFailed(error)) } } diff --git a/DashWallet/Sources/UI/Payments/Pay/SendScreen.swift b/DashWallet/Sources/UI/Payments/Pay/SendScreen.swift index f65d50bb46..d258d7e48b 100644 --- a/DashWallet/Sources/UI/Payments/Pay/SendScreen.swift +++ b/DashWallet/Sources/UI/Payments/Pay/SendScreen.swift @@ -390,6 +390,20 @@ struct SendSourceScreen: View { /// directly: same screen, same view model, with the recipient rendered as a /// contact and the button executing the send itself (there is no confirmation /// after it — `sendToContact` broadcasts in one shot). +private struct PlatformSendConfirmation: Identifiable { + let id = UUID() + let route: SendViewModel.Route + let destinationAddress: String + let destinationRaw43: Data? + let dashDuffs: Int64 + let creditsAmount: UInt64 + let fiatText: String + let withdrawalFeeCredits: UInt64? + let isFullPlatformWithdrawal: Bool + let isFullShieldedSweep: Bool + let preparation: Result +} + struct ExternalSendAmountScreen: View { @ObservedObject var viewModel: SendViewModel /// Pop back to the step that chose the recipient — the source step for an @@ -404,7 +418,7 @@ struct ExternalSendAmountScreen: View { /// A non-core route finished successfully (confirm sheet's Done). var onSendCompleted: () -> Void - @State private var showConfirm = false + @State private var confirmation: PlatformSendConfirmation? /// Set by the confirm sheet's Done so `onDismiss` can tell a finished send /// from a cancelled one — both close the sheet the same way. @State private var didCompleteSend = false @@ -489,30 +503,29 @@ struct ExternalSendAmountScreen: View { } } #endif - .sheet(isPresented: $showConfirm, onDismiss: { + .sheet(item: $confirmation, onDismiss: { guard didCompleteSend else { return } didCompleteSend = false onSendCompleted() - }) { - if let route = viewModel.route, route != .coreToCore { - SendConfirmSheet( - route: route, - destinationAddress: viewModel.trimmedAddress, - destinationRaw43: shieldedRecipientRaw43, - dashDuffs: viewModel.dashDuffs, - creditsAmount: viewModel.creditsPreview, - fiatText: viewModel.fiatAmountString, - withdrawalFeeCredits: viewModel.withdrawalPreflight?.estimatedFee, - isFullPlatformWithdrawal: viewModel.isFullPlatformWithdrawal, - isFullShieldedSweep: viewModel.isFullShieldedSweep, - onCancel: { showConfirm = false }, - onCompleted: { - didCompleteSend = true - showConfirm = false - }) - .presentationDetents([.large]) - .presentationDragIndicator(.hidden) - } + }) { submission in + SendConfirmSheet( + route: submission.route, + destinationAddress: submission.destinationAddress, + destinationRaw43: submission.destinationRaw43, + dashDuffs: submission.dashDuffs, + creditsAmount: submission.creditsAmount, + fiatText: submission.fiatText, + withdrawalFeeCredits: submission.withdrawalFeeCredits, + isFullPlatformWithdrawal: submission.isFullPlatformWithdrawal, + isFullShieldedSweep: submission.isFullShieldedSweep, + preparation: submission.preparation, + onCancel: { confirmation = nil }, + onCompleted: { + didCompleteSend = true + confirmation = nil + }) + .presentationDetents([.large]) + .presentationDragIndicator(.hidden) } } @@ -570,7 +583,17 @@ struct ExternalSendAmountScreen: View { if route == .coreToCore { onContinueCore(viewModel.trimmedAddress, viewModel.dashDuffsUnsigned) } else { - showConfirm = true + confirmation = PlatformSendConfirmation( + route: route, + destinationAddress: viewModel.trimmedAddress, + destinationRaw43: shieldedRecipientRaw43, + dashDuffs: viewModel.dashDuffs, + creditsAmount: viewModel.creditsPreview, + fiatText: viewModel.fiatAmountString, + withdrawalFeeCredits: viewModel.withdrawalPreflight?.estimatedFee, + isFullPlatformWithdrawal: viewModel.isFullPlatformWithdrawal, + isFullShieldedSweep: viewModel.isFullShieldedSweep, + preparation: Result { try viewModel.platformPreparationForConfirmation() }) } } @@ -1088,7 +1111,35 @@ struct SendConfirmSheet: View { var onCancel: () -> Void var onCompleted: () -> Void - @StateObject private var coordinator = ShieldedTransferCoordinator() + @StateObject private var coordinator: ShieldedTransferCoordinator + + init( + route: SendViewModel.Route, + destinationAddress: String, + destinationRaw43: Data?, + dashDuffs: Int64, + creditsAmount: UInt64, + fiatText: String, + withdrawalFeeCredits: UInt64?, + isFullPlatformWithdrawal: Bool, + isFullShieldedSweep: Bool, + preparation: Result, + onCancel: @escaping () -> Void, + onCompleted: @escaping () -> Void + ) { + self.route = route + self.destinationAddress = destinationAddress + self.destinationRaw43 = destinationRaw43 + self.dashDuffs = dashDuffs + self.creditsAmount = creditsAmount + self.fiatText = fiatText + self.withdrawalFeeCredits = withdrawalFeeCredits + self.isFullPlatformWithdrawal = isFullPlatformWithdrawal + self.isFullShieldedSweep = isFullShieldedSweep + self.onCancel = onCancel + self.onCompleted = onCompleted + _coordinator = StateObject(wrappedValue: ShieldedTransferCoordinator(confirmationPreparation: preparation)) + } var body: some View { DashUIKit.BottomSheet( @@ -1503,17 +1554,17 @@ struct SendConfirmSheet: View { // instead of building a second lock (which strands the first) — // mirrors the internal transfer's retry. if route == .coreToShielded, - let op = coordinator.lastAssetLockOutPoint, + coordinator.lastAssetLockOutPoint != nil, let destinationRaw43 { - coordinator.reset() Task { - await coordinator.resumeAssetLock( - outPointTxidWire: op.txidWire, - outPointVout: op.vout, - recipientRaw43: destinationRaw43) + await coordinator.retryLastAssetLock(recipientRaw43: destinationRaw43) } return } + if coordinator.requiresFreshConfirmation { + onCancel() + return + } coordinator.reset() confirm() } diff --git a/DashWallet/Sources/UI/Payments/Pay/SendViewModel.swift b/DashWallet/Sources/UI/Payments/Pay/SendViewModel.swift index 081be11c30..4050be6bdb 100644 --- a/DashWallet/Sources/UI/Payments/Pay/SendViewModel.swift +++ b/DashWallet/Sources/UI/Payments/Pay/SendViewModel.swift @@ -187,8 +187,27 @@ final class SendViewModel: ObservableObject { /// the sync monitor singleton. @Published private(set) var isChainSynced = false + /// Captured before any amount/fee calculation and kept with its cached quotes. + private var platformPreparation: SwiftDashSDKHost.PlatformPreparation? + + func platformPreparationForConfirmation() throws -> SwiftDashSDKHost.PlatformPreparation { + guard let platformPreparation else { + throw WalletOperationPreparationError.expired("Review the amount and confirm again") + } + try SwiftDashSDKHost.shared.validatePlatformOperation(platformPreparation) + return platformPreparation + } + + private var hasCurrentPlatformPreparation: Bool { + #if DEBUG + if isPreviewInstance { return true } + #endif + guard let route, route != .coreToCore else { return true } + return (try? platformPreparationForConfirmation()) != nil + } private var cancellables = Set() + #if DEBUG /// True only for `makeForPreview` instances — see the guard in `deinit`. private var isPreviewInstance = false @@ -213,6 +232,7 @@ final class SendViewModel: ObservableObject { init(pinnedSource: ChainNetwork? = nil) { self.pinnedSource = pinnedSource + if let pinnedSource { source = pinnedSource } @@ -264,6 +284,7 @@ final class SendViewModel: ObservableObject { self?.refreshShieldedSpendCeiling() } .store(in: &cancellables) + routeDidChange() } #if DEBUG @@ -337,11 +358,13 @@ final class SendViewModel: ObservableObject { /// Recomputes `shieldedSpendCeilingCredits` from the current note set. /// Cached rather than computed per keystroke — it reads SwiftData. private func refreshShieldedSpendCeiling() { - guard let feeKind = shieldedFeeKind(for: route) else { + guard hasCurrentPlatformPreparation, + let feeKind = shieldedFeeKind(for: route) else { shieldedSpendCeilingCredits = nil return } - shieldedSpendCeilingCredits = ShieldedTransferCoordinator.spendCeilingCredits(feeKind: feeKind) + let ceiling = ShieldedTransferCoordinator.spendCeilingCredits(feeKind: feeKind) + shieldedSpendCeilingCredits = hasCurrentPlatformPreparation ? ceiling : nil } // MARK: - Destination classification @@ -600,7 +623,22 @@ final class SendViewModel: ObservableObject { /// needs the withdrawal preflight (fee headroom + full-balance payout), /// Platform → Shielded the shield-capacity preflight. private func routeDidChange() { + preflightTask?.cancel() + preflightTask = nil + withdrawalPreflight = nil + withdrawalPreflightFailed = false + shieldPreflightTask?.cancel() + shieldPreflightTask = nil + platformShieldCapacity = nil + shieldPreflightFailed = false + shieldedSpendCeilingCredits = nil + platformPreparation = nil clearShieldedMaxSelection() + if let route, route != .coreToCore { + guard let preparation = try? SwiftDashSDKHost.shared.preparePlatformOperation() + else { return } + platformPreparation = preparation + } refreshShieldedSpendCeiling() refreshWithdrawalPreflight() refreshShieldPreflight() @@ -612,11 +650,18 @@ final class SendViewModel: ObservableObject { preflightTask = nil return } - guard preflightTask == nil else { return } + guard preflightTask == nil, + let preparation = try? platformPreparationForConfirmation() else { return } + withdrawalPreflight = nil withdrawalPreflightFailed = false preflightTask = Task { [weak self] in let result = try? await PlatformAddressSyncCoordinator.shared.preflightWithdrawal() guard let self, !Task.isCancelled else { return } + guard (try? SwiftDashSDKHost.shared.validatePlatformOperation(preparation)) != nil else { + self.withdrawalPreflight = nil + self.preflightTask = nil + return + } self.withdrawalPreflight = result self.withdrawalPreflightFailed = result == nil self.preflightTask = nil @@ -629,7 +674,8 @@ final class SendViewModel: ObservableObject { shieldPreflightTask = nil return } - guard shieldPreflightTask == nil else { return } + guard shieldPreflightTask == nil, + let preparation = try? platformPreparationForConfirmation() else { return } // Fail closed while resolving: a preflight only starts when the // cached capacity is suspect (route entry, balance change, Max // retry), so clear it rather than let `canContinue` accept a stale @@ -639,6 +685,11 @@ final class SendViewModel: ObservableObject { shieldPreflightTask = Task { [weak self] in let result = try? await PlatformAddressSyncCoordinator.shared.preflightShield() guard let self, !Task.isCancelled else { return } + guard (try? SwiftDashSDKHost.shared.validatePlatformOperation(preparation)) != nil else { + self.platformShieldCapacity = nil + self.shieldPreflightTask = nil + return + } self.platformShieldCapacity = result.map(PlatformShieldCapacity.init) self.shieldPreflightFailed = result == nil self.shieldPreflightTask = nil @@ -1179,6 +1230,7 @@ final class SendViewModel: ObservableObject { } var canContinue: Bool { + guard hasCurrentPlatformPreparation else { return false } #if DASHPAY // Terminal for this contact for the rest of the session: see // `contactSendOutcomeIsUnknown`. @@ -1239,6 +1291,11 @@ final class SendViewModel: ObservableObject { /// Source-aware Max fill — same envelopes as the internal transfer. func fillMaxFromWallet() { + guard hasCurrentPlatformPreparation else { + clearShieldedMaxSelection() + shieldedMaxNotice = Self.feeEstimateUnavailableMessage + return + } if hasUnavailableSourceBalance { clearShieldedMaxSelection() shieldedMaxNotice = NSLocalizedString("Balance unavailable", comment: "Max requires a known source balance") diff --git a/DashWallet/Sources/UI/Tx/Details/Model/TxDetailModel.swift b/DashWallet/Sources/UI/Tx/Details/Model/TxDetailModel.swift index e3f31853b1..c601c621bf 100644 --- a/DashWallet/Sources/UI/Tx/Details/Model/TxDetailModel.swift +++ b/DashWallet/Sources/UI/Tx/Details/Model/TxDetailModel.swift @@ -744,7 +744,7 @@ extension TxDetailModel { } // A restored lock we already probed reads as the weaker claim it earns: // the network says spent, we could not verify that, and there is - // nothing left to try. Bare "Completion unknown" is reserved for locks + // a user can retry that same outpoint. "Completion unknown" is for locks // nobody has asked about yet. if statusRaw == Self.recoveredFromChainStatus, wasProbedAlreadySpent { // "Already spent", not "Completed": the network reported the @@ -759,7 +759,11 @@ extension TxDetailModel { /// Whether this transaction's funding lock has already been probed and /// answered "already spent" (see `AssetLockProbeStore`). private var wasProbedAlreadySpent: Bool { - AssetLockProbeStore.shared.contains(transaction.txHashData) + let info = transaction.identityFundingLockInfo + ?? transaction.platformFundingLockInfo + ?? ShieldedTxLookup.shared.info(forTxidHex: transactionId) + guard let info else { return false } + return AssetLockProbeStore.shared.contains(transaction.txHashData, vout: info.vout) } /// `AssetLockStatus::RecoveredFromChain` as it crosses the FFI. Owned by @@ -855,10 +859,6 @@ extension TxDetailModel { ?? ShieldedTxLookup.shared.info(forTxidHex: transactionId) guard let info, Self.statusAllowsRetry(info.statusRaw), - // Asked once, told "already spent": repeating the probe cannot - // change the answer, so the action retires instead of standing - // on every restored row forever. - !wasProbedAlreadySpent, AssetLockRecoveryService.supportsRetry(fundingTypeRaw: info.fundingTypeRaw) else { return nil } return StuckAssetLockRetry( diff --git a/scripts/fixtures/AssetLockRecoveryHarness.swift b/scripts/fixtures/AssetLockRecoveryHarness.swift new file mode 100644 index 0000000000..f093f714f2 --- /dev/null +++ b/scripts/fixtures/AssetLockRecoveryHarness.swift @@ -0,0 +1,144 @@ +import Foundation +import OSLog + +enum WalletEnvironment { + static var activeWalletIdHex: String? +} +enum PlatformWalletError: Error { + case assetLockAlreadyConsumed + case shieldedSpendUnconfirmed +} +struct ShieldedFundFromAssetLockRecipient { + let recipientRaw43: Data + let credits: UInt64? +} +@MainActor +final class TestManager { + var error: Error? + var calls = 0 + var receivedTxid: Data? + var receivedVout: UInt32? + var receivedRecipients: [ShieldedFundFromAssetLockRecipient] = [] + func shieldedResumeFundFromAssetLock(walletId: Data, outPointTxid: Data, outPointVout: UInt32, + recipients: [ShieldedFundFromAssetLockRecipient]) async throws { + calls += 1 + receivedTxid = outPointTxid + receivedVout = outPointVout + receivedRecipients = recipients + if let error { throw error } + } +} +enum WalletOperationPreparationError: Error { case expired(String), unavailable(String) } +@MainActor final class SwiftDashSDKHost { + struct PlatformPreparation { let walletId: Data } + static let shared = SwiftDashSDKHost() + var recoveryPreparation: ((PlatformPreparation) throws -> PlatformPreparation)? + func preparePlatformRecoveryOperation(matching original: PlatformPreparation) throws -> PlatformPreparation { + guard let recoveryPreparation else { + throw WalletOperationPreparationError.expired("Configure the preparation boundary for this test") + } + return try recoveryPreparation(original) + } +} +// Dependency seam for the drain context check added by develop. Recovery +// tests must explicitly supply an outcome instead of fabricating a manager. +struct CoreShieldedDrainContext { + let walletId: Data + let networkScope: String +} +@MainActor +struct CoreShieldedDrainService { + enum TestError: Error { case contextChanged } + static var resolveManager: ((CoreShieldedDrainContext) throws -> TestManager)? + func manager(for context: CoreShieldedDrainContext) throws -> TestManager { + guard let resolveManager = Self.resolveManager else { throw TestError.contextChanged } + return try resolveManager(context) + } +} +@MainActor +final class ShieldedTxLookup { + static let shared = ShieldedTxLookup() + func refresh(reason: String) async {} +} +extension Notification.Name { + static let swiftDashSDKTransactionProjectionDidChange = Notification.Name("projection") +} +@MainActor +final class ShieldedTransferCoordinator { + enum CoordinatorError: Error { + case transferFailed(Error), authCancelled + var errorDescription: String? { "Authentication cancelled" } + } + enum Phase: Equatable { case idle, proving, broadcasting, success, submittedUnconfirmed, failed(String) } + enum ResumeReport { case alreadyConsumed } + struct Environment { + let manager: TestManager + let walletId: Data + let shieldedRecipient: Data + } + static let logger = Logger(subsystem: "RecoveryHarness", category: "test") + var phase: Phase = .idle + var lastResumeReport: ResumeReport? + var lastFailure: Error? + var confirmationPreparation: Result? + var operationPreparation: SwiftDashSDKHost.PlatformPreparation? + var lastAssetLockOutPoint: (txidWire: Data, vout: UInt32)? + let environment: Environment + var authorizations = 0 + var onAuthorize: (() -> Void)? + var authorizationError: Error? + init(environment: Environment) { self.environment = environment } + func beginTransfer() -> Bool { phase == .idle } + func resolveEnvironment() throws -> Environment { environment } + func authorize() async throws { + authorizations += 1 + onAuthorize?() + if let authorizationError { throw authorizationError } + } + func stopAssetLockPolling() {} + func performPrepared(_ body: () async throws -> Void) async throws { try await body() } + func handleFailure(_ error: Error) { + phase = .failed(error is CancellationError ? CoordinatorError.authCancelled.errorDescription! : "test failure") + } + enum Funding { case coinJoinDrain } + var newAssetLockCalls = 0 + func performAssetLock(funding: Funding) async { newAssetLockCalls += 1 } + func handleSpendError(_ error: Error, manager: TestManager) { phase = .submittedUnconfirmed } + func scheduleShieldedResync(manager: TestManager) {} + // PRODUCTION_METHODS +} + +// Actual caller retry methods are inserted by the runner. Presentation and +// fresh-send boundaries only record calls; native work uses the coordinator above. +@MainActor final class SwiftDashSDKWalletState { + static let shared = SwiftDashSDKWalletState() + func refreshCoinJoinBalance() {} +} +@MainActor final class CoinJoinRetryHarness { + enum Destination { case shielded } + enum Stage: Equatable { + case choice, shielding, success(Destination), submittedUnconfirmed + case failed(message: String, destination: Destination) + } + var stage: Stage = .choice + var isInFlight = false + let coordinator: ShieldedTransferCoordinator + var newDrainCalls: Int { coordinator.newAssetLockCalls } + init(_ coordinator: ShieldedTransferCoordinator) { self.coordinator = coordinator } + // COINJOIN_MOVE + // COINJOIN_FINISH + // COINJOIN_RETRY +} + +@MainActor final class SendRetryHarness { + enum Route { case coreToShielded, platformToShielded } + var route: Route = .platformToShielded + var destinationRaw43: Data? + let coordinator: ShieldedTransferCoordinator + var cancellations = 0 + var confirmations = 0 + init(_ coordinator: ShieldedTransferCoordinator) { self.coordinator = coordinator } + func onCancel() { cancellations += 1 } + func confirm() { confirmations += 1 } + // SEND_RETRY +} diff --git a/scripts/fixtures/AssetLockRecoveryTests.swift b/scripts/fixtures/AssetLockRecoveryTests.swift new file mode 100644 index 0000000000..1d7e610451 --- /dev/null +++ b/scripts/fixtures/AssetLockRecoveryTests.swift @@ -0,0 +1,244 @@ +import Foundation +import XCTest +@testable import RecoveryHarness + +@MainActor +final class AssetLockRecoveryTests: XCTestCase { + func testExplicitSendRetryAuthorizesRecordedProbeAndPreservesUnverifiedOutcome() async { + await checkExplicitSendRetryWithRecordedProbe(cancelAuthorization: false) + } + + func testExplicitSendRetryWithRecordedProbeCannotSubmitWithoutAuthorization() async { + await checkExplicitSendRetryWithRecordedProbe(cancelAuthorization: true) + } + + func testExplicitCoinJoinRetryRechecksRecordedProbeWithoutAnotherDrain() async { + await checkExplicitSendRetryWithRecordedProbe(cancelAuthorization: false, coinJoin: true) + } + + func testExplicitCoinJoinRetryCannotSubmitWithoutAuthorization() async { + await checkExplicitSendRetryWithRecordedProbe(cancelAuthorization: true, coinJoin: true) + } + + func testCoinJoinChoiceAfterCancelledRecoveryKeepsSameLock() async { + await checkExplicitSendRetryWithRecordedProbe(cancelAuthorization: true, coinJoin: true, fromChoice: true) + } + + private func checkExplicitSendRetryWithRecordedProbe(cancelAuthorization: Bool, coinJoin: Bool = false, + fromChoice: Bool = false) async { + let wallet = Data(repeating: 0x33, count: 32) + let walletHex = wallet.map { String(format: "%02x", $0) }.joined() + let txid = Data(repeating: 0x7a, count: 32) + let recipient = Data(repeating: 5, count: 43) + defer { + AssetLockProbeStore.shared.clearForWallet(walletIdHex: walletHex) + SwiftDashSDKHost.shared.recoveryPreparation = nil + } + AssetLockProbeStore.shared.record(txid: txid, vout: 3, walletIdHex: walletHex) + SwiftDashSDKHost.shared.recoveryPreparation = { original in + XCTAssertEqual(original.walletId, wallet) + return original + } + let manager = TestManager() + manager.error = PlatformWalletError.assetLockAlreadyConsumed + let coordinator = ShieldedTransferCoordinator(environment: .init( + manager: manager, walletId: wallet, shieldedRecipient: Data(repeating: 1, count: 43))) + coordinator.phase = .failed("test failure") + if coinJoin { + coordinator.operationPreparation = .init(walletId: wallet) + } else { + coordinator.confirmationPreparation = .success(.init(walletId: wallet)) + } + coordinator.lastAssetLockOutPoint = (txid, 3) + if cancelAuthorization { coordinator.authorizationError = CancellationError() } + + if coinJoin { + let caller = CoinJoinRetryHarness(coordinator) + await caller.retryShielded() + XCTAssertEqual(caller.stage, cancelAuthorization ? .choice : .submittedUnconfirmed) + if fromChoice { + coordinator.authorizationError = nil + await caller.moveToShielded() + XCTAssertEqual(caller.stage, .submittedUnconfirmed) + } + XCTAssertEqual(caller.newDrainCalls, 0) + } else { + await coordinator.retryLastAssetLock(recipientRaw43: recipient) + } + + XCTAssertEqual(coordinator.authorizations, fromChoice ? 2 : 1) + XCTAssertEqual(coordinator.lastAssetLockOutPoint?.txidWire, txid) + XCTAssertEqual(coordinator.lastAssetLockOutPoint?.vout, 3) + XCTAssertTrue(AssetLockProbeStore.shared.contains(txid, vout: 3, walletIdHex: walletHex)) + if cancelAuthorization && !fromChoice { + XCTAssertEqual(manager.calls, 0) + XCTAssertEqual(coordinator.phase, .failed("Authentication cancelled")) + } else { + XCTAssertEqual(manager.calls, 1) + XCTAssertEqual(manager.receivedTxid, txid) + XCTAssertEqual(manager.receivedVout, 3) + XCTAssertEqual(manager.receivedRecipients.map(\.recipientRaw43), + [coinJoin ? Data(repeating: 1, count: 43) : recipient]) + XCTAssertEqual(coordinator.phase, .submittedUnconfirmed) + } + } + + func testStaleSendRetryReturnsToFormWithoutResubmittingOldConfirmation() { + let manager = TestManager() + let errors: [Error] = [ + WalletOperationPreparationError.expired("operation version changed"), + ShieldedTransferCoordinator.CoordinatorError.transferFailed( + WalletOperationPreparationError.expired("runtime changed")), + ] + for error in errors { + for route in [SendRetryHarness.Route.coreToShielded, .platformToShielded] { + let coordinator = ShieldedTransferCoordinator(environment: .init( + manager: manager, walletId: Data([1]), shieldedRecipient: Data(repeating: 1, count: 43))) + coordinator.phase = .failed("test failure") + coordinator.lastFailure = error + let caller = SendRetryHarness(coordinator) + caller.route = route + caller.tryAgain() + XCTAssertEqual(caller.cancellations, 1) + XCTAssertEqual(caller.confirmations, 0) + XCTAssertEqual(coordinator.phase, .failed("test failure")) + } + } + XCTAssertEqual(manager.calls, 0) + } + + func testOtherSendFailureRetainsOrdinaryRetry() { + let manager = TestManager() + let coordinator = ShieldedTransferCoordinator(environment: .init( + manager: manager, walletId: Data([1]), shieldedRecipient: Data(repeating: 1, count: 43))) + coordinator.phase = .failed("test failure") + coordinator.lastFailure = NSError(domain: "test", code: 1) + let caller = SendRetryHarness(coordinator) + caller.tryAgain() + XCTAssertEqual(caller.cancellations, 0) + XCTAssertEqual(caller.confirmations, 1) + XCTAssertEqual(coordinator.phase, .idle) + } + + func testDirectRecoverySheetRecordsSpentProbeUnderOriginatingWallet() async { + let wallet = Data(repeating: 0x29, count: 32) + let walletHex = wallet.map { String(format: "%02x", $0) }.joined() + let txid = Data(repeating: 0x76, count: 32) + defer { + AssetLockProbeStore.shared.clearForWallet(walletIdHex: walletHex) + WalletEnvironment.activeWalletIdHex = nil + } + AssetLockProbeStore.shared.clearForWallet(walletIdHex: walletHex) + WalletEnvironment.activeWalletIdHex = walletHex + let manager = TestManager() + manager.error = PlatformWalletError.assetLockAlreadyConsumed + let environment = ShieldedTransferCoordinator.Environment(manager: manager, walletId: wallet, + shieldedRecipient: Data(repeating: 1, count: 43)) + let coordinator = ShieldedTransferCoordinator(environment: environment) + coordinator.onAuthorize = { WalletEnvironment.activeWalletIdHex = "another-wallet" } + await coordinator.resumeAssetLock(outPointTxidWire: txid, outPointVout: 0) + XCTAssertEqual(coordinator.phase, .submittedUnconfirmed) + XCTAssertEqual(manager.receivedTxid, txid) + XCTAssertTrue(AssetLockProbeStore.shared.contains(txid, vout: 0, walletIdHex: walletHex)) + XCTAssertFalse(AssetLockProbeStore.shared.contains(txid, vout: 0)) + + // A new presenter (or relaunch) must not authorize or submit again. + let reopened = ShieldedTransferCoordinator(environment: environment) + await reopened.resumeAssetLock(outPointTxidWire: txid, outPointVout: 0) + XCTAssertEqual(reopened.phase, .submittedUnconfirmed) + XCTAssertEqual(reopened.authorizations, 0) + XCTAssertEqual(manager.calls, 1) + let reloaded = AssetLockProbeStore() + XCTAssertTrue(reloaded.contains(txid, vout: 0, walletIdHex: walletHex)) + } + + func testExplicitRetryRechecksSameOutpointAfterUnverifiedConsumptionReport() async { + let wallet = Data(repeating: 0x32, count: 32) + let walletHex = wallet.map { String(format: "%02x", $0) }.joined() + let txid = Data(repeating: 0x79, count: 32) + defer { AssetLockProbeStore.shared.clearForWallet(walletIdHex: walletHex) } + AssetLockProbeStore.shared.record(txid: txid, vout: 2, walletIdHex: walletHex) + let manager = TestManager() + let coordinator = ShieldedTransferCoordinator(environment: .init( + manager: manager, walletId: wallet, shieldedRecipient: Data(repeating: 1, count: 43))) + await coordinator.resumeAssetLock(outPointTxidWire: txid, outPointVout: 2, + retryUnverifiedConsumption: true) + XCTAssertEqual(coordinator.authorizations, 1) + XCTAssertEqual(manager.calls, 1) + XCTAssertEqual(manager.receivedTxid, txid) + XCTAssertEqual(coordinator.phase, .success) + } + + func testLegacyTxidProbeCannotSuppressEveryCreditOutput() { + let suite = "RecoveryHarness-\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let txid = Data(repeating: 3, count: 32) + defaults.set([txid], forKey: "assetLockProbe.v1.alreadySpentTxids_A") + let store = AssetLockProbeStore(defaults: defaults) + XCTAssertFalse(store.contains(txid, vout: 0, walletIdHex: "A")) + XCTAssertFalse(store.contains(txid, vout: 1, walletIdHex: "A")) + store.record(txid: txid, vout: 1, walletIdHex: "A") + let reloaded = AssetLockProbeStore(defaults: defaults) + XCTAssertTrue(reloaded.contains(txid, vout: 1, walletIdHex: "A")) + XCTAssertFalse(reloaded.contains(txid, vout: 0, walletIdHex: "A")) + store.resetForWipe() + XCTAssertNil(defaults.object(forKey: "assetLockProbe.v1.alreadySpentTxids_A")) + XCTAssertFalse(AssetLockProbeStore(defaults: defaults).contains(txid, vout: 1, walletIdHex: "A")) + } + + func testTimeoutDoesNotInventAnAlreadySpentProbe() async { + let wallet = Data(repeating: 0x30, count: 32) + let walletHex = wallet.map { String(format: "%02x", $0) }.joined() + defer { AssetLockProbeStore.shared.clearForWallet(walletIdHex: walletHex) } + AssetLockProbeStore.shared.clearForWallet(walletIdHex: walletHex) + let txid = Data(repeating: 0x77, count: 32) + let manager = TestManager() + manager.error = PlatformWalletError.shieldedSpendUnconfirmed + let coordinator = ShieldedTransferCoordinator(environment: .init(manager: manager, walletId: wallet, + shieldedRecipient: Data(repeating: 1, count: 43))) + await coordinator.resumeAssetLock(outPointTxidWire: txid, outPointVout: 0) + XCTAssertFalse(AssetLockProbeStore.shared.contains(txid, vout: 0, walletIdHex: walletHex)) + XCTAssertNil(coordinator.lastResumeReport) + XCTAssertEqual(coordinator.phase, .submittedUnconfirmed) + } + + func testDrainContextChangeAfterAuthorizationNeverResubmitsAssetLock() async { + let wallet = Data(repeating: 0x31, count: 32) + let txid = Data(repeating: 0x78, count: 32) + let manager = TestManager() + let coordinator = ShieldedTransferCoordinator(environment: .init( + manager: manager, walletId: wallet, shieldedRecipient: Data(repeating: 1, count: 43))) + CoreShieldedDrainService.resolveManager = { _ in manager } + defer { CoreShieldedDrainService.resolveManager = nil } + coordinator.onAuthorize = { + CoreShieldedDrainService.resolveManager = { _ in + throw CoreShieldedDrainService.TestError.contextChanged + } + } + await coordinator.resumeAssetLock( + outPointTxidWire: txid, outPointVout: 0, + expectedDrainContext: .init(walletId: wallet, networkScope: "testnet")) + XCTAssertEqual(coordinator.authorizations, 1) + XCTAssertEqual(coordinator.phase, .failed("test failure")) + XCTAssertEqual(manager.calls, 0) + XCTAssertNil(manager.receivedTxid) + } + + func testProbePersistenceIsWalletScopedAndNeverMarksAnotherOutpoint() { + let suite = "RecoveryHarness-\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: suite)! + defer { defaults.removePersistentDomain(forName: suite) } + let store = AssetLockProbeStore(defaults: defaults) + let txid = Data(repeating: 1, count: 32) + store.record(txid: txid, vout: 0, walletIdHex: "A") + let reloaded = AssetLockProbeStore(defaults: defaults) + XCTAssertTrue(reloaded.contains(txid, vout: 0, walletIdHex: "A")) + XCTAssertFalse(reloaded.contains(txid, vout: 0, walletIdHex: "B")) + XCTAssertFalse(reloaded.contains(Data(repeating: 2, count: 32), vout: 0, walletIdHex: "A")) + reloaded.clearForWallet(walletIdHex: "B") + XCTAssertTrue(reloaded.contains(txid, vout: 0, walletIdHex: "A")) + reloaded.clearForWallet(walletIdHex: "A") + XCTAssertFalse(AssetLockProbeStore(defaults: defaults).contains(txid, vout: 0, walletIdHex: "A")) + } +} diff --git a/scripts/fixtures/CoreToShieldedFeeCompatibilityHarness.swift b/scripts/fixtures/CoreToShieldedFeeCompatibilityHarness.swift new file mode 100644 index 0000000000..5d68567b84 --- /dev/null +++ b/scripts/fixtures/CoreToShieldedFeeCompatibilityHarness.swift @@ -0,0 +1,43 @@ +import Foundation + +/// Only the host/FFI boundary is replaced. The fee-cache implementation is +/// extracted unchanged from InternalTransferViewModel.swift by the test runner. +@MainActor +final class SwiftDashSDKHost { + static let shared = SwiftDashSDKHost() + struct PlatformPreparation: Equatable { + let runtime: UUID + let version: UInt32 + } + enum Refusal: Error { case changed, estimateFailed } + final class Manager { + enum Kind { case transfer } + var fee: UInt64 = 100 + var calls = 0 + var onEstimate: (() throws -> Void)? + + func estimateShieldedFee(kind: Kind, numActions: Int) throws -> UInt64 { + calls += 1 + try onEstimate?() + return fee + } + } + + var manager: Manager? = Manager() + var runtime = UUID() + var version: UInt32 = 13 + + func preparePlatformOperation() throws -> PlatformPreparation { + return PlatformPreparation(runtime: runtime, version: version) + } + + func validatePlatformOperation(_ preparation: PlatformPreparation) throws { + guard try preparation == preparePlatformOperation() else { throw Refusal.changed } + } + + func reset() { + runtime = UUID() + version = 13 + manager = Manager() + } +} diff --git a/scripts/fixtures/CoreToShieldedFeeCompatibilityTests.swift b/scripts/fixtures/CoreToShieldedFeeCompatibilityTests.swift new file mode 100644 index 0000000000..bdab2af1e7 --- /dev/null +++ b/scripts/fixtures/CoreToShieldedFeeCompatibilityTests.swift @@ -0,0 +1,51 @@ +import XCTest +@testable import CoreToShieldedFeeHarness + +final class CoreToShieldedFeeCompatibilityTests: XCTestCase { + @MainActor + func testRealVersionChangeRequotes() async { + let host = SwiftDashSDKHost.shared + host.reset() + XCTAssertEqual(CoreToShieldedAmountPolicy.poolFeeCredits, 50_000_100) + XCTAssertEqual(CoreToShieldedAmountPolicy.poolFeeCredits, 50_000_100) + XCTAssertEqual(host.manager?.calls, 1) + + host.version = 14 + host.manager?.fee = 200 + XCTAssertEqual(CoreToShieldedAmountPolicy.poolFeeCredits, 50_000_200) + XCTAssertEqual(host.manager?.calls, 2) + } + + @MainActor + func testRecreatedRuntimeCannotReuseQuote() async { + let host = SwiftDashSDKHost.shared + host.reset() + XCTAssertEqual(CoreToShieldedAmountPolicy.poolFeeCredits, 50_000_100) + host.reset() + host.manager?.fee = 300 + XCTAssertEqual(CoreToShieldedAmountPolicy.poolFeeCredits, 50_000_300) + XCTAssertEqual(host.manager?.calls, 1) + } + + @MainActor + func testQuoteChangedDuringNativeEstimateIsDiscarded() async { + let host = SwiftDashSDKHost.shared + host.reset() + host.manager?.onEstimate = { host.version += 1 } + XCTAssertNil(CoreToShieldedAmountPolicy.poolFeeCredits) + host.manager?.onEstimate = nil + XCTAssertEqual(CoreToShieldedAmountPolicy.poolFeeCredits, 50_000_100) + XCTAssertEqual(host.manager?.calls, 2) + } + + @MainActor + func testFailedEstimateDoesNotPoisonRetry() async { + let host = SwiftDashSDKHost.shared + host.reset() + host.manager?.onEstimate = { throw SwiftDashSDKHost.Refusal.estimateFailed } + XCTAssertNil(CoreToShieldedAmountPolicy.poolFeeCredits) + host.manager?.onEstimate = nil + XCTAssertEqual(CoreToShieldedAmountPolicy.poolFeeCredits, 50_000_100) + XCTAssertEqual(host.manager?.calls, 2) + } +} diff --git a/scripts/fixtures/IdentityTopUpCompatibilityHarness.swift b/scripts/fixtures/IdentityTopUpCompatibilityHarness.swift new file mode 100644 index 0000000000..832f4c397f --- /dev/null +++ b/scripts/fixtures/IdentityTopUpCompatibilityHarness.swift @@ -0,0 +1,114 @@ +import Foundation + +enum SDKError: Error { case networkError(String) } +enum WalletOperationPreparationError: Error { case expired(String) } +enum PlatformWalletError: Error { + case transactionBroadcastUnconfirmed(String) + case shieldedSpendUnconfirmed(String) + case walletOperation(String) +} + +enum TestBoundaryError: Error { case unusedRoute } +struct ModelContainer {} +struct TestAuthorizer { func authorize() async throws {} } +extension UInt64 { + var dashAmount: UInt64 { self } + var formattedDashAmountWithoutCurrencySymbol: String { String(self) } +} +struct MnemonicResolver {} +struct KeychainSigner { init(modelContainer: ModelContainer) {} } +enum SwiftDashSDKContactsService { enum ServiceError: Error { case noWallet } } +enum AddressTransformer { + static func parseBech32mAddress(_ address: String) -> Data? { Data(repeating: 1, count: 21) } +} +enum PlatformPaymentIdentityFundingPolicy { + static let creditsPerDuff: UInt64 = 1_000 + static let feeHeadroomCredits: UInt64 = 5 + enum PlanningError: Error { case insufficient(UInt64, UInt64) } + static func candidates(walletId: Data, modelContainer: ModelContainer) throws -> [Int] { + throw TestBoundaryError.unusedRoute + } + static func makeInputs(candidates: [Int], targetCredits: UInt64) throws -> [ManagedPlatformWallet.IdentityAddressInput] { + throw TestBoundaryError.unusedRoute + } +} + +@MainActor final class ManagedPlatformWallet { + struct IdentityAddressInput { let addressType: UInt8; let hash: Data; let credits: UInt64 } + let walletId = Data([1]) + var topUpCalls = 0 + var failure: Error? + var afterTopUp: () -> Void = {} + func topUpIdentityWithFunding(identityId: Data, amountDuffs: UInt64, accountIndex: Int) async throws -> UInt64 { + throw TestBoundaryError.unusedRoute + } + func topUpFromAddresses( + identityId: Data, inputs: [IdentityAddressInput], addressSigner: KeychainSigner + ) async throws -> UInt64 { + topUpCalls += 1 + if let failure { throw failure } + afterTopUp() + return 97 + } +} + +@MainActor final class NativeManager { + var unshieldCalls = 0 + var failure: Error? + var afterUnshield: () -> Void = {} + func shieldedUnshield( + walletId: Data, resolver: MnemonicResolver, account: Int, toPlatformAddress: String, + amount: UInt64 + ) async throws { + unshieldCalls += 1 + if let failure { throw failure } + afterUnshield() + } +} + +@MainActor final class SwiftDashSDKHost { + struct PlatformPreparation: Sendable { let operationVersion: Int } + static let shared = SwiftDashSDKHost() + var wallet: ManagedPlatformWallet? = ManagedPlatformWallet() + var manager: NativeManager? = NativeManager() + var modelContainer: ModelContainer? = ModelContainer() + func preparePlatformOperation() throws -> PlatformPreparation { .init(operationVersion: operationVersion) } + var checkGeneration = 0 + var operationVersion = 0 + var scopeCalls = 0 + var rejectScopeCall: Int? + func validatePlatformOperation(_ preparation: PlatformPreparation) throws { + if preparation.operationVersion != operationVersion { + throw WalletOperationPreparationError.expired("Changed") + } + } + func withPlatformOperation( + preparation: PlatformPreparation, operation: () async throws -> T + ) async throws -> T { + scopeCalls += 1 + try validatePlatformOperation(preparation) + if rejectScopeCall == scopeCalls { + throw WalletOperationPreparationError.expired("Changed at scope admission") + } + return try await operation() + } +} + +@MainActor final class PlatformAddressSyncCoordinator { + struct Address { let address: String } + struct Addresses { var nextReceiveAddress: Address? = .init(address: "destination") } + static let shared = PlatformAddressSyncCoordinator() + var derivedAddresses = Addresses() + func refreshShieldedBalanceAfterSpend(using manager: NativeManager) {} + func syncNow() async {} +} + +@MainActor final class IdentityTopUpViewModel { + enum FundingSource { case transparent, platform, shielded } + var stepLabel: String? + var isProcessing = false + var submittedUnconfirmed = false + var errorMessage: String? + let authorizer = TestAuthorizer() + // PRODUCTION_TOP_UP +} diff --git a/scripts/fixtures/IdentityTopUpCompatibilityTests.swift b/scripts/fixtures/IdentityTopUpCompatibilityTests.swift new file mode 100644 index 0000000000..bd38b64cc8 --- /dev/null +++ b/scripts/fixtures/IdentityTopUpCompatibilityTests.swift @@ -0,0 +1,153 @@ +import XCTest +@testable import IdentityTopUpHarness + +@MainActor final class IdentityTopUpCompatibilityTests: XCTestCase { + let host = SwiftDashSDKHost.shared + + override func setUp() async throws { + host.wallet = ManagedPlatformWallet() + host.manager = NativeManager() + host.operationVersion = 0 + host.scopeCalls = 0 + host.rejectScopeCall = nil + } + + func topUp() async throws -> UInt64 { + try await IdentityTopUpViewModel().topUpFromShielded( + identityId: Data([2]), amountDuffs: 100, + wallet: host.wallet!, modelContainer: ModelContainer(), + preparation: .init(operationVersion: 0)) + } + + func testChangedOperationVersionDoesNotAttemptSecondLeg() async { + host.manager!.afterUnshield = { self.host.operationVersion += 1 } + do { + _ = try await topUp() + XCTFail("Expected stale preparation") + } catch IdentityTopUpViewModel.TopUpError.movedToPlatform { + } catch { + XCTFail("Expected settled-first-leg diagnostic: \(error)") + } + XCTAssertEqual(host.manager!.unshieldCalls, 1) + XCTAssertEqual(host.wallet!.topUpCalls, 0) + } + + func testAmbiguousSecondLegRetainsUnknownOutcome() async { + let unknowns: [PlatformWalletError] = [ + .transactionBroadcastUnconfirmed("may be sent"), + .shieldedSpendUnconfirmed("may be spent"), + ] + for unknown in unknowns { + host.wallet = ManagedPlatformWallet() + host.manager = NativeManager() + host.wallet!.failure = unknown + do { + _ = try await topUp() + XCTFail("Expected unknown broadcast outcome") + } catch PlatformWalletError.transactionBroadcastUnconfirmed, + PlatformWalletError.shieldedSpendUnconfirmed { + } catch { + XCTFail("Unknown outcome mislabeled as safe top-up from Platform: \(error)") + } + XCTAssertEqual(host.manager!.unshieldCalls, 1) + XCTAssertEqual(host.wallet!.topUpCalls, 1) + } + } + + func testAmbiguousSecondLegSetsNonRetryablePresentationState() async { + host.wallet!.failure = PlatformWalletError.transactionBroadcastUnconfirmed("proof unavailable after dispatch") + let model = IdentityTopUpViewModel() + let result = await model.topUp(identityId: Data([2]), amountDuffs: 100, source: .shielded) + XCTAssertNil(result) + XCTAssertTrue(model.submittedUnconfirmed) + XCTAssertFalse(model.isProcessing) + XCTAssertTrue(model.errorMessage?.contains("may have been submitted") == true) + XCTAssertFalse(model.errorMessage?.contains("Finish the top-up from Platform") == true) + XCTAssertEqual(host.manager!.unshieldCalls, 1) + XCTAssertEqual(host.wallet!.topUpCalls, 1) + } + + func testSecondLegRefusalKeepsSettledFirstLeg() async { + host.wallet!.failure = PlatformWalletError.walletOperation("rejected") + do { + _ = try await topUp() + XCTFail("Expected second-leg refusal") + } catch IdentityTopUpViewModel.TopUpError.movedToPlatform(let cause) { + guard case PlatformWalletError.walletOperation = cause else { + return XCTFail("Lost original refusal: \(cause)") + } + } catch { + XCTFail("Lost settled first leg: \(error)") + } + XCTAssertEqual(host.manager!.unshieldCalls, 1) + XCTAssertEqual(host.wallet!.topUpCalls, 1) + } + + func testCancelledSecondLegRetainsUnknownOutcome() async { + host.wallet!.failure = CancellationError() + do { + _ = try await topUp() + XCTFail("Expected cancellation") + } catch is CancellationError { + } catch { + XCTFail("Cancellation was misclassified: \(error)") + } + XCTAssertEqual(host.manager!.unshieldCalls, 1) + XCTAssertEqual(host.wallet!.topUpCalls, 1) + } + + func testAmbiguousUnshieldDoesNotStartIdentityTopUp() async { + host.manager!.failure = PlatformWalletError.shieldedSpendUnconfirmed("may be sent") + do { + _ = try await topUp() + XCTFail("Expected unknown unshield outcome") + } catch PlatformWalletError.shieldedSpendUnconfirmed { + } catch { + XCTFail("Unshield outcome was misclassified: \(error)") + } + XCTAssertEqual(host.manager!.unshieldCalls, 1) + XCTAssertEqual(host.wallet!.topUpCalls, 0) + } + + func testFirstLegFailureNeverClaimsFundsLanded() async { + host.manager!.failure = PlatformWalletError.walletOperation("rejected") + do { + _ = try await topUp() + XCTFail("Expected first-leg refusal") + } catch PlatformWalletError.walletOperation { + } catch { + XCTFail("First-leg failure was misclassified: \(error)") + } + XCTAssertEqual(host.wallet!.topUpCalls, 0) + } + + func testSuccessfulSecondLegRemainsSuccessAfterOperationVersionChanges() async throws { + host.wallet!.afterTopUp = { self.host.operationVersion += 1 } + let balance = try await topUp() + XCTAssertEqual(balance, 97) + XCTAssertEqual(host.manager!.unshieldCalls, 1) + XCTAssertEqual(host.wallet!.topUpCalls, 1) + } + + func testInformationalRefreshBetweenLegsDoesNotStopTransfer() async throws { + host.manager!.afterUnshield = { self.host.checkGeneration += 1 } + let result = try await topUp() + XCTAssertEqual(result, 97) + XCTAssertEqual(host.manager!.unshieldCalls, 1) + XCTAssertEqual(host.wallet!.topUpCalls, 1) + } + + func testSecondScopeAdmissionRefusalKeepsSettledFirstLeg() async { + host.rejectScopeCall = 2 + do { + _ = try await topUp() + XCTFail("Expected refusal entering the second operation's scope") + } catch IdentityTopUpViewModel.TopUpError.movedToPlatform(let cause) { + XCTAssertTrue(cause is WalletOperationPreparationError) + } catch { + XCTFail("Lost the settled first leg at scope admission: \(error)") + } + XCTAssertEqual(host.manager!.unshieldCalls, 1) + XCTAssertEqual(host.wallet!.topUpCalls, 0) + } +} diff --git a/scripts/fixtures/InternalTransferConfirmationHarness.swift b/scripts/fixtures/InternalTransferConfirmationHarness.swift new file mode 100644 index 0000000000..91b07a04a3 --- /dev/null +++ b/scripts/fixtures/InternalTransferConfirmationHarness.swift @@ -0,0 +1,71 @@ +import Foundation + +struct CoreShieldedDrainContext: Equatable { let wallet: Int } +struct CoreShieldedDrainOperation { let context: CoreShieldedDrainContext } +struct Outpoint { let txidWire = Data([1]); let vout: UInt32 = 2 } +struct WalletDrainOutcome { + enum State { case pending, completed } + let state: State + let outpoint: Outpoint? = Outpoint() +} +@MainActor struct CoreShieldedDrainService { + static var context = CoreShieldedDrainContext(wallet: 1) + func status(for operation: CoreShieldedDrainOperation) async throws -> WalletDrainOutcome { + WalletDrainOutcome(state: .pending) + } + func operationStatus(_ context: CoreShieldedDrainContext) async throws + -> (operation: CoreShieldedDrainOperation, outcome: WalletDrainOutcome)? { + (.init(context: context), .init(state: .pending)) + } + func manager(for context: CoreShieldedDrainContext) throws -> Int { + guard context == Self.context else { throw NSError(domain: "changed-context", code: 1) } + return context.wallet + } +} +@MainActor final class SwiftDashSDKHost { + struct PlatformPreparation { let runtime: Int } + static let shared = SwiftDashSDKHost() + var runtime = 1 + func preparePlatformOperation() throws -> PlatformPreparation { .init(runtime: runtime) } +} +@MainActor final class Authorizer { + var onAuthorize: () -> Void = {} + func authorize() async throws { onAuthorize() } +} +@MainActor enum DWIdentityAuthorizer { + static func preauthorized(_ work: () async -> Void) async { await work() } +} +@MainActor final class Coordinator { + var preparation: Result = .success(.init(runtime: 0)) + var acceptedResumes = 0 + // Deliberately retains the old confirmation, as the production reset does. + func reset() {} + func bindConfirmationPreparation(_ value: Result) { preparation = value } + func resumeAssetLock(outPointTxidWire: Data, outPointVout: UInt32, + expectedDrainContext: CoreShieldedDrainContext, retryUnverifiedConsumption: Bool) async { + guard (try? preparation.get().runtime) == SwiftDashSDKHost.shared.runtime else { return } + acceptedResumes += 1 + } +} +@MainActor final class InternalTransferRunner { + enum StartOutcome: Equatable { case started, busy, notAuthorized, rejected } + enum Phase: Equatable { case idle, inFlight, success, submittedUnconfirmed, failed(String) } + enum Notice: Equatable { case started, busy, succeeded, submitted, drainPending, failed(String) } + let authorizer = Authorizer() + let coordinator = Coordinator() + var phase: Phase = .idle + var notice: Notice? + var isAwaitingAuthorization = false + var isCoreDrainRecovery = false + var startOutcome: StartOutcome = .rejected + func start(_ request: Int, preparation: Result) async -> StartOutcome { startOutcome } + // ANNOUNCE_METHOD + // RESUME_METHOD +} +@MainActor final class ConfirmationModel { + enum Mode { case transfer(Int), unavailable } + var mode: Mode = .transfer(1) + let runner = InternalTransferRunner() + let preparation: Result = .success(.init(runtime: 1)) + // CONFIRM_METHOD +} diff --git a/scripts/fixtures/InternalTransferConfirmationTests.swift b/scripts/fixtures/InternalTransferConfirmationTests.swift new file mode 100644 index 0000000000..dc6a6c0732 --- /dev/null +++ b/scripts/fixtures/InternalTransferConfirmationTests.swift @@ -0,0 +1,44 @@ +import XCTest +@testable import ConfirmationHarness + +@MainActor final class ConfirmationTests: XCTestCase { + func testUnconfirmedTerminalPhaseReplacesStartedNoticeWithWarning() { + let runner = InternalTransferRunner() + runner.notice = .started + runner.announce(.inFlight) + XCTAssertEqual(runner.notice, .started) + runner.announce(.submittedUnconfirmed) + XCTAssertEqual(runner.notice, .submitted) + runner.announce(.failed("refused")) + XCTAssertEqual(runner.notice, .failed("refused")) + } + + func testRejectedConfirmationRemainsDistinctFromSubmissionAndCancelledAuthorization() async { + let model = ConfirmationModel() + for outcome in [InternalTransferRunner.StartOutcome.rejected, .notAuthorized, .started, .busy] { + model.runner.startOutcome = outcome + let result = await model.confirm() + XCTAssertEqual(result, outcome) + } + } + + func testRecoveryRebindsPreparationAfterRuntimeChangesDuringAuthorization() async { + let runner = InternalTransferRunner() + SwiftDashSDKHost.shared.runtime = 1 + CoreShieldedDrainService.context = .init(wallet: 1) + runner.authorizer.onAuthorize = { SwiftDashSDKHost.shared.runtime = 2 } + _ = await runner.resumeCoreDrain(context: .init(wallet: 1), operation: nil) + XCTAssertEqual(runner.coordinator.acceptedResumes, 1) + XCTAssertEqual(try runner.coordinator.preparation.get().runtime, 2) + XCTAssertFalse(runner.isAwaitingAuthorization) + } + + func testRecoveryDoesNotRebindAcrossWalletChangeDuringAuthorization() async { + let runner = InternalTransferRunner() + CoreShieldedDrainService.context = .init(wallet: 1) + runner.authorizer.onAuthorize = { CoreShieldedDrainService.context = .init(wallet: 2) } + _ = await runner.resumeCoreDrain(context: .init(wallet: 1), operation: nil) + XCTAssertEqual(runner.coordinator.acceptedResumes, 0) + XCTAssertFalse(runner.isAwaitingAuthorization) + } +} diff --git a/scripts/fixtures/PlatformPreparationHarness.swift b/scripts/fixtures/PlatformPreparationHarness.swift new file mode 100644 index 0000000000..7ac0cef900 --- /dev/null +++ b/scripts/fixtures/PlatformPreparationHarness.swift @@ -0,0 +1,84 @@ +import Foundation + +// SDK and environment stand-ins only. The production host's preparation +// struct, methods, and error type are inserted unchanged by the test runner. +enum Network { + case mainnet, testnet +} + +struct ProtocolVersionInfo { + var verifiedVersion: UInt32? = 14 + var effectiveVersion: UInt32 = 14 + var maximumSupportedVersion: UInt32 = 14 +} + +@MainActor +final class SDK { + var snapshot = ProtocolVersionInfo() + var snapshotError: Error? + + func protocolVersionInfo() throws -> ProtocolVersionInfo { + if let snapshotError { throw snapshotError } + return snapshot + } +} + +struct ManagedPlatformWallet { + let walletId: Data +} + +@MainActor +enum WalletEnvironment { + static var network: Network? = .mainnet + static var networkKind: Network? { network } + static var selectedWalletID: Data? + + static func activeWalletId(for network: Network?) -> Data? { selectedWalletID } +} + +@MainActor +final class SwiftDashSDKHost { + static var shared = SwiftDashSDKHost(sdk: SDK(), walletID: Data([1])) + var sdk: SDK? + var runningNetwork: Network? + var wallet: ManagedPlatformWallet? + var runtimeID = UUID() + + init(sdk: SDK, walletID: Data) { + self.sdk = sdk + self.runningNetwork = .mainnet + self.wallet = ManagedPlatformWallet(walletId: walletID) + } + + // EXTRACTED_PRODUCTION_METHODS +} + +// Only the resume/auth boundary is controlled; retry, reset and host context +// validation are extracted unchanged from production. No spend is performed. +@MainActor final class RetryCoordinator { + enum Phase { case idle, signing, failed(String) } + var phase: Phase = .failed("previous failure") + var confirmationPreparation: Result? + var operationPreparation: SwiftDashSDKHost.PlatformPreparation? + var lastAssetLockOutPoint: (txidWire: Data, vout: UInt32)? + var lastFailure: Error? + var lastResumeReport: Int? + var attempted: [(Data, UInt32, Data?)] = [] + var authorized: [(Data, UInt32, Data?)] = [] + var onAuthorize: () -> Void = {} + func stopAssetLockPolling() {} + func handleFailure(_ error: Error) { lastFailure = error; phase = .failed(error.localizedDescription) } + func resumeAssetLock(outPointTxidWire: Data, outPointVout: UInt32, recipientRaw43: Data?, + retryUnverifiedConsumption: Bool = false) async { + phase = .signing + attempted.append((outPointTxidWire, outPointVout, recipientRaw43)) + onAuthorize() + do { + try SwiftDashSDKHost.shared.validatePlatformOperation(confirmationPreparation!.get()) + authorized.append((outPointTxidWire, outPointVout, recipientRaw43)) + throw NSError(domain: "controlled-resume-failure", code: 1) + } catch { handleFailure(error) } + } + // RETRY_METHOD + // RESET_METHOD +} diff --git a/scripts/fixtures/PlatformPreparationTests.swift b/scripts/fixtures/PlatformPreparationTests.swift new file mode 100644 index 0000000000..f225ea7d56 --- /dev/null +++ b/scripts/fixtures/PlatformPreparationTests.swift @@ -0,0 +1,287 @@ +import Foundation +import XCTest +@testable import PlatformPreparationHarness + +@MainActor +final class PlatformPreparationTests: XCTestCase { + private let firstWallet = Data([1]) + private let secondWallet = Data([2]) + + private func makeHost(selectedWallet: Bool = true) -> SwiftDashSDKHost { + WalletEnvironment.network = .mainnet + WalletEnvironment.selectedWalletID = selectedWallet ? firstWallet : nil + return SwiftDashSDKHost(sdk: SDK(), walletID: firstWallet) + } + + private func expectExpired( + _ host: SwiftDashSDKHost, + _ preparation: SwiftDashSDKHost.PlatformPreparation, + file: StaticString = #filePath, + line: UInt = #line + ) async { + var didRun = false + do { + _ = try await host.withPlatformOperation(preparation: preparation) { + didRun = true + return "submitted" + } + XCTFail("An obsolete confirmation must be rejected", file: file, line: line) + } catch WalletOperationPreparationError.expired { + XCTAssertFalse(didRun, "Refuse before invoking the operation", file: file, line: line) + } catch { + XCTFail("Expected a local expired-preparation error, got \(error)", file: file, line: line) + } + } + + func testNewerObservationDoesNotInvalidateConfirmation() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + host.sdk!.snapshot.verifiedVersion = 99 + try host.validatePlatformOperation(preparation) + let value = try await host.withPlatformOperation(preparation: preparation) { 42 } + XCTAssertEqual(value, 42) + } + + func testMissingVerifiedVersionAllowsPreparation() async throws { + let host = makeHost() + host.sdk!.snapshot.verifiedVersion = nil + let preparation = try host.preparePlatformOperation() + let value = try await host.withPlatformOperation(preparation: preparation) { 42 } + XCTAssertEqual(value, 42) + } + + func testSelectedWalletChangeRejectsConfirmation() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + WalletEnvironment.selectedWalletID = secondWallet + await expectExpired(host, preparation) + } + + func testSelectedAndPublishedWalletMismatchRejectsPreparation() async { + let host = makeHost() + WalletEnvironment.selectedWalletID = secondWallet + do { + _ = try host.preparePlatformOperation() + XCTFail("The selected wallet must match the wallet that will execute the operation") + } catch WalletOperationPreparationError.unavailable { + // The selected wallet has not been published by the host yet. + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + func testPublishedWalletReplacementRejectsConfirmationWithUnchangedSelection() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + host.wallet = ManagedPlatformWallet(walletId: secondWallet) + XCTAssertEqual(WalletEnvironment.selectedWalletID, firstWallet) + await expectExpired(host, preparation) + } + + func testMissingPublishedWalletRejectsPreparationEvenWithSelection() async { + let host = makeHost() + host.wallet = nil + XCTAssertEqual(WalletEnvironment.selectedWalletID, firstWallet) + do { + _ = try host.preparePlatformOperation() + XCTFail("A registry ID cannot substitute for a published wallet") + } catch WalletOperationPreparationError.unavailable { + // A wallet must be bound before a quote can be confirmed. + } catch { + XCTFail("Unexpected error: \(error)") + } + } + + func testMissingPublishedWalletRejectsConfirmationWithUnchangedSelection() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + host.wallet = nil + await expectExpired(host, preparation) + } + + func testAbsentSelectionUsesPublishedWallet() async throws { + let host = makeHost(selectedWallet: false) + let preparation = try host.preparePlatformOperation() + let value = try await host.withPlatformOperation(preparation: preparation) { "submitted" } + XCTAssertEqual(value, "submitted") + } + + func testFallbackWalletChangeRejectsConfirmation() async throws { + let host = makeHost(selectedWallet: false) + let preparation = try host.preparePlatformOperation() + host.wallet = ManagedPlatformWallet(walletId: secondWallet) + await expectExpired(host, preparation) + } + + func testSelectedNetworkChangeRejectsConfirmation() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + WalletEnvironment.network = .testnet + await expectExpired(host, preparation) + } + + func testRunningNetworkChangeRejectsConfirmation() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + host.runningNetwork = .testnet + await expectExpired(host, preparation) + } + + func testSDKReplacementWithSameSnapshotRejectsConfirmation() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + let replacement = SDK() + replacement.snapshot = host.sdk!.snapshot + host.sdk = replacement + await expectExpired(host, preparation) + } + + func testRuntimeReplacementRejectsConfirmation() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + host.runtimeID = UUID() + await expectExpired(host, preparation) + } + + func testEffectiveOperationVersionChangeRejectsConfirmation() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + host.sdk!.snapshot.effectiveVersion += 1 + await expectExpired(host, preparation) + } + + func testMissingLocalContextRejectsPreparation() async { + let mutations: [(SwiftDashSDKHost) -> Void] = [ + { $0.sdk = nil }, + { $0.runningNetwork = nil }, + { $0.runningNetwork = nil; WalletEnvironment.network = nil }, + { $0.runningNetwork = .testnet }, + { $0.wallet = nil; WalletEnvironment.selectedWalletID = nil }, + ] + for mutate in mutations { + let host = makeHost() + mutate(host) + do { + _ = try host.preparePlatformOperation() + XCTFail("Missing wallet/runtime context must refuse preparation") + } catch WalletOperationPreparationError.unavailable { + // Expected local context failure, independent of check status. + } catch { + XCTFail("Unexpected error: \(error)") + } + } + } + + private enum TestFailure: Error, Equatable { case snapshot, operation } + + private func retryCoordinator(_ host: SwiftDashSDKHost) throws -> RetryCoordinator { + SwiftDashSDKHost.shared = host + let coordinator = RetryCoordinator() + coordinator.confirmationPreparation = .success(try host.preparePlatformOperation()) + coordinator.lastAssetLockOutPoint = (Data([7, 8]), 3) + return coordinator + } + + func testRepeatedAssetLockRetryRefreshesVersionAndRetainsExactOutpointAndRecipient() async throws { + let host = makeHost() + let coordinator = try retryCoordinator(host) + let recipient = Data(repeating: 9, count: 43) + for version: UInt32 in [15, 16] { + host.sdk!.snapshot.effectiveVersion = version + await coordinator.retryLastAssetLock(recipientRaw43: recipient) + XCTAssertEqual(coordinator.lastAssetLockOutPoint?.txidWire, Data([7, 8])) + XCTAssertEqual(coordinator.lastAssetLockOutPoint?.vout, 3) + } + XCTAssertEqual(coordinator.authorized.count, 2) + for attempt in coordinator.authorized { + XCTAssertEqual(attempt.0, Data([7, 8])) + XCTAssertEqual(attempt.1, 3) + XCTAssertEqual(attempt.2, recipient) + } + } + + func testAssetLockRetryCannotRebindChangedWalletNetworkOrRuntime() async throws { + let mutations: [(SwiftDashSDKHost) -> Void] = [ + { $0.wallet = .init(walletId: Data([2])); WalletEnvironment.selectedWalletID = Data([2]) }, + { $0.runningNetwork = .testnet; WalletEnvironment.network = .testnet }, + { $0.runtimeID = UUID() }, + { $0.sdk = SDK() }, + ] + for mutate in mutations { + let host = makeHost() + let coordinator = try retryCoordinator(host) + mutate(host) + await coordinator.retryLastAssetLock(recipientRaw43: Data(repeating: 9, count: 43)) + XCTAssertTrue(coordinator.attempted.isEmpty) + XCTAssertNotNil(coordinator.lastFailure) + XCTAssertEqual(coordinator.lastAssetLockOutPoint?.txidWire, Data([7, 8])) + } + } + + func testAssetLockRetryRevalidatesContextAfterAuthorizationAndKeepsLock() async throws { + let host = makeHost() + let coordinator = try retryCoordinator(host) + coordinator.onAuthorize = { host.runtimeID = UUID() } + await coordinator.retryLastAssetLock(recipientRaw43: Data(repeating: 9, count: 43)) + XCTAssertEqual(coordinator.attempted.count, 1) + XCTAssertTrue(coordinator.authorized.isEmpty) + XCTAssertEqual(coordinator.lastAssetLockOutPoint?.vout, 3) + await coordinator.retryLastAssetLock(recipientRaw43: Data(repeating: 9, count: 43)) + XCTAssertEqual(coordinator.attempted.count, 1) + } + + func testAssetLockRetryRequiresFailedPhaseAndExistingLock() async throws { + let host = makeHost() + let coordinator = try retryCoordinator(host) + coordinator.phase = .signing + await coordinator.retryLastAssetLock(recipientRaw43: Data()) + coordinator.phase = .failed("failure") + coordinator.lastAssetLockOutPoint = nil + await coordinator.retryLastAssetLock(recipientRaw43: Data()) + XCTAssertTrue(coordinator.attempted.isEmpty) + } + + func testSnapshotBridgeFailurePropagatesWithoutInvokingOperation() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + host.sdk!.snapshotError = TestFailure.snapshot + var didRun = false + do { + try await host.withPlatformOperation(preparation: preparation) { didRun = true } + XCTFail("A missing effective operation version must propagate its error") + } catch { + XCTAssertEqual(error as? TestFailure, .snapshot) + } + XCTAssertFalse(didRun) + } + + func testSuccessfulOperationHasNoRetroactivePreparationFailure() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + let result = try await host.withPlatformOperation(preparation: preparation) { + // The operation has been dispatched. Lifecycle changes during its + // await cannot turn its successful outcome into a retry prompt. + host.runtimeID = UUID() + host.sdk!.snapshot.effectiveVersion += 1 + WalletEnvironment.selectedWalletID = secondWallet + await Task.yield() + return "confirmed transaction" + } + XCTAssertEqual(result, "confirmed transaction") + await expectExpired(host, preparation) + } + + func testOperationFailureIsPreserved() async throws { + let host = makeHost() + let preparation = try host.preparePlatformOperation() + do { + try await host.withPlatformOperation(preparation: preparation) { + host.runtimeID = UUID() + throw TestFailure.operation + } + XCTFail("The operation error must propagate") + } catch { + XCTAssertEqual(error as? TestFailure, .operation) + } + } +} diff --git a/scripts/test_asset_lock_recovery.py b/scripts/test_asset_lock_recovery.py new file mode 100644 index 0000000000..dcc7076272 --- /dev/null +++ b/scripts/test_asset_lock_recovery.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Test the production resume entry point and durable probe store in isolation.""" +from pathlib import Path +import os +import subprocess +import tempfile + +repository = Path(__file__).resolve().parents[1] +with tempfile.TemporaryDirectory(prefix="asset-lock-recovery-tests-") as directory: + package = Path(directory) + source = package / "Sources/RecoveryHarness" + tests = package / "Tests/RecoveryHarnessTests" + source.mkdir(parents=True) + tests.mkdir(parents=True) + (source / "AssetLockProbeStore.swift").symlink_to(repository / "DashWallet/Sources/Infrastructure/SwiftDashSDK/AssetLockProbeStore.swift") + production = (repository / "DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedTransferCoordinator.swift").read_text() + methods = [] + for marker in (" func resumeAssetLock(", " static func alreadyConsumedAssetLockResumePhase(", + " func retryLastAssetLock(", " var requiresFreshConfirmation:", " func reset()"): + start = production.index(marker) + opening = production.index("{", start) + depth, end = 1, opening + 1 + while depth: + depth += (production[end] == "{") - (production[end] == "}") + end += 1 + methods.append(production[start:end]) + harness = (repository / "scripts/fixtures/AssetLockRecoveryHarness.swift").read_text() + def caller_method(path, marker): + text = (repository / path).read_text() + start = text.index(marker) + end = text.index("{", start) + 1 + depth = 1 + while depth: + depth += (text[end] == "{") - (text[end] == "}") + end += 1 + return text[start:end].replace("private func", "func", 1) + harness = harness.replace("// PRODUCTION_METHODS", "\n".join(methods)) + harness = harness.replace("// COINJOIN_RETRY", caller_method( + "DashWallet/Sources/UI/Home/Views/CoinJoinMoveFunds/CoinJoinMoveFundsViewModel.swift", + " func retryShielded()")) + harness = harness.replace("// COINJOIN_MOVE", caller_method( + "DashWallet/Sources/UI/Home/Views/CoinJoinMoveFunds/CoinJoinMoveFundsViewModel.swift", + " func moveToShielded()")) + harness = harness.replace("// COINJOIN_FINISH", caller_method( + "DashWallet/Sources/UI/Home/Views/CoinJoinMoveFunds/CoinJoinMoveFundsViewModel.swift", + " private func finishFromCoordinatorPhase()")) + harness = harness.replace("// SEND_RETRY", caller_method( + "DashWallet/Sources/UI/Payments/Pay/SendScreen.swift", " private func tryAgain()")) + (source / "Coordinator.swift").write_text(harness) + (tests / "RecoveryTests.swift").symlink_to(repository / "scripts/fixtures/AssetLockRecoveryTests.swift") + (package / "Package.swift").write_text('''// swift-tools-version: 5.9 +import PackageDescription +let package = Package(name: "RecoveryHarness", platforms: [.macOS("15.0")], targets: [ + .target(name: "RecoveryHarness"), + .testTarget(name: "RecoveryHarnessTests", dependencies: ["RecoveryHarness"]) +]) +''') + environment = os.environ.copy() + environment["CLANG_MODULE_CACHE_PATH"] = str(package / "modules") + environment["SWIFTPM_MODULECACHE_OVERRIDE"] = str(package / "modules") + subprocess.run(["xcrun", "swift", "test", "--package-path", str(package), + "--scratch-path", str(package / ".build"), "--cache-path", str(package / "cache"), + "--config-path", str(package / "configuration"), "--security-path", str(package / "security"), + "--disable-sandbox"], check=True, env=environment) diff --git a/scripts/test_core_to_shielded_fee_cache.py b/scripts/test_core_to_shielded_fee_cache.py new file mode 100644 index 0000000000..4431c78cb0 --- /dev/null +++ b/scripts/test_core_to_shielded_fee_cache.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Run the existing production fee-cache tests separately from protocol notices.""" +from pathlib import Path +import os +import subprocess +import tempfile + +repository = Path(__file__).resolve().parents[1] +with tempfile.TemporaryDirectory(prefix="core-shielded-fee-tests-") as directory: + package = Path(directory) + source = package / "Sources/CoreToShieldedFeeHarness" + tests = package / "Tests/CoreToShieldedFeeHarnessTests" + source.mkdir(parents=True) + tests.mkdir(parents=True) + (source / "Harness.swift").symlink_to( + repository / "scripts/fixtures/CoreToShieldedFeeCompatibilityHarness.swift") + (tests / "Tests.swift").symlink_to( + repository / "scripts/fixtures/CoreToShieldedFeeCompatibilityTests.swift") + production = (repository / "DashWallet/Sources/UI/Payments/InternalTransfer/InternalTransferViewModel.swift").read_text() + start = production.index("@MainActor\nenum CoreToShieldedAmountPolicy {") + opening = production.index("{", start) + depth, end = 1, opening + 1 + while depth: + depth += (production[end] == "{") - (production[end] == "}") + end += 1 + (source / "CoreToShieldedAmountPolicy.swift").write_text(production[start:end] + "\n") + (package / "Package.swift").write_text('''// swift-tools-version: 5.9 +import PackageDescription +let package = Package(name: "CoreToShieldedFeeHarness", platforms: [.macOS("15.0")], targets: [ + .target(name: "CoreToShieldedFeeHarness"), + .testTarget(name: "CoreToShieldedFeeHarnessTests", dependencies: ["CoreToShieldedFeeHarness"]) +]) +''') + environment = os.environ.copy() + environment["CLANG_MODULE_CACHE_PATH"] = str(package / "modules") + environment["SWIFTPM_MODULECACHE_OVERRIDE"] = str(package / "modules") + subprocess.run(["xcrun", "swift", "test", "--package-path", str(package), + "--scratch-path", str(package / ".build"), "--cache-path", str(package / "cache"), + "--config-path", str(package / "configuration"), "--security-path", str(package / "security"), + "--disable-sandbox"], check=True, env=environment) diff --git a/scripts/test_identity_top_up_compatibility.py b/scripts/test_identity_top_up_compatibility.py new file mode 100644 index 0000000000..365bbaae07 --- /dev/null +++ b/scripts/test_identity_top_up_compatibility.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Exercise the production two-leg top-up with deterministic SDK refusals.""" +from pathlib import Path +import os +import subprocess +import tempfile + +repository = Path(__file__).resolve().parents[1] +production = (repository / "DashWallet/Sources/UI/DashPay/Profile/SDKIdentityProfileSheet.swift").read_text() + + +def declaration(marker): + start = production.index(marker) + opening = production.index("{", start) + depth, end = 1, opening + 1 + while depth: + depth += (production[end] == "{") - (production[end] == "}") + end += 1 + return production[start:end].replace("private func", "func", 1) + + +with tempfile.TemporaryDirectory(prefix="identity-top-up-compatibility-") as directory: + package = Path(directory) + source = package / "Sources/IdentityTopUpHarness" + tests = package / "Tests/IdentityTopUpHarnessTests" + source.mkdir(parents=True) + tests.mkdir(parents=True) + # The production control flow and error classification are unchanged. + # Only the native SDK, persistence, and address-provider boundaries are fakes. + methods = "\n".join(declaration(marker) for marker in ( + " func topUp(", + " enum TopUpError: LocalizedError {", + " private func validatePreparation(", + " private func topUpFromShielded(", + )) + scaffold = (repository / "scripts/fixtures/IdentityTopUpCompatibilityHarness.swift").read_text() + sentinel = " // PRODUCTION_TOP_UP" + assert scaffold.count(sentinel) == 1 + (source / "IdentityTopUpHarness.swift").write_text(scaffold.replace(sentinel, methods)) + (tests / "IdentityTopUpCompatibilityTests.swift").symlink_to( + repository / "scripts/fixtures/IdentityTopUpCompatibilityTests.swift") + (package / "Package.swift").write_text("""// swift-tools-version: 5.9 +import PackageDescription +let package = Package(name: "IdentityTopUpHarness", platforms: [.macOS("15.0")], targets: [ + .target(name: "IdentityTopUpHarness"), + .testTarget(name: "IdentityTopUpHarnessTests", dependencies: ["IdentityTopUpHarness"]) +]) +""") + environment = os.environ.copy() + environment["CLANG_MODULE_CACHE_PATH"] = str(package / "modules") + environment["SWIFTPM_MODULECACHE_OVERRIDE"] = str(package / "modules") + subprocess.run([ + "xcrun", "swift", "test", "--package-path", str(package), + "--scratch-path", str(package / ".build"), "--cache-path", str(package / "cache"), + "--config-path", str(package / "configuration"), "--security-path", str(package / "security"), + "--disable-sandbox", + ], check=True, env=environment) diff --git a/scripts/test_internal_transfer_confirmation.py b/scripts/test_internal_transfer_confirmation.py new file mode 100644 index 0000000000..c3dc5ab16e --- /dev/null +++ b/scripts/test_internal_transfer_confirmation.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Run production confirmation and drain-resume decisions with controlled boundaries.""" +from pathlib import Path +import subprocess +import tempfile + +repo = Path(__file__).resolve().parents[1] +base = repo / 'DashWallet/Sources/UI/Payments/InternalTransfer/Confirm' + +def method(file, marker): + text = (base / file).read_text() + start = text.index(marker) + end = text.index('{', start) + 1 + depth = 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + +with tempfile.TemporaryDirectory(prefix='transfer-confirmation-tests-') as temp: + root = Path(temp) + sources = root / 'Sources/ConfirmationHarness' + tests = root / 'Tests/ConfirmationHarnessTests' + sources.mkdir(parents=True) + tests.mkdir(parents=True) + runner = method('InternalTransferRunner.swift', ' func resumeCoreDrain(') + announce = method('InternalTransferRunner.swift', ' private func announce(').replace('private func', 'func', 1) + confirm = method('InternalTransferConfirmViewModel.swift', ' func confirm()') + scaffold = (repo / 'scripts/fixtures/InternalTransferConfirmationHarness.swift').read_text() + (sources / 'Harness.swift').write_text(scaffold.replace('// RESUME_METHOD', runner).replace('// CONFIRM_METHOD', confirm).replace('// ANNOUNCE_METHOD', announce)) + (tests / 'Tests.swift').symlink_to(repo / 'scripts/fixtures/InternalTransferConfirmationTests.swift') + (root / 'Package.swift').write_text('''// swift-tools-version: 5.9 +import PackageDescription +let package = Package(name: "ConfirmationHarness", platforms: [.macOS("15.0")], targets: [ +.target(name: "ConfirmationHarness"), +.testTarget(name: "ConfirmationHarnessTests", dependencies: ["ConfirmationHarness"])]) +''') + subprocess.run(['xcrun', 'swift', 'test', '--package-path', str(root), '--disable-sandbox'], check=True) diff --git a/scripts/test_platform_preparation.py b/scripts/test_platform_preparation.py new file mode 100644 index 0000000000..8910cf8d21 --- /dev/null +++ b/scripts/test_platform_preparation.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Test the host's actual local Platform preparation methods without an SDK runtime.""" +from pathlib import Path +import os +import subprocess +import tempfile + + +repository = Path(__file__).resolve().parents[1] +host = (repository / "DashWallet/Sources/Infrastructure/SwiftDashSDK/SwiftDashSDKHost.swift").read_text() +start = host.index(" struct PlatformPreparation {") +end = host.index(" // MARK: - Wallet presence", start) +methods = host[start:end] +coordinator = (repository / "DashWallet/Sources/UI/Payments/InternalTransfer/Shielded/ShieldedTransferCoordinator.swift").read_text() + +def coordinator_method(marker): + start = coordinator.index(marker) + end = coordinator.index('{', start) + 1 + depth = 1 + while depth: + depth += (coordinator[end] == '{') - (coordinator[end] == '}') + end += 1 + return coordinator[start:end] + +error_start = host.index("enum WalletOperationPreparationError:") + +with tempfile.TemporaryDirectory(prefix="platform-preparation-tests-") as directory: + package = Path(directory) + source = package / "Sources/PlatformPreparationHarness" + tests = package / "Tests/PlatformPreparationHarnessTests" + source.mkdir(parents=True) + tests.mkdir(parents=True) + scaffold = (repository / "scripts/fixtures/PlatformPreparationHarness.swift").read_text() + assert scaffold.count("// EXTRACTED_PRODUCTION_METHODS") == 1 + (source / "PlatformPreparationHarness.swift").write_text( + scaffold.replace("// EXTRACTED_PRODUCTION_METHODS", methods) + .replace("// RETRY_METHOD", coordinator_method(" func retryLastAssetLock(")) + .replace("// RESET_METHOD", coordinator_method(" func reset()")) + + "\n" + host[error_start:] + "\n") + (tests / "PlatformPreparationTests.swift").symlink_to( + repository / "scripts/fixtures/PlatformPreparationTests.swift") + (package / "Package.swift").write_text('''// swift-tools-version: 5.9 +import PackageDescription +let package = Package(name: "PlatformPreparationHarness", platforms: [.macOS("15.0")], targets: [ + .target(name: "PlatformPreparationHarness"), + .testTarget(name: "PlatformPreparationHarnessTests", dependencies: ["PlatformPreparationHarness"]) +]) +''') + environment = os.environ.copy() + environment["CLANG_MODULE_CACHE_PATH"] = str(package / "modules") + environment["SWIFTPM_MODULECACHE_OVERRIDE"] = str(package / "modules") + subprocess.run([ + "xcrun", "swift", "test", "--package-path", str(package), + "--scratch-path", str(package / ".build"), "--cache-path", str(package / "cache"), + "--config-path", str(package / "configuration"), "--security-path", str(package / "security"), + "--disable-sandbox", + ], check=True, env=environment)