From 5714af00e4e44a592f32bc4d11473108cdd72f2f Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 30 Oct 2026 21:36:30 +0200 Subject: [PATCH 01/29] fix(dashconnect): refuse an App Connect v2 renewal that cannot turn off every replaced key A renewal disabled only the first maxKeysDisabledPerUpdate superseded keys of the connection and reported success while the rest stayed live. It is now refused before anything is submitted; a disconnect takes the keys in batches. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectV2Login.swift | 8 ++++++++ .../PlatformDashConnectDataSource.swift | 14 ++++++++++++-- DashWallet/ar.lproj/Localizable.strings | 1 + DashWallet/bg.lproj/Localizable.strings | 1 + DashWallet/ca.lproj/Localizable.strings | 1 + DashWallet/cs.lproj/Localizable.strings | 1 + DashWallet/da.lproj/Localizable.strings | 1 + DashWallet/de.lproj/Localizable.strings | 1 + DashWallet/el.lproj/Localizable.strings | 1 + DashWallet/en.lproj/Localizable.strings | 1 + DashWallet/eo.lproj/Localizable.strings | 1 + DashWallet/es.lproj/Localizable.strings | 1 + DashWallet/et.lproj/Localizable.strings | 1 + DashWallet/fa.lproj/Localizable.strings | 1 + DashWallet/fi.lproj/Localizable.strings | 1 + DashWallet/fil.lproj/Localizable.strings | 1 + DashWallet/fr.lproj/Localizable.strings | 1 + DashWallet/hr.lproj/Localizable.strings | 1 + DashWallet/hu.lproj/Localizable.strings | 1 + DashWallet/id.lproj/Localizable.strings | 1 + DashWallet/it.lproj/Localizable.strings | 1 + DashWallet/ja.lproj/Localizable.strings | 1 + DashWallet/ko.lproj/Localizable.strings | 1 + DashWallet/mk.lproj/Localizable.strings | 1 + DashWallet/ms.lproj/Localizable.strings | 1 + DashWallet/nb.lproj/Localizable.strings | 1 + DashWallet/nl.lproj/Localizable.strings | 1 + DashWallet/pl.lproj/Localizable.strings | 1 + DashWallet/pt.lproj/Localizable.strings | 1 + DashWallet/ro.lproj/Localizable.strings | 1 + DashWallet/ru.lproj/Localizable.strings | 1 + DashWallet/sk.lproj/Localizable.strings | 1 + DashWallet/sl.lproj/Localizable.strings | 1 + DashWallet/sl_SI.lproj/Localizable.strings | 1 + DashWallet/sq.lproj/Localizable.strings | 1 + DashWallet/sr.lproj/Localizable.strings | 1 + DashWallet/sv.lproj/Localizable.strings | 1 + DashWallet/th.lproj/Localizable.strings | 1 + DashWallet/tr.lproj/Localizable.strings | 1 + DashWallet/uk.lproj/Localizable.strings | 1 + DashWallet/vi.lproj/Localizable.strings | 1 + DashWallet/zh-Hans.lproj/Localizable.strings | 1 + DashWallet/zh-Hant-TW.lproj/Localizable.strings | 1 + DashWallet/zh.lproj/Localizable.strings | 1 + DashWallet/zh_TW.lproj/Localizable.strings | 1 + .../DashConnect/AppConnectV2LoginTests.swift | 6 ++++++ 46 files changed, 69 insertions(+), 2 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 695fa92e12..358fb56d46 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -781,6 +781,14 @@ extension AppConnect { .sorted() } + /// Whether one identity update can turn off all of `keyIds`. A login + /// that replaces a connection's keys turns them all off in its own + /// update or is refused: leaving some on would report a replacement + /// that did not happen. A disconnect takes them in batches. + static func fitsOneUpdate(disabling keyIds: [UInt32]) -> Bool { + keyIds.count <= maxKeysDisabledPerUpdate + } + /// The contracts and contract groups that v2-shaped keys no record names /// are bound to (`unrecordedV2Keys`), other than `appContractId`, the /// allowlisted foreign document types and Platform's system contracts diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index e2e61ce2f3..636ed5e043 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -84,6 +84,7 @@ enum DashConnectPlatformError: LocalizedError, Equatable { case loginUnresolved case grantNotRecorded case noFreeKeyId + case tooManyKeysToReplace case otherIdentitiesNotChecked case registrationPending case appConnectEncryptionKeyChanged @@ -182,6 +183,10 @@ enum DashConnectPlatformError: LocalizedError, Equatable { return NSLocalizedString("The active wallet or identity changed. Try again.", comment: "DashConnect") case .noFreeKeyId: return NSLocalizedString("This identity cannot take another key.", comment: "DashConnect") + case .tooManyKeysToReplace: + return NSLocalizedString( + "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again.", + comment: "DashConnect") case .approvalOutOfDate: return NSLocalizedString( "The details of this sign-in changed while it was on screen. Check them and approve again.", @@ -1624,14 +1629,19 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { guard AppConnect.sessionKeyIdsMissing(from: currentPublicKeys, for: superseded).isEmpty else { throw DashConnectPlatformError.identityKeysOutOfDate } - let disable = Array(AppConnect.supersededKeyIds( + let disable = AppConnect.supersededKeyIds( grants: superseded, identityId: identityId, appId: appId, connectionId: connectionId, keeping: reused, currentIdentityPublicKeys: currentPublicKeys - ).prefix(AppConnect.maxKeysDisabledPerUpdate)) + ) + guard AppConnect.fitsOneUpdate(disabling: disable) else { + Self.logger.error( + "🔗 DASHCONNECT :: \(disable.count, privacy: .public) superseded keys do not fit one update; not renewing") + throw DashConnectPlatformError.tooManyKeysToReplace + } // The grants whose every key is off once the update lands. let liveAfterUpdate = Set(currentPublicKeys.filter(AppConnect.isLiveGrantedKey) .map { UInt32(bitPattern: $0.keyId) }).subtracting(disable) diff --git a/DashWallet/ar.lproj/Localizable.strings b/DashWallet/ar.lproj/Localizable.strings index 4e642e1bc5..83e179aae8 100644 --- a/DashWallet/ar.lproj/Localizable.strings +++ b/DashWallet/ar.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/bg.lproj/Localizable.strings b/DashWallet/bg.lproj/Localizable.strings index 6ba8eac719..f5baa60112 100644 --- a/DashWallet/bg.lproj/Localizable.strings +++ b/DashWallet/bg.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ca.lproj/Localizable.strings b/DashWallet/ca.lproj/Localizable.strings index ca0f6ebdd3..47d63e7873 100644 --- a/DashWallet/ca.lproj/Localizable.strings +++ b/DashWallet/ca.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/cs.lproj/Localizable.strings b/DashWallet/cs.lproj/Localizable.strings index 4650a974ab..8b2f487b78 100644 --- a/DashWallet/cs.lproj/Localizable.strings +++ b/DashWallet/cs.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/da.lproj/Localizable.strings b/DashWallet/da.lproj/Localizable.strings index 92823b0f35..d42a75524e 100644 --- a/DashWallet/da.lproj/Localizable.strings +++ b/DashWallet/da.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/de.lproj/Localizable.strings b/DashWallet/de.lproj/Localizable.strings index 1f2f6f24e2..7577e7fbf3 100644 --- a/DashWallet/de.lproj/Localizable.strings +++ b/DashWallet/de.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/el.lproj/Localizable.strings b/DashWallet/el.lproj/Localizable.strings index e5bba03b30..ac8483ec5c 100644 --- a/DashWallet/el.lproj/Localizable.strings +++ b/DashWallet/el.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index bd2da748f7..9e7c8ca76b 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -6135,6 +6135,7 @@ "The details of this sign-in changed while it was on screen. Check them and approve again." = "The details of this sign-in changed while it was on screen. Check them and approve again."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; "This wallet cannot approve the scanned request (%@)." = "This wallet cannot approve the scanned request (%@)."; diff --git a/DashWallet/eo.lproj/Localizable.strings b/DashWallet/eo.lproj/Localizable.strings index 4854d32a61..52e6206d8e 100644 --- a/DashWallet/eo.lproj/Localizable.strings +++ b/DashWallet/eo.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/es.lproj/Localizable.strings b/DashWallet/es.lproj/Localizable.strings index 95864836f7..7b0a6a6fe8 100644 --- a/DashWallet/es.lproj/Localizable.strings +++ b/DashWallet/es.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/et.lproj/Localizable.strings b/DashWallet/et.lproj/Localizable.strings index 053988fb1b..2d6342c49d 100644 --- a/DashWallet/et.lproj/Localizable.strings +++ b/DashWallet/et.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/fa.lproj/Localizable.strings b/DashWallet/fa.lproj/Localizable.strings index badea36546..622161ac85 100644 --- a/DashWallet/fa.lproj/Localizable.strings +++ b/DashWallet/fa.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/fi.lproj/Localizable.strings b/DashWallet/fi.lproj/Localizable.strings index 1ab0a6d154..57cef8223c 100644 --- a/DashWallet/fi.lproj/Localizable.strings +++ b/DashWallet/fi.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/fil.lproj/Localizable.strings b/DashWallet/fil.lproj/Localizable.strings index bfce95328f..7aa0c7cd1e 100644 --- a/DashWallet/fil.lproj/Localizable.strings +++ b/DashWallet/fil.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/fr.lproj/Localizable.strings b/DashWallet/fr.lproj/Localizable.strings index 4b2c29830d..058b8c8f0b 100644 --- a/DashWallet/fr.lproj/Localizable.strings +++ b/DashWallet/fr.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/hr.lproj/Localizable.strings b/DashWallet/hr.lproj/Localizable.strings index f92236da4e..38ed9d1427 100644 --- a/DashWallet/hr.lproj/Localizable.strings +++ b/DashWallet/hr.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/hu.lproj/Localizable.strings b/DashWallet/hu.lproj/Localizable.strings index 7c19f63593..df93f75596 100644 --- a/DashWallet/hu.lproj/Localizable.strings +++ b/DashWallet/hu.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/id.lproj/Localizable.strings b/DashWallet/id.lproj/Localizable.strings index 119f9e582b..af1b4b7041 100644 --- a/DashWallet/id.lproj/Localizable.strings +++ b/DashWallet/id.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/it.lproj/Localizable.strings b/DashWallet/it.lproj/Localizable.strings index abff826290..ed85d2fabd 100644 --- a/DashWallet/it.lproj/Localizable.strings +++ b/DashWallet/it.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ja.lproj/Localizable.strings b/DashWallet/ja.lproj/Localizable.strings index 73582e88be..993167cacc 100644 --- a/DashWallet/ja.lproj/Localizable.strings +++ b/DashWallet/ja.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ko.lproj/Localizable.strings b/DashWallet/ko.lproj/Localizable.strings index 1cbf9b4cf8..c93b6320b2 100644 --- a/DashWallet/ko.lproj/Localizable.strings +++ b/DashWallet/ko.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/mk.lproj/Localizable.strings b/DashWallet/mk.lproj/Localizable.strings index 24569a38d6..5a134ad776 100644 --- a/DashWallet/mk.lproj/Localizable.strings +++ b/DashWallet/mk.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ms.lproj/Localizable.strings b/DashWallet/ms.lproj/Localizable.strings index caf6c6cf96..e82da9599d 100644 --- a/DashWallet/ms.lproj/Localizable.strings +++ b/DashWallet/ms.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/nb.lproj/Localizable.strings b/DashWallet/nb.lproj/Localizable.strings index f56861e3e9..67e9cd1947 100644 --- a/DashWallet/nb.lproj/Localizable.strings +++ b/DashWallet/nb.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/nl.lproj/Localizable.strings b/DashWallet/nl.lproj/Localizable.strings index 157c46e18d..0a10613623 100644 --- a/DashWallet/nl.lproj/Localizable.strings +++ b/DashWallet/nl.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/pl.lproj/Localizable.strings b/DashWallet/pl.lproj/Localizable.strings index 35e2ddd94f..bb1ee2ea34 100644 --- a/DashWallet/pl.lproj/Localizable.strings +++ b/DashWallet/pl.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/pt.lproj/Localizable.strings b/DashWallet/pt.lproj/Localizable.strings index 2882c76cb1..bf5d58b237 100644 --- a/DashWallet/pt.lproj/Localizable.strings +++ b/DashWallet/pt.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ro.lproj/Localizable.strings b/DashWallet/ro.lproj/Localizable.strings index f94eef93eb..b202e929ef 100644 --- a/DashWallet/ro.lproj/Localizable.strings +++ b/DashWallet/ro.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ru.lproj/Localizable.strings b/DashWallet/ru.lproj/Localizable.strings index eab1e7a07d..06e7f71322 100644 --- a/DashWallet/ru.lproj/Localizable.strings +++ b/DashWallet/ru.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sk.lproj/Localizable.strings b/DashWallet/sk.lproj/Localizable.strings index 31a7debb0d..a052622d44 100644 --- a/DashWallet/sk.lproj/Localizable.strings +++ b/DashWallet/sk.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sl.lproj/Localizable.strings b/DashWallet/sl.lproj/Localizable.strings index 1711bc24c5..f870ec9f4a 100644 --- a/DashWallet/sl.lproj/Localizable.strings +++ b/DashWallet/sl.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sl_SI.lproj/Localizable.strings b/DashWallet/sl_SI.lproj/Localizable.strings index 41917a23ac..e360f2db23 100644 --- a/DashWallet/sl_SI.lproj/Localizable.strings +++ b/DashWallet/sl_SI.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sq.lproj/Localizable.strings b/DashWallet/sq.lproj/Localizable.strings index d4dccd9bf4..aa5a9566da 100644 --- a/DashWallet/sq.lproj/Localizable.strings +++ b/DashWallet/sq.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sr.lproj/Localizable.strings b/DashWallet/sr.lproj/Localizable.strings index 3b654f21ab..f44d0fd1e8 100644 --- a/DashWallet/sr.lproj/Localizable.strings +++ b/DashWallet/sr.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sv.lproj/Localizable.strings b/DashWallet/sv.lproj/Localizable.strings index 943704a93b..3afed5e688 100644 --- a/DashWallet/sv.lproj/Localizable.strings +++ b/DashWallet/sv.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/th.lproj/Localizable.strings b/DashWallet/th.lproj/Localizable.strings index a2c55d46da..2e7fd7c4b8 100644 --- a/DashWallet/th.lproj/Localizable.strings +++ b/DashWallet/th.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/tr.lproj/Localizable.strings b/DashWallet/tr.lproj/Localizable.strings index 5e8392a4b9..af011292df 100644 --- a/DashWallet/tr.lproj/Localizable.strings +++ b/DashWallet/tr.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/uk.lproj/Localizable.strings b/DashWallet/uk.lproj/Localizable.strings index fc555a1338..119a4febac 100644 --- a/DashWallet/uk.lproj/Localizable.strings +++ b/DashWallet/uk.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/vi.lproj/Localizable.strings b/DashWallet/vi.lproj/Localizable.strings index e45a9bcfa9..7c8cd636e7 100644 --- a/DashWallet/vi.lproj/Localizable.strings +++ b/DashWallet/vi.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/zh-Hans.lproj/Localizable.strings b/DashWallet/zh-Hans.lproj/Localizable.strings index 10e926d4eb..a3b1324df0 100644 --- a/DashWallet/zh-Hans.lproj/Localizable.strings +++ b/DashWallet/zh-Hans.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/zh-Hant-TW.lproj/Localizable.strings b/DashWallet/zh-Hant-TW.lproj/Localizable.strings index dbc8dcbb01..e570045917 100644 --- a/DashWallet/zh-Hant-TW.lproj/Localizable.strings +++ b/DashWallet/zh-Hant-TW.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/zh.lproj/Localizable.strings b/DashWallet/zh.lproj/Localizable.strings index c33e6f131f..ed85f1bbf5 100644 --- a/DashWallet/zh.lproj/Localizable.strings +++ b/DashWallet/zh.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/zh_TW.lproj/Localizable.strings b/DashWallet/zh_TW.lproj/Localizable.strings index 317dcf035a..fc0b84981c 100644 --- a/DashWallet/zh_TW.lproj/Localizable.strings +++ b/DashWallet/zh_TW.lproj/Localizable.strings @@ -6241,6 +6241,7 @@ "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status." = "The name request succeeded for the original identity. Switch back to the original wallet and network to see its status."; "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; +"This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 136098d82e..f4d48e24a5 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1027,6 +1027,12 @@ final class AppConnectV2LoginTests: XCTestCase { [3], "a damaged record never gets the identity's own keys disabled") } + func testARenewalTurnsOffEveryReplacedKeyInOneUpdateOrNone() { + let max = UInt32(AppConnect.maxKeysDisabledPerUpdate) + XCTAssertTrue(AppConnect.fitsOneUpdate(disabling: Array(1 ... max))) + XCTAssertFalse(AppConnect.fitsOneUpdate(disabling: Array(1 ... max + 1))) + } + // MARK: - Disconnect and the grant record func testADisconnectDisablesEveryAuthKeyOfAV2Grant() { From 5270831ea079b7a84e5a785082228e285cb11510 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 30 Oct 2026 22:10:47 +0200 Subject: [PATCH 02/29] feat(dashconnect): add a confirming connection status A connection whose App Connect v2 identity update was submitted but whose outcome is not known yet. Its keys may be on the identity, so the row offers the disconnect switch as an active one does. Co-Authored-By: Claude Opus 5.5 --- .../Sources/Models/DashConnect/DashConnectModels.swift | 6 ++++++ .../Sources/UI/DashConnect/Components/ConnectionRow.swift | 5 +++-- .../UI/DashConnect/Components/ConnectionStatusBadge.swift | 7 +++++-- DashWallet/ar.lproj/Localizable.strings | 1 + DashWallet/bg.lproj/Localizable.strings | 1 + DashWallet/ca.lproj/Localizable.strings | 1 + DashWallet/cs.lproj/Localizable.strings | 1 + DashWallet/da.lproj/Localizable.strings | 1 + DashWallet/de.lproj/Localizable.strings | 1 + DashWallet/el.lproj/Localizable.strings | 1 + DashWallet/en.lproj/Localizable.strings | 1 + DashWallet/eo.lproj/Localizable.strings | 1 + DashWallet/es.lproj/Localizable.strings | 1 + DashWallet/et.lproj/Localizable.strings | 1 + DashWallet/fa.lproj/Localizable.strings | 1 + DashWallet/fi.lproj/Localizable.strings | 1 + DashWallet/fil.lproj/Localizable.strings | 1 + DashWallet/fr.lproj/Localizable.strings | 1 + DashWallet/hr.lproj/Localizable.strings | 1 + DashWallet/hu.lproj/Localizable.strings | 1 + DashWallet/id.lproj/Localizable.strings | 1 + DashWallet/it.lproj/Localizable.strings | 1 + DashWallet/ja.lproj/Localizable.strings | 1 + DashWallet/ko.lproj/Localizable.strings | 1 + DashWallet/mk.lproj/Localizable.strings | 1 + DashWallet/ms.lproj/Localizable.strings | 1 + DashWallet/nb.lproj/Localizable.strings | 1 + DashWallet/nl.lproj/Localizable.strings | 1 + DashWallet/pl.lproj/Localizable.strings | 1 + DashWallet/pt.lproj/Localizable.strings | 1 + DashWallet/ro.lproj/Localizable.strings | 1 + DashWallet/ru.lproj/Localizable.strings | 1 + DashWallet/sk.lproj/Localizable.strings | 1 + DashWallet/sl.lproj/Localizable.strings | 1 + DashWallet/sl_SI.lproj/Localizable.strings | 1 + DashWallet/sq.lproj/Localizable.strings | 1 + DashWallet/sr.lproj/Localizable.strings | 1 + DashWallet/sv.lproj/Localizable.strings | 1 + DashWallet/th.lproj/Localizable.strings | 1 + DashWallet/tr.lproj/Localizable.strings | 1 + DashWallet/uk.lproj/Localizable.strings | 1 + DashWallet/vi.lproj/Localizable.strings | 1 + DashWallet/zh-Hans.lproj/Localizable.strings | 1 + DashWallet/zh-Hant-TW.lproj/Localizable.strings | 1 + DashWallet/zh.lproj/Localizable.strings | 1 + DashWallet/zh_TW.lproj/Localizable.strings | 1 + 46 files changed, 57 insertions(+), 4 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift b/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift index 80e458826f..b091ae5c79 100644 --- a/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift +++ b/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift @@ -155,9 +155,15 @@ extension DashConnectTokenPurchaseRequest { /// wallet that this wallet has not disabled: the row is made once the key is /// seen on the identity, before its response is published, and stays /// whether or not the publish is confirmed. +/// +/// `confirming` is an App Connect v2 connection whose identity update was +/// submitted and whose outcome is not known yet: its keys may be on the +/// identity, so it can be disconnected like an active one. A build without +/// this status drops the row on load; the grant record stays. enum ConnectionStatus: String, Codable, CaseIterable { case approved case active + case confirming init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() diff --git a/DashWallet/Sources/UI/DashConnect/Components/ConnectionRow.swift b/DashWallet/Sources/UI/DashConnect/Components/ConnectionRow.swift index 00ac7e770c..92308f8d94 100644 --- a/DashWallet/Sources/UI/DashConnect/Components/ConnectionRow.swift +++ b/DashWallet/Sources/UI/DashConnect/Components/ConnectionRow.swift @@ -55,7 +55,7 @@ struct ConnectionRow: View { ConnectionStatusBadge(status: connection.status, updatedAt: connection.updatedAt) .fixedSize(horizontal: true, vertical: false) - if connection.status == .active { + if connection.status == .active || connection.status == .confirming { activeSwitch } } @@ -86,7 +86,8 @@ struct ConnectionRow: View { .frame(maxWidth: .infinity, alignment: .topLeading) } - /// Always reads as on: the row only shows it for an active connection, and + /// Always reads as on: the row only shows it for an active or confirming + /// connection (whose keys may be on the identity), and /// only the off direction is reachable from here. What turning it off does /// depends on the login that made the connection (see /// `DashConnectDataSource.disconnect`): a one-QR connection has the app's diff --git a/DashWallet/Sources/UI/DashConnect/Components/ConnectionStatusBadge.swift b/DashWallet/Sources/UI/DashConnect/Components/ConnectionStatusBadge.swift index 1883126f14..b1c119e758 100644 --- a/DashWallet/Sources/UI/DashConnect/Components/ConnectionStatusBadge.swift +++ b/DashWallet/Sources/UI/DashConnect/Components/ConnectionStatusBadge.swift @@ -53,8 +53,9 @@ struct ConnectionStatusBadge: View { } } - /// Green only once the connection is live; the only other state is - /// `approved`, which reads as neutral blue while it waits for the next scan. + /// Green only once the connection is live; `approved` (waiting for the + /// next scan) and `confirming` (waiting for the network) read as neutral + /// blue. private var dotColor: Color { status == .active ? Color.dash.green : Color.dash.blue } @@ -65,6 +66,8 @@ struct ConnectionStatusBadge: View { return NSLocalizedString("Approved", comment: "DashConnect") case .active: return NSLocalizedString("Active", comment: "DashConnect") + case .confirming: + return NSLocalizedString("Confirming", comment: "DashConnect") } } } diff --git a/DashWallet/ar.lproj/Localizable.strings b/DashWallet/ar.lproj/Localizable.strings index 83e179aae8..da010463d0 100644 --- a/DashWallet/ar.lproj/Localizable.strings +++ b/DashWallet/ar.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "مؤكدة"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "يؤدي التأكيد إلى حفظ ارتفاع البداية %u ومسح بيانات السلسلة لهذه الشبكة عند التشغيل التالي للتطبيق، ثم إعادة تنزيلها وإعادة فحص المرشّحات من ذلك الارتفاع. تحتفظ الجلسة الحالية بحدّ الفحص القديم — أغلق التطبيق وافتحه من جديد لتبدأ."; diff --git a/DashWallet/bg.lproj/Localizable.strings b/DashWallet/bg.lproj/Localizable.strings index f5baa60112..0bc102a8a8 100644 --- a/DashWallet/bg.lproj/Localizable.strings +++ b/DashWallet/bg.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Потвърдена"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Потвърждаването запазва началната височина %u и изчиства данните на веригата за тази мрежа при следващото стартиране на приложението, изтегля ги отново и сканира филтрите наново от тази височина. Текущата сесия запазва стария си праг на сканиране — затворете и отворете приложението отново, за да започне."; diff --git a/DashWallet/ca.lproj/Localizable.strings b/DashWallet/ca.lproj/Localizable.strings index 47d63e7873..a19e4a14db 100644 --- a/DashWallet/ca.lproj/Localizable.strings +++ b/DashWallet/ca.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Confirmada"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "En confirmar es desa l'alçada d'inici %u i es netegen les dades de la cadena d'aquesta xarxa al pròxim inici de l'aplicació, es tornen a baixar i es tornen a escanejar els filtres des d'aquella alçada. La sessió en curs conserva el seu límit d'escaneig antic: tanca i torna a obrir l'aplicació per començar."; diff --git a/DashWallet/cs.lproj/Localizable.strings b/DashWallet/cs.lproj/Localizable.strings index 8b2f487b78..aab6e4af85 100644 --- a/DashWallet/cs.lproj/Localizable.strings +++ b/DashWallet/cs.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Potvrzená"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Potvrzením se uloží počáteční výška %u a při příštím spuštění aplikace se vymažou data řetězce této sítě, znovu se stáhnou a filtry se od této výšky znovu prohledají. Běžící relace si ponechá původní spodní hranici skenování — ukončete a znovu otevřete aplikaci, aby se spustilo."; diff --git a/DashWallet/da.lproj/Localizable.strings b/DashWallet/da.lproj/Localizable.strings index d42a75524e..0f8c62915d 100644 --- a/DashWallet/da.lproj/Localizable.strings +++ b/DashWallet/da.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Bekræftet"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Bekræftelsen gemmer starthøjden %u og rydder dette netværks kædedata ved næste appstart, henter dem igen og scanner filtrene på ny fra den højde. Den kørende session beholder sin gamle scanningsgrænse — luk appen, og åbn den igen for at begynde."; diff --git a/DashWallet/de.lproj/Localizable.strings b/DashWallet/de.lproj/Localizable.strings index 7577e7fbf3..41a5256e7b 100644 --- a/DashWallet/de.lproj/Localizable.strings +++ b/DashWallet/de.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Bestätigt"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Beim Bestätigen wird die Starthöhe %u gespeichert und die Chain-Daten dieses Netzwerks werden beim nächsten App-Start gelöscht, neu heruntergeladen und die Filter ab dieser Höhe erneut durchsucht. Die laufende Sitzung behält ihre bisherige Scan-Untergrenze — beende die App und öffne sie erneut, um zu starten."; diff --git a/DashWallet/el.lproj/Localizable.strings b/DashWallet/el.lproj/Localizable.strings index ac8483ec5c..dcba37e099 100644 --- a/DashWallet/el.lproj/Localizable.strings +++ b/DashWallet/el.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Επιβεβαιωμένη"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Η επιβεβαίωση αποθηκεύει το ύψος έναρξης %u και εκκαθαρίζει τα δεδομένα αλυσίδας αυτού του δικτύου κατά την επόμενη εκκίνηση της εφαρμογής, τα κατεβάζει ξανά και σαρώνει εκ νέου τα φίλτρα από εκείνο το ύψος. Η τρέχουσα συνεδρία διατηρεί το παλιό της κατώφλι σάρωσης — κλείστε και ανοίξτε ξανά την εφαρμογή για να ξεκινήσει."; diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index 9e7c8ca76b..3efe3a3f3a 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -1192,6 +1192,7 @@ /* SPV diagnostics */ "Confirmed" = "Confirmed"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start."; /* ZenLedger */ diff --git a/DashWallet/eo.lproj/Localizable.strings b/DashWallet/eo.lproj/Localizable.strings index 52e6206d8e..e60c1661c2 100644 --- a/DashWallet/eo.lproj/Localizable.strings +++ b/DashWallet/eo.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Konfirmita"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Konfirmo konservas la komencan alton %u kaj forviŝas la ĉendatumojn de ĉi tiu reto ĉe la sekva lanĉo de la aplikaĵo, elŝutas ilin denove kaj reskanas la filtrilojn ekde tiu alto. La kuranta seanco konservas sian malnovan skanan limon — fermu kaj remalfermu la aplikaĵon por komenci."; diff --git a/DashWallet/es.lproj/Localizable.strings b/DashWallet/es.lproj/Localizable.strings index 7b0a6a6fe8..71af2eae14 100644 --- a/DashWallet/es.lproj/Localizable.strings +++ b/DashWallet/es.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Confirmada"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Al confirmar se guarda la altura de origen %u y se borran los datos de la cadena de esta red en el próximo inicio de la app, volviendo a descargarlos y reescaneando los filtros desde esa altura. La sesión en curso conserva su límite de escaneo anterior: cierra y vuelve a abrir la app para empezar."; diff --git a/DashWallet/et.lproj/Localizable.strings b/DashWallet/et.lproj/Localizable.strings index 2d6342c49d..d59d514b1c 100644 --- a/DashWallet/et.lproj/Localizable.strings +++ b/DashWallet/et.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Kinnitatud"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Kinnitamine salvestab alguskõrguse %u ja kustutab selle võrgu ahela andmed rakenduse järgmisel käivitamisel, laadib need uuesti alla ning skannib filtrid sellest kõrgusest uuesti läbi. Käimasolev seanss säilitab oma vana skannimispiiri — alustamiseks sulge rakendus ja ava see uuesti."; diff --git a/DashWallet/fa.lproj/Localizable.strings b/DashWallet/fa.lproj/Localizable.strings index 622161ac85..592bb4e818 100644 --- a/DashWallet/fa.lproj/Localizable.strings +++ b/DashWallet/fa.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "تأییدشده"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "تأیید، ارتفاع آغاز %u را ذخیره می‌کند و در اجرای بعدی برنامه داده‌های زنجیره این شبکه را پاک کرده، دوباره دانلود می‌کند و فیلترها را از آن ارتفاع بازپویش می‌کند. نشست جاری کف پویش قبلی خود را نگه می‌دارد — برنامه را ببندید و دوباره باز کنید تا آغاز شود."; diff --git a/DashWallet/fi.lproj/Localizable.strings b/DashWallet/fi.lproj/Localizable.strings index 57cef8223c..af26649b1b 100644 --- a/DashWallet/fi.lproj/Localizable.strings +++ b/DashWallet/fi.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Vahvistettu"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Vahvistus tallentaa aloituskorkeuden %u ja tyhjentää tämän verkon ketjutiedot sovelluksen seuraavalla käynnistyksellä, lataa ne uudelleen ja skannaa suodattimet uudelleen tuosta korkeudesta. Käynnissä oleva istunto säilyttää vanhan skannausrajansa — sulje sovellus ja avaa se uudelleen aloittaaksesi."; diff --git a/DashWallet/fil.lproj/Localizable.strings b/DashWallet/fil.lproj/Localizable.strings index 7aa0c7cd1e..88e745aab7 100644 --- a/DashWallet/fil.lproj/Localizable.strings +++ b/DashWallet/fil.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Nakumpirma"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Kapag kinumpirma, itatala ang panimulang taas na %u at buburahin ang chain data ng network na ito sa susunod na pagbukas ng app, ida-download itong muli at ise-scan muli ang mga filter mula sa taas na iyon. Pananatilihin ng kasalukuyang session ang dating sahig ng pag-scan — isara at buksang muli ang app para magsimula."; diff --git a/DashWallet/fr.lproj/Localizable.strings b/DashWallet/fr.lproj/Localizable.strings index 058b8c8f0b..0268a04ca2 100644 --- a/DashWallet/fr.lproj/Localizable.strings +++ b/DashWallet/fr.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Confirmée"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Confirmer enregistre la hauteur d'origine %u et efface les données de chaîne de ce réseau au prochain démarrage de l'application, puis les retélécharge et rescanne les filtres à partir de cette hauteur. La session en cours conserve son ancien plancher de scan — quittez et rouvrez l'application pour démarrer."; diff --git a/DashWallet/hr.lproj/Localizable.strings b/DashWallet/hr.lproj/Localizable.strings index 38ed9d1427..4007ed5972 100644 --- a/DashWallet/hr.lproj/Localizable.strings +++ b/DashWallet/hr.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Potvrđena"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Potvrda sprema početnu visinu %u i briše podatke lanca ove mreže pri sljedećem pokretanju aplikacije, ponovno ih preuzima i skenira filtre od te visine. Trenutna sesija zadržava stari prag skeniranja — zatvorite i ponovno otvorite aplikaciju da biste počeli."; diff --git a/DashWallet/hu.lproj/Localizable.strings b/DashWallet/hu.lproj/Localizable.strings index df93f75596..638ab75dfa 100644 --- a/DashWallet/hu.lproj/Localizable.strings +++ b/DashWallet/hu.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Megerősítve"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "A megerősítés elmenti a(z) %u kezdőmagasságot, és az alkalmazás következő indításakor törli e hálózat láncadatait, majd újra letölti azokat, és attól a magasságtól újra átvizsgálja a szűrőket. A futó munkamenet megtartja a régi vizsgálati küszöbét — lépj ki az alkalmazásból, és nyisd meg újra az indításhoz."; diff --git a/DashWallet/id.lproj/Localizable.strings b/DashWallet/id.lproj/Localizable.strings index af1b4b7041..85fb3e5ea9 100644 --- a/DashWallet/id.lproj/Localizable.strings +++ b/DashWallet/id.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Terkonfirmasi"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Mengonfirmasi akan menyimpan tinggi awal %u dan menghapus data rantai jaringan ini pada peluncuran aplikasi berikutnya, mengunduhnya kembali serta memindai ulang filter dari tinggi tersebut. Sesi yang sedang berjalan tetap memakai batas bawah pemindaian lamanya — tutup dan buka kembali aplikasi untuk memulai."; diff --git a/DashWallet/it.lproj/Localizable.strings b/DashWallet/it.lproj/Localizable.strings index ed85d2fabd..8d5aa442a4 100644 --- a/DashWallet/it.lproj/Localizable.strings +++ b/DashWallet/it.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Confermata"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "La conferma salva l'altezza di origine %u e cancella i dati della catena di questa rete al prossimo avvio dell'app, riscaricandoli e riscansionando i filtri da quell'altezza. La sessione in corso mantiene il suo vecchio limite di scansione: chiudi e riapri l'app per iniziare."; diff --git a/DashWallet/ja.lproj/Localizable.strings b/DashWallet/ja.lproj/Localizable.strings index 993167cacc..c98aee61c7 100644 --- a/DashWallet/ja.lproj/Localizable.strings +++ b/DashWallet/ja.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "承認済み"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "確定すると開始ブロック高 %u が保存され、次回のアプリ起動時にこのネットワークのチェーンデータが消去されて再ダウンロードされ、そのブロック高からフィルターが再スキャンされます。実行中のセッションは以前のスキャン下限を保持します。アプリを終了して開き直すと開始されます。"; diff --git a/DashWallet/ko.lproj/Localizable.strings b/DashWallet/ko.lproj/Localizable.strings index c93b6320b2..13eacf1123 100644 --- a/DashWallet/ko.lproj/Localizable.strings +++ b/DashWallet/ko.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "확인됨"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "확인하면 시작 블록 높이 %u가 저장되고, 다음 앱 실행 시 이 네트워크의 체인 데이터가 지워진 뒤 다시 다운로드되어 해당 높이부터 필터를 다시 스캔합니다. 실행 중인 세션은 기존 스캔 하한을 유지합니다. 앱을 종료했다가 다시 열면 시작됩니다."; diff --git a/DashWallet/mk.lproj/Localizable.strings b/DashWallet/mk.lproj/Localizable.strings index 5a134ad776..5a92cba34c 100644 --- a/DashWallet/mk.lproj/Localizable.strings +++ b/DashWallet/mk.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Потврдена"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Потврдувањето ја зачувува почетната височина %u и ги чисти податоците од синџирот на оваа мрежа при следното стартување на апликацијата, ги презема повторно и ги прескенира филтрите од таа височина. Тековната сесија го задржува стариот праг на скенирање — затворете и повторно отворете ја апликацијата за да започне."; diff --git a/DashWallet/ms.lproj/Localizable.strings b/DashWallet/ms.lproj/Localizable.strings index e82da9599d..81756421bd 100644 --- a/DashWallet/ms.lproj/Localizable.strings +++ b/DashWallet/ms.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Disahkan"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Mengesahkan akan menyimpan ketinggian mula %u dan mengosongkan data rantaian rangkaian ini pada pelancaran aplikasi seterusnya, memuat turunnya semula dan mengimbas semula penapis dari ketinggian tersebut. Sesi yang sedang berjalan mengekalkan had bawah imbasan lamanya — tutup dan buka semula aplikasi untuk bermula."; diff --git a/DashWallet/nb.lproj/Localizable.strings b/DashWallet/nb.lproj/Localizable.strings index 67e9cd1947..333c5bdca8 100644 --- a/DashWallet/nb.lproj/Localizable.strings +++ b/DashWallet/nb.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Bekreftet"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Bekreftelsen lagrer starthøyden %u og tømmer kjededataene for dette nettverket ved neste oppstart av appen, laster dem ned på nytt og skanner filtrene på nytt fra den høyden. Den pågående økten beholder den gamle skannegrensen sin — avslutt og åpne appen på nytt for å starte."; diff --git a/DashWallet/nl.lproj/Localizable.strings b/DashWallet/nl.lproj/Localizable.strings index 0a10613623..423b932455 100644 --- a/DashWallet/nl.lproj/Localizable.strings +++ b/DashWallet/nl.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Bevestigd"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Bevestigen slaat starthoogte %u op en wist de ketengegevens van dit netwerk bij de volgende start van de app, waarna ze opnieuw worden gedownload en de filters vanaf die hoogte opnieuw worden gescand. De lopende sessie behoudt zijn oude scanondergrens — sluit de app af en open hem opnieuw om te beginnen."; diff --git a/DashWallet/pl.lproj/Localizable.strings b/DashWallet/pl.lproj/Localizable.strings index bb1ee2ea34..680d150e82 100644 --- a/DashWallet/pl.lproj/Localizable.strings +++ b/DashWallet/pl.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Potwierdzona"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Potwierdzenie zapisuje wysokość początkową %u i czyści dane łańcucha tej sieci przy następnym uruchomieniu aplikacji, pobierając je ponownie i skanując filtry od tej wysokości. Bieżąca sesja zachowuje starą granicę skanowania — zamknij i otwórz aplikację ponownie, aby rozpocząć."; diff --git a/DashWallet/pt.lproj/Localizable.strings b/DashWallet/pt.lproj/Localizable.strings index bf5d58b237..8089a0cb86 100644 --- a/DashWallet/pt.lproj/Localizable.strings +++ b/DashWallet/pt.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Confirmada"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Confirmar salva a altura de origem %u e limpa os dados da cadeia desta rede na próxima inicialização do app, baixando-os novamente e revarrendo os filtros a partir dessa altura. A sessão atual mantém seu piso de varredura antigo — feche e reabra o app para começar."; diff --git a/DashWallet/ro.lproj/Localizable.strings b/DashWallet/ro.lproj/Localizable.strings index b202e929ef..0343c32dcf 100644 --- a/DashWallet/ro.lproj/Localizable.strings +++ b/DashWallet/ro.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Confirmată"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Confirmarea salvează înălțimea de start %u și șterge datele lanțului acestei rețele la următoarea pornire a aplicației, le descarcă din nou și rescanează filtrele de la acea înălțime. Sesiunea curentă își păstrează vechiul prag de scanare — închide și redeschide aplicația pentru a începe."; diff --git a/DashWallet/ru.lproj/Localizable.strings b/DashWallet/ru.lproj/Localizable.strings index 06e7f71322..efd77d2c6f 100644 --- a/DashWallet/ru.lproj/Localizable.strings +++ b/DashWallet/ru.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Подтверждена"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Подтверждение сохранит начальную высоту %u и очистит данные блокчейна этой сети при следующем запуске приложения, после чего они будут загружены заново, а фильтры пересканированы с этой высоты. Текущая сессия сохранит прежнюю границу сканирования — закройте и снова откройте приложение, чтобы начать."; diff --git a/DashWallet/sk.lproj/Localizable.strings b/DashWallet/sk.lproj/Localizable.strings index a052622d44..97f85c470c 100644 --- a/DashWallet/sk.lproj/Localizable.strings +++ b/DashWallet/sk.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Potvrdená"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Potvrdením sa uloží počiatočná výška %u a pri najbližšom spustení aplikácie sa vymažú dáta reťazca tejto siete, znovu sa stiahnu a filtre sa od tejto výšky znovu prehľadajú. Bežiaca relácia si ponechá pôvodnú spodnú hranicu skenovania — ukončite a znovu otvorte aplikáciu, aby sa spustilo."; diff --git a/DashWallet/sl.lproj/Localizable.strings b/DashWallet/sl.lproj/Localizable.strings index f870ec9f4a..c69b7006c9 100644 --- a/DashWallet/sl.lproj/Localizable.strings +++ b/DashWallet/sl.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Potrjena"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Potrditev shrani začetno višino %u in ob naslednjem zagonu aplikacije počisti podatke verige za to omrežje, jih znova prenese ter od te višine znova pregleda filtre. Trenutna seja obdrži svoj stari prag pregledovanja — zaprite in znova odprite aplikacijo, da se začne."; diff --git a/DashWallet/sl_SI.lproj/Localizable.strings b/DashWallet/sl_SI.lproj/Localizable.strings index e360f2db23..8cc5322f66 100644 --- a/DashWallet/sl_SI.lproj/Localizable.strings +++ b/DashWallet/sl_SI.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Potrjena"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Potrditev shrani začetno višino %u in ob naslednjem zagonu aplikacije počisti podatke verige za to omrežje, jih znova prenese ter od te višine znova pregleda filtre. Trenutna seja obdrži svoj stari prag pregledovanja — zaprite in znova odprite aplikacijo, da se začne."; diff --git a/DashWallet/sq.lproj/Localizable.strings b/DashWallet/sq.lproj/Localizable.strings index aa5a9566da..0a25fe93be 100644 --- a/DashWallet/sq.lproj/Localizable.strings +++ b/DashWallet/sq.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "E konfirmuar"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Konfirmimi ruan lartësinë fillestare %u dhe pastron të dhënat e zinxhirit të këtij rrjeti në nisjen e ardhshme të aplikacionit, i shkarkon sërish dhe i riskanon filtrat nga ajo lartësi. Sesioni aktual e mban kufirin e vjetër të skanimit — mbyllni dhe rihapni aplikacionin që të fillojë."; diff --git a/DashWallet/sr.lproj/Localizable.strings b/DashWallet/sr.lproj/Localizable.strings index f44d0fd1e8..79fb65d2c3 100644 --- a/DashWallet/sr.lproj/Localizable.strings +++ b/DashWallet/sr.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Potvrđena"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Potvrda čuva početnu visinu %u i briše podatke lanca ove mreže pri sledećem pokretanju aplikacije, ponovo ih preuzima i skenira filtere od te visine. Aktuelna sesija zadržava stari prag skeniranja — zatvorite i ponovo otvorite aplikaciju da biste počeli."; diff --git a/DashWallet/sv.lproj/Localizable.strings b/DashWallet/sv.lproj/Localizable.strings index 3afed5e688..d3ebfc2884 100644 --- a/DashWallet/sv.lproj/Localizable.strings +++ b/DashWallet/sv.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Bekräftad"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Bekräftelsen sparar starthöjden %u och rensar den här nätverkets kedjedata vid nästa appstart, laddar ner dem igen och skannar om filtren från den höjden. Den pågående sessionen behåller sin gamla skanningsgräns — avsluta och öppna appen igen för att börja."; diff --git a/DashWallet/th.lproj/Localizable.strings b/DashWallet/th.lproj/Localizable.strings index 2e7fd7c4b8..283b6383fe 100644 --- a/DashWallet/th.lproj/Localizable.strings +++ b/DashWallet/th.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "ยืนยันแล้ว"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "การยืนยันจะบันทึกความสูงเริ่มต้น %u และล้างข้อมูลเชนของเครือข่ายนี้เมื่อเปิดแอปครั้งถัดไป แล้วดาวน์โหลดใหม่และสแกนตัวกรองใหม่จากความสูงนั้น เซสชันที่กำลังทำงานอยู่จะยังใช้ขอบล่างการสแกนเดิม — ปิดแล้วเปิดแอปใหม่เพื่อเริ่ม"; diff --git a/DashWallet/tr.lproj/Localizable.strings b/DashWallet/tr.lproj/Localizable.strings index af011292df..9b7046e785 100644 --- a/DashWallet/tr.lproj/Localizable.strings +++ b/DashWallet/tr.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Onaylandı"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Onaylamak, %u başlangıç yüksekliğini kaydeder ve bu ağın zincir verilerini uygulamanın bir sonraki açılışında temizleyerek yeniden indirir ve filtreleri o yükseklikten yeniden tarar. Çalışan oturum eski tarama alt sınırını korur — başlatmak için uygulamadan çıkıp yeniden açın."; diff --git a/DashWallet/uk.lproj/Localizable.strings b/DashWallet/uk.lproj/Localizable.strings index 119a4febac..9dbf8927a3 100644 --- a/DashWallet/uk.lproj/Localizable.strings +++ b/DashWallet/uk.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Підтверджено"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Підтвердження збереже початкову висоту %u та очистить дані ланцюжка цієї мережі під час наступного запуску застосунку, після чого їх буде завантажено заново, а фільтри пересканує з цієї висоти. Поточний сеанс збереже стару межу сканування — закрийте та знову відкрийте застосунок, щоб почати."; diff --git a/DashWallet/vi.lproj/Localizable.strings b/DashWallet/vi.lproj/Localizable.strings index 7c8cd636e7..9173c4ec11 100644 --- a/DashWallet/vi.lproj/Localizable.strings +++ b/DashWallet/vi.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "Đã xác nhận"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "Việc xác nhận sẽ lưu độ cao khởi đầu %u và xoá dữ liệu chuỗi của mạng này ở lần mở ứng dụng sau, tải lại rồi quét lại các bộ lọc từ độ cao đó. Phiên đang chạy vẫn giữ mức sàn quét cũ — hãy thoát và mở lại ứng dụng để bắt đầu."; diff --git a/DashWallet/zh-Hans.lproj/Localizable.strings b/DashWallet/zh-Hans.lproj/Localizable.strings index a3b1324df0..0af8fd58f7 100644 --- a/DashWallet/zh-Hans.lproj/Localizable.strings +++ b/DashWallet/zh-Hans.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "已确认"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "确认后将保存起始区块高度 %u,并在下次启动应用时清除该网络的链数据,重新下载并从该高度重新扫描过滤器。当前会话仍沿用旧的扫描下限——退出并重新打开应用即可开始。"; diff --git a/DashWallet/zh-Hant-TW.lproj/Localizable.strings b/DashWallet/zh-Hant-TW.lproj/Localizable.strings index e570045917..28553a0b7d 100644 --- a/DashWallet/zh-Hant-TW.lproj/Localizable.strings +++ b/DashWallet/zh-Hant-TW.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "已確認"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "確認後將儲存起始區塊高度 %u,並在下次啟動應用程式時清除該網絡的鏈資料,重新下載並從該高度重新掃描過濾器。目前的工作階段仍沿用舊的掃描下限——結束並重新開啟應用程式即可開始。"; diff --git a/DashWallet/zh.lproj/Localizable.strings b/DashWallet/zh.lproj/Localizable.strings index ed85f1bbf5..c64315747b 100644 --- a/DashWallet/zh.lproj/Localizable.strings +++ b/DashWallet/zh.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "已确认"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "确认后将保存起始区块高度 %u,并在下次启动应用时清除该网络的链数据,重新下载并从该高度重新扫描过滤器。当前会话仍沿用旧的扫描下限——退出并重新打开应用即可开始。"; diff --git a/DashWallet/zh_TW.lproj/Localizable.strings b/DashWallet/zh_TW.lproj/Localizable.strings index fc0b84981c..4417373fc2 100644 --- a/DashWallet/zh_TW.lproj/Localizable.strings +++ b/DashWallet/zh_TW.lproj/Localizable.strings @@ -802,6 +802,7 @@ /* SPV diagnostics */ "Confirmed" = "已確認"; +"Confirming" = "Confirming"; "Confirming saves birth height %u and clears this network's chain data at the next app launch, re-downloading it and rescanning filters from that height. The running session keeps its old scan floor — quit and reopen the app to start." = "確認後將儲存起始區塊高度 %u,並在下次啟動應用程式時清除該網絡的鏈資料,重新下載並從該高度重新掃描過濾器。目前的工作階段仍沿用舊的掃描下限——結束並重新開啟應用程式即可開始。"; From 4c2b940f0184232b9afa0d83a98438ed50193135 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 30 Oct 2026 22:10:47 +0200 Subject: [PATCH 03/29] fix(dashconnect): record an App Connect v2 grant before submitting its identity update The grant and a confirming row were written only after the update was seen to land. An update that landed while every follow-up read failed left live keys with no record and no row to disconnect them from. The record is now written first, with every key the update adds. Its outcome is settled without guessing a revision: every key there as added means it landed; an expected id held by another key, or its encryption key under another id, means it never can; an update of this wallet that landed after it means an absent one never will; auth-only keys past their expiry end it. Settling runs at every approval, disconnect and shared-profile revoke, publishes the response of one that landed, and a retry of the same request resubmits the same keys under the same ids. Renewal, disconnect, the shared-profile count, the other-identity check, key-id allocation and the publish-time cleanup know the pending form. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 52 +- .../DashConnect/AppConnectV2Login.swift | 214 +++++++ .../PlatformDashConnectDataSource.swift | 588 ++++++++++++++---- .../DashConnect/AppConnectV2LoginTests.swift | 489 +++++++++++++++ 4 files changed, 1205 insertions(+), 138 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index eb7c768060..5fa7c160d7 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -159,12 +159,15 @@ enum AppConnect { /// `count` ids that no key of the identity has, for one update that /// adds `count` keys: above the highest id while they fit, then the - /// lowest gaps. Nil when the identity cannot take that many. + /// lowest gaps. Nil when the identity cannot take that many. `reserved` + /// ids count as taken: an update that may still land adds keys under + /// them (`reservedKeyIds`). static func freeKeyIds( count: Int, - currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo] + currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], + reserved: Set = [] ) -> [UInt32]? { - let taken = Set(currentIdentityPublicKeys.map { UInt32(bitPattern: $0.keyId) }) + let taken = Set(currentIdentityPublicKeys.map { UInt32(bitPattern: $0.keyId) }).union(reserved) let highest = taken.max() var ids: [UInt32] = [] var next = highest.map { $0 == .max ? nil : $0 + 1 } ?? 0 @@ -187,11 +190,13 @@ enum AppConnect { /// keys included. Platform only refuses an id the identity already has, /// so when the highest is the last id a key can have (a key an app /// registered can be given it) the lowest id no key has is taken - /// instead. `nil` only when every id is taken. + /// instead. `nil` only when every id is taken. `reserved` ids count as + /// taken (`reservedKeyIds`). static func nextKeyId( - currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo] + currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], + reserved: Set = [] ) -> UInt32? { - let taken = Set(currentIdentityPublicKeys.map { UInt32(bitPattern: $0.keyId) }) + let taken = Set(currentIdentityPublicKeys.map { UInt32(bitPattern: $0.keyId) }).union(reserved) let highest = taken.max() ?? 0 guard highest == .max else { return highest + 1 } // The identity holds far fewer keys than there are ids, so this @@ -201,6 +206,13 @@ enum AppConnect { /// The key an app is given: it can only sign for the contract the request /// named, spend up to `totalBudget`, and stops working at `expiresAt`. + /// The ids the v2 records of `identityId` that wait for their update + /// add keys under: a new key under one of them would make that update, + /// or itself, be refused. + static func reservedKeyIds(grants: [AppConnectGrant], identityId: String) -> Set { + Set(grants.filter { $0.identityId == identityId }.flatMap { $0.pendingUpdate?.addedKeys.map(\.keyId) ?? [] }) + } + static func sessionIdentityPubkey( keyId: UInt32, publicKeyHash160: Data, @@ -252,7 +264,7 @@ enum AppConnect { } /// A key's contract bound, as the wallet's store records it. - enum StoredBound: Equatable { + enum StoredBound: Equatable, Codable { case singleContract(Data) case documentType(contractId: Data, name: String) case contractGroup(Data) @@ -448,10 +460,11 @@ enum AppConnect { } } - /// Confirms the unconfirmed records of `identityId` whose key the + /// Confirms the unconfirmed one-QR records of `identityId` whose key the /// identity now holds, and returns them. A record whose key is not there /// stays as it is: the update may still land, and nothing is taken from - /// a view that may be behind. + /// a view that may be behind. An App Connect v2 record waiting for its + /// update is settled by `settlePendingV2Registrations`. static func confirmRegistrations( in grants: inout [AppConnectGrant], identityId: String, @@ -461,6 +474,7 @@ enum AppConnect { var confirmed: [AppConnectGrant] = [] for index in grants.indices where grants[index].identityId == identityId && grants[index].isUnconfirmed + && !grants[index].isPendingV2 && holdsRecordedKey( grants[index], currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: bindings) { grants[index].unconfirmedKeyHash160 = nil @@ -684,9 +698,29 @@ struct AppConnectGrant: Codable, Equatable { /// land. /// `nil` on a record from a build that did not note it. var submittedRevision: UInt64? = nil + /// App Connect v2: the update that registers this grant's keys, from + /// just before it is submitted until its outcome is known + /// (`AppConnect.pendingV2Outcome`). Set together with + /// `unconfirmedKeyHash160`, the primary key's hash, so a build that + /// does not know this field still reads the record as unconfirmed. + var pendingUpdate: PendingV2Update? = nil var isUnconfirmed: Bool { unconfirmedKeyHash160 != nil } + /// An App Connect v2 grant whose update may or may not have landed. + var isPendingV2: Bool { pendingUpdate != nil } + + /// What an App Connect v2 update was submitted with, kept with the + /// grant until its outcome is known. + struct PendingV2Update: Codable, Equatable { + /// Every key the update adds, as it adds it. + var addedKeys: [AppConnect.ExpectedKey] + /// The keys of the connection's earlier grants it disables. + var disabledKeyIds: [UInt32] + /// The records of those grants (`key`) that are done once it lands. + var retiredGrantKeys: [String] + } + /// What makes two records the same grant: one session key given for one /// request. Records are matched on this, never on whole-value equality — /// `publishedAt` does not survive the store's millisecond round trip bit diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 358fb56d46..afc3371966 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -966,6 +966,220 @@ extension AppConnect { return binding.bound == storedBound(of: bounds) } + // MARK: A v2 update whose outcome is not known + + /// A key an App Connect v2 update adds, as it adds it: what + /// `isAddedKey` compares, kept with the grant while the update's outcome + /// is not known. Nothing in it is secret. + struct ExpectedKey: Codable, Equatable { + let keyId: UInt32 + let keyType: KeyType + let purpose: KeyPurpose + let securityLevel: SecurityLevel + let data: Data + let readOnly: Bool + let totalBudget: UInt64? + let expiresAt: UInt64? + let bound: StoredBound? + + init(_ key: ManagedPlatformWallet.IdentityPubkey) { + keyId = key.keyId + keyType = key.keyType + purpose = key.purpose + securityLevel = key.securityLevel + data = key.pubkeyBytes + readOnly = key.readOnly + totalBudget = key.totalBudget + expiresAt = key.expiresAt + bound = key.contractBounds.map(AppConnect.storedBound(of:)) + } + + /// The key as the update submits it. + var identityPubkey: ManagedPlatformWallet.IdentityPubkey { + ManagedPlatformWallet.IdentityPubkey( + keyId: keyId, + keyType: keyType, + purpose: purpose, + securityLevel: securityLevel, + pubkeyBytes: data, + readOnly: readOnly, + contractBounds: bound.map(AppConnect.contractBounds(of:)), + totalBudget: totalBudget, + expiresAt: expiresAt + ) + } + } + + /// The bound a key is registered with, from its stored form. + static func contractBounds(of bound: StoredBound) -> ManagedPlatformWallet.ContractBounds { + switch bound { + case .singleContract(let id): return .singleContract(id: id) + case .documentType(let id, let name): return .singleContractDocumentType(id: id, documentTypeName: name) + case .contractGroup(let id): return .contractGroup(id: id) + } + } + + /// What a view of the identity tells of a v2 update whose outcome was + /// not known. + enum PendingV2Outcome: Equatable { + /// Every key it adds is on the identity, live, as it was added. + case landed + /// It can never land, or what it added is off again. + case cannotLand + /// It may still land, or the view cannot tell. + case unknown + } + + /// The outcome of `pending` by what `keys` (a fresh view of the + /// identity) and `bindings` (the store's bounds) show. No revision is + /// guessed: the SDK does not say which revision it signed. + /// + /// - Every added key there as it was added: it landed. + /// - A key under one of its ids with other data: Platform refuses an + /// update that adds an id the identity has, and never removes a key, + /// so it can never land. The same data under the id, disabled: it + /// landed and is off again. The same data, live, with other limits or + /// another readable bound: the id is another key's. + /// - Its encryption key (ECDSA_SECP256K1, unique on Platform) under + /// another id: it can never land. HASH160 auth keys are not unique, + /// so their data elsewhere says nothing. + /// - `afterOwnUpdate`: `keys` reflects an update of this wallet to the + /// identity that landed after `pending` was recorded. Platform takes an + /// update only at one above the identity's revision, and that update + /// took one above whatever the wallet's copy held, so `pending` cannot + /// land after it: none of its ids there means it never will. + /// - Every added key is an auth key past its expiry (with + /// `clockTolerance`): if it lands, nothing can sign with it. An + /// encryption key has no expiry, so this never ends one that adds it. + /// + /// A key under an expected id with the expected data and no readable + /// bound in the store is unknown: the store may not have loaded it yet. + static func pendingV2Outcome( + of pending: AppConnectGrant.PendingV2Update, + currentIdentityPublicKeys keys: [ManagedIdentity.IdentityPublicKeyInfo], + bindings: [KeyBinding], + nowMilliseconds: Int64, + afterOwnUpdate: Bool = false + ) -> PendingV2Outcome { + var allLanded = true + var anyPresent = false + for expected in pending.addedKeys { + guard let key = keys.first(where: { UInt32(bitPattern: $0.keyId) == expected.keyId }) else { + allLanded = false + continue + } + anyPresent = true + guard key.data == expected.data else { return .cannotLand } + guard key.disabledAt == nil else { return .cannotLand } + let binding = bindings.first { $0.keyId == expected.keyId && $0.data == key.data } + if isAddedKey(key, added: expected.identityPubkey, binding: binding) { continue } + allLanded = false + if expected.bound != nil, binding == nil || binding?.hasUnreadableBound == true { continue } + return .cannotLand + } + if allLanded { return .landed } + let takenElsewhere = pending.addedKeys.contains { expected in + expected.keyType == .ecdsaSecp256k1 && keys.contains { + $0.keyType == .ecdsaSecp256k1 && $0.data == expected.data + && UInt32(bitPattern: $0.keyId) != expected.keyId + } + } + if takenElsewhere { return .cannotLand } + if afterOwnUpdate && !anyPresent { return .cannotLand } + let allExpired = pending.addedKeys.allSatisfy { expected in + expected.purpose == .authentication + && expected.expiresAt.map { !isUnexpired(Int64(clamping: $0), nowMilliseconds: nowMilliseconds) } == true + } + return allExpired ? .cannotLand : .unknown + } + + /// Settles the v2 records of `identityId` whose update's outcome was not + /// known, by `pendingV2Outcome`. A landed one becomes a grant like any + /// other, and the earlier grants its update retired are marked done; one + /// that cannot land is dropped; the rest stay as they are. + static func settlePendingV2Registrations( + in grants: inout [AppConnectGrant], + identityId: String, + currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], + bindings: [KeyBinding], + nowMilliseconds: Int64, + afterOwnUpdate: Bool = false + ) -> (confirmed: [AppConnectGrant], dropped: [AppConnectGrant]) { + var confirmed: [AppConnectGrant] = [] + var dropped: [AppConnectGrant] = [] + var retired: Set = [] + for grant in grants where grant.identityId == identityId { + guard let pending = grant.pendingUpdate else { continue } + switch pendingV2Outcome( + of: pending, currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: bindings, + nowMilliseconds: nowMilliseconds, afterOwnUpdate: afterOwnUpdate + ) { + case .landed: + var settled = grant + settled.pendingUpdate = nil + settled.unconfirmedKeyHash160 = nil + confirmed.append(settled) + retired.formUnion(pending.retiredGrantKeys) + case .cannotLand: + dropped.append(grant) + case .unknown: + break + } + } + let droppedKeys = Set(dropped.map(\.key)) + grants.removeAll { droppedKeys.contains($0.key) } + for settled in confirmed { + guard let index = grants.firstIndex(where: { $0.key == settled.key }) else { continue } + grants[index] = settled + } + markKeysDisabled(in: &grants) { retired.contains($0.key) && !$0.isUnconfirmed } + return (confirmed, dropped) + } + + /// The ids a confirmed record of `identityId` names, and the ids of the + /// keys a v2 record waiting for its update adds that the store shows + /// there as added (same data and bound): those are that grant's, not + /// another app's. An unconfirmed record's id is otherwise not taken: it + /// may belong to another key by now. + static func recordedKeyIds( + of identityId: String, + grants: [AppConnectGrant], + bindings: [KeyBinding] + ) -> Set { + var ids = Set(grants.filter { $0.identityId == identityId && !$0.isUnconfirmed }.flatMap(\.keyIds)) + for grant in grants where grant.identityId == identityId { + for expected in grant.pendingUpdate?.addedKeys ?? [] where bindings.contains(where: { + $0.keyId == expected.keyId && $0.data == expected.data && !$0.hasUnreadableBound + && $0.bound == expected.bound + }) { + ids.insert(expected.keyId) + } + } + return ids + } + + /// For a request whose earlier update's outcome is not known, the ids + /// that update gave the keys this approval derives: each auth key + /// (`authKeyHash160s`, in request order) and each encryption key it + /// registers (`registeredEncryptionKeys`, in slot order) under the id it + /// was added with, so the retry submits the same keys and at most one of + /// the two updates can land. Nil when they are not the same keys. + static func keyIdsForRetry( + of pending: AppConnectGrant.PendingV2Update, + authKeyHash160s: [Data], + registeredEncryptionKeys: [Data] + ) -> (auth: [UInt32], encryption: [UInt32])? { + func id(of data: Data, purpose: (KeyPurpose) -> Bool) -> UInt32? { + pending.addedKeys.first { $0.data == data && purpose($0.purpose) }?.keyId + } + let auth = authKeyHash160s.compactMap { id(of: $0) { $0 == .authentication } } + let encryption = registeredEncryptionKeys.compactMap { id(of: $0) { $0 != .authentication } } + guard auth.count == authKeyHash160s.count, encryption.count == registeredEncryptionKeys.count, + Set(auth + encryption) == Set(pending.addedKeys.map(\.keyId)), + auth.count + encryption.count == pending.addedKeys.count else { return nil } + return (auth, encryption) + } + /// A live auth key a login could have granted: HASH160 and never MASTER, /// so a damaged record cannot get the identity's own keys disabled. static func isLiveGrantedKey(_ key: ManagedIdentity.IdentityPublicKeyInfo) -> Bool { diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 636ed5e043..3c4ea3375d 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1139,7 +1139,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { totalBudget = registered?.totalBudget expiresAt = registered?.expiresAt.map { UInt64(max(0, $0)) } case .absent: - guard let keyId = AppConnect.nextKeyId(currentIdentityPublicKeys: currentPublicKeys) else { + guard let keyId = AppConnect.nextKeyId( + currentIdentityPublicKeys: currentPublicKeys, + reserved: AppConnect.reservedKeyIds(grants: stores.grants.load(), identityId: identityId) + ) else { throw DashConnectPlatformError.noFreeKeyId } let budget = terms.budgetCredits @@ -1308,9 +1311,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // gone, so a login is the only moment left to finish that cleanup. await deleteAppConnectResponses( where: { - guard $0.identityId == identityId else { return false } - return $0.keyDisabled == true - || ($0.appContractId == appContractId && $0.values.appEphemeralPubKeyHash != requestHash) + Self.isLeftoverResponse( + $0, identityId: identityId, appContractId: appContractId, requestHash: requestHash) }, responseContractId: responseContractId, context: context, @@ -1362,6 +1364,21 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } } + /// Whether a login publishing the response to `requestHash` cleans up + /// `grant`'s response: one of this identity's whose key is off, or an + /// earlier one of the same app. An unconfirmed record has never had a + /// response published, so there is none to look for. + static func isLeftoverResponse( + _ grant: AppConnectGrant, + identityId: String, + appContractId: String, + requestHash: String + ) -> Bool { + guard grant.identityId == identityId, !grant.isUnconfirmed else { return false } + return grant.keyDisabled == true + || (grant.appContractId == appContractId && grant.values.appEphemeralPubKeyHash != requestHash) + } + /// App Connect request v2 (Yappr `docs/APP_CONNECT_PROFILE.md`): one key /// per auth binding, the identity's encryption key for the app, and the /// previous grant on the same connection disabled, all in one @@ -1452,6 +1469,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { defer { firstCurrentKeysRead.cancel() } let currentPublicKeys = try await refreshedIdentityPublicKeys(context: context) let bindings = try Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer) + // This identity's records whose update's outcome was not known are + // settled first: one that landed is a grant like any other below, and + // one that cannot land frees its ids. + await confirmRegistrations( + identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, + modelContainer: context.modelContainer, in: stores, publishing: (context, signer)) // Which rotations to derive depends on the keys the identity has. for grant in plan.encryption { encryptionKeys.append(try await MainActor.run { @@ -1619,14 +1642,19 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } // Wallet rule 8: this connection's previous grant goes in the same - // update. A key of it the fetched list lacks means the list is - // behind, and it could not be shown to be off. + // update. A key of a confirmed one the fetched list lacks means the + // list is behind, and it could not be shown to be off. A previous + // grant whose own update's outcome is not known has its keys that + // are there replaced like any other; the rest are settled once this + // update lands. func isSuperseded(_ grant: AppConnectGrant) -> Bool { connectionId != nil && grant.identityId == identityId && grant.appContractId == appId && grant.connectionId == connectionId && !isGrantForRequest(grant) } let superseded = stores.grants.load().filter(isSuperseded) - guard AppConnect.sessionKeyIdsMissing(from: currentPublicKeys, for: superseded).isEmpty else { + guard AppConnect.sessionKeyIdsMissing( + from: currentPublicKeys, for: superseded.filter { !$0.isUnconfirmed } + ).isEmpty else { throw DashConnectPlatformError.identityKeysOutOfDate } let disable = AppConnect.supersededKeyIds( @@ -1637,85 +1665,72 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { keeping: reused, currentIdentityPublicKeys: currentPublicKeys ) - guard AppConnect.fitsOneUpdate(disabling: disable) else { - Self.logger.error( - "🔗 DASHCONNECT :: \(disable.count, privacy: .public) superseded keys do not fit one update; not renewing") - throw DashConnectPlatformError.tooManyKeysToReplace - } - // The grants whose every key is off once the update lands. + // The confirmed grants whose every key is off once the update lands. let liveAfterUpdate = Set(currentPublicKeys.filter(AppConnect.isLiveGrantedKey) .map { UInt32(bitPattern: $0.keyId) }).subtracting(disable) - let retiredGrantKeys = Set(superseded.filter { !$0.keyIds.contains(where: liveAfterUpdate.contains) }.map(\.key)) + let retiredGrantKeys = Set(superseded + .filter { !$0.isUnconfirmed && !$0.keyIds.contains(where: liveAfterUpdate.contains) } + .map(\.key)) - let newKeyCount = authKeyIds.filter { $0 == nil }.count + encryptionSlots.filter { $0.keyId == nil }.count - guard var freeKeyIds = AppConnect.freeKeyIds(count: newKeyCount, currentIdentityPublicKeys: currentPublicKeys)? - .makeIterator() else { - throw DashConnectPlatformError.noFreeKeyId - } var add: [ManagedPlatformWallet.IdentityPubkey] = [] var signingKeys: [(publicKey: Data, privateKey: Data)] = [] - for (index, grant) in plan.auth.enumerated() where authKeyIds[index] == nil { - guard let keyId = freeKeyIds.next() else { throw DashConnectPlatformError.noFreeKeyId } - add.append(AppConnect.authIdentityPubkey( - grant, keyId: keyId, publicKeyHash160: authKeys[index].publicKeyHash160)) - signingKeys.append((authKeys[index].publicKeyHash160, authKeys[index].privateKey)) - authKeyIds[index] = keyId - } - for slot in encryptionSlots.indices where encryptionSlots[slot].keyId == nil { - guard let keyId = freeKeyIds.next() else { throw DashConnectPlatformError.noFreeKeyId } - let key = encryptionKeys[encryptionSlots[slot].keyIndex][encryptionSlots[slot].derivedIndex] - add.append(AppConnect.encryptionIdentityPubkey( - plan.encryption[encryptionSlots[slot].keyIndex], keyId: keyId, publicKey: key.publicKey)) - signingKeys.append((key.publicKey, key.privateKey)) - encryptionSlots[slot].keyId = keyId - } defer { for index in signingKeys.indices { Self.zero(&signingKeys[index].privateKey) } } - - if !add.isEmpty || !disable.isEmpty { - Self.logger.info( - "🔗 DASHCONNECT :: registering \(add.count, privacy: .public) key(s), disabling \(disable.count, privacy: .public)") - do { - try await signer.withAdditionalSigningKeys(signingKeys) { - try await context.wallet.updateIdentity( - identityId: context.identityId, - addPublicKeys: add, - disablePublicKeyIds: disable, - signer: signer - ) - } - } catch { - // An update can land without confirming, and the node asked - // next may not have it yet. If every new key shows up and - // every replaced key is off, it went through. - // Each new key has to be there as it was added, bound as the - // store reads it: a key under its id with the same payload - // but another bound is another request's, and is not sent. - func landed(_ keys: [ManagedIdentity.IdentityPublicKeyInfo], _ bindings: [AppConnect.KeyBinding]) -> Bool { - add.allSatisfy { new in keys.contains { key in - AppConnect.isAddedKey( - key, added: new, - binding: bindings.first { $0.keyId == new.keyId && $0.data == key.data }) - } } && disable.allSatisfy { id in keys.contains { - UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil - } } - } - var confirmed = false - for attempt in 0 ..< 3 where !confirmed { - if attempt > 0 { try? await Task.sleep(nanoseconds: 3_000_000_000) } - if let refreshed = try? await refreshedIdentityPublicKeys(context: context), - let refreshedBindings = try? Self.storedKeyBindings( - identityId: identityId, modelContainer: context.modelContainer) { - confirmed = landed(refreshed, refreshedBindings) - } + // An earlier approval of this request whose update's outcome is not + // known is submitted again with the same keys under the same ids, so + // at most one of the two updates can land. + let pendingRetry = stores.grants.load().first { isGrantForRequest($0) && $0.isPendingV2 } + if let pending = pendingRetry?.pendingUpdate { + guard reused.isEmpty else { throw DashConnectPlatformError.identityKeysOutOfDate } + let registered = encryptionSlots.indices.filter { encryptionSlots[$0].keyId == nil } + func encryptionKey(_ slot: Int) -> AppConnect.DerivedEncryptionKey { + encryptionKeys[encryptionSlots[slot].keyIndex][encryptionSlots[slot].derivedIndex] + } + guard let ids = AppConnect.keyIdsForRetry( + of: pending, + authKeyHash160s: authKeys.map(\.publicKeyHash160), + registeredEncryptionKeys: registered.map { encryptionKey($0).publicKey } + ) else { + throw DashConnectPlatformError.sessionKeyUnusable + } + for (index, keyId) in ids.auth.enumerated() { authKeyIds[index] = keyId } + for (slot, keyId) in zip(registered, ids.encryption) { encryptionSlots[slot].keyId = keyId } + add = pending.addedKeys.map(\.identityPubkey) + for key in add { + if let auth = authKeys.first(where: { $0.publicKeyHash160 == key.pubkeyBytes }) { + signingKeys.append((auth.publicKeyHash160, auth.privateKey)) + } else if let slot = registered.first(where: { encryptionKey($0).publicKey == key.pubkeyBytes }) { + signingKeys.append((encryptionKey(slot).publicKey, encryptionKey(slot).privateKey)) } - guard confirmed else { throw error } - Self.logger.info("🔗 DASHCONNECT :: the identity update landed without confirming") } - Self.logger.info("🔗 DASHCONNECT :: identity updated") + } else { + let newKeyCount = authKeyIds.filter { $0 == nil }.count + encryptionSlots.filter { $0.keyId == nil }.count + guard var freeKeyIds = AppConnect.freeKeyIds( + count: newKeyCount, + currentIdentityPublicKeys: currentPublicKeys, + reserved: AppConnect.reservedKeyIds(grants: stores.grants.load(), identityId: identityId) + )?.makeIterator() else { + throw DashConnectPlatformError.noFreeKeyId + } + for (index, grant) in plan.auth.enumerated() where authKeyIds[index] == nil { + guard let keyId = freeKeyIds.next() else { throw DashConnectPlatformError.noFreeKeyId } + add.append(AppConnect.authIdentityPubkey( + grant, keyId: keyId, publicKeyHash160: authKeys[index].publicKeyHash160)) + signingKeys.append((authKeys[index].publicKeyHash160, authKeys[index].privateKey)) + authKeyIds[index] = keyId + } + for slot in encryptionSlots.indices where encryptionSlots[slot].keyId == nil { + guard let keyId = freeKeyIds.next() else { throw DashConnectPlatformError.noFreeKeyId } + let key = encryptionKeys[encryptionSlots[slot].keyIndex][encryptionSlots[slot].derivedIndex] + add.append(AppConnect.encryptionIdentityPubkey( + plan.encryption[encryptionSlots[slot].keyIndex], keyId: keyId, publicKey: key.publicKey)) + signingKeys.append((key.publicKey, key.privateKey)) + encryptionSlots[slot].keyId = keyId + } } // Slots: the auth keys in request order, then the encryption keys - // that are sent. + // that are sent. The response is sealed before the update is + // submitted, so the record written first carries it. var slots = authKeys.map(\.privateKey) + encryptionSlots.map { encryptionKeys[$0.keyIndex][$0.derivedIndex].privateKey } defer { for index in slots.indices { Self.zero(&slots[index]) } } var walletEphemeralPrivateKey = try Self.generateEphemeralPrivateKey() @@ -1731,20 +1746,16 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { ).toHexString() ) - // From here the keys are on the identity. Record them, and show the - // connection, before anything else can fail. The grants this one - // replaces are done: their keys are off. A grant already recorded - // for this request keeps its values: if an earlier publish landed + // The record is written before the update is submitted: an update + // can land and still report a failure, and keys with no record and + // no row could not be disconnected. A grant already recorded for + // this request keeps its values: if an earlier publish landed // without confirming, those are the ones on Platform. let grantedKeyIds = authKeyIds.compactMap { $0 } - let sentEncryptionKeyIds = encryptionSlots.compactMap(\.keyId) let primary = plan.auth[0] - let grant = updateGrants(in: stores) { grants -> AppConnectGrant in - AppConnect.markKeysDisabled(in: &grants) { retiredGrantKeys.contains($0.key) } - if let existing = grants.first(where: { isGrantForRequest($0) && $0.sessionKeyId == grantedKeyIds[0] }) { - return existing - } - let new = AppConnectGrant( + var record = pendingRetry + ?? stores.grants.load().first { isGrantForRequest($0) && !$0.isUnconfirmed && $0.sessionKeyId == grantedKeyIds[0] } + ?? AppConnectGrant( identityId: identityId, appContractId: appId, documentId: nil, @@ -1755,18 +1766,99 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { publishedAt: now(), additionalKeyIds: Array(grantedKeyIds.dropFirst()), connectionId: connectionId, - encryptionKeyIds: sentEncryptionKeyIds + encryptionKeyIds: encryptionSlots.compactMap(\.keyId) ) - grants.append(new) - return new + if !add.isEmpty { + record.unconfirmedKeyHash160 = authKeys[0].publicKeyHash160.toHexString() + record.pendingUpdate = AppConnectGrant.PendingV2Update( + addedKeys: add.map(AppConnect.ExpectedKey.init), + disabledKeyIds: disable, + retiredGrantKeys: retiredGrantKeys.sorted()) } let connection = Self.makeConnection( preview: consent, status: .active, updatedAt: now(), loginKind: .oneQR) + let modelContainer = context.modelContainer + let grant = try await Self.registerAppConnectV2Grant( + record, + add: add, + disable: disable, + retiredGrantKeys: retiredGrantKeys, + grants: stores.grants, + nowMilliseconds: { Int64(AppConnect.milliseconds(self.now())) }, + showRow: { + // A record that waits for its update shows the app as + // confirming, unless its row is already active. + let confirming = Self.makeConnection( + preview: consent, status: .confirming, updatedAt: now(), loginKind: .oneQR) + let waits = record.isPendingV2 + await updateRows(in: stores) { rows in + guard waits else { return rows.filter { $0.id != connection.id } + [connection] } + if rows.contains(where: { $0.id == connection.id && $0.status == .active }) { return rows } + return rows.filter { $0.id != connection.id } + [confirming] + } + }, + submit: { + try await signer.withAdditionalSigningKeys(signingKeys) { + try await context.wallet.updateIdentity( + identityId: context.identityId, + addPublicKeys: add, + disablePublicKeyIds: disable, + signer: signer + ) + } + }, + reread: { + guard let keys = try? await refreshedIdentityPublicKeys(context: context), + let bindings = try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer) + else { return nil } + return (keys, bindings) + }, + pause: { _ in try? await Task.sleep(nanoseconds: 3_000_000_000) }, + onDropped: { + let grants = stores.grants.load() + let bindings = (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) ?? [] + await updateRows(in: stores) { + Self.rowsAfterDropping(appIds: [appId], grants: grants, bindings: bindings, rows: $0) + } + } + ) + + // From here the keys are on the identity. await updateRows(in: stores) { rows in rows.filter { $0.id != connection.id } + [connection] } + // Every record of this identity still waiting for its update was + // written before this one landed, so this update settles them. A + // previous grant of this connection that turned out to have landed + // holds keys this login replaces: they are turned off too. + if !add.isEmpty || !disable.isEmpty, + stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { + let landed = await settleAfterOwnUpdate( + context: context, + stores: stores, + reflects: { keys in + add.allSatisfy { new in keys.contains { + UInt32(bitPattern: $0.keyId) == new.keyId && $0.data == new.pubkeyBytes + } } && disable.allSatisfy { id in keys.contains { + UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil + } } + }, + signer: signer, + exceptAppId: appId) + let late = (landed ?? []).filter(isSuperseded) + if !late.isEmpty { + let lateKeys = Set(late.map(\.key)) + do { + try await disableKeys(Array(Set(late.flatMap(\.keyIds))).sorted(), context: context, signer: signer) + updateGrants(in: stores) { AppConnect.markKeysDisabled(in: &$0) { lateKeys.contains($0.key) } } + } catch { + Self.logger.error("🔗 DASHCONNECT :: keys of a replaced grant that landed late are still live — \(error.localizedDescription, privacy: .public)") + } + } + } + try await publishAppConnectResponse( grant: grant, appEphemeralPubKeyHash: plan.appEphemeralPubKeyHash, @@ -1777,6 +1869,113 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { return connection } + /// The registration step of an App Connect v2 approval: `record` is + /// written, and `showRow` run, before `submit` sends the identity update + /// that adds `add` and disables `disable`, so keys that land are never + /// without a record and a row to disconnect them from. A record that adds + /// keys carries them (`pendingUpdate`) until the outcome is known. + /// + /// Nothing is written or submitted when `disable` does not fit one + /// update: a renewal that left some of the replaced keys on would report + /// a replacement that did not happen. A disconnect takes them in batches. + /// + /// On success the record is confirmed and the grants in + /// `retiredGrantKeys` are marked done. A failure may still have landed: + /// up to three reads (`reread`, `pause` before the second and third) + /// settle it by `AppConnect.pendingV2Outcome`. Landed confirms as on + /// success; cannot land drops the record, runs `onDropped` and rethrows; + /// unknown keeps the record and rethrows. A record that adds nothing is + /// confirmed from the start and only waits for its disables. + /// + /// Returns the grant as recorded: an earlier confirmed record of the same + /// grant keeps its values. + static func registerAppConnectV2Grant( + _ record: AppConnectGrant, + add: [ManagedPlatformWallet.IdentityPubkey], + disable: [UInt32], + retiredGrantKeys: Set, + grants: any AppConnectResponseStore, + nowMilliseconds: () -> Int64, + showRow: () async -> Void, + submit: () async throws -> Void, + reread: () async -> (keys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [AppConnect.KeyBinding])?, + pause: (Int) async -> Void, + onDropped: () async -> Void + ) async throws -> AppConnectGrant { + guard AppConnect.fitsOneUpdate(disabling: disable) else { + logger.error("🔗 DASHCONNECT :: \(disable.count, privacy: .public) superseded keys do not fit one update; not renewing") + throw DashConnectPlatformError.tooManyKeysToReplace + } + var stored = grants.load() + if let existing = stored.first(where: { $0.key == record.key }), !existing.isUnconfirmed, !record.isUnconfirmed { + // Kept as it is: if its publish landed without confirming, its + // values are the ones on Platform. + } else { + stored.removeAll { $0.key == record.key } + stored.append(record) + grants.save(stored) + } + guard grants.load().contains(where: { $0.key == record.key }) else { + logger.error("🔗 DASHCONNECT :: the App Connect grant could not be recorded; not registering it") + throw DashConnectPlatformError.grantStoreUnavailable + } + await showRow() + + func confirm() -> AppConnectGrant { + var all = grants.load() + guard let index = all.firstIndex(where: { $0.key == record.key }) else { return record } + all[index].pendingUpdate = nil + all[index].unconfirmedKeyHash160 = nil + let confirmed = all[index] + AppConnect.markKeysDisabled(in: &all) { retiredGrantKeys.contains($0.key) && !$0.isUnconfirmed } + grants.save(all) + return confirmed + } + guard !add.isEmpty || !disable.isEmpty else { return confirm() } + + logger.info("🔗 DASHCONNECT :: registering \(add.count, privacy: .public) key(s), disabling \(disable.count, privacy: .public)") + do { + try await submit() + } catch { + for attempt in 0 ..< 3 { + if attempt > 0 { await pause(attempt) } + guard let view = await reread() else { continue } + let disabled = disable.allSatisfy { id in view.keys.contains { + UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil + } } + guard let pending = grants.load().first(where: { $0.key == record.key })?.pendingUpdate else { + // Nothing added: the update landed when its disables show. + if disabled { + logger.info("🔗 DASHCONNECT :: the identity update landed without confirming") + return confirm() + } + continue + } + switch AppConnect.pendingV2Outcome( + of: pending, currentIdentityPublicKeys: view.keys, bindings: view.bindings, + nowMilliseconds: nowMilliseconds() + ) { + case .landed: + logger.info("🔗 DASHCONNECT :: the identity update landed without confirming") + return confirm() + case .cannotLand: + logger.info("🔗 DASHCONNECT :: the identity update can no longer land; its record is dropped") + var all = grants.load() + all.removeAll { $0.key == record.key } + grants.save(all) + await onDropped() + throw error + case .unknown: + continue + } + } + logger.error("🔗 DASHCONNECT :: the identity update's outcome is not known; its record stays until it is") + throw error + } + logger.info("🔗 DASHCONNECT :: identity updated") + return confirm() + } + /// This identity's response to one request, with the values it has on /// Platform, or `nil` when there is none; a failed lookup or a response /// that cannot be read throws. @@ -2063,14 +2262,25 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// live and has to be reachable from Connections. That also covers a /// grant confirmed earlier whose row was never saved, or was saved by a /// two-QR login. + /// + /// A v2 record whose update's outcome was not known is settled by + /// `AppConnect.settlePendingV2Registrations` (`afterOwnUpdate` as there): + /// one that cannot land is dropped, and its row with it when nothing else + /// holds it (`rowsAfterDropping`). With `publishing`, the response of each + /// one that landed is published, except for `exceptAppId`'s; best effort, + /// as a later login retries it. Returns the v2 grants confirmed. + @discardableResult private func confirmRegistrations( identityId: String, currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], modelContainer: ModelContainer, - in stores: Stores - ) async { + in stores: Stores, + afterOwnUpdate: Bool = false, + publishing: (context: Context, signer: KeychainSigner)? = nil, + exceptAppId: String? = nil + ) async -> [AppConnectGrant] { guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) - else { return } + else { return [] } // Without the store's bindings no unconfirmed record is confirmed, // and a confirmed one does not need them. let bindings = (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) ?? [] @@ -2084,15 +2294,97 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.logger.info("🔗 DASHCONNECT :: \(confirmed.count, privacy: .public) unconfirmed session key(s) found on the identity") } } + var confirmedV2: [AppConnectGrant] = [] + if stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { + let nowMilliseconds = Int64(AppConnect.milliseconds(now())) + let settled = updateGrants(in: stores) { grants in + AppConnect.settlePendingV2Registrations( + in: &grants, identityId: identityId, currentIdentityPublicKeys: currentIdentityPublicKeys, + bindings: bindings, nowMilliseconds: nowMilliseconds, afterOwnUpdate: afterOwnUpdate) + } + confirmedV2 = settled.confirmed + if !settled.confirmed.isEmpty { + Self.logger.info("🔗 DASHCONNECT :: \(settled.confirmed.count, privacy: .public) App Connect update(s) found to have landed") + } + if !settled.dropped.isEmpty { + Self.logger.info("🔗 DASHCONNECT :: dropping \(settled.dropped.count, privacy: .public) App Connect update(s) that can no longer land") + let droppedAppIds = Set(settled.dropped.map(\.appContractId)) + let grants = stores.grants.load() + await updateRows(in: stores) { rows in + Self.rowsAfterDropping(appIds: droppedAppIds, grants: grants, bindings: bindings, rows: rows) + } + } + } let appIds = Self.appIdsWithoutTheirOneQRRow( grants: stores.grants.load(), identityId: identityId, currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: bindings, rows: rows(in: stores)) - guard !appIds.isEmpty else { return } - Self.logger.info("🔗 DASHCONNECT :: \(appIds.count, privacy: .public) app(s) with a live session key get their row back") - let confirmedAt = now() - await updateRows(in: stores) { rows in - Self.rowsAfterConfirming(appIds: appIds, in: rows, at: confirmedAt) + if !appIds.isEmpty { + Self.logger.info("🔗 DASHCONNECT :: \(appIds.count, privacy: .public) app(s) with a live session key get their row back") + let confirmedAt = now() + await updateRows(in: stores) { rows in + Self.rowsAfterConfirming(appIds: appIds, in: rows, at: confirmedAt) + } + } + if let publishing, let responseContractId = Self.decodeIdentifier(AppConnect.contractId) { + for confirmed in confirmedV2 where confirmed.appContractId != exceptAppId { + guard let grant = stores.grants.load().first(where: { $0.key == confirmed.key }), + let requestHash = AppConnect.data(fromHex: grant.values.appEphemeralPubKeyHash) else { continue } + do { + try await publishAppConnectResponse( + grant: grant, appEphemeralPubKeyHash: requestHash, responseContractId: responseContractId, + context: publishing.context, signer: publishing.signer) + } catch { + Self.logger.error("🔗 DASHCONNECT :: the response of a recovered App Connect grant was not published — \(error.localizedDescription, privacy: .public)") + } + } + } + return confirmedV2 + } + + /// After an update of this wallet to the identity landed: one more read + /// of the identity, which also writes what it shows to the store, and, + /// when it shows that update (`reflects`), every v2 record of the + /// identity waiting for its outcome is settled by it (`afterOwnUpdate`, + /// see `AppConnect.pendingV2Outcome`). Returns the v2 grants confirmed, + /// or nil when the read failed or is behind that update. + private func settleAfterOwnUpdate( + context: Context, + stores: Stores, + reflects: ([ManagedIdentity.IdentityPublicKeyInfo]) -> Bool, + signer: KeychainSigner, + exceptAppId: String? = nil + ) async -> [AppConnectGrant]? { + guard let keys = try? await refreshedIdentityPublicKeys(context: context), reflects(keys) else { return nil } + return await confirmRegistrations( + identityId: context.identityId.toBase58String(), currentIdentityPublicKeys: keys, + modelContainer: context.modelContainer, in: stores, afterOwnUpdate: true, + publishing: (context, signer), exceptAppId: exceptAppId) + } + + /// `rows` once the v2 records of `appIds` that were waiting for their + /// update are dropped: a row still `.confirming` stays while another + /// such record of the app does, becomes active when a confirmed grant of + /// the app or a live key the store shows bound to it remains, and goes + /// otherwise. Any other row is left as it is. + static func rowsAfterDropping( + appIds: Set, + grants: [AppConnectGrant], + bindings: [AppConnect.KeyBinding], + rows: [DAppConnection] + ) -> [DAppConnection] { + rows.compactMap { row in + guard appIds.contains(row.id), row.status == .confirming else { return row } + let appGrants = grants.filter { $0.appContractId == row.id } + if appGrants.contains(where: \.isPendingV2) { return row } + let appContract = Data.identifier(fromBase58: row.id) + let holdsKey = appGrants.contains { !$0.isUnconfirmed && $0.keyDisabled != true } + || bindings.contains { !$0.isDisabled && appContract != nil && $0.singleContractId == appContract } + guard holdsKey else { return nil } + var active = DAppConnection( + id: row.id, name: row.name, url: row.url, status: .active, updatedAt: row.updatedAt, loginKind: .oneQR) + active.scope = row.scope + return active } } @@ -2354,7 +2646,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let keyCount = (try? Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer)) .map { bindings in AppConnect.storedSharedProfileKeyIds( - recordedKeyIds: Self.recordedKeyIds(of: identityId, in: stores), bindings: bindings, + recordedKeyIds: Self.recordedKeyIds(of: identityId, in: stores, bindings: bindings), + bindings: bindings, nowMilliseconds: Int64(AppConnect.milliseconds(now()))).count } return SharedProfileAccess(keyCount: keyCount, scope: stores.scope, identityId: identityId) @@ -2368,11 +2661,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// read for that no confirmed grant record names, whichever app was given /// it. The set is read again from Platform after the PIN prompt; nothing /// from the count is reused. Nothing is turned off while that read cannot - /// be trusted (`AppConnect.sharedProfileKeyIdsToDisable`). - /// TODO(app-connect-v2-pending-record): a v2 approval writes its record - /// only once its update is seen to land, so the profile key of one whose - /// outcome was unknown when it failed has no record and is disabled here - /// like any other. + /// be trusted (`AppConnect.sharedProfileKeyIdsToDisable`). A v2 grant + /// whose update's outcome is not known is settled first; a key it added + /// that the store shows as added counts as that grant's. private func revokeSharedProfileAccessInTurn(_ access: SharedProfileAccess) async throws -> Int { guard let stores = await showActiveWalletRows() else { throw DashConnectPlatformError.noWallet @@ -2388,14 +2679,16 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { context = try await contextAfterAuthorization(matching: context) let identityId = context.identityId.toBase58String() let currentPublicKeys = try await refreshedIdentityPublicKeys(context: context) + let signer = KeychainSigner(modelContainer: context.modelContainer) // A registration whose key has turned up is confirmed, and its key is // then the app's, not shared. await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores) + modelContainer: context.modelContainer, in: stores, publishing: (context, signer)) + let bindings = try Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer) guard let keyIds = AppConnect.sharedProfileKeyIdsToDisable( - recordedKeyIds: Self.recordedKeyIds(of: identityId, in: stores), - bindings: try Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer), + recordedKeyIds: Self.recordedKeyIds(of: identityId, in: stores, bindings: bindings), + bindings: bindings, currentIdentityPublicKeys: currentPublicKeys, nowMilliseconds: Int64(AppConnect.milliseconds(now())) ) else { @@ -2403,17 +2696,27 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } guard !keyIds.isEmpty else { return 0 } Self.logger.info("🔗 DASHCONNECT :: disabling \(keyIds.count, privacy: .public) shared profile key(s)") - try await disableKeys(keyIds, context: context, signer: KeychainSigner(modelContainer: context.modelContainer)) + try await disableKeys(keyIds, context: context, signer: signer) // The reload writes the disabled keys to the store the count is read - // from. The keys are off either way. - _ = try? await refreshedIdentityPublicKeys(context: context) + // from, and settles the v2 records still waiting for their update. + // The keys are off either way. + _ = await settleAfterOwnUpdate( + context: context, stores: stores, + reflects: { keys in keyIds.allSatisfy { id in keys.contains { + UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil + } } }, + signer: signer) return keyIds.count } - /// The key ids this identity's confirmed grant records name. An - /// unconfirmed record's id may belong to another key by now. - private static func recordedKeyIds(of identityId: String, in stores: Stores) -> Set { - Set(stores.grants.load().filter { $0.identityId == identityId && !$0.isUnconfirmed }.flatMap(\.keyIds)) + /// The key ids this identity's grant records name + /// (`AppConnect.recordedKeyIds`). + private static func recordedKeyIds( + of identityId: String, + in stores: Stores, + bindings: [AppConnect.KeyBinding] + ) -> Set { + AppConnect.recordedKeyIds(of: identityId, grants: stores.grants.load(), bindings: bindings) } private func disconnectInTurn(id: String, scope: String?) async throws { @@ -2435,7 +2738,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // identity of the wallet count: the row is shared, and one held by // another identity is reported by the revocation. let hasGrants = stores.grants.load().contains { - $0.appContractId == id && (!$0.isUnconfirmed || $0.submittedRevision != nil) + $0.appContractId == id && (!$0.isUnconfirmed || $0.submittedRevision != nil || $0.isPendingV2) } if rowIsOneQR || hasGrants { let revocation = try await revokeAppConnectGrants( @@ -2556,8 +2859,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// as the error to show, or `nil` when no identity but `identityId` has /// part in it. A live key there (`heldOnAnotherIdentity` covers the keys /// no record names) comes first; a registration there that may still - /// land, one with a noted revision, is settled only by a read of that - /// identity, once it is the active one. + /// land, one with a noted revision or a v2 update whose outcome is not + /// known, is settled only by a read of that identity, once it is the + /// active one. static func reasonHeldElsewhere( grants: [AppConnectGrant], appContractId: String, @@ -2568,7 +2872,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { if heldOnAnotherIdentity || elsewhere.contains(where: { !$0.isUnconfirmed && $0.keyDisabled != true }) { return .grantOnAnotherIdentity } - if elsewhere.contains(where: { $0.isUnconfirmed && $0.submittedRevision != nil }) { + if elsewhere.contains(where: { $0.isUnconfirmed && ($0.submittedRevision != nil || $0.isPendingV2) }) { return .registrationPendingOnAnotherIdentity } return nil @@ -2651,7 +2955,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { throw DashConnectPlatformError.loginContractUnavailable } if !stores.grants.load().contains(where: { - isGranted($0) && (!$0.isUnconfirmed || $0.submittedRevision != nil) + isGranted($0) && (!$0.isUnconfirmed || $0.submittedRevision != nil || $0.isPendingV2) }) { // Before the PIN prompt, from the store alone: whether this // identity holds a key of the app's that has no record. @@ -2674,7 +2978,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // A registration whose key has turned up is confirmed. await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores) + modelContainer: context.modelContainer, in: stores, publishing: (context, signer), + exceptAppId: appContractId) + // A v2 update of the app whose outcome the read above could not + // tell is settled once an update of this disconnect lands. + let pendingV2 = Set(stores.grants.load().filter { isGranted($0) && $0.isPendingV2 }.map(\.key)) // One that has not is settled by its revision. One that does not // note it takes no part: its key id may belong to another key, and // its absence says nothing. @@ -2684,7 +2992,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // this identity. var mayStillLand: Set = [] var cannotLand: Set = [] - for grant in stores.grants.load() where isGranted(grant) && grant.isUnconfirmed { + for grant in stores.grants.load() where isGranted(grant) && grant.isUnconfirmed && !grant.isPendingV2 { switch Self.registrationOutcome( of: grant, currentIdentityPublicKeys: currentPublicKeys, identityRevision: revision) { case .keyLive: @@ -2722,7 +3030,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { }, holdsUnrevokedGrant: granted.contains { $0.keyDisabled != true }, holdsLiveTwoQRLoginKey: !liveTwoQRLoginKeyIds.isEmpty, - hasRegistrationThatMayStillLand: !mayStillLand.isEmpty) + hasRegistrationThatMayStillLand: !mayStillLand.isEmpty || !pendingV2.isEmpty) let checksUnrecordedKeys = asOneQR guard AppConnect.sessionKeyIdsMissing(from: currentPublicKeys, for: granted).isEmpty else { // Platform never removes a key, so the node that answered is @@ -2758,7 +3066,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // group they are bound to is the app's if the app's owner owns // it, which only the network says; if it cannot be read, // nothing is turned off and the row stays. - let recordedKeyIds = Self.recordedKeyIds(of: identityId, in: stores) + let recordedKeyIds = Self.recordedKeyIds(of: identityId, in: stores, bindings: bindings) let unrecorded = AppConnect.unrecordedV2Keys( recordedKeyIds: recordedKeyIds, bindings: bindings, currentIdentityPublicKeys: currentPublicKeys) // The store keeps every key it was ever given, the fetched view @@ -2779,7 +3087,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { appContractIds: owned.contracts, appGroupIds: owned.groups, keys: unrecorded) keyIds = Array(Set(keyIds).union(liveTwoQRLoginKeyIds).union(unrecordedV2KeyIds)).sorted() } - if !mayStillLand.isEmpty, keyIds.isEmpty { + if !mayStillLand.isEmpty || !pendingV2.isEmpty, keyIds.isEmpty { // No update would be sent, so nothing settles the registration. // This identity's own state comes first: whatever another // identity holds, this one cannot be told to be done. @@ -2808,11 +3116,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // attempt picks up what is still live. try await disableKeys(keyIds, context: context, signer: signer) Self.logger.info("🔗 DASHCONNECT :: app key(s) disabled") - // The reload writes the disabled keys to the store the shared - // profile count is read from. The keys are off either way. - if mayStillLand.isEmpty { - _ = try? await refreshedIdentityPublicKeys(context: context) - } // Each registration that might still land names a revision above // `revision`, the one below it the identity was already at. The // update that just landed took one above the identity's revision @@ -2836,6 +3139,33 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } updateGrants(in: stores) { grants in grants.removeAll { mayStillLand.contains($0.key) } } } + // The reload writes the disabled keys to the store the shared + // profile count is read from, and settles the v2 records still + // waiting for their update: this disconnect's update landed after + // them. One of the app's that turns out to have landed holds keys + // that are turned off too; one the read cannot tell keeps the + // row. The keys above are off either way. + let disabled = keyIds + let landed = await settleAfterOwnUpdate( + context: context, stores: stores, + reflects: { keys in disabled.allSatisfy { id in keys.contains { + UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil + } } }, + signer: signer, exceptAppId: appContractId) + if !pendingV2.isEmpty { + guard let landed, + !stores.grants.load().contains(where: { pendingV2.contains($0.key) && $0.isPendingV2 }) + else { + throw DashConnectPlatformError.identityKeysOutOfDate + } + let late = landed.filter { pendingV2.contains($0.key) } + if !late.isEmpty { + Self.logger.info("🔗 DASHCONNECT :: disabling the keys of \(late.count, privacy: .public) App Connect update(s) that landed late") + try await disableKeys(Array(Set(late.flatMap(\.keyIds))).sorted(), context: context, signer: signer) + let lateKeys = Set(late.map(\.key)) + updateGrants(in: stores) { AppConnect.markKeysDisabled(in: &$0) { lateKeys.contains($0.key) } } + } + } } // The session keys of the grants read above are now off, and only @@ -2909,7 +3239,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { if AppConnect.holdsLiveSessionKey(appContractId: appContractId, bindings: bindings) { return true } let otherIdentityId = other.identityId.toBase58String() let unrecorded = AppConnect.unrecordedV2Keys( - recordedKeyIds: Self.recordedKeyIds(of: otherIdentityId, in: context.stores), + recordedKeyIds: Self.recordedKeyIds(of: otherIdentityId, in: context.stores, bindings: bindings), bindings: bindings) if !unrecorded.isEmpty { let candidates = AppConnect.unrecordedV2KeyBoundIds(appContractId: appContractId, keys: unrecorded) diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index f4d48e24a5..351fe04646 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1125,3 +1125,492 @@ final class AppConnectV2LoginTests: XCTestCase { XCTAssertFalse(AppConnect.Login.refused(.init(.stale, "old")).isApprovable) } } + +// MARK: - A v2 update whose outcome is not known + +extension AppConnectV2LoginTests { + private static let pendingNow = Int64(createdAt) + 60_000 + + /// A CRITICAL group key as a v2 update adds it. + private static func addedAuthKey( + _ keyId: UInt32, + data: UInt8, + expiresAt: UInt64 = expiresAt + ) -> ManagedPlatformWallet.IdentityPubkey { + ManagedPlatformWallet.IdentityPubkey( + keyId: keyId, keyType: .ecdsaHash160, purpose: .authentication, securityLevel: .critical, + pubkeyBytes: Data(repeating: data, count: 20), contractBounds: .contractGroup(id: groupId), + totalBudget: 50_000_000_000, expiresAt: expiresAt) + } + + /// The app's encryption key as a v2 update registers it. + private static func addedEncryptionKey(_ keyId: UInt32, data: UInt8) -> ManagedPlatformWallet.IdentityPubkey { + ManagedPlatformWallet.IdentityPubkey( + keyId: keyId, keyType: .ecdsaSecp256k1, purpose: .encryption, securityLevel: .medium, + pubkeyBytes: Data(repeating: data, count: 33), contractBounds: .singleContract(id: appId)) + } + + /// `added` on the identity: as it was added unless told otherwise. + private static func onIdentity( + _ added: ManagedPlatformWallet.IdentityPubkey, + keyId: UInt32? = nil, + data: Data? = nil, + totalBudget: UInt64?? = nil, + disabled: Bool = false + ) -> ManagedIdentity.IdentityPublicKeyInfo { + ManagedIdentity.IdentityPublicKeyInfo( + keyId: Int32(bitPattern: keyId ?? added.keyId), purpose: added.purpose, + securityLevel: added.securityLevel, keyType: added.keyType, readOnly: false, + disabledAt: disabled ? 1 : nil, data: data ?? added.pubkeyBytes, + totalBudget: totalBudget ?? added.totalBudget, expiresAt: added.expiresAt.map { Int64($0) }) + } + + /// The store's record of `added`, bound as it was added. + private static func stored(_ added: ManagedPlatformWallet.IdentityPubkey) -> AppConnect.KeyBinding { + AppConnect.KeyBinding( + keyId: added.keyId, data: added.pubkeyBytes, singleContractId: nil, + bound: added.contractBounds.map(AppConnect.storedBound(of:))) + } + + private static func pendingUpdate( + _ added: [ManagedPlatformWallet.IdentityPubkey], + disabling: [UInt32] = [], + retiring: [String] = [] + ) -> AppConnectGrant.PendingV2Update { + .init(addedKeys: added.map(AppConnect.ExpectedKey.init), disabledKeyIds: disabling, retiredGrantKeys: retiring) + } + + /// A v2 record waiting for the update that adds `added`. + private static func pendingGrant( + _ added: [ManagedPlatformWallet.IdentityPubkey], + identityId: String = "identity", + appId: String = "app", + requestHash: String = "aa", + retiring: [String] = [] + ) -> AppConnectGrant { + let auth = added.filter { $0.purpose == .authentication } + var grant = AppConnectGrant( + identityId: identityId, appContractId: appId, documentId: nil, + values: .init(appEphemeralPubKeyHash: requestHash, walletEphemeralPubKey: "bb", encryptedPayload: "cc"), + sessionKeyId: auth[0].keyId, totalBudget: auth[0].totalBudget, expiresAt: auth[0].expiresAt, + publishedAt: Date(timeIntervalSince1970: 1_000), + additionalKeyIds: auth.dropFirst().map(\.keyId), connectionId: "c1", + encryptionKeyIds: added.filter { $0.purpose != .authentication }.map(\.keyId)) + grant.unconfirmedKeyHash160 = auth[0].pubkeyBytes.toHexString() + grant.pendingUpdate = pendingUpdate(added, retiring: retiring) + return grant + } + + private static func outcome( + _ added: [ManagedPlatformWallet.IdentityPubkey], + keys: [ManagedIdentity.IdentityPublicKeyInfo], + bindings: [AppConnect.KeyBinding]? = nil, + now: Int64 = pendingNow, + afterOwnUpdate: Bool = false + ) -> AppConnect.PendingV2Outcome { + AppConnect.pendingV2Outcome( + of: pendingUpdate(added), currentIdentityPublicKeys: keys, bindings: bindings ?? added.map(stored), + nowMilliseconds: now, afterOwnUpdate: afterOwnUpdate) + } + + func testAPendingUpdateLandedOnlyWhenEveryKeyIsThereAsItWasAdded() { + let auth = Self.addedAuthKey(7, data: 0x07) + let encryption = Self.addedEncryptionKey(8, data: 0x08) + let master = Self.key(0, level: .master) + XCTAssertEqual( + Self.outcome([auth, encryption], keys: [master, Self.onIdentity(auth), Self.onIdentity(encryption)]), + .landed) + XCTAssertEqual(Self.outcome([auth, encryption], keys: [master]), .unknown, "it may still land") + XCTAssertEqual( + Self.outcome([auth, encryption], keys: [master, Self.onIdentity(auth)]), .unknown, + "a view that shows part of one update is behind") + } + + func testAnIdHeldByAnotherKeyMeansThePendingUpdateCanNeverLand() { + let auth = Self.addedAuthKey(7, data: 0x07) + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth, data: Data(repeating: 0xEE, count: 20))]), .cannotLand, + "Platform refuses an update that adds an id the identity has") + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth, disabled: true)]), .cannotLand, + "it landed and is off again") + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth, totalBudget: .some(1))]), .cannotLand, + "the same payload with other limits is another request's key") + var otherBound = Self.stored(auth) + otherBound.bound = .contractGroup(Data(repeating: 0xEE, count: 32)) + XCTAssertEqual(Self.outcome([auth], keys: [Self.onIdentity(auth)], bindings: [otherBound]), .cannotLand) + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth)], bindings: []), .unknown, + "the store may not have loaded the key yet") + var unreadable = Self.stored(auth) + unreadable.hasUnreadableBound = true + XCTAssertEqual(Self.outcome([auth], keys: [Self.onIdentity(auth)], bindings: [unreadable]), .unknown) + } + + func testAPendingEncryptionKeyUnderAnotherIdMeansTheUpdateCanNeverLand() { + let auth = Self.addedAuthKey(7, data: 0x07) + let encryption = Self.addedEncryptionKey(8, data: 0x08) + XCTAssertEqual( + Self.outcome([auth, encryption], keys: [Self.onIdentity(encryption, keyId: 3)]), .cannotLand, + "an ECDSA_SECP256K1 key is unique on Platform") + XCTAssertEqual( + Self.outcome([auth, encryption], keys: [Self.onIdentity(auth, keyId: 3)]), .unknown, + "a HASH160 payload is not unique, so it says nothing") + } + + func testAnUpdateOfOursThatLandedLaterSettlesAPendingOne() { + let auth = Self.addedAuthKey(7, data: 0x07) + let master = Self.key(0, level: .master) + XCTAssertEqual(Self.outcome([auth], keys: [master], afterOwnUpdate: true), .cannotLand) + XCTAssertEqual(Self.outcome([auth], keys: [master]), .unknown) + XCTAssertEqual(Self.outcome([auth], keys: [master, Self.onIdentity(auth)], afterOwnUpdate: true), .landed) + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth)], bindings: [], afterOwnUpdate: true), .unknown, + "its key is there; the store just cannot place it") + } + + func testAPendingUpdateOfExpiredAuthKeysOnlyIsDropped() { + let auth = Self.addedAuthKey(7, data: 0x07, expiresAt: Self.createdAt) + let tolerance = Int64(AppConnect.clockTolerance * 1000) + let past = Int64(Self.createdAt) + tolerance + 1 + XCTAssertEqual(Self.outcome([auth], keys: [], now: past), .cannotLand) + XCTAssertEqual( + Self.outcome([auth], keys: [], now: Int64(Self.createdAt) + tolerance - 1), .unknown, + "a device clock up to the tolerance fast does not end it") + XCTAssertEqual( + Self.outcome([auth, Self.addedEncryptionKey(8, data: 0x08)], keys: [], now: past), .unknown, + "an encryption key never expires") + } + + func testSettlingConfirmsWhatLandedDropsWhatCannotAndMarksTheGrantsItRetired() { + let landedKey = Self.addedAuthKey(7, data: 0x07) + let impossibleKey = Self.addedAuthKey(9, data: 0x09) + let unknownKey = Self.addedAuthKey(11, data: 0x0B) + let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") + let landed = Self.pendingGrant([landedKey], requestHash: "a1", retiring: [old.key]) + let impossible = Self.pendingGrant([impossibleKey], requestHash: "a2") + let unknown = Self.pendingGrant([unknownKey], requestHash: "a3") + let otherIdentity = Self.pendingGrant([Self.addedAuthKey(7, data: 0x07)], identityId: "other", requestHash: "a4") + var grants = [old, landed, impossible, unknown, otherIdentity] + + let settled = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: "identity", + currentIdentityPublicKeys: [ + Self.onIdentity(landedKey), Self.onIdentity(impossibleKey, data: Data(repeating: 0xEE, count: 20)), + ], + bindings: [Self.stored(landedKey)], nowMilliseconds: Self.pendingNow) + + XCTAssertEqual(settled.confirmed.map(\.key), [landed.key]) + XCTAssertEqual(settled.dropped.map(\.key), [impossible.key]) + XCTAssertEqual(grants.map(\.key), [old.key, landed.key, unknown.key, otherIdentity.key]) + XCTAssertFalse(grants[1].isUnconfirmed) + XCTAssertNil(grants[1].pendingUpdate) + XCTAssertEqual(grants[0].keyDisabled, true, "the grant its update replaced is done") + XCTAssertTrue(grants[2].isPendingV2) + XCTAssertTrue(grants[3].isPendingV2, "another identity's record waits for a view of that identity") + } + + func testAPendingV2RecordStillReadsAsUnconfirmedWithoutItsNewField() throws { + let grant = Self.pendingGrant([Self.addedAuthKey(7, data: 0x07), Self.addedEncryptionKey(8, data: 0x08)]) + let encoded = try JSONEncoder().encode(grant) + XCTAssertEqual(try JSONDecoder().decode(AppConnectGrant.self, from: encoded), grant) + + var object = try XCTUnwrap(JSONSerialization.jsonObject(with: encoded) as? [String: Any]) + object["pendingUpdate"] = nil + let older = try JSONDecoder().decode( + AppConnectGrant.self, from: JSONSerialization.data(withJSONObject: object)) + XCTAssertNil(older.pendingUpdate, "a record from before the field loads") + XCTAssertTrue(older.isUnconfirmed, "a build without the field still sees the record as unconfirmed") + XCTAssertNil(older.submittedRevision, "and settles it by no revision") + } + + func testTheIdsAPendingUpdateAddsAreNotHandedOutAgain() { + let grants = [ + Self.pendingGrant([Self.addedAuthKey(4, data: 0x04), Self.addedEncryptionKey(5, data: 0x05)]), + Self.pendingGrant([Self.addedAuthKey(9, data: 0x09)], identityId: "other"), + Self.grant(sessionKeyId: 6), + ] + let reserved = AppConnect.reservedKeyIds(grants: grants, identityId: "identity") + XCTAssertEqual(reserved, [4, 5]) + let keys = [Self.key(0, level: .master), Self.key(1), Self.key(2), Self.key(3)] + XCTAssertEqual(AppConnect.freeKeyIds(count: 2, currentIdentityPublicKeys: keys, reserved: reserved), [6, 7]) + XCTAssertEqual(AppConnect.nextKeyId(currentIdentityPublicKeys: keys, reserved: reserved), 6) + } + + func testAKeyAPendingUpdateAddedCountsAsItsGrantsWhereTheStoreShowsIt() { + let profileKey = ManagedPlatformWallet.IdentityPubkey( + keyId: 7, keyType: .ecdsaHash160, purpose: .authentication, securityLevel: .high, + pubkeyBytes: Data(repeating: 0x07, count: 20), + contractBounds: .singleContractDocumentType(id: Self.dashpayContractId, documentTypeName: "profile"), + totalBudget: 1_000_000_000, expiresAt: Self.expiresAt) + let grants = [Self.pendingGrant([profileKey]), Self.grant(sessionKeyId: 3)] + XCTAssertEqual( + AppConnect.recordedKeyIds(of: "identity", grants: grants, bindings: [Self.stored(profileKey)]), [3, 7]) + var otherKey = Self.stored(profileKey) + otherKey = AppConnect.KeyBinding( + keyId: 7, data: Data(repeating: 0xEE, count: 20), singleContractId: nil, bound: otherKey.bound) + XCTAssertEqual( + AppConnect.recordedKeyIds(of: "identity", grants: grants, bindings: [otherKey]), [3], + "another key under the id is not the grant's") + XCTAssertEqual(AppConnect.recordedKeyIds(of: "identity", grants: grants, bindings: []), [3]) + } + + func testARetrySubmitsTheSameKeysUnderTheSameIds() throws { + let first = Self.addedAuthKey(4, data: 0x04) + let second = Self.addedAuthKey(5, data: 0x05) + let encryption = Self.addedEncryptionKey(6, data: 0x06) + let pending = Self.pendingUpdate([first, second, encryption]) + let ids = try XCTUnwrap(AppConnect.keyIdsForRetry( + of: pending, authKeyHash160s: [first.pubkeyBytes, second.pubkeyBytes], + registeredEncryptionKeys: [encryption.pubkeyBytes])) + XCTAssertEqual(ids.auth, [4, 5]) + XCTAssertEqual(ids.encryption, [6]) + XCTAssertNil( + AppConnect.keyIdsForRetry( + of: pending, authKeyHash160s: [first.pubkeyBytes, Data(repeating: 0xEE, count: 20)], + registeredEncryptionKeys: [encryption.pubkeyBytes]), + "other keys are another approval") + XCTAssertNil( + AppConnect.keyIdsForRetry( + of: pending, authKeyHash160s: [first.pubkeyBytes, second.pubkeyBytes], registeredEncryptionKeys: []), + "an update that adds less is not the same update") + } + + func testAPendingUpdateOnAnotherIdentityHoldsTheRow() { + let grants = [Self.pendingGrant([Self.addedAuthKey(7, data: 0x07)], identityId: "other")] + XCTAssertEqual( + PlatformDashConnectDataSource.reasonHeldElsewhere( + grants: grants, appContractId: "app", identityId: "identity", heldOnAnotherIdentity: false), + .registrationPendingOnAnotherIdentity) + } + + func testALoginCleansUpOnlyResponsesThatWereAttempted() { + var disabled = Self.grant(sessionKeyId: 3, requestHash: "00") + disabled.keyDisabled = true + var pendingDisabled = Self.pendingGrant([Self.addedAuthKey(4, data: 0x04)], requestHash: "01") + pendingDisabled.keyDisabled = true + func cleans(_ grant: AppConnectGrant) -> Bool { + PlatformDashConnectDataSource.isLeftoverResponse( + grant, identityId: "identity", appContractId: "app", requestHash: "ff") + } + XCTAssertTrue(cleans(disabled)) + XCTAssertTrue(cleans(Self.grant(sessionKeyId: 5, requestHash: "02")), "an earlier login of the app") + XCTAssertFalse(cleans(Self.grant(sessionKeyId: 6, requestHash: "ff")), "this login's own") + XCTAssertFalse(cleans(Self.pendingGrant([Self.addedAuthKey(7, data: 0x07)], requestHash: "03"))) + XCTAssertFalse(cleans(pendingDisabled), "no response was published for it") + } + + func testTheOneQRConfirmationLeavesAPendingV2RecordAlone() { + let key = ManagedPlatformWallet.IdentityPubkey( + keyId: 7, keyType: .ecdsaHash160, purpose: .authentication, securityLevel: .high, + pubkeyBytes: Data(repeating: 0x07, count: 20), contractBounds: .singleContract(id: Self.appId), + totalBudget: 1_000, expiresAt: Self.expiresAt) + var grants = [Self.pendingGrant([key], appId: Self.appId.toBase58String())] + let confirmed = AppConnect.confirmRegistrations( + in: &grants, identityId: "identity", currentIdentityPublicKeys: [Self.onIdentity(key)], + bindings: [AppConnect.KeyBinding( + keyId: 7, data: key.pubkeyBytes, singleContractId: Self.appId, bound: .singleContract(Self.appId))]) + XCTAssertEqual(confirmed, []) + XCTAssertTrue(grants[0].isPendingV2, "the v2 settlement owns it") + } + + func testARowWaitingForADroppedUpdateGoesUnlessSomethingElseHoldsIt() { + let app = Self.appId.toBase58String() + func row(_ status: ConnectionStatus, id: String = app) -> DAppConnection { + DAppConnection(id: id, name: "Yappr", url: "yap.pr", status: status, + updatedAt: Date(timeIntervalSince1970: 1_000), loginKind: .oneQR) + } + func after(_ grants: [AppConnectGrant], bindings: [AppConnect.KeyBinding] = [], + rows: [DAppConnection]) -> [DAppConnection] { + PlatformDashConnectDataSource.rowsAfterDropping(appIds: [app], grants: grants, bindings: bindings, rows: rows) + } + let other = Data(repeating: 0xD4, count: 32).toBase58String() + XCTAssertEqual(after([], rows: [row(.confirming), row(.confirming, id: other)]).map(\.id), [other]) + XCTAssertEqual( + after([Self.pendingGrant([Self.addedAuthKey(7, data: 0x07)], appId: app)], rows: [row(.confirming)]) + .map(\.status), + [.confirming], "another update of the app still waits") + XCTAssertEqual( + after([Self.grant(sessionKeyId: 3, appId: app)], rows: [row(.confirming)]).map(\.status), [.active]) + XCTAssertEqual( + after([], bindings: [AppConnect.KeyBinding(keyId: 3, data: Data([3]), singleContractId: Self.appId)], + rows: [row(.confirming)]).map(\.status), + [.active], "a live key bound to the app") + XCTAssertEqual(after([], rows: [row(.active)]).map(\.status), [.active], "only a confirming row is touched") + } +} + +// MARK: - Recording a v2 grant around its identity update + +/// A grant store held in memory; `persists: false` drops every write. +private final class MemoryGrantStore: AppConnectResponseStore { + var grants: [AppConnectGrant] + let persists: Bool + + init(_ grants: [AppConnectGrant] = [], persists: Bool = true) { + self.grants = grants + self.persists = persists + } + + func load() -> [AppConnectGrant] { grants } + func save(_ grants: [AppConnectGrant]) { if persists { self.grants = grants } } + func pinned(toWalletIdHex walletIdHex: String) -> any AppConnectResponseStore { self } +} + +private struct UpdateFailed: Error {} + +extension AppConnectV2LoginTests { + private typealias View = (keys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [AppConnect.KeyBinding]) + + private final class Calls { + var submitted = 0 + var rowShown = 0 + var rereads = 0 + var pauses: [Int] = [] + var dropped = 0 + } + + private static func register( + _ record: AppConnectGrant, + add: [ManagedPlatformWallet.IdentityPubkey], + disable: [UInt32] = [], + retiring: Set = [], + store: MemoryGrantStore, + calls: Calls, + submit: @escaping () throws -> Void = {}, + views: [View?] = [] + ) async throws -> AppConnectGrant { + var remaining = views + return try await PlatformDashConnectDataSource.registerAppConnectV2Grant( + record, add: add, disable: disable, retiredGrantKeys: retiring, grants: store, + nowMilliseconds: { pendingNow }, + showRow: { calls.rowShown += 1 }, + submit: { calls.submitted += 1; try submit() }, + reread: { + calls.rereads += 1 + return remaining.isEmpty ? nil : remaining.removeFirst() + }, + pause: { calls.pauses.append($0) }, + onDropped: { calls.dropped += 1 }) + } + + func testAV2GrantIsRecordedAndShownBeforeItsUpdateIsSubmitted() async throws { + let key = Self.addedAuthKey(7, data: 0x07) + let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") + let record = Self.pendingGrant([key], retiring: [old.key]) + let store = MemoryGrantStore([old]) + let calls = Calls() + + let grant = try await Self.register(record, add: [key], disable: [3], retiring: [old.key], store: store, calls: calls) { + let stored = store.grants.first { $0.key == record.key } + XCTAssertEqual(stored?.pendingUpdate?.addedKeys, [AppConnect.ExpectedKey(key)], "recorded first") + XCTAssertTrue(stored?.isUnconfirmed == true) + XCTAssertEqual(calls.rowShown, 1, "and shown") + XCTAssertNil(store.grants.first { $0.key == old.key }?.keyDisabled, "the replaced grant waits for the update") + } + + XCTAssertEqual(calls.submitted, 1) + XCTAssertFalse(grant.isUnconfirmed) + XCTAssertNil(grant.pendingUpdate) + XCTAssertEqual(store.grants.first { $0.key == record.key }, grant) + XCTAssertEqual(store.grants.first { $0.key == old.key }?.keyDisabled, true) + } + + func testARenewalThatCannotTurnOffEveryReplacedKeySubmitsNothing() async { + let key = Self.addedAuthKey(20, data: 0x14) + let store = MemoryGrantStore() + let calls = Calls() + let tooMany = (1 ... UInt32(AppConnect.maxKeysDisabledPerUpdate + 1)).map { $0 } + do { + _ = try await Self.register(Self.pendingGrant([key]), add: [key], disable: tooMany, store: store, calls: calls) + XCTFail("refused") + } catch { + XCTAssertEqual(error as? DashConnectPlatformError, .tooManyKeysToReplace) + } + XCTAssertEqual(calls.submitted, 0) + XCTAssertEqual(calls.rowShown, 0) + XCTAssertEqual(store.grants, [], "nothing recorded") + + let fits = Array(tooMany.dropLast()) + _ = try? await Self.register(Self.pendingGrant([key]), add: [key], disable: fits, store: store, calls: calls) + XCTAssertEqual(calls.submitted, 1, "every replaced key fits one update") + } + + func testAFailedUpdateThatLandedAnywayIsConfirmed() async throws { + let key = Self.addedAuthKey(7, data: 0x07) + let store = MemoryGrantStore() + let calls = Calls() + let grant = try await Self.register( + Self.pendingGrant([key]), add: [key], store: store, calls: calls, submit: { throw UpdateFailed() }, + views: [nil, ([Self.onIdentity(key)], [Self.stored(key)])]) + XCTAssertFalse(grant.isUnconfirmed) + XCTAssertEqual(calls.rereads, 2) + XCTAssertEqual(calls.pauses, [1]) + } + + func testAFailedUpdateThatCanNeverLandDropsItsRecord() async { + let key = Self.addedAuthKey(7, data: 0x07) + let store = MemoryGrantStore() + let calls = Calls() + do { + _ = try await Self.register( + Self.pendingGrant([key]), add: [key], store: store, calls: calls, submit: { throw UpdateFailed() }, + views: [([Self.onIdentity(key, data: Data(repeating: 0xEE, count: 20))], [])]) + XCTFail("the failure stands") + } catch { + XCTAssertTrue(error is UpdateFailed) + } + XCTAssertEqual(store.grants, []) + XCTAssertEqual(calls.dropped, 1, "its row is repaired") + } + + func testAFailedUpdateWhoseOutcomeIsUnknownKeepsItsRecord() async { + let key = Self.addedAuthKey(7, data: 0x07) + let record = Self.pendingGrant([key]) + let store = MemoryGrantStore() + let calls = Calls() + do { + _ = try await Self.register(record, add: [key], store: store, calls: calls, submit: { throw UpdateFailed() }, + views: [([Self.key(0, level: .master)], [])]) + XCTFail("the failure stands") + } catch { + XCTAssertTrue(error is UpdateFailed) + } + XCTAssertEqual(calls.rereads, 3) + XCTAssertEqual(calls.pauses, [1, 2]) + XCTAssertEqual(store.grants, [record], "kept until the outcome is known") + XCTAssertEqual(calls.dropped, 0) + } + + func testAGrantThatCannotBeRecordedIsNotSubmitted() async { + let key = Self.addedAuthKey(7, data: 0x07) + let calls = Calls() + do { + _ = try await Self.register( + Self.pendingGrant([key]), add: [key], store: MemoryGrantStore(persists: false), calls: calls) + XCTFail("refused") + } catch { + XCTAssertEqual(error as? DashConnectPlatformError, .grantStoreUnavailable) + } + XCTAssertEqual(calls.submitted, 0) + XCTAssertEqual(calls.rowShown, 0) + } + + func testAnUpdateThatOnlyDisablesKeepsTheEarlierRecordAndLandsWhenItsDisablesShow() async throws { + var earlier = Self.grant(sessionKeyId: 7, requestHash: "aa", connectionId: "c1") + earlier.documentId = "doc" + let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") + var resent = earlier + resent.values = .init(appEphemeralPubKeyHash: "aa", walletEphemeralPubKey: "new", encryptedPayload: "new") + resent.documentId = nil + let store = MemoryGrantStore([old, earlier]) + let calls = Calls() + let grant = try await Self.register( + resent, add: [], disable: [3], retiring: [old.key], store: store, calls: calls, + submit: { throw UpdateFailed() }, + views: [([Self.key(3, disabled: true)], [])]) + XCTAssertEqual(grant, earlier, "its values are the ones on Platform") + XCTAssertEqual(store.grants.first { $0.key == old.key }?.keyDisabled, true) + } +} From 5362828300b510aa6ccdd45493c614d197da3898 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 30 Oct 2026 22:23:08 +0200 Subject: [PATCH 04/29] fix(dashconnect): settle a pending App Connect v2 update by a noted later update Every identity update of this wallet that returns success is noted, by the keys it added and the ids it disabled, on the v2 records still waiting for theirs; a later view that shows it settles them. A disconnect whose follow-up read is behind therefore no longer leaves its record waiting for good, and finishes marking and deleting what it turned off before keeping the row. Also: nothing is published at the start of an approval; a recovered response is published without the cleanup of the app's other responses; a retry reseals the response with the identity's current encryption keys; the app's earlier row comes back when its update can never land. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 8 +- .../DashConnect/AppConnectV2Login.swift | 67 +++++- .../PlatformDashConnectDataSource.swift | 205 ++++++++++-------- .../DashConnect/AppConnectV2LoginTests.swift | 47 +++- 4 files changed, 213 insertions(+), 114 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 5fa7c160d7..035073db55 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -204,8 +204,6 @@ enum AppConnect { return (0 ... UInt32.max).first { !taken.contains($0) } } - /// The key an app is given: it can only sign for the contract the request - /// named, spend up to `totalBudget`, and stops working at `expiresAt`. /// The ids the v2 records of `identityId` that wait for their update /// add keys under: a new key under one of them would make that update, /// or itself, be refused. @@ -213,6 +211,8 @@ enum AppConnect { Set(grants.filter { $0.identityId == identityId }.flatMap { $0.pendingUpdate?.addedKeys.map(\.keyId) ?? [] }) } + /// The key an app is given: it can only sign for the contract the request + /// named, spend up to `totalBudget`, and stops working at `expiresAt`. static func sessionIdentityPubkey( keyId: UInt32, publicKeyHash160: Data, @@ -719,6 +719,10 @@ struct AppConnectGrant: Codable, Equatable { var disabledKeyIds: [UInt32] /// The records of those grants (`key`) that are done once it lands. var retiredGrantKeys: [String] + /// An update of this wallet to the identity that landed after this + /// one was submitted (`AppConnect.noteOwnUpdate`): this one cannot + /// land after it. + var outlivedBy: AppConnect.OwnUpdate? = nil } /// What makes two records the same grant: one session key given for one diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index afc3371966..ec6dd44600 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1019,6 +1019,52 @@ extension AppConnect { } } + /// What an update of this wallet to an identity did, by what Platform + /// never undoes: the keys it added (a key is never removed) and the ids + /// it disabled (a key is never enabled again). A view that shows all of + /// it is at that update or past it. + struct OwnUpdate: Codable, Equatable { + struct AddedKey: Codable, Equatable { + let keyId: UInt32 + let data: Data + } + + var addedKeys: [AddedKey] + var disabledKeyIds: [UInt32] + + init(added: [ManagedPlatformWallet.IdentityPubkey] = [], disabledKeyIds: [UInt32] = []) { + addedKeys = added.map { AddedKey(keyId: $0.keyId, data: $0.pubkeyBytes) } + self.disabledKeyIds = disabledKeyIds + } + + func isShown(in keys: [ManagedIdentity.IdentityPublicKeyInfo]) -> Bool { + addedKeys.allSatisfy { added in keys.contains { + UInt32(bitPattern: $0.keyId) == added.keyId && $0.data == added.data + } } && showsDisabled(disabledKeyIds, in: keys) + } + } + + /// Whether `keys` shows every one of `keyIds`, disabled. + static func showsDisabled(_ keyIds: [UInt32], in keys: [ManagedIdentity.IdentityPublicKeyInfo]) -> Bool { + keyIds.allSatisfy { id in keys.contains { UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil } } + } + + /// Notes on every v2 record of `identityId` still waiting for its update + /// (except `exceptKey`'s, the update's own) that `update` landed after + /// it was submitted. An earlier note stays: it settles the same way. + static func noteOwnUpdate( + _ update: OwnUpdate, + in grants: inout [AppConnectGrant], + identityId: String, + exceptKey: String? = nil + ) { + for index in grants.indices + where grants[index].identityId == identityId && grants[index].key != exceptKey + && grants[index].pendingUpdate != nil && grants[index].pendingUpdate?.outlivedBy == nil { + grants[index].pendingUpdate?.outlivedBy = update + } + } + /// What a view of the identity tells of a v2 update whose outcome was /// not known. enum PendingV2Outcome: Equatable { @@ -1043,11 +1089,12 @@ extension AppConnect { /// - Its encryption key (ECDSA_SECP256K1, unique on Platform) under /// another id: it can never land. HASH160 auth keys are not unique, /// so their data elsewhere says nothing. - /// - `afterOwnUpdate`: `keys` reflects an update of this wallet to the - /// identity that landed after `pending` was recorded. Platform takes an - /// update only at one above the identity's revision, and that update - /// took one above whatever the wallet's copy held, so `pending` cannot - /// land after it: none of its ids there means it never will. + /// - An update of this wallet that landed after it was submitted + /// (`outlivedBy`) and that `keys` shows: Platform takes an update only + /// at one above the identity's revision, and that update took one + /// above whatever the wallet's copy held, so `pending` cannot land + /// after it. A view that shows that update and none of its ids means + /// it never will. No revision is read: what the update did is. /// - Every added key is an auth key past its expiry (with /// `clockTolerance`): if it lands, nothing can sign with it. An /// encryption key has no expiry, so this never ends one that adds it. @@ -1058,8 +1105,7 @@ extension AppConnect { of pending: AppConnectGrant.PendingV2Update, currentIdentityPublicKeys keys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [KeyBinding], - nowMilliseconds: Int64, - afterOwnUpdate: Bool = false + nowMilliseconds: Int64 ) -> PendingV2Outcome { var allLanded = true var anyPresent = false @@ -1085,7 +1131,7 @@ extension AppConnect { } } if takenElsewhere { return .cannotLand } - if afterOwnUpdate && !anyPresent { return .cannotLand } + if !anyPresent, pending.outlivedBy?.isShown(in: keys) == true { return .cannotLand } let allExpired = pending.addedKeys.allSatisfy { expected in expected.purpose == .authentication && expected.expiresAt.map { !isUnexpired(Int64(clamping: $0), nowMilliseconds: nowMilliseconds) } == true @@ -1102,8 +1148,7 @@ extension AppConnect { identityId: String, currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [KeyBinding], - nowMilliseconds: Int64, - afterOwnUpdate: Bool = false + nowMilliseconds: Int64 ) -> (confirmed: [AppConnectGrant], dropped: [AppConnectGrant]) { var confirmed: [AppConnectGrant] = [] var dropped: [AppConnectGrant] = [] @@ -1112,7 +1157,7 @@ extension AppConnect { guard let pending = grant.pendingUpdate else { continue } switch pendingV2Outcome( of: pending, currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: bindings, - nowMilliseconds: nowMilliseconds, afterOwnUpdate: afterOwnUpdate + nowMilliseconds: nowMilliseconds ) { case .landed: var settled = grant diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 3c4ea3375d..c76a14d0c8 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1200,6 +1200,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { signer: signer ) } + noteOwnUpdateLanded(AppConnect.OwnUpdate(added: [key]), context: context) } catch { // Another update of the identity that landed meanwhile moved // the wallet's revision, and this one may have been built on @@ -1283,7 +1284,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { appEphemeralPubKeyHash: Data, responseContractId: Data, context: Context, - signer: KeychainSigner + signer: KeychainSigner, + cleansUp: Bool = true ) async throws { let stores = context.stores let identityId = grant.identityId @@ -1309,15 +1311,17 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // Besides this app's earlier responses, this takes whatever an earlier // disconnect of any app left behind for this identity: its row is // gone, so a login is the only moment left to finish that cleanup. - await deleteAppConnectResponses( - where: { - Self.isLeftoverResponse( - $0, identityId: identityId, appContractId: appContractId, requestHash: requestHash) - }, - responseContractId: responseContractId, - context: context, - signer: signer - ) + if cleansUp { + await deleteAppConnectResponses( + where: { + Self.isLeftoverResponse( + $0, identityId: identityId, appContractId: appContractId, requestHash: requestHash) + }, + responseContractId: responseContractId, + context: context, + signer: signer + ) + } // Recorded before the publish is submitted: a response this record // had as deleted may be back on Platform after a publish that fails @@ -1471,10 +1475,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let bindings = try Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer) // This identity's records whose update's outcome was not known are // settled first: one that landed is a grant like any other below, and - // one that cannot land frees its ids. + // one that cannot land frees its ids. Nothing is published here: this + // approval may still be refused, and its own response is published + // once its checks pass. await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores, publishing: (context, signer)) + modelContainer: context.modelContainer, in: stores, bindings: bindings) // Which rotations to derive depends on the keys the identity has. for grant in plan.encryption { encryptionKeys.append(try await MainActor.run { @@ -1753,7 +1759,15 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // without confirming, those are the ones on Platform. let grantedKeyIds = authKeyIds.compactMap { $0 } let primary = plan.auth[0] - var record = pendingRetry + // A record waiting for its update has never had its response + // published, so a retry seals it again, with the encryption keys the + // identity has now. + var record = pendingRetry.map { pending -> AppConnectGrant in + var retried = pending + retried.values = values + retried.encryptionKeyIds = encryptionSlots.compactMap(\.keyId) + return retried + } ?? stores.grants.load().first { isGrantForRequest($0) && !$0.isUnconfirmed && $0.sessionKeyId == grantedKeyIds[0] } ?? AppConnectGrant( identityId: identityId, @@ -1779,6 +1793,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let connection = Self.makeConnection( preview: consent, status: .active, updatedAt: now(), loginKind: .oneQR) let modelContainer = context.modelContainer + // The app's row before this approval, put back if its update turns + // out never to land and nothing else holds the app. + let previousRow = rows(in: stores).first { $0.id == connection.id } let grant = try await Self.registerAppConnectV2Grant( record, add: add, @@ -1807,6 +1824,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { signer: signer ) } + noteOwnUpdateLanded( + AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), context: context, exceptKey: record.key) }, reread: { guard let keys = try? await refreshedIdentityPublicKeys(context: context), @@ -1818,8 +1837,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { onDropped: { let grants = stores.grants.load() let bindings = (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) ?? [] - await updateRows(in: stores) { - Self.rowsAfterDropping(appIds: [appId], grants: grants, bindings: bindings, rows: $0) + await updateRows(in: stores) { rows in + let after = Self.rowsAfterDropping(appIds: [appId], grants: grants, bindings: bindings, rows: rows) + guard let previousRow, !after.contains(where: { $0.id == appId }) else { return after } + return after + [previousRow] } } ) @@ -1832,30 +1853,16 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // Every record of this identity still waiting for its update was // written before this one landed, so this update settles them. A // previous grant of this connection that turned out to have landed - // holds keys this login replaces: they are turned off too. + // holds keys this login replaces: they are turned off too, and its + // response is not published. if !add.isEmpty || !disable.isEmpty, stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { let landed = await settleAfterOwnUpdate( - context: context, - stores: stores, - reflects: { keys in - add.allSatisfy { new in keys.contains { - UInt32(bitPattern: $0.keyId) == new.keyId && $0.data == new.pubkeyBytes - } } && disable.allSatisfy { id in keys.contains { - UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil - } } - }, - signer: signer, - exceptAppId: appId) - let late = (landed ?? []).filter(isSuperseded) - if !late.isEmpty { - let lateKeys = Set(late.map(\.key)) - do { - try await disableKeys(Array(Set(late.flatMap(\.keyIds))).sorted(), context: context, signer: signer) - updateGrants(in: stores) { AppConnect.markKeysDisabled(in: &$0) { lateKeys.contains($0.key) } } - } catch { - Self.logger.error("🔗 DASHCONNECT :: keys of a replaced grant that landed late are still live — \(error.localizedDescription, privacy: .public)") - } + context: context, stores: stores, signer: signer, except: isSuperseded) ?? [] + do { + try await disableLateLandedGrants(landed.filter(isSuperseded), context: context, signer: signer) + } catch { + Self.logger.error("🔗 DASHCONNECT :: keys of a replaced grant that landed late are still live — \(error.localizedDescription, privacy: .public)") } } @@ -1940,9 +1947,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { for attempt in 0 ..< 3 { if attempt > 0 { await pause(attempt) } guard let view = await reread() else { continue } - let disabled = disable.allSatisfy { id in view.keys.contains { - UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil - } } + let disabled = AppConnect.showsDisabled(disable, in: view.keys) guard let pending = grants.load().first(where: { $0.key == record.key })?.pendingUpdate else { // Nothing added: the update landed when its disables show. if disabled { @@ -2227,6 +2232,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { signer: signer ) } + noteOwnUpdateLanded( + AppConnect.OwnUpdate(added: missingKeys.map(Self.makeManagedIdentityPubkey)), context: authorized) await markActive(pendingConnection, in: authorized.stores) } @@ -2264,26 +2271,29 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// two-QR login. /// /// A v2 record whose update's outcome was not known is settled by - /// `AppConnect.settlePendingV2Registrations` (`afterOwnUpdate` as there): - /// one that cannot land is dropped, and its row with it when nothing else - /// holds it (`rowsAfterDropping`). With `publishing`, the response of each - /// one that landed is published, except for `exceptAppId`'s; best effort, - /// as a later login retries it. Returns the v2 grants confirmed. + /// `AppConnect.settlePendingV2Registrations`: one that cannot land is + /// dropped, and its row with it when nothing else holds it + /// (`rowsAfterDropping`). With `publishing`, the response of each one + /// that landed is published unless `except` says otherwise; best effort, + /// as a later login retries it, and with no cleanup of other responses: + /// the app may have answered a newer request since. Returns the v2 + /// grants confirmed. @discardableResult private func confirmRegistrations( identityId: String, currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], modelContainer: ModelContainer, in stores: Stores, - afterOwnUpdate: Bool = false, + bindings knownBindings: [AppConnect.KeyBinding]? = nil, publishing: (context: Context, signer: KeychainSigner)? = nil, - exceptAppId: String? = nil + except: (AppConnectGrant) -> Bool = { _ in false } ) async -> [AppConnectGrant] { guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) else { return [] } // Without the store's bindings no unconfirmed record is confirmed, // and a confirmed one does not need them. - let bindings = (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) ?? [] + let bindings = knownBindings + ?? (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) ?? [] if stores.grants.load().contains(where: { $0.identityId == identityId && $0.isUnconfirmed }) { let confirmed = updateGrants(in: stores) { grants in AppConnect.confirmRegistrations( @@ -2300,7 +2310,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let settled = updateGrants(in: stores) { grants in AppConnect.settlePendingV2Registrations( in: &grants, identityId: identityId, currentIdentityPublicKeys: currentIdentityPublicKeys, - bindings: bindings, nowMilliseconds: nowMilliseconds, afterOwnUpdate: afterOwnUpdate) + bindings: bindings, nowMilliseconds: nowMilliseconds) } confirmedV2 = settled.confirmed if !settled.confirmed.isEmpty { @@ -2327,13 +2337,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } } if let publishing, let responseContractId = Self.decodeIdentifier(AppConnect.contractId) { - for confirmed in confirmedV2 where confirmed.appContractId != exceptAppId { + for confirmed in confirmedV2 where !except(confirmed) { guard let grant = stores.grants.load().first(where: { $0.key == confirmed.key }), let requestHash = AppConnect.data(fromHex: grant.values.appEphemeralPubKeyHash) else { continue } do { try await publishAppConnectResponse( grant: grant, appEphemeralPubKeyHash: requestHash, responseContractId: responseContractId, - context: publishing.context, signer: publishing.signer) + context: publishing.context, signer: publishing.signer, cleansUp: false) } catch { Self.logger.error("🔗 DASHCONNECT :: the response of a recovered App Connect grant was not published — \(error.localizedDescription, privacy: .public)") } @@ -2342,24 +2352,21 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { return confirmedV2 } - /// After an update of this wallet to the identity landed: one more read - /// of the identity, which also writes what it shows to the store, and, - /// when it shows that update (`reflects`), every v2 record of the - /// identity waiting for its outcome is settled by it (`afterOwnUpdate`, - /// see `AppConnect.pendingV2Outcome`). Returns the v2 grants confirmed, - /// or nil when the read failed or is behind that update. + /// After an update of this wallet to the identity landed (and was noted, + /// `noteOwnUpdateLanded`): one more read of the identity, which also + /// writes what it shows to the store, and the v2 records of the identity + /// waiting for their outcome are settled by it. Returns the v2 grants + /// confirmed, or nil when the read failed. private func settleAfterOwnUpdate( context: Context, stores: Stores, - reflects: ([ManagedIdentity.IdentityPublicKeyInfo]) -> Bool, signer: KeychainSigner, - exceptAppId: String? = nil + except: (AppConnectGrant) -> Bool = { _ in false } ) async -> [AppConnectGrant]? { - guard let keys = try? await refreshedIdentityPublicKeys(context: context), reflects(keys) else { return nil } + guard let keys = try? await refreshedIdentityPublicKeys(context: context) else { return nil } return await confirmRegistrations( identityId: context.identityId.toBase58String(), currentIdentityPublicKeys: keys, - modelContainer: context.modelContainer, in: stores, afterOwnUpdate: true, - publishing: (context, signer), exceptAppId: exceptAppId) + modelContainer: context.modelContainer, in: stores, publishing: (context, signer), except: except) } /// `rows` once the v2 records of `appIds` that were waiting for their @@ -2700,12 +2707,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // The reload writes the disabled keys to the store the count is read // from, and settles the v2 records still waiting for their update. // The keys are off either way. - _ = await settleAfterOwnUpdate( - context: context, stores: stores, - reflects: { keys in keyIds.allSatisfy { id in keys.contains { - UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil - } } }, - signer: signer) + _ = await settleAfterOwnUpdate(context: context, stores: stores, signer: signer) return keyIds.count } @@ -2979,7 +2981,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, modelContainer: context.modelContainer, in: stores, publishing: (context, signer), - exceptAppId: appContractId) + except: { $0.appContractId == appContractId }) // A v2 update of the app whose outcome the read above could not // tell is settled once an update of this disconnect lands. let pendingV2 = Set(stores.grants.load().filter { isGranted($0) && $0.isPendingV2 }.map(\.key)) @@ -3094,7 +3096,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // TODO(dashconnect-pending-registration): an update that was // refused, or never sent, cannot be told from one still on its // way, so this stays until the identity's revision moves or the - // app's code is approved again. Until then the record also holds + // app's code is approved again. A v2 record stays until an update + // of this wallet to the identity lands, or its auth keys expire + // when it registers no encryption key. Until then the record also holds // the row for the wallet's other identities // (`registrationPendingOnAnotherIdentity`). Self.logger.error("🔗 DASHCONNECT :: a session key registration of the app may still land, and there is no key to disable") @@ -3143,29 +3147,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // profile count is read from, and settles the v2 records still // waiting for their update: this disconnect's update landed after // them. One of the app's that turns out to have landed holds keys - // that are turned off too; one the read cannot tell keeps the - // row. The keys above are off either way. - let disabled = keyIds + // that are turned off too. The keys above are off either way. let landed = await settleAfterOwnUpdate( - context: context, stores: stores, - reflects: { keys in disabled.allSatisfy { id in keys.contains { - UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil - } } }, - signer: signer, exceptAppId: appContractId) - if !pendingV2.isEmpty { - guard let landed, - !stores.grants.load().contains(where: { pendingV2.contains($0.key) && $0.isPendingV2 }) - else { - throw DashConnectPlatformError.identityKeysOutOfDate - } - let late = landed.filter { pendingV2.contains($0.key) } - if !late.isEmpty { - Self.logger.info("🔗 DASHCONNECT :: disabling the keys of \(late.count, privacy: .public) App Connect update(s) that landed late") - try await disableKeys(Array(Set(late.flatMap(\.keyIds))).sorted(), context: context, signer: signer) - let lateKeys = Set(late.map(\.key)) - updateGrants(in: stores) { AppConnect.markKeysDisabled(in: &$0) { lateKeys.contains($0.key) } } - } - } + context: context, stores: stores, signer: signer, + except: { $0.appContractId == appContractId }) ?? [] + try await disableLateLandedGrants( + landed.filter { pendingV2.contains($0.key) }, context: context, signer: signer) } // The session keys of the grants read above are now off, and only @@ -3182,6 +3169,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { signer: signer ) } + // An update of the app whose outcome this disconnect could not tell + // keeps the row: the next disconnect settles it by the update that + // landed here, which it has noted. + if stores.grants.load().contains(where: { pendingV2.contains($0.key) && $0.isPendingV2 }) { + Self.logger.error("🔗 DASHCONNECT :: an App Connect update of the app may still land") + throw DashConnectPlatformError.registrationPending + } if let heldElsewhere = reasonHeldElsewhere(heldOnAnotherIdentity: heldOnAnotherIdentity == true) { return (heldElsewhere: heldElsewhere, asOneQR: asOneQR) } @@ -3196,14 +3190,41 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// takes. private func disableKeys(_ keyIds: [UInt32], context: Context, signer: KeychainSigner) async throws { for start in stride(from: 0, to: keyIds.count, by: AppConnect.maxKeysDisabledPerUpdate) { + let batch = Array(keyIds[start ..< min(start + AppConnect.maxKeysDisabledPerUpdate, keyIds.count)]) try await context.wallet.updateIdentity( identityId: context.identityId, - disablePublicKeyIds: Array(keyIds[start ..< min(start + AppConnect.maxKeysDisabledPerUpdate, keyIds.count)]), + disablePublicKeyIds: batch, signer: signer ) + noteOwnUpdateLanded(AppConnect.OwnUpdate(disabledKeyIds: batch), context: context) } } + /// An update of this wallet to the identity returned success: every v2 + /// record of the identity still waiting for its own update (but + /// `exceptKey`'s, the update's own) cannot land after it, which a later + /// view that shows `update` settles (`AppConnect.pendingV2Outcome`). + private func noteOwnUpdateLanded(_ update: AppConnect.OwnUpdate, context: Context, exceptKey: String? = nil) { + let identityId = context.identityId.toBase58String() + guard context.stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) else { + return + } + updateGrants(in: context.stores) { grants in + AppConnect.noteOwnUpdate(update, in: &grants, identityId: identityId, exceptKey: exceptKey) + } + } + + /// Turns off the keys of `grants`, earlier grants that turned out to + /// have landed after the keys to replace or disconnect were picked, and + /// marks them done. + private func disableLateLandedGrants(_ grants: [AppConnectGrant], context: Context, signer: KeychainSigner) async throws { + guard !grants.isEmpty else { return } + Self.logger.info("🔗 DASHCONNECT :: disabling the keys of \(grants.count, privacy: .public) App Connect grant(s) that landed late") + try await disableKeys(Array(Set(grants.flatMap(\.keyIds))).sorted(), context: context, signer: signer) + let keys = Set(grants.map(\.key)) + updateGrants(in: context.stores) { AppConnect.markKeysDisabled(in: &$0) { keys.contains($0.key) } } + } + /// Whether the wallet's store shows another identity of this wallet with /// a live key of the app that no grant record names: a session key bound /// to the app's contract, or a key the two-QR login derives for it. diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 351fe04646..76cf09b3d1 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1206,11 +1206,12 @@ extension AppConnectV2LoginTests { keys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [AppConnect.KeyBinding]? = nil, now: Int64 = pendingNow, - afterOwnUpdate: Bool = false + outlivedBy: AppConnect.OwnUpdate? = nil ) -> AppConnect.PendingV2Outcome { - AppConnect.pendingV2Outcome( - of: pendingUpdate(added), currentIdentityPublicKeys: keys, bindings: bindings ?? added.map(stored), - nowMilliseconds: now, afterOwnUpdate: afterOwnUpdate) + var pending = pendingUpdate(added) + pending.outlivedBy = outlivedBy + return AppConnect.pendingV2Outcome( + of: pending, currentIdentityPublicKeys: keys, bindings: bindings ?? added.map(stored), nowMilliseconds: now) } func testAPendingUpdateLandedOnlyWhenEveryKeyIsThereAsItWasAdded() { @@ -1259,15 +1260,43 @@ extension AppConnectV2LoginTests { "a HASH160 payload is not unique, so it says nothing") } - func testAnUpdateOfOursThatLandedLaterSettlesAPendingOne() { + func testAnUpdateOfOursThatLandedLaterSettlesAPendingOneOnceAViewShowsIt() { let auth = Self.addedAuthKey(7, data: 0x07) let master = Self.key(0, level: .master) - XCTAssertEqual(Self.outcome([auth], keys: [master], afterOwnUpdate: true), .cannotLand) - XCTAssertEqual(Self.outcome([auth], keys: [master]), .unknown) - XCTAssertEqual(Self.outcome([auth], keys: [master, Self.onIdentity(auth)], afterOwnUpdate: true), .landed) + let later = AppConnect.OwnUpdate(disabledKeyIds: [3]) + let showsLater = Self.key(3, disabled: true) + XCTAssertEqual(Self.outcome([auth], keys: [master, showsLater], outlivedBy: later), .cannotLand) XCTAssertEqual( - Self.outcome([auth], keys: [Self.onIdentity(auth)], bindings: [], afterOwnUpdate: true), .unknown, + Self.outcome([auth], keys: [master, Self.key(3)], outlivedBy: later), .unknown, + "a view that does not show the later update is behind it") + XCTAssertEqual(Self.outcome([auth], keys: [master, showsLater]), .unknown, "without one it may still land") + XCTAssertEqual( + Self.outcome([auth], keys: [master, showsLater, Self.onIdentity(auth)], outlivedBy: later), .landed) + XCTAssertEqual( + Self.outcome([auth], keys: [showsLater, Self.onIdentity(auth)], bindings: [], outlivedBy: later), .unknown, "its key is there; the store just cannot place it") + let added = Self.addedAuthKey(9, data: 0x09) + XCTAssertEqual( + Self.outcome([auth], keys: [master, Self.onIdentity(added)], + outlivedBy: AppConnect.OwnUpdate(added: [added])), + .cannotLand, "a later update that added a key is shown by that key") + } + + func testAnUpdateOfOursIsNotedOnEveryRecordWaitingButItsOwn() { + let own = Self.pendingGrant([Self.addedAuthKey(7, data: 0x07)], requestHash: "a1") + let earlier = Self.pendingGrant([Self.addedAuthKey(9, data: 0x09)], requestHash: "a2") + var noted = Self.pendingGrant([Self.addedAuthKey(11, data: 0x0B)], requestHash: "a3") + let first = AppConnect.OwnUpdate(disabledKeyIds: [1]) + noted.pendingUpdate?.outlivedBy = first + let other = Self.pendingGrant([Self.addedAuthKey(13, data: 0x0D)], identityId: "other", requestHash: "a4") + var grants = [own, earlier, noted, other, Self.grant(sessionKeyId: 3)] + let update = AppConnect.OwnUpdate(disabledKeyIds: [2]) + AppConnect.noteOwnUpdate(update, in: &grants, identityId: "identity", exceptKey: own.key) + XCTAssertNil(grants[0].pendingUpdate?.outlivedBy, "an update does not outlive itself") + XCTAssertEqual(grants[1].pendingUpdate?.outlivedBy, update) + XCTAssertEqual(grants[2].pendingUpdate?.outlivedBy, first, "an earlier note settles the same way") + XCTAssertNil(grants[3].pendingUpdate?.outlivedBy, "another identity's update") + XCTAssertNil(grants[4].pendingUpdate) } func testAPendingUpdateOfExpiredAuthKeysOnlyIsDropped() { From 6f9d6594c2811e4b430e57ff66cf298728f86dae Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 30 Oct 2026 22:37:15 +0200 Subject: [PATCH 05/29] fix(dashconnect): keep a confirmed App Connect v2 grant on a lagging view, and resubmit a pending update as it was A confirmed grant of the request whose keys a view lacks means the view is behind; the approval stops instead of turning the record pending again. A retry resubmits the earlier update with its disables, so the record's retirements hold whichever update lands. An own update is noted on the other waiting records whenever its landing is known, not only on success. A pending update that landed and whose keys are off again is dropped with what it retired marked done. A replaced grant's response is not published, responses found at the start of an approval are published once it went through, and a two-QR approved row a confirming one replaced comes back. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 4 + .../DashConnect/AppConnectV2Login.swift | 25 ++- .../PlatformDashConnectDataSource.swift | 156 ++++++++++++------ .../DashConnect/AppConnectV2LoginTests.swift | 59 ++++++- 4 files changed, 189 insertions(+), 55 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 035073db55..835f8f7c46 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -723,6 +723,10 @@ struct AppConnectGrant: Codable, Equatable { /// one was submitted (`AppConnect.noteOwnUpdate`): this one cannot /// land after it. var outlivedBy: AppConnect.OwnUpdate? = nil + /// The app's row was a two-QR `.approved` one before this approval + /// showed it as confirming: it goes back to that if the update never + /// lands. + var replacesApprovedRow: Bool? = nil } /// What makes two records the same grant: one session key given for one diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index ec6dd44600..3fd1081f6c 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1070,7 +1070,10 @@ extension AppConnect { enum PendingV2Outcome: Equatable { /// Every key it adds is on the identity, live, as it was added. case landed - /// It can never land, or what it added is off again. + /// It landed, and what it added is off again: its keys were turned + /// off since. + case landedAndOff + /// It can never land. case cannotLand /// It may still land, or the view cannot tell. case unknown @@ -1084,8 +1087,8 @@ extension AppConnect { /// - A key under one of its ids with other data: Platform refuses an /// update that adds an id the identity has, and never removes a key, /// so it can never land. The same data under the id, disabled: it - /// landed and is off again. The same data, live, with other limits or - /// another readable bound: the id is another key's. + /// landed and is off again (`landedAndOff`). The same data, live, with + /// other limits or another readable bound: the id is another key's. /// - Its encryption key (ECDSA_SECP256K1, unique on Platform) under /// another id: it can never land. HASH160 auth keys are not unique, /// so their data elsewhere says nothing. @@ -1116,7 +1119,7 @@ extension AppConnect { } anyPresent = true guard key.data == expected.data else { return .cannotLand } - guard key.disabledAt == nil else { return .cannotLand } + guard key.disabledAt == nil else { return .landedAndOff } let binding = bindings.first { $0.keyId == expected.keyId && $0.data == key.data } if isAddedKey(key, added: expected.identityPubkey, binding: binding) { continue } allLanded = false @@ -1142,6 +1145,7 @@ extension AppConnect { /// Settles the v2 records of `identityId` whose update's outcome was not /// known, by `pendingV2Outcome`. A landed one becomes a grant like any /// other, and the earlier grants its update retired are marked done; one + /// that landed and is off again is dropped with those marked done; one /// that cannot land is dropped; the rest stay as they are. static func settlePendingV2Registrations( in grants: inout [AppConnectGrant], @@ -1165,6 +1169,9 @@ extension AppConnect { settled.unconfirmedKeyHash160 = nil confirmed.append(settled) retired.formUnion(pending.retiredGrantKeys) + case .landedAndOff: + dropped.append(grant) + retired.formUnion(pending.retiredGrantKeys) case .cannotLand: dropped.append(grant) case .unknown: @@ -1181,6 +1188,16 @@ extension AppConnect { return (confirmed, dropped) } + /// Whether a newer confirmed grant of the same connection replaced + /// `grant`: its response is not for the app any more. + static func isReplaced(_ grant: AppConnectGrant, in grants: [AppConnectGrant]) -> Bool { + guard let connectionId = grant.connectionId else { return false } + return grants.contains { + $0.key != grant.key && $0.identityId == grant.identityId && $0.appContractId == grant.appContractId + && $0.connectionId == connectionId && !$0.isUnconfirmed && $0.publishedAt > grant.publishedAt + } + } + /// The ids a confirmed record of `identityId` names, and the ids of the /// keys a v2 record waiting for its update adds that the store shows /// there as added (same data and bound): those are that grant's, not diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index c76a14d0c8..294a129195 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1228,6 +1228,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { throw error } Self.logger.info("🔗 DASHCONNECT :: session key is on the identity although the update reported a failure") + noteOwnUpdateLanded(AppConnect.OwnUpdate(added: [key]), context: context) } Self.logger.info("🔗 DASHCONNECT :: session key registered") sessionKeyId = keyId @@ -1478,7 +1479,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // one that cannot land frees its ids. Nothing is published here: this // approval may still be refused, and its own response is published // once its checks pass. - await confirmRegistrations( + let recoveredAtStart = await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, modelContainer: context.modelContainer, in: stores, bindings: bindings) // Which rotations to derive depends on the keys the identity has. @@ -1517,6 +1518,14 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // keys: its response carries them. A key recorded for another app or // request is that one's, and must not be taken over. let reused = Set(authKeyIds.compactMap { $0 }) + // A confirmed record for this request means its keys are on the + // identity, and a view without them is behind: registering again + // would be refused, or add the same keys under other ids. + guard !reused.isEmpty || !stores.grants.load().contains(where: { + isGrantForRequest($0) && !$0.isUnconfirmed && $0.keyDisabled != true + }) else { + throw DashConnectPlatformError.identityKeysOutOfDate + } if !reused.isEmpty { let grants = stores.grants.load().filter { $0.identityId == identityId } if let recorded = grants.first(where: isGrantForRequest), @@ -1663,7 +1672,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { ).isEmpty else { throw DashConnectPlatformError.identityKeysOutOfDate } - let disable = AppConnect.supersededKeyIds( + // An earlier approval of this request whose update's outcome is not + // known is submitted again as it was: the same keys under the same + // ids and the same disables, so at most one of the two updates can + // land, and what the record says it did holds whichever one does. + let pendingRetry = stores.grants.load().first { isGrantForRequest($0) && $0.isPendingV2 } + let disable = pendingRetry?.pendingUpdate?.disabledKeyIds ?? AppConnect.supersededKeyIds( grants: superseded, identityId: identityId, appId: appId, @@ -1674,17 +1688,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // The confirmed grants whose every key is off once the update lands. let liveAfterUpdate = Set(currentPublicKeys.filter(AppConnect.isLiveGrantedKey) .map { UInt32(bitPattern: $0.keyId) }).subtracting(disable) - let retiredGrantKeys = Set(superseded + let retiredGrantKeys = pendingRetry?.pendingUpdate.map { Set($0.retiredGrantKeys) } ?? Set(superseded .filter { !$0.isUnconfirmed && !$0.keyIds.contains(where: liveAfterUpdate.contains) } .map(\.key)) var add: [ManagedPlatformWallet.IdentityPubkey] = [] var signingKeys: [(publicKey: Data, privateKey: Data)] = [] defer { for index in signingKeys.indices { Self.zero(&signingKeys[index].privateKey) } } - // An earlier approval of this request whose update's outcome is not - // known is submitted again with the same keys under the same ids, so - // at most one of the two updates can land. - let pendingRetry = stores.grants.load().first { isGrantForRequest($0) && $0.isPendingV2 } if let pending = pendingRetry?.pendingUpdate { guard reused.isEmpty else { throw DashConnectPlatformError.identityKeysOutOfDate } let registered = encryptionSlots.indices.filter { encryptionSlots[$0].keyId == nil } @@ -1782,20 +1792,22 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { connectionId: connectionId, encryptionKeyIds: encryptionSlots.compactMap(\.keyId) ) - if !add.isEmpty { - record.unconfirmedKeyHash160 = authKeys[0].publicKeyHash160.toHexString() - record.pendingUpdate = AppConnectGrant.PendingV2Update( - addedKeys: add.map(AppConnect.ExpectedKey.init), - disabledKeyIds: disable, - retiredGrantKeys: retiredGrantKeys.sorted()) - } - let connection = Self.makeConnection( preview: consent, status: .active, updatedAt: now(), loginKind: .oneQR) let modelContainer = context.modelContainer // The app's row before this approval, put back if its update turns // out never to land and nothing else holds the app. let previousRow = rows(in: stores).first { $0.id == connection.id } + if !add.isEmpty { + record.unconfirmedKeyHash160 = authKeys[0].publicKeyHash160.toHexString() + record.pendingUpdate = AppConnectGrant.PendingV2Update( + addedKeys: add.map(AppConnect.ExpectedKey.init), + disabledKeyIds: disable, + retiredGrantKeys: retiredGrantKeys.sorted(), + outlivedBy: nil, + replacesApprovedRow: previousRow?.status == .approved + || pendingRetry?.pendingUpdate?.replacesApprovedRow == true) + } let grant = try await Self.registerAppConnectV2Grant( record, add: add, @@ -1824,8 +1836,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { signer: signer ) } - noteOwnUpdateLanded( - AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), context: context, exceptKey: record.key) }, reread: { guard let keys = try? await refreshedIdentityPublicKeys(context: context), @@ -1839,7 +1849,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let bindings = (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) ?? [] await updateRows(in: stores) { rows in let after = Self.rowsAfterDropping(appIds: [appId], grants: grants, bindings: bindings, rows: rows) - guard let previousRow, !after.contains(where: { $0.id == appId }) else { return after } + guard let previousRow, previousRow.status != .confirming, + !after.contains(where: { $0.id == appId }) else { return after } return after + [previousRow] } } @@ -1851,7 +1862,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } // Every record of this identity still waiting for its update was - // written before this one landed, so this update settles them. A + // written before this one landed, and has it noted: a view that + // shows this update settles them (`AppConnect.pendingV2Outcome`). A // previous grant of this connection that turned out to have landed // holds keys this login replaces: they are turned off too, and its // response is not published. @@ -1873,6 +1885,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { context: context, signer: signer ) + // What the settle above found to have landed, now that this + // approval went through. + await publishRecoveredResponses( + recoveredAtStart.filter { !isGrantForRequest($0) && !isSuperseded($0) }, context: context, signer: signer) return connection } @@ -1886,8 +1902,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// update: a renewal that left some of the replaced keys on would report /// a replacement that did not happen. A disconnect takes them in batches. /// - /// On success the record is confirmed and the grants in - /// `retiredGrantKeys` are marked done. A failure may still have landed: + /// On success the record is confirmed, the grants in `retiredGrantKeys` + /// are marked done, and the update is noted on the identity's other + /// records still waiting for theirs (`AppConnect.noteOwnUpdate`). A + /// failure may still have landed: /// up to three reads (`reread`, `pause` before the second and third) /// settle it by `AppConnect.pendingV2Outcome`. Landed confirms as on /// success; cannot land drops the record, runs `onDropped` and rethrows; @@ -1928,13 +1946,22 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } await showRow() - func confirm() -> AppConnectGrant { + // Once this update is known to have landed, every other record of + // the identity still waiting for its own cannot land after it. + func landed() -> [AppConnectGrant] { var all = grants.load() + AppConnect.noteOwnUpdate( + AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), in: &all, + identityId: record.identityId, exceptKey: record.key) + AppConnect.markKeysDisabled(in: &all) { retiredGrantKeys.contains($0.key) && !$0.isUnconfirmed } + return all + } + func confirm() -> AppConnectGrant { + var all = add.isEmpty && disable.isEmpty ? grants.load() : landed() guard let index = all.firstIndex(where: { $0.key == record.key }) else { return record } all[index].pendingUpdate = nil all[index].unconfirmedKeyHash160 = nil let confirmed = all[index] - AppConnect.markKeysDisabled(in: &all) { retiredGrantKeys.contains($0.key) && !$0.isUnconfirmed } grants.save(all) return confirmed } @@ -1963,6 +1990,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { case .landed: logger.info("🔗 DASHCONNECT :: the identity update landed without confirming") return confirm() + case .landedAndOff: + logger.info("🔗 DASHCONNECT :: the identity update landed, and its keys are off already") + var all = landed() + all.removeAll { $0.key == record.key } + grants.save(all) + await onDropped() + throw error case .cannotLand: logger.info("🔗 DASHCONNECT :: the identity update can no longer land; its record is dropped") var all = grants.load() @@ -2319,9 +2353,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { if !settled.dropped.isEmpty { Self.logger.info("🔗 DASHCONNECT :: dropping \(settled.dropped.count, privacy: .public) App Connect update(s) that can no longer land") let droppedAppIds = Set(settled.dropped.map(\.appContractId)) + let restoring = Set(settled.dropped + .filter { $0.pendingUpdate?.replacesApprovedRow == true }.map(\.appContractId)) let grants = stores.grants.load() await updateRows(in: stores) { rows in - Self.rowsAfterDropping(appIds: droppedAppIds, grants: grants, bindings: bindings, rows: rows) + Self.rowsAfterDropping( + appIds: droppedAppIds, restoringApproved: restoring, grants: grants, bindings: bindings, + rows: rows) } } } @@ -2336,22 +2374,35 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.rowsAfterConfirming(appIds: appIds, in: rows, at: confirmedAt) } } - if let publishing, let responseContractId = Self.decodeIdentifier(AppConnect.contractId) { - for confirmed in confirmedV2 where !except(confirmed) { - guard let grant = stores.grants.load().first(where: { $0.key == confirmed.key }), - let requestHash = AppConnect.data(fromHex: grant.values.appEphemeralPubKeyHash) else { continue } - do { - try await publishAppConnectResponse( - grant: grant, appEphemeralPubKeyHash: requestHash, responseContractId: responseContractId, - context: publishing.context, signer: publishing.signer, cleansUp: false) - } catch { - Self.logger.error("🔗 DASHCONNECT :: the response of a recovered App Connect grant was not published — \(error.localizedDescription, privacy: .public)") - } - } + if let publishing { + await publishRecoveredResponses( + confirmedV2.filter { !except($0) }, context: publishing.context, signer: publishing.signer) } return confirmedV2 } + /// Publishes the responses of `grants`, v2 grants found to have landed + /// after their approval stopped waiting, while their records still have + /// none and no newer grant of the same connection replaced them. Best + /// effort: a failure is logged, and the app asks again. Other responses + /// are left alone: the app may have answered a newer request since. + private func publishRecoveredResponses(_ grants: [AppConnectGrant], context: Context, signer: KeychainSigner) async { + guard let responseContractId = Self.decodeIdentifier(AppConnect.contractId) else { return } + for recovered in grants { + let all = context.stores.grants.load() + guard let grant = all.first(where: { $0.key == recovered.key }), !grant.isUnconfirmed, + grant.keyDisabled != true, !AppConnect.isReplaced(grant, in: all), + let requestHash = AppConnect.data(fromHex: grant.values.appEphemeralPubKeyHash) else { continue } + do { + try await publishAppConnectResponse( + grant: grant, appEphemeralPubKeyHash: requestHash, responseContractId: responseContractId, + context: context, signer: signer, cleansUp: false) + } catch { + Self.logger.error("🔗 DASHCONNECT :: the response of a recovered App Connect grant was not published — \(error.localizedDescription, privacy: .public)") + } + } + } + /// After an update of this wallet to the identity landed (and was noted, /// `noteOwnUpdateLanded`): one more read of the identity, which also /// writes what it shows to the store, and the v2 records of the identity @@ -2372,10 +2423,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// `rows` once the v2 records of `appIds` that were waiting for their /// update are dropped: a row still `.confirming` stays while another /// such record of the app does, becomes active when a confirmed grant of - /// the app or a live key the store shows bound to it remains, and goes - /// otherwise. Any other row is left as it is. + /// the app or a live key the store shows bound to it remains, goes back + /// to the two-QR `.approved` row it replaced (`restoringApproved`), and + /// goes otherwise. Any other row is left as it is. static func rowsAfterDropping( appIds: Set, + restoringApproved: Set = [], grants: [AppConnectGrant], bindings: [AppConnect.KeyBinding], rows: [DAppConnection] @@ -2387,11 +2440,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let appContract = Data.identifier(fromBase58: row.id) let holdsKey = appGrants.contains { !$0.isUnconfirmed && $0.keyDisabled != true } || bindings.contains { !$0.isDisabled && appContract != nil && $0.singleContractId == appContract } - guard holdsKey else { return nil } - var active = DAppConnection( - id: row.id, name: row.name, url: row.url, status: .active, updatedAt: row.updatedAt, loginKind: .oneQR) - active.scope = row.scope - return active + if holdsKey { return row.withStatus(.active, loginKind: .oneQR, at: row.updatedAt) } + guard restoringApproved.contains(row.id) else { return nil } + return row.withStatus(.approved, loginKind: .twoQR, at: row.updatedAt) } } @@ -2422,13 +2473,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { static func rowsAfterConfirming(appIds: Set, in rows: [DAppConnection], at confirmedAt: Date) -> [DAppConnection] { let reconciled = rows.map { connection in guard appIds.contains(connection.id) else { return connection } - var updated = DAppConnection( - id: connection.id, - name: connection.name, - url: connection.url, - status: .active, updatedAt: confirmedAt, loginKind: .oneQR) - updated.scope = connection.scope - return updated + return connection.withStatus(.active, loginKind: .oneQR, at: confirmedAt) } let missing = appIds.subtracting(rows.map(\.id)) return reconciled + missing.sorted().map { appId in @@ -4385,3 +4430,14 @@ enum DashConnectPlatformQueries { return object } } + +extension DAppConnection { + /// This row with another status and login kind, keeping its app, its + /// branding and its scope. + func withStatus(_ status: ConnectionStatus, loginKind: DashConnectLoginKind, at updatedAt: Date) -> DAppConnection { + var row = DAppConnection( + id: id, name: name, url: url, status: status, updatedAt: updatedAt, loginKind: loginKind) + row.scope = scope + return row + } +} diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 76cf09b3d1..d81761c8b7 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1233,7 +1233,7 @@ extension AppConnectV2LoginTests { Self.outcome([auth], keys: [Self.onIdentity(auth, data: Data(repeating: 0xEE, count: 20))]), .cannotLand, "Platform refuses an update that adds an id the identity has") XCTAssertEqual( - Self.outcome([auth], keys: [Self.onIdentity(auth, disabled: true)]), .cannotLand, + Self.outcome([auth], keys: [Self.onIdentity(auth, disabled: true)]), .landedAndOff, "it landed and is off again") XCTAssertEqual( Self.outcome([auth], keys: [Self.onIdentity(auth, totalBudget: .some(1))]), .cannotLand, @@ -1340,6 +1340,36 @@ extension AppConnectV2LoginTests { XCTAssertTrue(grants[3].isPendingV2, "another identity's record waits for a view of that identity") } + func testAPendingUpdateThatLandedAndIsOffAgainIsDroppedWithWhatItRetired() { + let key = Self.addedAuthKey(7, data: 0x07) + let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") + let pending = Self.pendingGrant([key], requestHash: "a1", retiring: [old.key]) + var grants = [old, pending] + let settled = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: "identity", + currentIdentityPublicKeys: [Self.onIdentity(key, disabled: true), Self.key(3, disabled: true)], + bindings: [Self.stored(key)], nowMilliseconds: Self.pendingNow) + XCTAssertEqual(settled.dropped.map(\.key), [pending.key]) + XCTAssertEqual(grants.map(\.key), [old.key]) + XCTAssertEqual(grants[0].keyDisabled, true, "its update turned the replaced grant off") + } + + func testAGrantANewerOneOfTheSameConnectionReplacedIsNotTheAppsAnyMore() { + let older = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") + var newer = Self.grant(sessionKeyId: 5, requestHash: "01", connectionId: "c1") + newer = AppConnectGrant( + identityId: newer.identityId, appContractId: newer.appContractId, documentId: nil, values: newer.values, + sessionKeyId: 5, totalBudget: nil, expiresAt: nil, publishedAt: Date(timeIntervalSince1970: 2_000), + connectionId: "c1") + let otherConnection = Self.grant(sessionKeyId: 7, requestHash: "02", connectionId: "c2") + XCTAssertTrue(AppConnect.isReplaced(older, in: [older, newer])) + XCTAssertFalse(AppConnect.isReplaced(newer, in: [older, newer])) + XCTAssertFalse(AppConnect.isReplaced(otherConnection, in: [older, newer, otherConnection])) + var pendingNewer = newer + pendingNewer.unconfirmedKeyHash160 = "11" + XCTAssertFalse(AppConnect.isReplaced(older, in: [older, pendingNewer]), "a newer one that may never land") + } + func testAPendingV2RecordStillReadsAsUnconfirmedWithoutItsNewField() throws { let grant = Self.pendingGrant([Self.addedAuthKey(7, data: 0x07), Self.addedEncryptionKey(8, data: 0x08)]) let encoded = try JSONEncoder().encode(grant) @@ -1467,6 +1497,10 @@ extension AppConnectV2LoginTests { rows: [row(.confirming)]).map(\.status), [.active], "a live key bound to the app") XCTAssertEqual(after([], rows: [row(.active)]).map(\.status), [.active], "only a confirming row is touched") + let restored = PlatformDashConnectDataSource.rowsAfterDropping( + appIds: [app], restoringApproved: [app], grants: [], bindings: [], rows: [row(.confirming)]) + XCTAssertEqual(restored.map(\.status), [.approved], "the two-QR row it replaced comes back") + XCTAssertEqual(restored.map(\.loginKind), [.twoQR]) } } @@ -1546,6 +1580,29 @@ extension AppConnectV2LoginTests { XCTAssertEqual(store.grants.first { $0.key == old.key }?.keyDisabled, true) } + func testAnUpdateKnownToHaveLandedIsNotedOnTheOtherRecordsWaiting() async throws { + let waiting = Self.pendingGrant([Self.addedAuthKey(9, data: 0x09)], requestHash: "a9") + let key = Self.addedAuthKey(7, data: 0x07) + let succeeded = MemoryGrantStore([waiting]) + _ = try await Self.register(Self.pendingGrant([key]), add: [key], disable: [3], store: succeeded, calls: Calls()) + XCTAssertEqual( + succeeded.grants.first { $0.key == waiting.key }?.pendingUpdate?.outlivedBy, + AppConnect.OwnUpdate(added: [key], disabledKeyIds: [3])) + + let landedAnyway = MemoryGrantStore([waiting]) + _ = try await Self.register( + Self.pendingGrant([key]), add: [key], store: landedAnyway, calls: Calls(), submit: { throw UpdateFailed() }, + views: [([Self.onIdentity(key)], [Self.stored(key)])]) + XCTAssertNotNil(landedAnyway.grants.first { $0.key == waiting.key }?.pendingUpdate?.outlivedBy) + + let unknown = MemoryGrantStore([waiting]) + _ = try? await Self.register( + Self.pendingGrant([key]), add: [key], store: unknown, calls: Calls(), submit: { throw UpdateFailed() }) + XCTAssertNil( + unknown.grants.first { $0.key == waiting.key }?.pendingUpdate?.outlivedBy, + "an update whose outcome is not known proves nothing") + } + func testARenewalThatCannotTurnOffEveryReplacedKeySubmitsNothing() async { let key = Self.addedAuthKey(20, data: 0x14) let store = MemoryGrantStore() From c4d71b858eca0a843720cbc62ffb6a85a23a03c7 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 30 Oct 2026 22:50:00 +0200 Subject: [PATCH 06/29] fix(dashconnect): finish what an App Connect disconnect turned off, and keep one-QR ids reserved A disconnect that turned the app's keys off but could not turn off keys that landed late now marks and cleans up what it did before reporting it. A renewal that sends nothing still retires the grants it replaces. A one-QR registration that may still land keeps its id from a v2 approval. The responses of other grants found to have landed are published at the start of an approval, so a later refusal does not lose them, and the settle after this approval runs once its own response is out. A confirming row is not shown as an existing connection, and a retry that can never land puts the approved row back by what the record says. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 14 +++- .../PlatformDashConnectDataSource.swift | 74 +++++++++++-------- .../DashConnect/AppConnectV2LoginTests.swift | 19 +++++ 3 files changed, 71 insertions(+), 36 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 835f8f7c46..7fb9ee8ca7 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -204,11 +204,17 @@ enum AppConnect { return (0 ... UInt32.max).first { !taken.contains($0) } } - /// The ids the v2 records of `identityId` that wait for their update - /// add keys under: a new key under one of them would make that update, - /// or itself, be refused. + /// The ids the unconfirmed records of `identityId` whose update may + /// still land add keys under: every key of a v2 record waiting for its + /// update, and the session key of a one-QR registration that notes its + /// revision. A new key under one of them would make that update, or + /// itself, be refused. A caller retrying one of them leaves its own + /// record out of `grants`. static func reservedKeyIds(grants: [AppConnectGrant], identityId: String) -> Set { - Set(grants.filter { $0.identityId == identityId }.flatMap { $0.pendingUpdate?.addedKeys.map(\.keyId) ?? [] }) + Set(grants.filter { $0.identityId == identityId && $0.isUnconfirmed }.flatMap { grant -> [UInt32] in + if let pending = grant.pendingUpdate { return pending.addedKeys.map(\.keyId) } + return grant.submittedRevision == nil ? [] : [grant.sessionKeyId] + }) } /// The key an app is given: it can only sign for the contract the request diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 294a129195..69176100d8 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -621,7 +621,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { ) } - let existingConnection = rows(in: context.stores).first { $0.id == fallback.appContractId } + // A row waiting for its update is not a connection the app has yet. + let existingConnection = rows(in: context.stores) + .first { $0.id == fallback.appContractId && $0.status != .confirming } // Which login this network gets is settled here, so the sheet can // show what the app is given. With the version unknown the request @@ -1141,7 +1143,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { case .absent: guard let keyId = AppConnect.nextKeyId( currentIdentityPublicKeys: currentPublicKeys, - reserved: AppConnect.reservedKeyIds(grants: stores.grants.load(), identityId: identityId) + reserved: AppConnect.reservedKeyIds( + grants: stores.grants.load().filter { !isGrantForRequest($0) }, identityId: identityId) ) else { throw DashConnectPlatformError.noFreeKeyId } @@ -1476,12 +1479,16 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let bindings = try Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer) // This identity's records whose update's outcome was not known are // settled first: one that landed is a grant like any other below, and - // one that cannot land frees its ids. Nothing is published here: this - // approval may still be refused, and its own response is published - // once its checks pass. - let recoveredAtStart = await confirmRegistrations( + // one that cannot land frees its ids. The response of one that + // landed is published now, unless it is this request's, published + // once this approval's checks pass, or this connection's, replaced + // by it. + await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores, bindings: bindings) + modelContainer: context.modelContainer, in: stores, bindings: bindings, + publishing: (context, signer), + except: { $0.appContractId == appId && ($0.values.appEphemeralPubKeyHash == requestHash + || (connectionId != nil && $0.connectionId == connectionId)) }) // Which rotations to derive depends on the keys the identity has. for grant in plan.encryption { encryptionKeys.append(try await MainActor.run { @@ -1795,8 +1802,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let connection = Self.makeConnection( preview: consent, status: .active, updatedAt: now(), loginKind: .oneQR) let modelContainer = context.modelContainer - // The app's row before this approval, put back if its update turns - // out never to land and nothing else holds the app. let previousRow = rows(in: stores).first { $0.id == connection.id } if !add.isEmpty { record.unconfirmedKeyHash160 = authKeys[0].publicKeyHash160.toHexString() @@ -1847,11 +1852,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { onDropped: { let grants = stores.grants.load() let bindings = (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) ?? [] + let restoring: Set = record.pendingUpdate?.replacesApprovedRow == true ? [appId] : [] await updateRows(in: stores) { rows in - let after = Self.rowsAfterDropping(appIds: [appId], grants: grants, bindings: bindings, rows: rows) - guard let previousRow, previousRow.status != .confirming, - !after.contains(where: { $0.id == appId }) else { return after } - return after + [previousRow] + Self.rowsAfterDropping( + appIds: [appId], restoringApproved: restoring, grants: grants, bindings: bindings, rows: rows) } } ) @@ -1861,12 +1865,20 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { rows.filter { $0.id != connection.id } + [connection] } + try await publishAppConnectResponse( + grant: grant, + appEphemeralPubKeyHash: plan.appEphemeralPubKeyHash, + responseContractId: responseContractId, + context: context, + signer: signer + ) // Every record of this identity still waiting for its update was // written before this one landed, and has it noted: a view that // shows this update settles them (`AppConnect.pendingV2Outcome`). A // previous grant of this connection that turned out to have landed // holds keys this login replaces: they are turned off too, and its - // response is not published. + // response is not published. This runs after this request's own + // response is out: the app is waiting for it. if !add.isEmpty || !disable.isEmpty, stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { let landed = await settleAfterOwnUpdate( @@ -1877,18 +1889,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.logger.error("🔗 DASHCONNECT :: keys of a replaced grant that landed late are still live — \(error.localizedDescription, privacy: .public)") } } - - try await publishAppConnectResponse( - grant: grant, - appEphemeralPubKeyHash: plan.appEphemeralPubKeyHash, - responseContractId: responseContractId, - context: context, - signer: signer - ) - // What the settle above found to have landed, now that this - // approval went through. - await publishRecoveredResponses( - recoveredAtStart.filter { !isGrantForRequest($0) && !isSuperseded($0) }, context: context, signer: signer) return connection } @@ -1950,14 +1950,16 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // the identity still waiting for its own cannot land after it. func landed() -> [AppConnectGrant] { var all = grants.load() - AppConnect.noteOwnUpdate( - AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), in: &all, - identityId: record.identityId, exceptKey: record.key) + if !add.isEmpty || !disable.isEmpty { + AppConnect.noteOwnUpdate( + AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), in: &all, + identityId: record.identityId, exceptKey: record.key) + } AppConnect.markKeysDisabled(in: &all) { retiredGrantKeys.contains($0.key) && !$0.isUnconfirmed } return all } func confirm() -> AppConnectGrant { - var all = add.isEmpty && disable.isEmpty ? grants.load() : landed() + var all = landed() guard let index = all.firstIndex(where: { $0.key == record.key }) else { return record } all[index].pendingUpdate = nil all[index].unconfirmedKeyHash160 = nil @@ -3030,6 +3032,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // A v2 update of the app whose outcome the read above could not // tell is settled once an update of this disconnect lands. let pendingV2 = Set(stores.grants.load().filter { isGranted($0) && $0.isPendingV2 }.map(\.key)) + var lateDisableFailure: Error? // One that has not is settled by its revision. One that does not // note it takes no part: its key id may belong to another key, and // its absence says nothing. @@ -3196,8 +3199,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let landed = await settleAfterOwnUpdate( context: context, stores: stores, signer: signer, except: { $0.appContractId == appContractId }) ?? [] - try await disableLateLandedGrants( - landed.filter { pendingV2.contains($0.key) }, context: context, signer: signer) + do { + try await disableLateLandedGrants( + landed.filter { pendingV2.contains($0.key) }, context: context, signer: signer) + } catch { + lateDisableFailure = error + } } // The session keys of the grants read above are now off, and only @@ -3214,6 +3221,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { signer: signer ) } + // Keys of the app that landed late and could not be turned off keep + // the row, once what was turned off above is marked. + if let lateDisableFailure { throw lateDisableFailure } // An update of the app whose outcome this disconnect could not tell // keeps the row: the next disconnect settles it by the update that // landed here, which it has noted. diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index d81761c8b7..f527116331 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1390,6 +1390,14 @@ extension AppConnectV2LoginTests { Self.pendingGrant([Self.addedAuthKey(9, data: 0x09)], identityId: "other"), Self.grant(sessionKeyId: 6), ] + var oneQR = Self.grant(sessionKeyId: 12, requestHash: "b1") + oneQR.unconfirmedKeyHash160 = "12" + oneQR.submittedRevision = 3 + var oneQRWithoutRevision = Self.grant(sessionKeyId: 14, requestHash: "b2") + oneQRWithoutRevision.unconfirmedKeyHash160 = "14" + XCTAssertEqual( + AppConnect.reservedKeyIds(grants: grants + [oneQR, oneQRWithoutRevision], identityId: "identity"), + [4, 5, 12], "a one-QR registration that may still land holds its id too") let reserved = AppConnect.reservedKeyIds(grants: grants, identityId: "identity") XCTAssertEqual(reserved, [4, 5]) let keys = [Self.key(0, level: .master), Self.key(1), Self.key(2), Self.key(3)] @@ -1603,6 +1611,17 @@ extension AppConnectV2LoginTests { "an update whose outcome is not known proves nothing") } + func testARenewalThatReusesItsKeysStillRetiresTheGrantsItReplaced() async throws { + var earlier = Self.grant(sessionKeyId: 7, requestHash: "aa", connectionId: "c1") + earlier.documentId = "doc" + let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") + let store = MemoryGrantStore([old, earlier]) + let calls = Calls() + _ = try await Self.register(earlier, add: [], disable: [], retiring: [old.key], store: store, calls: calls) + XCTAssertEqual(calls.submitted, 0, "nothing to send") + XCTAssertEqual(store.grants.first { $0.key == old.key }?.keyDisabled, true) + } + func testARenewalThatCannotTurnOffEveryReplacedKeySubmitsNothing() async { let key = Self.addedAuthKey(20, data: 0x14) let store = MemoryGrantStore() From b2c828c8b37eab11e8fd767d4447e1cff74f9ad6 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 30 Oct 2026 23:03:06 +0200 Subject: [PATCH 07/29] fix(dashconnect): publish recovered App Connect responses until they go out A v2 grant found to have landed is marked as waiting for its response, and every settle point that can sign publishes the marked ones (the one-QR approval among them) until one goes out, instead of only those confirmed in the same call. A pending update with some of its keys off again landed and keeps its record; only one with every key off is dropped. A retry whose connection changed since its first submission waits for that one to settle. A second confirming approval keeps the approved row to restore, and a confirming row is never shown as an existing connection. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 4 ++ .../DashConnect/AppConnectV2Login.swift | 15 +++-- .../PlatformDashConnectDataSource.swift | 56 ++++++++++++++----- .../DashConnect/AppConnectV2LoginTests.swift | 19 +++++++ 4 files changed, 75 insertions(+), 19 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 7fb9ee8ca7..9542875be9 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -710,6 +710,10 @@ struct AppConnectGrant: Codable, Equatable { /// `unconfirmedKeyHash160`, the primary key's hash, so a build that /// does not know this field still reads the record as unconfirmed. var pendingUpdate: PendingV2Update? = nil + /// App Connect v2: the update was found to have landed after its + /// approval stopped waiting, and its response has not been published + /// since (`publishRecoveredResponses`). + var awaitsRecoveredPublish: Bool? = nil var isUnconfirmed: Bool { unconfirmedKeyHash160 != nil } diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 3fd1081f6c..d47cb3c07a 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1083,11 +1083,11 @@ extension AppConnect { /// identity) and `bindings` (the store's bounds) show. No revision is /// guessed: the SDK does not say which revision it signed. /// - /// - Every added key there as it was added: it landed. + /// - Every added key there as it was added, or turned off since: it + /// landed (`landedAndOff` when every one of them is off). /// - A key under one of its ids with other data: Platform refuses an /// update that adds an id the identity has, and never removes a key, - /// so it can never land. The same data under the id, disabled: it - /// landed and is off again (`landedAndOff`). The same data, live, with + /// so it can never land. The same data, live, with /// other limits or another readable bound: the id is another key's. /// - Its encryption key (ECDSA_SECP256K1, unique on Platform) under /// another id: it can never land. HASH160 auth keys are not unique, @@ -1112,6 +1112,7 @@ extension AppConnect { ) -> PendingV2Outcome { var allLanded = true var anyPresent = false + var offCount = 0 for expected in pending.addedKeys { guard let key = keys.first(where: { UInt32(bitPattern: $0.keyId) == expected.keyId }) else { allLanded = false @@ -1119,14 +1120,17 @@ extension AppConnect { } anyPresent = true guard key.data == expected.data else { return .cannotLand } - guard key.disabledAt == nil else { return .landedAndOff } + guard key.disabledAt == nil else { + offCount += 1 + continue + } let binding = bindings.first { $0.keyId == expected.keyId && $0.data == key.data } if isAddedKey(key, added: expected.identityPubkey, binding: binding) { continue } allLanded = false if expected.bound != nil, binding == nil || binding?.hasUnreadableBound == true { continue } return .cannotLand } - if allLanded { return .landed } + if allLanded { return offCount == pending.addedKeys.count ? .landedAndOff : .landed } let takenElsewhere = pending.addedKeys.contains { expected in expected.keyType == .ecdsaSecp256k1 && keys.contains { $0.keyType == .ecdsaSecp256k1 && $0.data == expected.data @@ -1167,6 +1171,7 @@ extension AppConnect { var settled = grant settled.pendingUpdate = nil settled.unconfirmedKeyHash160 = nil + settled.awaitsRecoveredPublish = true confirmed.append(settled) retired.formUnion(pending.retiredGrantKeys) case .landedAndOff: diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 69176100d8..54d336c097 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -609,7 +609,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { do { context = try await requireContext() } catch { - let existingConnection = await shownRow(id: fallback.appContractId) + let shown = await shownRow(id: fallback.appContractId) + let existingConnection = shown?.status == .confirming ? nil : shown return ConnectionRequest( loginRequest: loginRequest, appLabel: fallback.appLabel, @@ -1101,7 +1102,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let currentPublicKeys = try await refreshedIdentityPublicKeys(context: context) await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores) + modelContainer: context.modelContainer, in: stores, publishing: (context, signer)) func isGrantForRequest(_ grant: AppConnectGrant) -> Bool { grant.identityId == identityId && grant.appContractId == appContractId && grant.values.appEphemeralPubKeyHash == requestHash @@ -1368,6 +1369,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { updateGrants(in: stores) { grants in guard let index = grants.firstIndex(where: { $0.key == grant.key }) else { return } grants[index].documentId = documentId.toBase58String() + grants[index].awaitsRecoveredPublish = nil grants[index].values = publishedValues } } @@ -1704,6 +1706,17 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { defer { for index in signingKeys.indices { Self.zero(&signingKeys[index].privateKey) } } if let pending = pendingRetry?.pendingUpdate { guard reused.isEmpty else { throw DashConnectPlatformError.identityKeysOutOfDate } + // The earlier update replaced what the connection held then. If + // that changed since (a replaced key is off, or another grant of + // the connection turned up), sending it again would be refused + // or leave a key on; its outcome has to settle first. + let current = AppConnect.supersededKeyIds( + grants: superseded, identityId: identityId, appId: appId, connectionId: connectionId, + keeping: reused, currentIdentityPublicKeys: currentPublicKeys) + guard Set(current) == Set(pending.disabledKeyIds) else { + Self.logger.error("🔗 DASHCONNECT :: an earlier approval of this request may still land, and the connection changed since") + throw DashConnectPlatformError.registrationPending + } let registered = encryptionSlots.indices.filter { encryptionSlots[$0].keyId == nil } func encryptionKey(_ slot: Int) -> AppConnect.DerivedEncryptionKey { encryptionKeys[encryptionSlots[slot].keyIndex][encryptionSlots[slot].derivedIndex] @@ -1811,7 +1824,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { retiredGrantKeys: retiredGrantKeys.sorted(), outlivedBy: nil, replacesApprovedRow: previousRow?.status == .approved - || pendingRetry?.pendingUpdate?.replacesApprovedRow == true) + || (previousRow?.status == .confirming && stores.grants.load().contains { + $0.appContractId == appId && $0.pendingUpdate?.replacesApprovedRow == true + })) } let grant = try await Self.registerAppConnectV2Grant( record, @@ -2377,24 +2392,37 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } } if let publishing { - await publishRecoveredResponses( - confirmedV2.filter { !except($0) }, context: publishing.context, signer: publishing.signer) + await publishRecoveredResponses(context: publishing.context, signer: publishing.signer, except: except) } return confirmedV2 } - /// Publishes the responses of `grants`, v2 grants found to have landed - /// after their approval stopped waiting, while their records still have - /// none and no newer grant of the same connection replaced them. Best - /// effort: a failure is logged, and the app asks again. Other responses - /// are left alone: the app may have answered a newer request since. - private func publishRecoveredResponses(_ grants: [AppConnectGrant], context: Context, signer: KeychainSigner) async { + /// Publishes the responses of this identity's v2 grants found to have + /// landed after their approval stopped waiting (`awaitsRecoveredPublish`), + /// but those `except` names, while no newer grant of the same connection + /// replaced them. Best effort: a failure is logged and tried again by the + /// next call. Other responses are left alone: the app may have answered + /// a newer request since. + private func publishRecoveredResponses( + context: Context, + signer: KeychainSigner, + except: (AppConnectGrant) -> Bool = { _ in false } + ) async { guard let responseContractId = Self.decodeIdentifier(AppConnect.contractId) else { return } - for recovered in grants { + let identityId = context.identityId.toBase58String() + let recovered = context.stores.grants.load() + .filter { $0.identityId == identityId && $0.awaitsRecoveredPublish == true && !except($0) } + for candidate in recovered { let all = context.stores.grants.load() - guard let grant = all.first(where: { $0.key == recovered.key }), !grant.isUnconfirmed, + guard let grant = all.first(where: { $0.key == candidate.key }), !grant.isUnconfirmed, grant.keyDisabled != true, !AppConnect.isReplaced(grant, in: all), - let requestHash = AppConnect.data(fromHex: grant.values.appEphemeralPubKeyHash) else { continue } + let requestHash = AppConnect.data(fromHex: grant.values.appEphemeralPubKeyHash) else { + updateGrants(in: context.stores) { grants in + guard let index = grants.firstIndex(where: { $0.key == candidate.key }) else { return } + grants[index].awaitsRecoveredPublish = nil + } + continue + } do { try await publishAppConnectResponse( grant: grant, appEphemeralPubKeyHash: requestHash, responseContractId: responseContractId, diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index f527116331..b2950c77ad 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1227,6 +1227,25 @@ extension AppConnectV2LoginTests { "a view that shows part of one update is behind") } + func testAPendingUpdateWithSomeKeysOffAgainLandedAndKeepsItsRecord() { + let first = Self.addedAuthKey(7, data: 0x07) + let second = Self.addedAuthKey(8, data: 0x08) + XCTAssertEqual( + Self.outcome([first, second], keys: [Self.onIdentity(first), Self.onIdentity(second, disabled: true)]), + .landed, "a live key of it still needs its record") + XCTAssertEqual( + Self.outcome([first, second], keys: [ + Self.onIdentity(first, disabled: true), Self.onIdentity(second, disabled: true), + ]), + .landedAndOff) + var grants = [Self.pendingGrant([first, second])] + _ = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: "identity", + currentIdentityPublicKeys: [Self.onIdentity(first), Self.onIdentity(second)], + bindings: [Self.stored(first), Self.stored(second)], nowMilliseconds: Self.pendingNow) + XCTAssertEqual(grants[0].awaitsRecoveredPublish, true, "its response is still to be published") + } + func testAnIdHeldByAnotherKeyMeansThePendingUpdateCanNeverLand() { let auth = Self.addedAuthKey(7, data: 0x07) XCTAssertEqual( From 36918b322c50f51739191376b8ee778910d07ca7 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 30 Oct 2026 23:25:25 +0200 Subject: [PATCH 08/29] fix(dashconnect): confirm a late-landed App Connect v2 grant without publishing its response A grant found to have landed after its approval stopped waiting is now only confirmed and shown; its response is not published, and the app asks again. This removes the recovered-publish path and its flag. Also: rows of dropped records are left as they are when the key store cannot be read, instead of being judged against no keys; one helper writes them for both the approval and the settle; a retry whose connection changed since says so instead of describing a disconnect; the unused exception of noteOwnUpdateLanded is gone. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 4 - .../DashConnect/AppConnectV2Login.swift | 13 +- .../PlatformDashConnectDataSource.swift | 184 +++++++----------- DashWallet/ar.lproj/Localizable.strings | 1 + DashWallet/bg.lproj/Localizable.strings | 1 + DashWallet/ca.lproj/Localizable.strings | 1 + DashWallet/cs.lproj/Localizable.strings | 1 + DashWallet/da.lproj/Localizable.strings | 1 + DashWallet/de.lproj/Localizable.strings | 1 + DashWallet/el.lproj/Localizable.strings | 1 + DashWallet/en.lproj/Localizable.strings | 1 + DashWallet/eo.lproj/Localizable.strings | 1 + DashWallet/es.lproj/Localizable.strings | 1 + DashWallet/et.lproj/Localizable.strings | 1 + DashWallet/fa.lproj/Localizable.strings | 1 + DashWallet/fi.lproj/Localizable.strings | 1 + DashWallet/fil.lproj/Localizable.strings | 1 + DashWallet/fr.lproj/Localizable.strings | 1 + DashWallet/hr.lproj/Localizable.strings | 1 + DashWallet/hu.lproj/Localizable.strings | 1 + DashWallet/id.lproj/Localizable.strings | 1 + DashWallet/it.lproj/Localizable.strings | 1 + DashWallet/ja.lproj/Localizable.strings | 1 + DashWallet/ko.lproj/Localizable.strings | 1 + DashWallet/mk.lproj/Localizable.strings | 1 + DashWallet/ms.lproj/Localizable.strings | 1 + DashWallet/nb.lproj/Localizable.strings | 1 + DashWallet/nl.lproj/Localizable.strings | 1 + DashWallet/pl.lproj/Localizable.strings | 1 + DashWallet/pt.lproj/Localizable.strings | 1 + DashWallet/ro.lproj/Localizable.strings | 1 + DashWallet/ru.lproj/Localizable.strings | 1 + DashWallet/sk.lproj/Localizable.strings | 1 + DashWallet/sl.lproj/Localizable.strings | 1 + DashWallet/sl_SI.lproj/Localizable.strings | 1 + DashWallet/sq.lproj/Localizable.strings | 1 + DashWallet/sr.lproj/Localizable.strings | 1 + DashWallet/sv.lproj/Localizable.strings | 1 + DashWallet/th.lproj/Localizable.strings | 1 + DashWallet/tr.lproj/Localizable.strings | 1 + DashWallet/uk.lproj/Localizable.strings | 1 + DashWallet/vi.lproj/Localizable.strings | 1 + DashWallet/zh-Hans.lproj/Localizable.strings | 1 + .../zh-Hant-TW.lproj/Localizable.strings | 1 + DashWallet/zh.lproj/Localizable.strings | 1 + DashWallet/zh_TW.lproj/Localizable.strings | 1 + .../DashConnect/AppConnectV2LoginTests.swift | 22 --- 47 files changed, 114 insertions(+), 152 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 9542875be9..7fb9ee8ca7 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -710,10 +710,6 @@ struct AppConnectGrant: Codable, Equatable { /// `unconfirmedKeyHash160`, the primary key's hash, so a build that /// does not know this field still reads the record as unconfirmed. var pendingUpdate: PendingV2Update? = nil - /// App Connect v2: the update was found to have landed after its - /// approval stopped waiting, and its response has not been published - /// since (`publishRecoveredResponses`). - var awaitsRecoveredPublish: Bool? = nil var isUnconfirmed: Bool { unconfirmedKeyHash160 != nil } diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index d47cb3c07a..8e73991440 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1148,7 +1148,7 @@ extension AppConnect { /// Settles the v2 records of `identityId` whose update's outcome was not /// known, by `pendingV2Outcome`. A landed one becomes a grant like any - /// other, and the earlier grants its update retired are marked done; one + /// other (its response is not published: its approval stopped waiting), and the earlier grants its update retired are marked done; one /// that landed and is off again is dropped with those marked done; one /// that cannot land is dropped; the rest stay as they are. static func settlePendingV2Registrations( @@ -1171,7 +1171,6 @@ extension AppConnect { var settled = grant settled.pendingUpdate = nil settled.unconfirmedKeyHash160 = nil - settled.awaitsRecoveredPublish = true confirmed.append(settled) retired.formUnion(pending.retiredGrantKeys) case .landedAndOff: @@ -1193,16 +1192,6 @@ extension AppConnect { return (confirmed, dropped) } - /// Whether a newer confirmed grant of the same connection replaced - /// `grant`: its response is not for the app any more. - static func isReplaced(_ grant: AppConnectGrant, in grants: [AppConnectGrant]) -> Bool { - guard let connectionId = grant.connectionId else { return false } - return grants.contains { - $0.key != grant.key && $0.identityId == grant.identityId && $0.appContractId == grant.appContractId - && $0.connectionId == connectionId && !$0.isUnconfirmed && $0.publishedAt > grant.publishedAt - } - } - /// The ids a confirmed record of `identityId` names, and the ids of the /// keys a v2 record waiting for its update adds that the store shows /// there as added (same data and bound): those are that grant's, not diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 54d336c097..5a66dbaff3 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -85,6 +85,7 @@ enum DashConnectPlatformError: LocalizedError, Equatable { case grantNotRecorded case noFreeKeyId case tooManyKeysToReplace + case earlierApprovalPending case otherIdentitiesNotChecked case registrationPending case appConnectEncryptionKeyChanged @@ -183,6 +184,10 @@ enum DashConnectPlatformError: LocalizedError, Equatable { return NSLocalizedString("The active wallet or identity changed. Try again.", comment: "DashConnect") case .noFreeKeyId: return NSLocalizedString("This identity cannot take another key.", comment: "DashConnect") + case .earlierApprovalPending: + return NSLocalizedString( + "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code.", + comment: "DashConnect") case .tooManyKeysToReplace: return NSLocalizedString( "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again.", @@ -1102,7 +1107,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let currentPublicKeys = try await refreshedIdentityPublicKeys(context: context) await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores, publishing: (context, signer)) + modelContainer: context.modelContainer, in: stores) func isGrantForRequest(_ grant: AppConnectGrant) -> Bool { grant.identityId == identityId && grant.appContractId == appContractId && grant.values.appEphemeralPubKeyHash == requestHash @@ -1289,8 +1294,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { appEphemeralPubKeyHash: Data, responseContractId: Data, context: Context, - signer: KeychainSigner, - cleansUp: Bool = true + signer: KeychainSigner ) async throws { let stores = context.stores let identityId = grant.identityId @@ -1316,17 +1320,15 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // Besides this app's earlier responses, this takes whatever an earlier // disconnect of any app left behind for this identity: its row is // gone, so a login is the only moment left to finish that cleanup. - if cleansUp { - await deleteAppConnectResponses( - where: { - Self.isLeftoverResponse( - $0, identityId: identityId, appContractId: appContractId, requestHash: requestHash) - }, - responseContractId: responseContractId, - context: context, - signer: signer - ) - } + await deleteAppConnectResponses( + where: { + Self.isLeftoverResponse( + $0, identityId: identityId, appContractId: appContractId, requestHash: requestHash) + }, + responseContractId: responseContractId, + context: context, + signer: signer + ) // Recorded before the publish is submitted: a response this record // had as deleted may be back on Platform after a publish that fails @@ -1369,7 +1371,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { updateGrants(in: stores) { grants in guard let index = grants.firstIndex(where: { $0.key == grant.key }) else { return } grants[index].documentId = documentId.toBase58String() - grants[index].awaitsRecoveredPublish = nil grants[index].values = publishedValues } } @@ -1480,17 +1481,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let currentPublicKeys = try await refreshedIdentityPublicKeys(context: context) let bindings = try Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer) // This identity's records whose update's outcome was not known are - // settled first: one that landed is a grant like any other below, and - // one that cannot land frees its ids. The response of one that - // landed is published now, unless it is this request's, published - // once this approval's checks pass, or this connection's, replaced - // by it. + // settled first: one that landed is a grant like any other below (for + // this request, its keys are sent again and its response published + // as on any retry), and one that cannot land frees its ids. await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores, bindings: bindings, - publishing: (context, signer), - except: { $0.appContractId == appId && ($0.values.appEphemeralPubKeyHash == requestHash - || (connectionId != nil && $0.connectionId == connectionId)) }) + modelContainer: context.modelContainer, in: stores, bindings: bindings) // Which rotations to derive depends on the keys the identity has. for grant in plan.encryption { encryptionKeys.append(try await MainActor.run { @@ -1715,7 +1711,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { keeping: reused, currentIdentityPublicKeys: currentPublicKeys) guard Set(current) == Set(pending.disabledKeyIds) else { Self.logger.error("🔗 DASHCONNECT :: an earlier approval of this request may still land, and the connection changed since") - throw DashConnectPlatformError.registrationPending + throw DashConnectPlatformError.earlierApprovalPending } let registered = encryptionSlots.indices.filter { encryptionSlots[$0].keyId == nil } func encryptionKey(_ slot: Int) -> AppConnect.DerivedEncryptionKey { @@ -1865,13 +1861,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { }, pause: { _ in try? await Task.sleep(nanoseconds: 3_000_000_000) }, onDropped: { - let grants = stores.grants.load() - let bindings = (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) ?? [] - let restoring: Set = record.pendingUpdate?.replacesApprovedRow == true ? [appId] : [] - await updateRows(in: stores) { rows in - Self.rowsAfterDropping( - appIds: [appId], restoringApproved: restoring, grants: grants, bindings: bindings, rows: rows) - } + await showRowsAfterDropping( + [record], + bindings: try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer), + in: stores) } ) @@ -1891,13 +1884,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // written before this one landed, and has it noted: a view that // shows this update settles them (`AppConnect.pendingV2Outcome`). A // previous grant of this connection that turned out to have landed - // holds keys this login replaces: they are turned off too, and its - // response is not published. This runs after this request's own - // response is out: the app is waiting for it. + // holds keys this login replaces: they are turned off too. This runs + // after this request's own response is out: the app is waiting for + // it. if !add.isEmpty || !disable.isEmpty, stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { - let landed = await settleAfterOwnUpdate( - context: context, stores: stores, signer: signer, except: isSuperseded) ?? [] + let landed = await settleAfterOwnUpdate(context: context, stores: stores) ?? [] do { try await disableLateLandedGrants(landed.filter(isSuperseded), context: context, signer: signer) } catch { @@ -2322,29 +2314,25 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// two-QR login. /// /// A v2 record whose update's outcome was not known is settled by - /// `AppConnect.settlePendingV2Registrations`: one that cannot land is - /// dropped, and its row with it when nothing else holds it - /// (`rowsAfterDropping`). With `publishing`, the response of each one - /// that landed is published unless `except` says otherwise; best effort, - /// as a later login retries it, and with no cleanup of other responses: - /// the app may have answered a newer request since. Returns the v2 - /// grants confirmed. + /// `AppConnect.settlePendingV2Registrations`. One that landed is confirmed + /// and its row shown; its response is not published: its approval + /// stopped waiting, and the app asks again. One that cannot land is + /// dropped (`rowsAfterDroppingRecords`). Returns the v2 grants confirmed. @discardableResult private func confirmRegistrations( identityId: String, currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], modelContainer: ModelContainer, in stores: Stores, - bindings knownBindings: [AppConnect.KeyBinding]? = nil, - publishing: (context: Context, signer: KeychainSigner)? = nil, - except: (AppConnectGrant) -> Bool = { _ in false } + bindings knownBindings: [AppConnect.KeyBinding]? = nil ) async -> [AppConnectGrant] { guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) else { return [] } - // Without the store's bindings no unconfirmed record is confirmed, - // and a confirmed one does not need them. - let bindings = knownBindings - ?? (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) ?? [] + // Unknown when the store cannot be read: no unconfirmed record is + // confirmed without it, and no row is changed by it. + let readBindings = knownBindings + ?? (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) + let bindings = readBindings ?? [] if stores.grants.load().contains(where: { $0.identityId == identityId && $0.isUnconfirmed }) { let confirmed = updateGrants(in: stores) { grants in AppConnect.confirmRegistrations( @@ -2369,15 +2357,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } if !settled.dropped.isEmpty { Self.logger.info("🔗 DASHCONNECT :: dropping \(settled.dropped.count, privacy: .public) App Connect update(s) that can no longer land") - let droppedAppIds = Set(settled.dropped.map(\.appContractId)) - let restoring = Set(settled.dropped - .filter { $0.pendingUpdate?.replacesApprovedRow == true }.map(\.appContractId)) - let grants = stores.grants.load() - await updateRows(in: stores) { rows in - Self.rowsAfterDropping( - appIds: droppedAppIds, restoringApproved: restoring, grants: grants, bindings: bindings, - rows: rows) - } + await showRowsAfterDropping(settled.dropped, bindings: readBindings, in: stores) } } let appIds = Self.appIdsWithoutTheirOneQRRow( @@ -2391,45 +2371,28 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.rowsAfterConfirming(appIds: appIds, in: rows, at: confirmedAt) } } - if let publishing { - await publishRecoveredResponses(context: publishing.context, signer: publishing.signer, except: except) - } return confirmedV2 } - /// Publishes the responses of this identity's v2 grants found to have - /// landed after their approval stopped waiting (`awaitsRecoveredPublish`), - /// but those `except` names, while no newer grant of the same connection - /// replaced them. Best effort: a failure is logged and tried again by the - /// next call. Other responses are left alone: the app may have answered - /// a newer request since. - private func publishRecoveredResponses( - context: Context, - signer: KeychainSigner, - except: (AppConnectGrant) -> Bool = { _ in false } + /// Writes the rows of the apps whose v2 records in `dropped` were + /// dropped (`rowsAfterDropping`). With the store's bindings unknown + /// (`nil`) no row is changed: a live key bound to the app could not be + /// ruled out, and a confirming row can still be disconnected. + private func showRowsAfterDropping( + _ dropped: [AppConnectGrant], + bindings: [AppConnect.KeyBinding]?, + in stores: Stores ) async { - guard let responseContractId = Self.decodeIdentifier(AppConnect.contractId) else { return } - let identityId = context.identityId.toBase58String() - let recovered = context.stores.grants.load() - .filter { $0.identityId == identityId && $0.awaitsRecoveredPublish == true && !except($0) } - for candidate in recovered { - let all = context.stores.grants.load() - guard let grant = all.first(where: { $0.key == candidate.key }), !grant.isUnconfirmed, - grant.keyDisabled != true, !AppConnect.isReplaced(grant, in: all), - let requestHash = AppConnect.data(fromHex: grant.values.appEphemeralPubKeyHash) else { - updateGrants(in: context.stores) { grants in - guard let index = grants.firstIndex(where: { $0.key == candidate.key }) else { return } - grants[index].awaitsRecoveredPublish = nil - } - continue - } - do { - try await publishAppConnectResponse( - grant: grant, appEphemeralPubKeyHash: requestHash, responseContractId: responseContractId, - context: context, signer: signer, cleansUp: false) - } catch { - Self.logger.error("🔗 DASHCONNECT :: the response of a recovered App Connect grant was not published — \(error.localizedDescription, privacy: .public)") - } + guard let bindings else { + Self.logger.error("🔗 DASHCONNECT :: the key store could not be read; rows of dropped App Connect updates stay") + return + } + let grants = stores.grants.load() + let restoring = Set(dropped.filter { $0.pendingUpdate?.replacesApprovedRow == true }.map(\.appContractId)) + await updateRows(in: stores) { rows in + Self.rowsAfterDropping( + appIds: Set(dropped.map(\.appContractId)), restoringApproved: restoring, grants: grants, + bindings: bindings, rows: rows) } } @@ -2438,16 +2401,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// writes what it shows to the store, and the v2 records of the identity /// waiting for their outcome are settled by it. Returns the v2 grants /// confirmed, or nil when the read failed. - private func settleAfterOwnUpdate( - context: Context, - stores: Stores, - signer: KeychainSigner, - except: (AppConnectGrant) -> Bool = { _ in false } - ) async -> [AppConnectGrant]? { + private func settleAfterOwnUpdate(context: Context, stores: Stores) async -> [AppConnectGrant]? { guard let keys = try? await refreshedIdentityPublicKeys(context: context) else { return nil } return await confirmRegistrations( identityId: context.identityId.toBase58String(), currentIdentityPublicKeys: keys, - modelContainer: context.modelContainer, in: stores, publishing: (context, signer), except: except) + modelContainer: context.modelContainer, in: stores) } /// `rows` once the v2 records of `appIds` that were waiting for their @@ -2766,7 +2724,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // then the app's, not shared. await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores, publishing: (context, signer)) + modelContainer: context.modelContainer, in: stores) let bindings = try Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer) guard let keyIds = AppConnect.sharedProfileKeyIdsToDisable( recordedKeyIds: Self.recordedKeyIds(of: identityId, in: stores, bindings: bindings), @@ -2782,7 +2740,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // The reload writes the disabled keys to the store the count is read // from, and settles the v2 records still waiting for their update. // The keys are off either way. - _ = await settleAfterOwnUpdate(context: context, stores: stores, signer: signer) + _ = await settleAfterOwnUpdate(context: context, stores: stores) return keyIds.count } @@ -3055,8 +3013,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // A registration whose key has turned up is confirmed. await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores, publishing: (context, signer), - except: { $0.appContractId == appContractId }) + modelContainer: context.modelContainer, in: stores) // A v2 update of the app whose outcome the read above could not // tell is settled once an update of this disconnect lands. let pendingV2 = Set(stores.grants.load().filter { isGranted($0) && $0.isPendingV2 }.map(\.key)) @@ -3224,9 +3181,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // waiting for their update: this disconnect's update landed after // them. One of the app's that turns out to have landed holds keys // that are turned off too. The keys above are off either way. - let landed = await settleAfterOwnUpdate( - context: context, stores: stores, signer: signer, - except: { $0.appContractId == appContractId }) ?? [] + let landed = await settleAfterOwnUpdate(context: context, stores: stores) ?? [] do { try await disableLateLandedGrants( landed.filter { pendingV2.contains($0.key) }, context: context, signer: signer) @@ -3284,16 +3239,17 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } /// An update of this wallet to the identity returned success: every v2 - /// record of the identity still waiting for its own update (but - /// `exceptKey`'s, the update's own) cannot land after it, which a later - /// view that shows `update` settles (`AppConnect.pendingV2Outcome`). - private func noteOwnUpdateLanded(_ update: AppConnect.OwnUpdate, context: Context, exceptKey: String? = nil) { + /// record of the identity still waiting for its own update cannot land + /// after it, which a later view that shows `update` settles + /// (`AppConnect.pendingV2Outcome`). The v2 approval notes its own update + /// in `registerAppConnectV2Grant`, leaving its own record out. + private func noteOwnUpdateLanded(_ update: AppConnect.OwnUpdate, context: Context) { let identityId = context.identityId.toBase58String() guard context.stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) else { return } updateGrants(in: context.stores) { grants in - AppConnect.noteOwnUpdate(update, in: &grants, identityId: identityId, exceptKey: exceptKey) + AppConnect.noteOwnUpdate(update, in: &grants, identityId: identityId) } } diff --git a/DashWallet/ar.lproj/Localizable.strings b/DashWallet/ar.lproj/Localizable.strings index da010463d0..2bf40834b7 100644 --- a/DashWallet/ar.lproj/Localizable.strings +++ b/DashWallet/ar.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/bg.lproj/Localizable.strings b/DashWallet/bg.lproj/Localizable.strings index 0bc102a8a8..cc2103057d 100644 --- a/DashWallet/bg.lproj/Localizable.strings +++ b/DashWallet/bg.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ca.lproj/Localizable.strings b/DashWallet/ca.lproj/Localizable.strings index a19e4a14db..1045717564 100644 --- a/DashWallet/ca.lproj/Localizable.strings +++ b/DashWallet/ca.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/cs.lproj/Localizable.strings b/DashWallet/cs.lproj/Localizable.strings index aab6e4af85..4d381f51d0 100644 --- a/DashWallet/cs.lproj/Localizable.strings +++ b/DashWallet/cs.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/da.lproj/Localizable.strings b/DashWallet/da.lproj/Localizable.strings index 0f8c62915d..6aa5533c93 100644 --- a/DashWallet/da.lproj/Localizable.strings +++ b/DashWallet/da.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/de.lproj/Localizable.strings b/DashWallet/de.lproj/Localizable.strings index 41a5256e7b..b92dbeb9b4 100644 --- a/DashWallet/de.lproj/Localizable.strings +++ b/DashWallet/de.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/el.lproj/Localizable.strings b/DashWallet/el.lproj/Localizable.strings index dcba37e099..625da84281 100644 --- a/DashWallet/el.lproj/Localizable.strings +++ b/DashWallet/el.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index 3efe3a3f3a..9c0b8dc6e1 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -6137,6 +6137,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; "This wallet cannot approve the scanned request (%@)." = "This wallet cannot approve the scanned request (%@)."; diff --git a/DashWallet/eo.lproj/Localizable.strings b/DashWallet/eo.lproj/Localizable.strings index e60c1661c2..be8cd9fcc0 100644 --- a/DashWallet/eo.lproj/Localizable.strings +++ b/DashWallet/eo.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/es.lproj/Localizable.strings b/DashWallet/es.lproj/Localizable.strings index 71af2eae14..7a28752e21 100644 --- a/DashWallet/es.lproj/Localizable.strings +++ b/DashWallet/es.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/et.lproj/Localizable.strings b/DashWallet/et.lproj/Localizable.strings index d59d514b1c..8f967c92fd 100644 --- a/DashWallet/et.lproj/Localizable.strings +++ b/DashWallet/et.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/fa.lproj/Localizable.strings b/DashWallet/fa.lproj/Localizable.strings index 592bb4e818..83c41bff2e 100644 --- a/DashWallet/fa.lproj/Localizable.strings +++ b/DashWallet/fa.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/fi.lproj/Localizable.strings b/DashWallet/fi.lproj/Localizable.strings index af26649b1b..b05712a0a6 100644 --- a/DashWallet/fi.lproj/Localizable.strings +++ b/DashWallet/fi.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/fil.lproj/Localizable.strings b/DashWallet/fil.lproj/Localizable.strings index 88e745aab7..e1f6ff0a9c 100644 --- a/DashWallet/fil.lproj/Localizable.strings +++ b/DashWallet/fil.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/fr.lproj/Localizable.strings b/DashWallet/fr.lproj/Localizable.strings index 0268a04ca2..4680bf2dab 100644 --- a/DashWallet/fr.lproj/Localizable.strings +++ b/DashWallet/fr.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/hr.lproj/Localizable.strings b/DashWallet/hr.lproj/Localizable.strings index 4007ed5972..38a27cda21 100644 --- a/DashWallet/hr.lproj/Localizable.strings +++ b/DashWallet/hr.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/hu.lproj/Localizable.strings b/DashWallet/hu.lproj/Localizable.strings index 638ab75dfa..3683e50453 100644 --- a/DashWallet/hu.lproj/Localizable.strings +++ b/DashWallet/hu.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/id.lproj/Localizable.strings b/DashWallet/id.lproj/Localizable.strings index 85fb3e5ea9..433ab3a849 100644 --- a/DashWallet/id.lproj/Localizable.strings +++ b/DashWallet/id.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/it.lproj/Localizable.strings b/DashWallet/it.lproj/Localizable.strings index 8d5aa442a4..b5e9e2f65f 100644 --- a/DashWallet/it.lproj/Localizable.strings +++ b/DashWallet/it.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ja.lproj/Localizable.strings b/DashWallet/ja.lproj/Localizable.strings index c98aee61c7..131c36a8e3 100644 --- a/DashWallet/ja.lproj/Localizable.strings +++ b/DashWallet/ja.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ko.lproj/Localizable.strings b/DashWallet/ko.lproj/Localizable.strings index 13eacf1123..11bbf2ee08 100644 --- a/DashWallet/ko.lproj/Localizable.strings +++ b/DashWallet/ko.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/mk.lproj/Localizable.strings b/DashWallet/mk.lproj/Localizable.strings index 5a92cba34c..f87bb49b43 100644 --- a/DashWallet/mk.lproj/Localizable.strings +++ b/DashWallet/mk.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ms.lproj/Localizable.strings b/DashWallet/ms.lproj/Localizable.strings index 81756421bd..950af63931 100644 --- a/DashWallet/ms.lproj/Localizable.strings +++ b/DashWallet/ms.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/nb.lproj/Localizable.strings b/DashWallet/nb.lproj/Localizable.strings index 333c5bdca8..2fa68641c8 100644 --- a/DashWallet/nb.lproj/Localizable.strings +++ b/DashWallet/nb.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/nl.lproj/Localizable.strings b/DashWallet/nl.lproj/Localizable.strings index 423b932455..5ee24cfcdc 100644 --- a/DashWallet/nl.lproj/Localizable.strings +++ b/DashWallet/nl.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/pl.lproj/Localizable.strings b/DashWallet/pl.lproj/Localizable.strings index 680d150e82..f8e092cde0 100644 --- a/DashWallet/pl.lproj/Localizable.strings +++ b/DashWallet/pl.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/pt.lproj/Localizable.strings b/DashWallet/pt.lproj/Localizable.strings index 8089a0cb86..35b426fdb6 100644 --- a/DashWallet/pt.lproj/Localizable.strings +++ b/DashWallet/pt.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ro.lproj/Localizable.strings b/DashWallet/ro.lproj/Localizable.strings index 0343c32dcf..6d99eb18e4 100644 --- a/DashWallet/ro.lproj/Localizable.strings +++ b/DashWallet/ro.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/ru.lproj/Localizable.strings b/DashWallet/ru.lproj/Localizable.strings index efd77d2c6f..deae530b68 100644 --- a/DashWallet/ru.lproj/Localizable.strings +++ b/DashWallet/ru.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sk.lproj/Localizable.strings b/DashWallet/sk.lproj/Localizable.strings index 97f85c470c..03cb2db9ea 100644 --- a/DashWallet/sk.lproj/Localizable.strings +++ b/DashWallet/sk.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sl.lproj/Localizable.strings b/DashWallet/sl.lproj/Localizable.strings index c69b7006c9..50d2e72777 100644 --- a/DashWallet/sl.lproj/Localizable.strings +++ b/DashWallet/sl.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sl_SI.lproj/Localizable.strings b/DashWallet/sl_SI.lproj/Localizable.strings index 8cc5322f66..f80671ef51 100644 --- a/DashWallet/sl_SI.lproj/Localizable.strings +++ b/DashWallet/sl_SI.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sq.lproj/Localizable.strings b/DashWallet/sq.lproj/Localizable.strings index 0a25fe93be..e766e4daf5 100644 --- a/DashWallet/sq.lproj/Localizable.strings +++ b/DashWallet/sq.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sr.lproj/Localizable.strings b/DashWallet/sr.lproj/Localizable.strings index 79fb65d2c3..eda8fa2dc9 100644 --- a/DashWallet/sr.lproj/Localizable.strings +++ b/DashWallet/sr.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/sv.lproj/Localizable.strings b/DashWallet/sv.lproj/Localizable.strings index d3ebfc2884..07b881a691 100644 --- a/DashWallet/sv.lproj/Localizable.strings +++ b/DashWallet/sv.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/th.lproj/Localizable.strings b/DashWallet/th.lproj/Localizable.strings index 283b6383fe..b6477a3e44 100644 --- a/DashWallet/th.lproj/Localizable.strings +++ b/DashWallet/th.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/tr.lproj/Localizable.strings b/DashWallet/tr.lproj/Localizable.strings index 9b7046e785..8129e07d3a 100644 --- a/DashWallet/tr.lproj/Localizable.strings +++ b/DashWallet/tr.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/uk.lproj/Localizable.strings b/DashWallet/uk.lproj/Localizable.strings index 9dbf8927a3..c95b84dfe4 100644 --- a/DashWallet/uk.lproj/Localizable.strings +++ b/DashWallet/uk.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/vi.lproj/Localizable.strings b/DashWallet/vi.lproj/Localizable.strings index 9173c4ec11..7d2a7037ad 100644 --- a/DashWallet/vi.lproj/Localizable.strings +++ b/DashWallet/vi.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/zh-Hans.lproj/Localizable.strings b/DashWallet/zh-Hans.lproj/Localizable.strings index 0af8fd58f7..fc4c13fb26 100644 --- a/DashWallet/zh-Hans.lproj/Localizable.strings +++ b/DashWallet/zh-Hans.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/zh-Hant-TW.lproj/Localizable.strings b/DashWallet/zh-Hant-TW.lproj/Localizable.strings index 28553a0b7d..8b8c88da3f 100644 --- a/DashWallet/zh-Hant-TW.lproj/Localizable.strings +++ b/DashWallet/zh-Hant-TW.lproj/Localizable.strings @@ -6245,6 +6245,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/zh.lproj/Localizable.strings b/DashWallet/zh.lproj/Localizable.strings index c64315747b..513a8ed5c6 100644 --- a/DashWallet/zh.lproj/Localizable.strings +++ b/DashWallet/zh.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWallet/zh_TW.lproj/Localizable.strings b/DashWallet/zh_TW.lproj/Localizable.strings index 4417373fc2..979a0bbfd2 100644 --- a/DashWallet/zh_TW.lproj/Localizable.strings +++ b/DashWallet/zh_TW.lproj/Localizable.strings @@ -6243,6 +6243,7 @@ "This access ends after %d days, or when you disconnect the app." = "This access ends after %d days, or when you disconnect the app."; "This app has a key on another identity of this wallet. Switch to that identity to turn it off." = "This app has a key on another identity of this wallet. Switch to that identity to turn it off."; "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again." = "This connection has more keys than one sign-in can turn off. Disconnect it under Connections, then sign in again."; +"An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code." = "An earlier approval of this sign-in has not finished on the network, and this connection changed since. Ask the app for a new code."; "This identity cannot take another key." = "This identity cannot take another key."; "This identity has no credits. Use Top Up in My Profile, then return to finish registration." = "This identity has no credits. Use Top Up in My Profile, then return to finish registration."; "This sign-in request can no longer be approved. Ask the app for a new code." = "This sign-in request can no longer be approved. Ask the app for a new code."; diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index b2950c77ad..dad55748ed 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1238,12 +1238,6 @@ extension AppConnectV2LoginTests { Self.onIdentity(first, disabled: true), Self.onIdentity(second, disabled: true), ]), .landedAndOff) - var grants = [Self.pendingGrant([first, second])] - _ = AppConnect.settlePendingV2Registrations( - in: &grants, identityId: "identity", - currentIdentityPublicKeys: [Self.onIdentity(first), Self.onIdentity(second)], - bindings: [Self.stored(first), Self.stored(second)], nowMilliseconds: Self.pendingNow) - XCTAssertEqual(grants[0].awaitsRecoveredPublish, true, "its response is still to be published") } func testAnIdHeldByAnotherKeyMeansThePendingUpdateCanNeverLand() { @@ -1373,22 +1367,6 @@ extension AppConnectV2LoginTests { XCTAssertEqual(grants[0].keyDisabled, true, "its update turned the replaced grant off") } - func testAGrantANewerOneOfTheSameConnectionReplacedIsNotTheAppsAnyMore() { - let older = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") - var newer = Self.grant(sessionKeyId: 5, requestHash: "01", connectionId: "c1") - newer = AppConnectGrant( - identityId: newer.identityId, appContractId: newer.appContractId, documentId: nil, values: newer.values, - sessionKeyId: 5, totalBudget: nil, expiresAt: nil, publishedAt: Date(timeIntervalSince1970: 2_000), - connectionId: "c1") - let otherConnection = Self.grant(sessionKeyId: 7, requestHash: "02", connectionId: "c2") - XCTAssertTrue(AppConnect.isReplaced(older, in: [older, newer])) - XCTAssertFalse(AppConnect.isReplaced(newer, in: [older, newer])) - XCTAssertFalse(AppConnect.isReplaced(otherConnection, in: [older, newer, otherConnection])) - var pendingNewer = newer - pendingNewer.unconfirmedKeyHash160 = "11" - XCTAssertFalse(AppConnect.isReplaced(older, in: [older, pendingNewer]), "a newer one that may never land") - } - func testAPendingV2RecordStillReadsAsUnconfirmedWithoutItsNewField() throws { let grant = Self.pendingGrant([Self.addedAuthKey(7, data: 0x07), Self.addedEncryptionKey(8, data: 0x08)]) let encoded = try JSONEncoder().encode(grant) From 52802eccd669e349917969b2de872129df9b1467 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 30 Oct 2026 23:42:44 +0200 Subject: [PATCH 09/29] fix(dashconnect): turn off only live keys of late-landed App Connect grants, and judge orphaned confirming rows Keys of a grant found to have landed late are turned off only where a fresh view shows them live. An update whose auth keys are all off is done, whatever its encryption key: nothing here turns that one off. A confirming row whose record went while the key store could not be read is judged at the next settle. The settle after an approval runs even when its publish fails. Every DashConnect identity update outside a v2 approval goes through one helper that notes it on the waiting records. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 5 +- .../DashConnect/AppConnectV2Login.swift | 12 +- .../PlatformDashConnectDataSource.swift | 190 +++++++++++------- .../DashConnect/AppConnectV2LoginTests.swift | 4 + 4 files changed, 130 insertions(+), 81 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 38163f4abb..2df01dfdf5 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -693,9 +693,10 @@ struct AppConnectGrant: Codable, Equatable { /// The hex hash160 of the session key, set from just before its /// registration is submitted until the key is seen on the identity. /// While set, the key may be there or not: an update can land without - /// confirming. Such a record has no row and no response; it is kept so + /// confirming. A one-QR record has no row and no response; it is kept so /// the key, if it lands, is found and confirmed, until a disconnect - /// finds that the update can no longer land. + /// finds that the update can no longer land. A v2 record + /// (`pendingUpdate`) has a confirming row and no response. var unconfirmedKeyHash160: String? = nil /// The identity revision the registration's update was submitted with, /// set with `unconfirmedKeyHash160`. Platform takes an identity update diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 821d6d35ed..47f0aab2e7 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1102,7 +1102,7 @@ extension AppConnect { /// guessed: the SDK does not say which revision it signed. /// /// - Every added key there as it was added, or turned off since: it - /// landed (`landedAndOff` when every one of them is off). + /// landed (`landedAndOff` when every auth key of it is off). /// - A key under one of its ids with other data: Platform refuses an /// update that adds an id the identity has, and never removes a key, /// so it can never land. The same data, live, with @@ -1130,7 +1130,7 @@ extension AppConnect { ) -> PendingV2Outcome { var allLanded = true var anyPresent = false - var offCount = 0 + var offAuthCount = 0 for expected in pending.addedKeys { guard let key = keys.first(where: { UInt32(bitPattern: $0.keyId) == expected.keyId }) else { allLanded = false @@ -1139,7 +1139,7 @@ extension AppConnect { anyPresent = true guard key.data == expected.data else { return .cannotLand } guard key.disabledAt == nil else { - offCount += 1 + if expected.purpose == .authentication { offAuthCount += 1 } continue } let binding = bindings.first { $0.keyId == expected.keyId && $0.data == key.data } @@ -1148,7 +1148,11 @@ extension AppConnect { if expected.bound != nil, binding == nil || binding?.hasUnreadableBound == true { continue } return .cannotLand } - if allLanded { return offCount == pending.addedKeys.count ? .landedAndOff : .landed } + // Nothing here turns an encryption key off (it is the identity's, + // shared by every device), so the update is done once its auth keys + // are. + let authCount = pending.addedKeys.filter { $0.purpose == .authentication }.count + if allLanded { return authCount > 0 && offAuthCount == authCount ? .landedAndOff : .landed } let takenElsewhere = pending.addedKeys.contains { expected in expected.keyType == .ecdsaSecp256k1 && keys.contains { $0.keyType == .ecdsaSecp256k1 && $0.data == expected.data diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 26179efcc6..d902385924 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1208,13 +1208,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { try await signer.withAdditionalSigningKeys([ (publicKey: sessionKeyHash160, privateKey: sessionPrivateKey), ]) { - try await context.wallet.updateIdentity( - identityId: context.identityId, - addPublicKeys: [key], - signer: signer - ) + try await updateIdentity(add: [key], context: context, signer: signer) } - noteOwnUpdateLanded(AppConnect.OwnUpdate(added: [key]), context: context) } catch { // Another update of the identity that landed meanwhile moved // the wallet's revision, and this one may have been built on @@ -1398,9 +1393,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// App Connect request v2 (Yappr `docs/APP_CONNECT_PROFILE.md`): one key /// per auth binding, the identity's encryption key for the app, and the /// previous grant on the same connection disabled, all in one - /// MASTER-signed identity update; then the grant and the connection row - /// are recorded and the sealed response is published, as for the one-QR - /// login. + /// MASTER-signed identity update. The grant is recorded, and the + /// connection shown as confirming, before that update is submitted + /// (`registerAppConnectV2Grant`); once it lands the row is active and the + /// sealed response is published, as for the one-QR login. /// /// Approving the same request again finds its keys registered and /// recorded, registers nothing and publishes the recorded response if it @@ -1878,29 +1874,37 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { rows.filter { $0.id != connection.id } + [connection] } - try await publishAppConnectResponse( - grant: grant, - appEphemeralPubKeyHash: plan.appEphemeralPubKeyHash, - responseContractId: responseContractId, - context: context, - signer: signer - ) + var publishFailure: Error? + do { + try await publishAppConnectResponse( + grant: grant, + appEphemeralPubKeyHash: plan.appEphemeralPubKeyHash, + responseContractId: responseContractId, + context: context, + signer: signer + ) + } catch { + publishFailure = error + } // Every record of this identity still waiting for its update was // written before this one landed, and has it noted: a view that // shows this update settles them (`AppConnect.pendingV2Outcome`). A // previous grant of this connection that turned out to have landed // holds keys this login replaces: they are turned off too. This runs - // after this request's own response is out: the app is waiting for - // it. + // after this request's own response is out, the app is waiting for + // it, and whether or not that publish went through. if !add.isEmpty || !disable.isEmpty, stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { - let landed = await settleAfterOwnUpdate(context: context, stores: stores) ?? [] - do { - try await disableLateLandedGrants(landed.filter(isSuperseded), context: context, signer: signer) - } catch { - Self.logger.error("🔗 DASHCONNECT :: keys of a replaced grant that landed late are still live — \(error.localizedDescription, privacy: .public)") + if let settled = await settleAfterOwnUpdate(context: context, stores: stores) { + do { + try await disableLateLandedGrants( + settled.confirmed.filter(isSuperseded), liveIn: settled.keys, context: context, signer: signer) + } catch { + Self.logger.error("🔗 DASHCONNECT :: keys of a replaced grant that landed late are still live — \(error.localizedDescription, privacy: .public)") + } } } + if let publishFailure { throw publishFailure } return connection } @@ -1997,23 +2001,17 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } continue } - switch AppConnect.pendingV2Outcome( + let outcome = AppConnect.pendingV2Outcome( of: pending, currentIdentityPublicKeys: view.keys, bindings: view.bindings, - nowMilliseconds: nowMilliseconds() - ) { + nowMilliseconds: nowMilliseconds()) + switch outcome { case .landed: logger.info("🔗 DASHCONNECT :: the identity update landed without confirming") return confirm() - case .landedAndOff: - logger.info("🔗 DASHCONNECT :: the identity update landed, and its keys are off already") - var all = landed() - all.removeAll { $0.key == record.key } - grants.save(all) - await onDropped() - throw error - case .cannotLand: - logger.info("🔗 DASHCONNECT :: the identity update can no longer land; its record is dropped") - var all = grants.load() + case .landedAndOff, .cannotLand: + let didLand = outcome == .landedAndOff + logger.info("🔗 DASHCONNECT :: \(didLand ? "the identity update landed, and its keys are off already" : "the identity update can no longer land", privacy: .public); its record is dropped") + var all = didLand ? landed() : grants.load() all.removeAll { $0.key == record.key } grants.save(all) await onDropped() @@ -2274,14 +2272,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { privateKey: derivedMaterial.encryptionPrivateKey ), ]) { - try await authorized.wallet.updateIdentity( - identityId: authorized.identityId, - addPublicKeys: missingKeys.map(Self.makeManagedIdentityPubkey), - signer: signer - ) + try await updateIdentity( + add: missingKeys.map(Self.makeManagedIdentityPubkey), context: authorized, signer: signer) } - noteOwnUpdateLanded( - AppConnect.OwnUpdate(added: missingKeys.map(Self.makeManagedIdentityPubkey)), context: authorized) await markActive(pendingConnection, in: authorized.stores) } @@ -2322,7 +2315,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// `AppConnect.settlePendingV2Registrations`. One that landed is confirmed /// and its row shown; its response is not published: its approval /// stopped waiting, and the app asks again. One that cannot land is - /// dropped (`rowsAfterDroppingRecords`). Returns the v2 grants confirmed. + /// dropped, and its row with it when nothing else holds it + /// (`showRowsAfterDropping`); so is a confirming row whose record went + /// while its rows could not be judged. Returns the v2 grants confirmed. @discardableResult private func confirmRegistrations( identityId: String, @@ -2331,13 +2326,22 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { in stores: Stores, bindings knownBindings: [AppConnect.KeyBinding]? = nil ) async -> [AppConnectGrant] { - guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) - else { return [] } // Unknown when the store cannot be read: no unconfirmed record is // confirmed without it, and no row is changed by it. let readBindings = knownBindings ?? (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) let bindings = readBindings ?? [] + // A confirming row whose record is gone (dropped while the rows could + // not be judged) is judged now. + let orphaned = Set(rows(in: stores).filter { row in + row.status == .confirming + && !stores.grants.load().contains { $0.appContractId == row.id && $0.isPendingV2 } + }.map(\.id)) + if !orphaned.isEmpty { + await showRowsAfterDropping(appIds: orphaned, restoringApproved: [], bindings: readBindings, in: stores) + } + guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) + else { return [] } if stores.grants.load().contains(where: { $0.identityId == identityId && $0.isUnconfirmed }) { let confirmed = updateGrants(in: stores) { grants in AppConnect.confirmRegistrations( @@ -2380,24 +2384,36 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } /// Writes the rows of the apps whose v2 records in `dropped` were - /// dropped (`rowsAfterDropping`). With the store's bindings unknown - /// (`nil`) no row is changed: a live key bound to the app could not be - /// ruled out, and a confirming row can still be disconnected. + /// dropped (`rowsAfterDropping`). private func showRowsAfterDropping( _ dropped: [AppConnectGrant], bindings: [AppConnect.KeyBinding]?, in stores: Stores + ) async { + await showRowsAfterDropping( + appIds: Set(dropped.map(\.appContractId)), + restoringApproved: Set(dropped.filter { $0.pendingUpdate?.replacesApprovedRow == true }.map(\.appContractId)), + bindings: bindings, + in: stores) + } + + /// With the store's bindings unknown (`nil`) no row is changed: a live + /// key bound to the app could not be ruled out, and a confirming row can + /// still be disconnected. The next settle judges such a row again. + private func showRowsAfterDropping( + appIds: Set, + restoringApproved: Set, + bindings: [AppConnect.KeyBinding]?, + in stores: Stores ) async { guard let bindings else { Self.logger.error("🔗 DASHCONNECT :: the key store could not be read; rows of dropped App Connect updates stay") return } let grants = stores.grants.load() - let restoring = Set(dropped.filter { $0.pendingUpdate?.replacesApprovedRow == true }.map(\.appContractId)) await updateRows(in: stores) { rows in Self.rowsAfterDropping( - appIds: Set(dropped.map(\.appContractId)), restoringApproved: restoring, grants: grants, - bindings: bindings, rows: rows) + appIds: appIds, restoringApproved: restoringApproved, grants: grants, bindings: bindings, rows: rows) } } @@ -2405,12 +2421,16 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// `noteOwnUpdateLanded`): one more read of the identity, which also /// writes what it shows to the store, and the v2 records of the identity /// waiting for their outcome are settled by it. Returns the v2 grants - /// confirmed, or nil when the read failed. - private func settleAfterOwnUpdate(context: Context, stores: Stores) async -> [AppConnectGrant]? { + /// confirmed and the keys read, or nil when the read failed. + private func settleAfterOwnUpdate( + context: Context, + stores: Stores + ) async -> (confirmed: [AppConnectGrant], keys: [ManagedIdentity.IdentityPublicKeyInfo])? { guard let keys = try? await refreshedIdentityPublicKeys(context: context) else { return nil } - return await confirmRegistrations( + let confirmed = await confirmRegistrations( identityId: context.identityId.toBase58String(), currentIdentityPublicKeys: keys, modelContainer: context.modelContainer, in: stores) + return (confirmed, keys) } /// `rows` once the v2 records of `appIds` that were waiting for their @@ -3287,12 +3307,14 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // waiting for their update: this disconnect's update landed after // them. One of the app's that turns out to have landed holds keys // that are turned off too. The keys above are off either way. - let landed = await settleAfterOwnUpdate(context: context, stores: stores) ?? [] - do { - try await disableLateLandedGrants( - landed.filter { pendingV2.contains($0.key) }, context: context, signer: signer) - } catch { - lateDisableFailure = error + if let settled = await settleAfterOwnUpdate(context: context, stores: stores) { + do { + try await disableLateLandedGrants( + settled.confirmed.filter { pendingV2.contains($0.key) }, liveIn: settled.keys, + context: context, signer: signer) + } catch { + lateDisableFailure = error + } } } @@ -3335,15 +3357,24 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { private func disableKeys(_ keyIds: [UInt32], context: Context, signer: KeychainSigner) async throws { for start in stride(from: 0, to: keyIds.count, by: AppConnect.maxKeysDisabledPerUpdate) { let batch = Array(keyIds[start ..< min(start + AppConnect.maxKeysDisabledPerUpdate, keyIds.count)]) - try await context.wallet.updateIdentity( - identityId: context.identityId, - disablePublicKeyIds: batch, - signer: signer - ) - noteOwnUpdateLanded(AppConnect.OwnUpdate(disabledKeyIds: batch), context: context) + try await updateIdentity(disable: batch, context: context, signer: signer) } } + /// Every identity update DashConnect sends outside a v2 approval (which + /// notes its own, `registerAppConnectV2Grant`): on success it is noted on + /// the v2 records still waiting for theirs (`noteOwnUpdateLanded`). + private func updateIdentity( + add: [ManagedPlatformWallet.IdentityPubkey] = [], + disable: [UInt32] = [], + context: Context, + signer: KeychainSigner + ) async throws { + try await context.wallet.updateIdentity( + identityId: context.identityId, addPublicKeys: add, disablePublicKeyIds: disable, signer: signer) + noteOwnUpdateLanded(AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), context: context) + } + /// An update of this wallet to the identity returned success: every v2 /// record of the identity still waiting for its own update cannot land /// after it, which a later view that shows `update` settles @@ -3359,15 +3390,24 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } } - /// Turns off the keys of `grants`, earlier grants that turned out to - /// have landed after the keys to replace or disconnect were picked, and - /// marks them done. - private func disableLateLandedGrants(_ grants: [AppConnectGrant], context: Context, signer: KeychainSigner) async throws { + /// Turns off the keys of `grants` that `keys` (a fresh view) shows live: + /// earlier grants that turned out to have landed after the keys to + /// replace or disconnect were picked. Then marks them done. + private func disableLateLandedGrants( + _ grants: [AppConnectGrant], + liveIn keys: [ManagedIdentity.IdentityPublicKeyInfo], + context: Context, + signer: KeychainSigner + ) async throws { guard !grants.isEmpty else { return } - Self.logger.info("🔗 DASHCONNECT :: disabling the keys of \(grants.count, privacy: .public) App Connect grant(s) that landed late") - try await disableKeys(Array(Set(grants.flatMap(\.keyIds))).sorted(), context: context, signer: signer) - let keys = Set(grants.map(\.key)) - updateGrants(in: context.stores) { AppConnect.markKeysDisabled(in: &$0) { keys.contains($0.key) } } + let live = Set(keys.filter { $0.disabledAt == nil }.map { UInt32(bitPattern: $0.keyId) }) + let keyIds = Set(grants.flatMap(\.keyIds)).intersection(live).sorted() + if !keyIds.isEmpty { + Self.logger.info("🔗 DASHCONNECT :: disabling \(keyIds.count, privacy: .public) key(s) of App Connect grants that landed late") + try await disableKeys(keyIds, context: context, signer: signer) + } + let grantKeys = Set(grants.map(\.key)) + updateGrants(in: context.stores) { AppConnect.markKeysDisabled(in: &$0) { grantKeys.contains($0.key) } } } /// Whether the wallet's store shows another identity of this wallet with diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index a856c4bc5d..21b2edd708 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1257,6 +1257,10 @@ extension AppConnectV2LoginTests { Self.onIdentity(first, disabled: true), Self.onIdentity(second, disabled: true), ]), .landedAndOff) + let encryption = Self.addedEncryptionKey(9, data: 0x09) + XCTAssertEqual( + Self.outcome([first, encryption], keys: [Self.onIdentity(first, disabled: true), Self.onIdentity(encryption)]), + .landedAndOff, "the identity's encryption key is never turned off here") } func testAnIdHeldByAnotherKeyMeansThePendingUpdateCanNeverLand() { From 56960f9dd5092385ee83d80abe540a231e0fd627 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 30 Oct 2026 23:55:14 +0200 Subject: [PATCH 10/29] fix(dashconnect): restore a replaced two-QR row before judging by bound keys A dropped v2 record that replaced a two-QR approved row restores that row even while the two-QR login's keys, bound to the app, are live; only a confirmed grant of the app makes it active first. An orphaned confirming row is not judged while a grant record of the identity cannot be read, and row ids are decoded as everywhere else. Co-Authored-By: Claude Opus 5.5 --- .../PlatformDashConnectDataSource.swift | 40 +++++++++++-------- .../DashConnect/AppConnectV2LoginTests.swift | 5 +++ 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 6a29d92ffb..aa23f80126 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -2010,7 +2010,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { return confirm() case .landedAndOff, .cannotLand: let didLand = outcome == .landedAndOff - logger.info("🔗 DASHCONNECT :: \(didLand ? "the identity update landed, and its keys are off already" : "the identity update can no longer land", privacy: .public); its record is dropped") + let what = didLand ? "landed, and its keys are off already" : "can no longer land" + logger.info("🔗 DASHCONNECT :: the identity update \(what, privacy: .public); its record is dropped") var all = didLand ? landed() : grants.load() all.removeAll { $0.key == record.key } grants.save(all) @@ -2333,11 +2334,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let bindings = readBindings ?? [] // A confirming row whose record is gone (dropped while the rows could // not be judged) is judged now. - let orphaned = Set(rows(in: stores).filter { row in - row.status == .confirming - && !stores.grants.load().contains { $0.appContractId == row.id && $0.isPendingV2 } - }.map(\.id)) - if !orphaned.isEmpty { + // A record the store cannot read may be that row's. + let waitingAppIds = Set(stores.grants.load().filter(\.isPendingV2).map(\.appContractId)) + let orphaned = Set(rows(in: stores) + .filter { $0.status == .confirming && !waitingAppIds.contains($0.id) }.map(\.id)) + if !orphaned.isEmpty, !stores.grants.hasUnreadableRows(identityId: identityId) { await showRowsAfterDropping(appIds: orphaned, restoringApproved: [], bindings: readBindings, in: stores) } guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) @@ -2435,10 +2436,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// `rows` once the v2 records of `appIds` that were waiting for their /// update are dropped: a row still `.confirming` stays while another - /// such record of the app does, becomes active when a confirmed grant of - /// the app or a live key the store shows bound to it remains, goes back - /// to the two-QR `.approved` row it replaced (`restoringApproved`), and - /// goes otherwise. Any other row is left as it is. + /// such record of the app does; becomes active while a confirmed grant + /// of the app remains; goes back to the two-QR `.approved` row it + /// replaced (`restoringApproved`); becomes active while a live key the + /// store shows bound to the app remains; and goes otherwise. Any other + /// row is left as it is. static func rowsAfterDropping( appIds: Set, restoringApproved: Set = [], @@ -2450,12 +2452,18 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { guard appIds.contains(row.id), row.status == .confirming else { return row } let appGrants = grants.filter { $0.appContractId == row.id } if appGrants.contains(where: \.isPendingV2) { return row } - let appContract = Data.identifier(fromBase58: row.id) - let holdsKey = appGrants.contains { !$0.isUnconfirmed && $0.keyDisabled != true } - || bindings.contains { !$0.isDisabled && appContract != nil && $0.singleContractId == appContract } - if holdsKey { return row.withStatus(.active, loginKind: .oneQR, at: row.updatedAt) } - guard restoringApproved.contains(row.id) else { return nil } - return row.withStatus(.approved, loginKind: .twoQR, at: row.updatedAt) + if appGrants.contains(where: { !$0.isUnconfirmed && $0.keyDisabled != true }) { + return row.withStatus(.active, loginKind: .oneQR, at: row.updatedAt) + } + // Before any key bound to the app: the two-QR login's keys are + // bound to it too, and the row it replaced is theirs. + if restoringApproved.contains(row.id) { + return row.withStatus(.approved, loginKind: .twoQR, at: row.updatedAt) + } + let appContract = decodeIdentifier(row.id) + guard bindings.contains(where: { !$0.isDisabled && appContract != nil && $0.singleContractId == appContract }) + else { return nil } + return row.withStatus(.active, loginKind: .oneQR, at: row.updatedAt) } } diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 21b2edd708..428db8024a 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1529,6 +1529,11 @@ extension AppConnectV2LoginTests { appIds: [app], restoringApproved: [app], grants: [], bindings: [], rows: [row(.confirming)]) XCTAssertEqual(restored.map(\.status), [.approved], "the two-QR row it replaced comes back") XCTAssertEqual(restored.map(\.loginKind), [.twoQR]) + let twoQRKeyLive = PlatformDashConnectDataSource.rowsAfterDropping( + appIds: [app], restoringApproved: [app], grants: [], + bindings: [AppConnect.KeyBinding(keyId: 3, data: Data([3]), singleContractId: Self.appId)], + rows: [row(.confirming)]) + XCTAssertEqual(twoQRKeyLive.map(\.status), [.approved], "the two-QR login's live key is that row's") } } From e3c90781e3555390542e5c19021f020261caceb9 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 00:09:39 +0200 Subject: [PATCH 11/29] fix(dashconnect): judge a dropped App Connect row by auth keys only, and retry a partial update A dropped record's row stays active only for a live auth key bound to the app; its encryption key stays on after a disconnect and connects nothing. A failed submit that adds keys is settled by the record it was given, not by a reread of the store. An orphaned confirming row is not judged while any grant record of the wallet cannot be read. A retry of an update that added only some of the request's keys maps the ones it adds. The recordedKeyIds forwarder is gone. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 8 ++++ .../PlatformDashConnectDataSource.swift | 45 ++++++++++--------- .../DashConnect/AppConnectV2LoginTests.swift | 9 +++- 3 files changed, 38 insertions(+), 24 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 2df01dfdf5..c50695a8c0 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -825,6 +825,8 @@ protocol AppConnectResponseStore { /// read, and that may be a record of `identityId`: one naming another /// identity is not. func hasUnreadableRows(identityId: String) -> Bool + /// Whether the store holds any row `load` leaves out, of any identity. + var hasAnyUnreadableRows: Bool { get } func load() -> [AppConnectGrant] func save(_ grants: [AppConnectGrant]) /// This store fixed to one wallet, and to the network scope it has now, @@ -835,6 +837,7 @@ protocol AppConnectResponseStore { extension AppConnectResponseStore { var canPersist: Bool { true } func hasUnreadableRows(identityId: String) -> Bool { false } + var hasAnyUnreadableRows: Bool { false } } /// Wallet- and network-scoped, like `UserDefaultsDashConnectStore`, whose @@ -908,6 +911,11 @@ final class UserDefaultsAppConnectResponseStore: AppConnectResponseStore { /// leaves such a value alone, so nothing new would be kept. var canPersist: Bool { storageKey != nil && !readRows().isNotRowList } + var hasAnyUnreadableRows: Bool { + let rows = readRows() + return rows.isNotRowList || !rows.unreadable.isEmpty + } + func hasUnreadableRows(identityId: String) -> Bool { let rows = readRows() return rows.isNotRowList || rows.unreadable.contains { diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index aa23f80126..36601801bc 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1702,7 +1702,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { var signingKeys: [(publicKey: Data, privateKey: Data)] = [] defer { for index in signingKeys.indices { Self.zero(&signingKeys[index].privateKey) } } if let pending = pendingRetry?.pendingUpdate { - guard reused.isEmpty else { throw DashConnectPlatformError.identityKeysOutOfDate } + // A key of the request already on the identity is sent again as + // it was the first time; it is not one the update adds. + guard reused.isDisjoint(with: pending.addedKeys.map(\.keyId)) else { + throw DashConnectPlatformError.identityKeysOutOfDate + } // The earlier update replaced what the connection held then. If // that changed since (a replaced key is off, or another grant of // the connection turned up), sending it again would be refused @@ -1718,14 +1722,15 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { func encryptionKey(_ slot: Int) -> AppConnect.DerivedEncryptionKey { encryptionKeys[encryptionSlots[slot].keyIndex][encryptionSlots[slot].derivedIndex] } + let added = authKeyIds.indices.filter { authKeyIds[$0] == nil } guard let ids = AppConnect.keyIdsForRetry( of: pending, - authKeyHash160s: authKeys.map(\.publicKeyHash160), + authKeyHash160s: added.map { authKeys[$0].publicKeyHash160 }, registeredEncryptionKeys: registered.map { encryptionKey($0).publicKey } ) else { throw DashConnectPlatformError.sessionKeyUnusable } - for (index, keyId) in ids.auth.enumerated() { authKeyIds[index] = keyId } + for (index, keyId) in zip(added, ids.auth) { authKeyIds[index] = keyId } for (slot, keyId) in zip(registered, ids.encryption) { encryptionSlots[slot].keyId = keyId } add = pending.addedKeys.map(\.identityPubkey) for key in add { @@ -1993,7 +1998,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { if attempt > 0 { await pause(attempt) } guard let view = await reread() else { continue } let disabled = AppConnect.showsDisabled(disable, in: view.keys) - guard let pending = grants.load().first(where: { $0.key == record.key })?.pendingUpdate else { + guard !add.isEmpty, let pending = record.pendingUpdate else { // Nothing added: the update landed when its disables show. if disabled { logger.info("🔗 DASHCONNECT :: the identity update landed without confirming") @@ -2334,11 +2339,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let bindings = readBindings ?? [] // A confirming row whose record is gone (dropped while the rows could // not be judged) is judged now. - // A record the store cannot read may be that row's. + // A record the store cannot read, of any identity, may be that row's. let waitingAppIds = Set(stores.grants.load().filter(\.isPendingV2).map(\.appContractId)) let orphaned = Set(rows(in: stores) .filter { $0.status == .confirming && !waitingAppIds.contains($0.id) }.map(\.id)) - if !orphaned.isEmpty, !stores.grants.hasUnreadableRows(identityId: identityId) { + if !orphaned.isEmpty, !stores.grants.hasAnyUnreadableRows { await showRowsAfterDropping(appIds: orphaned, restoringApproved: [], bindings: readBindings, in: stores) } guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) @@ -2438,8 +2443,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// update are dropped: a row still `.confirming` stays while another /// such record of the app does; becomes active while a confirmed grant /// of the app remains; goes back to the two-QR `.approved` row it - /// replaced (`restoringApproved`); becomes active while a live key the - /// store shows bound to the app remains; and goes otherwise. Any other + /// replaced (`restoringApproved`); becomes active while a live auth key + /// the store shows bound to the app remains; and goes otherwise. Any other /// row is left as it is. static func rowsAfterDropping( appIds: Set, @@ -2460,9 +2465,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { if restoringApproved.contains(row.id) { return row.withStatus(.approved, loginKind: .twoQR, at: row.updatedAt) } + // An auth key: the app's encryption key stays on after a + // disconnect, and connects nothing by itself. let appContract = decodeIdentifier(row.id) - guard bindings.contains(where: { !$0.isDisabled && appContract != nil && $0.singleContractId == appContract }) - else { return nil } + guard bindings.contains(where: { + !$0.isDisabled && ($0.isSessionKeyShaped || $0.isV2AuthKeyShaped) + && appContract != nil && $0.singleContractId == appContract + }) else { return nil } return row.withStatus(.active, loginKind: .oneQR, at: row.updatedAt) } } @@ -2795,7 +2804,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { in stores: Stores, bindings: [AppConnect.KeyBinding] ) -> Set { - Self.recordedKeyIds(of: identityId, in: stores, bindings: bindings) + AppConnect.recordedKeyIds(of: identityId, grants: stores.grants.load(), bindings: bindings) .union(keptSharedProfileKeyIds(scope: stores.scope, identityId: identityId)) } @@ -2892,15 +2901,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { return keyIds.count } - /// The key ids this identity's grant records name - /// (`AppConnect.recordedKeyIds`). - private static func recordedKeyIds( - of identityId: String, - in stores: Stores, - bindings: [AppConnect.KeyBinding] - ) -> Set { - AppConnect.recordedKeyIds(of: identityId, grants: stores.grants.load(), bindings: bindings) - } private func disconnectInTurn(id: String, scope: String?) async throws { guard let stores = await showActiveWalletRows() else { @@ -3249,7 +3249,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // group they are bound to is the app's if the app's owner owns // it, which only the network says; if it cannot be read, // nothing is turned off and the row stays. - let recordedKeyIds = Self.recordedKeyIds(of: identityId, in: stores, bindings: bindings) + let recordedKeyIds = AppConnect.recordedKeyIds(of: identityId, grants: stores.grants.load(), bindings: bindings) let unrecorded = AppConnect.unrecordedV2Keys( recordedKeyIds: recordedKeyIds, bindings: bindings, currentIdentityPublicKeys: currentPublicKeys) // The store keeps every key it was ever given, the fetched view @@ -3467,7 +3467,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { if AppConnect.holdsLiveSessionKey(appContractId: appContractId, bindings: bindings) { return true } let otherIdentityId = other.identityId.toBase58String() let unrecorded = AppConnect.unrecordedV2Keys( - recordedKeyIds: Self.recordedKeyIds(of: otherIdentityId, in: context.stores, bindings: bindings), + recordedKeyIds: AppConnect.recordedKeyIds( + of: otherIdentityId, grants: context.stores.grants.load(), bindings: bindings), bindings: bindings) if !unrecorded.isEmpty { let candidates = AppConnect.unrecordedV2KeyBoundIds(appContractId: appContractId, keys: unrecorded) diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 428db8024a..773bc624c2 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1521,9 +1521,14 @@ extension AppConnectV2LoginTests { XCTAssertEqual( after([Self.grant(sessionKeyId: 3, appId: app)], rows: [row(.confirming)]).map(\.status), [.active]) XCTAssertEqual( - after([], bindings: [AppConnect.KeyBinding(keyId: 3, data: Data([3]), singleContractId: Self.appId)], + after([], bindings: [AppConnect.KeyBinding( + keyId: 3, data: Data([3]), singleContractId: Self.appId, isV2AuthKeyShaped: true)], rows: [row(.confirming)]).map(\.status), - [.active], "a live key bound to the app") + [.active], "a live auth key bound to the app") + XCTAssertEqual( + after([], bindings: [AppConnect.KeyBinding(keyId: 4, data: Data([4]), singleContractId: Self.appId)], + rows: [row(.confirming)]).map(\.status), + [], "the app's encryption key connects nothing by itself") XCTAssertEqual(after([], rows: [row(.active)]).map(\.status), [.active], "only a confirming row is touched") let restored = PlatformDashConnectDataSource.rowsAfterDropping( appIds: [app], restoringApproved: [app], grants: [], bindings: [], rows: [row(.confirming)]) From b5be80037390939628a1b6ea7f72b361557a69f7 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 00:25:14 +0200 Subject: [PATCH 12/29] fix(dashconnect): note an App Connect update only when its own submission succeeded Keys found after a failed submission may be an earlier submission's of the same grant, which says nothing about other waiting records, so only a submission that returned success is noted on them. The keys a waiting v2 record sends again count as that grant's for the shared profile count. A dropped record's row stays for a v2 auth key bound to a document type of the app. A retry keeps the earlier record's note, and one whose derived keys no longer match the earlier update says so. Co-Authored-By: Claude Opus 5.5 --- .../DashConnect/AppConnectV2Login.swift | 12 ++++-- .../PlatformDashConnectDataSource.swift | 41 +++++++++++-------- .../DashConnect/AppConnectV2LoginTests.swift | 16 +++++++- 3 files changed, 48 insertions(+), 21 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 47f0aab2e7..fc66bea04f 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1216,9 +1216,10 @@ extension AppConnect { /// The ids a confirmed record of `identityId` names, and the ids of the /// keys a v2 record waiting for its update adds that the store shows - /// there as added (same data and bound): those are that grant's, not - /// another app's. An unconfirmed record's id is otherwise not taken: it - /// may belong to another key by now. + /// there as added (same data and bound), and the auth keys such a record + /// sends again: those are that grant's, not another app's. An + /// unconfirmed record's id is otherwise not taken: it may belong to + /// another key by now. static func recordedKeyIds( of identityId: String, grants: [AppConnectGrant], @@ -1226,6 +1227,11 @@ extension AppConnect { ) -> Set { var ids = Set(grants.filter { $0.identityId == identityId && !$0.isUnconfirmed }.flatMap(\.keyIds)) for grant in grants where grant.identityId == identityId { + // Its auth keys the update does not add were on the identity + // when it was recorded: sent again, they are the grant's. + if let pending = grant.pendingUpdate { + ids.formUnion(Set(grant.keyIds).subtracting(pending.addedKeys.map(\.keyId))) + } for expected in grant.pendingUpdate?.addedKeys ?? [] where bindings.contains(where: { $0.keyId == expected.keyId && $0.data == expected.data && !$0.hasUnreadableBound && $0.bound == expected.bound diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 36601801bc..1127503122 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1237,7 +1237,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { throw error } Self.logger.info("🔗 DASHCONNECT :: session key is on the identity although the update reported a failure") - noteOwnUpdateLanded(AppConnect.OwnUpdate(added: [key]), context: context) } Self.logger.info("🔗 DASHCONNECT :: session key registered") sessionKeyId = keyId @@ -1728,7 +1727,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { authKeyHash160s: added.map { authKeys[$0].publicKeyHash160 }, registeredEncryptionKeys: registered.map { encryptionKey($0).publicKey } ) else { - throw DashConnectPlatformError.sessionKeyUnusable + // The keys this approval derives are not the ones the earlier + // update adds (the app's encryption key changed since). + throw DashConnectPlatformError.earlierApprovalPending } for (index, keyId) in zip(added, ids.auth) { authKeyIds[index] = keyId } for (slot, keyId) in zip(registered, ids.encryption) { encryptionSlots[slot].keyId = keyId } @@ -1824,7 +1825,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { addedKeys: add.map(AppConnect.ExpectedKey.init), disabledKeyIds: disable, retiredGrantKeys: retiredGrantKeys.sorted(), - outlivedBy: nil, + outlivedBy: pendingRetry?.pendingUpdate?.outlivedBy, replacesApprovedRow: previousRow?.status == .approved || (previousRow?.status == .confirming && stores.grants.load().contains { $0.appContractId == appId && $0.pendingUpdate?.replacesApprovedRow == true @@ -1925,8 +1926,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// /// On success the record is confirmed, the grants in `retiredGrantKeys` /// are marked done, and the update is noted on the identity's other - /// records still waiting for theirs (`AppConnect.noteOwnUpdate`). A - /// failure may still have landed: + /// records still waiting for theirs (`AppConnect.noteOwnUpdate`); a + /// landing found after a failure is not noted, as it may be an earlier + /// submission's. A failure may still have landed: /// up to three reads (`reread`, `pause` before the second and third) /// settle it by `AppConnect.pendingV2Outcome`. Landed confirms as on /// success; cannot land drops the record, runs `onDropped` and rethrows; @@ -1967,11 +1969,14 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } await showRow() - // Once this update is known to have landed, every other record of - // the identity still waiting for its own cannot land after it. - func landed() -> [AppConnectGrant] { + // Once this submission returned success, every other record of the + // identity still waiting for its own cannot land after it. Keys + // found after a failure may be an earlier submission's of the same + // grant, which proves nothing about the others, so that is not + // noted. + func landed(noting: Bool) -> [AppConnectGrant] { var all = grants.load() - if !add.isEmpty || !disable.isEmpty { + if noting, !add.isEmpty || !disable.isEmpty { AppConnect.noteOwnUpdate( AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), in: &all, identityId: record.identityId, exceptKey: record.key) @@ -1979,8 +1984,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { AppConnect.markKeysDisabled(in: &all) { retiredGrantKeys.contains($0.key) && !$0.isUnconfirmed } return all } - func confirm() -> AppConnectGrant { - var all = landed() + func confirm(noting: Bool = false) -> AppConnectGrant { + var all = landed(noting: noting) guard let index = all.firstIndex(where: { $0.key == record.key }) else { return record } all[index].pendingUpdate = nil all[index].unconfirmedKeyHash160 = nil @@ -2017,7 +2022,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let didLand = outcome == .landedAndOff let what = didLand ? "landed, and its keys are off already" : "can no longer land" logger.info("🔗 DASHCONNECT :: the identity update \(what, privacy: .public); its record is dropped") - var all = didLand ? landed() : grants.load() + var all = didLand ? landed(noting: false) : grants.load() all.removeAll { $0.key == record.key } grants.save(all) await onDropped() @@ -2030,7 +2035,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { throw error } logger.info("🔗 DASHCONNECT :: identity updated") - return confirm() + return confirm(noting: true) } /// This identity's response to one request, with the values it has on @@ -2468,9 +2473,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // An auth key: the app's encryption key stays on after a // disconnect, and connects nothing by itself. let appContract = decodeIdentifier(row.id) - guard bindings.contains(where: { - !$0.isDisabled && ($0.isSessionKeyShaped || $0.isV2AuthKeyShaped) - && appContract != nil && $0.singleContractId == appContract + // A contract group is the app's only by its owner, which this + // does not look up. + guard let appContract, bindings.contains(where: { binding in + guard !binding.isDisabled, binding.isSessionKeyShaped || binding.isV2AuthKeyShaped else { return false } + if binding.singleContractId == appContract { return true } + if case .documentType(let contractId, _) = binding.bound { return contractId == appContract } + return false }) else { return nil } return row.withStatus(.active, loginKind: .oneQR, at: row.updatedAt) } diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 773bc624c2..4992689a46 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1441,6 +1441,11 @@ extension AppConnectV2LoginTests { AppConnect.recordedKeyIds(of: "identity", grants: grants, bindings: [otherKey]), [3], "another key under the id is not the grant's") XCTAssertEqual(AppConnect.recordedKeyIds(of: "identity", grants: grants, bindings: []), [3]) + var withReused = Self.pendingGrant([Self.addedAuthKey(8, data: 0x08)], requestHash: "a6") + withReused.additionalKeyIds = [5] + XCTAssertTrue( + AppConnect.recordedKeyIds(of: "identity", grants: [withReused], bindings: []).contains(5), + "an auth key the record sends again was there when it was recorded") } func testARetrySubmitsTheSameKeysUnderTheSameIds() throws { @@ -1534,6 +1539,11 @@ extension AppConnectV2LoginTests { appIds: [app], restoringApproved: [app], grants: [], bindings: [], rows: [row(.confirming)]) XCTAssertEqual(restored.map(\.status), [.approved], "the two-QR row it replaced comes back") XCTAssertEqual(restored.map(\.loginKind), [.twoQR]) + XCTAssertEqual( + after([], bindings: [AppConnect.KeyBinding( + keyId: 5, data: Data([5]), singleContractId: nil, bound: .documentType(contractId: Self.appId, name: "post"), + isV2AuthKeyShaped: true)], rows: [row(.confirming)]).map(\.status), + [.active], "a v2 key bound to a document type of the app") let twoQRKeyLive = PlatformDashConnectDataSource.rowsAfterDropping( appIds: [app], restoringApproved: [app], grants: [], bindings: [AppConnect.KeyBinding(keyId: 3, data: Data([3]), singleContractId: Self.appId)], @@ -1618,7 +1628,7 @@ extension AppConnectV2LoginTests { XCTAssertEqual(store.grants.first { $0.key == old.key }?.keyDisabled, true) } - func testAnUpdateKnownToHaveLandedIsNotedOnTheOtherRecordsWaiting() async throws { + func testOnlyAnUpdateThatReturnedSuccessIsNotedOnTheOtherRecordsWaiting() async throws { let waiting = Self.pendingGrant([Self.addedAuthKey(9, data: 0x09)], requestHash: "a9") let key = Self.addedAuthKey(7, data: 0x07) let succeeded = MemoryGrantStore([waiting]) @@ -1631,7 +1641,9 @@ extension AppConnectV2LoginTests { _ = try await Self.register( Self.pendingGrant([key]), add: [key], store: landedAnyway, calls: Calls(), submit: { throw UpdateFailed() }, views: [([Self.onIdentity(key)], [Self.stored(key)])]) - XCTAssertNotNil(landedAnyway.grants.first { $0.key == waiting.key }?.pendingUpdate?.outlivedBy) + XCTAssertNil( + landedAnyway.grants.first { $0.key == waiting.key }?.pendingUpdate?.outlivedBy, + "keys found after a failure may be an earlier submission's") let unknown = MemoryGrantStore([waiting]) _ = try? await Self.register( From bb9fb7277436094e08743dca04ab4b2f5e7c13dc Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 00:35:23 +0200 Subject: [PATCH 13/29] fix(dashconnect): a resubmitted App Connect update starts without the earlier note A retry is built past any update noted on its earlier submission and can land after it, so its record starts with no note; carrying it over dropped a retry that could still land. An update whose expired keys are on the identity but not yet placed by the store stays unknown instead of being dropped. Co-Authored-By: Claude Opus 5.5 --- DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift | 3 ++- .../Models/DashConnect/PlatformDashConnectDataSource.swift | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index fc66bea04f..2b86040558 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1165,7 +1165,8 @@ extension AppConnect { expected.purpose == .authentication && expected.expiresAt.map { !isUnexpired(Int64(clamping: $0), nowMilliseconds: nowMilliseconds) } == true } - return allExpired ? .cannotLand : .unknown + // Its keys there, unplaced, may be a landed update still to settle. + return allExpired && !anyPresent ? .cannotLand : .unknown } /// Settles the v2 records of `identityId` whose update's outcome was not diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 1127503122..69e689ba1d 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1825,7 +1825,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { addedKeys: add.map(AppConnect.ExpectedKey.init), disabledKeyIds: disable, retiredGrantKeys: retiredGrantKeys.sorted(), - outlivedBy: pendingRetry?.pendingUpdate?.outlivedBy, + // The submission about to be sent is built past any update + // noted on the earlier one, and can land after it. + outlivedBy: nil, replacesApprovedRow: previousRow?.status == .approved || (previousRow?.status == .confirming && stores.grants.load().contains { $0.appContractId == appId && $0.pendingUpdate?.replacesApprovedRow == true From f05161155dc158fc103f47dc99c503ab5f64b2df Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 00:39:08 +0200 Subject: [PATCH 14/29] test(dashconnect): an expired App Connect update whose keys are there stays unknown Co-Authored-By: Claude Opus 5.5 --- DashWalletTests/DashConnect/AppConnectV2LoginTests.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 4992689a46..8c7667df24 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1346,6 +1346,9 @@ extension AppConnectV2LoginTests { XCTAssertEqual( Self.outcome([auth, Self.addedEncryptionKey(8, data: 0x08)], keys: [], now: past), .unknown, "an encryption key never expires") + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth)], bindings: [], now: past), .unknown, + "its key is there, the store just cannot place it yet") } func testSettlingConfirmsWhatLandedDropsWhatCannotAndMarksTheGrantsItRetired() { From d64936764c6e27a6f71b0c50e8538959959df356 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 00:46:03 +0200 Subject: [PATCH 15/29] fix(dashconnect): judge an App Connect row by the dropped record's identity, active rows included A v2 record that can never land is dropped only once its rows are judged by the store's keys of its own identity; while those cannot be read it is kept, and the next settle drops it. No confirming row is left without a record, so the sweep that judged such rows by the active identity's keys is gone. An active one-QR row a waiting record kept is judged too, and goes once nothing holds the app. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 8 -- .../DashConnect/AppConnectV2Login.swift | 2 +- .../PlatformDashConnectDataSource.swift | 86 ++++++++----------- .../DashConnect/AppConnectV2LoginTests.swift | 43 +++++++++- 4 files changed, 76 insertions(+), 63 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index c50695a8c0..2df01dfdf5 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -825,8 +825,6 @@ protocol AppConnectResponseStore { /// read, and that may be a record of `identityId`: one naming another /// identity is not. func hasUnreadableRows(identityId: String) -> Bool - /// Whether the store holds any row `load` leaves out, of any identity. - var hasAnyUnreadableRows: Bool { get } func load() -> [AppConnectGrant] func save(_ grants: [AppConnectGrant]) /// This store fixed to one wallet, and to the network scope it has now, @@ -837,7 +835,6 @@ protocol AppConnectResponseStore { extension AppConnectResponseStore { var canPersist: Bool { true } func hasUnreadableRows(identityId: String) -> Bool { false } - var hasAnyUnreadableRows: Bool { false } } /// Wallet- and network-scoped, like `UserDefaultsDashConnectStore`, whose @@ -911,11 +908,6 @@ final class UserDefaultsAppConnectResponseStore: AppConnectResponseStore { /// leaves such a value alone, so nothing new would be kept. var canPersist: Bool { storageKey != nil && !readRows().isNotRowList } - var hasAnyUnreadableRows: Bool { - let rows = readRows() - return rows.isNotRowList || !rows.unreadable.isEmpty - } - func hasUnreadableRows(identityId: String) -> Bool { let rows = readRows() return rows.isNotRowList || rows.unreadable.contains { diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 52cdbe3546..ea3bef659b 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1168,7 +1168,7 @@ extension AppConnect { if !anyPresent, pending.outlivedBy?.isShown(in: keys) == true { return .cannotLand } let allExpired = pending.addedKeys.allSatisfy { expected in expected.purpose == .authentication - && expected.expiresAt.map { !isUnexpired(Int64(clamping: $0), nowMilliseconds: nowMilliseconds) } == true + && expected.expiresAt.map { !isUnexpired(Int64(bitPattern: $0), nowMilliseconds: nowMilliseconds) } == true } // Its keys there, unplaced, may be a landed update still to settle. return allExpired && !anyPresent ? .cannotLand : .unknown diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 69e689ba1d..8c4f458dec 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1869,11 +1869,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { return (keys, bindings) }, pause: { _ in try? await Task.sleep(nanoseconds: 3_000_000_000) }, - onDropped: { - await showRowsAfterDropping( - [record], - bindings: try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer), - in: stores) + onDropped: { remaining in + guard let bindings = try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer) + else { return false } + await showRowsAfterDropping([record], grants: remaining, bindings: bindings, in: stores) + return true } ) @@ -1933,7 +1933,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// submission's. A failure may still have landed: /// up to three reads (`reread`, `pause` before the second and third) /// settle it by `AppConnect.pendingV2Outcome`. Landed confirms as on - /// success; cannot land drops the record, runs `onDropped` and rethrows; + /// success; cannot land runs `onDropped` with the records without this + /// one, drops it when that wrote the rows, and rethrows; /// unknown keeps the record and rethrows. A record that adds nothing is /// confirmed from the start and only waits for its disables. /// @@ -1950,7 +1951,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { submit: () async throws -> Void, reread: () async -> (keys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [AppConnect.KeyBinding])?, pause: (Int) async -> Void, - onDropped: () async -> Void + onDropped: ([AppConnectGrant]) async -> Bool ) async throws -> AppConnectGrant { guard AppConnect.fitsOneUpdate(disabling: disable) else { logger.error("🔗 DASHCONNECT :: \(disable.count, privacy: .public) superseded keys do not fit one update; not renewing") @@ -2026,8 +2027,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { logger.info("🔗 DASHCONNECT :: the identity update \(what, privacy: .public); its record is dropped") var all = didLand ? landed(noting: false) : grants.load() all.removeAll { $0.key == record.key } - grants.save(all) - await onDropped() + // Dropped only once its rows can be judged; otherwise the + // next settle drops it. + if await onDropped(all) { grants.save(all) } throw error case .unknown: continue @@ -2329,8 +2331,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// and its row shown; its response is not published: its approval /// stopped waiting, and the app asks again. One that cannot land is /// dropped, and its row with it when nothing else holds it - /// (`showRowsAfterDropping`); so is a confirming row whose record went - /// while its rows could not be judged. Returns the v2 grants confirmed. + /// (`showRowsAfterDropping`). Nothing is settled while the store's + /// bindings cannot be read. Returns the v2 grants confirmed. @discardableResult private func confirmRegistrations( identityId: String, @@ -2344,15 +2346,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let readBindings = knownBindings ?? (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) let bindings = readBindings ?? [] - // A confirming row whose record is gone (dropped while the rows could - // not be judged) is judged now. - // A record the store cannot read, of any identity, may be that row's. - let waitingAppIds = Set(stores.grants.load().filter(\.isPendingV2).map(\.appContractId)) - let orphaned = Set(rows(in: stores) - .filter { $0.status == .confirming && !waitingAppIds.contains($0.id) }.map(\.id)) - if !orphaned.isEmpty, !stores.grants.hasAnyUnreadableRows { - await showRowsAfterDropping(appIds: orphaned, restoringApproved: [], bindings: readBindings, in: stores) - } guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) else { return [] } if stores.grants.load().contains(where: { $0.identityId == identityId && $0.isUnconfirmed }) { @@ -2366,7 +2359,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } } var confirmedV2: [AppConnectGrant] = [] - if stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { + // Without the store's bindings a v2 record is not settled: one that + // could not land would be dropped with its rows not judged. + if let readBindings, stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { let nowMilliseconds = Int64(AppConnect.milliseconds(now())) let settled = updateGrants(in: stores) { grants in AppConnect.settlePendingV2Registrations( @@ -2379,7 +2374,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } if !settled.dropped.isEmpty { Self.logger.info("🔗 DASHCONNECT :: dropping \(settled.dropped.count, privacy: .public) App Connect update(s) that can no longer land") - await showRowsAfterDropping(settled.dropped, bindings: readBindings, in: stores) + await showRowsAfterDropping( + settled.dropped, grants: stores.grants.load(), bindings: readBindings, in: stores) } } let appIds = Self.appIdsWithoutTheirOneQRRow( @@ -2397,36 +2393,20 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } /// Writes the rows of the apps whose v2 records in `dropped` were - /// dropped (`rowsAfterDropping`). + /// dropped (`rowsAfterDropping`), judged by `grants` (the records left) + /// and `bindings`, the store's keys of the identity those records were + /// of. private func showRowsAfterDropping( _ dropped: [AppConnectGrant], - bindings: [AppConnect.KeyBinding]?, - in stores: Stores - ) async { - await showRowsAfterDropping( - appIds: Set(dropped.map(\.appContractId)), - restoringApproved: Set(dropped.filter { $0.pendingUpdate?.replacesApprovedRow == true }.map(\.appContractId)), - bindings: bindings, - in: stores) - } - - /// With the store's bindings unknown (`nil`) no row is changed: a live - /// key bound to the app could not be ruled out, and a confirming row can - /// still be disconnected. The next settle judges such a row again. - private func showRowsAfterDropping( - appIds: Set, - restoringApproved: Set, - bindings: [AppConnect.KeyBinding]?, + grants: [AppConnectGrant], + bindings: [AppConnect.KeyBinding], in stores: Stores ) async { - guard let bindings else { - Self.logger.error("🔗 DASHCONNECT :: the key store could not be read; rows of dropped App Connect updates stay") - return - } - let grants = stores.grants.load() + let appIds = Set(dropped.map(\.appContractId)) + let restoring = Set(dropped.filter { $0.pendingUpdate?.replacesApprovedRow == true }.map(\.appContractId)) await updateRows(in: stores) { rows in Self.rowsAfterDropping( - appIds: appIds, restoringApproved: restoringApproved, grants: grants, bindings: bindings, rows: rows) + appIds: appIds, restoringApproved: restoring, grants: grants, bindings: bindings, rows: rows) } } @@ -2447,9 +2427,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } /// `rows` once the v2 records of `appIds` that were waiting for their - /// update are dropped: a row still `.confirming` stays while another - /// such record of the app does; becomes active while a confirmed grant - /// of the app remains; goes back to the two-QR `.approved` row it + /// update are dropped: a `.confirming` row, or an active one-QR row the + /// waiting record kept, stays while another such record of the app + /// does; is active while a confirmed grant of the app remains; goes back to the two-QR `.approved` row it /// replaced (`restoringApproved`); becomes active while a live auth key /// the store shows bound to the app remains; and goes otherwise. Any other /// row is left as it is. @@ -2461,7 +2441,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { rows: [DAppConnection] ) -> [DAppConnection] { rows.compactMap { row in - guard appIds.contains(row.id), row.status == .confirming else { return row } + // An active one-QR row the waiting record kept is judged too: the + // keys behind it may have gone off meanwhile. + let isConfirming = row.status == .confirming + guard appIds.contains(row.id), + isConfirming || (row.status == .active && row.loginKind == .oneQR) else { return row } let appGrants = grants.filter { $0.appContractId == row.id } if appGrants.contains(where: \.isPendingV2) { return row } if appGrants.contains(where: { !$0.isUnconfirmed && $0.keyDisabled != true }) { @@ -2469,7 +2453,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } // Before any key bound to the app: the two-QR login's keys are // bound to it too, and the row it replaced is theirs. - if restoringApproved.contains(row.id) { + if isConfirming, restoringApproved.contains(row.id) { return row.withStatus(.approved, loginKind: .twoQR, at: row.updatedAt) } // An auth key: the app's encryption key stays on after a diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 7138f3611c..c18cca354a 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1551,7 +1551,23 @@ extension AppConnectV2LoginTests { after([], bindings: [AppConnect.KeyBinding(keyId: 4, data: Data([4]), singleContractId: Self.appId)], rows: [row(.confirming)]).map(\.status), [], "the app's encryption key connects nothing by itself") - XCTAssertEqual(after([], rows: [row(.active)]).map(\.status), [.active], "only a confirming row is touched") + XCTAssertEqual( + after([], rows: [row(.active)]).map(\.status), [], + "an active one-QR row the waiting record kept goes once nothing holds the app") + XCTAssertEqual( + after([Self.grant(sessionKeyId: 3, appId: app)], rows: [row(.active)]).map(\.status), [.active]) + XCTAssertEqual( + after([], bindings: [AppConnect.KeyBinding( + keyId: 3, data: Data([3]), singleContractId: Self.appId, isSessionKeyShaped: true)], + rows: [row(.active)]).map(\.status), + [.active], "a live session key of the app with no record") + let twoQR = DAppConnection(id: app, name: "Yappr", url: "yap.pr", status: .active, + updatedAt: Date(timeIntervalSince1970: 1_000), loginKind: .twoQR) + XCTAssertEqual(after([], rows: [twoQR]).map(\.status), [.active], "a two-QR row is not the record's") + XCTAssertEqual( + PlatformDashConnectDataSource.rowsAfterDropping( + appIds: [app], restoringApproved: [app], grants: [], bindings: [], rows: [row(.active)]).map(\.status), + [], "only a confirming row goes back to the row it replaced") let restored = PlatformDashConnectDataSource.rowsAfterDropping( appIds: [app], restoringApproved: [app], grants: [], bindings: [], rows: [row(.confirming)]) XCTAssertEqual(restored.map(\.status), [.approved], "the two-QR row it replaced comes back") @@ -1607,7 +1623,8 @@ extension AppConnectV2LoginTests { store: MemoryGrantStore, calls: Calls, submit: @escaping () throws -> Void = {}, - views: [View?] = [] + views: [View?] = [], + rowsJudged: Bool = true ) async throws -> AppConnectGrant { var remaining = views return try await PlatformDashConnectDataSource.registerAppConnectV2Grant( @@ -1620,7 +1637,10 @@ extension AppConnectV2LoginTests { return remaining.isEmpty ? nil : remaining.removeFirst() }, pause: { calls.pauses.append($0) }, - onDropped: { calls.dropped += 1 }) + onDropped: { _ in + calls.dropped += 1 + return rowsJudged + }) } func testAV2GrantIsRecordedAndShownBeforeItsUpdateIsSubmitted() async throws { @@ -1729,6 +1749,23 @@ extension AppConnectV2LoginTests { XCTAssertEqual(calls.dropped, 1, "its row is repaired") } + func testARecordWhoseRowsCannotBeJudgedIsNotDroppedYet() async { + let key = Self.addedAuthKey(7, data: 0x07) + let record = Self.pendingGrant([key]) + let store = MemoryGrantStore() + let calls = Calls() + do { + _ = try await Self.register( + record, add: [key], store: store, calls: calls, submit: { throw UpdateFailed() }, + views: [([Self.onIdentity(key, data: Data(repeating: 0xEE, count: 20))], [])], rowsJudged: false) + XCTFail("the failure stands") + } catch { + XCTAssertTrue(error is UpdateFailed) + } + XCTAssertEqual(store.grants, [record], "the next settle drops it, with its rows judged") + XCTAssertEqual(calls.dropped, 1) + } + func testAFailedUpdateWhoseOutcomeIsUnknownKeepsItsRecord() async { let key = Self.addedAuthKey(7, data: 0x07) let record = Self.pendingGrant([key]) From 9308b140ad6864e9dbb8f27830f45b25c41d673e Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 01:00:27 +0200 Subject: [PATCH 16/29] fix(dashconnect): a disconnected app's two-QR row stays gone, and settled records go after their rows A one-QR disconnect of an app clears, on its waiting v2 records, the two-QR row they would put back: that row's keys are off too. A settle writes the rows of dropped records before it saves the store without them. Co-Authored-By: Claude Opus 5.5 --- .../PlatformDashConnectDataSource.swift | 39 ++++++++++++------- .../DashConnect/AppConnectV2LoginTests.swift | 2 +- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 8c4f458dec..67c22759f3 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -2341,13 +2341,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { in stores: Stores, bindings knownBindings: [AppConnect.KeyBinding]? = nil ) async -> [AppConnectGrant] { + guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) + else { return [] } // Unknown when the store cannot be read: no unconfirmed record is // confirmed without it, and no row is changed by it. let readBindings = knownBindings ?? (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) let bindings = readBindings ?? [] - guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) - else { return [] } if stores.grants.load().contains(where: { $0.identityId == identityId && $0.isUnconfirmed }) { let confirmed = updateGrants(in: stores) { grants in AppConnect.confirmRegistrations( @@ -2363,20 +2363,21 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // could not land would be dropped with its rows not judged. if let readBindings, stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { let nowMilliseconds = Int64(AppConnect.milliseconds(now())) - let settled = updateGrants(in: stores) { grants in - AppConnect.settlePendingV2Registrations( - in: &grants, identityId: identityId, currentIdentityPublicKeys: currentIdentityPublicKeys, - bindings: bindings, nowMilliseconds: nowMilliseconds) - } + var grants = stores.grants.load() + let settled = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: identityId, currentIdentityPublicKeys: currentIdentityPublicKeys, + bindings: bindings, nowMilliseconds: nowMilliseconds) confirmedV2 = settled.confirmed if !settled.confirmed.isEmpty { Self.logger.info("🔗 DASHCONNECT :: \(settled.confirmed.count, privacy: .public) App Connect update(s) found to have landed") } + // The rows first: a record is gone from the store only once its + // rows are written. A stop in between drops it again next time. if !settled.dropped.isEmpty { Self.logger.info("🔗 DASHCONNECT :: dropping \(settled.dropped.count, privacy: .public) App Connect update(s) that can no longer land") - await showRowsAfterDropping( - settled.dropped, grants: stores.grants.load(), bindings: readBindings, in: stores) + await showRowsAfterDropping(settled.dropped, grants: grants, bindings: readBindings, in: stores) } + stores.grants.save(grants) } let appIds = Self.appIdsWithoutTheirOneQRRow( grants: stores.grants.load(), identityId: identityId, @@ -2410,10 +2411,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } } - /// After an update of this wallet to the identity landed (and was noted, - /// `noteOwnUpdateLanded`): one more read of the identity, which also - /// writes what it shows to the store, and the v2 records of the identity - /// waiting for their outcome are settled by it. Returns the v2 grants + /// After an update of this wallet to the identity landed: one more read + /// of the identity, which also writes what it shows to the store, and + /// the v2 records of the identity waiting for their outcome are settled + /// by it (by that update only when its submission returned success and + /// it was noted, `AppConnect.noteOwnUpdate`). Returns the v2 grants /// confirmed and the keys read, or nil when the read failed. private func settleAfterOwnUpdate( context: Context, @@ -3335,6 +3337,17 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } } + // The user turned the app off: a waiting record of it no longer puts + // back the two-QR row it replaced, whose keys this disconnect + // disabled too. + if asOneQR { + updateGrants(in: stores) { grants in + for index in grants.indices where isGranted(grants[index]) && grants[index].isPendingV2 { + grants[index].pendingUpdate?.replacesApprovedRow = nil + } + } + } + // The session keys of the grants read above are now off, and only // those are marked. let revoked = Set(granted.map(\.key)) diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index c18cca354a..d4d2f62977 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1749,7 +1749,7 @@ extension AppConnectV2LoginTests { XCTAssertEqual(calls.dropped, 1, "its row is repaired") } - func testARecordWhoseRowsCannotBeJudgedIsNotDroppedYet() async { + func testARecordWhoseRowsCannotBeJudgedIsKept() async { let key = Self.addedAuthKey(7, data: 0x07) let record = Self.pendingGrant([key]) let store = MemoryGrantStore() From d2a626bdfd4c2e9bf2aed5e1540371e04ea03139 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 14:36:58 +0200 Subject: [PATCH 17/29] fix(dashconnect): retries stay within the approval, raised key limits keep the record, replacements wait for their disables - A retry of a v2 approval whose outcome is not known sends the earlier keys only when their terms are within this approval's (same bound, level and budget, an expiry still ahead and no later) and the connection is the same; otherwise earlierApprovalPending. - A key limits update only raises a limit, so a recorded key with a higher budget or a later expiry is still the record's key, for v2 and one-QR records. Expiry is read with its unsigned bits. - An update whose keys are there but whose disables are not was not this update: the grant is confirmed and nothing it replaced is retired. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 10 +- .../DashConnect/AppConnectV2Login.swift | 74 +++++++++++--- .../PlatformDashConnectDataSource.swift | 50 ++++++++-- .../DashConnect/AppConnectV2LoginTests.swift | 97 ++++++++++++++++++- .../PlatformDashConnectDataSourceTests.swift | 10 +- 5 files changed, 212 insertions(+), 29 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 2df01dfdf5..45fdf36e2c 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -438,9 +438,9 @@ enum AppConnect { /// Whether the identity holds, live, the key a record names. For an /// unconfirmed record that is the key it was going to register, with - /// everything that key was given: the data, the kind, the limits, and the - /// bound to the record's app as the wallet's store reads it. A bound the - /// store does not show is not taken on trust. + /// everything that key was given: the data, the kind, the limits (raised + /// at most), and the bound to the record's app as the wallet's store + /// reads it. A bound the store does not show is not taken on trust. static func holdsRecordedKey( _ grant: AppConnectGrant, currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], @@ -457,8 +457,8 @@ enum AppConnect { guard let appContractId = Data.identifier(fromBase58: grant.appContractId) else { return false } return key.keyType == .ecdsaHash160 && key.data.toHexString() == hash && key.purpose == .authentication && key.securityLevel == .high - && key.totalBudget == grant.totalBudget - && key.expiresAt.map({ UInt64(max(0, $0)) }) == grant.expiresAt + && isNotLowered(key.totalBudget, from: grant.totalBudget) + && isNotLowered(key.expiresAt.map { UInt64(bitPattern: $0) }, from: grant.expiresAt) && bindings.contains { $0.keyId == grant.sessionKeyId && $0.data == key.data && !$0.hasUnreadableBound && $0.singleContractId == appContractId diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index ea3bef659b..d763a84236 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -968,10 +968,12 @@ extension AppConnect { /// Whether `key`, found on the identity after an update reported a /// failure, is the key the update added (`added`): the same id and /// payload, live, and everything it was registered with — type, - /// purpose, level, read-only flag, limits, and the bound as the store - /// reads it - /// (`binding`). A key with the same payload but another bound came from - /// another request that repeated the ephemeral key, and is not taken. + /// purpose, level, read-only flag, and the bound as the store reads it + /// (`binding`) — with limits no lower than it was added with: a key + /// limits update only raises a limit the key has, and keeps its id and + /// payload. A key with the same payload but another bound or lower + /// limits came from another request that repeated the ephemeral key, + /// and is not taken. static func isAddedKey( _ key: ManagedIdentity.IdentityPublicKeyInfo, added: ManagedPlatformWallet.IdentityPubkey, @@ -980,8 +982,8 @@ extension AppConnect { guard UInt32(bitPattern: key.keyId) == added.keyId, key.data == added.pubkeyBytes, key.disabledAt == nil, key.keyType == added.keyType, key.purpose == added.purpose, key.securityLevel == added.securityLevel, key.readOnly == added.readOnly, - key.totalBudget == added.totalBudget, - key.expiresAt.map({ UInt64(max(0, $0)) }) == added.expiresAt else { return false } + isNotLowered(key.totalBudget, from: added.totalBudget), + isNotLowered(key.expiresAt.map { UInt64(bitPattern: $0) }, from: added.expiresAt) else { return false } guard let bounds = added.contractBounds else { return binding == nil || binding?.bound == nil } guard let binding, binding.keyId == added.keyId, binding.data == key.data, !binding.hasUnreadableBound else { return false @@ -989,6 +991,17 @@ extension AppConnect { return binding.bound == storedBound(of: bounds) } + /// Whether `limit`, as the identity shows it, is `added` or a raise of + /// it. No limit stays no limit: a limits update raises only a limit the + /// key has. + static func isNotLowered(_ limit: UInt64?, from added: UInt64?) -> Bool { + switch (limit, added) { + case (nil, nil): return true + case let (limit?, added?): return limit >= added + default: return false + } + } + // MARK: A v2 update whose outcome is not known /// A key an App Connect v2 update adds, as it adds it: what @@ -1106,12 +1119,16 @@ extension AppConnect { /// identity) and `bindings` (the store's bounds) show. No revision is /// guessed: the SDK does not say which revision it signed. /// - /// - Every added key there as it was added, or turned off since: it - /// landed (`landedAndOff` when every auth key of it is off). + /// - Every added key there as it was added (its limits raised at + /// most), or turned off since: it landed (`landedAndOff` when every + /// auth key of it is off). The keys it disables are not part of this: + /// another update can add the same keys under the same ids, so a + /// caller retires what it replaced only once `showsDisabled` shows + /// them off. /// - A key under one of its ids with other data: Platform refuses an /// update that adds an id the identity has, and never removes a key, /// so it can never land. The same data, live, with - /// other limits or another readable bound: the id is another key's. + /// lower limits or another readable bound: the id is another key's. /// - Its encryption key (ECDSA_SECP256K1, unique on Platform) under /// another id: it can never land. HASH160 auth keys are not unique, /// so their data elsewhere says nothing. @@ -1176,9 +1193,12 @@ extension AppConnect { /// Settles the v2 records of `identityId` whose update's outcome was not /// known, by `pendingV2Outcome`. A landed one becomes a grant like any - /// other (its response is not published: its approval stopped waiting), and the earlier grants its update retired are marked done; one - /// that landed and is off again is dropped with those marked done; one - /// that cannot land is dropped; the rest stay as they are. + /// other (its response is not published: its approval stopped waiting), + /// and the earlier grants its update retired are marked done once the + /// keys it disables show off; one that landed and is off again is + /// dropped, with those marked done the same way; one that cannot land is + /// dropped; the rest stay as they are. A grant whose keys are still on + /// stays live, and a disconnect turns them off. static func settlePendingV2Registrations( in grants: inout [AppConnectGrant], identityId: String, @@ -1191,6 +1211,8 @@ extension AppConnect { var retired: Set = [] for grant in grants where grant.identityId == identityId { guard let pending = grant.pendingUpdate else { continue } + let replaced = showsDisabled(pending.disabledKeyIds, in: currentIdentityPublicKeys) + ? pending.retiredGrantKeys : [] switch pendingV2Outcome( of: pending, currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: bindings, nowMilliseconds: nowMilliseconds @@ -1200,10 +1222,10 @@ extension AppConnect { settled.pendingUpdate = nil settled.unconfirmedKeyHash160 = nil confirmed.append(settled) - retired.formUnion(pending.retiredGrantKeys) + retired.formUnion(replaced) case .landedAndOff: dropped.append(grant) - retired.formUnion(pending.retiredGrantKeys) + retired.formUnion(replaced) case .cannotLand: dropped.append(grant) case .unknown: @@ -1270,6 +1292,30 @@ extension AppConnect { return (auth, encryption) } + /// Whether `stored`, a key an earlier approval of the same request + /// added, may be sent again for an approval that grants `planned`: the + /// same key under the same id, type, purpose, level, read-only flag, + /// bound and budget, and an expiry still ahead and no later than the + /// plan's (`clockTolerance` covers a clock moved back between two tries), + /// as `canResendAuthKey` asks of a key already there. A request that + /// repeats the ephemeral key derives the same keys whatever terms it + /// asks for, so the earlier approval's terms are checked against this + /// one's. + static func isWithinPlan( + _ stored: ExpectedKey, + planned: ManagedPlatformWallet.IdentityPubkey, + now: Date + ) -> Bool { + guard stored.keyId == planned.keyId, stored.data == planned.pubkeyBytes, stored.keyType == planned.keyType, + stored.purpose == planned.purpose, stored.securityLevel == planned.securityLevel, + stored.readOnly == planned.readOnly, + stored.bound == planned.contractBounds.map(storedBound(of:)), + stored.totalBudget == planned.totalBudget else { return false } + guard let plannedExpiry = planned.expiresAt else { return stored.expiresAt == nil } + guard let expiry = stored.expiresAt, expiry > milliseconds(now) else { return false } + return expiry <= plannedExpiry + UInt64(clockTolerance * 1000) + } + /// A live auth key a login could have granted: HASH160 and never MASTER, /// so a damaged record cannot get the identity's own keys disabled. static func isLiveGrantedKey(_ key: ManagedIdentity.IdentityPublicKeyInfo) -> Bool { diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 67c22759f3..e0d7dcc0c9 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1731,6 +1731,27 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // update adds (the app's encryption key changed since). throw DashConnectPlatformError.earlierApprovalPending } + // The same keys may come with other terms: the request repeats + // the ephemeral key and asks for less. What is sent again has to + // be within what this approval grants, for this connection. + let planned = zip(added, ids.auth).map { index, keyId in + AppConnect.authIdentityPubkey( + plan.auth[index], keyId: keyId, publicKeyHash160: authKeys[index].publicKeyHash160) + } + zip(registered, ids.encryption).map { slot, keyId in + AppConnect.encryptionIdentityPubkey( + plan.encryption[encryptionSlots[slot].keyIndex], keyId: keyId, publicKey: encryptionKey(slot).publicKey) + } + guard pendingRetry?.connectionId == connectionId else { + Self.logger.error("🔗 DASHCONNECT :: an earlier approval of this request for another connection may still land") + throw DashConnectPlatformError.earlierApprovalPending + } + let retryNow = now() + guard planned.allSatisfy({ key in + pending.addedKeys.contains { AppConnect.isWithinPlan($0, planned: key, now: retryNow) } + }) else { + Self.logger.error("🔗 DASHCONNECT :: an earlier approval of this request with other terms may still land") + throw DashConnectPlatformError.earlierApprovalPending + } for (index, keyId) in zip(added, ids.auth) { authKeyIds[index] = keyId } for (slot, keyId) in zip(registered, ids.encryption) { encryptionSlots[slot].keyId = keyId } add = pending.addedKeys.map(\.identityPubkey) @@ -1933,8 +1954,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// submission's. A failure may still have landed: /// up to three reads (`reread`, `pause` before the second and third) /// settle it by `AppConnect.pendingV2Outcome`. Landed confirms as on - /// success; cannot land runs `onDropped` with the records without this - /// one, drops it when that wrote the rows, and rethrows; + /// success when the keys it disables show off; with any of them still + /// on, the keys were added by another update, so the record is confirmed + /// without retiring anything and the failure stands; cannot land runs + /// `onDropped` with the records without this one, drops it when that + /// wrote the rows, and rethrows; /// unknown keeps the record and rethrows. A record that adds nothing is /// confirmed from the start and only waits for its disables. /// @@ -1977,18 +2001,20 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // found after a failure may be an earlier submission's of the same // grant, which proves nothing about the others, so that is not // noted. - func landed(noting: Bool) -> [AppConnectGrant] { + func landed(noting: Bool, retiring: Bool = true) -> [AppConnectGrant] { var all = grants.load() if noting, !add.isEmpty || !disable.isEmpty { AppConnect.noteOwnUpdate( AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), in: &all, identityId: record.identityId, exceptKey: record.key) } - AppConnect.markKeysDisabled(in: &all) { retiredGrantKeys.contains($0.key) && !$0.isUnconfirmed } + if retiring { + AppConnect.markKeysDisabled(in: &all) { retiredGrantKeys.contains($0.key) && !$0.isUnconfirmed } + } return all } - func confirm(noting: Bool = false) -> AppConnectGrant { - var all = landed(noting: noting) + func confirm(noting: Bool = false, retiring: Bool = true) -> AppConnectGrant { + var all = landed(noting: noting, retiring: retiring) guard let index = all.firstIndex(where: { $0.key == record.key }) else { return record } all[index].pendingUpdate = nil all[index].unconfirmedKeyHash160 = nil @@ -2018,14 +2044,22 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { of: pending, currentIdentityPublicKeys: view.keys, bindings: view.bindings, nowMilliseconds: nowMilliseconds()) switch outcome { - case .landed: + case .landed where disabled: logger.info("🔗 DASHCONNECT :: the identity update landed without confirming") return confirm() + case .landed: + // Its keys are there and the keys it replaces are not + // off: another update added them. They are this grant's, + // and the grants it replaces keep theirs until a retry + // or a disconnect turns them off. + logger.error("🔗 DASHCONNECT :: the keys of this approval are on the identity, the keys it replaces are still on") + _ = confirm(retiring: false) + throw error case .landedAndOff, .cannotLand: let didLand = outcome == .landedAndOff let what = didLand ? "landed, and its keys are off already" : "can no longer land" logger.info("🔗 DASHCONNECT :: the identity update \(what, privacy: .public); its record is dropped") - var all = didLand ? landed(noting: false) : grants.load() + var all = didLand ? landed(noting: false, retiring: disabled) : grants.load() all.removeAll { $0.key == record.key } // Dropped only once its rows can be judged; otherwise the // next settle drops it. diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index d4d2f62977..b651b26e5b 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1189,13 +1189,14 @@ extension AppConnectV2LoginTests { keyId: UInt32? = nil, data: Data? = nil, totalBudget: UInt64?? = nil, + expiresAt: UInt64?? = nil, disabled: Bool = false ) -> ManagedIdentity.IdentityPublicKeyInfo { ManagedIdentity.IdentityPublicKeyInfo( keyId: Int32(bitPattern: keyId ?? added.keyId), purpose: added.purpose, securityLevel: added.securityLevel, keyType: added.keyType, readOnly: false, disabledAt: disabled ? 1 : nil, data: data ?? added.pubkeyBytes, - totalBudget: totalBudget ?? added.totalBudget, expiresAt: added.expiresAt.map { Int64($0) }) + totalBudget: totalBudget ?? added.totalBudget, expiresAt: (expiresAt ?? added.expiresAt).map { Int64(bitPattern: $0) }) } /// The store's record of `added`, bound as it was added. @@ -1365,6 +1366,79 @@ extension AppConnectV2LoginTests { "its key is there, the store just cannot place it yet") } + func testAPendingUpdateWhoseKeyLimitsWereRaisedSinceLanded() { + let auth = Self.addedAuthKey(7, data: 0x07) + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth, totalBudget: .some(auth.totalBudget! + 1))]), .landed, + "a limits update raised its budget") + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth, expiresAt: .some(auth.expiresAt! + Self.dayMilliseconds))]), + .landed, "a limits update extended it") + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth, expiresAt: .some(UInt64.max))]), .landed, + "extended to the largest expiry") + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth, totalBudget: .some(nil))]), .cannotLand, + "a limits update never takes a limit away") + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth, expiresAt: .some(auth.expiresAt! - 1))]), .cannotLand, + "nor lowers one") + } + + func testAPendingUpdateWhoseReplacedKeysAreStillOnRetiresNothing() { + let key = Self.addedAuthKey(7, data: 0x07) + let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") + var pending = Self.pendingGrant([key], requestHash: "a1", retiring: [old.key]) + pending.pendingUpdate?.disabledKeyIds = [3] + var grants = [old, pending] + let settled = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: "identity", + currentIdentityPublicKeys: [Self.onIdentity(key), Self.key(3)], + bindings: [Self.stored(key)], nowMilliseconds: Self.pendingNow) + XCTAssertEqual(settled.confirmed.map(\.key), [pending.key], "its keys are there and need their record") + XCTAssertNil(grants[0].keyDisabled, "another update added them; the replaced key is still on") + + var landedOff = [old, pending] + _ = AppConnect.settlePendingV2Registrations( + in: &landedOff, identityId: "identity", + currentIdentityPublicKeys: [Self.onIdentity(key, disabled: true), Self.key(3)], + bindings: [Self.stored(key)], nowMilliseconds: Self.pendingNow) + XCTAssertEqual(landedOff.map(\.key), [old.key]) + XCTAssertNil(landedOff[0].keyDisabled) + } + + func testARetryIsSentOnlyWithinWhatThisApprovalGrants() { + let stored = AppConnect.ExpectedKey(Self.addedAuthKey(7, data: 0x07)) + let planned = Self.addedAuthKey(7, data: 0x07, expiresAt: Self.expiresAt + Self.dayMilliseconds) + XCTAssertTrue( + AppConnect.isWithinPlan(stored, planned: planned, now: Self.now), "the plan's default expiry moved on") + func plan( + level: SecurityLevel = .critical, + bounds: ManagedPlatformWallet.ContractBounds = .contractGroup(id: Self.groupId), + budget: UInt64? = 50_000_000_000, + expiresAt: UInt64? = Self.expiresAt + ) -> ManagedPlatformWallet.IdentityPubkey { + ManagedPlatformWallet.IdentityPubkey( + keyId: 7, keyType: .ecdsaHash160, purpose: .authentication, securityLevel: level, + pubkeyBytes: Data(repeating: 0x07, count: 20), contractBounds: bounds, + totalBudget: budget, expiresAt: expiresAt) + } + for (key, why) in [ + (plan(budget: 1), "a smaller budget"), + (plan(budget: 60_000_000_000), "another budget"), + (plan(budget: nil), "no limit"), + (plan(expiresAt: Self.expiresAt - Self.dayMilliseconds), "an earlier expiry"), + (plan(level: .high), "another level"), + (plan(bounds: .singleContract(id: Self.appId)), "another bound"), + ] { + XCTAssertFalse(AppConnect.isWithinPlan(stored, planned: key, now: Self.now), why) + } + XCTAssertFalse( + AppConnect.isWithinPlan( + stored, planned: plan(), now: Self.date(milliseconds: Self.expiresAt)), + "its expiry has passed") + } + func testSettlingConfirmsWhatLandedDropsWhatCannotAndMarksTheGrantsItRetired() { let landedKey = Self.addedAuthKey(7, data: 0x07) let impossibleKey = Self.addedAuthKey(9, data: 0x09) @@ -1733,6 +1807,27 @@ extension AppConnectV2LoginTests { XCTAssertEqual(calls.pauses, [1]) } + func testAFailedUpdateWhoseKeysAnotherUpdateAddedRetiresNothing() async { + let key = Self.addedAuthKey(7, data: 0x07) + let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") + var record = Self.pendingGrant([key], retiring: [old.key]) + record.pendingUpdate?.disabledKeyIds = [3] + let store = MemoryGrantStore([old]) + do { + _ = try await Self.register( + record, add: [key], disable: [3], retiring: [old.key], store: store, calls: Calls(), + submit: { throw UpdateFailed() }, + views: [([Self.onIdentity(key), Self.key(3)], [Self.stored(key)])]) + XCTFail("the replacement did not happen") + } catch { + XCTAssertTrue(error is UpdateFailed) + } + let recorded = store.grants.first { $0.key == record.key } + XCTAssertNotNil(recorded) + XCTAssertNil(recorded?.pendingUpdate, "its keys are on the identity") + XCTAssertNil(store.grants.first { $0.key == old.key }?.keyDisabled, "the replaced key is still on") + } + func testAFailedUpdateThatCanNeverLandDropsItsRecord() async { let key = Self.addedAuthKey(7, data: 0x07) let store = MemoryGrantStore() diff --git a/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift b/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift index fb75d6ed29..062fdcf2dc 100644 --- a/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift +++ b/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift @@ -3041,12 +3041,20 @@ final class AppConnectLoginTests: XCTestCase { } XCTAssertTrue(AppConnect.holdsRecordedKey(pending, currentIdentityPublicKeys: key(), bindings: bound)) + for (keys, why) in [ + (key(budget: 9_000), "a limits update raised its budget"), + (key(expiry: 7_000), "a limits update extended it"), + (key(expiry: -1), "extended to the largest expiry, read with its unsigned bits"), + ] { + XCTAssertTrue(AppConnect.holdsRecordedKey(pending, currentIdentityPublicKeys: keys, bindings: bound), why) + } for (keys, why) in [ (key(data: Data(repeating: 0x01, count: 20)), "another key under the same id"), (key(disabledAt: 1), "a disabled key"), (key(level: .critical), "another security level"), (key(budget: nil), "no budget"), - (key(budget: 9_000), "another budget"), + (key(budget: 4_000), "a lower budget"), + (key(expiry: 5_000), "an earlier expiry"), (key(expiry: nil), "no expiry"), ([], "no key at all"), ] { From 5f6564ef46f4fd3d9a9d7c9b0ae0a35d0820476a Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 15:16:00 +0200 Subject: [PATCH 18/29] fix(dashconnect): a waiting approval's reused keys reach its retry, a recovered grant completes only within its limits - An approval whose earlier attempt reused some keys and added others, and whose outcome is not known, is matched by the keys it sends again (AppConnect.resentKeyIds), so its retry is reached. - A failed update found landed completes the approval only when every key it added is live with the limits it was added with (AppConnect.showsAddedLimits); otherwise the grant is recorded so a disconnect turns it off, and the failure stands. - A disconnect turns off the live keys a waiting record sends again; a view that lacks one, or a store that cannot place one, stops it. - Late-landed grants: only keys a login could have granted are turned off, and a grant naming a key left on or not shown is not marked off. - A retry adds the superseded grants confirmed since to those it retires. Co-Authored-By: Claude Opus 5.5 --- .../DashConnect/AppConnectV2Login.swift | 45 +++++++++-- .../DashConnect/DashConnectModels.swift | 7 +- .../PlatformDashConnectDataSource.swift | 75 ++++++++++++++----- .../DashConnect/AppConnectV2LoginTests.swift | 62 +++++++++++++++ 4 files changed, 162 insertions(+), 27 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index d763a84236..df7994ab45 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1242,6 +1242,33 @@ extension AppConnect { return (confirmed, dropped) } + /// Whether every key `pending` adds is on the identity, live, with the + /// limits it was added with: what the approval granted, so its response + /// may go out. A key whose limits were raised since is still the grant's + /// (`isAddedKey`), but wider than the approval; a key turned off since + /// cannot be handed out. + static func showsAddedLimits( + of pending: AppConnectGrant.PendingV2Update, + in keys: [ManagedIdentity.IdentityPublicKeyInfo] + ) -> Bool { + pending.addedKeys.allSatisfy { expected in + keys.contains { + UInt32(bitPattern: $0.keyId) == expected.keyId && $0.data == expected.data && $0.disabledAt == nil + && $0.totalBudget == expected.totalBudget + && $0.expiresAt.map { UInt64(bitPattern: $0) } == expected.expiresAt + } + } + } + + /// The auth keys a v2 record waiting for its update sends again: the + /// ones it names that the update does not add. They were on the + /// identity when it was recorded, and are the grant's. Empty for any + /// other record. + static func resentKeyIds(of grant: AppConnectGrant) -> Set { + guard let pending = grant.pendingUpdate else { return [] } + return Set(grant.keyIds).subtracting(pending.addedKeys.map(\.keyId)) + } + /// The ids a confirmed record of `identityId` names, and the ids of the /// keys a v2 record waiting for its update adds that the store shows /// there as added (same data and bound), and the auth keys such a record @@ -1255,11 +1282,7 @@ extension AppConnect { ) -> Set { var ids = Set(grants.filter { $0.identityId == identityId && !$0.isUnconfirmed }.flatMap(\.keyIds)) for grant in grants where grant.identityId == identityId { - // Its auth keys the update does not add were on the identity - // when it was recorded: sent again, they are the grant's. - if let pending = grant.pendingUpdate { - ids.formUnion(Set(grant.keyIds).subtracting(pending.addedKeys.map(\.keyId))) - } + ids.formUnion(resentKeyIds(of: grant)) for expected in grant.pendingUpdate?.addedKeys ?? [] where bindings.contains(where: { $0.keyId == expected.keyId && $0.data == expected.data && !$0.hasUnreadableBound && $0.bound == expected.bound @@ -1295,9 +1318,10 @@ extension AppConnect { /// Whether `stored`, a key an earlier approval of the same request /// added, may be sent again for an approval that grants `planned`: the /// same key under the same id, type, purpose, level, read-only flag, - /// bound and budget, and an expiry still ahead and no later than the - /// plan's (`clockTolerance` covers a clock moved back between two tries), - /// as `canResendAuthKey` asks of a key already there. A request that + /// bound and budget; and, when the plan sets an expiry, one still ahead + /// and no later than it (`clockTolerance` covers a clock moved back + /// between two tries), as `canResendAuthKey` asks of a key already + /// there; when it sets none, none. A request that /// repeats the ephemeral key derives the same keys whatever terms it /// asks for, so the earlier approval's terms are checked against this /// one's. @@ -1323,6 +1347,11 @@ extension AppConnect { && key.securityLevel != .master && key.disabledAt == nil } + /// The ids of `keys` that pass `isLiveGrantedKey`. + static func liveGrantedKeyIds(in keys: [ManagedIdentity.IdentityPublicKeyInfo]) -> Set { + Set(keys.filter(isLiveGrantedKey).map { UInt32(bitPattern: $0.keyId) }) + } + /// Whether a key already on the identity at this binding's derived /// payload can be sent again for it: an earlier answer to the same /// request (a retry, or an update that landed without confirming). It diff --git a/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift b/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift index 2446d334d3..134283e6db 100644 --- a/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift +++ b/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift @@ -158,8 +158,11 @@ extension DashConnectTokenPurchaseRequest { /// /// `confirming` is an App Connect v2 connection whose identity update was /// submitted and whose outcome is not known yet: its keys may be on the -/// identity, so it can be disconnected like an active one. A build without -/// this status drops the row on load; the grant record stays. +/// identity, so it offers a disconnect like an active one. The disconnect +/// turns off the app's live auth keys on the active identity; while the +/// record still waits after that, or with nothing to turn off, it is +/// refused (`registrationPending`). A build without this +/// status drops the row on load; the grant record stays. enum ConnectionStatus: String, Codable, CaseIterable { case approved case active diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index e0d7dcc0c9..87a2b506e7 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1533,9 +1533,20 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } if !reused.isEmpty { let grants = stores.grants.load().filter { $0.identityId == identityId } - if let recorded = grants.first(where: isGrantForRequest), - Set(recorded.keyIds) != reused || authKeyIds.contains(nil) { - throw DashConnectPlatformError.sessionKeyUnusable + if let recorded = grants.first(where: { isGrantForRequest($0) && $0.isPendingV2 }) + ?? grants.first(where: isGrantForRequest) { + // A record waiting for its update sends these again and adds + // the rest; the retry below checks what it adds. One of them + // missing from the fetched list means the list is behind. + let fetched = Set(currentPublicKeys.map { UInt32(bitPattern: $0.keyId) }) + guard !recorded.isPendingV2 || AppConnect.resentKeyIds(of: recorded).isSubset(of: fetched) else { + throw DashConnectPlatformError.identityKeysOutOfDate + } + let sentAgain = recorded.isPendingV2 + ? AppConnect.resentKeyIds(of: recorded) : Set(recorded.keyIds) + guard sentAgain == reused, recorded.isPendingV2 || !authKeyIds.contains(nil) else { + throw DashConnectPlatformError.sessionKeyUnusable + } } if grants.contains(where: { !isGrantForRequest($0) && !reused.isDisjoint(with: $0.keyIds) }) { throw DashConnectPlatformError.sessionKeyUnusable @@ -1691,9 +1702,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { currentIdentityPublicKeys: currentPublicKeys ) // The confirmed grants whose every key is off once the update lands. - let liveAfterUpdate = Set(currentPublicKeys.filter(AppConnect.isLiveGrantedKey) - .map { UInt32(bitPattern: $0.keyId) }).subtracting(disable) - let retiredGrantKeys = pendingRetry?.pendingUpdate.map { Set($0.retiredGrantKeys) } ?? Set(superseded + // A retry keeps the earlier attempt's, and adds a grant confirmed + // since whose keys are all off once the update lands. + let liveAfterUpdate = AppConnect.liveGrantedKeyIds(in: currentPublicKeys).subtracting(disable) + let retiredGrantKeys = Set(pendingRetry?.pendingUpdate?.retiredGrantKeys ?? []).union(superseded .filter { !$0.isUnconfirmed && !$0.keyIds.contains(where: liveAfterUpdate.contains) } .map(\.key)) @@ -1956,7 +1968,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// settle it by `AppConnect.pendingV2Outcome`. Landed confirms as on /// success when the keys it disables show off; with any of them still /// on, the keys were added by another update, so the record is confirmed - /// without retiring anything and the failure stands; cannot land runs + /// without retiring anything and the failure stands; with limits raised + /// past what was added (`AppConnect.showsAddedLimits`), the record is + /// confirmed and the failure stands, so nothing wider than the approval + /// is published; cannot land runs /// `onDropped` with the records without this one, drops it when that /// wrote the rows, and rethrows; /// unknown keeps the record and rethrows. A record that adds nothing is @@ -2044,16 +2059,19 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { of: pending, currentIdentityPublicKeys: view.keys, bindings: view.bindings, nowMilliseconds: nowMilliseconds()) switch outcome { - case .landed where disabled: + case .landed where disabled && AppConnect.showsAddedLimits(of: pending, in: view.keys): logger.info("🔗 DASHCONNECT :: the identity update landed without confirming") return confirm() case .landed: - // Its keys are there and the keys it replaces are not - // off: another update added them. They are this grant's, - // and the grants it replaces keep theirs until a retry - // or a disconnect turns them off. - logger.error("🔗 DASHCONNECT :: the keys of this approval are on the identity, the keys it replaces are still on") - _ = confirm(retiring: false) + // Its keys are there, but either the keys it replaces are + // not off, so another update added them, or their limits + // are wider than this approval's. They are this grant's, + // recorded so a disconnect turns them off, but the + // approval is not completed with them. The grants it + // replaces are retired only when their keys show off. + let why = disabled ? "with limits wider than this approval's" : "and the keys it replaces are still on" + logger.error("🔗 DASHCONNECT :: the keys of this approval are on the identity \(why, privacy: .public)") + _ = confirm(retiring: disabled) throw error case .landedAndOff, .cannotLand: let didLand = outcome == .landedAndOff @@ -3275,6 +3293,22 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { currentIdentityPublicKeys: currentPublicKeys, twoQRAuthenticationKeyHash160: checksUnrecordedKeys ? nil : twoQRKeys.authenticationPublicKeyHash160 ) + // A waiting v2 record sends some of its auth keys again: they are + // live and counted as its (`AppConnect.recordedKeyIds`), so they go + // with the confirmed grants' keys. One the fetched list lacks, or a + // live one the store cannot place, means a view is behind. + let resentByWaiting = stores.grants.load().filter { pendingV2.contains($0.key) } + .reduce(into: Set()) { $0.formUnion(AppConnect.resentKeyIds(of: $1)) } + let resentLive = AppConnect.liveGrantedKeyIds(in: currentPublicKeys).intersection(resentByWaiting) + guard resentByWaiting.isSubset(of: currentPublicKeys.map { UInt32(bitPattern: $0.keyId) }), + currentPublicKeys.filter({ resentLive.contains(UInt32(bitPattern: $0.keyId)) }).allSatisfy({ key in + bindings.contains { + $0.keyId == UInt32(bitPattern: key.keyId) && $0.data == key.data && !$0.hasUnreadableBound + } + }) else { + throw DashConnectPlatformError.identityKeysOutOfDate + } + keyIds = Array(Set(keyIds).union(resentLive)).sorted() if checksUnrecordedKeys { // The keys of v2 grants whose record is gone. A contract or a // group they are bound to is the app's if the app's owner owns @@ -3464,13 +3498,20 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { signer: KeychainSigner ) async throws { guard !grants.isEmpty else { return } - let live = Set(keys.filter { $0.disabledAt == nil }.map { UInt32(bitPattern: $0.keyId) }) - let keyIds = Set(grants.flatMap(\.keyIds)).intersection(live).sorted() + let keyIds = Set(grants.flatMap(\.keyIds)).intersection(AppConnect.liveGrantedKeyIds(in: keys)).sorted() if !keyIds.isEmpty { Self.logger.info("🔗 DASHCONNECT :: disabling \(keyIds.count, privacy: .public) key(s) of App Connect grants that landed late") try await disableKeys(keyIds, context: context, signer: signer) } - let grantKeys = Set(grants.map(\.key)) + // A live key a login could not have granted is left on, and so is + // the grant that names it. + // A grant naming a key the view lacks is not marked either: the view + // may be behind. + let leftOn = Set(keys.filter { $0.disabledAt == nil && !AppConnect.isLiveGrantedKey($0) } + .map { UInt32(bitPattern: $0.keyId) }) + let shown = Set(keys.map { UInt32(bitPattern: $0.keyId) }) + let grantKeys = Set(grants.filter { $0.keyIds.allSatisfy { shown.contains($0) && !leftOn.contains($0) } } + .map(\.key)) updateGrants(in: context.stores) { AppConnect.markKeysDisabled(in: &$0) { grantKeys.contains($0.key) } } } diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index b651b26e5b..d4a43ff183 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1437,6 +1437,17 @@ extension AppConnectV2LoginTests { AppConnect.isWithinPlan( stored, planned: plan(), now: Self.date(milliseconds: Self.expiresAt)), "its expiry has passed") + XCTAssertFalse( + AppConnect.isWithinPlan(stored, planned: plan(expiresAt: nil), now: Self.now), + "the plan sets no expiry, the earlier approval did") + let encryption = Self.addedEncryptionKey(8, data: 0x08) + XCTAssertTrue(AppConnect.isWithinPlan(AppConnect.ExpectedKey(encryption), planned: encryption, now: Self.now)) + let otherContract = ManagedPlatformWallet.IdentityPubkey( + keyId: 8, keyType: .ecdsaSecp256k1, purpose: .encryption, securityLevel: .medium, + pubkeyBytes: encryption.pubkeyBytes, contractBounds: .singleContract(id: Self.groupId)) + XCTAssertFalse( + AppConnect.isWithinPlan(AppConnect.ExpectedKey(encryption), planned: otherContract, now: Self.now), + "an encryption key bound to another contract") } func testSettlingConfirmsWhatLandedDropsWhatCannotAndMarksTheGrantsItRetired() { @@ -1537,6 +1548,12 @@ extension AppConnectV2LoginTests { XCTAssertTrue( AppConnect.recordedKeyIds(of: "identity", grants: [withReused], bindings: []).contains(5), "an auth key the record sends again was there when it was recorded") + XCTAssertEqual(AppConnect.resentKeyIds(of: withReused), [5]) + let added = withReused.pendingUpdate! + XCTAssertTrue(AppConnect.showsAddedLimits(of: added, in: [Self.onIdentity(Self.addedAuthKey(8, data: 0x08))])) + XCTAssertFalse(AppConnect.showsAddedLimits( + of: added, in: [Self.onIdentity(Self.addedAuthKey(8, data: 0x08), totalBudget: .some(1))])) + XCTAssertEqual(AppConnect.resentKeyIds(of: Self.grant(sessionKeyId: 3, additionalKeyIds: [4])), [], "only a waiting record") } func testARetrySubmitsTheSameKeysUnderTheSameIds() throws { @@ -1828,6 +1845,51 @@ extension AppConnectV2LoginTests { XCTAssertNil(store.grants.first { $0.key == old.key }?.keyDisabled, "the replaced key is still on") } + func testARecoveredGrantWithWiderLimitsIsRecordedButNotCompleted() async { + let key = Self.addedAuthKey(7, data: 0x07) + for (raised, why) in [ + (Self.onIdentity(key, totalBudget: .some(key.totalBudget! + 1)), "a larger budget"), + (Self.onIdentity(key, expiresAt: .some(key.expiresAt! + Self.dayMilliseconds)), "a later expiry"), + ] { + let record = Self.pendingGrant([key]) + let store = MemoryGrantStore() + do { + _ = try await Self.register( + record, add: [key], store: store, calls: Calls(), submit: { throw UpdateFailed() }, + views: [([raised], [Self.stored(key)])]) + XCTFail("not completed with \(why)") + } catch { + XCTAssertTrue(error is UpdateFailed, why) + } + let recorded = store.grants.first { $0.key == record.key } + XCTAssertNotNil(recorded, why) + XCTAssertNil(recorded?.pendingUpdate, "its key is there and can be disconnected") + } + + let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") + var renewal = Self.pendingGrant([key], retiring: [old.key]) + renewal.pendingUpdate?.disabledKeyIds = [3] + let store = MemoryGrantStore([old]) + _ = try? await Self.register( + renewal, add: [key], disable: [3], retiring: [old.key], store: store, calls: Calls(), + submit: { throw UpdateFailed() }, + views: [([Self.onIdentity(key, totalBudget: .some(key.totalBudget! + 1)), Self.key(3, disabled: true)], + [Self.stored(key)])]) + XCTAssertEqual(store.grants.first { $0.key == old.key }?.keyDisabled, true, "its disables landed") + + let off = MemoryGrantStore() + do { + _ = try await Self.register( + Self.pendingGrant([key, Self.addedAuthKey(8, data: 0x08)]), add: [key, Self.addedAuthKey(8, data: 0x08)], + store: off, calls: Calls(), submit: { throw UpdateFailed() }, + views: [([Self.onIdentity(key), Self.onIdentity(Self.addedAuthKey(8, data: 0x08), disabled: true)], + [Self.stored(key), Self.stored(Self.addedAuthKey(8, data: 0x08))])]) + XCTFail("a key turned off since is not handed out") + } catch { + XCTAssertTrue(error is UpdateFailed) + } + } + func testAFailedUpdateThatCanNeverLandDropsItsRecord() async { let key = Self.addedAuthKey(7, data: 0x07) let store = MemoryGrantStore() From 30c5b4d771cce68f20d698e7800da7e3a39f3d0c Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 17:15:12 +0200 Subject: [PATCH 19/29] fix(dashconnect): one-QR recovery hands out only the approved limits, no drop on the device clock, one-QR keeps off a waiting v2 record's ids - A one-QR registration found landed after a failure is handed out only when its key is live with exactly the limits it was registered with (AppConnect.showsRecordedLimits); a key whose limits were raised since is recorded so a disconnect turns it off, and the failure stands. - A v2 update whose outcome is not known is no longer taken as unable to land when its auth keys look expired: Platform judges expiry by block time, which a view does not carry. - A one-QR login reserves the ids of the same request's v2 record still waiting for its update, so it cannot take that record's id or record. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 15 ++++++++++ .../DashConnect/AppConnectV2Login.swift | 21 +++++--------- .../PlatformDashConnectDataSource.swift | 25 ++++++++++++----- .../DashConnect/AppConnectV2LoginTests.swift | 28 ++++--------------- .../PlatformDashConnectDataSourceTests.swift | 8 ++++++ 5 files changed, 53 insertions(+), 44 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 45fdf36e2c..87d8761fe2 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -466,6 +466,21 @@ enum AppConnect { } } + /// Whether the identity shows a record's session key live with exactly + /// the limits it was registered with: what the approval granted, so it + /// may be handed out. `holdsRecordedKey` also takes a key whose limits + /// were raised since, which is the grant's but wider than the approval. + static func showsRecordedLimits( + of grant: AppConnectGrant, + in keys: [ManagedIdentity.IdentityPublicKeyInfo] + ) -> Bool { + keys.contains { + UInt32(bitPattern: $0.keyId) == grant.sessionKeyId && $0.disabledAt == nil + && $0.totalBudget == grant.totalBudget + && $0.expiresAt.map { UInt64(bitPattern: $0) } == grant.expiresAt + } + } + /// Confirms the unconfirmed one-QR records of `identityId` whose key the /// identity now holds, and returns them. A record whose key is not there /// stays as it is: the update may still land, and nothing is taken from diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index df7994ab45..9397d7fb61 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1138,17 +1138,16 @@ extension AppConnect { /// above whatever the wallet's copy held, so `pending` cannot land /// after it. A view that shows that update and none of its ids means /// it never will. No revision is read: what the update did is. - /// - Every added key is an auth key past its expiry (with - /// `clockTolerance`): if it lands, nothing can sign with it. An - /// encryption key has no expiry, so this never ends one that adds it. + /// + /// Expiry ends nothing: Platform judges it by block time, which a view + /// does not carry, and the device's clock is not that. /// /// A key under an expected id with the expected data and no readable /// bound in the store is unknown: the store may not have loaded it yet. static func pendingV2Outcome( of pending: AppConnectGrant.PendingV2Update, currentIdentityPublicKeys keys: [ManagedIdentity.IdentityPublicKeyInfo], - bindings: [KeyBinding], - nowMilliseconds: Int64 + bindings: [KeyBinding] ) -> PendingV2Outcome { var allLanded = true var anyPresent = false @@ -1183,12 +1182,8 @@ extension AppConnect { } if takenElsewhere { return .cannotLand } if !anyPresent, pending.outlivedBy?.isShown(in: keys) == true { return .cannotLand } - let allExpired = pending.addedKeys.allSatisfy { expected in - expected.purpose == .authentication - && expected.expiresAt.map { !isUnexpired(Int64(bitPattern: $0), nowMilliseconds: nowMilliseconds) } == true - } // Its keys there, unplaced, may be a landed update still to settle. - return allExpired && !anyPresent ? .cannotLand : .unknown + return .unknown } /// Settles the v2 records of `identityId` whose update's outcome was not @@ -1203,8 +1198,7 @@ extension AppConnect { in grants: inout [AppConnectGrant], identityId: String, currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], - bindings: [KeyBinding], - nowMilliseconds: Int64 + bindings: [KeyBinding] ) -> (confirmed: [AppConnectGrant], dropped: [AppConnectGrant]) { var confirmed: [AppConnectGrant] = [] var dropped: [AppConnectGrant] = [] @@ -1214,8 +1208,7 @@ extension AppConnect { let replaced = showsDisabled(pending.disabledKeyIds, in: currentIdentityPublicKeys) ? pending.retiredGrantKeys : [] switch pendingV2Outcome( - of: pending, currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: bindings, - nowMilliseconds: nowMilliseconds + of: pending, currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: bindings ) { case .landed: var settled = grant diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 87a2b506e7..31289f536f 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1154,8 +1154,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { case .absent: guard let keyId = AppConnect.nextKeyId( currentIdentityPublicKeys: currentPublicKeys, + // A one-QR retry of this request may take its own id again; + // a v2 record of it waiting for its update may not: one-QR + // and v2 derive other keys from the same ephemeral key. reserved: AppConnect.reservedKeyIds( - grants: stores.grants.load().filter { !isGrantForRequest($0) }, identityId: identityId) + grants: stores.grants.load().filter { !isGrantForRequest($0) || $0.isPendingV2 }, + identityId: identityId) ) else { throw DashConnectPlatformError.noFreeKeyId } @@ -1236,6 +1240,17 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.logger.error("🔗 DASHCONNECT :: session key registration failed or is unconfirmed — \(error.localizedDescription, privacy: .public)") throw error } + // Its limits raised since: the key is the grant's, recorded + // so a disconnect turns it off, but wider than this approval, + // so it is not handed out. + guard AppConnect.showsRecordedLimits(of: pending, in: keys) else { + Self.logger.error("🔗 DASHCONNECT :: the session key is on the identity with limits wider than this approval's") + updateGrants(in: stores) { grants in + guard let index = grants.firstIndex(where: { $0.key == pending.key }) else { return } + grants[index].unconfirmedKeyHash160 = nil + } + throw error + } Self.logger.info("🔗 DASHCONNECT :: session key is on the identity although the update reported a failure") } Self.logger.info("🔗 DASHCONNECT :: session key registered") @@ -1872,7 +1887,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { disable: disable, retiredGrantKeys: retiredGrantKeys, grants: stores.grants, - nowMilliseconds: { Int64(AppConnect.milliseconds(self.now())) }, showRow: { // A record that waits for its update shows the app as // confirming, unless its row is already active. @@ -1985,7 +1999,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { disable: [UInt32], retiredGrantKeys: Set, grants: any AppConnectResponseStore, - nowMilliseconds: () -> Int64, showRow: () async -> Void, submit: () async throws -> Void, reread: () async -> (keys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [AppConnect.KeyBinding])?, @@ -2056,8 +2069,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { continue } let outcome = AppConnect.pendingV2Outcome( - of: pending, currentIdentityPublicKeys: view.keys, bindings: view.bindings, - nowMilliseconds: nowMilliseconds()) + of: pending, currentIdentityPublicKeys: view.keys, bindings: view.bindings) switch outcome { case .landed where disabled && AppConnect.showsAddedLimits(of: pending, in: view.keys): logger.info("🔗 DASHCONNECT :: the identity update landed without confirming") @@ -2414,11 +2426,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // Without the store's bindings a v2 record is not settled: one that // could not land would be dropped with its rows not judged. if let readBindings, stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { - let nowMilliseconds = Int64(AppConnect.milliseconds(now())) var grants = stores.grants.load() let settled = AppConnect.settlePendingV2Registrations( in: &grants, identityId: identityId, currentIdentityPublicKeys: currentIdentityPublicKeys, - bindings: bindings, nowMilliseconds: nowMilliseconds) + bindings: bindings) confirmedV2 = settled.confirmed if !settled.confirmed.isEmpty { Self.logger.info("🔗 DASHCONNECT :: \(settled.confirmed.count, privacy: .public) App Connect update(s) found to have landed") diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index d4a43ff183..c868a42f83 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1239,13 +1239,12 @@ extension AppConnectV2LoginTests { _ added: [ManagedPlatformWallet.IdentityPubkey], keys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [AppConnect.KeyBinding]? = nil, - now: Int64 = pendingNow, outlivedBy: AppConnect.OwnUpdate? = nil ) -> AppConnect.PendingV2Outcome { var pending = pendingUpdate(added) pending.outlivedBy = outlivedBy return AppConnect.pendingV2Outcome( - of: pending, currentIdentityPublicKeys: keys, bindings: bindings ?? added.map(stored), nowMilliseconds: now) + of: pending, currentIdentityPublicKeys: keys, bindings: bindings ?? added.map(stored)) } func testAPendingUpdateLandedOnlyWhenEveryKeyIsThereAsItWasAdded() { @@ -1350,22 +1349,6 @@ extension AppConnectV2LoginTests { XCTAssertNil(grants[4].pendingUpdate) } - func testAPendingUpdateOfExpiredAuthKeysOnlyIsDropped() { - let auth = Self.addedAuthKey(7, data: 0x07, expiresAt: Self.createdAt) - let tolerance = Int64(AppConnect.clockTolerance * 1000) - let past = Int64(Self.createdAt) + tolerance + 1 - XCTAssertEqual(Self.outcome([auth], keys: [], now: past), .cannotLand) - XCTAssertEqual( - Self.outcome([auth], keys: [], now: Int64(Self.createdAt) + tolerance - 1), .unknown, - "a device clock up to the tolerance fast does not end it") - XCTAssertEqual( - Self.outcome([auth, Self.addedEncryptionKey(8, data: 0x08)], keys: [], now: past), .unknown, - "an encryption key never expires") - XCTAssertEqual( - Self.outcome([auth], keys: [Self.onIdentity(auth)], bindings: [], now: past), .unknown, - "its key is there, the store just cannot place it yet") - } - func testAPendingUpdateWhoseKeyLimitsWereRaisedSinceLanded() { let auth = Self.addedAuthKey(7, data: 0x07) XCTAssertEqual( @@ -1394,7 +1377,7 @@ extension AppConnectV2LoginTests { let settled = AppConnect.settlePendingV2Registrations( in: &grants, identityId: "identity", currentIdentityPublicKeys: [Self.onIdentity(key), Self.key(3)], - bindings: [Self.stored(key)], nowMilliseconds: Self.pendingNow) + bindings: [Self.stored(key)]) XCTAssertEqual(settled.confirmed.map(\.key), [pending.key], "its keys are there and need their record") XCTAssertNil(grants[0].keyDisabled, "another update added them; the replaced key is still on") @@ -1402,7 +1385,7 @@ extension AppConnectV2LoginTests { _ = AppConnect.settlePendingV2Registrations( in: &landedOff, identityId: "identity", currentIdentityPublicKeys: [Self.onIdentity(key, disabled: true), Self.key(3)], - bindings: [Self.stored(key)], nowMilliseconds: Self.pendingNow) + bindings: [Self.stored(key)]) XCTAssertEqual(landedOff.map(\.key), [old.key]) XCTAssertNil(landedOff[0].keyDisabled) } @@ -1466,7 +1449,7 @@ extension AppConnectV2LoginTests { currentIdentityPublicKeys: [ Self.onIdentity(landedKey), Self.onIdentity(impossibleKey, data: Data(repeating: 0xEE, count: 20)), ], - bindings: [Self.stored(landedKey)], nowMilliseconds: Self.pendingNow) + bindings: [Self.stored(landedKey)]) XCTAssertEqual(settled.confirmed.map(\.key), [landed.key]) XCTAssertEqual(settled.dropped.map(\.key), [impossible.key]) @@ -1486,7 +1469,7 @@ extension AppConnectV2LoginTests { let settled = AppConnect.settlePendingV2Registrations( in: &grants, identityId: "identity", currentIdentityPublicKeys: [Self.onIdentity(key, disabled: true), Self.key(3, disabled: true)], - bindings: [Self.stored(key)], nowMilliseconds: Self.pendingNow) + bindings: [Self.stored(key)]) XCTAssertEqual(settled.dropped.map(\.key), [pending.key]) XCTAssertEqual(grants.map(\.key), [old.key]) XCTAssertEqual(grants[0].keyDisabled, true, "its update turned the replaced grant off") @@ -1720,7 +1703,6 @@ extension AppConnectV2LoginTests { var remaining = views return try await PlatformDashConnectDataSource.registerAppConnectV2Grant( record, add: add, disable: disable, retiredGrantKeys: retiring, grants: store, - nowMilliseconds: { pendingNow }, showRow: { calls.rowShown += 1 }, submit: { calls.submitted += 1; try submit() }, reread: { diff --git a/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift b/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift index 062fdcf2dc..b4fed92ff5 100644 --- a/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift +++ b/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift @@ -3041,6 +3041,14 @@ final class AppConnectLoginTests: XCTestCase { } XCTAssertTrue(AppConnect.holdsRecordedKey(pending, currentIdentityPublicKeys: key(), bindings: bound)) + XCTAssertTrue(AppConnect.showsRecordedLimits(of: pending, in: key())) + for (keys, why) in [ + (key(budget: 9_000), "a raised budget is wider than the approval"), + (key(expiry: 7_000), "so is a later expiry"), + (key(disabledAt: 1), "a key turned off"), + ] { + XCTAssertFalse(AppConnect.showsRecordedLimits(of: pending, in: keys), why) + } for (keys, why) in [ (key(budget: 9_000), "a limits update raised its budget"), (key(expiry: 7_000), "a limits update extended it"), From c0945f314d915e8746ce5bb56e96e4a9e8da207b Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 18:59:32 +0200 Subject: [PATCH 20/29] fix(dashconnect): keep a row while the app may still hold keys, settle predecessors only on placed keys, approved expiry as a ceiling - A row that a dropped record would take away stays while the app may still hold a key no record names, on this identity or another one of the wallet (identityHoldsAppKeys, shared with the disconnect's check); not known counts as held, so the user keeps the way to disconnect. - A renewal turns off a waiting predecessor's added keys only where the store places them, and waits while one is live but unplaced. - A one-QR login reserves a waiting v2 record's own ids as well. - The approved expiry is a ceiling when keys are sent again, for a waiting record and for keys already on the identity. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 4 +- .../DashConnect/AppConnectV2Login.swift | 52 +++-- .../PlatformDashConnectDataSource.swift | 191 ++++++++++++------ .../DashConnect/AppConnectV2LoginTests.swift | 35 +++- 4 files changed, 208 insertions(+), 74 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 87d8761fe2..a0a3b73473 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -212,7 +212,9 @@ enum AppConnect { /// record out of `grants`. static func reservedKeyIds(grants: [AppConnectGrant], identityId: String) -> Set { Set(grants.filter { $0.identityId == identityId && $0.isUnconfirmed }.flatMap { grant -> [UInt32] in - if let pending = grant.pendingUpdate { return pending.addedKeys.map(\.keyId) } + // A v2 record holds the ids it adds and the ones it sends again: + // a view that lags behind the record may not show the latter. + if let pending = grant.pendingUpdate { return grant.keyIds + pending.addedKeys.map(\.keyId) } return grant.submittedRevision == nil ? [] : [grant.sessionKeyId] }) } diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 9397d7fb61..964856e9d4 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -766,12 +766,19 @@ extension AppConnect { appId: String, connectionId: String?, keeping: Set, - currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo] + currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], + bindings: [KeyBinding] ) -> [UInt32] { guard let connectionId else { return [] } + // A record waiting for its update holds the keys it sends again, and + // of those it adds only the ones the store shows as added: an id + // with the same payload and another bound may be another request's. let previous = Set(grants .filter { $0.identityId == identityId && $0.appContractId == appId && $0.connectionId == connectionId } - .flatMap(\.keyIds)) + .flatMap { grant -> [UInt32] in + guard let pending = grant.pendingUpdate else { return grant.keyIds } + return Array(resentKeyIds(of: grant)) + pending.addedKeys.filter { isPlaced($0, in: bindings) }.map(\.keyId) + }) .subtracting(keeping) return currentIdentityPublicKeys .filter { @@ -781,6 +788,31 @@ extension AppConnect { .sorted() } + /// Whether the store shows `expected` as it was added: the same id, + /// payload and bound. + static func isPlaced(_ expected: ExpectedKey, in bindings: [KeyBinding]) -> Bool { + bindings.contains { + $0.keyId == expected.keyId && $0.data == expected.data && !$0.hasUnreadableBound && $0.bound == expected.bound + } + } + + /// Whether `grants` has a record waiting for its update with a key it + /// adds live under its id and payload that the store cannot place: whose + /// it is cannot be told yet. + static func hasUnplacedPendingKey( + _ grants: [AppConnectGrant], + currentIdentityPublicKeys keys: [ManagedIdentity.IdentityPublicKeyInfo], + bindings: [KeyBinding] + ) -> Bool { + grants.contains { grant in + grant.pendingUpdate?.addedKeys.contains { expected in + !isPlaced(expected, in: bindings) && keys.contains { + UInt32(bitPattern: $0.keyId) == expected.keyId && $0.data == expected.data && isLiveGrantedKey($0) + } + } == true + } + } + /// Whether one identity update can turn off all of `keyIds`. A login /// that replaces a connection's keys turns them all off in its own /// update or is refused: leaving some on would report a replacement @@ -1276,10 +1308,7 @@ extension AppConnect { var ids = Set(grants.filter { $0.identityId == identityId && !$0.isUnconfirmed }.flatMap(\.keyIds)) for grant in grants where grant.identityId == identityId { ids.formUnion(resentKeyIds(of: grant)) - for expected in grant.pendingUpdate?.addedKeys ?? [] where bindings.contains(where: { - $0.keyId == expected.keyId && $0.data == expected.data && !$0.hasUnreadableBound - && $0.bound == expected.bound - }) { + for expected in grant.pendingUpdate?.addedKeys ?? [] where isPlaced(expected, in: bindings) { ids.insert(expected.keyId) } } @@ -1312,9 +1341,7 @@ extension AppConnect { /// added, may be sent again for an approval that grants `planned`: the /// same key under the same id, type, purpose, level, read-only flag, /// bound and budget; and, when the plan sets an expiry, one still ahead - /// and no later than it (`clockTolerance` covers a clock moved back - /// between two tries), as `canResendAuthKey` asks of a key already - /// there; when it sets none, none. A request that + /// and no later than it; when it sets none, none. A request that /// repeats the ephemeral key derives the same keys whatever terms it /// asks for, so the earlier approval's terms are checked against this /// one's. @@ -1330,7 +1357,7 @@ extension AppConnect { stored.totalBudget == planned.totalBudget else { return false } guard let plannedExpiry = planned.expiresAt else { return stored.expiresAt == nil } guard let expiry = stored.expiresAt, expiry > milliseconds(now) else { return false } - return expiry <= plannedExpiry + UInt64(clockTolerance * 1000) + return expiry <= plannedExpiry } /// A live auth key a login could have granted: HASH160 and never MASTER, @@ -1351,8 +1378,7 @@ extension AppConnect { /// still has to be live, bound as the binding asks (`binding`, the /// store's record of the key; a key the store does not show, or shows /// with another bound, is not sent), carry the level the plan grants, - /// and limits no wider than the plan's (`clockTolerance` covers a clock - /// moved back between two tries). The payload alone proves nothing: a + /// and limits no wider than the plan's (its expiry is a ceiling). The payload alone proves nothing: a /// request that repeats another's ephemeral key derives the same one. /// A grant recorded for this request, when there is one, must name /// exactly the keys sent again; the caller checks that. @@ -1367,7 +1393,7 @@ extension AppConnect { guard isLiveGrantedKey(key), key.securityLevel == grant.securityLevel, key.totalBudget == grant.totalBudget, let expiresAt = key.expiresAt, expiresAt > Int64(milliseconds(now)) else { return false } - return UInt64(expiresAt) <= grant.expiresAt + UInt64(clockTolerance * 1000) + return UInt64(expiresAt) <= grant.expiresAt } /// `callback` with `ac=` appended, keeping its query. diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 31289f536f..d632a0cc21 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1112,7 +1112,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let currentPublicKeys = try await refreshedIdentityPublicKeys(context: context) await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores) + context: context, in: stores) func isGrantForRequest(_ grant: AppConnectGrant) -> Bool { grant.identityId == identityId && grant.appContractId == appContractId && grant.values.appEphemeralPubKeyHash == requestHash @@ -1501,7 +1501,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // as on any retry), and one that cannot land frees its ids. await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores, bindings: bindings) + context: context, in: stores, bindings: bindings) // Which rotations to derive depends on the keys the identity has. for grant in plan.encryption { encryptionKeys.append(try await MainActor.run { @@ -1700,7 +1700,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let superseded = stores.grants.load().filter(isSuperseded) guard AppConnect.sessionKeyIdsMissing( from: currentPublicKeys, for: superseded.filter { !$0.isUnconfirmed } - ).isEmpty else { + ).isEmpty, !AppConnect.hasUnplacedPendingKey( + superseded, currentIdentityPublicKeys: currentPublicKeys, bindings: bindings + ) else { throw DashConnectPlatformError.identityKeysOutOfDate } // An earlier approval of this request whose update's outcome is not @@ -1714,7 +1716,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { appId: appId, connectionId: connectionId, keeping: reused, - currentIdentityPublicKeys: currentPublicKeys + currentIdentityPublicKeys: currentPublicKeys, + bindings: bindings ) // The confirmed grants whose every key is off once the update lands. // A retry keeps the earlier attempt's, and adds a grant confirmed @@ -1739,7 +1742,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // or leave a key on; its outcome has to settle first. let current = AppConnect.supersededKeyIds( grants: superseded, identityId: identityId, appId: appId, connectionId: connectionId, - keeping: reused, currentIdentityPublicKeys: currentPublicKeys) + keeping: reused, currentIdentityPublicKeys: currentPublicKeys, bindings: bindings) guard Set(current) == Set(pending.disabledKeyIds) else { Self.logger.error("🔗 DASHCONNECT :: an earlier approval of this request may still land, and the connection changed since") throw DashConnectPlatformError.earlierApprovalPending @@ -1919,7 +1922,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { onDropped: { remaining in guard let bindings = try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer) else { return false } - await showRowsAfterDropping([record], grants: remaining, bindings: bindings, in: stores) + await showRowsAfterDropping( + [record], grants: remaining, bindings: bindings, context: context, in: stores) return true } ) @@ -2401,7 +2405,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { private func confirmRegistrations( identityId: String, currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], - modelContainer: ModelContainer, + context: Context, in stores: Stores, bindings knownBindings: [AppConnect.KeyBinding]? = nil ) async -> [AppConnectGrant] { @@ -2410,7 +2414,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // Unknown when the store cannot be read: no unconfirmed record is // confirmed without it, and no row is changed by it. let readBindings = knownBindings - ?? (try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer)) + ?? (try? Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer)) let bindings = readBindings ?? [] if stores.grants.load().contains(where: { $0.identityId == identityId && $0.isUnconfirmed }) { let confirmed = updateGrants(in: stores) { grants in @@ -2438,7 +2442,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // rows are written. A stop in between drops it again next time. if !settled.dropped.isEmpty { Self.logger.info("🔗 DASHCONNECT :: dropping \(settled.dropped.count, privacy: .public) App Connect update(s) that can no longer land") - await showRowsAfterDropping(settled.dropped, grants: grants, bindings: readBindings, in: stores) + await showRowsAfterDropping( + settled.dropped, grants: grants, bindings: readBindings, context: context, in: stores) } stores.grants.save(grants) } @@ -2464,16 +2469,56 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { _ dropped: [AppConnectGrant], grants: [AppConnectGrant], bindings: [AppConnect.KeyBinding], + context: Context, in stores: Stores ) async { let appIds = Set(dropped.map(\.appContractId)) let restoring = Set(dropped.filter { $0.pendingUpdate?.replacesApprovedRow == true }.map(\.appContractId)) + // A row that would go is kept while the app may still hold keys + // only a disconnect can judge: a key of this identity no record + // names, bound where only its owner says whose it is, or a key of the + // app on another identity of the wallet. Not known counts as yes: a + // row kept for nothing goes at the next disconnect, while a row + // dropped for live keys leaves no way to them. + let rows = rows(in: stores) + let after = Set(Self.rowsAfterDropping( + appIds: appIds, restoringApproved: restoring, grants: grants, bindings: bindings, rows: rows + ).map(\.id)) + let going = appIds.filter { appId in rows.contains { $0.id == appId } && !after.contains(appId) } + var keeping: Set = [] + for appId in going { + guard let appContract = Self.decodeIdentifier(appId) else { continue } + if await appMayHoldUnrecordedKeys( + appContractId: appContract, grants: grants, bindings: bindings, context: context + ) != false { + keeping.insert(appId) + } + } await updateRows(in: stores) { rows in Self.rowsAfterDropping( - appIds: appIds, restoringApproved: restoring, grants: grants, bindings: bindings, rows: rows) + appIds: appIds, restoringApproved: restoring, keeping: keeping, grants: grants, bindings: bindings, + rows: rows) } } + /// Whether the app holds a live key no grant record names, on this + /// identity or on another identity of the wallet + /// (`identityHoldsAppKeys`). Nil when that could not be told. + private func appMayHoldUnrecordedKeys( + appContractId: Data, + grants: [AppConnectGrant], + bindings: [AppConnect.KeyBinding], + context: Context + ) async -> Bool? { + let here = await identityHoldsAppKeys( + appContractId: appContractId, identityId: context.identityId, identityIndex: context.identityIndex, + bindings: bindings, grants: grants, context: context) + if here == true { return true } + let elsewhere = await anotherIdentityHoldsAppKeys(appContractId: appContractId, context: context) + if elsewhere == true { return true } + return here == nil || elsewhere == nil ? nil : false + } + /// After an update of this wallet to the identity landed: one more read /// of the identity, which also writes what it shows to the store, and /// the v2 records of the identity waiting for their outcome are settled @@ -2487,7 +2532,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { guard let keys = try? await refreshedIdentityPublicKeys(context: context) else { return nil } let confirmed = await confirmRegistrations( identityId: context.identityId.toBase58String(), currentIdentityPublicKeys: keys, - modelContainer: context.modelContainer, in: stores) + context: context, in: stores) return (confirmed, keys) } @@ -2496,11 +2541,14 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// waiting record kept, stays while another such record of the app /// does; is active while a confirmed grant of the app remains; goes back to the two-QR `.approved` row it /// replaced (`restoringApproved`); becomes active while a live auth key - /// the store shows bound to the app remains; and goes otherwise. Any other + /// the store shows bound to the app remains, or while the app may hold + /// keys elsewhere (`keeping`), so a disconnect can judge them; and goes + /// otherwise. Any other /// row is left as it is. static func rowsAfterDropping( appIds: Set, restoringApproved: Set = [], + keeping: Set = [], grants: [AppConnectGrant], bindings: [AppConnect.KeyBinding], rows: [DAppConnection] @@ -2531,7 +2579,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { if binding.singleContractId == appContract { return true } if case .documentType(let contractId, _) = binding.bound { return contractId == appContract } return false - }) else { return nil } + }) || keeping.contains(row.id) else { return nil } return row.withStatus(.active, loginKind: .oneQR, at: row.updatedAt) } } @@ -2934,7 +2982,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // then the app's, not shared. await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores) + context: context, in: stores) let bindings = try Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer) guard !bindings.isEmpty, !stores.grants.hasUnreadableRows(identityId: identityId) else { throw DashConnectPlatformError.identityKeysOutOfDate @@ -3221,7 +3269,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // A registration whose key has turned up is confirmed. await confirmRegistrations( identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, - modelContainer: context.modelContainer, in: stores) + context: context, in: stores) // A v2 update of the app whose outcome the read above could not // tell is settled once an update of this disconnect lands. let pendingV2 = Set(stores.grants.load().filter { isGranted($0) && $0.isPendingV2 }.map(\.key)) @@ -3555,60 +3603,87 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // another. var hasUnknown = false for other in others { + let bindings: [AppConnect.KeyBinding] do { - let bindings = try Self.storedKeyBindings( + bindings = try Self.storedKeyBindings( identityId: other.identityId.toBase58String(), modelContainer: context.modelContainer) - if AppConnect.holdsLiveSessionKey(appContractId: appContractId, bindings: bindings) { return true } - let otherIdentityId = other.identityId.toBase58String() - let unrecorded = AppConnect.unrecordedV2Keys( - recordedKeyIds: AppConnect.recordedKeyIds( - of: otherIdentityId, grants: context.stores.grants.load(), bindings: bindings), - bindings: bindings) - if !unrecorded.isEmpty { - let candidates = AppConnect.unrecordedV2KeyBoundIds(appContractId: appContractId, keys: unrecorded) - let owned = try await Self.ownedByOwner( - of: appContractId, contractIds: candidates.contracts, groupIds: candidates.groups, - sdk: context.sdk) - if !AppConnect.appsV2KeyIds( - appContractIds: owned.contracts, appGroupIds: owned.groups, keys: unrecorded - ).isEmpty { - return true - } - } - // An identity always has keys, so none stored means not - // loaded; and a session-shaped key with an unreadable bound - // may be the app's. - if bindings.isEmpty || bindings.contains(where: { - !$0.isDisabled && ($0.isSessionKeyShaped || $0.isV2AuthKeyShaped) && $0.hasUnreadableBound - }) { - hasUnknown = true - } - // Derive only for an identity that has a live key of either - // two-QR kind at all. - guard bindings.contains(where: { - !$0.isDisabled && ($0.isTwoQRAuthenticationKeyShaped || $0.isTwoQREncryptionKeyShaped) - }) else { continue } - let twoQRKeys = try await twoQRLoginPublicKeys( - appContractId: appContractId, - identityId: other.identityId, - identityIndex: other.identityIndex, - context: context) - if AppConnect.holdsLiveTwoQRLoginKey( - authenticationPublicKeyHash160: twoQRKeys.authenticationPublicKeyHash160, - encryptionPublicKey: twoQRKeys.encryptionPublicKey, - bindings: bindings - ) { - return true - } } catch { Self.logger.error( "🔗 DASHCONNECT :: keys of another identity not checked — \(error.localizedDescription, privacy: .public)") hasUnknown = true + continue + } + switch await identityHoldsAppKeys( + appContractId: appContractId, identityId: other.identityId, identityIndex: other.identityIndex, + bindings: bindings, grants: context.stores.grants.load(), context: context) { + case true?: return true + case nil: hasUnknown = true + case false?: break } } return hasUnknown ? nil : false } + /// Whether the store shows `identityId` with a live key of the app that + /// no grant record in `grants` names: a session key bound to the app's + /// contract, a v2-shaped key bound to a contract or group the app's + /// owner owns (read from Platform), or a key the two-QR login derives + /// for it. `nil` when that cannot be told: no keys stored, a live + /// session- or v2-shaped key with a bound this build cannot read, or a + /// read or derivation that failed. + private func identityHoldsAppKeys( + appContractId: Data, + identityId: Data, + identityIndex: UInt32, + bindings: [AppConnect.KeyBinding], + grants: [AppConnectGrant], + context: Context + ) async -> Bool? { + do { + if AppConnect.holdsLiveSessionKey(appContractId: appContractId, bindings: bindings) { return true } + let unrecorded = AppConnect.unrecordedV2Keys( + recordedKeyIds: AppConnect.recordedKeyIds( + of: identityId.toBase58String(), grants: grants, bindings: bindings), + bindings: bindings) + if !unrecorded.isEmpty { + let candidates = AppConnect.unrecordedV2KeyBoundIds(appContractId: appContractId, keys: unrecorded) + let owned = try await Self.ownedByOwner( + of: appContractId, contractIds: candidates.contracts, groupIds: candidates.groups, + sdk: context.sdk) + if !AppConnect.appsV2KeyIds( + appContractIds: owned.contracts, appGroupIds: owned.groups, keys: unrecorded + ).isEmpty { + return true + } + } + // An identity always has keys, so none stored means not + // loaded; and a session-shaped key with an unreadable bound + // may be the app's. + let unknown = bindings.isEmpty || bindings.contains(where: { + !$0.isDisabled && ($0.isSessionKeyShaped || $0.isV2AuthKeyShaped) && $0.hasUnreadableBound + }) + // Derive only for an identity that has a live key of either + // two-QR kind at all. + guard bindings.contains(where: { + !$0.isDisabled && ($0.isTwoQRAuthenticationKeyShaped || $0.isTwoQREncryptionKeyShaped) + }) else { return unknown ? nil : false } + let twoQRKeys = try await twoQRLoginPublicKeys( + appContractId: appContractId, identityId: identityId, identityIndex: identityIndex, context: context) + if AppConnect.holdsLiveTwoQRLoginKey( + authenticationPublicKeyHash160: twoQRKeys.authenticationPublicKeyHash160, + encryptionPublicKey: twoQRKeys.encryptionPublicKey, + bindings: bindings + ) { + return true + } + return unknown ? nil : false + } catch { + Self.logger.error( + "🔗 DASHCONNECT :: keys of an identity not checked — \(error.localizedDescription, privacy: .public)") + return nil + } + } + /// The identities the SDK's store attaches to this wallet on `network`. private static func storedWalletIdentities( walletId: Data, diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index c868a42f83..c3c9552b0b 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -346,6 +346,7 @@ final class AppConnectV2LoginTests: XCTestCase { XCTAssertFalse(resend(key(budget: 60_000_000_000))) XCTAssertFalse(resend(key(budget: nil))) XCTAssertFalse(resend(key(expiresAt: Self.expiresAt + 2 * Self.dayMilliseconds))) + XCTAssertFalse(resend(key(expiresAt: Self.expiresAt + 1)), "the approved expiry is a ceiling") XCTAssertFalse(resend(key(), now: Self.date(milliseconds: Self.expiresAt + 1)), "an expired key cannot sign") // The payload alone does not make the key this binding's: the store // has to show it with the binding's bound. @@ -1035,7 +1036,7 @@ final class AppConnectV2LoginTests: XCTestCase { func superseded(_ connectionId: String?, keeping: Set = []) -> [UInt32] { AppConnect.supersededKeyIds( grants: grants, identityId: "identity", appId: "app", connectionId: connectionId, - keeping: keeping, currentIdentityPublicKeys: keys) + keeping: keeping, currentIdentityPublicKeys: keys, bindings: []) } XCTAssertEqual(superseded("c1"), [10, 11]) XCTAssertEqual(superseded("c2"), [20, 21]) @@ -1056,10 +1057,33 @@ final class AppConnectV2LoginTests: XCTestCase { XCTAssertEqual( AppConnect.supersededKeyIds( grants: grants, identityId: "identity", appId: "app", connectionId: "c1", - keeping: [], currentIdentityPublicKeys: keys), + keeping: [], currentIdentityPublicKeys: keys, bindings: []), [3], "a damaged record never gets the identity's own keys disabled") } + func testAPendingPredecessorGivesUpOnlyTheKeysItCanBeShownToHold() { + let added = Self.addedAuthKey(8, data: 0x08) + var waiting = Self.pendingGrant([added], requestHash: "a1") + waiting.additionalKeyIds = [5] + let keys = [Self.key(5, level: .critical), Self.onIdentity(added)] + func superseded(_ bindings: [AppConnect.KeyBinding]) -> [UInt32] { + AppConnect.supersededKeyIds( + grants: [waiting], identityId: "identity", appId: "app", connectionId: "c1", + keeping: [], currentIdentityPublicKeys: keys, bindings: bindings) + } + XCTAssertEqual(superseded([Self.stored(added)]), [5, 8]) + XCTAssertEqual(superseded([]), [5], "the same payload under its id may be another request's") + var otherBound = Self.stored(added) + otherBound.bound = .singleContract(Self.appId) + XCTAssertEqual(superseded([otherBound]), [5]) + XCTAssertTrue(AppConnect.hasUnplacedPendingKey([waiting], currentIdentityPublicKeys: keys, bindings: [])) + XCTAssertFalse( + AppConnect.hasUnplacedPendingKey([waiting], currentIdentityPublicKeys: keys, bindings: [Self.stored(added)])) + XCTAssertEqual( + AppConnect.reservedKeyIds(grants: [waiting], identityId: "identity"), [5, 8], + "a waiting record holds the ids it sends again too") + } + func testARenewalTurnsOffEveryReplacedKeyInOneUpdateOrNone() { let max = UInt32(AppConnect.maxKeysDisabledPerUpdate) XCTAssertTrue(AppConnect.fitsOneUpdate(disabling: Array(1 ... max))) @@ -1420,6 +1444,9 @@ extension AppConnectV2LoginTests { AppConnect.isWithinPlan( stored, planned: plan(), now: Self.date(milliseconds: Self.expiresAt)), "its expiry has passed") + XCTAssertFalse( + AppConnect.isWithinPlan(stored, planned: plan(expiresAt: Self.expiresAt - 1), now: Self.now), + "an expiry even slightly earlier than the earlier approval's") XCTAssertFalse( AppConnect.isWithinPlan(stored, planned: plan(expiresAt: nil), now: Self.now), "the plan sets no expiry, the earlier approval did") @@ -1628,6 +1655,10 @@ extension AppConnectV2LoginTests { XCTAssertEqual( after([], rows: [row(.active)]).map(\.status), [], "an active one-QR row the waiting record kept goes once nothing holds the app") + XCTAssertEqual( + PlatformDashConnectDataSource.rowsAfterDropping( + appIds: [app], keeping: [app], grants: [], bindings: [], rows: [row(.confirming)]).map(\.status), + [.active], "the app may hold keys elsewhere: a disconnect judges them") XCTAssertEqual( after([Self.grant(sessionKeyId: 3, appId: app)], rows: [row(.active)]).map(\.status), [.active]) XCTAssertEqual( From 8c50790b54b141274383472d755cf6e2d9043007 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 19:07:51 +0200 Subject: [PATCH 21/29] fix(dashconnect): a kept row stays as it was, a disconnect clears a row whose update never left, a renewal checks its view - A row kept after a record is dropped, while the app may still hold keys, keeps its status instead of showing the app as connected; keys of other apps' records no longer make that answer unknown. - A disconnect with no live key of the app and a v2 update still waiting removes the row and keeps the record: an update that never left the device no longer leaves a row that cannot be disconnected, and one that lands after all shows the app again. - A renewal waits while the view lacks a key a waiting predecessor sends again. Co-Authored-By: Claude Opus 5.5 --- .../DashConnect/DashConnectModels.swift | 7 ++- .../PlatformDashConnectDataSource.swift | 63 +++++++++++-------- .../DashConnect/AppConnectV2LoginTests.swift | 2 +- 3 files changed, 42 insertions(+), 30 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift b/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift index 134283e6db..5653541001 100644 --- a/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift +++ b/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift @@ -159,9 +159,10 @@ extension DashConnectTokenPurchaseRequest { /// `confirming` is an App Connect v2 connection whose identity update was /// submitted and whose outcome is not known yet: its keys may be on the /// identity, so it offers a disconnect like an active one. The disconnect -/// turns off the app's live auth keys on the active identity; while the -/// record still waits after that, or with nothing to turn off, it is -/// refused (`registrationPending`). A build without this +/// turns off the app's live auth keys on the active identity, and is +/// refused (`registrationPending`) while the record still waits after +/// that. With nothing to turn off, the row goes and the record stays: an +/// update that lands after all shows the app again. A build without this /// status drops the row on load; the grant record stays. enum ConnectionStatus: String, Codable, CaseIterable { case approved diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index d632a0cc21..e4f7e65407 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1702,7 +1702,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { from: currentPublicKeys, for: superseded.filter { !$0.isUnconfirmed } ).isEmpty, !AppConnect.hasUnplacedPendingKey( superseded, currentIdentityPublicKeys: currentPublicKeys, bindings: bindings - ) else { + ), superseded.reduce(into: Set(), { $0.formUnion(AppConnect.resentKeyIds(of: $1)) }) + .isSubset(of: currentPublicKeys.map { UInt32(bitPattern: $0.keyId) }) + else { throw DashConnectPlatformError.identityKeysOutOfDate } // An earlier approval of this request whose update's outcome is not @@ -2513,10 +2515,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let here = await identityHoldsAppKeys( appContractId: appContractId, identityId: context.identityId, identityIndex: context.identityIndex, bindings: bindings, grants: grants, context: context) - if here == true { return true } - let elsewhere = await anotherIdentityHoldsAppKeys(appContractId: appContractId, context: context) - if elsewhere == true { return true } - return here == nil || elsewhere == nil ? nil : false + guard here == false else { return here } + return await anotherIdentityHoldsAppKeys(appContractId: appContractId, context: context) } /// After an update of this wallet to the identity landed: one more read @@ -2541,8 +2541,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// waiting record kept, stays while another such record of the app /// does; is active while a confirmed grant of the app remains; goes back to the two-QR `.approved` row it /// replaced (`restoringApproved`); becomes active while a live auth key - /// the store shows bound to the app remains, or while the app may hold - /// keys elsewhere (`keeping`), so a disconnect can judge them; and goes + /// the store shows bound to the app remains; stays as it is while the + /// app may hold keys elsewhere (`keeping`), so a disconnect can judge + /// them; and goes /// otherwise. Any other /// row is left as it is. static func rowsAfterDropping( @@ -2572,14 +2573,18 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // An auth key: the app's encryption key stays on after a // disconnect, and connects nothing by itself. let appContract = decodeIdentifier(row.id) - // A contract group is the app's only by its owner, which this - // does not look up. + // A contract group is the app's only by its owner, which the + // caller looks up (`keeping`). guard let appContract, bindings.contains(where: { binding in guard !binding.isDisabled, binding.isSessionKeyShaped || binding.isV2AuthKeyShaped else { return false } if binding.singleContractId == appContract { return true } if case .documentType(let contractId, _) = binding.bound { return contractId == appContract } return false - }) || keeping.contains(row.id) else { return nil } + }) else { + // Kept as it is, for a disconnect to judge: nothing here + // shows the app connected. + return keeping.contains(row.id) ? row : nil + } return row.withStatus(.active, loginKind: .oneQR, at: row.updatedAt) } } @@ -3394,21 +3399,25 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { appContractIds: owned.contracts, appGroupIds: owned.groups, keys: unrecorded) keyIds = Array(Set(keyIds).union(liveTwoQRLoginKeyIds).union(unrecordedV2KeyIds)).sorted() } - if !mayStillLand.isEmpty || !pendingV2.isEmpty, keyIds.isEmpty { + if !mayStillLand.isEmpty, keyIds.isEmpty { // No update would be sent, so nothing settles the registration. // This identity's own state comes first: whatever another // identity holds, this one cannot be told to be done. // TODO(dashconnect-pending-registration): an update that was // refused, or never sent, cannot be told from one still on its // way, so this stays until the identity's revision moves or the - // app's code is approved again. A v2 record stays until an update - // of this wallet to the identity lands, or its auth keys expire - // when it registers no encryption key. Until then the record also holds + // app's code is approved again. Until then the record also holds // the row for the wallet's other identities // (`registrationPendingOnAnotherIdentity`). Self.logger.error("🔗 DASHCONNECT :: a session key registration of the app may still land, and there is no key to disable") throw DashConnectPlatformError.registrationPending } + // A v2 update that never left the device reads the same as one on + // its way. With nothing live to turn off, the row goes and its record + // stays: if the update lands after all, a later settle confirms it + // and shows the app again (`appIdsWithoutTheirOneQRRow`), to be + // disconnected then. + let leavesWaitingRecord = !pendingV2.isEmpty && keyIds.isEmpty // For a one-QR row, the keys on another identity that no grant // record shows. `nil` when that could not be told. let heldOnAnotherIdentity: Bool? = checksUnrecordedKeys && !hasLiveGrantElsewhere() @@ -3495,10 +3504,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // An update of the app whose outcome this disconnect could not tell // keeps the row: the next disconnect settles it by the update that // landed here, which it has noted. - if stores.grants.load().contains(where: { pendingV2.contains($0.key) && $0.isPendingV2 }) { + if !leavesWaitingRecord, stores.grants.load().contains(where: { pendingV2.contains($0.key) && $0.isPendingV2 }) { Self.logger.error("🔗 DASHCONNECT :: an App Connect update of the app may still land") throw DashConnectPlatformError.registrationPending } + if leavesWaitingRecord { + Self.logger.info("🔗 DASHCONNECT :: no key of the app is live; its waiting update stays recorded") + } if let heldElsewhere = reasonHeldElsewhere(heldOnAnotherIdentity: heldOnAnotherIdentity == true) { return (heldElsewhere: heldElsewhere, asOneQR: asOneQR) } @@ -3624,13 +3636,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { return hasUnknown ? nil : false } - /// Whether the store shows `identityId` with a live key of the app that - /// no grant record in `grants` names: a session key bound to the app's - /// contract, a v2-shaped key bound to a contract or group the app's - /// owner owns (read from Platform), or a key the two-QR login derives - /// for it. `nil` when that cannot be told: no keys stored, a live - /// session- or v2-shaped key with a bound this build cannot read, or a - /// read or derivation that failed. + /// Whether the store shows `identityId` with a live key of the app: a + /// session key bound to the app's contract, a v2-shaped key no grant + /// record in `grants` names bound to a contract or group the app's owner + /// owns (read from Platform), or a key the two-QR login derives for it. + /// `nil` when that cannot be told: no keys stored, a live session- or + /// v2-shaped key no record names with a bound this build cannot read, + /// or a read or derivation that failed. private func identityHoldsAppKeys( appContractId: Data, identityId: Data, @@ -3641,10 +3653,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { ) async -> Bool? { do { if AppConnect.holdsLiveSessionKey(appContractId: appContractId, bindings: bindings) { return true } - let unrecorded = AppConnect.unrecordedV2Keys( - recordedKeyIds: AppConnect.recordedKeyIds( - of: identityId.toBase58String(), grants: grants, bindings: bindings), - bindings: bindings) + let recorded = AppConnect.recordedKeyIds(of: identityId.toBase58String(), grants: grants, bindings: bindings) + let unrecorded = AppConnect.unrecordedV2Keys(recordedKeyIds: recorded, bindings: bindings) if !unrecorded.isEmpty { let candidates = AppConnect.unrecordedV2KeyBoundIds(appContractId: appContractId, keys: unrecorded) let owned = try await Self.ownedByOwner( @@ -3661,6 +3671,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // may be the app's. let unknown = bindings.isEmpty || bindings.contains(where: { !$0.isDisabled && ($0.isSessionKeyShaped || $0.isV2AuthKeyShaped) && $0.hasUnreadableBound + && !recorded.contains($0.keyId) }) // Derive only for an identity that has a live key of either // two-QR kind at all. diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index c3c9552b0b..47c8c1d580 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1658,7 +1658,7 @@ extension AppConnectV2LoginTests { XCTAssertEqual( PlatformDashConnectDataSource.rowsAfterDropping( appIds: [app], keeping: [app], grants: [], bindings: [], rows: [row(.confirming)]).map(\.status), - [.active], "the app may hold keys elsewhere: a disconnect judges them") + [.confirming], "the app may hold keys elsewhere: kept as it is for a disconnect to judge") XCTAssertEqual( after([Self.grant(sessionKeyId: 3, appId: app)], rows: [row(.active)]).map(\.status), [.active]) XCTAssertEqual( From 0fef35b72e956bc2584ebebae816dfbfdb99de02 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 19:38:21 +0200 Subject: [PATCH 22/29] fix(dashconnect): only an added key witnesses an update, a dropped record's re-sent keys show again, a disconnect turns off placed pending keys - An update that only disables keys is no witness that a waiting update can no longer land: Platform takes a disable of a key that is already off. Only updates that added keys are noted and shown. - When a waiting record is dropped, the keys it sent again are taken off the shared profile keys the user kept, so they show in shared profile access, where they can be revoked. - A disconnect also turns off the keys a waiting record adds that the store places as added, and waits while one is live but unplaced. Co-Authored-By: Claude Opus 5.5 --- .../DashConnect/AppConnectV2Login.swift | 17 +++++---- .../PlatformDashConnectDataSource.swift | 36 ++++++++++++++++--- .../DashConnect/AppConnectV2LoginTests.swift | 23 ++++++++---- 3 files changed, 59 insertions(+), 17 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 964856e9d4..c39890559d 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1087,10 +1087,12 @@ extension AppConnect { } } - /// What an update of this wallet to an identity did, by what Platform - /// never undoes: the keys it added (a key is never removed) and the ids - /// it disabled (a key is never enabled again). A view that shows all of - /// it is at that update or past it. + /// What an update of this wallet to an identity did: the keys it added + /// and the ids it disabled. Only an added key witnesses the update: a key + /// is never removed and its id never taken again, while Platform takes a + /// disable of a key that is already off, so an update that only disables + /// proves nothing about when it landed. A view that shows all of an + /// update that added keys is at that update or past it. struct OwnUpdate: Codable, Equatable { struct AddedKey: Codable, Equatable { let keyId: UInt32 @@ -1106,7 +1108,7 @@ extension AppConnect { } func isShown(in keys: [ManagedIdentity.IdentityPublicKeyInfo]) -> Bool { - addedKeys.allSatisfy { added in keys.contains { + !addedKeys.isEmpty && addedKeys.allSatisfy { added in keys.contains { UInt32(bitPattern: $0.keyId) == added.keyId && $0.data == added.data } } && showsDisabled(disabledKeyIds, in: keys) } @@ -1119,13 +1121,16 @@ extension AppConnect { /// Notes on every v2 record of `identityId` still waiting for its update /// (except `exceptKey`'s, the update's own) that `update` landed after - /// it was submitted. An earlier note stays: it settles the same way. + /// it was submitted, when it added keys. An earlier note stays: it + /// settles the same way. static func noteOwnUpdate( _ update: OwnUpdate, in grants: inout [AppConnectGrant], identityId: String, exceptKey: String? = nil ) { + // One that only disables witnesses nothing (`OwnUpdate`). + guard !update.addedKeys.isEmpty else { return } for index in grants.indices where grants[index].identityId == identityId && grants[index].key != exceptKey && grants[index].pendingUpdate != nil && grants[index].pendingUpdate?.outlivedBy == nil { diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index e4f7e65407..c25a64c366 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1926,6 +1926,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { else { return false } await showRowsAfterDropping( [record], grants: remaining, bindings: bindings, context: context, in: stores) + forgetKeptSharedProfileKeys( + AppConnect.resentKeyIds(of: record), scope: stores.scope, identityId: identityId) return true } ) @@ -2446,6 +2448,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.logger.info("🔗 DASHCONNECT :: dropping \(settled.dropped.count, privacy: .public) App Connect update(s) that can no longer land") await showRowsAfterDropping( settled.dropped, grants: grants, bindings: readBindings, context: context, in: stores) + forgetKeptSharedProfileKeys( + settled.dropped.reduce(into: Set()) { $0.formUnion(AppConnect.resentKeyIds(of: $1)) }, + scope: stores.scope, identityId: identityId) } stores.grants.save(grants) } @@ -2938,6 +2943,19 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { recordedKeyIds: recordedKeyIds, bindings: bindings, nowMilliseconds: nowMilliseconds) } + /// Takes `keyIds` off the shared profile keys the user kept for this + /// identity: a record that sent them again is dropped, and a kept key + /// with no record has to show in shared profile access again, where it + /// can be revoked. + private func forgetKeptSharedProfileKeys(_ keyIds: Set, scope: String, identityId: String) { + guard !keyIds.isEmpty else { return } + let kept = keptSharedProfileKeyIds(scope: scope, identityId: identityId) + guard !kept.isDisjoint(with: keyIds) else { return } + keptSharedProfileKeys.set( + kept.subtracting(keyIds).sorted().map(Int.init), + forKey: Self.keptSharedProfileKeysKey(scope: scope, identityId: identityId)) + } + /// The shared profile keys the user kept for this identity in this scope. /// A key id is never reused on an identity, so an id names one key. private func keptSharedProfileKeyIds(scope: String, identityId: String) -> Set { @@ -3361,10 +3379,17 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // live and counted as its (`AppConnect.recordedKeyIds`), so they go // with the confirmed grants' keys. One the fetched list lacks, or a // live one the store cannot place, means a view is behind. - let resentByWaiting = stores.grants.load().filter { pendingV2.contains($0.key) } - .reduce(into: Set()) { $0.formUnion(AppConnect.resentKeyIds(of: $1)) } + // The keys it adds that the store places as added are its too. + let waiting = stores.grants.load().filter { pendingV2.contains($0.key) } + guard !AppConnect.hasUnplacedPendingKey(waiting, currentIdentityPublicKeys: currentPublicKeys, bindings: bindings) + else { throw DashConnectPlatformError.identityKeysOutOfDate } + let resentByWaiting = waiting.reduce(into: Set()) { ids, grant in + ids.formUnion(AppConnect.resentKeyIds(of: grant)) + ids.formUnion(grant.pendingUpdate?.addedKeys.filter { AppConnect.isPlaced($0, in: bindings) }.map(\.keyId) ?? []) + } let resentLive = AppConnect.liveGrantedKeyIds(in: currentPublicKeys).intersection(resentByWaiting) - guard resentByWaiting.isSubset(of: currentPublicKeys.map { UInt32(bitPattern: $0.keyId) }), + let resentOnly = waiting.reduce(into: Set()) { $0.formUnion(AppConnect.resentKeyIds(of: $1)) } + guard resentOnly.isSubset(of: currentPublicKeys.map { UInt32(bitPattern: $0.keyId) }), currentPublicKeys.filter({ resentLive.contains(UInt32(bitPattern: $0.keyId)) }).allSatisfy({ key in bindings.contains { $0.keyId == UInt32(bitPattern: key.keyId) && $0.data == key.data && !$0.hasUnreadableBound @@ -3502,8 +3527,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // the row, once what was turned off above is marked. if let lateDisableFailure { throw lateDisableFailure } // An update of the app whose outcome this disconnect could not tell - // keeps the row: the next disconnect settles it by the update that - // landed here, which it has noted. + // keeps the row. A disconnect only disables, which witnesses nothing + // (`AppConnect.OwnUpdate`), so the next disconnect finds nothing live + // and lets the row go with the record kept. if !leavesWaitingRecord, stores.grants.load().contains(where: { pendingV2.contains($0.key) && $0.isPendingV2 }) { Self.logger.error("🔗 DASHCONNECT :: an App Connect update of the app may still land") throw DashConnectPlatformError.registrationPending diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 47c8c1d580..19e23b4d0f 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1337,17 +1337,24 @@ extension AppConnectV2LoginTests { func testAnUpdateOfOursThatLandedLaterSettlesAPendingOneOnceAViewShowsIt() { let auth = Self.addedAuthKey(7, data: 0x07) let master = Self.key(0, level: .master) - let later = AppConnect.OwnUpdate(disabledKeyIds: [3]) + let laterKey = Self.addedAuthKey(11, data: 0x0B) + let later = AppConnect.OwnUpdate(added: [laterKey], disabledKeyIds: [3]) let showsLater = Self.key(3, disabled: true) - XCTAssertEqual(Self.outcome([auth], keys: [master, showsLater], outlivedBy: later), .cannotLand) + XCTAssertEqual( + Self.outcome([auth], keys: [master, showsLater, Self.onIdentity(laterKey)], outlivedBy: later), .cannotLand) + XCTAssertEqual( + Self.outcome([auth], keys: [master, showsLater], outlivedBy: AppConnect.OwnUpdate(disabledKeyIds: [3])), + .unknown, "a disable can be sent again for a key already off, so it witnesses nothing") XCTAssertEqual( Self.outcome([auth], keys: [master, Self.key(3)], outlivedBy: later), .unknown, "a view that does not show the later update is behind it") XCTAssertEqual(Self.outcome([auth], keys: [master, showsLater]), .unknown, "without one it may still land") XCTAssertEqual( - Self.outcome([auth], keys: [master, showsLater, Self.onIdentity(auth)], outlivedBy: later), .landed) + Self.outcome([auth], keys: [master, showsLater, Self.onIdentity(laterKey), Self.onIdentity(auth)], + outlivedBy: later), .landed) XCTAssertEqual( - Self.outcome([auth], keys: [showsLater, Self.onIdentity(auth)], bindings: [], outlivedBy: later), .unknown, + Self.outcome([auth], keys: [showsLater, Self.onIdentity(laterKey), Self.onIdentity(auth)], bindings: [], + outlivedBy: later), .unknown, "its key is there; the store just cannot place it") let added = Self.addedAuthKey(9, data: 0x09) XCTAssertEqual( @@ -1360,11 +1367,15 @@ extension AppConnectV2LoginTests { let own = Self.pendingGrant([Self.addedAuthKey(7, data: 0x07)], requestHash: "a1") let earlier = Self.pendingGrant([Self.addedAuthKey(9, data: 0x09)], requestHash: "a2") var noted = Self.pendingGrant([Self.addedAuthKey(11, data: 0x0B)], requestHash: "a3") - let first = AppConnect.OwnUpdate(disabledKeyIds: [1]) + let first = AppConnect.OwnUpdate(added: [Self.addedAuthKey(21, data: 0x15)], disabledKeyIds: [1]) noted.pendingUpdate?.outlivedBy = first let other = Self.pendingGrant([Self.addedAuthKey(13, data: 0x0D)], identityId: "other", requestHash: "a4") var grants = [own, earlier, noted, other, Self.grant(sessionKeyId: 3)] - let update = AppConnect.OwnUpdate(disabledKeyIds: [2]) + var disableOnly = grants + AppConnect.noteOwnUpdate( + AppConnect.OwnUpdate(disabledKeyIds: [2]), in: &disableOnly, identityId: "identity", exceptKey: own.key) + XCTAssertNil(disableOnly[1].pendingUpdate?.outlivedBy, "an update that only disables witnesses nothing") + let update = AppConnect.OwnUpdate(added: [Self.addedAuthKey(22, data: 0x16)], disabledKeyIds: [2]) AppConnect.noteOwnUpdate(update, in: &grants, identityId: "identity", exceptKey: own.key) XCTAssertNil(grants[0].pendingUpdate?.outlivedBy, "an update does not outlive itself") XCTAssertEqual(grants[1].pendingUpdate?.outlivedBy, update) From 43a448cef99eab823429c4cad650fd1ae2605354 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 19:45:32 +0200 Subject: [PATCH 23/29] fix(dashconnect): keep disables as an update's witness, a disconnect does not wait on unplaced pending keys Restores the disable witness of an own update: without it no disconnect settles a waiting record and the first one ends in an error after its keys are off. The repeatable-disable gap is noted as a TODO against the SDK's transition handle. A disconnect no longer refuses while a waiting record's added key is unplaced, which could block it for good; it turns off the keys the record holds (AppConnect.waitingKeyIds). Co-Authored-By: Claude Opus 5.5 --- .../DashConnect/AppConnectV2Login.swift | 30 ++++++++++++------- .../PlatformDashConnectDataSource.swift | 14 +++------ .../DashConnect/AppConnectV2LoginTests.swift | 10 ++----- 3 files changed, 26 insertions(+), 28 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index c39890559d..c3f78c5866 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -788,6 +788,15 @@ extension AppConnect { .sorted() } + /// The keys records waiting for their update hold: the ones they send + /// again, and the ones they add that the store places as added. + static func waitingKeyIds(_ waiting: [AppConnectGrant], bindings: [KeyBinding]) -> Set { + waiting.reduce(into: Set()) { ids, grant in + ids.formUnion(resentKeyIds(of: grant)) + ids.formUnion(grant.pendingUpdate?.addedKeys.filter { isPlaced($0, in: bindings) }.map(\.keyId) ?? []) + } + } + /// Whether the store shows `expected` as it was added: the same id, /// payload and bound. static func isPlaced(_ expected: ExpectedKey, in bindings: [KeyBinding]) -> Bool { @@ -1087,12 +1096,14 @@ extension AppConnect { } } - /// What an update of this wallet to an identity did: the keys it added - /// and the ids it disabled. Only an added key witnesses the update: a key - /// is never removed and its id never taken again, while Platform takes a - /// disable of a key that is already off, so an update that only disables - /// proves nothing about when it landed. A view that shows all of an - /// update that added keys is at that update or past it. + /// What an update of this wallet to an identity did, by what Platform + /// never undoes: the keys it added (a key is never removed) and the ids + /// it disabled (a key is never enabled again). A view that shows all of + /// it is at that update or past it. + /// TODO(dashconnect-disable-witness): Platform also takes a disable of + /// a key already off, so a view taken after an earlier disable of the + /// same id shows a disable-only update too; the SDK's handle to the + /// signed transition (dashpay/platform#5690) would settle it exactly. struct OwnUpdate: Codable, Equatable { struct AddedKey: Codable, Equatable { let keyId: UInt32 @@ -1108,7 +1119,7 @@ extension AppConnect { } func isShown(in keys: [ManagedIdentity.IdentityPublicKeyInfo]) -> Bool { - !addedKeys.isEmpty && addedKeys.allSatisfy { added in keys.contains { + addedKeys.allSatisfy { added in keys.contains { UInt32(bitPattern: $0.keyId) == added.keyId && $0.data == added.data } } && showsDisabled(disabledKeyIds, in: keys) } @@ -1121,16 +1132,13 @@ extension AppConnect { /// Notes on every v2 record of `identityId` still waiting for its update /// (except `exceptKey`'s, the update's own) that `update` landed after - /// it was submitted, when it added keys. An earlier note stays: it - /// settles the same way. + /// it was submitted. An earlier note stays: it settles the same way. static func noteOwnUpdate( _ update: OwnUpdate, in grants: inout [AppConnectGrant], identityId: String, exceptKey: String? = nil ) { - // One that only disables witnesses nothing (`OwnUpdate`). - guard !update.addedKeys.isEmpty else { return } for index in grants.indices where grants[index].identityId == identityId && grants[index].key != exceptKey && grants[index].pendingUpdate != nil && grants[index].pendingUpdate?.outlivedBy == nil { diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index c25a64c366..23a17a41c8 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -3381,14 +3381,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // live one the store cannot place, means a view is behind. // The keys it adds that the store places as added are its too. let waiting = stores.grants.load().filter { pendingV2.contains($0.key) } - guard !AppConnect.hasUnplacedPendingKey(waiting, currentIdentityPublicKeys: currentPublicKeys, bindings: bindings) - else { throw DashConnectPlatformError.identityKeysOutOfDate } - let resentByWaiting = waiting.reduce(into: Set()) { ids, grant in - ids.formUnion(AppConnect.resentKeyIds(of: grant)) - ids.formUnion(grant.pendingUpdate?.addedKeys.filter { AppConnect.isPlaced($0, in: bindings) }.map(\.keyId) ?? []) - } - let resentLive = AppConnect.liveGrantedKeyIds(in: currentPublicKeys).intersection(resentByWaiting) let resentOnly = waiting.reduce(into: Set()) { $0.formUnion(AppConnect.resentKeyIds(of: $1)) } + let resentByWaiting = AppConnect.waitingKeyIds(waiting, bindings: bindings) + let resentLive = AppConnect.liveGrantedKeyIds(in: currentPublicKeys).intersection(resentByWaiting) guard resentOnly.isSubset(of: currentPublicKeys.map { UInt32(bitPattern: $0.keyId) }), currentPublicKeys.filter({ resentLive.contains(UInt32(bitPattern: $0.keyId)) }).allSatisfy({ key in bindings.contains { @@ -3527,9 +3522,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // the row, once what was turned off above is marked. if let lateDisableFailure { throw lateDisableFailure } // An update of the app whose outcome this disconnect could not tell - // keeps the row. A disconnect only disables, which witnesses nothing - // (`AppConnect.OwnUpdate`), so the next disconnect finds nothing live - // and lets the row go with the record kept. + // keeps the row: the next disconnect settles it by the update that + // landed here, which it has noted. if !leavesWaitingRecord, stores.grants.load().contains(where: { pendingV2.contains($0.key) && $0.isPendingV2 }) { Self.logger.error("🔗 DASHCONNECT :: an App Connect update of the app may still land") throw DashConnectPlatformError.registrationPending diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 19e23b4d0f..9627e797a8 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1082,6 +1082,9 @@ final class AppConnectV2LoginTests: XCTestCase { XCTAssertEqual( AppConnect.reservedKeyIds(grants: [waiting], identityId: "identity"), [5, 8], "a waiting record holds the ids it sends again too") + XCTAssertEqual(AppConnect.waitingKeyIds([waiting], bindings: [Self.stored(added)]), [5, 8]) + XCTAssertEqual( + AppConnect.waitingKeyIds([waiting], bindings: []), [5], "an added key the store does not place is not taken") } func testARenewalTurnsOffEveryReplacedKeyInOneUpdateOrNone() { @@ -1342,9 +1345,6 @@ extension AppConnectV2LoginTests { let showsLater = Self.key(3, disabled: true) XCTAssertEqual( Self.outcome([auth], keys: [master, showsLater, Self.onIdentity(laterKey)], outlivedBy: later), .cannotLand) - XCTAssertEqual( - Self.outcome([auth], keys: [master, showsLater], outlivedBy: AppConnect.OwnUpdate(disabledKeyIds: [3])), - .unknown, "a disable can be sent again for a key already off, so it witnesses nothing") XCTAssertEqual( Self.outcome([auth], keys: [master, Self.key(3)], outlivedBy: later), .unknown, "a view that does not show the later update is behind it") @@ -1371,10 +1371,6 @@ extension AppConnectV2LoginTests { noted.pendingUpdate?.outlivedBy = first let other = Self.pendingGrant([Self.addedAuthKey(13, data: 0x0D)], identityId: "other", requestHash: "a4") var grants = [own, earlier, noted, other, Self.grant(sessionKeyId: 3)] - var disableOnly = grants - AppConnect.noteOwnUpdate( - AppConnect.OwnUpdate(disabledKeyIds: [2]), in: &disableOnly, identityId: "identity", exceptKey: own.key) - XCTAssertNil(disableOnly[1].pendingUpdate?.outlivedBy, "an update that only disables witnesses nothing") let update = AppConnect.OwnUpdate(added: [Self.addedAuthKey(22, data: 0x16)], disabledKeyIds: [2]) AppConnect.noteOwnUpdate(update, in: &grants, identityId: "identity", exceptKey: own.key) XCTAssertNil(grants[0].pendingUpdate?.outlivedBy, "an update does not outlive itself") From 140d69d3f37ecdca1a6f385b75e54deb60e6d8b9 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 20:26:03 +0200 Subject: [PATCH 24/29] fix(dashconnect): a disconnect waits while the fetched view lacks a key a waiting record holds The view-is-behind check covered only the keys a waiting record sends again; it now covers the keys it adds that the store places as added too, so a lagging view cannot let the row go while such a key is live. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/PlatformDashConnectDataSource.swift | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 23a17a41c8..07d67da453 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -3381,10 +3381,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // live one the store cannot place, means a view is behind. // The keys it adds that the store places as added are its too. let waiting = stores.grants.load().filter { pendingV2.contains($0.key) } - let resentOnly = waiting.reduce(into: Set()) { $0.formUnion(AppConnect.resentKeyIds(of: $1)) } let resentByWaiting = AppConnect.waitingKeyIds(waiting, bindings: bindings) let resentLive = AppConnect.liveGrantedKeyIds(in: currentPublicKeys).intersection(resentByWaiting) - guard resentOnly.isSubset(of: currentPublicKeys.map { UInt32(bitPattern: $0.keyId) }), + // Every key it holds (sent again, or added and placed by the store) + // has to be in the fetched list: one it lacks means the list is + // behind, and the keys could not be shown off. + guard resentByWaiting.isSubset(of: currentPublicKeys.map { UInt32(bitPattern: $0.keyId) }), currentPublicKeys.filter({ resentLive.contains(UInt32(bitPattern: $0.keyId)) }).allSatisfy({ key in bindings.contains { $0.keyId == UInt32(bitPattern: key.keyId) && $0.data == key.data && !$0.hasUnreadableBound From 4aabd15e37325ce923ea225cccb8ea34652d2459 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 21:03:22 +0200 Subject: [PATCH 25/29] fix(dashconnect): profile keys go only with a disconnect that leaves none of the app's records waiting A disconnect that leaves one of the app's v2 records waiting ends in registrationPending (or lets the row go without settling it), so it does not take the unattributed profile keys. The profile selection's doc and a test now cover a waiting record of another app holding its re-sent and placed profile keys. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectV2Login.swift | 5 +++-- .../PlatformDashConnectDataSource.swift | 5 ++++- .../DashConnect/AppConnectV2LoginTests.swift | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index ecf12a2ac2..3f1c962436 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -933,8 +933,9 @@ extension AppConnect { /// The unattributed profile keys a disconnect disables, from a fresh view /// of the identity: live, not yet expired, bound to an allowlisted - /// foreign document type, and not in `recordedKeyIds` (the keys confirmed - /// records name). + /// foreign document type, and not in `recordedKeyIds` (`recordedKeyIds(of:grants:bindings:)`: + /// the keys confirmed records name, and the keys a record waiting for its + /// update sends again or adds and the store places). /// `nil` when the view cannot be trusted: a live v2-shaped key no record /// names, in the view or in the store, has no readable stored bound, so /// it may be one of them; or the store holds one of them that the view diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index a3182e7620..94704b5b71 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -3281,8 +3281,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // is not taken for an unattributed one. A dropped record names // nothing, and the profile key it sent again goes here like any // other. + // A disconnect that leaves one of the app's records waiting ends in + // `registrationPending` (or lets the row go without settling it), so + // it is not one that ends here. let completesHere = (!keyIds.isEmpty || !granted.isEmpty) && heldOnAnotherIdentity == false - && reasonHeldElsewhere(heldOnAnotherIdentity: false) == nil + && reasonHeldElsewhere(heldOnAnotherIdentity: false) == nil && pendingV2.isEmpty var profileKeysOff: [UInt32] = [] var profileKeysUnchecked = false if completesHere { diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 2d63833eaf..091e1190ce 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -474,6 +474,20 @@ final class AppConnectV2LoginTests: XCTestCase { AppConnect.sharedProfileKeyIdsToDisable( recordedKeyIds: [5], bindings: bindings, currentIdentityPublicKeys: keys, nowMilliseconds: now), [1, 2], "not the expired one, the app's own, or the recorded one") + // A record of another app waiting for its update holds the profile + // key it sends again (2) and the one it adds that the store places (1). + var waiting = Self.pendingGrant( + [ManagedPlatformWallet.IdentityPubkey( + keyId: 1, keyType: .ecdsaHash160, purpose: .authentication, securityLevel: .high, + pubkeyBytes: Data([1]), contractBounds: .singleContractDocumentType(id: dashPay, documentTypeName: "profile"), + totalBudget: 1_000, expiresAt: 200_000_000)], + appId: "other-app") + waiting.additionalKeyIds = [2] + let recorded = AppConnect.recordedKeyIds(of: "identity", grants: [waiting], bindings: bindings) + XCTAssertEqual( + AppConnect.sharedProfileKeyIdsToDisable( + recordedKeyIds: recorded, bindings: bindings, currentIdentityPublicKeys: keys, nowMilliseconds: now), + [5], "another app's waiting profile keys are its own, not unattributed") XCTAssertEqual( AppConnect.storedSharedProfileKeyIds(recordedKeyIds: [5], bindings: bindings, nowMilliseconds: now), [1, 2]) From 37b62e6e9726cea0f5a8fbe719217af820b747bf Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sat, 31 Oct 2026 23:14:32 +0200 Subject: [PATCH 26/29] fix(dashconnect): a waiting record holding a live key is kept, a disable-only update witnesses nothing, renewals check placed pending keys - A waiting v2 record that would be dropped (cannot land, or landed and off) while it holds a live grantable auth key, one it sends again or a placed one it added, stays waiting: it keeps the app's row and lets a disconnect turn that key off. Once nothing of it is live it is dropped. Same in the failed-submit path of the registration. - An own update that only disables is not noted, and a view that shows it is no witness: Platform takes a disable of a key already off. An older note of such an update gives way to the next one that adds keys. - A disconnect whose app still has waiting records ends with success, the row going and the records kept, when the identity read after its update shows none of their keys live (placed or not); otherwise registrationPending. - A renewal requires every key a waiting predecessor holds (sent again, or added and placed) in the fetched view. Co-Authored-By: Claude Opus 5.5 --- .../DashConnect/AppConnectV2Login.swift | 74 ++++++++++++++----- .../PlatformDashConnectDataSource.swift | 68 +++++++++++------ .../DashConnect/AppConnectV2LoginTests.swift | 73 ++++++++++++++++++ 3 files changed, 174 insertions(+), 41 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 3f1c962436..4c6a305508 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -788,6 +788,30 @@ extension AppConnect { .sorted() } + /// The auth keys a v2 record waiting for its update holds that `keys` + /// shows live and grantable (`isLiveGrantedKey`): the ones it sends again, and the ones it adds that are + /// there under their id with their data and that the store places as + /// added (`isPlaced`: the same payload under its id with another bound + /// is another request's). Empty for any other record. + static func liveAuthKeyIds( + heldBy grant: AppConnectGrant, + in keys: [ManagedIdentity.IdentityPublicKeyInfo], + bindings: [KeyBinding] + ) -> Set { + guard let pending = grant.pendingUpdate else { return [] } + let resent = resentKeyIds(of: grant) + return Set(keys.compactMap { key -> UInt32? in + let keyId = UInt32(bitPattern: key.keyId) + // Keys a disconnect can turn off (`isLiveGrantedKey`), so a + // record kept for one does not wait on a key nothing turns off. + guard isLiveGrantedKey(key) else { return nil } + if resent.contains(keyId) { return keyId } + return pending.addedKeys.contains { + $0.keyId == keyId && $0.data == key.data && $0.purpose == .authentication && isPlaced($0, in: bindings) + } ? keyId : nil + }) + } + /// The keys records waiting for their update hold: the ones they send /// again, and the ones they add that the store places as added. static func waitingKeyIds(_ waiting: [AppConnectGrant], bindings: [KeyBinding]) -> Set { @@ -1099,14 +1123,16 @@ extension AppConnect { } } - /// What an update of this wallet to an identity did, by what Platform - /// never undoes: the keys it added (a key is never removed) and the ids - /// it disabled (a key is never enabled again). A view that shows all of - /// it is at that update or past it. - /// TODO(dashconnect-disable-witness): Platform also takes a disable of - /// a key already off, so a view taken after an earlier disable of the - /// same id shows a disable-only update too; the SDK's handle to the - /// signed transition (dashpay/platform#5690) would settle it exactly. + /// What an update of this wallet to an identity did: the keys it added + /// and the ids it disabled. Only an added key witnesses the update: a + /// key is never removed and its id never taken again, while Platform + /// takes a disable of a key that is already off, so a view taken after + /// an earlier disable of the same id would show a disable-only update + /// too. An update that added nothing is not noted (`noteOwnUpdate`), and + /// one that did is shown by a view that shows all of it. + /// TODO(dashconnect-disable-witness): a disconnect only disables, so it + /// never settles a waiting record; the SDK's handle to the signed + /// transition (dashpay/platform#5690) would. struct OwnUpdate: Codable, Equatable { struct AddedKey: Codable, Equatable { let keyId: UInt32 @@ -1122,7 +1148,7 @@ extension AppConnect { } func isShown(in keys: [ManagedIdentity.IdentityPublicKeyInfo]) -> Bool { - addedKeys.allSatisfy { added in keys.contains { + !addedKeys.isEmpty && addedKeys.allSatisfy { added in keys.contains { UInt32(bitPattern: $0.keyId) == added.keyId && $0.data == added.data } } && showsDisabled(disabledKeyIds, in: keys) } @@ -1142,9 +1168,14 @@ extension AppConnect { identityId: String, exceptKey: String? = nil ) { + // One that only disables witnesses nothing (`OwnUpdate`). + guard !update.addedKeys.isEmpty else { return } for index in grants.indices where grants[index].identityId == identityId && grants[index].key != exceptKey - && grants[index].pendingUpdate != nil && grants[index].pendingUpdate?.outlivedBy == nil { + && grants[index].pendingUpdate != nil + // A note an earlier build made of an update that added nothing + // witnesses nothing either, and gives way. + && grants[index].pendingUpdate?.outlivedBy?.addedKeys.isEmpty != false { grants[index].pendingUpdate?.outlivedBy = update } } @@ -1240,8 +1271,11 @@ extension AppConnect { /// and the earlier grants its update retired are marked done once the /// keys it disables show off; one that landed and is off again is /// dropped, with those marked done the same way; one that cannot land is - /// dropped; the rest stay as they are. A grant whose keys are still on - /// stays live, and a disconnect turns them off. + /// dropped; the rest stay as they are. A record that would be dropped + /// while it holds a live auth key (`liveAuthKeyIds(heldBy:in:bindings:)`) stays + /// waiting instead: it is what keeps the app's row and lets a disconnect + /// turn that key off. A grant whose keys are still on stays live, and a + /// disconnect turns them off. static func settlePendingV2Registrations( in grants: inout [AppConnectGrant], identityId: String, @@ -1255,20 +1289,20 @@ extension AppConnect { guard let pending = grant.pendingUpdate else { continue } let replaced = showsDisabled(pending.disabledKeyIds, in: currentIdentityPublicKeys) ? pending.retiredGrantKeys : [] - switch pendingV2Outcome( - of: pending, currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: bindings - ) { + let outcome = pendingV2Outcome( + of: pending, currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: bindings) + switch outcome { case .landed: var settled = grant settled.pendingUpdate = nil settled.unconfirmedKeyHash160 = nil confirmed.append(settled) retired.formUnion(replaced) - case .landedAndOff: - dropped.append(grant) - retired.formUnion(replaced) - case .cannotLand: - dropped.append(grant) + case .landedAndOff, .cannotLand: + if outcome == .landedAndOff { retired.formUnion(replaced) } + if liveAuthKeyIds(heldBy: grant, in: currentIdentityPublicKeys, bindings: bindings).isEmpty { + dropped.append(grant) + } case .unknown: break } diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 94704b5b71..2bafad7347 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1716,7 +1716,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { from: currentPublicKeys, for: superseded.filter { !$0.isUnconfirmed } ).isEmpty, !AppConnect.hasUnplacedPendingKey( superseded, currentIdentityPublicKeys: currentPublicKeys, bindings: bindings - ), superseded.reduce(into: Set(), { $0.formUnion(AppConnect.resentKeyIds(of: $1)) }) + // Every key a waiting predecessor holds (sent again, or added and + // placed by the store) has to be in the fetched list: one it lacks + // means the list is behind, and the renewal could not turn it off. + ), AppConnect.waitingKeyIds(superseded, bindings: bindings) .isSubset(of: currentPublicKeys.map { UInt32(bitPattern: $0.keyId) }) else { throw DashConnectPlatformError.identityKeysOutOfDate @@ -2007,7 +2010,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// confirmed and the failure stands, so nothing wider than the approval /// is published; cannot land runs /// `onDropped` with the records without this one, drops it when that - /// wrote the rows, and rethrows; + /// wrote the rows, and rethrows (a record that still holds a live auth + /// key stays waiting instead, and the failure stands); /// unknown keeps the record and rethrows. A record that adds nothing is /// confirmed from the start and only waits for its disables. /// @@ -2051,7 +2055,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // noted. func landed(noting: Bool, retiring: Bool = true) -> [AppConnectGrant] { var all = grants.load() - if noting, !add.isEmpty || !disable.isEmpty { + if noting, !add.isEmpty { AppConnect.noteOwnUpdate( AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), in: &all, identityId: record.identityId, exceptKey: record.key) @@ -2107,6 +2111,14 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { throw error case .landedAndOff, .cannotLand: let didLand = outcome == .landedAndOff + // A record that holds a live auth key (one it sends + // again, or one it added) stays waiting: it keeps the + // app's row and lets a disconnect turn that key off. + guard AppConnect.liveAuthKeyIds(heldBy: record, in: view.keys, bindings: view.bindings).isEmpty else { + logger.info("🔗 DASHCONNECT :: the identity update will not complete, and its record holds a live key; it stays") + if didLand { grants.save(landed(noting: false, retiring: disabled)) } + throw error + } let what = didLand ? "landed, and its keys are off already" : "can no longer land" logger.info("🔗 DASHCONNECT :: the identity update \(what, privacy: .public); its record is dropped") var all = didLand ? landed(noting: false, retiring: disabled) : grants.load() @@ -3249,12 +3261,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.logger.error("🔗 DASHCONNECT :: a session key registration of the app may still land, and there is no key to disable") throw DashConnectPlatformError.registrationPending } - // A v2 update that never left the device reads the same as one on - // its way. With nothing live to turn off, the row goes and its record - // stays: if the update lands after all, a later settle confirms it - // and shows the app again (`appIdsWithoutTheirOneQRRow`), to be - // disconnected then. - let leavesWaitingRecord = !pendingV2.isEmpty && keyIds.isEmpty // For a one-QR row, the keys on another identity that no grant // record shows. `nil` when that could not be told. let heldOnAnotherIdentity: Bool? = checksUnrecordedKeys && !hasLiveGrantElsewhere() @@ -3281,9 +3287,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // is not taken for an unattributed one. A dropped record names // nothing, and the profile key it sent again goes here like any // other. - // A disconnect that leaves one of the app's records waiting ends in - // `registrationPending` (or lets the row go without settling it), so - // it is not one that ends here. + // A disconnect with one of the app's records waiting can still end in + // `registrationPending` after its update (a key turned up, or the + // identity could not be read again), so it is not one that ends here. let completesHere = (!keyIds.isEmpty || !granted.isEmpty) && heldOnAnotherIdentity == false && reasonHeldElsewhere(heldOnAnotherIdentity: false) == nil && pendingV2.isEmpty var profileKeysOff: [UInt32] = [] @@ -3304,6 +3310,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { profileKeysUnchecked = true } } + // The identity as this disconnect leaves it: as read, when it sends + // nothing; as read again after its update, when it does. + var keysAfterUpdate: [ManagedIdentity.IdentityPublicKeyInfo]? = keyIds.isEmpty ? currentPublicKeys : nil if !keyIds.isEmpty { Self.logger.info("🔗 DASHCONNECT :: disabling \(keyIds.count, privacy: .public) app key(s)") // Platform takes a limited number of keys per update. A failure @@ -3340,6 +3349,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // turns out to have landed holds keys that are turned off too. // The keys above are off either way. if let settled = await settleAfterOwnUpdate(context: context, stores: stores) { + keysAfterUpdate = settled.keys do { try await disableLateLandedGrants( settled.confirmed.filter { pendingV2.contains($0.key) }, liveIn: settled.keys, @@ -3378,15 +3388,29 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // Keys of the app that landed late and could not be turned off keep // the row, once what was turned off above is marked. if let lateDisableFailure { throw lateDisableFailure } - // An update of the app whose outcome this disconnect could not tell - // keeps the row: the next disconnect settles it by the update that - // landed here, which it has noted. - if !leavesWaitingRecord, stores.grants.load().contains(where: { pendingV2.contains($0.key) && $0.isPendingV2 }) { - Self.logger.error("🔗 DASHCONNECT :: an App Connect update of the app may still land") - throw DashConnectPlatformError.registrationPending - } - if leavesWaitingRecord { - Self.logger.info("🔗 DASHCONNECT :: no key of the app is live; its waiting update stays recorded") + // A record of the app still waiting for its update keeps the row + // while it holds a live key, or while the identity could not be read + // again. One that holds none lets the row go and stays recorded: a + // disconnect only disables, which witnesses nothing + // (`AppConnect.OwnUpdate`), and an update that never left the device + // reads the same as one on its way. If it lands after all, a later + // settle confirms it and shows the app again + // (`appIdsWithoutTheirOneQRRow`), to be disconnected then. + let stillWaiting = stores.grants.load().filter { pendingV2.contains($0.key) && $0.isPendingV2 } + if !stillWaiting.isEmpty { + // The store as the read after the update left it; a live key a + // record adds that it cannot place may be the record's too. + guard let keysAfterUpdate, + let bindingsAfter = try? Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer), + stillWaiting.allSatisfy({ + AppConnect.liveAuthKeyIds(heldBy: $0, in: keysAfterUpdate, bindings: bindingsAfter).isEmpty + }), + !AppConnect.hasUnplacedPendingKey(stillWaiting, currentIdentityPublicKeys: keysAfterUpdate, bindings: bindingsAfter) + else { + Self.logger.error("🔗 DASHCONNECT :: an App Connect update of the app may still land") + throw DashConnectPlatformError.registrationPending + } + Self.logger.info("🔗 DASHCONNECT :: no key of the app's waiting update is live; it stays recorded") } if let heldElsewhere = reasonHeldElsewhere(heldOnAnotherIdentity: heldOnAnotherIdentity == true) { return (heldElsewhere: heldElsewhere, asOneQR: asOneQR, profileKeys: DashConnectDisconnectResult()) @@ -3428,6 +3452,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// (`AppConnect.pendingV2Outcome`). The v2 approval notes its own update /// in `registerAppConnectV2Grant`, leaving its own record out. private func noteOwnUpdateLanded(_ update: AppConnect.OwnUpdate, context: Context) { + // One that only disables witnesses nothing (`AppConnect.OwnUpdate`). + guard !update.addedKeys.isEmpty else { return } let identityId = context.identityId.toBase58String() guard context.stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) else { return diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 091e1190ce..1eab585a1a 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1359,6 +1359,12 @@ extension AppConnectV2LoginTests { let showsLater = Self.key(3, disabled: true) XCTAssertEqual( Self.outcome([auth], keys: [master, showsLater, Self.onIdentity(laterKey)], outlivedBy: later), .cannotLand) + // Key 3 turned off once before this update, which then lands, and + // turned off again by a later disconnect: a view from between the + // two disables shows the second one too, without this update's key. + XCTAssertEqual( + Self.outcome([auth], keys: [master, showsLater], outlivedBy: AppConnect.OwnUpdate(disabledKeyIds: [3])), + .unknown, "a disable can be sent again for a key already off, so it witnesses nothing") XCTAssertEqual( Self.outcome([auth], keys: [master, Self.key(3)], outlivedBy: later), .unknown, "a view that does not show the later update is behind it") @@ -1386,6 +1392,14 @@ extension AppConnectV2LoginTests { let other = Self.pendingGrant([Self.addedAuthKey(13, data: 0x0D)], identityId: "other", requestHash: "a4") var grants = [own, earlier, noted, other, Self.grant(sessionKeyId: 3)] let update = AppConnect.OwnUpdate(added: [Self.addedAuthKey(22, data: 0x16)], disabledKeyIds: [2]) + var disableOnly = grants + AppConnect.noteOwnUpdate( + AppConnect.OwnUpdate(disabledKeyIds: [2]), in: &disableOnly, identityId: "identity", exceptKey: own.key) + XCTAssertNil(disableOnly[1].pendingUpdate?.outlivedBy, "an update that only disables witnesses nothing") + var olderNote = grants + olderNote[1].pendingUpdate?.outlivedBy = AppConnect.OwnUpdate(disabledKeyIds: [4]) + AppConnect.noteOwnUpdate(update, in: &olderNote, identityId: "identity", exceptKey: own.key) + XCTAssertEqual(olderNote[1].pendingUpdate?.outlivedBy, update, "a note of a disable-only update gives way") AppConnect.noteOwnUpdate(update, in: &grants, identityId: "identity", exceptKey: own.key) XCTAssertNil(grants[0].pendingUpdate?.outlivedBy, "an update does not outlive itself") XCTAssertEqual(grants[1].pendingUpdate?.outlivedBy, update) @@ -1509,6 +1523,45 @@ extension AppConnectV2LoginTests { XCTAssertTrue(grants[3].isPendingV2, "another identity's record waits for a view of that identity") } + func testAWaitingRecordThatHoldsALiveKeyIsNotDropped() { + let added = Self.addedAuthKey(8, data: 0x08) + var record = Self.pendingGrant([added], requestHash: "a1") + record.additionalKeyIds = [5] + let resentLive = Self.key(5, level: .critical) + let taken = Self.onIdentity(added, data: Data(repeating: 0xEE, count: 20)) + let placed = [Self.stored(added)] + XCTAssertEqual(AppConnect.liveAuthKeyIds(heldBy: record, in: [resentLive, taken], bindings: placed), [5]) + XCTAssertEqual(AppConnect.liveAuthKeyIds(heldBy: record, in: [Self.onIdentity(added)], bindings: placed), [8]) + XCTAssertEqual( + AppConnect.liveAuthKeyIds(heldBy: record, in: [Self.onIdentity(added)], bindings: []), [], + "an added key the store does not place may be another request's") + XCTAssertEqual( + AppConnect.liveAuthKeyIds(heldBy: record, in: [taken, Self.key(5, disabled: true)], bindings: placed), [], + "another key under its id is not its own") + XCTAssertEqual( + AppConnect.liveAuthKeyIds(heldBy: Self.grant(sessionKeyId: 5), in: [resentLive], bindings: []), [], + "only a waiting record") + + for (keys, why) in [ + ([resentLive, taken], "cannot land, a key it sends again is live"), + ([resentLive, Self.onIdentity(added, disabled: true)], "landed and off, a key it sends again is live"), + ([Self.key(5, disabled: true), Self.onIdentity(added, totalBudget: .some(1))], + "cannot land by its limits, its placed added key is live"), + ] { + var grants = [record] + let settled = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: "identity", currentIdentityPublicKeys: keys, bindings: [Self.stored(added)]) + XCTAssertEqual(settled.dropped, [], why) + XCTAssertEqual(grants.map(\.key), [record.key], why) + XCTAssertTrue(grants[0].isPendingV2, why) + } + var grants = [record] + let settled = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: "identity", + currentIdentityPublicKeys: [Self.key(5, disabled: true), taken], bindings: []) + XCTAssertEqual(settled.dropped.map(\.key), [record.key], "nothing of it is live any more") + } + func testAPendingUpdateThatLandedAndIsOffAgainIsDroppedWithWhatItRetired() { let key = Self.addedAuthKey(7, data: 0x07) let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") @@ -1924,6 +1977,26 @@ extension AppConnectV2LoginTests { } } + func testAFailedUpdateThatCanNeverLandKeepsARecordHoldingALiveKey() async { + let added = Self.addedAuthKey(8, data: 0x08) + var record = Self.pendingGrant([added]) + record.additionalKeyIds = [5] + let store = MemoryGrantStore() + let calls = Calls() + do { + _ = try await Self.register( + record, add: [added], store: store, calls: calls, submit: { throw UpdateFailed() }, + views: [([Self.key(5, level: .critical), Self.onIdentity(added, data: Data(repeating: 0xEE, count: 20))], [])]) + XCTFail("the failure stands") + } catch { + XCTAssertTrue(error is UpdateFailed) + } + XCTAssertEqual(store.grants.map(\.key), [record.key], "the key it sent again is live, so the record stays") + XCTAssertTrue(store.grants.first?.isPendingV2 == true) + XCTAssertEqual(calls.dropped, 0, "its row stays") + + } + func testAFailedUpdateThatCanNeverLandDropsItsRecord() async { let key = Self.addedAuthKey(7, data: 0x07) let store = MemoryGrantStore() From 17770c1f775c0ff8e80dcd61e03296c1c6eb1ee8 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sun, 1 Nov 2026 00:15:14 +0200 Subject: [PATCH 27/29] fix(dashconnect): a waiting record keeps the keys the store gives it, and a disconnect checks its follow-up view - A waiting record is dropped only when it holds no key by the store or the view (AppConnect.heldKeyIds): its re-sent keys and its added keys the store places count even when a lagging view omits them, unless the view shows them off or under another key or the store has them disabled; an added key live as added with no readable store record counts as unknown. Used by the settle and the failed-submit path. - A disconnect lets the row go with records still waiting only when its follow-up view shows every auth key the store gives them (AppConnect.showsWaitingKeys) and none of them is held. Co-Authored-By: Claude Opus 5.5 --- .../DashConnect/AppConnectV2Login.swift | 81 +++++++++++++---- .../PlatformDashConnectDataSource.swift | 22 ++--- .../DashConnect/AppConnectV2LoginTests.swift | 90 +++++++++++++++++-- 3 files changed, 158 insertions(+), 35 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 4c6a305508..52809290d7 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -788,28 +788,71 @@ extension AppConnect { .sorted() } - /// The auth keys a v2 record waiting for its update holds that `keys` - /// shows live and grantable (`isLiveGrantedKey`): the ones it sends again, and the ones it adds that are - /// there under their id with their data and that the store places as - /// added (`isPlaced`: the same payload under its id with another bound - /// is another request's). Empty for any other record. - static func liveAuthKeyIds( + /// The auth keys a v2 record waiting for its update may still hold, so + /// that it is not dropped while one of them could be live. Ownership is + /// taken from the store, not only from `keys` (one view, which may lag + /// behind the store or omit a key): + /// - a key it sends again, or one it adds that the store places as added + /// (`isPlaced`), unless `keys` shows that id off or with another key, + /// or the store has it disabled; one `keys` omits counts while the + /// store still holds it; + /// - a key it adds that `keys` shows live under its id with its data and + /// that the store has no readable record of yet: whose it is is not + /// known. A readable record with another bound is another request's. + /// A key `keys` shows live must be one a disconnect can turn off + /// (`isLiveGrantedKey`). Empty for any other record. + static func heldKeyIds( heldBy grant: AppConnectGrant, in keys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [KeyBinding] ) -> Set { guard let pending = grant.pendingUpdate else { return [] } - let resent = resentKeyIds(of: grant) - return Set(keys.compactMap { key -> UInt32? in - let keyId = UInt32(bitPattern: key.keyId) - // Keys a disconnect can turn off (`isLiveGrantedKey`), so a - // record kept for one does not wait on a key nothing turns off. - guard isLiveGrantedKey(key) else { return nil } - if resent.contains(keyId) { return keyId } - return pending.addedKeys.contains { - $0.keyId == keyId && $0.data == key.data && $0.purpose == .authentication && isPlaced($0, in: bindings) - } ? keyId : nil - }) + func shown(_ keyId: UInt32) -> ManagedIdentity.IdentityPublicKeyInfo? { + keys.first { UInt32(bitPattern: $0.keyId) == keyId } + } + func isOff(_ keyId: UInt32) -> Bool { + shown(keyId)?.disabledAt != nil || bindings.contains { $0.keyId == keyId && $0.isDisabled } + } + // A key the view omits counts only while the store holds it, so a + // record is not kept for an id nothing on the identity shows. + func canBeTurnedOff(_ keyId: UInt32) -> Bool { + shown(keyId).map(isLiveGrantedKey) ?? bindings.contains { $0.keyId == keyId } + } + var held = Set() + for keyId in resentKeyIds(of: grant) where !isOff(keyId) && canBeTurnedOff(keyId) { + held.insert(keyId) + } + for expected in pending.addedKeys where expected.purpose == .authentication { + if isPlaced(expected, in: bindings) { + // Another key under its id in the view means the store's + // placement is not this key's: ids are never reused. + let sameKey = shown(expected.keyId).map { $0.data == expected.data } ?? true + if sameKey && !isOff(expected.keyId) && canBeTurnedOff(expected.keyId) { held.insert(expected.keyId) } + } else if let key = shown(expected.keyId), key.data == expected.data, isLiveGrantedKey(key), + !bindings.contains(where: { + $0.keyId == expected.keyId && $0.data == expected.data && !$0.hasUnreadableBound + }) { + held.insert(expected.keyId) + } + } + return held + } + + /// Whether `keys` shows every auth key the records in `waiting` hold by + /// the store (the ones they send again, and the ones they add that the + /// store places): a view that lacks one is behind, and cannot show those + /// keys off. + static func showsWaitingKeys( + _ waiting: [AppConnectGrant], + in keys: [ManagedIdentity.IdentityPublicKeyInfo], + bindings: [KeyBinding] + ) -> Bool { + let held = waiting.reduce(into: Set()) { ids, grant in + ids.formUnion(resentKeyIds(of: grant)) + ids.formUnion(grant.pendingUpdate?.addedKeys + .filter { $0.purpose == .authentication && isPlaced($0, in: bindings) }.map(\.keyId) ?? []) + } + return held.isSubset(of: keys.map { UInt32(bitPattern: $0.keyId) }) } /// The keys records waiting for their update hold: the ones they send @@ -1272,7 +1315,7 @@ extension AppConnect { /// keys it disables show off; one that landed and is off again is /// dropped, with those marked done the same way; one that cannot land is /// dropped; the rest stay as they are. A record that would be dropped - /// while it holds a live auth key (`liveAuthKeyIds(heldBy:in:bindings:)`) stays + /// while it may still hold an auth key (`heldKeyIds(heldBy:in:bindings:)`) stays /// waiting instead: it is what keeps the app's row and lets a disconnect /// turn that key off. A grant whose keys are still on stays live, and a /// disconnect turns them off. @@ -1300,7 +1343,7 @@ extension AppConnect { retired.formUnion(replaced) case .landedAndOff, .cannotLand: if outcome == .landedAndOff { retired.formUnion(replaced) } - if liveAuthKeyIds(heldBy: grant, in: currentIdentityPublicKeys, bindings: bindings).isEmpty { + if heldKeyIds(heldBy: grant, in: currentIdentityPublicKeys, bindings: bindings).isEmpty { dropped.append(grant) } case .unknown: diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 2bafad7347..37f2e59fb5 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -2111,11 +2111,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { throw error case .landedAndOff, .cannotLand: let didLand = outcome == .landedAndOff - // A record that holds a live auth key (one it sends - // again, or one it added) stays waiting: it keeps the - // app's row and lets a disconnect turn that key off. - guard AppConnect.liveAuthKeyIds(heldBy: record, in: view.keys, bindings: view.bindings).isEmpty else { - logger.info("🔗 DASHCONNECT :: the identity update will not complete, and its record holds a live key; it stays") + // A record that may still hold an auth key (one it sends + // again, or one it added, by the store or by this view) + // stays waiting: it keeps the app's row and lets a + // disconnect turn that key off. + guard AppConnect.heldKeyIds(heldBy: record, in: view.keys, bindings: view.bindings).isEmpty else { + logger.info("🔗 DASHCONNECT :: the identity update will not complete, and its record may hold a live key; it stays") if didLand { grants.save(landed(noting: false, retiring: disabled)) } throw error } @@ -3389,8 +3390,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // the row, once what was turned off above is marked. if let lateDisableFailure { throw lateDisableFailure } // A record of the app still waiting for its update keeps the row - // while it holds a live key, or while the identity could not be read - // again. One that holds none lets the row go and stays recorded: a + // while it may hold a live key, while the read after the update + // lacks a key the store gives it (`showsWaitingKeys`), or while the + // identity could not be read again. One that holds none lets the row go and stays recorded: a // disconnect only disables, which witnesses nothing // (`AppConnect.OwnUpdate`), and an update that never left the device // reads the same as one on its way. If it lands after all, a later @@ -3402,10 +3404,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // record adds that it cannot place may be the record's too. guard let keysAfterUpdate, let bindingsAfter = try? Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer), + AppConnect.showsWaitingKeys(stillWaiting, in: keysAfterUpdate, bindings: bindingsAfter), stillWaiting.allSatisfy({ - AppConnect.liveAuthKeyIds(heldBy: $0, in: keysAfterUpdate, bindings: bindingsAfter).isEmpty - }), - !AppConnect.hasUnplacedPendingKey(stillWaiting, currentIdentityPublicKeys: keysAfterUpdate, bindings: bindingsAfter) + AppConnect.heldKeyIds(heldBy: $0, in: keysAfterUpdate, bindings: bindingsAfter).isEmpty + }) else { Self.logger.error("🔗 DASHCONNECT :: an App Connect update of the app may still land") throw DashConnectPlatformError.registrationPending diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 1eab585a1a..5fda3743b6 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1530,16 +1530,34 @@ extension AppConnectV2LoginTests { let resentLive = Self.key(5, level: .critical) let taken = Self.onIdentity(added, data: Data(repeating: 0xEE, count: 20)) let placed = [Self.stored(added)] - XCTAssertEqual(AppConnect.liveAuthKeyIds(heldBy: record, in: [resentLive, taken], bindings: placed), [5]) - XCTAssertEqual(AppConnect.liveAuthKeyIds(heldBy: record, in: [Self.onIdentity(added)], bindings: placed), [8]) + XCTAssertEqual(AppConnect.heldKeyIds(heldBy: record, in: [resentLive, taken], bindings: placed), [5]) + XCTAssertEqual(AppConnect.heldKeyIds(heldBy: record, in: [Self.onIdentity(added)], bindings: placed), [8]) XCTAssertEqual( - AppConnect.liveAuthKeyIds(heldBy: record, in: [Self.onIdentity(added)], bindings: []), [], - "an added key the store does not place may be another request's") + AppConnect.heldKeyIds(heldBy: record, in: [Self.onIdentity(added)], bindings: []), [8], + "an added key live as added that the store cannot place yet: whose it is is not known") + var otherBound = Self.stored(added) + otherBound.bound = .singleContract(Self.appId) + XCTAssertEqual( + AppConnect.heldKeyIds(heldBy: record, in: [Self.onIdentity(added)], bindings: [otherBound]), [], + "the store reads it with another bound: another request's") + var otherBoundGrants = [record] + XCTAssertEqual( + AppConnect.settlePendingV2Registrations( + in: &otherBoundGrants, identityId: "identity", + currentIdentityPublicKeys: [Self.onIdentity(added)], bindings: [otherBound]).dropped.map(\.key), + [record.key]) XCTAssertEqual( - AppConnect.liveAuthKeyIds(heldBy: record, in: [taken, Self.key(5, disabled: true)], bindings: placed), [], + AppConnect.heldKeyIds(heldBy: record, in: [taken], bindings: [AppConnect.KeyBinding( + keyId: 5, data: Data([5]), singleContractId: nil)]), [5], + "a key it sends again that the view omits counts while the store holds it") + XCTAssertEqual( + AppConnect.heldKeyIds(heldBy: record, in: [taken], bindings: []), [], + "nor once nothing shows it") + XCTAssertEqual( + AppConnect.heldKeyIds(heldBy: record, in: [taken, Self.key(5, disabled: true)], bindings: placed), [], "another key under its id is not its own") XCTAssertEqual( - AppConnect.liveAuthKeyIds(heldBy: Self.grant(sessionKeyId: 5), in: [resentLive], bindings: []), [], + AppConnect.heldKeyIds(heldBy: Self.grant(sessionKeyId: 5), in: [resentLive], bindings: []), [], "only a waiting record") for (keys, why) in [ @@ -1562,6 +1580,66 @@ extension AppConnectV2LoginTests { XCTAssertEqual(settled.dropped.map(\.key), [record.key], "nothing of it is live any more") } + func testAWaitingRecordKeepsTheKeysTheStorePlacesEvenWhenAViewOmitsThem() { + // It adds A (7) and B (8); another key holds A's id, and the store + // already placed B, which this lagging view omits. + let keyA = Self.addedAuthKey(7, data: 0x07) + let keyB = Self.addedAuthKey(8, data: 0x08) + let record = Self.pendingGrant([keyA, keyB], requestHash: "a1") + let conflict = Self.onIdentity(keyA, data: Data(repeating: 0xEE, count: 20)) + XCTAssertEqual(AppConnect.heldKeyIds(heldBy: record, in: [conflict], bindings: [Self.stored(keyB)]), [8]) + var bOff = Self.stored(keyB) + bOff.isDisabled = true + XCTAssertEqual( + AppConnect.heldKeyIds(heldBy: record, in: [conflict], bindings: [bOff]), [], + "the store has it off") + + var grants = [record] + let settled = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: "identity", currentIdentityPublicKeys: [conflict], bindings: [Self.stored(keyB)]) + XCTAssertEqual(settled.dropped, [], "it cannot land, but the store gives it B") + XCTAssertTrue(grants[0].isPendingV2) + + // A matching key under A's id the store cannot place yet, with B's id + // held by another key: whose A is is not known, so the record stays. + let unplaced = [Self.onIdentity(keyA), Self.onIdentity(keyB, data: Data(repeating: 0xEE, count: 20))] + XCTAssertEqual(AppConnect.heldKeyIds(heldBy: record, in: unplaced, bindings: []), [7]) + var others = [record] + XCTAssertEqual( + AppConnect.settlePendingV2Registrations( + in: &others, identityId: "identity", currentIdentityPublicKeys: unplaced, bindings: []).dropped, []) + } + + func testAFailedUpdateKeepsARecordTheStoreGivesAKeyAViewOmits() async { + let keyA = Self.addedAuthKey(7, data: 0x07) + let keyB = Self.addedAuthKey(8, data: 0x08) + let record = Self.pendingGrant([keyA, keyB]) + let store = MemoryGrantStore() + let calls = Calls() + _ = try? await Self.register( + record, add: [keyA, keyB], store: store, calls: calls, submit: { throw UpdateFailed() }, + views: [([Self.onIdentity(keyA, data: Data(repeating: 0xEE, count: 20))], [Self.stored(keyB)])]) + XCTAssertEqual(store.grants.map(\.key), [record.key], "the store places B, which the view omits") + XCTAssertEqual(calls.dropped, 0) + } + + func testAViewThatLacksAKeyAWaitingRecordHoldsIsBehind() { + let keyB = Self.addedAuthKey(8, data: 0x08) + var record = Self.pendingGrant([keyB], requestHash: "a1") + record.additionalKeyIds = [5] + XCTAssertTrue(AppConnect.showsWaitingKeys( + [record], in: [Self.key(5), Self.onIdentity(keyB)], bindings: [Self.stored(keyB)])) + XCTAssertFalse( + AppConnect.showsWaitingKeys([record], in: [Self.key(5)], bindings: [Self.stored(keyB)]), + "the store places B and the view lacks it") + XCTAssertFalse( + AppConnect.showsWaitingKeys([record], in: [Self.onIdentity(keyB)], bindings: [Self.stored(keyB)]), + "it sends 5 again and the view lacks it") + XCTAssertTrue( + AppConnect.showsWaitingKeys([record], in: [Self.key(5)], bindings: []), + "an added key the store does not place is not required") + } + func testAPendingUpdateThatLandedAndIsOffAgainIsDroppedWithWhatItRetired() { let key = Self.addedAuthKey(7, data: 0x07) let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") From a69857ce794d34c2b13a54769045a5d37518ce59 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Sun, 1 Nov 2026 00:48:04 +0200 Subject: [PATCH 28/29] fix(dashconnect): a later own update settles nothing; a waiting record that holds a key gets a row back - `pendingV2Outcome` no longer takes a later update of this wallet as proof that a waiting one cannot land: the SDK's copy of the identity can be reloaded while an update is on its way. A waiting record settles only on its own keys, an id held by other data, or its encryption key under another id. `outlivedBy` is only decoded; nothing notes it. - A waiting record that holds a key a disconnect can turn off gets a confirming row when the app has none offering a disconnect; a two-QR row waiting for its second scan is remembered for the drop. - Another identity's waiting record holds the row only while the store shows it holding an auth key, so one whose update never left the device does not block that app's disconnects elsewhere for good; nor does it keep a disconnect from turning off the unattributed profile keys. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 5 +- .../DashConnect/AppConnectV2Login.swift | 56 ++--- .../PlatformDashConnectDataSource.swift | 193 ++++++++++++------ .../DashConnect/AppConnectV2LoginTests.swift | 136 ++++++------ 4 files changed, 199 insertions(+), 191 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index a0a3b73473..a714c03b5d 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -743,9 +743,8 @@ struct AppConnectGrant: Codable, Equatable { var disabledKeyIds: [UInt32] /// The records of those grants (`key`) that are done once it lands. var retiredGrantKeys: [String] - /// An update of this wallet to the identity that landed after this - /// one was submitted (`AppConnect.noteOwnUpdate`): this one cannot - /// land after it. + /// What an earlier build noted of a later update of this wallet. Read + /// back, never used: it proves nothing about this one (`OwnUpdate`). var outlivedBy: AppConnect.OwnUpdate? = nil /// The app's row was a two-QR `.approved` one before this approval /// showed it as confirming: it goes back to that if the update never diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 52809290d7..67e87327b9 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1166,16 +1166,14 @@ extension AppConnect { } } - /// What an update of this wallet to an identity did: the keys it added - /// and the ids it disabled. Only an added key witnesses the update: a - /// key is never removed and its id never taken again, while Platform - /// takes a disable of a key that is already off, so a view taken after - /// an earlier disable of the same id would show a disable-only update - /// too. An update that added nothing is not noted (`noteOwnUpdate`), and - /// one that did is shown by a view that shows all of it. - /// TODO(dashconnect-disable-witness): a disconnect only disables, so it - /// never settles a waiting record; the SDK's handle to the signed - /// transition (dashpay/platform#5690) would. + /// What an update of this wallet to an identity did, as an earlier build + /// noted it on a waiting record (`PendingV2Update.outlivedBy`). It is + /// only decoded, never used to settle: a later own update is no proof + /// that a waiting one cannot land, because the SDK's copy of the + /// identity can be reloaded while an update is on its way. + /// TODO(dashconnect-update-outcome): a waiting record settles only on + /// what the identity shows of its own keys; the SDK's handle to the + /// signed transition (dashpay/platform#5690) would settle the rest. struct OwnUpdate: Codable, Equatable { struct AddedKey: Codable, Equatable { let keyId: UInt32 @@ -1189,12 +1187,6 @@ extension AppConnect { addedKeys = added.map { AddedKey(keyId: $0.keyId, data: $0.pubkeyBytes) } self.disabledKeyIds = disabledKeyIds } - - func isShown(in keys: [ManagedIdentity.IdentityPublicKeyInfo]) -> Bool { - !addedKeys.isEmpty && addedKeys.allSatisfy { added in keys.contains { - UInt32(bitPattern: $0.keyId) == added.keyId && $0.data == added.data - } } && showsDisabled(disabledKeyIds, in: keys) - } } /// Whether `keys` shows every one of `keyIds`, disabled. @@ -1202,27 +1194,6 @@ extension AppConnect { keyIds.allSatisfy { id in keys.contains { UInt32(bitPattern: $0.keyId) == id && $0.disabledAt != nil } } } - /// Notes on every v2 record of `identityId` still waiting for its update - /// (except `exceptKey`'s, the update's own) that `update` landed after - /// it was submitted. An earlier note stays: it settles the same way. - static func noteOwnUpdate( - _ update: OwnUpdate, - in grants: inout [AppConnectGrant], - identityId: String, - exceptKey: String? = nil - ) { - // One that only disables witnesses nothing (`OwnUpdate`). - guard !update.addedKeys.isEmpty else { return } - for index in grants.indices - where grants[index].identityId == identityId && grants[index].key != exceptKey - && grants[index].pendingUpdate != nil - // A note an earlier build made of an update that added nothing - // witnesses nothing either, and gives way. - && grants[index].pendingUpdate?.outlivedBy?.addedKeys.isEmpty != false { - grants[index].pendingUpdate?.outlivedBy = update - } - } - /// What a view of the identity tells of a v2 update whose outcome was /// not known. enum PendingV2Outcome: Equatable { @@ -1254,12 +1225,10 @@ extension AppConnect { /// - Its encryption key (ECDSA_SECP256K1, unique on Platform) under /// another id: it can never land. HASH160 auth keys are not unique, /// so their data elsewhere says nothing. - /// - An update of this wallet that landed after it was submitted - /// (`outlivedBy`) and that `keys` shows: Platform takes an update only - /// at one above the identity's revision, and that update took one - /// above whatever the wallet's copy held, so `pending` cannot land - /// after it. A view that shows that update and none of its ids means - /// it never will. No revision is read: what the update did is. + /// + /// A later update of this wallet is no evidence: the SDK's copy of the + /// identity can be reloaded while an update is on its way, so a waiting + /// one may still land after it. /// /// Expiry ends nothing: Platform judges it by block time, which a view /// does not carry, and the device's clock is not that. @@ -1303,7 +1272,6 @@ extension AppConnect { } } if takenElsewhere { return .cannotLand } - if !anyPresent, pending.outlivedBy?.isShown(in: keys) == true { return .cannotLand } // Its keys there, unplaced, may be a landed update still to settle. return .unknown } diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 37f2e59fb5..bb355241ea 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1895,9 +1895,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { addedKeys: add.map(AppConnect.ExpectedKey.init), disabledKeyIds: disable, retiredGrantKeys: retiredGrantKeys.sorted(), - // The submission about to be sent is built past any update - // noted on the earlier one, and can land after it. - outlivedBy: nil, replacesApprovedRow: previousRow?.status == .approved || (previousRow?.status == .confirming && stores.grants.load().contains { $0.appContractId == appId && $0.pendingUpdate?.replacesApprovedRow == true @@ -1964,10 +1961,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } catch { publishFailure = error } - // Every record of this identity still waiting for its update was - // written before this one landed, and has it noted: a view that - // shows this update settles them (`AppConnect.pendingV2Outcome`). A - // previous grant of this connection that turned out to have landed + // One more read settles the identity's records still waiting for + // their update by what it shows of their keys. A previous grant of this connection that turned out to have landed // holds keys this login replaces: they are turned off too. This runs // after this request's own response is out, the app is waiting for // it, and whether or not that publish went through. @@ -1996,11 +1991,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// update: a renewal that left some of the replaced keys on would report /// a replacement that did not happen. A disconnect takes them in batches. /// - /// On success the record is confirmed, the grants in `retiredGrantKeys` - /// are marked done, and the update is noted on the identity's other - /// records still waiting for theirs (`AppConnect.noteOwnUpdate`); a - /// landing found after a failure is not noted, as it may be an earlier - /// submission's. A failure may still have landed: + /// On success the record is confirmed and the grants in + /// `retiredGrantKeys` are marked done. A failure may still have landed: /// up to three reads (`reread`, `pause` before the second and third) /// settle it by `AppConnect.pendingV2Outcome`. Landed confirms as on /// success when the keys it disables show off; with any of them still @@ -2048,25 +2040,15 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } await showRow() - // Once this submission returned success, every other record of the - // identity still waiting for its own cannot land after it. Keys - // found after a failure may be an earlier submission's of the same - // grant, which proves nothing about the others, so that is not - // noted. - func landed(noting: Bool, retiring: Bool = true) -> [AppConnectGrant] { + func landed(retiring: Bool = true) -> [AppConnectGrant] { var all = grants.load() - if noting, !add.isEmpty { - AppConnect.noteOwnUpdate( - AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), in: &all, - identityId: record.identityId, exceptKey: record.key) - } if retiring { AppConnect.markKeysDisabled(in: &all) { retiredGrantKeys.contains($0.key) && !$0.isUnconfirmed } } return all } - func confirm(noting: Bool = false, retiring: Bool = true) -> AppConnectGrant { - var all = landed(noting: noting, retiring: retiring) + func confirm(retiring: Bool = true) -> AppConnectGrant { + var all = landed(retiring: retiring) guard let index = all.firstIndex(where: { $0.key == record.key }) else { return record } all[index].pendingUpdate = nil all[index].unconfirmedKeyHash160 = nil @@ -2117,12 +2099,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // disconnect turn that key off. guard AppConnect.heldKeyIds(heldBy: record, in: view.keys, bindings: view.bindings).isEmpty else { logger.info("🔗 DASHCONNECT :: the identity update will not complete, and its record may hold a live key; it stays") - if didLand { grants.save(landed(noting: false, retiring: disabled)) } + if didLand { grants.save(landed(retiring: disabled)) } throw error } let what = didLand ? "landed, and its keys are off already" : "can no longer land" logger.info("🔗 DASHCONNECT :: the identity update \(what, privacy: .public); its record is dropped") - var all = didLand ? landed(noting: false, retiring: disabled) : grants.load() + var all = didLand ? landed(retiring: disabled) : grants.load() all.removeAll { $0.key == record.key } // Dropped only once its rows can be judged; otherwise the // next settle drops it. @@ -2136,7 +2118,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { throw error } logger.info("🔗 DASHCONNECT :: identity updated") - return confirm(noting: true) + return confirm() } /// This identity's response to one request, with the values it has on @@ -2487,9 +2469,83 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.rowsAfterConfirming(appIds: appIds, in: rows, at: confirmedAt) } } + // A record still waiting that holds a key of the app needs a row to + // disconnect it, whether or not its whole update can be confirmed. + let waitingAppIds = readBindings.map { readBindings in + Self.appIdsWithoutTheirConfirmingRow( + grants: stores.grants.load(), identityId: identityId, + currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: readBindings, + rows: rows(in: stores)) + } ?? [] + if !waitingAppIds.isEmpty { + Self.logger.info("🔗 DASHCONNECT :: \(waitingAppIds.count, privacy: .public) app(s) with a key held by a waiting update get their row back") + let shownAt = now() + // A two-QR row waiting for its second scan comes back when the + // records that held its place are dropped (`replacesApprovedRow`). + let replacingApproved = Set(rows(in: stores).filter { + waitingAppIds.contains($0.id) && $0.status == .approved + }.map(\.id)) + if !replacingApproved.isEmpty { + updateGrants(in: stores) { grants in + for index in grants.indices + where grants[index].identityId == identityId && grants[index].isPendingV2 + && replacingApproved.contains(grants[index].appContractId) { + grants[index].pendingUpdate?.replacesApprovedRow = true + } + } + } + await updateRows(in: stores) { rows in + Self.rowsAfterHolding(appIds: waitingAppIds, in: rows, at: shownAt) + } + } return confirmedV2 } + /// The apps of `identityId` whose v2 record waiting for its update holds + /// a key a disconnect can turn off (`AppConnect.heldKeyIds` within + /// `AppConnect.waitingKeyIds`) and that have no row offering a + /// disconnect: none, or only a two-QR row waiting for its second scan. + static func appIdsWithoutTheirConfirmingRow( + grants: [AppConnectGrant], + identityId: String, + currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], + bindings: [AppConnect.KeyBinding], + rows: [DAppConnection] + ) -> Set { + // Only the keys a disconnect can turn off (`waitingKeyIds`): a row + // for a key the store cannot place yet would offer a disconnect that + // cannot end. + let holding = grants.filter { + $0.identityId == identityId && $0.isPendingV2 + && !AppConnect.heldKeyIds(heldBy: $0, in: currentIdentityPublicKeys, bindings: bindings) + .intersection(AppConnect.waitingKeyIds([$0], bindings: bindings)).isEmpty + } + return Set(holding.map(\.appContractId)).filter { appId in + !rows.contains { $0.id == appId && ($0.status == .active || $0.status == .confirming) } + } + } + + /// `rows` once the apps in `appIds` hold a key through a waiting record: + /// each app's row reads confirming, which offers a disconnect, and an + /// app with no row gets one. + static func rowsAfterHolding(appIds: Set, in rows: [DAppConnection], at shownAt: Date) -> [DAppConnection] { + let reconciled = rows.map { connection in + // A row that offers a disconnect already (written meanwhile) stays. + guard appIds.contains(connection.id), connection.status != .active, connection.status != .confirming + else { return connection } + return connection.withStatus(.confirming, loginKind: .oneQR, at: shownAt) + } + let missing = appIds.subtracting(rows.map(\.id)) + return reconciled + missing.sorted().map { appId in + let branding = DashConnectFallbackAppMetadata.resolve(contractId: appId, unauthenticatedLabel: "") + return DAppConnection( + id: appId, + name: branding.name.isEmpty ? NSLocalizedString("Unknown app", comment: "DashConnect") : branding.name, + url: branding.url, + status: .confirming, updatedAt: shownAt, loginKind: .oneQR) + } + } + /// Writes the rows of the apps whose v2 records in `dropped` were /// dropped (`rowsAfterDropping`), judged by `grants` (the records left) /// and `bindings`, the store's keys of the identity those records were @@ -2549,8 +2605,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// After an update of this wallet to the identity landed: one more read /// of the identity, which also writes what it shows to the store, and /// the v2 records of the identity waiting for their outcome are settled - /// by it (by that update only when its submission returned success and - /// it was noted, `AppConnect.noteOwnUpdate`). Returns the v2 grants + /// by what it shows of their keys. Returns the v2 grants /// confirmed and the keys read, or nil when the read failed. private func settleAfterOwnUpdate( context: Context, @@ -2997,25 +3052,43 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// as the error to show, or `nil` when no identity but `identityId` has /// part in it. A live key there (`heldOnAnotherIdentity` covers the keys /// no record names) comes first; a registration there that may still - /// land, one with a noted revision or a v2 update whose outcome is not - /// known, is settled only by a read of that identity, once it is the - /// active one. + /// land, one with a noted revision, or a v2 update whose outcome is not + /// known and that holds a key there (`waitingHoldsKeys`), is settled + /// only by a read of that identity, once it is the active one. A v2 + /// record that holds none, such as one whose update never left the + /// device, does not hold the row: nothing may settle it. static func reasonHeldElsewhere( grants: [AppConnectGrant], appContractId: String, identityId: String, - heldOnAnotherIdentity: Bool + heldOnAnotherIdentity: Bool, + waitingHoldsKeys: (AppConnectGrant) -> Bool = { _ in true } ) -> DashConnectPlatformError? { let elsewhere = grants.filter { $0.appContractId == appContractId && $0.identityId != identityId } if heldOnAnotherIdentity || elsewhere.contains(where: { !$0.isUnconfirmed && $0.keyDisabled != true }) { return .grantOnAnotherIdentity } - if elsewhere.contains(where: { $0.isUnconfirmed && ($0.submittedRevision != nil || $0.isPendingV2) }) { + if elsewhere.contains(where: { + $0.isUnconfirmed && ($0.isPendingV2 ? waitingHoldsKeys($0) : $0.submittedRevision != nil) + }) { return .registrationPendingOnAnotherIdentity } return nil } + /// Whether the wallet's store shows `grant` (a v2 record waiting for its + /// update, of an identity that is not the active one) holding a key: + /// an auth key it sends again, or one it adds that the store places, + /// not off. + /// A store that cannot be read counts as holding. + static func waitingRecordHoldsStoredKeys(_ grant: AppConnectGrant, modelContainer: ModelContainer) -> Bool { + guard let bindings = try? storedKeyBindings(identityId: grant.identityId, modelContainer: modelContainer), + !bindings.isEmpty else { return true } + // Auth keys only: the app's encryption key is never turned off. + let liveAuth = Set(bindings.filter { !$0.isDisabled && ($0.isV2AuthKeyShaped || $0.isSessionKeyShaped) }.map(\.keyId)) + return !AppConnect.waitingKeyIds([grant], bindings: bindings).intersection(liveAuth).isEmpty + } + /// Ends the access one-QR logins gave an app: disables its session keys /// on the identity, then deletes the responses that carried them. /// @@ -3091,7 +3164,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { func reasonHeldElsewhere(heldOnAnotherIdentity: Bool = false) -> DashConnectPlatformError? { Self.reasonHeldElsewhere( grants: stores.grants.load(), appContractId: appContractId, identityId: identityId, - heldOnAnotherIdentity: heldOnAnotherIdentity) + heldOnAnotherIdentity: heldOnAnotherIdentity, + waitingHoldsKeys: { Self.waitingRecordHoldsStoredKeys($0, modelContainer: context.modelContainer) }) } guard let appContract = Self.decodeIdentifier(appContractId) else { throw DashConnectPlatformError.loginContractUnavailable @@ -3288,11 +3362,15 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // is not taken for an unattributed one. A dropped record names // nothing, and the profile key it sent again goes here like any // other. - // A disconnect with one of the app's records waiting can still end in - // `registrationPending` after its update (a key turned up, or the - // identity could not be read again), so it is not one that ends here. + // A record of the app still waiting that holds a key this update does + // not turn off keeps the disconnect from ending here; one that holds + // none (an update that never left the device) does not, since nothing + // may ever settle it. + let waitingHoldsOtherKeys = stores.grants.load().filter { pendingV2.contains($0.key) }.contains { + !AppConnect.heldKeyIds(heldBy: $0, in: currentPublicKeys, bindings: bindings).subtracting(keyIds).isEmpty + } let completesHere = (!keyIds.isEmpty || !granted.isEmpty) && heldOnAnotherIdentity == false - && reasonHeldElsewhere(heldOnAnotherIdentity: false) == nil && pendingV2.isEmpty + && reasonHeldElsewhere(heldOnAnotherIdentity: false) == nil && !waitingHoldsOtherKeys var profileKeysOff: [UInt32] = [] var profileKeysUnchecked = false if completesHere { @@ -3345,9 +3423,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { updateGrants(in: stores) { grants in grants.removeAll { mayStillLand.contains($0.key) } } } // The reload writes the disabled keys to the store, and settles - // the v2 records still waiting for their update: this - // disconnect's update landed after them. One of the app's that - // turns out to have landed holds keys that are turned off too. + // the v2 records still waiting for their update by what it shows + // of their keys. One of the app's that turns out to have landed + // holds keys that are turned off too. // The keys above are off either way. if let settled = await settleAfterOwnUpdate(context: context, stores: stores) { keysAfterUpdate = settled.keys @@ -3392,10 +3470,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // A record of the app still waiting for its update keeps the row // while it may hold a live key, while the read after the update // lacks a key the store gives it (`showsWaitingKeys`), or while the - // identity could not be read again. One that holds none lets the row go and stays recorded: a - // disconnect only disables, which witnesses nothing - // (`AppConnect.OwnUpdate`), and an update that never left the device - // reads the same as one on its way. If it lands after all, a later + // identity could not be read again. One that holds none lets the row + // go and stays recorded: an update that never left the device reads + // the same as one on its way. If it lands after all, a later // settle confirms it and shows the app again // (`appIdsWithoutTheirOneQRRow`), to be disconnected then. let stillWaiting = stores.grants.load().filter { pendingV2.contains($0.key) && $0.isPendingV2 } @@ -3434,9 +3511,7 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } } - /// Every identity update DashConnect sends outside a v2 approval (which - /// notes its own, `registerAppConnectV2Grant`): on success it is noted on - /// the v2 records still waiting for theirs (`noteOwnUpdateLanded`). + /// An identity update DashConnect sends outside a v2 approval. private func updateIdentity( add: [ManagedPlatformWallet.IdentityPubkey] = [], disable: [UInt32] = [], @@ -3445,24 +3520,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { ) async throws { try await context.wallet.updateIdentity( identityId: context.identityId, addPublicKeys: add, disablePublicKeyIds: disable, signer: signer) - noteOwnUpdateLanded(AppConnect.OwnUpdate(added: add, disabledKeyIds: disable), context: context) - } - - /// An update of this wallet to the identity returned success: every v2 - /// record of the identity still waiting for its own update cannot land - /// after it, which a later view that shows `update` settles - /// (`AppConnect.pendingV2Outcome`). The v2 approval notes its own update - /// in `registerAppConnectV2Grant`, leaving its own record out. - private func noteOwnUpdateLanded(_ update: AppConnect.OwnUpdate, context: Context) { - // One that only disables witnesses nothing (`AppConnect.OwnUpdate`). - guard !update.addedKeys.isEmpty else { return } - let identityId = context.identityId.toBase58String() - guard context.stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) else { - return - } - updateGrants(in: context.stores) { grants in - AppConnect.noteOwnUpdate(update, in: &grants, identityId: identityId) - } } /// Turns off the keys of `grants` that `keys` (a fresh view) shows live: diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index 5fda3743b6..fc1ddc9623 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1351,61 +1351,21 @@ extension AppConnectV2LoginTests { "a HASH160 payload is not unique, so it says nothing") } - func testAnUpdateOfOursThatLandedLaterSettlesAPendingOneOnceAViewShowsIt() { + func testALaterUpdateOfOursLeavesAPendingOneUnknown() { let auth = Self.addedAuthKey(7, data: 0x07) let master = Self.key(0, level: .master) let laterKey = Self.addedAuthKey(11, data: 0x0B) let later = AppConnect.OwnUpdate(added: [laterKey], disabledKeyIds: [3]) - let showsLater = Self.key(3, disabled: true) - XCTAssertEqual( - Self.outcome([auth], keys: [master, showsLater, Self.onIdentity(laterKey)], outlivedBy: later), .cannotLand) - // Key 3 turned off once before this update, which then lands, and - // turned off again by a later disconnect: a view from between the - // two disables shows the second one too, without this update's key. - XCTAssertEqual( - Self.outcome([auth], keys: [master, showsLater], outlivedBy: AppConnect.OwnUpdate(disabledKeyIds: [3])), - .unknown, "a disable can be sent again for a key already off, so it witnesses nothing") - XCTAssertEqual( - Self.outcome([auth], keys: [master, Self.key(3)], outlivedBy: later), .unknown, - "a view that does not show the later update is behind it") - XCTAssertEqual(Self.outcome([auth], keys: [master, showsLater]), .unknown, "without one it may still land") - XCTAssertEqual( - Self.outcome([auth], keys: [master, showsLater, Self.onIdentity(laterKey), Self.onIdentity(auth)], - outlivedBy: later), .landed) - XCTAssertEqual( - Self.outcome([auth], keys: [showsLater, Self.onIdentity(laterKey), Self.onIdentity(auth)], bindings: [], - outlivedBy: later), .unknown, - "its key is there; the store just cannot place it") - let added = Self.addedAuthKey(9, data: 0x09) - XCTAssertEqual( - Self.outcome([auth], keys: [master, Self.onIdentity(added)], - outlivedBy: AppConnect.OwnUpdate(added: [added])), - .cannotLand, "a later update that added a key is shown by that key") - } - - func testAnUpdateOfOursIsNotedOnEveryRecordWaitingButItsOwn() { - let own = Self.pendingGrant([Self.addedAuthKey(7, data: 0x07)], requestHash: "a1") - let earlier = Self.pendingGrant([Self.addedAuthKey(9, data: 0x09)], requestHash: "a2") - var noted = Self.pendingGrant([Self.addedAuthKey(11, data: 0x0B)], requestHash: "a3") - let first = AppConnect.OwnUpdate(added: [Self.addedAuthKey(21, data: 0x15)], disabledKeyIds: [1]) - noted.pendingUpdate?.outlivedBy = first - let other = Self.pendingGrant([Self.addedAuthKey(13, data: 0x0D)], identityId: "other", requestHash: "a4") - var grants = [own, earlier, noted, other, Self.grant(sessionKeyId: 3)] - let update = AppConnect.OwnUpdate(added: [Self.addedAuthKey(22, data: 0x16)], disabledKeyIds: [2]) - var disableOnly = grants - AppConnect.noteOwnUpdate( - AppConnect.OwnUpdate(disabledKeyIds: [2]), in: &disableOnly, identityId: "identity", exceptKey: own.key) - XCTAssertNil(disableOnly[1].pendingUpdate?.outlivedBy, "an update that only disables witnesses nothing") - var olderNote = grants - olderNote[1].pendingUpdate?.outlivedBy = AppConnect.OwnUpdate(disabledKeyIds: [4]) - AppConnect.noteOwnUpdate(update, in: &olderNote, identityId: "identity", exceptKey: own.key) - XCTAssertEqual(olderNote[1].pendingUpdate?.outlivedBy, update, "a note of a disable-only update gives way") - AppConnect.noteOwnUpdate(update, in: &grants, identityId: "identity", exceptKey: own.key) - XCTAssertNil(grants[0].pendingUpdate?.outlivedBy, "an update does not outlive itself") - XCTAssertEqual(grants[1].pendingUpdate?.outlivedBy, update) - XCTAssertEqual(grants[2].pendingUpdate?.outlivedBy, first, "an earlier note settles the same way") - XCTAssertNil(grants[3].pendingUpdate?.outlivedBy, "another identity's update") - XCTAssertNil(grants[4].pendingUpdate) + // A note an earlier build made: the SDK's copy of the identity can + // be reloaded while an update is on its way, so the pending one can + // still land after the later one. + XCTAssertEqual( + Self.outcome([auth], keys: [master, Self.key(3, disabled: true), Self.onIdentity(laterKey)], outlivedBy: later), + .unknown) + XCTAssertEqual( + Self.outcome([auth], keys: [master, Self.key(3, disabled: true), Self.onIdentity(laterKey), Self.onIdentity(auth)], + outlivedBy: later), + .landed, "its own key settles it") } func testAPendingUpdateWhoseKeyLimitsWereRaisedSinceLanded() { @@ -1610,6 +1570,50 @@ extension AppConnectV2LoginTests { in: &others, identityId: "identity", currentIdentityPublicKeys: unplaced, bindings: []).dropped, []) } + func testAWaitingRecordThatHoldsAKeyGetsARowToDisconnectIt() { + // It adds profile key A (7) and B (8); only A is on the identity and + // in the store, and the app has no row (a disconnect let it go). + let keyA = ManagedPlatformWallet.IdentityPubkey( + keyId: 7, keyType: .ecdsaHash160, purpose: .authentication, securityLevel: .high, + pubkeyBytes: Data(repeating: 0x07, count: 20), + contractBounds: .singleContractDocumentType(id: Self.dashpayContractId, documentTypeName: "profile"), + totalBudget: 1_000_000_000, expiresAt: Self.expiresAt) + let keyB = Self.addedAuthKey(8, data: 0x08) + let record = Self.pendingGrant([keyA, keyB], appId: Self.appId.toBase58String(), requestHash: "a1") + let keys = [Self.onIdentity(keyA)] + let bindings = [Self.stored(keyA)] + let app = Self.appId.toBase58String() + let appIds = PlatformDashConnectDataSource.appIdsWithoutTheirConfirmingRow( + grants: [record], identityId: "identity", currentIdentityPublicKeys: keys, bindings: bindings, rows: []) + XCTAssertEqual(appIds, [app]) + let rows = PlatformDashConnectDataSource.rowsAfterHolding( + appIds: appIds, in: [], at: Date(timeIntervalSince1970: 2_000)) + XCTAssertEqual(rows.map(\.id), [app]) + XCTAssertEqual(rows.map(\.status), [.confirming], "a confirming row offers the disconnect") + + let row = DAppConnection(id: app, name: "Yappr", url: "yap.pr", status: .confirming, + updatedAt: Date(timeIntervalSince1970: 1_000), loginKind: .oneQR) + XCTAssertEqual( + PlatformDashConnectDataSource.appIdsWithoutTheirConfirmingRow( + grants: [record], identityId: "identity", currentIdentityPublicKeys: keys, bindings: bindings, + rows: [row]), + [], "a row that offers a disconnect is left as it is") + XCTAssertEqual( + PlatformDashConnectDataSource.appIdsWithoutTheirConfirmingRow( + grants: [record], identityId: "identity", currentIdentityPublicKeys: [], bindings: [], rows: []), + [], "a record that holds nothing needs no row") + XCTAssertEqual( + PlatformDashConnectDataSource.appIdsWithoutTheirConfirmingRow( + grants: [record], identityId: "identity", currentIdentityPublicKeys: keys, bindings: [], rows: []), + [], "a key the store cannot place yet could not be turned off from that row") + let active = DAppConnection(id: app, name: "Yappr", url: "yap.pr", status: .active, + updatedAt: Date(timeIntervalSince1970: 1_000), loginKind: .oneQR) + XCTAssertEqual( + PlatformDashConnectDataSource.rowsAfterHolding( + appIds: [app], in: [active], at: Date(timeIntervalSince1970: 2_000)).map(\.status), + [.active], "a row written meanwhile that offers a disconnect stays") + } + func testAFailedUpdateKeepsARecordTheStoreGivesAKeyAViewOmits() async { let keyA = Self.addedAuthKey(7, data: 0x07) let keyB = Self.addedAuthKey(8, data: 0x08) @@ -1745,6 +1749,11 @@ extension AppConnectV2LoginTests { PlatformDashConnectDataSource.reasonHeldElsewhere( grants: grants, appContractId: "app", identityId: "identity", heldOnAnotherIdentity: false), .registrationPendingOnAnotherIdentity) + XCTAssertNil( + PlatformDashConnectDataSource.reasonHeldElsewhere( + grants: grants, appContractId: "app", identityId: "identity", heldOnAnotherIdentity: false, + waitingHoldsKeys: { _ in false }), + "one that holds no key there, such as an update that never left the device, does not hold the row") } func testALoginCleansUpOnlyResponsesThatWereAttempted() { @@ -1921,31 +1930,6 @@ extension AppConnectV2LoginTests { XCTAssertEqual(store.grants.first { $0.key == old.key }?.keyDisabled, true) } - func testOnlyAnUpdateThatReturnedSuccessIsNotedOnTheOtherRecordsWaiting() async throws { - let waiting = Self.pendingGrant([Self.addedAuthKey(9, data: 0x09)], requestHash: "a9") - let key = Self.addedAuthKey(7, data: 0x07) - let succeeded = MemoryGrantStore([waiting]) - _ = try await Self.register(Self.pendingGrant([key]), add: [key], disable: [3], store: succeeded, calls: Calls()) - XCTAssertEqual( - succeeded.grants.first { $0.key == waiting.key }?.pendingUpdate?.outlivedBy, - AppConnect.OwnUpdate(added: [key], disabledKeyIds: [3])) - - let landedAnyway = MemoryGrantStore([waiting]) - _ = try await Self.register( - Self.pendingGrant([key]), add: [key], store: landedAnyway, calls: Calls(), submit: { throw UpdateFailed() }, - views: [([Self.onIdentity(key)], [Self.stored(key)])]) - XCTAssertNil( - landedAnyway.grants.first { $0.key == waiting.key }?.pendingUpdate?.outlivedBy, - "keys found after a failure may be an earlier submission's") - - let unknown = MemoryGrantStore([waiting]) - _ = try? await Self.register( - Self.pendingGrant([key]), add: [key], store: unknown, calls: Calls(), submit: { throw UpdateFailed() }) - XCTAssertNil( - unknown.grants.first { $0.key == waiting.key }?.pendingUpdate?.outlivedBy, - "an update whose outcome is not known proves nothing") - } - func testARenewalThatReusesItsKeysStillRetiresTheGrantsItReplaced() async throws { var earlier = Self.grant(sessionKeyId: 7, requestHash: "aa", connectionId: "c1") earlier.documentId = "doc" From be313b27c69f2faf70cb0c94cdf9c396aa3881ca Mon Sep 17 00:00:00 2001 From: romchornyi Date: Mon, 2 Nov 2026 23:40:16 +0200 Subject: [PATCH 29/29] fix(dashconnect): settle a waiting App Connect v2 update by the revision it was submitted at An identity update notes the revision it is submitted at (read before the submit, raised after a failed one; a retry never lowers it), for v1 session key registrations and v2 updates alike. A waiting v2 update whose key is absent from an identity at that revision or past it can no longer land, and its record is settled instead of lingering. Platform applies an identity update only at one above the identity's revision, so an earlier waiting update cannot land after a later update of this wallet did: the renewal and the disconnect no longer turn keys off after their own update. A waiting update the read after the update shows landed keeps the disconnect's row, and is logged after a renewal. Co-Authored-By: Claude Opus 5.5 --- .../Models/DashConnect/AppConnectLogin.swift | 60 +++- .../DashConnect/AppConnectV2Login.swift | 59 +++- .../PlatformDashConnectDataSource.swift | 287 ++++++++++-------- .../DashConnect/AppConnectV2LoginTests.swift | 197 ++++++++++-- .../PlatformDashConnectDataSourceTests.swift | 55 ++++ 5 files changed, 500 insertions(+), 158 deletions(-) diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index a714c03b5d..fab7dd6219 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift @@ -506,6 +506,52 @@ enum AppConnect { return confirmed } + /// The identity revision a registration's update is submitted at, noted + /// on its record before it is submitted. The SDK builds an update at one + /// above the revision the wallet holds for the identity, and Platform + /// applies it only at one above the identity's revision, so once the + /// identity is at this revision or past it without the update's keys, + /// the update can never land. + struct SubmittedRevision { + /// The revision the wallet held for the identity before the update + /// was built. + let held: UInt64 + /// The revision noted for an earlier submission of the same keys + /// under the same ids, which may still land at it: the record stands + /// for that one too. + var earlier: UInt64? = nil + + /// One above `held`, or `earlier` where that is higher: a read from + /// a node that is behind never lowers it. Nil at the largest + /// revision, which no update follows, with nothing noted earlier. + var value: UInt64? { + let own = held == .max ? nil : held + 1 + guard let earlier else { return own } + return max(own ?? earlier, earlier) + } + + /// Runs `submit`. When it throws, the wallet's revision is read + /// again (`readHeld`): if another update of the identity landed + /// meanwhile and moved it so that this one may have been built above + /// `value`, `raise` gets one above it before the error is rethrown. + /// The record then names the highest, which only makes a settle wait + /// longer for the outcome. + func submit( + _ submit: () async throws -> Void, + readHeld: () throws -> UInt64, + raise: (UInt64) -> Void + ) async throws { + do { + try await submit() + } catch { + if let after = try? readHeld(), after < .max, after + 1 > (value ?? .max) { + raise(after + 1) + } + throw error + } + } + } + /// Granted session keys the given view of the identity does not contain. /// Platform never removes a key, it only disables it, so a missing id /// means the view is out of date — not that the key is gone. A disconnect @@ -719,7 +765,9 @@ struct AppConnectGrant: Codable, Equatable { /// set with `unconfirmedKeyHash160`. Platform takes an identity update /// only at one above the identity's revision, so once the identity is at /// this revision or past it without the key live, the update can never - /// land. + /// land. Noted for a session-key registration without `pendingUpdate`; + /// an App Connect v2 update notes its own + /// (`PendingV2Update.submittedRevision`) and leaves this `nil`. /// `nil` on a record from a build that did not note it. var submittedRevision: UInt64? = nil /// App Connect v2: the update that registers this grant's keys, from @@ -743,8 +791,16 @@ struct AppConnectGrant: Codable, Equatable { var disabledKeyIds: [UInt32] /// The records of those grants (`key`) that are done once it lands. var retiredGrantKeys: [String] + /// The identity revision the update was submitted at + /// (`AppConnect.SubmittedRevision`), set before it is submitted. + /// Kept with the update it was noted for. A retry sends the same + /// keys under the same ids and keeps the higher of its own and the + /// one noted before (`SubmittedRevision.earlier`). `nil` on a record + /// from a build that did not note it. + var submittedRevision: UInt64? = nil /// What an earlier build noted of a later update of this wallet. Read - /// back, never used: it proves nothing about this one (`OwnUpdate`). + /// back, never used: the update's own `submittedRevision` is what + /// settles it against the identity's revision (`OwnUpdate`). var outlivedBy: AppConnect.OwnUpdate? = nil /// The app's row was a two-QR `.approved` one before this approval /// showed it as confirming: it goes back to that if the update never diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index 67e87327b9..94ca93a100 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -1168,12 +1168,15 @@ extension AppConnect { /// What an update of this wallet to an identity did, as an earlier build /// noted it on a waiting record (`PendingV2Update.outlivedBy`). It is - /// only decoded, never used to settle: a later own update is no proof - /// that a waiting one cannot land, because the SDK's copy of the - /// identity can be reloaded while an update is on its way. - /// TODO(dashconnect-update-outcome): a waiting record settles only on - /// what the identity shows of its own keys; the SDK's handle to the - /// signed transition (dashpay/platform#5690) would settle the rest. + /// only decoded, never used to settle: a waiting record is settled by + /// what the identity shows of its own keys and by the revision its own + /// update was submitted at (`PendingV2Update.submittedRevision`). + /// TODO(dashconnect-update-outcome): that revision is read from the + /// wallet's copy of the identity around the submit, not taken from the + /// signed transition: a reload of that copy elsewhere between the read + /// and the build would sign above a higher revision than the one noted. + /// The SDK returning the revision it signed (dashpay/platform#5690) would + /// make it exact. struct OwnUpdate: Codable, Equatable { struct AddedKey: Codable, Equatable { let keyId: UInt32 @@ -1208,9 +1211,23 @@ extension AppConnect { case unknown } - /// The outcome of `pending` by what `keys` (a fresh view of the - /// identity) and `bindings` (the store's bounds) show. No revision is - /// guessed: the SDK does not say which revision it signed. + /// Whether a record of `waiting` (keys of records that were waiting for + /// their update) is now confirmed with a key `keys` shows live: its + /// update landed after all. + static func landedWithLiveKeys( + _ grants: [AppConnectGrant], + among waiting: Set, + in keys: [ManagedIdentity.IdentityPublicKeyInfo] + ) -> Bool { + let live = Set(keys.filter { $0.disabledAt == nil }.map { UInt32(bitPattern: $0.keyId) }) + return grants.contains { grant in + waiting.contains(grant.key) && !grant.isPendingV2 && !grant.isUnconfirmed + && grant.keyIds.contains(where: live.contains) + } + } + + /// The outcome of `pending` by what `keys` and `identityRevision` (a + /// fresh view of the identity) and `bindings` (the store's bounds) show. /// /// - Every added key there as it was added (its limits raised at /// most), or turned off since: it landed (`landedAndOff` when every @@ -1225,10 +1242,17 @@ extension AppConnect { /// - Its encryption key (ECDSA_SECP256K1, unique on Platform) under /// another id: it can never land. HASH160 auth keys are not unique, /// so their data elsewhere says nothing. + /// - A key it adds absent, with the identity at the revision the update + /// was submitted at or past it (`submittedRevision`): Platform applies + /// an identity update only at one above the identity's revision, and + /// never removes a key, so it can never land. An update whose keys + /// are all there, placed or not, is judged as above, whatever the + /// revision. /// - /// A later update of this wallet is no evidence: the SDK's copy of the - /// identity can be reloaded while an update is on its way, so a waiting - /// one may still land after it. + /// TODO(dashconnect-unconfirmed-row): a record that does not note its + /// revision (from a build before `PendingV2Update.submittedRevision`) + /// with a key absent stays unknown: only its keys turning up, or another + /// key under its ids, settles it. /// /// Expiry ends nothing: Platform judges it by block time, which a view /// does not carry, and the device's clock is not that. @@ -1238,14 +1262,17 @@ extension AppConnect { static func pendingV2Outcome( of pending: AppConnectGrant.PendingV2Update, currentIdentityPublicKeys keys: [ManagedIdentity.IdentityPublicKeyInfo], + identityRevision: UInt64, bindings: [KeyBinding] ) -> PendingV2Outcome { var allLanded = true var anyPresent = false + var anyAbsent = false var offAuthCount = 0 for expected in pending.addedKeys { guard let key = keys.first(where: { UInt32(bitPattern: $0.keyId) == expected.keyId }) else { allLanded = false + anyAbsent = true continue } anyPresent = true @@ -1272,12 +1299,14 @@ extension AppConnect { } } if takenElsewhere { return .cannotLand } + if anyAbsent, let submitted = pending.submittedRevision, identityRevision >= submitted { return .cannotLand } // Its keys there, unplaced, may be a landed update still to settle. return .unknown } /// Settles the v2 records of `identityId` whose update's outcome was not - /// known, by `pendingV2Outcome`. A landed one becomes a grant like any + /// known, by `pendingV2Outcome` over `currentIdentityPublicKeys` and + /// `identityRevision`, read together. A landed one becomes a grant like any /// other (its response is not published: its approval stopped waiting), /// and the earlier grants its update retired are marked done once the /// keys it disables show off; one that landed and is off again is @@ -1291,6 +1320,7 @@ extension AppConnect { in grants: inout [AppConnectGrant], identityId: String, currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], + identityRevision: UInt64, bindings: [KeyBinding] ) -> (confirmed: [AppConnectGrant], dropped: [AppConnectGrant]) { var confirmed: [AppConnectGrant] = [] @@ -1301,7 +1331,8 @@ extension AppConnect { let replaced = showsDisabled(pending.disabledKeyIds, in: currentIdentityPublicKeys) ? pending.retiredGrantKeys : [] let outcome = pendingV2Outcome( - of: pending, currentIdentityPublicKeys: currentIdentityPublicKeys, bindings: bindings) + of: pending, currentIdentityPublicKeys: currentIdentityPublicKeys, + identityRevision: identityRevision, bindings: bindings) switch outcome { case .landed: var settled = grant diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index bb355241ea..176b9ab8dd 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -1123,9 +1123,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let appContractId = request.contractId.toBase58String() let requestHash = sealed.appEphemeralPubKeyHash.toHexString() let signer = KeychainSigner(modelContainer: context.modelContainer) - let currentPublicKeys = try await refreshedIdentityPublicKeys(context: context) + let (currentPublicKeys, currentRevision) = try await refreshedIdentityKeysAndRevision(context: context) await confirmRegistrations( - identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, + identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, identityRevision: currentRevision, context: context, in: stores) func isGrantForRequest(_ grant: AppConnectGrant) -> Bool { grant.identityId == identityId && grant.appContractId == appContractId @@ -1203,8 +1203,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { pending.unconfirmedKeyHash160 = sessionKeyHash160.toHexString() // The update is built at one above the revision the wallet holds // for the identity, read again from Platform above. - let revisionBefore = try context.wallet.managedIdentity(identityId: context.identityId).getRevision() - pending.submittedRevision = revisionBefore == .max ? nil : revisionBefore + 1 + let readHeldRevision = { try Self.heldRevision(context: context) } + let revision = AppConnect.SubmittedRevision( + held: try readHeldRevision(), + earlier: stores.grants.load().first { $0.key == pending.key && $0.isUnconfirmed }?.submittedRevision) + pending.submittedRevision = revision.value // A confirmed record for this request means its key is on the // identity, and a view without it is behind: registering again // would be refused, and the record must keep its values. @@ -1223,25 +1226,20 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } Self.logger.info("🔗 DASHCONNECT :: registering session key") do { - try await signer.withAdditionalSigningKeys([ - (publicKey: sessionKeyHash160, privateKey: sessionPrivateKey), - ]) { - try await updateIdentity(add: [key], context: context, signer: signer) - } - } catch { - // Another update of the identity that landed meanwhile moved - // the wallet's revision, and this one may have been built on - // it: the record names the higher of the two, which only - // makes a disconnect wait longer for the outcome. - if let revisionAfter = try? context.wallet - .managedIdentity(identityId: context.identityId).getRevision(), - revisionAfter > revisionBefore, revisionAfter < .max { + try await revision.submit({ + try await signer.withAdditionalSigningKeys([ + (publicKey: sessionKeyHash160, privateKey: sessionPrivateKey), + ]) { + try await updateIdentity(add: [key], context: context, signer: signer) + } + }, readHeld: readHeldRevision, raise: { raised in updateGrants(in: stores) { grants in guard let index = grants.firstIndex(where: { $0.key == pending.key }) else { return } - grants[index].submittedRevision = revisionAfter + 1 + grants[index].submittedRevision = raised } - pending.submittedRevision = revisionAfter + 1 - } + pending.submittedRevision = raised + }) + } catch { // The update may have landed all the same. If the key is on // the identity, the login goes on; otherwise the failure // stands and the record stays unconfirmed, to be confirmed if @@ -1507,14 +1505,14 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } let firstCurrentKeysRead = Task { try await readCurrentKeys() } defer { firstCurrentKeysRead.cancel() } - let currentPublicKeys = try await refreshedIdentityPublicKeys(context: context) + let (currentPublicKeys, currentRevision) = try await refreshedIdentityKeysAndRevision(context: context) let bindings = try Self.storedKeyBindings(identityId: identityId, modelContainer: context.modelContainer) // This identity's records whose update's outcome was not known are // settled first: one that landed is a grant like any other below (for // this request, its keys are sent again and its response published // as on any retry), and one that cannot land frees its ids. await confirmRegistrations( - identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, + identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, identityRevision: currentRevision, context: context, in: stores, bindings: bindings) // Which rotations to derive depends on the keys the identity has. for grant in plan.encryption { @@ -1705,8 +1703,17 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // update. A key of a confirmed one the fetched list lacks means the // list is behind, and it could not be shown to be off. A previous // grant whose own update's outcome is not known has its keys that - // are there replaced like any other; the rest are settled once this - // update lands. + // are there replaced like any other. The rest are not turned off + // after this update: Platform applies an identity update only at one + // above the identity's revision, and the SDK builds this one above + // the revision of its copy, replaced by the read above, so an earlier + // update that lands first gets this one refused. The read after this + // update settles its record (`AppConnect.pendingV2Outcome`). + // TODO(dashconnect-update-outcome): a reload of the SDK's copy + // elsewhere between that read and the submit would build this update + // above a revision the earlier one already took; its keys then stay + // on, under a confirmed record, until this connection's next + // renewal or disconnect. func isSuperseded(_ grant: AppConnectGrant) -> Bool { connectionId != nil && grant.identityId == identityId && grant.appContractId == appId && grant.connectionId == connectionId && !isGrantForRequest(grant) @@ -1928,11 +1935,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { ) } }, + readHeldRevision: { try Self.heldRevision(context: context) }, reread: { - guard let keys = try? await refreshedIdentityPublicKeys(context: context), + guard let read = try? await refreshedIdentityKeysAndRevision(context: context), let bindings = try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer) else { return nil } - return (keys, bindings) + return (read.keys, read.revision, bindings) }, pause: { _ in try? await Task.sleep(nanoseconds: 3_000_000_000) }, onDropped: { remaining in @@ -1962,19 +1970,22 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { publishFailure = error } // One more read settles the identity's records still waiting for - // their update by what it shows of their keys. A previous grant of this connection that turned out to have landed - // holds keys this login replaces: they are turned off too. This runs - // after this request's own response is out, the app is waiting for - // it, and whether or not that publish went through. + // their update by what it shows of their keys and its revision. This + // runs after this request's own response is out, the app is waiting + // for it, and whether or not that publish went through. Nothing is + // turned off after it (see the renewal's rule above): a previous + // grant of this connection whose update had not landed when this + // approval read the identity is refused once this update lands, as + // long as the SDK built it on that read. if !add.isEmpty || !disable.isEmpty, stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { - if let settled = await settleAfterOwnUpdate(context: context, stores: stores) { - do { - try await disableLateLandedGrants( - settled.confirmed.filter(isSuperseded), liveIn: settled.keys, context: context, signer: signer) - } catch { - Self.logger.error("🔗 DASHCONNECT :: keys of a replaced grant that landed late are still live — \(error.localizedDescription, privacy: .public)") - } + let waiting = Set(stores.grants.load().filter { isSuperseded($0) && $0.isPendingV2 }.map(\.key)) + if let keys = await settleAfterOwnUpdate(context: context, stores: stores), + AppConnect.landedWithLiveKeys(stores.grants.load(), among: waiting, in: keys) { + // TODO(dashconnect-update-outcome): the window above; the + // keys stay on until this connection's next renewal or + // disconnect. + Self.logger.error("🔗 DASHCONNECT :: an earlier grant of this connection landed after this update; its keys are still live") } } if let publishFailure { throw publishFailure } @@ -1985,7 +1996,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// written, and `showRow` run, before `submit` sends the identity update /// that adds `add` and disables `disable`, so keys that land are never /// without a record and a row to disconnect them from. A record that adds - /// keys carries them (`pendingUpdate`) until the outcome is known. + /// keys carries them (`pendingUpdate`) until the outcome is known, with + /// the revision the update is submitted at (`AppConnect.SubmittedRevision` + /// over `readHeldRevision`, the revision the wallet holds), raised on the + /// record and in the store when a failed submit finds the wallet's + /// revision moved. /// /// Nothing is written or submitted when `disable` does not fit one /// update: a renewal that left some of the replaced keys on would report @@ -1993,8 +2008,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// /// On success the record is confirmed and the grants in /// `retiredGrantKeys` are marked done. A failure may still have landed: - /// up to three reads (`reread`, `pause` before the second and third) - /// settle it by `AppConnect.pendingV2Outcome`. Landed confirms as on + /// up to three reads (`reread`, the identity's keys and revision, with + /// `pause` before the second and third) settle it by + /// `AppConnect.pendingV2Outcome`. Landed confirms as on /// success when the keys it disables show off; with any of them still /// on, the keys were added by another update, so the record is confirmed /// without retiring anything and the failure stands; with limits raised @@ -2017,7 +2033,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { grants: any AppConnectResponseStore, showRow: () async -> Void, submit: () async throws -> Void, - reread: () async -> (keys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [AppConnect.KeyBinding])?, + readHeldRevision: () throws -> UInt64, + reread: () async -> ( + keys: [ManagedIdentity.IdentityPublicKeyInfo], revision: UInt64, bindings: [AppConnect.KeyBinding] + )?, pause: (Int) async -> Void, onDropped: ([AppConnectGrant]) async -> Bool ) async throws -> AppConnectGrant { @@ -2025,7 +2044,15 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { logger.error("🔗 DASHCONNECT :: \(disable.count, privacy: .public) superseded keys do not fit one update; not renewing") throw DashConnectPlatformError.tooManyKeysToReplace } + var record = record + // Noted on the record before it is written, so the update is never + // submitted without it. var stored = grants.load() + let earlierNoted = stored.first { $0.key == record.key }?.pendingUpdate?.submittedRevision + let revision = try record.pendingUpdate.map { _ in + AppConnect.SubmittedRevision(held: try readHeldRevision(), earlier: earlierNoted) + } + record.pendingUpdate?.submittedRevision = revision?.value if let existing = stored.first(where: { $0.key == record.key }), !existing.isUnconfirmed, !record.isUnconfirmed { // Kept as it is: if its publish landed without confirming, its // values are the ones on Platform. @@ -2060,7 +2087,17 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { logger.info("🔗 DASHCONNECT :: registering \(add.count, privacy: .public) key(s), disabling \(disable.count, privacy: .public)") do { - try await submit() + if let revision { + try await revision.submit(submit, readHeld: readHeldRevision) { raised in + record.pendingUpdate?.submittedRevision = raised + var all = grants.load() + guard let index = all.firstIndex(where: { $0.key == record.key }) else { return } + all[index].pendingUpdate?.submittedRevision = raised + grants.save(all) + } + } else { + try await submit() + } } catch { for attempt in 0 ..< 3 { if attempt > 0 { await pause(attempt) } @@ -2075,7 +2112,8 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { continue } let outcome = AppConnect.pendingV2Outcome( - of: pending, currentIdentityPublicKeys: view.keys, bindings: view.bindings) + of: pending, currentIdentityPublicKeys: view.keys, identityRevision: view.revision, + bindings: view.bindings) switch outcome { case .landed where disabled && AppConnect.showsAddedLimits(of: pending, in: view.keys): logger.info("🔗 DASHCONNECT :: the identity update landed without confirming") @@ -2406,22 +2444,24 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// two-QR login. /// /// A v2 record whose update's outcome was not known is settled by - /// `AppConnect.settlePendingV2Registrations`. One that landed is confirmed + /// `AppConnect.settlePendingV2Registrations`, over + /// `currentIdentityPublicKeys` and `identityRevision` read together + /// (`refreshedIdentityKeysAndRevision`). One that landed is confirmed /// and its row shown; its response is not published: its approval /// stopped waiting, and the app asks again. One that cannot land is /// dropped, and its row with it when nothing else holds it /// (`showRowsAfterDropping`). Nothing is settled while the store's - /// bindings cannot be read. Returns the v2 grants confirmed. - @discardableResult + /// bindings cannot be read. private func confirmRegistrations( identityId: String, currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], + identityRevision: UInt64, context: Context, in stores: Stores, bindings knownBindings: [AppConnect.KeyBinding]? = nil - ) async -> [AppConnectGrant] { + ) async { guard stores.grants.load().contains(where: { $0.identityId == identityId && $0.keyDisabled != true }) - else { return [] } + else { return } // Unknown when the store cannot be read: no unconfirmed record is // confirmed without it, and no row is changed by it. let readBindings = knownBindings @@ -2437,15 +2477,13 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.logger.info("🔗 DASHCONNECT :: \(confirmed.count, privacy: .public) unconfirmed session key(s) found on the identity") } } - var confirmedV2: [AppConnectGrant] = [] // Without the store's bindings a v2 record is not settled: one that // could not land would be dropped with its rows not judged. if let readBindings, stores.grants.load().contains(where: { $0.identityId == identityId && $0.isPendingV2 }) { var grants = stores.grants.load() let settled = AppConnect.settlePendingV2Registrations( in: &grants, identityId: identityId, currentIdentityPublicKeys: currentIdentityPublicKeys, - bindings: bindings) - confirmedV2 = settled.confirmed + identityRevision: identityRevision, bindings: bindings) if !settled.confirmed.isEmpty { Self.logger.info("🔗 DASHCONNECT :: \(settled.confirmed.count, privacy: .public) App Connect update(s) found to have landed") } @@ -2498,7 +2536,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.rowsAfterHolding(appIds: waitingAppIds, in: rows, at: shownAt) } } - return confirmedV2 } /// The apps of `identityId` whose v2 record waiting for its update holds @@ -2605,17 +2642,17 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// After an update of this wallet to the identity landed: one more read /// of the identity, which also writes what it shows to the store, and /// the v2 records of the identity waiting for their outcome are settled - /// by what it shows of their keys. Returns the v2 grants - /// confirmed and the keys read, or nil when the read failed. + /// by what it shows of their keys and its revision. Returns the keys + /// read, or nil when the read failed. private func settleAfterOwnUpdate( context: Context, stores: Stores - ) async -> (confirmed: [AppConnectGrant], keys: [ManagedIdentity.IdentityPublicKeyInfo])? { - guard let keys = try? await refreshedIdentityPublicKeys(context: context) else { return nil } - let confirmed = await confirmRegistrations( - identityId: context.identityId.toBase58String(), currentIdentityPublicKeys: keys, - context: context, in: stores) - return (confirmed, keys) + ) async -> [ManagedIdentity.IdentityPublicKeyInfo]? { + guard let read = try? await refreshedIdentityKeysAndRevision(context: context) else { return nil } + await confirmRegistrations( + identityId: context.identityId.toBase58String(), currentIdentityPublicKeys: read.keys, + identityRevision: read.revision, context: context, in: stores) + return read.keys } /// `rows` once the v2 records of `appIds` that were waiting for their @@ -3056,7 +3093,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { /// known and that holds a key there (`waitingHoldsKeys`), is settled /// only by a read of that identity, once it is the active one. A v2 /// record that holds none, such as one whose update never left the - /// device, does not hold the row: nothing may settle it. + /// device, does not hold the row: it is settled by a read of that + /// identity, while it is the active one, that shows it at the revision + /// the record notes or past it, and never when it notes none + /// (TODO(dashconnect-unconfirmed-row)). static func reasonHeldElsewhere( grants: [AppConnectGrant], appContractId: String, @@ -3193,12 +3233,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { let (currentPublicKeys, revision) = try await refreshedIdentityKeysAndRevision(context: context) // A registration whose key has turned up is confirmed. await confirmRegistrations( - identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, + identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, identityRevision: revision, context: context, in: stores) // A v2 update of the app whose outcome the read above could not // tell is settled once an update of this disconnect lands. let pendingV2 = Set(stores.grants.load().filter { isGranted($0) && $0.isPendingV2 }.map(\.key)) - var lateDisableFailure: Error? // One that has not is settled by its revision. One that does not // note it takes no part: its key id may belong to another key, and // its absence says nothing. @@ -3364,8 +3403,10 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // other. // A record of the app still waiting that holds a key this update does // not turn off keeps the disconnect from ending here; one that holds - // none (an update that never left the device) does not, since nothing - // may ever settle it. + // none (an update that never left the device) does not: it is + // settled by a read that shows the identity at the revision it + // notes or past it, and never when it notes none + // (TODO(dashconnect-unconfirmed-row)). let waitingHoldsOtherKeys = stores.grants.load().filter { pendingV2.contains($0.key) }.contains { !AppConnect.heldKeyIds(heldBy: $0, in: currentPublicKeys, bindings: bindings).subtracting(keyIds).isEmpty } @@ -3389,6 +3430,16 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { profileKeysUnchecked = true } } + // The user turned the app off: a waiting record of it no longer puts + // back the two-QR row it replaced, whose keys this disconnect + // disables too. + func forgetReplacedApprovedRows() { + updateGrants(in: stores) { grants in + for index in grants.indices where isGranted(grants[index]) && grants[index].isPendingV2 { + grants[index].pendingUpdate?.replacesApprovedRow = nil + } + } + } // The identity as this disconnect leaves it: as read, when it sends // nothing; as read again after its update, when it does. var keysAfterUpdate: [ManagedIdentity.IdentityPublicKeyInfo]? = keyIds.isEmpty ? currentPublicKeys : nil @@ -3399,6 +3450,9 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // attempt picks up what is still live. try await disableKeys(keyIds, context: context, signer: signer) Self.logger.info("🔗 DASHCONNECT :: app key(s) disabled") + // Before any settle below can drop a waiting record and put back + // the two-QR row it replaced, whose keys are now off too. + if asOneQR { forgetReplacedApprovedRows() } // Each registration that might still land names a revision above // `revision`, the one below it the identity was already at. The // update that just landed took one above the identity's revision @@ -3424,31 +3478,27 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } // The reload writes the disabled keys to the store, and settles // the v2 records still waiting for their update by what it shows - // of their keys. One of the app's that turns out to have landed - // holds keys that are turned off too. - // The keys above are off either way. - if let settled = await settleAfterOwnUpdate(context: context, stores: stores) { - keysAfterUpdate = settled.keys - do { - try await disableLateLandedGrants( - settled.confirmed.filter { pendingV2.contains($0.key) }, liveIn: settled.keys, - context: context, signer: signer) - } catch { - lateDisableFailure = error - } - } - } - - // The user turned the app off: a waiting record of it no longer puts - // back the two-QR row it replaced, whose keys this disconnect - // disabled too. - if asOneQR { - updateGrants(in: stores) { grants in - for index in grants.indices where isGranted(grants[index]) && grants[index].isPendingV2 { - grants[index].pendingUpdate?.replacesApprovedRow = nil - } - } - } + // of their keys and its revision. Nothing is turned off after it: + // a waiting update of the app that had not landed when the + // identity was read above is refused once the update of this + // disconnect lands (Platform applies an identity update only at + // one above the identity's revision), as long as the SDK built + // that update on the read above. + // TODO(dashconnect-update-outcome): a reload of the SDK's copy + // elsewhere in between would let both land; this read then + // confirms the waiting record with its keys on (`landedLate`). + keysAfterUpdate = await settleAfterOwnUpdate(context: context, stores: stores) + } else if asOneQR { + forgetReplacedApprovedRows() + } + // A waiting update of the app that the read after the update shows + // landed (the window above, or a key the first read showed that the + // store could not place yet) left keys on that this disconnect did + // not turn off: once what was turned off is marked, the row stays + // and the next attempt turns them off. + let landedLate = keysAfterUpdate.map { + AppConnect.landedWithLiveKeys(stores.grants.load(), among: pendingV2, in: $0) + } ?? false // The session keys of the grants read above are now off, and only // those are marked. @@ -3464,15 +3514,20 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { signer: signer ) } - // Keys of the app that landed late and could not be turned off keep - // the row, once what was turned off above is marked. - if let lateDisableFailure { throw lateDisableFailure } + if landedLate { + Self.logger.error("🔗 DASHCONNECT :: a waiting update of the app turned out to have landed; its keys are still live") + throw DashConnectPlatformError.identityKeysOutOfDate + } // A record of the app still waiting for its update keeps the row // while it may hold a live key, while the read after the update // lacks a key the store gives it (`showsWaitingKeys`), or while the - // identity could not be read again. One that holds none lets the row - // go and stays recorded: an update that never left the device reads - // the same as one on its way. If it lands after all, a later + // identity could not be read again. A read that shows the identity + // at the revision its update was submitted at, or past it, without + // its keys has dropped it already, unless it holds a key + // (`AppConnect.pendingV2Outcome`). + // One left that holds none lets the row go and stays recorded: + // below that revision, or with none noted, an update that never left + // the device reads the same as one on its way. If it lands after all, a later // settle confirms it and shows the app again // (`appIdsWithoutTheirOneQRRow`), to be disconnected then. let stillWaiting = stores.grants.load().filter { pendingV2.contains($0.key) && $0.isPendingV2 } @@ -3522,33 +3577,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { identityId: context.identityId, addPublicKeys: add, disablePublicKeyIds: disable, signer: signer) } - /// Turns off the keys of `grants` that `keys` (a fresh view) shows live: - /// earlier grants that turned out to have landed after the keys to - /// replace or disconnect were picked. Then marks them done. - private func disableLateLandedGrants( - _ grants: [AppConnectGrant], - liveIn keys: [ManagedIdentity.IdentityPublicKeyInfo], - context: Context, - signer: KeychainSigner - ) async throws { - guard !grants.isEmpty else { return } - let keyIds = Set(grants.flatMap(\.keyIds)).intersection(AppConnect.liveGrantedKeyIds(in: keys)).sorted() - if !keyIds.isEmpty { - Self.logger.info("🔗 DASHCONNECT :: disabling \(keyIds.count, privacy: .public) key(s) of App Connect grants that landed late") - try await disableKeys(keyIds, context: context, signer: signer) - } - // A live key a login could not have granted is left on, and so is - // the grant that names it. - // A grant naming a key the view lacks is not marked either: the view - // may be behind. - let leftOn = Set(keys.filter { $0.disabledAt == nil && !AppConnect.isLiveGrantedKey($0) } - .map { UInt32(bitPattern: $0.keyId) }) - let shown = Set(keys.map { UInt32(bitPattern: $0.keyId) }) - let grantKeys = Set(grants.filter { $0.keyIds.allSatisfy { shown.contains($0) && !leftOn.contains($0) } } - .map(\.key)) - updateGrants(in: context.stores) { AppConnect.markKeysDisabled(in: &$0) { grantKeys.contains($0.key) } } - } - /// Whether the wallet's store shows another identity of this wallet with /// a live key of the app that no grant record names: a session key bound /// to the app's contract, or a key the two-QR login derives for it. @@ -4164,8 +4192,11 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { try await refreshedIdentityKeysAndRevision(context: context).keys } - /// The identity's keys and revision as Platform has them, both read from - /// one copy of the identity. + /// The identity's keys and revision as Platform has them, read from the + /// SDK's copy of the identity right after it is reloaded. Both come from + /// one handle, a snapshot the SDK copies out of the wallet, so they are + /// of the same copy: a key absent from them was absent at that revision, + /// which is what settling an update by its revision takes. private func refreshedIdentityKeysAndRevision( context: Context ) async throws -> (keys: [ManagedIdentity.IdentityPublicKeyInfo], revision: UInt64) { @@ -4176,6 +4207,12 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { return (try identity.getPublicKeys(), try identity.getRevision()) } + /// The revision of the SDK's copy of the identity: the one the SDK + /// builds the next identity update above. + private static func heldRevision(context: Context) throws -> UInt64 { + try context.wallet.managedIdentity(identityId: context.identityId).getRevision() + } + /// What the wallet's store holds for each key of the identity. The store /// is written by the SDK as it loads and updates the identity. private static func storedKeyBindings( diff --git a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift index fc1ddc9623..aa0f059bd6 100644 --- a/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift +++ b/DashWalletTests/DashConnect/AppConnectV2LoginTests.swift @@ -1276,16 +1276,24 @@ extension AppConnectV2LoginTests { return grant } + /// The identity revision the views in these tests show, below the + /// revision a record notes unless a test says otherwise. + private static let revision: UInt64 = 5 + private static func outcome( _ added: [ManagedPlatformWallet.IdentityPubkey], keys: [ManagedIdentity.IdentityPublicKeyInfo], bindings: [AppConnect.KeyBinding]? = nil, - outlivedBy: AppConnect.OwnUpdate? = nil + outlivedBy: AppConnect.OwnUpdate? = nil, + submittedRevision: UInt64? = nil, + identityRevision: UInt64 = revision ) -> AppConnect.PendingV2Outcome { var pending = pendingUpdate(added) pending.outlivedBy = outlivedBy + pending.submittedRevision = submittedRevision return AppConnect.pendingV2Outcome( - of: pending, currentIdentityPublicKeys: keys, bindings: bindings ?? added.map(stored)) + of: pending, currentIdentityPublicKeys: keys, identityRevision: identityRevision, + bindings: bindings ?? added.map(stored)) } func testAPendingUpdateLandedOnlyWhenEveryKeyIsThereAsItWasAdded() { @@ -1356,9 +1364,8 @@ extension AppConnectV2LoginTests { let master = Self.key(0, level: .master) let laterKey = Self.addedAuthKey(11, data: 0x0B) let later = AppConnect.OwnUpdate(added: [laterKey], disabledKeyIds: [3]) - // A note an earlier build made: the SDK's copy of the identity can - // be reloaded while an update is on its way, so the pending one can - // still land after the later one. + // A note an earlier build made is not used to settle: a record that + // notes no revision of its own stays unknown. XCTAssertEqual( Self.outcome([auth], keys: [master, Self.key(3, disabled: true), Self.onIdentity(laterKey)], outlivedBy: later), .unknown) @@ -1387,6 +1394,97 @@ extension AppConnectV2LoginTests { "nor lowers one") } + func testAnAbsentKeyWithTheIdentityAtItsSubmittedRevisionMeansTheUpdateCanNeverLand() { + let auth = Self.addedAuthKey(7, data: 0x07) + let encryption = Self.addedEncryptionKey(8, data: 0x08) + let master = Self.key(0, level: .master) + XCTAssertEqual( + Self.outcome([auth, encryption], keys: [master], submittedRevision: 5, identityRevision: 5), .cannotLand, + "Platform applies an update only at one above the identity's revision") + XCTAssertEqual( + Self.outcome([auth, encryption], keys: [master], submittedRevision: 5, identityRevision: 9), .cannotLand) + XCTAssertEqual( + Self.outcome([auth, encryption], keys: [master, Self.onIdentity(auth)], submittedRevision: 5, + identityRevision: 5), + .cannotLand, "one key of it absent is enough: an update lands whole") + XCTAssertEqual( + Self.outcome([auth, encryption], keys: [master], submittedRevision: 6, identityRevision: 5), .unknown, + "the identity is below its revision: it may still land") + XCTAssertEqual( + Self.outcome([auth, encryption], keys: [master], submittedRevision: nil, identityRevision: 9), .unknown, + "a record that notes no revision is not settled by one") + XCTAssertEqual( + Self.outcome([auth, encryption], keys: [master, Self.onIdentity(auth), Self.onIdentity(encryption)], + submittedRevision: 5, identityRevision: 9), + .landed, "its keys there settle it whatever the revision") + } + + func testAKeyThatIsThereButUnplacedStaysUnknownPastItsSubmittedRevision() { + let auth = Self.addedAuthKey(7, data: 0x07) + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth)], bindings: [], submittedRevision: 5, identityRevision: 9), + .unknown, "the store may not have loaded the key yet") + var unreadable = Self.stored(auth) + unreadable.hasUnreadableBound = true + XCTAssertEqual( + Self.outcome([auth], keys: [Self.onIdentity(auth)], bindings: [unreadable], submittedRevision: 5, + identityRevision: 9), + .unknown) + } + + func testASettleDropsAWaitingRecordWhoseUpdateCanNoLongerLand() { + let key = Self.addedAuthKey(7, data: 0x07) + var cannotLand = Self.pendingGrant([key], requestHash: "a1") + cannotLand.pendingUpdate?.submittedRevision = Self.revision + var mayStillLand = Self.pendingGrant([Self.addedAuthKey(8, data: 0x08)], requestHash: "a2") + mayStillLand.pendingUpdate?.submittedRevision = Self.revision + 1 + let unnoted = Self.pendingGrant([Self.addedAuthKey(9, data: 0x09)], requestHash: "a3") + var grants = [cannotLand, mayStillLand, unnoted] + let settled = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: "identity", currentIdentityPublicKeys: [Self.key(0, level: .master)], + identityRevision: Self.revision, bindings: []) + XCTAssertEqual(settled.dropped.map(\.key), [cannotLand.key]) + XCTAssertEqual(grants.map(\.key), [mayStillLand.key, unnoted.key]) + XCTAssertTrue(grants.allSatisfy(\.isPendingV2)) + } + + func testAWaitingRecordThatLandedWithALiveKeyIsTold() { + let waiting = Self.pendingGrant([Self.addedAuthKey(7, data: 0x07)], requestHash: "a1") + var landed = waiting + landed.pendingUpdate = nil + landed.unconfirmedKeyHash160 = nil + let other = Self.grant(sessionKeyId: 4, requestHash: "b1") + XCTAssertTrue(AppConnect.landedWithLiveKeys( + [landed], among: [waiting.key], in: [Self.onIdentity(Self.addedAuthKey(7, data: 0x07))])) + XCTAssertFalse( + AppConnect.landedWithLiveKeys([landed], among: [waiting.key], in: [Self.key(7, disabled: true)]), + "its key is off") + XCTAssertFalse( + AppConnect.landedWithLiveKeys([waiting], among: [waiting.key], in: [Self.onIdentity(Self.addedAuthKey(7, data: 0x07))]), + "still waiting") + XCTAssertFalse( + AppConnect.landedWithLiveKeys([other], among: [waiting.key], in: [Self.key(4, level: .high)]), + "not one that was waiting") + } + + func testARecordKeptForAKeyItHoldsIsDroppedOnceThatKeyIsOff() { + let added = Self.addedAuthKey(8, data: 0x08) + var record = Self.pendingGrant([added], requestHash: "a1") + record.additionalKeyIds = [5] + record.pendingUpdate?.submittedRevision = Self.revision + var grants = [record] + let held = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: "identity", currentIdentityPublicKeys: [Self.key(5, level: .critical)], + identityRevision: Self.revision, bindings: []) + XCTAssertEqual(held.dropped, [], "it cannot land, but the key it sends again is live") + XCTAssertEqual(grants.map(\.key), [record.key]) + let off = AppConnect.settlePendingV2Registrations( + in: &grants, identityId: "identity", currentIdentityPublicKeys: [Self.key(5, disabled: true)], + identityRevision: Self.revision + 1, bindings: []) + XCTAssertEqual(off.dropped.map(\.key), [record.key]) + XCTAssertEqual(grants, []) + } + func testAPendingUpdateWhoseReplacedKeysAreStillOnRetiresNothing() { let key = Self.addedAuthKey(7, data: 0x07) let old = Self.grant(sessionKeyId: 3, requestHash: "00", connectionId: "c1") @@ -1396,7 +1494,7 @@ extension AppConnectV2LoginTests { let settled = AppConnect.settlePendingV2Registrations( in: &grants, identityId: "identity", currentIdentityPublicKeys: [Self.onIdentity(key), Self.key(3)], - bindings: [Self.stored(key)]) + identityRevision: Self.revision, bindings: [Self.stored(key)]) XCTAssertEqual(settled.confirmed.map(\.key), [pending.key], "its keys are there and need their record") XCTAssertNil(grants[0].keyDisabled, "another update added them; the replaced key is still on") @@ -1404,7 +1502,7 @@ extension AppConnectV2LoginTests { _ = AppConnect.settlePendingV2Registrations( in: &landedOff, identityId: "identity", currentIdentityPublicKeys: [Self.onIdentity(key, disabled: true), Self.key(3)], - bindings: [Self.stored(key)]) + identityRevision: Self.revision, bindings: [Self.stored(key)]) XCTAssertEqual(landedOff.map(\.key), [old.key]) XCTAssertNil(landedOff[0].keyDisabled) } @@ -1471,7 +1569,7 @@ extension AppConnectV2LoginTests { currentIdentityPublicKeys: [ Self.onIdentity(landedKey), Self.onIdentity(impossibleKey, data: Data(repeating: 0xEE, count: 20)), ], - bindings: [Self.stored(landedKey)]) + identityRevision: Self.revision, bindings: [Self.stored(landedKey)]) XCTAssertEqual(settled.confirmed.map(\.key), [landed.key]) XCTAssertEqual(settled.dropped.map(\.key), [impossible.key]) @@ -1504,7 +1602,7 @@ extension AppConnectV2LoginTests { XCTAssertEqual( AppConnect.settlePendingV2Registrations( in: &otherBoundGrants, identityId: "identity", - currentIdentityPublicKeys: [Self.onIdentity(added)], bindings: [otherBound]).dropped.map(\.key), + currentIdentityPublicKeys: [Self.onIdentity(added)], identityRevision: Self.revision, bindings: [otherBound]).dropped.map(\.key), [record.key]) XCTAssertEqual( AppConnect.heldKeyIds(heldBy: record, in: [taken], bindings: [AppConnect.KeyBinding( @@ -1528,7 +1626,7 @@ extension AppConnectV2LoginTests { ] { var grants = [record] let settled = AppConnect.settlePendingV2Registrations( - in: &grants, identityId: "identity", currentIdentityPublicKeys: keys, bindings: [Self.stored(added)]) + in: &grants, identityId: "identity", currentIdentityPublicKeys: keys, identityRevision: Self.revision, bindings: [Self.stored(added)]) XCTAssertEqual(settled.dropped, [], why) XCTAssertEqual(grants.map(\.key), [record.key], why) XCTAssertTrue(grants[0].isPendingV2, why) @@ -1536,7 +1634,7 @@ extension AppConnectV2LoginTests { var grants = [record] let settled = AppConnect.settlePendingV2Registrations( in: &grants, identityId: "identity", - currentIdentityPublicKeys: [Self.key(5, disabled: true), taken], bindings: []) + currentIdentityPublicKeys: [Self.key(5, disabled: true), taken], identityRevision: Self.revision, bindings: []) XCTAssertEqual(settled.dropped.map(\.key), [record.key], "nothing of it is live any more") } @@ -1556,7 +1654,7 @@ extension AppConnectV2LoginTests { var grants = [record] let settled = AppConnect.settlePendingV2Registrations( - in: &grants, identityId: "identity", currentIdentityPublicKeys: [conflict], bindings: [Self.stored(keyB)]) + in: &grants, identityId: "identity", currentIdentityPublicKeys: [conflict], identityRevision: Self.revision, bindings: [Self.stored(keyB)]) XCTAssertEqual(settled.dropped, [], "it cannot land, but the store gives it B") XCTAssertTrue(grants[0].isPendingV2) @@ -1567,7 +1665,7 @@ extension AppConnectV2LoginTests { var others = [record] XCTAssertEqual( AppConnect.settlePendingV2Registrations( - in: &others, identityId: "identity", currentIdentityPublicKeys: unplaced, bindings: []).dropped, []) + in: &others, identityId: "identity", currentIdentityPublicKeys: unplaced, identityRevision: Self.revision, bindings: []).dropped, []) } func testAWaitingRecordThatHoldsAKeyGetsARowToDisconnectIt() { @@ -1652,7 +1750,7 @@ extension AppConnectV2LoginTests { let settled = AppConnect.settlePendingV2Registrations( in: &grants, identityId: "identity", currentIdentityPublicKeys: [Self.onIdentity(key, disabled: true), Self.key(3, disabled: true)], - bindings: [Self.stored(key)]) + identityRevision: Self.revision, bindings: [Self.stored(key)]) XCTAssertEqual(settled.dropped.map(\.key), [pending.key]) XCTAssertEqual(grants.map(\.key), [old.key]) XCTAssertEqual(grants[0].keyDisabled, true, "its update turned the replaced grant off") @@ -1879,6 +1977,7 @@ extension AppConnectV2LoginTests { var rereads = 0 var pauses: [Int] = [] var dropped = 0 + var heldReads = 0 } private static func register( @@ -1890,16 +1989,24 @@ extension AppConnectV2LoginTests { calls: Calls, submit: @escaping () throws -> Void = {}, views: [View?] = [], + identityRevision: UInt64 = revision, + heldRevisions: [UInt64] = [revision], rowsJudged: Bool = true ) async throws -> AppConnectGrant { var remaining = views + var held = heldRevisions return try await PlatformDashConnectDataSource.registerAppConnectV2Grant( record, add: add, disable: disable, retiredGrantKeys: retiring, grants: store, showRow: { calls.rowShown += 1 }, submit: { calls.submitted += 1; try submit() }, + readHeldRevision: { + calls.heldReads += 1 + return held.count > 1 ? held.removeFirst() : held[0] + }, reread: { calls.rereads += 1 - return remaining.isEmpty ? nil : remaining.removeFirst() + guard !remaining.isEmpty, let view = remaining.removeFirst() else { return nil } + return (view.keys, identityRevision, view.bindings) }, pause: { calls.pauses.append($0) }, onDropped: { _ in @@ -1918,6 +2025,7 @@ extension AppConnectV2LoginTests { let grant = try await Self.register(record, add: [key], disable: [3], retiring: [old.key], store: store, calls: calls) { let stored = store.grants.first { $0.key == record.key } XCTAssertEqual(stored?.pendingUpdate?.addedKeys, [AppConnect.ExpectedKey(key)], "recorded first") + XCTAssertEqual(stored?.pendingUpdate?.submittedRevision, Self.revision + 1, "with the revision it is built at") XCTAssertTrue(stored?.isUnconfirmed == true) XCTAssertEqual(calls.rowShown, 1, "and shown") XCTAssertNil(store.grants.first { $0.key == old.key }?.keyDisabled, "the replaced grant waits for the update") @@ -1938,6 +2046,7 @@ extension AppConnectV2LoginTests { let calls = Calls() _ = try await Self.register(earlier, add: [], disable: [], retiring: [old.key], store: store, calls: calls) XCTAssertEqual(calls.submitted, 0, "nothing to send") + XCTAssertEqual(calls.heldReads, 0, "a record that adds nothing notes no revision") XCTAssertEqual(store.grants.first { $0.key == old.key }?.keyDisabled, true) } @@ -2088,7 +2197,9 @@ extension AppConnectV2LoginTests { } catch { XCTAssertTrue(error is UpdateFailed) } - XCTAssertEqual(store.grants, [record], "the next settle drops it, with its rows judged") + var noted = record + noted.pendingUpdate?.submittedRevision = Self.revision + 1 + XCTAssertEqual(store.grants, [noted], "the next settle drops it, with its rows judged") XCTAssertEqual(calls.dropped, 1) } @@ -2106,10 +2217,62 @@ extension AppConnectV2LoginTests { } XCTAssertEqual(calls.rereads, 3) XCTAssertEqual(calls.pauses, [1, 2]) - XCTAssertEqual(store.grants, [record], "kept until the outcome is known") + var noted = record + noted.pendingUpdate?.submittedRevision = Self.revision + 1 + XCTAssertEqual(store.grants, [noted], "kept until the outcome is known") XCTAssertEqual(calls.dropped, 0) } + func testAFailedUpdateThatCanNoLongerLandByItsRevisionDropsItsRecord() async { + let key = Self.addedAuthKey(7, data: 0x07) + let store = MemoryGrantStore() + let calls = Calls() + do { + _ = try await Self.register( + Self.pendingGrant([key]), add: [key], store: store, calls: calls, submit: { throw UpdateFailed() }, + views: [([Self.key(0, level: .master)], [])], identityRevision: Self.revision + 1) + XCTFail("the failure stands") + } catch { + XCTAssertTrue(error is UpdateFailed) + } + XCTAssertEqual(store.grants, [], "the identity is at the revision it was submitted at, without its key") + XCTAssertEqual(calls.rereads, 1) + XCTAssertEqual(calls.dropped, 1) + } + + func testAFailedSubmitRaisesTheNotedRevisionWhenTheWalletsRevisionMoved() async { + let key = Self.addedAuthKey(7, data: 0x07) + let record = Self.pendingGrant([key]) + let store = MemoryGrantStore() + let calls = Calls() + do { + _ = try await Self.register( + record, add: [key], store: store, calls: calls, + submit: { + XCTAssertEqual(store.grants.first?.pendingUpdate?.submittedRevision, Self.revision + 1) + throw UpdateFailed() + }, + views: [([Self.key(0, level: .master)], [])], identityRevision: Self.revision + 2, + heldRevisions: [Self.revision, Self.revision + 2]) + XCTFail("the failure stands") + } catch { + XCTAssertTrue(error is UpdateFailed) + } + XCTAssertEqual(calls.heldReads, 2) + XCTAssertEqual( + store.grants.first?.pendingUpdate?.submittedRevision, Self.revision + 3, + "it may have been built on the update that moved the wallet's revision") + XCTAssertEqual(store.grants.map(\.key), [record.key], "the raised revision is the one it is judged by") + XCTAssertEqual(calls.dropped, 0) + + let unmoved = MemoryGrantStore() + _ = try? await Self.register( + record, add: [key], store: unmoved, calls: Calls(), submit: { throw UpdateFailed() }, + views: [([Self.key(0, level: .master)], [])], identityRevision: Self.revision + 2, + heldRevisions: [Self.revision, Self.revision]) + XCTAssertEqual(unmoved.grants, [], "with the revision unmoved, the same view settles it") + } + func testAGrantThatCannotBeRecordedIsNotSubmitted() async { let key = Self.addedAuthKey(7, data: 0x07) let calls = Calls() diff --git a/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift b/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift index ce444f1065..48630e0245 100644 --- a/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift +++ b/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift @@ -2936,6 +2936,61 @@ final class AppConnectLoginTests: XCTestCase { XCTAssertEqual(outcome(unnoted, keys: [Self.key(keyId: 9, data: hash)], revision: 9), .keyLive) } + /// The revision a registration notes: one above the one the wallet + /// holds, raised after a failed submit when the wallet's revision moved. + func testASubmittedRevisionIsRaisedOnlyWhenAFailedSubmitFindsTheRevisionMoved() async { + struct Failed: Error {} + XCTAssertEqual(AppConnect.SubmittedRevision(held: 3).value, 4) + XCTAssertNil(AppConnect.SubmittedRevision(held: .max).value, "no update follows the largest revision") + + let revision = AppConnect.SubmittedRevision(held: 3) + var reads = 0 + var raised: [UInt64] = [] + try? await revision.submit({}, readHeld: { reads += 1; return 9 }, raise: { raised.append($0) }) + XCTAssertEqual(reads, 0, "a submit that went through reads nothing again") + XCTAssertEqual(raised, []) + + for (after, expected, why) in [ + (UInt64(5), [UInt64(6)], "another update moved it"), + (3, [], "unmoved"), + (2, [], "a lower read never lowers it"), + (.max, [], "nothing above the largest revision"), + ] { + raised = [] + do { + try await revision.submit({ throw Failed() }, readHeld: { after }, raise: { raised.append($0) }) + XCTFail("the failure stands: \(why)") + } catch { + XCTAssertTrue(error is Failed, why) + } + XCTAssertEqual(raised, expected, why) + } + raised = [] + try? await revision.submit({ throw Failed() }, readHeld: { throw Failed() }, raise: { raised.append($0) }) + XCTAssertEqual(raised, [], "an unreadable revision keeps the one noted") + } + + func testARetryNeverLowersTheRevisionAnEarlierSubmissionNoted() async { + struct Failed: Error {} + XCTAssertEqual(AppConnect.SubmittedRevision(held: 3).value, 4) + XCTAssertEqual( + AppConnect.SubmittedRevision(held: 3, earlier: 7).value, 7, + "a read from a node that is behind keeps the earlier submission's") + XCTAssertEqual(AppConnect.SubmittedRevision(held: 8, earlier: 7).value, 9) + XCTAssertEqual(AppConnect.SubmittedRevision(held: .max, earlier: 7).value, 7) + + let retry = AppConnect.SubmittedRevision(held: 3, earlier: 7) + for (after, expected, why) in [ + (UInt64(4), [UInt64](), "below what is noted: kept"), + (6, [], "one above it is what is noted"), + (7, [8], "moved past what is noted"), + ] { + var raised: [UInt64] = [] + try? await retry.submit({ throw Failed() }, readHeld: { after }, raise: { raised.append($0) }) + XCTAssertEqual(raised, expected, why) + } + } + /// After a disable update of the disconnect has landed, a registration /// that could still land when its keys were picked has either put its /// key on the identity, which is then picked for disabling too, or