diff --git a/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift b/DashWallet/Sources/Models/DashConnect/AppConnectLogin.swift index 6e6741912e..fab7dd6219 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 @@ -199,6 +204,21 @@ enum AppConnect { return (0 ... UInt32.max).first { !taken.contains($0) } } + /// 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 && $0.isUnconfirmed }.flatMap { grant -> [UInt32] in + // 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] + }) + } + /// 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( @@ -252,7 +272,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) @@ -420,9 +440,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], @@ -439,8 +459,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 @@ -448,10 +468,26 @@ enum AppConnect { } } - /// Confirms the unconfirmed records of `identityId` whose key the + /// 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 - /// 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 +497,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 @@ -469,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 @@ -673,20 +756,58 @@ 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 /// 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 + /// 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] + /// 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: 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 + /// lands. + var replacesApprovedRow: Bool? = nil + } + /// 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 5b6db6f56f..94ca93a100 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,115 @@ extension AppConnect { .sorted() } + /// 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 [] } + 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 + /// 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 { + 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 + /// 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 @@ -884,8 +1000,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 @@ -962,10 +1079,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, @@ -974,8 +1093,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 @@ -983,6 +1102,356 @@ 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 + /// `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 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 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 + 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 + } + } + + /// 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 } } + } + + /// 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 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 + } + + /// 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 + /// 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 + /// 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. + /// - 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. + /// + /// 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. + /// + /// 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], + 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 + guard key.data == expected.data else { return .cannotLand } + guard key.disabledAt == nil else { + if expected.purpose == .authentication { offAuthCount += 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 + } + // 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 + && UInt32(bitPattern: $0.keyId) != expected.keyId + } + } + 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` 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 + /// 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 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. + static func settlePendingV2Registrations( + in grants: inout [AppConnectGrant], + identityId: String, + currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], + identityRevision: UInt64, + bindings: [KeyBinding] + ) -> (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 } + let replaced = showsDisabled(pending.disabledKeyIds, in: currentIdentityPublicKeys) + ? pending.retiredGrantKeys : [] + let outcome = pendingV2Outcome( + of: pending, currentIdentityPublicKeys: currentIdentityPublicKeys, + identityRevision: identityRevision, bindings: bindings) + switch outcome { + case .landed: + var settled = grant + settled.pendingUpdate = nil + settled.unconfirmedKeyHash160 = nil + confirmed.append(settled) + retired.formUnion(replaced) + case .landedAndOff, .cannotLand: + if outcome == .landedAndOff { retired.formUnion(replaced) } + if heldKeyIds(heldBy: grant, in: currentIdentityPublicKeys, bindings: bindings).isEmpty { + 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) + } + + /// 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 + /// 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], + bindings: [KeyBinding] + ) -> Set { + 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 isPlaced(expected, in: bindings) { + 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) + } + + /// 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, when the plan sets an expiry, one still ahead + /// 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. + 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 + } + /// 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 { @@ -990,14 +1459,18 @@ 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 /// 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. @@ -1012,7 +1485,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/DashConnectModels.swift b/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift index 98627bce8f..abfdcf4f04 100644 --- a/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift +++ b/DashWallet/Sources/Models/DashConnect/DashConnectModels.swift @@ -155,9 +155,19 @@ 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 offers a disconnect like an active one. The disconnect +/// 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 case active + case confirming init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() diff --git a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift index 8edeeaa646..176b9ab8dd 100644 --- a/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift +++ b/DashWallet/Sources/Models/DashConnect/PlatformDashConnectDataSource.swift @@ -84,6 +84,8 @@ enum DashConnectPlatformError: LocalizedError, Equatable { case loginUnresolved case grantNotRecorded case noFreeKeyId + case tooManyKeysToReplace + case earlierApprovalPending case otherIdentitiesNotChecked case registrationPending case appConnectEncryptionKeyChanged @@ -182,6 +184,14 @@ 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.", + comment: "DashConnect") case .approvalOutOfDate: return NSLocalizedString( "The details of this sign-in changed while it was on screen. Check them and approve again.", @@ -623,7 +633,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, @@ -635,7 +646,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 @@ -1110,10 +1123,10 @@ 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, - modelContainer: context.modelContainer, in: stores) + identityId: identityId, currentIdentityPublicKeys: currentPublicKeys, identityRevision: currentRevision, + context: context, in: stores) func isGrantForRequest(_ grant: AppConnectGrant) -> Bool { grant.identityId == identityId && grant.appContractId == appContractId && grant.values.appEphemeralPubKeyHash == requestHash @@ -1153,7 +1166,15 @@ 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, + // 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) || $0.isPendingV2 }, + identityId: identityId) + ) else { throw DashConnectPlatformError.noFreeKeyId } let budget = terms.budgetCredits @@ -1182,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. @@ -1202,29 +1226,20 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { } Self.logger.info("🔗 DASHCONNECT :: registering session key") do { - try await signer.withAdditionalSigningKeys([ - (publicKey: sessionKeyHash160, privateKey: sessionPrivateKey), - ]) { - try await context.wallet.updateIdentity( - identityId: context.identityId, - addPublicKeys: [key], - 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 @@ -1237,6 +1252,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") @@ -1322,9 +1348,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, @@ -1376,12 +1401,28 @@ 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 - /// 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 @@ -1464,8 +1505,15 @@ 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, identityRevision: currentRevision, + 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 { @@ -1502,11 +1550,30 @@ 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), - 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 @@ -1633,98 +1700,153 @@ 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 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) } 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, !AppConnect.hasUnplacedPendingKey( + superseded, currentIdentityPublicKeys: currentPublicKeys, bindings: bindings + // 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 } - let disable = Array(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, connectionId: connectionId, keeping: reused, - currentIdentityPublicKeys: currentPublicKeys - ).prefix(AppConnect.maxKeysDisabledPerUpdate)) - // 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) - let retiredGrantKeys = Set(superseded.filter { !$0.keyIds.contains(where: liveAfterUpdate.contains) }.map(\.key)) + 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 + // 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)) - 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) - } + if let pending = pendingRetry?.pendingUpdate { + // 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 + // 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, 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 + } + let registered = encryptionSlots.indices.filter { encryptionSlots[$0].keyId == nil } + 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: added.map { authKeys[$0].publicKeyHash160 }, + registeredEncryptionKeys: registered.map { encryptionKey($0).publicKey } + ) else { + // The keys this approval derives are not the ones the earlier + // 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) + 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() @@ -1740,20 +1862,24 @@ 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( + // 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, appContractId: appId, documentId: nil, @@ -1764,28 +1890,275 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { publishedAt: now(), additionalKeyIds: Array(grantedKeyIds.dropFirst()), connectionId: connectionId, - encryptionKeyIds: sentEncryptionKeyIds + encryptionKeyIds: encryptionSlots.compactMap(\.keyId) ) - grants.append(new) - return new - } - let connection = Self.makeConnection( preview: consent, status: .active, updatedAt: now(), loginKind: .oneQR) + let modelContainer = context.modelContainer + 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(), + replacesApprovedRow: previousRow?.status == .approved + || (previousRow?.status == .confirming && stores.grants.load().contains { + $0.appContractId == appId && $0.pendingUpdate?.replacesApprovedRow == true + })) + } + let grant = try await Self.registerAppConnectV2Grant( + record, + add: add, + disable: disable, + retiredGrantKeys: retiredGrantKeys, + grants: stores.grants, + 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 + ) + } + }, + readHeldRevision: { try Self.heldRevision(context: context) }, + reread: { + guard let read = try? await refreshedIdentityKeysAndRevision(context: context), + let bindings = try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer) + else { return nil } + return (read.keys, read.revision, bindings) + }, + pause: { _ in try? await Task.sleep(nanoseconds: 3_000_000_000) }, + onDropped: { remaining in + guard let bindings = try? Self.storedKeyBindings(identityId: identityId, modelContainer: modelContainer) + else { return false } + await showRowsAfterDropping( + [record], grants: remaining, bindings: bindings, context: context, in: stores) + return true + } + ) + + // From here the keys are on the identity. await updateRows(in: stores) { rows in 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 + } + // One more read settles the identity's records still waiting for + // 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 }) { + 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 } 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, 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 + /// 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`, 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 + /// 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 (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. + /// + /// 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, + showRow: () async -> Void, + submit: () async throws -> Void, + readHeldRevision: () throws -> UInt64, + reread: () async -> ( + keys: [ManagedIdentity.IdentityPublicKeyInfo], revision: UInt64, bindings: [AppConnect.KeyBinding] + )?, + pause: (Int) 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") + 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. + } 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 landed(retiring: Bool = true) -> [AppConnectGrant] { + var all = grants.load() + if retiring { + AppConnect.markKeysDisabled(in: &all) { retiredGrantKeys.contains($0.key) && !$0.isUnconfirmed } + } + return all + } + 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 + let confirmed = all[index] + 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 { + 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) } + guard let view = await reread() else { continue } + let disabled = AppConnect.showsDisabled(disable, in: view.keys) + 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") + return confirm() + } + continue + } + let outcome = AppConnect.pendingV2Outcome( + 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") + return confirm() + case .landed: + // 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 + // 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(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(retiring: disabled) : grants.load() + all.removeAll { $0.key == record.key } + // 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 + } + } + 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. @@ -2031,11 +2404,8 @@ 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) } await markActive(pendingConnection, in: authorized.stores) @@ -2072,17 +2442,31 @@ 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`, 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. private func confirmRegistrations( identityId: String, currentIdentityPublicKeys: [ManagedIdentity.IdentityPublicKeyInfo], - modelContainer: ModelContainer, - in stores: Stores + identityRevision: UInt64, + context: Context, + in stores: Stores, + bindings knownBindings: [AppConnect.KeyBinding]? = nil ) async { 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)) ?? [] + // 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: context.modelContainer)) + let bindings = readBindings ?? [] if stores.grants.load().contains(where: { $0.identityId == identityId && $0.isUnconfirmed }) { let confirmed = updateGrants(in: stores) { grants in AppConnect.confirmRegistrations( @@ -2093,15 +2477,234 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { Self.logger.info("🔗 DASHCONNECT :: \(confirmed.count, privacy: .public) unconfirmed session key(s) found on the identity") } } + // 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, + 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") + } + // 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: grants, bindings: readBindings, context: context, in: stores) + } + stores.grants.save(grants) + } 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() + 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) + } + } + // 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) + } + } + } + + /// 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 + /// of. + private func showRowsAfterDropping( + _ 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.rowsAfterConfirming(appIds: appIds, in: rows, at: confirmedAt) + Self.rowsAfterDropping( + 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) + 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 + /// 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 and its revision. Returns the keys + /// read, or nil when the read failed. + private func settleAfterOwnUpdate( + context: Context, + stores: Stores + ) 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 + /// 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; 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( + appIds: Set, + restoringApproved: Set = [], + keeping: Set = [], + grants: [AppConnectGrant], + bindings: [AppConnect.KeyBinding], + rows: [DAppConnection] + ) -> [DAppConnection] { + rows.compactMap { row in + // 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 }) { + 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 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 + // disconnect, and connects nothing by itself. + let appContract = decodeIdentifier(row.id) + // 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 + }) 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) } } @@ -2132,13 +2735,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 @@ -2348,11 +2945,6 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { try await gated { try await disconnectInTurn(id: id, scope: scope) } } - /// 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)) - } private func disconnectInTurn(id: String, scope: String?) async throws -> DashConnectDisconnectResult { guard let stores = await showActiveWalletRows() else { @@ -2373,7 +2965,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) } var result = DashConnectDisconnectResult() if rowIsOneQR || hasGrants { @@ -2497,24 +3089,46 @@ 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 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: 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, 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 }) { + 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. /// @@ -2590,13 +3204,14 @@ 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 } 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. @@ -2618,8 +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, - modelContainer: context.modelContainer, in: stores) + 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)) // 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. @@ -2629,7 +3247,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: @@ -2667,7 +3285,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 @@ -2698,7 +3316,27 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { currentIdentityPublicKeys: currentPublicKeys, twoQRAuthenticationKeyHash160: checksUnrecordedKeys ? nil : twoQRKeys.authenticationPublicKeyHash160 ) - let recordedKeyIds = Self.recordedKeyIds(of: identityId, in: stores) + // 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. + // The keys it adds that the store places as added are its too. + let waiting = stores.grants.load().filter { pendingV2.contains($0.key) } + let resentByWaiting = AppConnect.waitingKeyIds(waiting, bindings: bindings) + let resentLive = AppConnect.liveGrantedKeyIds(in: currentPublicKeys).intersection(resentByWaiting) + // 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 + } + }) else { + throw DashConnectPlatformError.identityKeysOutOfDate + } + keyIds = Array(Set(keyIds).union(resentLive)).sorted() + let recordedKeyIds = AppConnect.recordedKeyIds(of: identityId, grants: stores.grants.load(), bindings: bindings) 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 @@ -2757,12 +3395,23 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { // (a live key no record names whose bound the store cannot read, a // stored one the view lacks, a record the store cannot read), none // of them is touched, and the app's own keys still go. - // 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 turned off - // here like any other. + // A v2 record still waiting for its update names the keys it sends + // again and the ones it adds that the store places + // (`AppConnect.recordedKeyIds`), so another app's waiting profile key + // 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 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: 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 + } let completesHere = (!keyIds.isEmpty || !granted.isEmpty) && heldOnAnotherIdentity == false - && reasonHeldElsewhere(heldOnAnotherIdentity: false) == nil + && reasonHeldElsewhere(heldOnAnotherIdentity: false) == nil && !waitingHoldsOtherKeys var profileKeysOff: [UInt32] = [] var profileKeysUnchecked = false if completesHere { @@ -2781,6 +3430,19 @@ 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 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 @@ -2788,11 +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") - // The reload writes the disabled keys to the store. The keys are - // off either way. - if mayStillLand.isEmpty { - _ = try? await refreshedIdentityPublicKeys(context: context) - } + // 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 @@ -2816,7 +3476,29 @@ 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 by what it shows + // 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. @@ -2832,6 +3514,38 @@ final class PlatformDashConnectDataSource: DashConnectDataSource { signer: signer ) } + 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. 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 } + 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), + AppConnect.showsWaitingKeys(stillWaiting, in: keysAfterUpdate, bindings: bindingsAfter), + stillWaiting.allSatisfy({ + 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 + } + 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()) } @@ -2847,14 +3561,22 @@ 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) { - try await context.wallet.updateIdentity( - identityId: context.identityId, - disablePublicKeyIds: Array(keyIds[start ..< min(start + AppConnect.maxKeysDisabledPerUpdate, keyIds.count)]), - signer: signer - ) + let batch = Array(keyIds[start ..< min(start + AppConnect.maxKeysDisabledPerUpdate, keyIds.count)]) + try await updateIdentity(disable: batch, context: context, signer: signer) } } + /// An identity update DashConnect sends outside a v2 approval. + 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) + } + /// 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. @@ -2884,59 +3606,86 @@ 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: Self.recordedKeyIds(of: otherIdentityId, in: context.stores), - 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: 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, + identityIndex: UInt32, + bindings: [AppConnect.KeyBinding], + grants: [AppConnectGrant], + context: Context + ) async -> Bool? { + do { + if AppConnect.holdsLiveSessionKey(appContractId: appContractId, bindings: bindings) { return true } + 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( + 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 + && !recorded.contains($0.keyId) + }) + // 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, @@ -3443,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) { @@ -3455,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( @@ -4015,3 +4773,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/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 cb1138f005..d2ceb0eb02 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 ومسح بيانات السلسلة لهذه الشبكة عند التشغيل التالي للتطبيق، ثم إعادة تنزيلها وإعادة فحص المرشّحات من ذلك الارتفاع. تحتفظ الجلسة الحالية بحدّ الفحص القديم — أغلق التطبيق وافتحه من جديد لتبدأ."; @@ -6229,6 +6230,8 @@ "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."; +"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 0997874e63..e18a76fbf9 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 и изчиства данните на веригата за тази мрежа при следващото стартиране на приложението, изтегля ги отново и сканира филтрите наново от тази височина. Текущата сесия запазва стария си праг на сканиране — затворете и отворете приложението отново, за да започне."; @@ -6229,6 +6230,8 @@ "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."; +"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 fe271fe9ce..8dd87a22af 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 ea46780ece..ee0257776f 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 541ef20bd6..4889ebe130 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 5efea37d2d..5ca14ae7e3 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."; @@ -6227,6 +6228,8 @@ "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."; +"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 f7ed9d59b2..e6b74ae876 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 και εκκαθαρίζει τα δεδομένα αλυσίδας αυτού του δικτύου κατά την επόμενη εκκίνηση της εφαρμογής, τα κατεβάζει ξανά και σαρώνει εκ νέου τα φίλτρα από εκείνο το ύψος. Η τρέχουσα συνεδρία διατηρεί το παλιό της κατώφλι σάρωσης — κλείστε και ανοίξτε ξανά την εφαρμογή για να ξεκινήσει."; @@ -6227,6 +6228,8 @@ "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."; +"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 a4a0bbfe05..e0ae09613b 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 */ @@ -6121,6 +6122,8 @@ "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."; +"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 85e149cdfb..2a460a48d2 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 a9f3fdfa0c..bfedac8edf 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."; @@ -6227,6 +6228,8 @@ "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."; +"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 4647c289e1..37ba3e844e 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 a2adeaa4b4..25c52999e9 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 را ذخیره می‌کند و در اجرای بعدی برنامه داده‌های زنجیره این شبکه را پاک کرده، دوباره دانلود می‌کند و فیلترها را از آن ارتفاع بازپویش می‌کند. نشست جاری کف پویش قبلی خود را نگه می‌دارد — برنامه را ببندید و دوباره باز کنید تا آغاز شود."; @@ -6227,6 +6228,8 @@ "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."; +"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 837e4bc388..c0f4b6c711 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 ebb45da784..096fb268d8 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."; @@ -6227,6 +6228,8 @@ "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."; +"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 0abe6dbd2a..d0f5ec9040 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."; @@ -6227,6 +6228,8 @@ "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."; +"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 09f233575b..2dd0da1b1c 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 e57a4afc68..f2cc66747a 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 869c1c1056..2c9f2cb405 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."; @@ -6227,6 +6228,8 @@ "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."; +"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 84f1c833bd..f5d244dc77 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."; @@ -6227,6 +6228,8 @@ "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."; +"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 f254730250..afd5b869d8 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 が保存され、次回のアプリ起動時にこのネットワークのチェーンデータが消去されて再ダウンロードされ、そのブロック高からフィルターが再スキャンされます。実行中のセッションは以前のスキャン下限を保持します。アプリを終了して開き直すと開始されます。"; @@ -6227,6 +6228,8 @@ "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."; +"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 f45ea73914..c6e38ccee3 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가 저장되고, 다음 앱 실행 시 이 네트워크의 체인 데이터가 지워진 뒤 다시 다운로드되어 해당 높이부터 필터를 다시 스캔합니다. 실행 중인 세션은 기존 스캔 하한을 유지합니다. 앱을 종료했다가 다시 열면 시작됩니다."; @@ -6227,6 +6228,8 @@ "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."; +"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 73c3d17f75..0d373d7b21 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 и ги чисти податоците од синџирот на оваа мрежа при следното стартување на апликацијата, ги презема повторно и ги прескенира филтрите од таа височина. Тековната сесија го задржува стариот праг на скенирање — затворете и повторно отворете ја апликацијата за да започне."; @@ -6229,6 +6230,8 @@ "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."; +"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 6264633bdc..524e545f64 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 66c0040f27..4d7d91b8fb 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 97bcfe25c9..2dedbca0b2 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."; @@ -6227,6 +6228,8 @@ "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."; +"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 5412a6055c..5890209d3c 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ąć."; @@ -6227,6 +6228,8 @@ "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."; +"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 4e9bb5f04a..0831a6e4ec 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."; @@ -6227,6 +6228,8 @@ "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."; +"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 0e8230a88c..92c2ed3258 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 703eeb7fe7..15548665a5 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 и очистит данные блокчейна этой сети при следующем запуске приложения, после чего они будут загружены заново, а фильтры пересканированы с этой высоты. Текущая сессия сохранит прежнюю границу сканирования — закройте и снова откройте приложение, чтобы начать."; @@ -6227,6 +6228,8 @@ "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."; +"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 a7d6c4a93a..5c514cf3d6 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."; @@ -6227,6 +6228,8 @@ "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."; +"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 3bf497d86f..f500c913be 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 064983e5b7..55f9f85456 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 9041bb4e67..a9ef299f28 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ë."; @@ -6229,6 +6230,8 @@ "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."; +"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 06e89b8d00..1fccbc511b 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 e447a0a5d6..77ecf1d5d7 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 7de13d1468..f22282afbe 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 และล้างข้อมูลเชนของเครือข่ายนี้เมื่อเปิดแอปครั้งถัดไป แล้วดาวน์โหลดใหม่และสแกนตัวกรองใหม่จากความสูงนั้น เซสชันที่กำลังทำงานอยู่จะยังใช้ขอบล่างการสแกนเดิม — ปิดแล้วเปิดแอปใหม่เพื่อเริ่ม"; @@ -6227,6 +6228,8 @@ "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."; +"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 ff12c142f1..9c560ce636 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."; @@ -6227,6 +6228,8 @@ "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."; +"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 371fa76fd0..f917124576 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 та очистить дані ланцюжка цієї мережі під час наступного запуску застосунку, після чого їх буде завантажено заново, а фільтри пересканує з цієї висоти. Поточний сеанс збереже стару межу сканування — закрийте та знову відкрийте застосунок, щоб почати."; @@ -6227,6 +6228,8 @@ "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."; +"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 bff79a1f94..c088178858 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."; @@ -6229,6 +6230,8 @@ "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."; +"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 aec64335b4..e5c5bc9c90 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,并在下次启动应用时清除该网络的链数据,重新下载并从该高度重新扫描过滤器。当前会话仍沿用旧的扫描下限——退出并重新打开应用即可开始。"; @@ -6229,6 +6230,8 @@ "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."; +"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 911d3caa59..b16f11be6d 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,並在下次啟動應用程式時清除該網絡的鏈資料,重新下載並從該高度重新掃描過濾器。目前的工作階段仍沿用舊的掃描下限——結束並重新開啟應用程式即可開始。"; @@ -6229,6 +6230,8 @@ "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."; +"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 b7a3fb65a3..40c13a35ec 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,并在下次启动应用时清除该网络的链数据,重新下载并从该高度重新扫描过滤器。当前会话仍沿用旧的扫描下限——退出并重新打开应用即可开始。"; @@ -6227,6 +6228,8 @@ "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."; +"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 4f0dda2804..51ca3c5589 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,並在下次啟動應用程式時清除該網絡的鏈資料,重新下載並從該高度重新掃描過濾器。目前的工作階段仍沿用舊的掃描下限——結束並重新開啟應用程式即可開始。"; @@ -6227,6 +6228,8 @@ "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."; +"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 45e227e9bc..aa0f059bd6 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. @@ -473,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]) @@ -1035,7 +1050,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 +1071,42 @@ 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") + 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() { + 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() { @@ -1153,6 +1200,1111 @@ final class AppConnectV2LoginTests: XCTestCase { } } +// 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, + 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: (expiresAt ?? added.expiresAt).map { Int64(bitPattern: $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 + } + + /// 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, + 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, identityRevision: identityRevision, + bindings: bindings ?? added.map(stored)) + } + + 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 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) + 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() { + 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)]), .landedAndOff, + "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 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]) + // 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) + 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() { + 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 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") + 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)], + 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") + + var landedOff = [old, pending] + _ = AppConnect.settlePendingV2Registrations( + in: &landedOff, identityId: "identity", + currentIdentityPublicKeys: [Self.onIdentity(key, disabled: true), Self.key(3)], + identityRevision: Self.revision, bindings: [Self.stored(key)]) + 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") + 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") + 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() { + 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)), + ], + identityRevision: Self.revision, bindings: [Self.stored(landedKey)]) + + 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 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.heldKeyIds(heldBy: record, in: [resentLive, taken], bindings: placed), [5]) + XCTAssertEqual(AppConnect.heldKeyIds(heldBy: record, in: [Self.onIdentity(added)], bindings: placed), [8]) + XCTAssertEqual( + 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)], identityRevision: Self.revision, bindings: [otherBound]).dropped.map(\.key), + [record.key]) + XCTAssertEqual( + 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.heldKeyIds(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, identityRevision: Self.revision, 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], identityRevision: Self.revision, bindings: []) + 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], identityRevision: Self.revision, 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, identityRevision: Self.revision, 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) + 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") + 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)], + 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") + } + + 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), + ] + 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)] + 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]) + 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") + 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 { + 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) + 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() { + 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, isV2AuthKeyShaped: true)], + rows: [row(.confirming)]).map(\.status), + [.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), [], + "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), + [.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( + 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") + 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)], + rows: [row(.confirming)]) + XCTAssertEqual(twoQRKeyLive.map(\.status), [.approved], "the two-QR login's live key is that row's") + } +} + +// 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 + var heldReads = 0 + } + + private static func register( + _ record: AppConnectGrant, + add: [ManagedPlatformWallet.IdentityPubkey], + disable: [UInt32] = [], + retiring: Set = [], + store: MemoryGrantStore, + 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 + guard !remaining.isEmpty, let view = remaining.removeFirst() else { return nil } + return (view.keys, identityRevision, view.bindings) + }, + pause: { calls.pauses.append($0) }, + onDropped: { _ in + calls.dropped += 1 + return rowsJudged + }) + } + + 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") + 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") + } + + 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 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(calls.heldReads, 0, "a record that adds nothing notes no revision") + 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 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 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 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() + 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 testARecordWhoseRowsCannotBeJudgedIsKept() 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) + } + 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) + } + + 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]) + 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() + 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) + } +} + private extension AppConnect.KeyBinding { func disabled() -> AppConnect.KeyBinding { var binding = self diff --git a/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift b/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift index 051c26be97..48630e0245 100644 --- a/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift +++ b/DashWalletTests/DashConnect/PlatformDashConnectDataSourceTests.swift @@ -2741,12 +2741,28 @@ 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"), + (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"), ] { @@ -2920,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