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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,15 @@ public final class DWIdentityRegistrationBridge: NSObject {
/// surface for what is effectively SwiftDashSDK-path-only state.
@objc public var preferredFundingSource: DWIdentityFundingSource = .core

/// Non-contested companion ("temporary") username to register in the
/// same flow as a contested submission — see
/// `DWIdentityRegistrationCoordinator.startCreateUsername`'s
/// `temporaryUsername` parameter. Same lifecycle as
/// `preferredFundingSource`: written by the SwiftUI form right before
/// submit (nil for a plain submission), preserved across `.failed` so
/// a retry keeps the user's choice, reset on `.completed`.
@objc public var pendingTemporaryUsername: String?

// MARK: - Subscriptions

private var coordinatorSubscription: AnyCancellable?
Expand All @@ -155,12 +164,14 @@ public final class DWIdentityRegistrationBridge: NSObject {
completion: @escaping (String?, NSError?) -> Void
) {
let source = preferredFundingSource
Self.logger.info("🪪 IDENT-BRIDGE :: startCreateUsername username=\(username, privacy: .public) funding=\(source.logLabel, privacy: .public)")
let temporaryUsername = sanitizedTemporaryUsername(for: username)
Self.logger.info("🪪 IDENT-BRIDGE :: startCreateUsername username=\(username, privacy: .public) funding=\(source.logLabel, privacy: .public) temporary=\(temporaryUsername ?? "none", privacy: .public)")
Task { @MainActor in
do {
let identityId = try await DWIdentityRegistrationCoordinator.shared.startCreateUsername(
username,
fundingSource: source)
fundingSource: source,
temporaryUsername: temporaryUsername)
let hex = identityId.map { String(format: "%02x", $0) }.joined()
completion(hex, nil)
} catch {
Expand All @@ -176,12 +187,14 @@ public final class DWIdentityRegistrationBridge: NSObject {
completion: @escaping (String?, NSError?) -> Void
) {
let source = preferredFundingSource
let temporaryUsername = sanitizedTemporaryUsername(for: username)
Self.logger.info("🪪 IDENT-BRIDGE :: retry username=\(username, privacy: .public) funding=\(source.logLabel, privacy: .public)")
Task { @MainActor in
do {
let identityId = try await DWIdentityRegistrationCoordinator.shared.retry(
username,
fundingSource: source)
fundingSource: source,
temporaryUsername: temporaryUsername)
let hex = identityId.map { String(format: "%02x", $0) }.joined()
completion(hex, nil)
} catch {
Expand Down Expand Up @@ -219,6 +232,29 @@ public final class DWIdentityRegistrationBridge: NSObject {

// MARK: - Internal

/// Resolve `pendingTemporaryUsername` for a submission of `username`.
///
/// The property channel can go stale: a PIN-cancelled attempt never
/// reaches a terminal phase (so the `.completed` cleanup doesn't
/// run), and the legacy Obj-C entry point
/// (`DWDashPayModel.createUsername:`) never writes the property at
/// all. Rather than let a stale companion fail an unrelated
/// submission at the coordinator's pre-flight pairing guard, drop —
/// and clear — any value that doesn't validly pair with the label
/// actually being submitted (contested main + non-contested
/// companion). An intentional retry of the same contested attempt
/// still pairs validly, so it keeps the user's choice.
private func sanitizedTemporaryUsername(for username: String) -> String? {
guard let temporary = pendingTemporaryUsername else { return nil }
guard DWContestedNameStatusService.isContestedLabel(username),
!DWContestedNameStatusService.isContestedLabel(temporary) else {
Self.logger.warning("🪪 IDENT-BRIDGE :: dropping stale temporary username \(temporary, privacy: .public) for submission of \(username, privacy: .public)")
pendingTemporaryUsername = nil
return nil
}
return temporary
}

/// Subscribe to the coordinator's published surface and mirror
/// each transition into the cached @objc state + post the internal
/// `stateChangedNotification`. `DWDashPayModel` is the sole
Expand Down Expand Up @@ -282,6 +318,7 @@ public final class DWIdentityRegistrationBridge: NSObject {
// strand a PP-only wallet on a path that has no Core balance.
if case .completed = phase {
preferredFundingSource = .core
pendingTemporaryUsername = nil
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// Internal notification — DWDashPayModel observes this,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,19 @@ final class DWIdentityRegistrationCoordinator: ObservableObject {
/// an active attempt.
private(set) var currentFundingSource: DWIdentityFundingSource = .core

/// Non-contested companion label registered alongside a contested
/// submission in the same flow ("temporary username"), non-nil only
/// after its `registerDpnsName` succeeded. Read by
/// `CreateUsernameViewModel.registrationOutcome(for:)` to tell the
/// form which of the two names actually landed.
private(set) var registeredTemporaryUsername: String?

/// Failure description when the companion registration was requested
/// but failed. Deliberately non-fatal: the contested submission has
/// already succeeded by the time the companion registers, so the flow
/// completes and the form reports the partial outcome.
private(set) var temporaryUsernameError: String?

// MARK: - Internal state

private var controller: DWIdentityRegistrationController?
Expand Down Expand Up @@ -337,6 +350,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject {
case shieldedCreateUnconfirmed
case missingInvitation
case alreadyInFlight
case invalidTemporaryUsername

var errorDescription: String? {
switch self {
Expand Down Expand Up @@ -395,6 +409,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject {
return NSLocalizedString("This invitation link is not valid.", comment: "DashPay Invitations")
case .alreadyInFlight:
return NSLocalizedString("Identity registration already in progress", comment: "DashPay")
case .invalidTemporaryUsername:
return NSLocalizedString("The temporary username must not itself require voting.", comment: "Usernames")
}
}
}
Expand All @@ -418,13 +434,38 @@ final class DWIdentityRegistrationCoordinator: ObservableObject {
/// `startClaimInvitation(username:invitationURI:)`, which supplies
/// the voucher link; calling this method with `.invitation` and no
/// `invitationURI` fails with `.missingInvitation`.
///
/// `temporaryUsername` (contested submissions only) is a
/// NON-contested companion label registered to the same identity
/// right after the contested submission, inside the same authorized
/// flow — the user is reachable at it while masternode voting runs,
/// and keeps it permanently afterwards. Its registration failure is
/// non-fatal (`temporaryUsernameError`); its success is recorded in
/// `registeredTemporaryUsername` and mirrored to `DWGlobalOptions`
/// as the active username (the deferred contested label then never
/// displaces it — `finalizeWon` only backfills an empty mirror, so
/// a vote win adds the second name instead of replacing the first).
@discardableResult
func startCreateUsername(
_ username: String,
fundingSource: DWIdentityFundingSource = .core,
invitationURI: String? = nil
invitationURI: String? = nil,
temporaryUsername: String? = nil
) async throws -> Identifier {
Self.logger.info("🪪 IDENT-COORD :: startCreateUsername username=\(username, privacy: .public) funding=\(fundingSource.logLabel, privacy: .public)")
Self.logger.info("🪪 IDENT-COORD :: startCreateUsername username=\(username, privacy: .public) funding=\(fundingSource.logLabel, privacy: .public) temporary=\(temporaryUsername ?? "none", privacy: .public)")

// A companion label only makes sense next to a contested main
// label, and must itself be non-contested — registering a second
// contested name here would silently open a second vote the UI
// never explained. Reject before any money moves.
if let temporaryUsername {
guard DWContestedNameStatusService.isContestedLabel(username),
!DWContestedNameStatusService.isContestedLabel(temporaryUsername)
else {
Self.logger.error("🪪 IDENT-COORD :: invalid temporary username pairing main=\(username, privacy: .public) temporary=\(temporaryUsername, privacy: .public)")
throw CoordinatorError.invalidTemporaryUsername
}
}

// Preconditions — resolved once up-front so failures are
// surfaced before the PIN prompt.
Expand Down Expand Up @@ -795,6 +836,34 @@ final class DWIdentityRegistrationCoordinator: ObservableObject {
}
}

// Step 3.6: companion (temporary) username. The contested label
// above is only preregistered — it belongs to nobody until the
// vote resolves — so the user asked for a second, non-contested
// name to be reachable at in the meantime. Same identity, same
// signer, no additional PIN prompt. Failure is deliberately
// non-fatal: the contested submission (the primary intent, and
// the user's locked funds) already succeeded, so the flow
// completes and the form reports the partial outcome from
// `temporaryUsernameError`.
if let temporaryUsername, isContestedSubmission {
do {
_ = try await wallet.registerDpnsName(
identityId: identityId,
name: temporaryUsername,
signer: signer)
registeredTemporaryUsername = temporaryUsername
Self.logger.info("🪪 IDENT-COORD :: temporary DPNS name registered: \(temporaryUsername, privacy: .public)")
// Push the new label into the identity read model right
// away (same post-registration refresh the marketplace's
// `register(label:)` does) so profile/username surfaces
// don't wait for the next Home-appear sync.
DWCurrentUserIdentityInfo.shared.refreshFromSDK()
} catch {
temporaryUsernameError = error.localizedDescription
Self.logger.error("🪪 IDENT-COORD :: temporary DPNS registration failed: \(String(describing: error), privacy: .public)")
}
}

// Step 4: mark complete + mirror to DWGlobalOptions. The
// controller transition triggers the phaseSubscription
// sink which posts the notification + writes
Expand All @@ -820,12 +889,14 @@ final class DWIdentityRegistrationCoordinator: ObservableObject {
@discardableResult
func startClaimInvitation(
username: String,
invitationURI: String
invitationURI: String,
temporaryUsername: String? = nil
) async throws -> Identifier {
try await startCreateUsername(
username,
fundingSource: .invitation,
invitationURI: invitationURI)
invitationURI: invitationURI,
temporaryUsername: temporaryUsername)
}

/// Direct purchase of a marketplace-listed name from the
Expand Down Expand Up @@ -1019,10 +1090,14 @@ final class DWIdentityRegistrationCoordinator: ObservableObject {
@discardableResult
func retry(
_ username: String,
fundingSource: DWIdentityFundingSource = .core
fundingSource: DWIdentityFundingSource = .core,
temporaryUsername: String? = nil
) async throws -> Identifier {
Self.logger.info("🪪 IDENT-COORD :: retry username=\(username, privacy: .public) funding=\(fundingSource.logLabel, privacy: .public)")
return try await startCreateUsername(username, fundingSource: fundingSource)
return try await startCreateUsername(
username,
fundingSource: fundingSource,
temporaryUsername: temporaryUsername)
}

/// Abort the current attempt and reset to `.idle`. Safe to call
Expand Down Expand Up @@ -1252,7 +1327,19 @@ final class DWIdentityRegistrationCoordinator: ObservableObject {
if case .completed = newPhase, let username = currentUsername {
let isContestedSubmission = DWContestedNameStatusService.shared.isPendingLabel(username)
if isContestedSubmission {
Self.logger.info("🪪 IDENT-COORD :: completed (contested) — deferring DWGlobalOptions mirror writes")
if let temporaryUsername = registeredTemporaryUsername {
// The companion name registered in Step 3.6 is live
// immediately — it becomes the active username while
// the contested label stays deferred until the vote
// resolves. `finalizeWon` only backfills an EMPTY
// mirror, so a later vote win adds the contested name
// to the identity without displacing this one.
Self.logger.info("🪪 IDENT-COORD :: completed (contested) — mirroring temporary username \(temporaryUsername, privacy: .public)")
DWGlobalOptions.sharedInstance().dashpayUsername = temporaryUsername
DWGlobalOptions.sharedInstance().dashpayRegistrationCompleted = true
} else {
Self.logger.info("🪪 IDENT-COORD :: completed (contested) — deferring DWGlobalOptions mirror writes")
}
} else {
DWGlobalOptions.sharedInstance().dashpayUsername = username
DWGlobalOptions.sharedInstance().dashpayRegistrationCompleted = true
Expand Down Expand Up @@ -1323,6 +1410,8 @@ final class DWIdentityRegistrationCoordinator: ObservableObject {
lastErrorMessage = nil
currentUsername = nil
currentFundingSource = .core
registeredTemporaryUsername = nil
temporaryUsernameError = nil
}

/// Look up the persisted identity at `pinnedIdentityIndex` for
Expand Down
Loading
Loading