Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions .github/workflows/core-drain-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand All @@ -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
2 changes: 1 addition & 1 deletion .platform-ref
Original file line number Diff line number Diff line change
@@ -1 +1 @@
5b89fe8b529c66d5e972880196545c902285258b
48490f211b2004e27e656019a41b14fbb4c56815
Original file line number Diff line number Diff line change
Expand Up @@ -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 (`<legacyKey>_<activeWalletIdHex>`) 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 (`<storageKey>_<activeWalletIdHex>`) 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<Data>?

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
Expand All @@ -85,30 +68,40 @@ final class AssetLockProbeStore {
return set
}

private func loaded() -> Set<Data> { 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
Expand All @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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 —
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 {
Expand Down
Loading
Loading