diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectProjection.swift b/DashWallet/Sources/Models/DashConnect/AppConnectProjection.swift index 2dbad42065..e0edfe548e 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectProjection.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectProjection.swift @@ -718,6 +718,41 @@ extension AppConnect { } && outstandingDisables(of: intent, in: snapshot).isEmpty } + /// The key under `id` on `snapshot` whose bound the store holds: the + /// only proof the connection sheet takes that a key is the app's. Every + /// claim it makes from a key on Platform (access, messages, funding) + /// rests on it. A key whose bound the store does not hold yet may be + /// bound to another contract, so it backs no claim until a read places it. + static func placedKey(withId id: UInt32, in snapshot: IdentitySnapshot) -> PlatformKey? { + snapshot.keys.first { $0.id == id && $0.boundKnown } + } + + /// The key on `snapshot` an intended auth key gives access through: it + /// landed (live or expired) and is placed (`placedKey`), so its bound is + /// the intended one (`isSameKey`). + static func accessKey(of intended: IntendedKey, in snapshot: IdentitySnapshot) -> PlatformKey? { + guard [.live, .expired].contains(presence(of: intended, in: snapshot)) else { return nil } + return placedKey(withId: intended.id, in: snapshot) + } + + /// Whether `intent`'s encryption keys give the app message access on + /// `snapshot`, as the connection sheet says it: every key it re-sends is + /// placed (`placedKey`) and live, and every key it adds is placed and + /// live, or not there yet while the intent may still land. One that is + /// off, expired, not placed, or whose id another key holds gives none. + static func encryptionKeysGiveAccess(_ intent: ConnectionIntent, in snapshot: IdentitySnapshot) -> Bool { + let mayLand = status(of: intent, in: snapshot) == .confirming + return intent.sentEncryptionKeyIds.allSatisfy { id in + placedKey(withId: id, in: snapshot).map { isLive($0, at: snapshot.platformTime) } == true + } && intent.keys.filter { !$0.isAuthentication }.allSatisfy { key in + switch presence(of: key, in: snapshot) { + case .live: return placedKey(withId: key.id, in: snapshot) != nil + case .missing: return mayLand + case .conflicting, .expired, .disabled: return false + } + } + } + /// Whether the encryption keys `intent`'s response carries can still be /// used: those it re-sends are live, and those it adds are not off. static func encryptionKeysUsable(_ intent: ConnectionIntent, in snapshot: IdentitySnapshot) -> Bool { diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift index e495abb410..0311af221d 100644 --- a/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift +++ b/DashWallet/Sources/Models/DashConnect/AppConnectV2Login.swift @@ -106,7 +106,8 @@ extension AppConnect { } } - /// What an approval gives an app, as the approval sheet lists it. + /// What an approval gives an app, as the approval sheet and the + /// connection sheet list it. struct GrantedAccess: Equatable { struct Key: Equatable { let bound: StoredBound @@ -139,6 +140,72 @@ extension AppConnect { }, receivesMessages: receivesMessages) } + + /// What `intents` gave, in their order: the auth keys each one adds, + /// with the terms it submitted them with, a key two intents name + /// once. An intent always names a bound and an expiry for an auth + /// key; one without is not listed. + init(intents: [ConnectionIntent]) { + self.init(intents: intents, snapshot: nil) + } + + /// `init(intents:)` as the keys on Platform give it, when `snapshot` + /// read them: a key that landed gives the limits Platform holds now, + /// which an authorized limits update may have raised; a disabled key, + /// or one whose id another key holds, gives nothing; a key not there + /// yet gives its submitted terms while its intent may still land. + /// `unrecorded`: keys on `snapshot` the projection gives the app that + /// no intent names, with the limits Platform holds; + /// `administeredGroups`: the groups of those keys that may have + /// administrators. Message access, with `snapshot`, is what its + /// encryption keys still give. + init( + intents: [ConnectionIntent], snapshot: IdentitySnapshot?, unrecorded: [PlatformKey] = [], + administeredGroups: Set = [] + ) { + var listed = Set() + self.init( + keys: intents.flatMap { intent in + let mayLand = snapshot.map { AppConnect.status(of: intent, in: $0) == .confirming } ?? true + return intent.authKeys.compactMap { key -> Key? in + guard let bound = key.bound, let submittedExpiry = key.expiresAt else { return nil } + var expiresAt = submittedExpiry + var totalBudget = key.totalBudget + if let snapshot { + switch AppConnect.presence(of: key, in: snapshot) { + case .live, .expired: + // Its bound not read yet: not known to be access. + guard let actual = AppConnect.accessKey(of: key, in: snapshot) else { return nil } + totalBudget = actual.totalBudget + expiresAt = actual.expiresAt ?? submittedExpiry + case .missing: + guard mayLand else { return nil } + case .disabled, .conflicting: + return nil + } + } + guard listed.insert(key.id).inserted else { return nil } + return Key( + bound: bound, isCritical: key.securityLevel == .critical, totalBudget: totalBudget, + expiresAt: expiresAt, isAdministered: intent.isAdministered(bound)) + } + } + unrecorded.compactMap { key -> Key? in + // The projection lists only keys with an expiry. + guard let bound = key.bound, let expiresAt = key.expiresAt, listed.insert(key.id).inserted else { + return nil + } + var isAdministered = false + if case .contractGroup(let id) = bound { isAdministered = administeredGroups.contains(id) } + return Key( + bound: bound, isCritical: key.securityLevel == .critical, totalBudget: key.totalBudget, + expiresAt: expiresAt, isAdministered: isAdministered) + }, + receivesMessages: intents.contains { intent in + let hasMessageKey = !intent.sentEncryptionKeyIds.isEmpty || intent.keys.contains { !$0.isAuthentication } + guard hasMessageKey else { return false } + return snapshot.map { AppConnect.encryptionKeysGiveAccess(intent, in: $0) } ?? true + }) + } } /// What approving a v2 request gives the app, as the approval sheet diff --git a/DashWallet/Sources/Models/DashConnect/DashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/DashConnectDataSource.swift index a401b35101..7961eb2a52 100644 --- a/DashWallet/Sources/Models/DashConnect/DashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/DashConnectDataSource.swift @@ -74,11 +74,17 @@ protocol DashConnectDataSource { /// identity's intents for the app; `nil` when there is no active wallet /// or `scope` is not its. func connectionDetails(id: String, scope: String?) async -> ConnectionDetails? + /// What is left of the budgets of the keys `basis` gives the app, read + /// after the details told from it and apart from them, so the sheet + /// shows them first; `.notRead` when `basis` is not of the active + /// identity of the wallet `scope` names. + func connectionFunding(for basis: ConnectionBasis, scope: String?) async -> ConnectionFundingRead } extension DashConnectDataSource { func refreshConnections() async {} func connectionDetails(id: String, scope: String?) async -> ConnectionDetails? { nil } + func connectionFunding(for basis: ConnectionBasis, scope: String?) async -> ConnectionFundingRead { .notRead } } /// Why a token purchase failed, and — the part that decides what the UI may diff --git a/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift b/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift index 6e8ed49bbf..fc7ba9d7d2 100644 --- a/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift +++ b/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift @@ -250,15 +250,218 @@ struct DashConnectDisconnectResult: Equatable { var keysOnAnotherIdentity = false } +/// What a connection gives its app, from the intents of one identity that +/// hold it, as the connection sheet shows it. +struct ConnectionAccess: Equatable { + /// What each key can do. + let keys: [AppConnect.GrantedAccess.Key] + /// The most the keys can spend together, in credits: Platform counts + /// each key's budget apart, so it is their sum. `nil` when no key has a + /// budget (see `hasUnlimitedKey`). + let budgetLimit: UInt64? + /// A key with no spending limit. + let hasUnlimitedKey: Bool + /// When the last of the keys stops working. + let expiresAt: Date? + /// The connection can receive messages encrypted to this identity. + let receivesMessages: Bool + + /// `nil` when no auth key of `intents` or `unrecorded` gives access on + /// `snapshot` (`GrantedAccess(intents:snapshot:unrecorded:)`). It needs a + /// read of the identity: without one, what the intents submitted is not + /// known to be the app's access. + init?( + intents: [AppConnect.ConnectionIntent], snapshot: AppConnect.IdentitySnapshot, + unrecorded: [AppConnect.PlatformKey] = [], administeredGroups: Set = [] + ) { + let access = AppConnect.GrantedAccess( + intents: intents, snapshot: snapshot, unrecorded: unrecorded, administeredGroups: administeredGroups) + guard !access.keys.isEmpty else { return nil } + self.init(access) + } + + init(_ access: AppConnect.GrantedAccess) { + keys = access.keys + let budgets = access.keys.compactMap(\.totalBudget) + budgetLimit = budgets.isEmpty ? nil : budgets.reduce(0) { sum, budget in + let (total, overflow) = sum.addingReportingOverflow(budget) + return overflow ? .max : total + } + hasUnlimitedKey = access.keys.contains { $0.totalBudget == nil } + expiresAt = access.keys.map(\.expiresAt).max().map { Date(timeIntervalSince1970: TimeInterval($0) / 1000) } + receivesMessages = access.receivesMessages + } + + var granted: AppConnect.GrantedAccess { + AppConnect.GrantedAccess(keys: keys, receivesMessages: receivesMessages) + } +} + +/// What a connection sheet is told from: one read of the identity, the +/// intents that hold the app on it, and the keys that read gives the app +/// that no intent names. The sheet's access and what is left of its keys' +/// budgets both come from one basis, so they tell of the same read. A newer +/// read is another basis: funding read for an earlier one is never shown +/// beside it (`ConnectionDetails.attaching(_:for:)`). +struct ConnectionBasis: Equatable { + let snapshot: AppConnect.IdentitySnapshot + /// The open intents of the snapshot's identity that hold the app. + let intents: [AppConnect.ConnectionIntent] + /// Keys on `snapshot` the projection gives the app that no intent names. + let unrecorded: [AppConnect.PlatformKey] + /// The groups of `unrecorded` keys that may have administrators. + let administeredGroups: Set + + /// What the app was given; `nil` when no auth key gives access. + var access: ConnectionAccess? { + ConnectionAccess( + intents: intents, snapshot: snapshot, unrecorded: unrecorded, administeredGroups: administeredGroups) + } + + /// The keys whose remaining budgets the sheet reads, by id. + var fundedKeyIds: [UInt32] { + KeyFunding.keyIds(of: intents, snapshot: snapshot, unrecorded: unrecorded) + } + + /// The funding lines of `fundedKeyIds` with what `remaining` (by key id) + /// says is left. What is left is read after `snapshot`: when it is above + /// a total of this read, a limits update came between them, and the read + /// fails rather than show it against totals it outgrew; the next read of + /// the identity brings them together. + func funding(remaining: [UInt32: UInt64?]) -> ConnectionFundingRead { + let lines = KeyFunding.of(intents: intents, snapshot: snapshot, unrecorded: unrecorded, remaining: remaining) + return KeyFunding.agree(lines) ? .read(lines) : .failed + } +} + /// A connection as its sheet shows it: the app, the identity it is -/// connected on, and when it was made. +/// connected on, and what it was given. struct ConnectionDetails: Equatable { let appId: String let identityId: String? let username: String? + /// What `access` and the funding lines are told from; `nil` without a + /// read of the identity, or when the connection is not the active + /// identity's. + let basis: ConnectionBasis? + /// What the app was given, from `basis`. Without one nothing is known to + /// be the app's access: the sheet shows none rather than what the + /// intents submitted, which may never have landed. + let access: ConnectionAccess? /// When the connection was made: the latest of its approvals, so a /// renewal from a new code counts as the connection it made. - var connectedAt: Date? = nil + let connectedAt: Date? + /// What is left of each key's budget, read from Platform for `basis`; + /// `nil` when it was not read or could not be (`fundingReadFailed`). + private(set) var keyFunding: [KeyFunding]? + private(set) var fundingReadFailed = false + + init( + appId: String, identityId: String?, username: String?, basis: ConnectionBasis? = nil, connectedAt: Date? = nil + ) { + self.appId = appId + self.identityId = identityId + self.username = username + self.basis = basis + access = basis?.access + self.connectedAt = connectedAt + } + + /// These details with `read`, the funding read for `basis`; `nil` when + /// these details are not told from `basis`: what is left of the keys of + /// another read is not shown beside the access of this one. + func attaching(_ read: ConnectionFundingRead, for basis: ConnectionBasis) -> ConnectionDetails? { + guard basis == self.basis else { return nil } + var details = self + switch read { + case .notRead: + details.keyFunding = nil + details.fundingReadFailed = false + case .read(let lines): + details.keyFunding = lines + details.fundingReadFailed = false + case .failed: + details.keyFunding = nil + details.fundingReadFailed = true + } + return details + } + + /// These details with the funding `previous` shows, when both are told + /// from the same basis; otherwise as they are, with none. + func keepingFunding(of previous: ConnectionDetails) -> ConnectionDetails { + guard previous.basis == basis else { return self } + var details = self + details.keyFunding = previous.keyFunding + details.fundingReadFailed = previous.fundingReadFailed + return details + } +} + +/// What is left of a connection's keys' budgets, read apart from its details +/// so the sheet does not wait on it. +enum ConnectionFundingRead: Equatable { + /// Nothing to read: no landed key, or not the active identity's basis. + case notRead + case read([KeyFunding]) + /// The read failed, or what it said is above the totals the identity + /// read gave (a limits update between the two). + case failed +} + +/// One of a connection's keys, with what is left of its budget. +struct KeyFunding: Equatable { + /// The key is bound to the DashPay profile, not to the app's data. + let isProfileKey: Bool + /// What the key may spend over its life; `nil` with no limit. + let totalBudget: UInt64? + /// What is left of it; `nil` with no limit, or when Platform did not say. + let remaining: UInt64? + + /// The auth keys of `intents` that are on `snapshot` and not disabled, + /// then the `unrecorded` keys the projection gives the app, in their + /// order, each with its budget as Platform holds it now and what + /// `remaining` (by key id) says is left. A key is listed once. + static func of( + intents: [AppConnect.ConnectionIntent], snapshot: AppConnect.IdentitySnapshot, + unrecorded: [AppConnect.PlatformKey] = [], remaining: [UInt32: UInt64?] + ) -> [KeyFunding] { + landedKeys(of: intents, snapshot: snapshot, unrecorded: unrecorded).map { key in + KeyFunding( + isProfileKey: key.bound.map(AppConnect.isProfileBound) ?? false, + totalBudget: key.totalBudget, + remaining: remaining[key.id] ?? nil) + } + } + + /// Whether `lines` hold together: nothing left above its key's total. + /// The totals come from an identity read and what is left from a later + /// one, so a limits update between them makes them disagree. + static func agree(_ lines: [KeyFunding]) -> Bool { + lines.allSatisfy { line in + guard let total = line.totalBudget, let remaining = line.remaining else { return true } + return remaining <= total + } + } + + /// The ids `of(intents:snapshot:unrecorded:remaining:)` lists, whose + /// remaining budgets are read from Platform. + static func keyIds( + of intents: [AppConnect.ConnectionIntent], snapshot: AppConnect.IdentitySnapshot, + unrecorded: [AppConnect.PlatformKey] = [] + ) -> [UInt32] { + landedKeys(of: intents, snapshot: snapshot, unrecorded: unrecorded).map(\.id).sorted() + } + + private static func landedKeys( + of intents: [AppConnect.ConnectionIntent], snapshot: AppConnect.IdentitySnapshot, + unrecorded: [AppConnect.PlatformKey] + ) -> [AppConnect.PlatformKey] { + var listed = Set() + let recorded = intents.flatMap(\.authKeys).compactMap { AppConnect.accessKey(of: $0, in: snapshot) } + let placed = unrecorded.compactMap { AppConnect.placedKey(withId: $0.id, in: snapshot) } + return (recorded + placed).filter { listed.insert($0.id).inserted } + } } /// A pending request derived from a scanned login QR code. diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index fb52728ee8..f95c9a0c30 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -2656,43 +2656,96 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { return await details(of: id, stores: stores) } - /// The app's connection on the active identity, as the intents that hold - /// it show it: the identity, its username and when the connection was - /// made. With a read of the identity, only the intents whose keys are - /// live, expired or may still land count; without one, every open intent. - private func details(of appId: String, stores: Stores) async -> ConnectionDetails? { - // Not read: the sheet says so and keeps details it already shows. + func connectionFunding(for basis: ConnectionBasis, scope: String?) async -> ConnectionFundingRead { + guard let stores = await showActiveWalletRows(), scope == stores.scope, + let context = try? await requireContext(pinnedTo: stores), + context.identityId == basis.snapshot.identityId else { return .notRead } + let keyIds = basis.fundedKeyIds + guard !keyIds.isEmpty else { return .notRead } + // A read-only query, off the main actor: it does not touch the + // identity copy the operations that sign use, so it does not wait on + // them, and the UI does not wait on the network. + guard let remaining = try? await DashConnectPlatformQueries.keysRemainingBudgets( + sdk: context.sdk, identityId: context.identityId.toBase58String(), keyIds: keyIds) + else { return .failed } + return basis.funding(remaining: remaining) + } + + /// What the sheet of `appId` is told from: the active identity, its open + /// intents that hold the app, and, with a read of the identity, the + /// basis of the sheet's access and funding. `nil` when the identity + /// cannot be read. + private struct HeldConnection { + let context: Context + let held: [AppConnect.ConnectionIntent] + let basis: ConnectionBasis? + } + + private func heldConnection(of appId: String, stores: Stores) async -> HeldConnection? { guard let context = try? await requireContext(pinnedTo: stores) else { return nil } let open = stores.intents.load().filter { $0.identityId == context.identityId && $0.appId.toBase58String() == appId && $0.closedAt == nil } - let snapshot = Self.newestSnapshots.withLock { $0[context.identityId] } - let held = snapshot.map { snapshot in - open.filter { - switch AppConnect.status(of: $0, in: snapshot) { - case .active, .expired, .confirming: return true - case .refused, .disconnected, .neverLanded: return false - } + // One read of the identity for everything the sheet says of the keys. + guard let snapshot = Self.newestSnapshots.withLock({ $0[context.identityId] }) else { + return HeldConnection(context: context, held: open, basis: nil) + } + let held = open.filter { + switch AppConnect.status(of: $0, in: snapshot) { + case .active, .expired, .confirming: return true + case .refused, .disconnected, .neverLanded: return false } - } ?? open - guard !held.isEmpty else { - // A row of keys no intent names (a restore, another device's - // grant, the profile keys) is the active identity's when the - // projection shows them on it; when it was made is not known. - let all = stores.intents.load() - if let snapshot, Self.showsUnrecordedKeys( - of: appId, on: snapshot, intents: all, - owners: await Self.ownerReader(context: context).knownOwners(for: snapshot, intents: all)) { - return ConnectionDetails( - appId: appId, identityId: context.identityId.toBase58String(), username: context.storedUsername) - } - // The app's row is held by another identity of the wallet: its - // intents are not the active identity's to show. + } + // Keys the row shows that no intent names (another device's, or + // attributed by owner) are the app's access too, from the same + // projection, with the owners it reads. + let all = stores.intents.load() + let owners = await Self.ownerReader(context: context).knownOwners(for: snapshot, intents: all) + let unrecorded = Self.unrecordedKeys(of: appId, on: snapshot, intents: all, owners: owners) + return HeldConnection( + context: context, held: held, + basis: ConnectionBasis( + snapshot: snapshot, intents: held, unrecorded: unrecorded, + administeredGroups: Self.mayBeAdministered(unrecorded, owners: owners))) + } + + /// The app's connection on the active identity, as the intents that hold + /// it show it. With a read of the identity, only the intents whose keys + /// are live, expired or may still land count. What is left of the keys' + /// budgets is read apart, for the same basis (`connectionFunding`). + private func details(of appId: String, stores: Stores) async -> ConnectionDetails? { + // Not read: the sheet says so and keeps details it already shows. + guard let shown = await heldConnection(of: appId, stores: stores) else { return nil } + // The app's row is held by another identity of the wallet: its + // intents are not the active identity's to show. + guard !shown.held.isEmpty || shown.basis?.unrecorded.isEmpty == false else { return ConnectionDetails(appId: appId, identityId: nil, username: nil) } return ConnectionDetails( - appId: appId, identityId: context.identityId.toBase58String(), username: context.storedUsername, - connectedAt: held.map(\.createdAt).max()) + appId: appId, identityId: shown.context.identityId.toBase58String(), username: shown.context.storedUsername, + basis: shown.basis, connectedAt: shown.held.map(\.createdAt).max()) + } + + /// The groups of `keys` that may have administrators: the owner read + /// as administered, or not read. Unknown is not said to be absent. + static func mayBeAdministered(_ keys: [AppConnect.PlatformKey], owners: [Data: Data]) -> Set { + Set(keys.compactMap { key -> Data? in + guard case .contractGroup(let id) = key.bound else { return nil } + let owner = owners[id] + return owner == nil || owner == AppConnect.administeredGroupOwnerId ? id : nil + }) + } + + /// The keys on `snapshot` that the projection, with the `owners` known, + /// shows under `appId` and no intent names. + private static func unrecordedKeys( + of appId: String, on snapshot: AppConnect.IdentitySnapshot, intents: [AppConnect.ConnectionIntent], + owners: [Data: Data] + ) -> [AppConnect.PlatformKey] { + let connection = AppConnect.project([snapshot], intents: intents, owners: owners).connections + .first { $0.appId.toBase58String() == appId } + let ids = Set(connection?.unrecordedKeyIds[snapshot.identityId] ?? []) + return snapshot.keys.filter { ids.contains($0.id) } } /// Whether the projection of `snapshot`, with the owners known, shows @@ -3701,12 +3754,14 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } /// Platform reads the Swift SDK offers only on the main actor (the current -/// epoch and an identity's contract keys), where their blocking FFI calls +/// epoch, an identity's contract keys, and what is left of keys' budgets), where their blocking FFI calls /// would hold the UI for a network round trip. They run here on queues of /// their own instead, with the SDK kept alive for the call; each copies the /// native result and releases it before returning. -/// TODO(dashconnect-off-main-queries): use the SDK's own off-main reads once -/// it has them for these, as it has for `documentList`. +/// TODO(dashconnect-off-main-queries): use the SDK's own off-main reads for +/// these once dashpay/platform#5867 provides them (the remaining budgets +/// included), as it has for `documentList`; then remove these wrappers and +/// the budgets parser. enum DashConnectPlatformQueries { /// One queue per kind of read, so a slow contract-keys read does not hold /// back the protocol-version read a sheet waits for. @@ -3716,6 +3771,47 @@ enum DashConnectPlatformQueries { private static let contractKeysQueue = DispatchQueue( label: "org.dashfoundation.dash.dashconnect.contract-keys-query", attributes: .concurrent) + /// Concurrent, like the contract-keys reads: a sheet's read it no longer + /// waits for must not hold back the next one. + private static let budgetsQueue = DispatchQueue( + label: "org.dashfoundation.dash.dashconnect.key-budgets-query", attributes: .concurrent) + + /// `SDK.fetchKeysRemainingBudgets(identityId:keyIds:)` off the main + /// actor: what is left of each key's budget in credits, `nil` for a key + /// with no budget or that the identity does not have. + static func keysRemainingBudgets(sdk: SDK, identityId: String, keyIds: [UInt32]) async throws -> [UInt32: UInt64?] { + guard !keyIds.isEmpty else { throw SDKError.invalidParameter("At least one key id is required") } + let answer = try await run(sdk, on: budgetsQueue) { handle in + try keyIds.withUnsafeBufferPointer { buffer in + try json(from: dash_sdk_identity_fetch_keys_remaining_budgets( + handle, identityId, buffer.baseAddress, UInt(buffer.count))) + } + } + return try remainingBudgets(answer) + } + + /// The remaining-budgets answer: a JSON object keyed by key id whose + /// values are decimal strings (credits are `u64`, which JSON numbers + /// cannot carry losslessly) or null. + static func remainingBudgets(_ answer: [String: Any]) throws -> [UInt32: UInt64?] { + var budgets: [UInt32: UInt64?] = [:] + for (rawKeyId, value) in answer { + guard let keyId = UInt32(rawKeyId) else { + throw SDKError.serializationError("Unparseable key id in remaining-budgets answer: \(rawKeyId)") + } + if value is NSNull { + // `updateValue`: assigning `nil` through the subscript removes the entry. + budgets.updateValue(nil, forKey: keyId) + continue + } + guard let text = value as? String, let credits = UInt64(text) else { + throw SDKError.serializationError("Unparseable remaining budget for key \(keyId)") + } + budgets.updateValue(credits, forKey: keyId) + } + return budgets + } + /// The protocol version the network runs, from a proved read of the /// current epoch. It throws when that read fails: there is no fallback /// value. diff --git a/DashWallet/Sources/UI/DashConnect/Components/ConnectionSheet.swift b/DashWallet/Sources/UI/DashConnect/Components/ConnectionSheet.swift index efe38ac87a..54e4e420f2 100644 --- a/DashWallet/Sources/UI/DashConnect/Components/ConnectionSheet.swift +++ b/DashWallet/Sources/UI/DashConnect/Components/ConnectionSheet.swift @@ -28,8 +28,15 @@ struct ConnectionSheet: View { /// which with details shown says a refresh of them failed). let details: ConnectionDetails? let detailsFailed: Bool - /// What an app is never given. + /// What the app was given; `nil` while unknown. + let granted: [String]? + /// What it was not given. let withheld: [String] + /// Each key with what is left of its budget; `nil` while unknown or not + /// read. + let funding: [(title: String, value: String)]? + /// Platform could not be read for it. + let fundingFailed: Bool /// When the connection was made. let connectedAt: Date? let isBusy: Bool @@ -45,7 +52,9 @@ struct ConnectionSheet: View { let takeDisconnectQuestion: () -> Bool /// Whether the sheet's own Disconnect may ask now. let disconnectQuestion: () -> Bool + let onShowFundingLimitsInfo: () -> Void + @State private var showsGranted = false @State private var showsWithheld = false @State private var isConfirmingDisconnect = false @@ -73,8 +82,13 @@ struct ConnectionSheet: View { .foregroundColor(Color.dash.secondaryText) .frame(maxWidth: .infinity, alignment: .leading) } - connectedCard - if details != nil { + limitsCard + if let granted { + collapsible(title: grantedTitle, isExpanded: $showsGranted) { + ForEach(Array(granted.enumerated()), id: \.offset) { + PermissionRow(icon: .custom("dashconnect.check.circle", maxHeight: 18), text: $0.element) + } + } collapsible(title: withheldTitle, isExpanded: $showsWithheld) { ForEach(withheld, id: \.self) { PermissionRow(icon: .custom("dashconnect.xmark.circle", maxHeight: 18), text: $0) @@ -208,19 +222,85 @@ struct ConnectionSheet: View { } @ViewBuilder - private var connectedCard: some View { - if let connectedAt { + private var limitsCard: some View { + let access = details?.access + if access != nil || connectedAt != nil { VStack(alignment: .leading, spacing: 2) { - Text(NSLocalizedString("Connected", comment: "DashConnect connection sheet: when the connection was made")) - .dashFont(.footnote) - .foregroundColor(Color.dash.tertiaryText) - Text(Self.dateFormatter.string(from: connectedAt)) - .dashFont(.subhead) - .foregroundColor(Color.dash.primaryText) + if let access { + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 4) { + Text(NSLocalizedString("Identity funding limits", comment: "DashConnect connection sheet")) + .dashFont(.footnote) + .foregroundColor(Color.dash.tertiaryText) + Button(action: onShowFundingLimitsInfo) { + InfoRoundIcon(size: 13, color: Color.dash.gray300Alpha90) + .frame(width: 44, height: 44) + .contentShape(Rectangle()) + } + .frame(width: 18, height: 18) + .accessibilityLabel(Text(NSLocalizedString( + "What are identity funding limits?", comment: "DashConnect connection sheet"))) + } + Text(fundingLimitText(access)) + .dashFont(.subhead) + .foregroundColor(Color.dash.primaryText) + } + .padding(.leading, 14) + .padding(.vertical, 8) + } + if let funding, !funding.isEmpty, item.connection != nil { + VStack(alignment: .leading, spacing: 2) { + Text(NSLocalizedString("Funding left", comment: "DashConnect connection sheet")) + .dashFont(.footnote) + .foregroundColor(Color.dash.tertiaryText) + ForEach(Array(funding.enumerated()), id: \.offset) { _, line in + Text(String( + format: NSLocalizedString( + "%1$@: %2$@", comment: "DashConnect connection sheet: a key's name, then its budget"), + line.title, line.value)) + .dashFont(.subhead) + .foregroundColor(Color.dash.primaryText) + } + } + .accessibilityElement(children: .combine) + .padding(.leading, 14) + .padding(.vertical, 8) + } + if fundingFailed, item.connection != nil { + Text(NSLocalizedString( + "What is left of the keys' budgets could not be read.", comment: "DashConnect connection sheet")) + .dashFont(.footnote) + .foregroundColor(Color.dash.tertiaryText) + .padding(.leading, 14) + .padding(.vertical, 8) + } + if let connectedAt { + VStack(alignment: .leading, spacing: 2) { + Text(NSLocalizedString("Connected", comment: "DashConnect connection sheet: when the connection was made")) + .dashFont(.footnote) + .foregroundColor(Color.dash.tertiaryText) + Text(Self.dateFormatter.string(from: connectedAt)) + .dashFont(.subhead) + .foregroundColor(Color.dash.primaryText) + } + .accessibilityElement(children: .combine) + .padding(.leading, 14) + .padding(.vertical, 8) + } + if let date = dateLine { + VStack(alignment: .leading, spacing: 2) { + Text(date.title) + .dashFont(.footnote) + .foregroundColor(Color.dash.tertiaryText) + Text(Self.dateFormatter.string(from: date.date)) + .dashFont(.subhead) + .foregroundColor(Color.dash.primaryText) + } + .accessibilityElement(children: .combine) + .padding(.leading, 14) + .padding(.vertical, 8) + } } - .accessibilityElement(children: .combine) - .padding(.leading, 14) - .padding(.vertical, 8) .frame(maxWidth: .infinity, alignment: .leading) .padding(6) .overlay( @@ -317,6 +397,13 @@ struct ConnectionSheet: View { ConnectionStatusBadge.label(for: item.status) } + private var grantedTitle: String { + String( + format: NSLocalizedString( + "See what %@ will be able to do", comment: "DashConnect connection sheet: the app's name"), + item.name) + } + private var withheldTitle: String { String( format: NSLocalizedString( @@ -324,6 +411,25 @@ struct ConnectionSheet: View { item.name) } + private func fundingLimitText(_ access: ConnectionAccess) -> String { + if access.hasUnlimitedKey { + return NSLocalizedString("No limit", comment: "DashConnect connection sheet: a key with no spending limit") + } + guard let budget = access.budgetLimit else { + return NSLocalizedString("Not known", comment: "DashConnect connection sheet") + } + return String( + format: NSLocalizedString( + "Maximum of %@", comment: "DashConnect connection sheet: an amount with its unit, e.g. 0.5 DASH"), + PlatformCreditsFormatter.dashString(budget)) + } + + private var dateLine: (title: String, date: Date)? { + guard let expiresAt = details?.access?.expiresAt else { return nil } + // Whether that time has passed on Platform is not read here. + return (NSLocalizedString("Connection expiry", comment: "DashConnect connection sheet: the date its keys expire"), expiresAt) + } + private static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateStyle = .medium @@ -364,22 +470,36 @@ private enum ConnectionSheetPreview { id: appId, name: name, url: "yap.pr", status: status, updatedAt: Date(timeIntervalSince1970: 1_793_000_000))) } + /// One key the app was given, as Platform shows it. + static let key = AppConnect.PlatformKey( + id: 10, purpose: .authentication, securityLevel: .high, keyType: .ecdsaHash160, + data: Data(repeating: 3, count: 20), readOnly: false, + bound: .documentType(contractId: Data(repeating: 1, count: 32), name: "post"), boundKnown: true, + totalBudget: 1_000_000_000, expiresAt: 1_794_000_000_000, disabledAt: nil) + static let details = ConnectionDetails( appId: appId, identityId: "5DbLwAxEWR695MsqP4KybNQD5n7CUDWydJYNg63FzUo8", username: "alice", + basis: ConnectionBasis( + snapshot: AppConnect.IdentitySnapshot( + identityId: Data(repeating: 2, count: 32), revision: 3, keys: [key], platformTime: 1_793_500_000_000), + intents: [], unrecorded: [key], administeredGroups: []), connectedAt: Date(timeIntervalSince1970: 1_793_000_000)) static func sheet( _ item: ConnectionSheetItem, details: ConnectionDetails?, detailsFailed: Bool = false, + granted: [String]? = nil, + funding: [(title: String, value: String)]? = nil, + fundingFailed: Bool = false, isBusy: Bool = false, message: ConnectionsScreenMessage? = nil ) -> ConnectionSheet { ConnectionSheet( - item: item, details: details, detailsFailed: detailsFailed, - withheld: DashConnectPermissionText.withheld, + item: item, details: details, detailsFailed: detailsFailed, granted: granted, + withheld: DashConnectPermissionText.withheld, funding: funding, fundingFailed: fundingFailed, connectedAt: details?.connectedAt, isBusy: isBusy, message: message, onClose: {}, onDisconnect: {}, onRemove: {}, - takeDisconnectQuestion: { false }, disconnectQuestion: { false }) + takeDisconnectQuestion: { false }, disconnectQuestion: { false }, onShowFundingLimitsInfo: {}) } } @@ -388,15 +508,21 @@ private enum ConnectionSheetPreview { } #Preview("Loaded") { - ConnectionSheetPreview.sheet(ConnectionSheetPreview.item(.active), details: ConnectionSheetPreview.details) + ConnectionSheetPreview.sheet( + ConnectionSheetPreview.item(.active), details: ConnectionSheetPreview.details, + granted: ConnectionSheetPreview.details.access.map { + DashConnectPermissionText.granted($0.granted, appLabel: "Yappr") + }, + funding: [(title: "App key", value: "0.004 DASH left of 0.01 DASH")]) } #Preview("Details failed") { ConnectionSheetPreview.sheet(ConnectionSheetPreview.item(.active), details: nil, detailsFailed: true) } -#Preview("Confirming") { - ConnectionSheetPreview.sheet(ConnectionSheetPreview.item(.confirming), details: ConnectionSheetPreview.details) +#Preview("Confirming, funding not read") { + ConnectionSheetPreview.sheet( + ConnectionSheetPreview.item(.confirming), details: ConnectionSheetPreview.details, fundingFailed: true) } #Preview("Not delivered, disconnecting") { diff --git a/DashWallet/Sources/UI/DashConnect/ConnectionsScreen.swift b/DashWallet/Sources/UI/DashConnect/ConnectionsScreen.swift index 8d28cd27c8..93241ecf77 100644 --- a/DashWallet/Sources/UI/DashConnect/ConnectionsScreen.swift +++ b/DashWallet/Sources/UI/DashConnect/ConnectionsScreen.swift @@ -34,6 +34,8 @@ struct ConnectionsScreen: View { _viewModel = StateObject(wrappedValue: viewModel ?? ConnectionsViewModel()) } + @State private var showsFundingLimitsInfo = false + var body: some View { ZStack { VStack(alignment: .leading, spacing: 0) { @@ -88,6 +90,7 @@ struct ConnectionsScreen: View { } } .sheet(item: shownConnectionBinding, onDismiss: { + showsFundingLimitsInfo = false viewModel.connectionSheetDismissed() }) { item in connectionSheet(for: item) @@ -139,7 +142,10 @@ struct ConnectionsScreen: View { item: item, details: viewModel.shownDetails, detailsFailed: viewModel.shownDetailsFailed, + granted: viewModel.shownGrantedLines, withheld: viewModel.shownWithheldLines, + funding: viewModel.shownFundingLines, + fundingFailed: viewModel.shownFundingFailed, connectedAt: viewModel.shownConnectedAt, isBusy: viewModel.isDisconnecting, message: viewModel.connectionSheetMessage, @@ -150,9 +156,17 @@ struct ConnectionsScreen: View { viewModel.hideConnection() }, takeDisconnectQuestion: viewModel.takeDisconnectQuestion, - disconnectQuestion: viewModel.disconnectQuestion + disconnectQuestion: viewModel.disconnectQuestion, + onShowFundingLimitsInfo: { showsFundingLimitsInfo = true } ) .presentationDragIndicator(.visible) + .sheet(isPresented: $showsFundingLimitsInfo) { + FundingLimitsInfoSheet(onClose: { showsFundingLimitsInfo = false }) + // Starts at the tallest it may be, so the first measurement + // is of the whole text; the sheet then settles at its height. + .selfSizingSheet(fallback: .greatestFiniteMagnitude, background: Color.dash.secondaryBackground) + .presentationDragIndicator(.visible) + } } private func approveSheet(for request: ConnectionRequest) -> some View { diff --git a/DashWallet/Sources/UI/DashConnect/ConnectionsViewModel.swift b/DashWallet/Sources/UI/DashConnect/ConnectionsViewModel.swift index 68a0dca2f2..3e8a1cda68 100644 --- a/DashWallet/Sources/UI/DashConnect/ConnectionsViewModel.swift +++ b/DashWallet/Sources/UI/DashConnect/ConnectionsViewModel.swift @@ -76,6 +76,42 @@ final class ConnectionsViewModel: ObservableObject { /// of details already shown failed). @Published private(set) var shownDetails: ConnectionDetails? @Published private(set) var shownDetailsFailed = false + /// The lines of what the shown connection's app was given and was not; + /// `nil` while unknown. + var shownGrantedLines: [String]? { + guard let item = shownConnection, let access = shownDetails?.access else { return nil } + return DashConnectPermissionText.granted(access.granted, appLabel: item.name) + } + + /// Each of the shown connection's keys with what is left of its budget, + /// as the sheet lists them; `nil` while unknown or not read. + var shownFundingLines: [(title: String, value: String)]? { + guard let funding = shownDetails?.keyFunding else { return nil } + return funding.map { key in + let title = key.isProfileKey + ? NSLocalizedString("DashPay profile key", comment: "DashConnect connection sheet: a key's budget line") + : NSLocalizedString("App key", comment: "DashConnect connection sheet: a key's budget line") + guard let total = key.totalBudget else { + return (title, NSLocalizedString( + "No limit", comment: "DashConnect connection sheet: a key with no spending limit")) + } + guard let remaining = key.remaining else { + return (title, String( + format: NSLocalizedString( + "Maximum of %@", comment: "DashConnect connection sheet: an amount with its unit, e.g. 0.5 DASH"), + PlatformCreditsFormatter.dashString(total))) + } + return (title, String( + format: NSLocalizedString( + "%1$@ left of %2$@", + comment: "DashConnect connection sheet: what is left of a key's budget, then the budget; amounts with units"), + PlatformCreditsFormatter.dashString(remaining), PlatformCreditsFormatter.dashString(total))) + } + } + + /// Platform could not be read for what is left of the keys' budgets. + var shownFundingFailed: Bool { shownDetails?.fundingReadFailed == true } + /// When the shown connection was made. var shownConnectedAt: Date? { shownDetails?.connectedAt @@ -268,8 +304,29 @@ final class ConnectionsViewModel: ObservableObject { self.shownDetailsFailed = true return } - self.shownDetails = details + // A refresh from the same read of the identity keeps the funding + // lines shown until its own read of them ends; one from another + // read drops them, as they tell of keys it may not show. + var shown = details + if keepingShown, let previous = self.shownDetails { + shown = shown?.keepingFunding(of: previous) + } + self.shownDetails = shown self.shownDetailsFailed = details == nil + if let basis = details?.basis { self.readShownFunding(item, for: basis, number: number) } + } + } + + /// What is left of the budgets of the keys `basis` gives the app, read + /// after the details told from it so the sheet does not wait on it; the + /// latest read only, and only beside details told from `basis`. + private func readShownFunding(_ item: ConnectionSheetItem, for basis: ConnectionBasis, number: Int) { + Task { [weak self] in + guard let self else { return } + let funding = await self.dataSource.connectionFunding(for: basis, scope: item.connection?.scope) + guard number == self.detailsReadNumber, self.shownConnection != nil, + let details = self.shownDetails?.attaching(funding, for: basis) else { return } + self.shownDetails = details } } diff --git a/DashWalletTests/DashConnect/AppConnectProjectionTests.swift b/DashWalletTests/DashConnect/AppConnectProjectionTests.swift index b15f96b8cd..32300f0428 100644 --- a/DashWalletTests/DashConnect/AppConnectProjectionTests.swift +++ b/DashWalletTests/DashConnect/AppConnectProjectionTests.swift @@ -19,11 +19,12 @@ final class AppConnectProjectionTests: XCTestCase { private static let now: UInt64 = 1_800_000_000_000 private static func authKey( - _ id: UInt32, data: UInt8? = nil, bound: AppConnect.StoredBound? = .singleContract(app), expiresAt: UInt64? = now + 1000 + _ id: UInt32, data: UInt8? = nil, bound: AppConnect.StoredBound? = .singleContract(app), expiresAt: UInt64? = now + 1000, + budget: UInt64? = 1000 ) -> Key { Key(id: id, purpose: .authentication, securityLevel: .high, keyType: .ecdsaHash160, data: Data(repeating: data ?? UInt8(truncatingIfNeeded: id), count: 20), readOnly: false, bound: bound, - totalBudget: 1000, expiresAt: expiresAt) + totalBudget: budget, expiresAt: expiresAt) } private static func encryptionKey(_ id: UInt32) -> Key { @@ -34,12 +35,14 @@ final class AppConnectProjectionTests: XCTestCase { /// The key as Platform shows it once its update landed. private static func onPlatform( - _ key: Key, disabledAt: UInt64? = nil, boundKnown: Bool = true, data: Data? = nil + _ key: Key, disabledAt: UInt64? = nil, boundKnown: Bool = true, data: Data? = nil, + limits: (totalBudget: UInt64?, expiresAt: UInt64?)? = nil ) -> AppConnect.PlatformKey { AppConnect.PlatformKey( id: key.id, purpose: key.purpose, securityLevel: key.securityLevel, keyType: key.keyType, data: data ?? key.data, readOnly: key.readOnly, bound: boundKnown ? key.bound : nil, - boundKnown: boundKnown, totalBudget: key.totalBudget, expiresAt: key.expiresAt, disabledAt: disabledAt) + boundKnown: boundKnown, totalBudget: limits.map(\.totalBudget) ?? key.totalBudget, + expiresAt: limits.map(\.expiresAt) ?? key.expiresAt, disabledAt: disabledAt) } private static func intent( @@ -64,6 +67,266 @@ final class AppConnectProjectionTests: XCTestCase { // MARK: What a connection gave + func testTheAccessOfAConnectionIsWhatItsIntentsAdded() { + let profile = Self.authKey(11, bound: .documentType(contractId: Self.dashPay, name: "profile")) + var group = Self.intent([Self.authKey(12, bound: .contractGroup(Self.appGroup), expiresAt: Self.now + 5000)]) + group.administeredGroupIds = [Self.appGroup] + let access = ConnectionAccess( + intents: [Self.intent([Self.authKey(10), profile, Self.encryptionKey(13)]), group], snapshot: Self.snapshot([])) + + XCTAssertEqual(access?.keys.map(\.bound), [.singleContract(Self.app), profile.bound!, .contractGroup(Self.appGroup)]) + XCTAssertEqual(access?.keys.map(\.isAdministered), [false, false, true]) + XCTAssertEqual(access?.budgetLimit, 3000, "three keys of 1000, each spent apart") + XCTAssertEqual(access?.hasUnlimitedKey, false) + XCTAssertEqual(access?.expiresAt, Date(timeIntervalSince1970: TimeInterval(Self.now + 5000) / 1000)) + XCTAssertEqual(access?.receivesMessages, true, "an encryption key it added") + XCTAssertNil(ConnectionAccess(intents: [Self.intent([Self.encryptionKey(13)])], snapshot: Self.snapshot([])), "no auth key, nothing to show") + } + + func testAConnectionReceivesMessagesWhenItsResponseCarriesAnEncryptionKey() { + let added = ConnectionAccess(intents: [Self.intent([Self.authKey(10)])], snapshot: Self.snapshot([])) + XCTAssertEqual(added?.receivesMessages, false) + var sent = Self.intent([Self.authKey(10)]) + sent = Intent( + id: sent.id, identityId: sent.identityId, appId: sent.appId, appLabel: sent.appLabel, appUrl: sent.appUrl, + requestHash: sent.requestHash, connectionId: nil, keys: sent.keys, sentEncryptionKeyIds: [3], disables: [], + response: sent.response, responseDocumentId: nil, responseRemoved: true, createdAt: sent.createdAt, closedAt: nil) + XCTAssertEqual( + ConnectionAccess(intents: [sent], snapshot: Self.snapshot([Self.onPlatform(Self.encryptionKey(3))]))?.receivesMessages, true, + "the identity's key, sent again and still live") + } + + func testEachAuthKeyIsListedOnceWithWhatIsLeftOfItsBudget() { + let profile = Self.authKey(11, bound: .documentType(contractId: Self.dashPay, name: "profile")) + let first = Self.intent([Self.authKey(10), profile, Self.encryptionKey(13)]) + let snapshot = Self.snapshot([Self.onPlatform(Self.authKey(10)), Self.onPlatform(profile)]) + let funding = KeyFunding.of( + intents: [first, Self.intent([Self.authKey(10)])], snapshot: snapshot, remaining: [10: 400, 11: nil]) + XCTAssertEqual(funding, [ + KeyFunding(isProfileKey: false, totalBudget: 1000, remaining: 400), + KeyFunding(isProfileKey: true, totalBudget: 1000, remaining: nil), + ]) + } + + /// A connection gives what its keys on Platform give: a disabled or + /// taken key gives nothing, even in an intent with a live key, and a + /// key that landed gives its limits as Platform holds them now, which an + /// authorized limits update may have raised. + func testAConnectionGivesWhatItsKeysOnPlatformGive() { + let app = Self.authKey(10) + let profile = Self.authKey(11, bound: .documentType(contractId: Self.dashPay, name: "profile")) + let taken = Self.authKey(12, bound: .contractGroup(Self.appGroup)) + let intent = Self.intent([app, profile, taken]) + let snapshot = Self.snapshot([ + Self.onPlatform(app, limits: (2000, Self.now + 9000)), + Self.onPlatform(profile, disabledAt: Self.now - 10), + Self.onPlatform(taken, data: Data(repeating: 0x77, count: 20)), + ]) + + let access = ConnectionAccess(intents: [intent], snapshot: snapshot) + XCTAssertEqual(access?.keys.map(\.bound), [.singleContract(Self.app)], "not the disabled profile key nor the taken id") + XCTAssertEqual(access?.keys.first?.totalBudget, 2000, "the budget Platform holds now") + XCTAssertEqual(access?.expiresAt, Date(timeIntervalSince1970: TimeInterval(Self.now + 9000) / 1000)) + XCTAssertEqual( + KeyFunding.of(intents: [intent], snapshot: snapshot, remaining: [10: 1500, 11: 900]), + [KeyFunding(isProfileKey: false, totalBudget: 2000, remaining: 1500)], + "no funding line for the disabled key") + let unlimited = Self.snapshot([Self.onPlatform(app, limits: (nil, Self.now + 9000))]) + XCTAssertEqual(ConnectionAccess(intents: [intent], snapshot: unlimited)?.hasUnlimitedKey, true, "no limit now") + } + + /// Keys that have not landed show the terms the wallet submitted while + /// the update may still land, and nothing once another key landed in + /// their place. + func testKeysThatHaveNotLandedShowTheSubmittedTermsWhileTheyMayLand() { + let confirming = Self.intent([Self.authKey(10), Self.authKey(11, bound: .contractGroup(Self.appGroup))]) + let access = ConnectionAccess(intents: [confirming], snapshot: Self.snapshot([])) + XCTAssertEqual(access?.keys.count, 2) + XCTAssertEqual(access?.keys.first?.totalBudget, 1000) + XCTAssertNil(ConnectionAccess(intents: [Self.intent([Self.authKey(10)])], snapshot: Self.snapshot([ + Self.onPlatform(Self.authKey(10), data: Data(repeating: 0x77, count: 20)), + ])), "its id is taken: it can never land") + } + + /// Platform counts each key's budget apart, so what an app may spend at + /// most is their sum, not the largest one; a key named twice counts once. + func testTheFundingLimitIsTheSumOfTheKeysBudgets() { + let first = Self.authKey(10, budget: 500) + let second = Self.authKey(11, bound: .contractGroup(Self.appGroup), budget: 500) + let access = ConnectionAccess(intents: [Self.intent([first, second]), Self.intent([first])], snapshot: Self.snapshot([])) + XCTAssertEqual(access?.budgetLimit, 1000) + XCTAssertEqual(access?.hasUnlimitedKey, false) + } + + /// Keys the projection gives the app that no intent names (granted on + /// another device, before a restore, or attributed by owner) count in + /// what its sheet says: their limits from Platform, and a key with no + /// budget makes it unlimited. + func testUnrecordedKeysTheAppHoldsCountInItsAccess() { + let recorded = Self.authKey(10, budget: 500) + let intent = Self.intent([recorded]) + let unlimited = Self.onPlatform(Self.authKey(20, expiresAt: Self.now + 9000, budget: nil)) + let budgeted = Self.onPlatform(Self.authKey(21, expiresAt: Self.now + 2000, budget: 300)) + let snapshot = Self.snapshot([Self.onPlatform(recorded), unlimited, budgeted]) + + let withUnlimited = ConnectionAccess(intents: [intent], snapshot: snapshot, unrecorded: [unlimited]) + XCTAssertEqual(withUnlimited?.keys.count, 2) + XCTAssertEqual(withUnlimited?.hasUnlimitedKey, true, "not 'Maximum of 500'") + XCTAssertEqual(withUnlimited?.expiresAt, Date(timeIntervalSince1970: TimeInterval(Self.now + 9000) / 1000)) + + let withBudgeted = ConnectionAccess(intents: [intent], snapshot: snapshot, unrecorded: [budgeted, budgeted]) + XCTAssertEqual(withBudgeted?.budgetLimit, 800, "the unrecorded key once") + XCTAssertEqual(ConnectionAccess(intents: [], snapshot: snapshot, unrecorded: [budgeted])?.keys.count, 1, + "a row of unrecorded keys only") + + XCTAssertEqual( + KeyFunding.of(intents: [intent], snapshot: snapshot, unrecorded: [unlimited], remaining: [10: 100, 20: nil]), + [KeyFunding(isProfileKey: false, totalBudget: 500, remaining: 100), + KeyFunding(isProfileKey: false, totalBudget: nil, remaining: nil)]) + XCTAssertEqual(KeyFunding.keyIds(of: [intent], snapshot: snapshot, unrecorded: [unlimited]), [10, 20]) + } + + /// An unrecorded key on a group gives the administrators' warning when + /// the group may have them: its owner reads as administered, or was not + /// read. Unknown is not said to be absent. + func testAnUnrecordedGroupKeyWarnsOfAdministratorsUnlessTheGroupHasNone() { + let groupKey = Self.onPlatform(Self.authKey(20, bound: .contractGroup(Self.appGroup))) + let snapshot = Self.snapshot([groupKey]) + XCTAssertEqual( + PlatformDashConnectDataSource.mayBeAdministered([groupKey], owners: [Self.appGroup: AppConnect.administeredGroupOwnerId]), + [Self.appGroup]) + XCTAssertEqual(PlatformDashConnectDataSource.mayBeAdministered([groupKey], owners: [:]), [Self.appGroup], "not read") + XCTAssertEqual( + PlatformDashConnectDataSource.mayBeAdministered([groupKey], owners: [Self.appGroup: Data(repeating: 0x0A, count: 32)]), []) + XCTAssertEqual( + ConnectionAccess(intents: [], snapshot: snapshot, unrecorded: [groupKey], administeredGroups: [Self.appGroup])? + .keys.map(\.isAdministered), [true]) + XCTAssertEqual( + ConnectionAccess(intents: [], snapshot: snapshot, unrecorded: [groupKey], administeredGroups: [])? + .keys.map(\.isAdministered), [false]) + } + + /// Message access is what the snapshot still holds: an encryption key + /// the response added that is now off, or a re-sent one no longer live, + /// gives none. + func testMessageAccessNeedsTheEncryptionKeysStillUsable() { + let auth = Self.authKey(10), encryption = Self.encryptionKey(13) + let intent = Self.intent([auth, encryption]) + XCTAssertEqual(ConnectionAccess(intents: [intent], snapshot: Self.snapshot([ + Self.onPlatform(auth), Self.onPlatform(encryption), + ]))?.receivesMessages, true) + XCTAssertEqual(ConnectionAccess(intents: [intent], snapshot: Self.snapshot([ + Self.onPlatform(auth), Self.onPlatform(encryption, disabledAt: Self.now - 10), + ]))?.receivesMessages, false, "its encryption key is off") + XCTAssertEqual(ConnectionAccess(intents: [intent], snapshot: Self.snapshot([ + Self.onPlatform(auth), Self.onPlatform(encryption, data: Data(repeating: 0x77, count: 33)), + ]))?.receivesMessages, false, "another key holds its encryption key's id: it never lands") + XCTAssertEqual(ConnectionAccess(intents: [intent], snapshot: Self.snapshot([Self.onPlatform(auth)]))?.receivesMessages, + false, "the update landed without it") + XCTAssertEqual(ConnectionAccess(intents: [intent], snapshot: Self.snapshot([]))?.receivesMessages, + true, "not landed yet: it may still") + } + + /// An encryption key whose bound the store does not hold yet may be + /// bound to another contract: it gives no message access, whether the + /// response added it or sent it again, until a read places it. + func testMessageAccessNeedsItsEncryptionKeysPlaced() { + let auth = Self.authKey(10), encryption = Self.encryptionKey(13) + let added = Self.intent([auth, encryption]) + XCTAssertEqual(ConnectionAccess(intents: [added], snapshot: Self.snapshot([ + Self.onPlatform(auth), Self.onPlatform(encryption, boundKnown: false), + ]))?.receivesMessages, false, "an added key not placed") + + var resent = Self.intent([auth]) + resent = Intent( + id: resent.id, identityId: resent.identityId, appId: resent.appId, appLabel: resent.appLabel, + appUrl: resent.appUrl, requestHash: resent.requestHash, connectionId: nil, keys: resent.keys, + sentEncryptionKeyIds: [3], disables: [], response: resent.response, responseDocumentId: nil, + responseRemoved: true, createdAt: resent.createdAt, closedAt: nil) + let identityKey = Self.encryptionKey(3) + XCTAssertFalse(AppConnect.encryptionKeysGiveAccess( + resent, in: Self.snapshot([Self.onPlatform(auth), Self.onPlatform(identityKey, boundKnown: false)])), + "a re-sent key not placed") + XCTAssertTrue(AppConnect.encryptionKeysGiveAccess( + resent, in: Self.snapshot([Self.onPlatform(auth), Self.onPlatform(identityKey)]))) + } + + /// Details and funding come from one read of the identity: funding read + /// for another read is not set beside the details, and a refresh from + /// another read drops the lines the sheet shows. + func testFundingIsShownOnlyBesideTheDetailsOfItsRead() { + let key = Self.authKey(10) + let intent = Self.intent([key]) + let first = ConnectionBasis( + snapshot: Self.snapshot([Self.onPlatform(key)]), intents: [intent], unrecorded: [], administeredGroups: []) + let raised = ConnectionBasis( + snapshot: Self.snapshot([Self.onPlatform(key, limits: (5000, Self.now + 1000))], revision: 6), + intents: [intent], unrecorded: [], administeredGroups: []) + let details = ConnectionDetails(appId: "app", identityId: "identity", username: nil, basis: first) + XCTAssertEqual(details.access?.budgetLimit, 1000) + + let lines = [KeyFunding(isProfileKey: false, totalBudget: 5000, remaining: 4000)] + XCTAssertNil(details.attaching(.read(lines), for: raised), "funding of a newer read beside the older totals") + let shown = details.attaching(first.funding(remaining: [10: 400]), for: first) + XCTAssertEqual(shown?.keyFunding, [KeyFunding(isProfileKey: false, totalBudget: 1000, remaining: 400)]) + XCTAssertEqual(first.funding(remaining: [10: 4000]), .failed, "4000 left of the 1000 this read gave") + + let refreshed = ConnectionDetails(appId: "app", identityId: "identity", username: nil, basis: raised) + XCTAssertNil(refreshed.keepingFunding(of: shown!).keyFunding, "the lines told of the earlier read") + let again = ConnectionDetails(appId: "app", identityId: "identity", username: nil, basis: first) + XCTAssertEqual(again.keepingFunding(of: shown!).keyFunding, shown?.keyFunding, "the same read") + } + + /// What is left of a key's budget, read after the identity, above the + /// total that read gave: a limits update landed between the two reads, + /// so the lines are not shown as if they agreed. + func testRemainingBudgetsAboveTheReadTotalsAreNotShown() { + let key = Self.authKey(10) + let snapshot = Self.snapshot([Self.onPlatform(key)]) + let agreeing = KeyFunding.of(intents: [Self.intent([key])], snapshot: snapshot, remaining: [10: 400]) + XCTAssertTrue(KeyFunding.agree(agreeing)) + let raised = KeyFunding.of(intents: [Self.intent([key])], snapshot: snapshot, remaining: [10: 2000]) + XCTAssertFalse(KeyFunding.agree(raised), "2000 left of 1000") + XCTAssertTrue(KeyFunding.agree([KeyFunding(isProfileKey: false, totalBudget: nil, remaining: nil)])) + } + + /// A key that matches an intent but whose bound the store does not hold + /// yet may be bound elsewhere: it gives no access and no funding line + /// until a read places it. + func testAKeyWhoseBoundIsUnknownGivesNoAccessYet() { + let profile = Self.authKey(11, bound: .documentType(contractId: Self.dashPay, name: "profile")) + let intent = Self.intent([profile]) + let unplaced = Self.snapshot([Self.onPlatform(profile, boundKnown: false)]) + XCTAssertNil(AppConnect.accessKey(of: profile, in: unplaced)) + XCTAssertNil(ConnectionAccess(intents: [intent], snapshot: unplaced), "no 'Edit your DashPay profile'") + XCTAssertEqual(KeyFunding.keyIds(of: [intent], snapshot: unplaced), []) + let placed = Self.snapshot([Self.onPlatform(profile)]) + XCTAssertEqual(ConnectionAccess(intents: [intent], snapshot: placed)?.keys.count, 1) + } + + /// Funding lines are chosen key by key: a live key keeps its line when + /// another key of its intent never landed. + func testALiveKeyKeepsItsFundingLineWhenASiblingNeverLanded() { + let live = Self.authKey(10), taken = Self.authKey(11, bound: .contractGroup(Self.appGroup)) + let intent = Self.intent([live, taken]) + let snapshot = Self.snapshot([Self.onPlatform(live), Self.onPlatform(taken, data: Data(repeating: 0x77, count: 20))]) + XCTAssertFalse(AppConnect.hasLanded(intent, in: snapshot)) + XCTAssertEqual(KeyFunding.keyIds(of: [intent], snapshot: snapshot), [10]) + XCTAssertEqual( + KeyFunding.of(intents: [intent], snapshot: snapshot, remaining: [10: 400]), + [KeyFunding(isProfileKey: false, totalBudget: 1000, remaining: 400)]) + } + + /// What the remaining-budgets query answers: decimal strings, or null + /// for a key with no budget; anything else is refused. + func testRemainingBudgetsAreReadFromTheQueryAnswer() throws { + XCTAssertEqual( + try DashConnectPlatformQueries.remainingBudgets(["10": "400", "11": NSNull()]), + [10: 400, 11: nil]) + XCTAssertThrowsError(try DashConnectPlatformQueries.remainingBudgets(["10": 400])) + XCTAssertThrowsError(try DashConnectPlatformQueries.remainingBudgets(["ten": "400"])) + } + /// A row of keys no intent names (a restore, another device's grant, the /// profile keys) is the active identity's when the projection shows them /// on it; a row only another identity's intents hold is not. diff --git a/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift b/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift index 22895ac41b..602c6e36bc 100644 --- a/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift +++ b/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift @@ -1428,6 +1428,47 @@ final class ConnectionsViewModelStatusTests: XCTestCase { /// A row that turns Refused or Disconnected while its sheet asks about /// a disconnect no longer offers one: neither the question nor its /// confirmation runs it, and the sheet says why. + /// The sheet shows a connection's details while what is left of its + /// budgets is still read, then adds the funding lines when they come. + func testTheSheetShowsItsDetailsBeforeTheFundingReadEnds() async { + let spy = ConnectionStatusSpy(rows: [Self.row("app", .active)]) + spy.funding = .read([KeyFunding(isProfileKey: false, totalBudget: 1000, remaining: 400)]) + spy.fundingDelay = 400_000_000 + let viewModel = ConnectionsViewModel(dataSource: spy, featureUnavailable: false) + await waitUntil { !viewModel.connections.isEmpty } + viewModel.showConnection(viewModel.rows[0]) + await waitUntil { viewModel.shownDetails != nil } + XCTAssertNil(viewModel.shownFundingLines, "the details do not wait for the budgets") + await waitUntil { viewModel.shownFundingLines != nil } + XCTAssertEqual(viewModel.shownFundingLines?.count, 1) + + spy.funding = .failed + spy.fundingDelay = 0 + viewModel.hideConnection() + viewModel.showConnection(viewModel.rows[0]) + await waitUntil { viewModel.shownFundingFailed } + XCTAssertNil(viewModel.shownFundingLines) + } + + /// A refresh whose funding read ends with nothing to read (no key gives + /// the app access any more, or no identity read) clears the lines and + /// any failure the earlier read showed. + func testAFundingRefreshWithNothingToReadClearsTheLines() async { + let spy = ConnectionStatusSpy(rows: [Self.row("app", .active)]) + spy.funding = .read([KeyFunding(isProfileKey: false, totalBudget: 1000, remaining: 400)]) + let viewModel = ConnectionsViewModel(dataSource: spy, featureUnavailable: false) + await waitUntil { !viewModel.connections.isEmpty } + viewModel.showConnection(viewModel.rows[0]) + await waitUntil { viewModel.shownFundingLines != nil } + + spy.funding = .notRead + // The same app and status, published again: the sheet reads anew. + spy.sendRows([DAppConnection( + id: "app", name: "app", url: "app.app", status: .active, updatedAt: Date(timeIntervalSince1970: 20))]) + await waitUntil { viewModel.shownFundingLines == nil } + XCTAssertFalse(viewModel.shownFundingFailed) + } + /// A refresh of a sheet's details that fails keeps the details shown /// and says they could not be read again. func testARefreshThatFailsKeepsTheDetailsAndSaysSo() async { @@ -1469,6 +1510,66 @@ final class ConnectionsViewModelStatusTests: XCTestCase { } } + func testTheSheetListsWhatIsLeftOfEachKey() async { + let spy = ConnectionStatusSpy(rows: [Self.row("app", .active)]) + spy.details = ConnectionDetails( + appId: "app", identityId: "identity", username: nil, basis: Self.sheetBasis(revision: 1), + connectedAt: Date(timeIntervalSince1970: 1_000)) + spy.funding = .read([ + KeyFunding(isProfileKey: false, totalBudget: 50_000_000_000, remaining: 20_000_000_000), + KeyFunding(isProfileKey: true, totalBudget: 200_000_000, remaining: nil), + KeyFunding(isProfileKey: false, totalBudget: nil, remaining: nil), + ]) + let viewModel = ConnectionsViewModel(dataSource: spy, featureUnavailable: false) + await waitUntil { !viewModel.connections.isEmpty } + viewModel.showConnection(viewModel.rows[0]) + await waitUntil { viewModel.shownFundingLines != nil } + let lines = viewModel.shownFundingLines + XCTAssertEqual(lines?.map(\.title), ["App key", "DashPay profile key", "App key"]) + let dash: (UInt64) -> String = PlatformCreditsFormatter.dashString + XCTAssertEqual(lines?[0].value, "\(dash(20_000_000_000)) left of \(dash(50_000_000_000))") + XCTAssertEqual(lines?[1].value, "Maximum of \(dash(200_000_000))", "Platform did not say what is left") + XCTAssertEqual(lines?[2].value, "No limit") + XCTAssertEqual(viewModel.shownConnectedAt, Date(timeIntervalSince1970: 1_000)) + XCTAssertEqual(spy.fundingBases, [Self.sheetBasis(revision: 1)], "read for the read the details were told from") + } + + /// A refresh told from another read of the identity drops the funding + /// lines of the earlier one, and shows those read for its own. + func testARefreshFromAnotherReadDoesNotKeepTheEarlierFundingLines() async { + let spy = ConnectionStatusSpy(rows: [Self.row("app", .active)]) + spy.details = ConnectionDetails( + appId: "app", identityId: "identity", username: nil, basis: Self.sheetBasis(revision: 1)) + spy.funding = .read([KeyFunding(isProfileKey: false, totalBudget: 1000, remaining: 400)]) + let viewModel = ConnectionsViewModel(dataSource: spy, featureUnavailable: false) + await waitUntil { !viewModel.connections.isEmpty } + viewModel.showConnection(viewModel.rows[0]) + await waitUntil { viewModel.shownFundingLines != nil } + + spy.details = ConnectionDetails( + appId: "app", identityId: "identity", username: nil, basis: Self.sheetBasis(revision: 2)) + spy.funding = .read([KeyFunding(isProfileKey: false, totalBudget: 5000, remaining: 4000)]) + spy.fundingDelay = 300_000_000 + spy.sendRows([Self.row("app", .active)]) + await waitUntil { viewModel.shownDetails?.basis == Self.sheetBasis(revision: 2) } + XCTAssertNil(viewModel.shownDetails?.keyFunding, "the lines told of the earlier read") + await waitUntil { viewModel.shownDetails?.keyFunding != nil } + XCTAssertEqual(viewModel.shownDetails?.keyFunding?.first?.totalBudget, 5000) + } + + /// A read of the identity with one app key, at `revision`. + nonisolated static func sheetBasis(revision: UInt64) -> ConnectionBasis { + let key = AppConnect.PlatformKey( + id: 10, purpose: .authentication, securityLevel: .high, keyType: .ecdsaHash160, + data: Data(repeating: 3, count: 20), readOnly: false, bound: .singleContract(Data(repeating: 1, count: 32)), + boundKnown: true, totalBudget: revision == 1 ? 1000 : 5000, expiresAt: 1_900_000_000_000, disabledAt: nil) + return ConnectionBasis( + snapshot: AppConnect.IdentitySnapshot( + identityId: Data(repeating: 2, count: 32), revision: revision, keys: [key], + platformTime: 1_800_000_000_000), + intents: [], unrecorded: [key], administeredGroups: []) + } + func testADetailsReadFromBeforeTheSheetOpenedAgainIsNotShown() async { let spy = ConnectionStatusSpy(rows: [Self.row("app", .active)]) spy.details = ConnectionDetails(appId: "app", identityId: "identity", username: "before") @@ -1563,6 +1664,12 @@ private final class ConnectionStatusSpy: DashConnectDataSource { var details: ConnectionDetails? /// Reads of the details fail, as when the identity cannot be read. var failsDetails = false + /// What the funding read answers, and how long it takes. + var funding: ConnectionFundingRead = .notRead + var fundingDelay: UInt64 = 0 + private var storedFundingBases: [ConnectionBasis] = [] + /// The bases funding was read for, in order. + var fundingBases: [ConnectionBasis] { lock.withLock { storedFundingBases } } private var storedDisconnectFailure: Error? /// Thrown by every disconnect while set, before anything runs. var disconnectFailure: Error? { @@ -1587,7 +1694,18 @@ private final class ConnectionStatusSpy: DashConnectDataSource { } if delay > 0 { try? await Task.sleep(nanoseconds: delay) } if fails { return nil } - return answer ?? ConnectionDetails(appId: id, identityId: "identity", username: "bob") + return answer ?? ConnectionDetails( + appId: id, identityId: "identity", username: "bob", + basis: ConnectionsViewModelStatusTests.sheetBasis(revision: 1)) + } + + func connectionFunding(for basis: ConnectionBasis, scope: String?) async -> ConnectionFundingRead { + let (answer, delay) = lock.withLock { + storedFundingBases.append(basis) + return (funding, fundingDelay) + } + if delay > 0 { try? await Task.sleep(nanoseconds: delay) } + return answer } func sendRows(_ value: [DAppConnection]) { rows.send(value) }