From a384ef253986ea880d1259d2b013ab7c910de9d6 Mon Sep 17 00:00:00 2001 From: Alexander Lisovik Date: Tue, 17 Oct 2023 14:42:57 +0400 Subject: [PATCH 01/12] Dapp extend session exp --- .../ConnectionDetailsView.swift | 41 ++++++++++++++++++- .../SessionRequestPresenter.swift | 2 +- .../Engine/Common/SessionEngine.swift | 6 ++- .../NonControllerSessionStateMachine.swift | 14 ++++++- .../WalletConnectSign/Sign/SignClient.swift | 9 +++- .../Types/Session/WCSession.swift | 2 +- 6 files changed, 67 insertions(+), 7 deletions(-) diff --git a/Example/WalletApp/PresentationLayer/Wallet/ConnectionDetails/ConnectionDetailsView.swift b/Example/WalletApp/PresentationLayer/Wallet/ConnectionDetails/ConnectionDetailsView.swift index 65a838b11..5174bc80e 100644 --- a/Example/WalletApp/PresentationLayer/Wallet/ConnectionDetails/ConnectionDetailsView.swift +++ b/Example/WalletApp/PresentationLayer/Wallet/ConnectionDetails/ConnectionDetailsView.swift @@ -2,7 +2,13 @@ import SwiftUI struct ConnectionDetailsView: View { @EnvironmentObject var presenter: ConnectionDetailsPresenter - + + private var dateFormatter: DateFormatter { + let formatter = DateFormatter() + formatter.dateFormat = "HH:mm:ss E, d MMM y" + return formatter + } + var body: some View { ZStack { Color.grey100 @@ -145,6 +151,39 @@ struct ConnectionDetailsView: View { .padding(.top, 30) } + VStack(alignment: .leading) { + Text("Expiry") + .font(.system(size: 15, weight: .semibold, design: .rounded)) + .foregroundColor(.whiteBackground) + .padding(.horizontal, 8) + .padding(.vertical, 5) + .background(Color.grey70) + .cornerRadius(28, corners: .allCorners) + .padding(.leading, 15) + .padding(.top, 9) + + VStack(spacing: 0) { + TagsView(items: [dateFormatter.string(from: presenter.session.expiryDate)]) { + Text($0) + .foregroundColor(.cyanBackround) + .font(.system(size: 13, weight: .semibold, design: .rounded)) + .padding(.horizontal, 8) + .padding(.vertical, 3) + .background(Color.cyanBackround.opacity(0.2)) + .cornerRadius(10, corners: .allCorners) + } + .padding(10) + } + .background(Color.whiteBackground) + .cornerRadius(20, corners: .allCorners) + .padding(.horizontal, 5) + .padding(.bottom, 5) + } + .background(Color("grey95")) + .cornerRadius(25, corners: .allCorners) + .padding(.horizontal, 20) + .padding(.top, 30) + Button { presenter.onDelete() } label: { diff --git a/Example/WalletApp/PresentationLayer/Wallet/SessionRequest/SessionRequestPresenter.swift b/Example/WalletApp/PresentationLayer/Wallet/SessionRequest/SessionRequestPresenter.swift index 2cd2fc2d8..103002dd6 100644 --- a/Example/WalletApp/PresentationLayer/Wallet/SessionRequest/SessionRequestPresenter.swift +++ b/Example/WalletApp/PresentationLayer/Wallet/SessionRequest/SessionRequestPresenter.swift @@ -15,7 +15,7 @@ final class SessionRequestPresenter: ObservableObject { var message: String { let message = try? sessionRequest.params.get([String].self) let decryptedMessage = message.map { String(data: Data(hex: $0.first ?? ""), encoding: .utf8) } - return (decryptedMessage ?? "Failed to decrypt") ?? "Failed to decrypt" + return (decryptedMessage ?? String(describing: sessionRequest.params.value)) ?? String(describing: sessionRequest.params.value) } @Published var showError = false diff --git a/Sources/WalletConnectSign/Engine/Common/SessionEngine.swift b/Sources/WalletConnectSign/Engine/Common/SessionEngine.swift index 3e6cec6bf..5cf17d9c8 100644 --- a/Sources/WalletConnectSign/Engine/Common/SessionEngine.swift +++ b/Sources/WalletConnectSign/Engine/Common/SessionEngine.swift @@ -51,8 +51,12 @@ final class SessionEngine { return sessionStore.hasSession(forTopic: topic) } + func getWCSessions() -> [WCSession] { + sessionStore.getAll() + } + func getSessions() -> [Session] { - sessionStore.getAll().map {$0.publicRepresentation()} + getWCSessions().map { $0.publicRepresentation() } } func request(_ request: Request) async throws { diff --git a/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift b/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift index c7dba0e07..32efa4312 100644 --- a/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift +++ b/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift @@ -22,7 +22,19 @@ final class NonControllerSessionStateMachine { self.logger = logger setupSubscriptions() } - + + func extend(topic: String, by ttl: Int64) async throws { + guard var session = sessionStore.getSession(forTopic: topic) else { + throw WalletConnectError.noSessionMatchingTopic(topic) + } + let protocolMethod = SessionExtendProtocolMethod() + try session.updateExpiry(by: ttl) + let newExpiry = Int64(session.expiryDate.timeIntervalSince1970 ) + sessionStore.setSession(session) + let request = RPCRequest(method: protocolMethod.method, params: SessionType.UpdateExpiryParams(expiry: newExpiry)) + try await networkingInteractor.request(request, topic: topic, protocolMethod: protocolMethod) + } + private func setupSubscriptions() { networkingInteractor.requestSubscription(on: SessionUpdateProtocolMethod()) .sink { [unowned self] (payload: RequestSubscriptionPayload) in diff --git a/Sources/WalletConnectSign/Sign/SignClient.swift b/Sources/WalletConnectSign/Sign/SignClient.swift index 57dd897a2..7c80eacc6 100644 --- a/Sources/WalletConnectSign/Sign/SignClient.swift +++ b/Sources/WalletConnectSign/Sign/SignClient.swift @@ -259,13 +259,18 @@ public final class SignClient: SignClientProtocol { try await controllerSessionStateMachine.update(topic: topic, namespaces: namespaces) } - /// For wallet to extend a session to 7 days + /// For dapp and wallet to extend a session to 7 days /// - Parameters: /// - topic: Topic of the session that is intended to be extended. public func extend(topic: String) async throws { let ttl: Int64 = Session.defaultTimeToLive - if sessionEngine.hasSession(for: topic) { + guard let session = sessionEngine.getWCSessions().first(where: { $0.topic == topic }) else { + throw WalletConnectError.noSessionMatchingTopic(topic) + } + if session.selfIsController { try await controllerSessionStateMachine.extend(topic: topic, by: ttl) + } else { + try await nonControllerSessionStateMachine.extend(topic: topic, by: ttl) } } diff --git a/Sources/WalletConnectSign/Types/Session/WCSession.swift b/Sources/WalletConnectSign/Types/Session/WCSession.swift index f9acf29e6..30d237a85 100644 --- a/Sources/WalletConnectSign/Types/Session/WCSession.swift +++ b/Sources/WalletConnectSign/Types/Session/WCSession.swift @@ -158,7 +158,7 @@ struct WCSession: SequenceObject, Equatable { mutating func updateExpiry(to expiry: Int64) throws { let newExpiryDate = Date(timeIntervalSince1970: TimeInterval(expiry)) let maxExpiryDate = Date(timeIntervalSinceNow: TimeInterval(WCSession.defaultTimeToLive)) - guard newExpiryDate >= expiryDate && newExpiryDate <= maxExpiryDate else { + guard newExpiryDate.millisecondsSince1970 >= (expiryDate.millisecondsSince1970 / 1000) && newExpiryDate <= maxExpiryDate else { throw WalletConnectError.invalidUpdateExpiryValue } self.expiryDate = newExpiryDate From 6fe5114954b8ebfbcd6a6f9d142ba1a0375aca3f Mon Sep 17 00:00:00 2001 From: Alexander Lisovik Date: Tue, 24 Oct 2023 16:38:16 +0400 Subject: [PATCH 02/12] Add SessionExtendRequester --- .../Engine/Common/SessionEngine.swift | 6 +---- .../Common/SessionExtendRequester.swift | 27 +++++++++++++++++++ .../ControllerSessionStateMachine.swift | 12 --------- .../NonControllerSessionStateMachine.swift | 14 +--------- .../WalletConnectSign/Sign/SignClient.swift | 12 ++++----- .../Sign/SignClientFactory.swift | 2 ++ .../ControllerSessionStateMachineTests.swift | 24 ++++------------- 7 files changed, 41 insertions(+), 56 deletions(-) create mode 100644 Sources/WalletConnectSign/Engine/Common/SessionExtendRequester.swift diff --git a/Sources/WalletConnectSign/Engine/Common/SessionEngine.swift b/Sources/WalletConnectSign/Engine/Common/SessionEngine.swift index 5cf17d9c8..185d0d444 100644 --- a/Sources/WalletConnectSign/Engine/Common/SessionEngine.swift +++ b/Sources/WalletConnectSign/Engine/Common/SessionEngine.swift @@ -50,13 +50,9 @@ final class SessionEngine { func hasSession(for topic: String) -> Bool { return sessionStore.hasSession(forTopic: topic) } - - func getWCSessions() -> [WCSession] { - sessionStore.getAll() - } func getSessions() -> [Session] { - getWCSessions().map { $0.publicRepresentation() } + sessionStore.getAll().map { $0.publicRepresentation() } } func request(_ request: Request) async throws { diff --git a/Sources/WalletConnectSign/Engine/Common/SessionExtendRequester.swift b/Sources/WalletConnectSign/Engine/Common/SessionExtendRequester.swift new file mode 100644 index 000000000..5b815cb14 --- /dev/null +++ b/Sources/WalletConnectSign/Engine/Common/SessionExtendRequester.swift @@ -0,0 +1,27 @@ +import Foundation + +final class SessionExtendRequester { + private let sessionStore: WCSessionStorage + private let networkingInteractor: NetworkInteracting + + init( + sessionStore: WCSessionStorage, + networkingInteractor: NetworkInteracting + ) { + self.sessionStore = sessionStore + self.networkingInteractor = networkingInteractor + } + + func extend(topic: String, by ttl: Int64) async throws { + guard var session = sessionStore.getSession(forTopic: topic) else { + throw WalletConnectError.noSessionMatchingTopic(topic) + } + + let protocolMethod = SessionExtendProtocolMethod() + try session.updateExpiry(by: ttl) + let newExpiry = Int64(session.expiryDate.timeIntervalSince1970) + sessionStore.setSession(session) + let request = RPCRequest(method: protocolMethod.method, params: SessionType.UpdateExpiryParams(expiry: newExpiry)) + try await networkingInteractor.request(request, topic: topic, protocolMethod: protocolMethod) + } +} diff --git a/Sources/WalletConnectSign/Engine/Controller/ControllerSessionStateMachine.swift b/Sources/WalletConnectSign/Engine/Controller/ControllerSessionStateMachine.swift index eb6becf93..1219ad988 100644 --- a/Sources/WalletConnectSign/Engine/Controller/ControllerSessionStateMachine.swift +++ b/Sources/WalletConnectSign/Engine/Controller/ControllerSessionStateMachine.swift @@ -35,19 +35,7 @@ final class ControllerSessionStateMachine { try await networkingInteractor.request(request, topic: topic, protocolMethod: protocolMethod) } - func extend(topic: String, by ttl: Int64) async throws { - var session = try getSession(for: topic) - let protocolMethod = SessionExtendProtocolMethod() - try validateController(session) - try session.updateExpiry(by: ttl) - let newExpiry = Int64(session.expiryDate.timeIntervalSince1970 ) - sessionStore.setSession(session) - let request = RPCRequest(method: protocolMethod.method, params: SessionType.UpdateExpiryParams(expiry: newExpiry)) - try await networkingInteractor.request(request, topic: topic, protocolMethod: protocolMethod) - } - // MARK: - Handle Response - private func setupSubscriptions() { networkingInteractor.responseSubscription(on: SessionUpdateProtocolMethod()) .sink { [unowned self] (payload: ResponseSubscriptionPayload) in diff --git a/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift b/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift index 32efa4312..c7dba0e07 100644 --- a/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift +++ b/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift @@ -22,19 +22,7 @@ final class NonControllerSessionStateMachine { self.logger = logger setupSubscriptions() } - - func extend(topic: String, by ttl: Int64) async throws { - guard var session = sessionStore.getSession(forTopic: topic) else { - throw WalletConnectError.noSessionMatchingTopic(topic) - } - let protocolMethod = SessionExtendProtocolMethod() - try session.updateExpiry(by: ttl) - let newExpiry = Int64(session.expiryDate.timeIntervalSince1970 ) - sessionStore.setSession(session) - let request = RPCRequest(method: protocolMethod.method, params: SessionType.UpdateExpiryParams(expiry: newExpiry)) - try await networkingInteractor.request(request, topic: topic, protocolMethod: protocolMethod) - } - + private func setupSubscriptions() { networkingInteractor.requestSubscription(on: SessionUpdateProtocolMethod()) .sink { [unowned self] (payload: RequestSubscriptionPayload) in diff --git a/Sources/WalletConnectSign/Sign/SignClient.swift b/Sources/WalletConnectSign/Sign/SignClient.swift index 7c80eacc6..5a173e067 100644 --- a/Sources/WalletConnectSign/Sign/SignClient.swift +++ b/Sources/WalletConnectSign/Sign/SignClient.swift @@ -109,6 +109,7 @@ public final class SignClient: SignClientProtocol { private let sessionPingService: SessionPingService private let nonControllerSessionStateMachine: NonControllerSessionStateMachine private let controllerSessionStateMachine: ControllerSessionStateMachine + private let sessionExtendRequester: SessionExtendRequester private let appProposeService: AppProposeService private let historyService: HistoryService private let cleanupService: SignCleanupService @@ -138,6 +139,7 @@ public final class SignClient: SignClientProtocol { sessionPingService: SessionPingService, nonControllerSessionStateMachine: NonControllerSessionStateMachine, controllerSessionStateMachine: ControllerSessionStateMachine, + sessionExtendRequester: SessionExtendRequester, appProposeService: AppProposeService, disconnectService: DisconnectService, historyService: HistoryService, @@ -152,6 +154,7 @@ public final class SignClient: SignClientProtocol { self.sessionPingService = sessionPingService self.nonControllerSessionStateMachine = nonControllerSessionStateMachine self.controllerSessionStateMachine = controllerSessionStateMachine + self.sessionExtendRequester = sessionExtendRequester self.appProposeService = appProposeService self.historyService = historyService self.cleanupService = cleanupService @@ -264,13 +267,8 @@ public final class SignClient: SignClientProtocol { /// - topic: Topic of the session that is intended to be extended. public func extend(topic: String) async throws { let ttl: Int64 = Session.defaultTimeToLive - guard let session = sessionEngine.getWCSessions().first(where: { $0.topic == topic }) else { - throw WalletConnectError.noSessionMatchingTopic(topic) - } - if session.selfIsController { - try await controllerSessionStateMachine.extend(topic: topic, by: ttl) - } else { - try await nonControllerSessionStateMachine.extend(topic: topic, by: ttl) + if sessionEngine.hasSession(for: topic) { + try await sessionExtendRequester.extend(topic: topic, by: ttl) } } diff --git a/Sources/WalletConnectSign/Sign/SignClientFactory.swift b/Sources/WalletConnectSign/Sign/SignClientFactory.swift index a7903a01b..079e5f87a 100644 --- a/Sources/WalletConnectSign/Sign/SignClientFactory.swift +++ b/Sources/WalletConnectSign/Sign/SignClientFactory.swift @@ -30,6 +30,7 @@ public struct SignClientFactory { let sessionEngine = SessionEngine(networkingInteractor: networkingClient, historyService: historyService, verifyContextStore: verifyContextStore, verifyClient: verifyClient, kms: kms, sessionStore: sessionStore, logger: logger) let nonControllerSessionStateMachine = NonControllerSessionStateMachine(networkingInteractor: networkingClient, kms: kms, sessionStore: sessionStore, logger: logger) let controllerSessionStateMachine = ControllerSessionStateMachine(networkingInteractor: networkingClient, kms: kms, sessionStore: sessionStore, logger: logger) + let sessionExtendRequester = SessionExtendRequester(sessionStore: sessionStore, networkingInteractor: networkingClient) let sessionTopicToProposal = CodableStore(defaults: RuntimeKeyValueStorage(), identifier: SignStorageIdentifiers.sessionTopicToProposal.rawValue) let approveEngine = ApproveEngine( networkingInteractor: networkingClient, @@ -60,6 +61,7 @@ public struct SignClientFactory { sessionPingService: sessionPingService, nonControllerSessionStateMachine: nonControllerSessionStateMachine, controllerSessionStateMachine: controllerSessionStateMachine, + sessionExtendRequester: sessionExtendRequester, appProposeService: appProposerService, disconnectService: disconnectService, historyService: historyService, diff --git a/Tests/WalletConnectSignTests/ControllerSessionStateMachineTests.swift b/Tests/WalletConnectSignTests/ControllerSessionStateMachineTests.swift index 539b335ec..f2a2a1772 100644 --- a/Tests/WalletConnectSignTests/ControllerSessionStateMachineTests.swift +++ b/Tests/WalletConnectSignTests/ControllerSessionStateMachineTests.swift @@ -6,6 +6,7 @@ import WalletConnectKMS class ControllerSessionStateMachineTests: XCTestCase { var sut: ControllerSessionStateMachine! + var sessionExtendRequester: SessionExtendRequester! var networkingInteractor: NetworkingInteractorMock! var storageMock: WCSessionStorageMock! var cryptoMock: KeyManagementServiceMock! @@ -15,6 +16,7 @@ class ControllerSessionStateMachineTests: XCTestCase { storageMock = WCSessionStorageMock() cryptoMock = KeyManagementServiceMock() sut = ControllerSessionStateMachine(networkingInteractor: networkingInteractor, kms: cryptoMock, sessionStore: storageMock, logger: ConsoleLoggerMock()) + sessionExtendRequester = SessionExtendRequester(sessionStore: storageMock, networkingInteractor: networkingInteractor) } override func tearDown() { @@ -66,33 +68,17 @@ class ControllerSessionStateMachineTests: XCTestCase { let session = WCSession.stub(isSelfController: true, expiryDate: tomorrow) storageMock.setSession(session) let twoDays = 2*Time.day - await XCTAssertNoThrowAsync(try await sut.extend(topic: session.topic, by: Int64(twoDays))) + await XCTAssertNoThrowAsync(try await sessionExtendRequester.extend(topic: session.topic, by: Int64(twoDays))) let extendedSession = storageMock.getAll().first {$0.topic == session.topic}! XCTAssertEqual(extendedSession.expiryDate.timeIntervalSinceReferenceDate, TimeTraveler.dateByAdding(days: 2).timeIntervalSinceReferenceDate, accuracy: 1) } - func testUpdateExpirySessionNotSettled() async { - let tomorrow = TimeTraveler.dateByAdding(days: 1) - let session = WCSession.stub(isSelfController: false, expiryDate: tomorrow, acknowledged: false) - storageMock.setSession(session) - let twoDays = 2*Time.day - await XCTAssertThrowsErrorAsync(try await sut.extend(topic: session.topic, by: Int64(twoDays))) - } - - func testUpdateExpiryOnNonControllerClient() async { - let tomorrow = TimeTraveler.dateByAdding(days: 1) - let session = WCSession.stub(isSelfController: false, expiryDate: tomorrow) - storageMock.setSession(session) - let twoDays = 2*Time.day - await XCTAssertThrowsErrorAsync( try await sut.extend(topic: session.topic, by: Int64(twoDays))) - } - func testUpdateExpiryTtlTooHigh() async { let tomorrow = TimeTraveler.dateByAdding(days: 1) let session = WCSession.stub(isSelfController: true, expiryDate: tomorrow) storageMock.setSession(session) let tenDays = 10*Time.day - await XCTAssertThrowsErrorAsync( try await sut.extend(topic: session.topic, by: Int64(tenDays))) + await XCTAssertThrowsErrorAsync( try await sessionExtendRequester.extend(topic: session.topic, by: Int64(tenDays))) } func testUpdateExpiryTtlTooLow() async { @@ -100,6 +86,6 @@ class ControllerSessionStateMachineTests: XCTestCase { let session = WCSession.stub(isSelfController: true, expiryDate: dayAfterTommorow) storageMock.setSession(session) let oneDay = Int64(1*Time.day) - await XCTAssertThrowsErrorAsync( try await sut.extend(topic: session.topic, by: oneDay)) + await XCTAssertThrowsErrorAsync( try await sessionExtendRequester.extend(topic: session.topic, by: oneDay)) } } From 20a5f592c241cbd67025b363d86cc80d7e6299e2 Mon Sep 17 00:00:00 2001 From: Alexander Lisovik Date: Wed, 25 Oct 2023 16:54:38 +0400 Subject: [PATCH 03/12] Add SessionExtendRequestSubscriber, SessionExtendResponseSubscriber --- .../SessionExtendRequestSubscriber.swift | 66 +++++++++++++++++++ .../SessionExtendResponseSubscriber.swift | 48 ++++++++++++++ .../ControllerSessionStateMachine.swift | 24 ------- .../NonControllerSessionStateMachine.swift | 40 ++--------- .../WalletConnectSign/Sign/SignClient.swift | 14 ++-- .../Sign/SignClientFactory.swift | 4 ++ ...onControllerSessionStateMachineTests.swift | 14 ---- 7 files changed, 134 insertions(+), 76 deletions(-) create mode 100644 Sources/WalletConnectSign/Engine/Common/SessionExtendRequestSubscriber.swift create mode 100644 Sources/WalletConnectSign/Engine/Common/SessionExtendResponseSubscriber.swift diff --git a/Sources/WalletConnectSign/Engine/Common/SessionExtendRequestSubscriber.swift b/Sources/WalletConnectSign/Engine/Common/SessionExtendRequestSubscriber.swift new file mode 100644 index 000000000..af291b26e --- /dev/null +++ b/Sources/WalletConnectSign/Engine/Common/SessionExtendRequestSubscriber.swift @@ -0,0 +1,66 @@ +import Foundation +import Combine + +final class SessionExtendRequestSubscriber { + var onExtend: ((String, Date) -> Void)? + + private let sessionStore: WCSessionStorage + private let networkingInteractor: NetworkInteracting + private var publishers = [AnyCancellable]() + private let logger: ConsoleLogging + + init( + networkingInteractor: NetworkInteracting, + sessionStore: WCSessionStorage, + logger: ConsoleLogging + ) { + self.networkingInteractor = networkingInteractor + self.sessionStore = sessionStore + self.logger = logger + + setupSubscriptions() + } +} + +// MARK: - Private functions +extension SessionExtendRequestSubscriber { + private func setupSubscriptions() { + networkingInteractor.requestSubscription(on: SessionExtendProtocolMethod()) + .sink { [unowned self] (payload: RequestSubscriptionPayload) in + onSessionUpdateExpiry(payload: payload, updateExpiryParams: payload.request) + }.store(in: &publishers) + } + + private func onSessionUpdateExpiry(payload: SubscriptionPayload, updateExpiryParams: SessionType.UpdateExpiryParams) { + let protocolMethod = SessionExtendProtocolMethod() + let topic = payload.topic + guard var session = sessionStore.getSession(forTopic: topic) else { + return respondError(payload: payload, reason: .noSessionForTopic, protocolMethod: protocolMethod) + } + guard session.peerIsController else { + return respondError(payload: payload, reason: .unauthorizedExtendRequest, protocolMethod: protocolMethod) + } + do { + try session.updateExpiry(to: updateExpiryParams.expiry) + } catch { + return respondError(payload: payload, reason: .invalidExtendRequest, protocolMethod: protocolMethod) + } + sessionStore.setSession(session) + + Task(priority: .high) { + try await networkingInteractor.respondSuccess(topic: payload.topic, requestId: payload.id, protocolMethod: protocolMethod) + } + + onExtend?(session.topic, session.expiryDate) + } + + private func respondError(payload: SubscriptionPayload, reason: SignReasonCode, protocolMethod: ProtocolMethod) { + Task(priority: .high) { + do { + try await networkingInteractor.respondError(topic: payload.topic, requestId: payload.id, protocolMethod: protocolMethod, reason: reason) + } catch { + logger.error("Respond Error failed with: \(error.localizedDescription)") + } + } + } +} diff --git a/Sources/WalletConnectSign/Engine/Common/SessionExtendResponseSubscriber.swift b/Sources/WalletConnectSign/Engine/Common/SessionExtendResponseSubscriber.swift new file mode 100644 index 000000000..a802da680 --- /dev/null +++ b/Sources/WalletConnectSign/Engine/Common/SessionExtendResponseSubscriber.swift @@ -0,0 +1,48 @@ +import Foundation +import Combine + +final class SessionExtendResponseSubscriber { + var onExtend: ((String, Date) -> Void)? + + private let sessionStore: WCSessionStorage + private let networkingInteractor: NetworkInteracting + private var publishers = [AnyCancellable]() + private let logger: ConsoleLogging + + init( + networkingInteractor: NetworkInteracting, + sessionStore: WCSessionStorage, + logger: ConsoleLogging + ) { + self.networkingInteractor = networkingInteractor + self.sessionStore = sessionStore + self.logger = logger + + setupSubscriptions() + } + + // MARK: - Handle Response + private func setupSubscriptions() { + networkingInteractor.responseSubscription(on: SessionExtendProtocolMethod()) + .sink { [unowned self] (payload: ResponseSubscriptionPayload) in + handleUpdateExpiryResponse(payload: payload) + } + .store(in: &publishers) + } + + private func handleUpdateExpiryResponse(payload: ResponseSubscriptionPayload) { + guard var session = sessionStore.getSession(forTopic: payload.topic) else { return } + switch payload.response { + case .response: + do { + try session.updateExpiry(to: payload.request.expiry) + sessionStore.setSession(session) + onExtend?(session.topic, session.expiryDate) + } catch { + logger.error("Update expiry error: \(error.localizedDescription)") + } + case .error: + logger.error("Peer failed to extend session") + } + } +} diff --git a/Sources/WalletConnectSign/Engine/Controller/ControllerSessionStateMachine.swift b/Sources/WalletConnectSign/Engine/Controller/ControllerSessionStateMachine.swift index 1219ad988..d95a2b8b1 100644 --- a/Sources/WalletConnectSign/Engine/Controller/ControllerSessionStateMachine.swift +++ b/Sources/WalletConnectSign/Engine/Controller/ControllerSessionStateMachine.swift @@ -2,9 +2,7 @@ import Foundation import Combine final class ControllerSessionStateMachine { - var onNamespacesUpdate: ((String, [String: SessionNamespace]) -> Void)? - var onExtend: ((String, Date) -> Void)? private let sessionStore: WCSessionStorage private let networkingInteractor: NetworkInteracting @@ -42,12 +40,6 @@ final class ControllerSessionStateMachine { handleUpdateResponse(payload: payload) } .store(in: &publishers) - - networkingInteractor.responseSubscription(on: SessionExtendProtocolMethod()) - .sink { [unowned self] (payload: ResponseSubscriptionPayload) in - handleUpdateExpiryResponse(payload: payload) - } - .store(in: &publishers) } private func handleUpdateResponse(payload: ResponseSubscriptionPayload) { @@ -68,22 +60,6 @@ final class ControllerSessionStateMachine { } } - private func handleUpdateExpiryResponse(payload: ResponseSubscriptionPayload) { - guard var session = sessionStore.getSession(forTopic: payload.topic) else { return } - switch payload.response { - case .response: - do { - try session.updateExpiry(to: payload.request.expiry) - sessionStore.setSession(session) - onExtend?(session.topic, session.expiryDate) - } catch { - logger.error("Update expiry error: \(error.localizedDescription)") - } - case .error: - logger.error("Peer failed to extend session") - } - } - // MARK: - Private private func getSession(for topic: String) throws -> WCSession { if let session = sessionStore.getSession(forTopic: topic) { diff --git a/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift b/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift index c7dba0e07..b371a579b 100644 --- a/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift +++ b/Sources/WalletConnectSign/Engine/NonController/NonControllerSessionStateMachine.swift @@ -2,9 +2,7 @@ import Foundation import Combine final class NonControllerSessionStateMachine { - var onNamespacesUpdate: ((String, [String: SessionNamespace]) -> Void)? - var onExtend: ((String, Date) -> Void)? private let sessionStore: WCSessionStorage private let networkingInteractor: NetworkInteracting @@ -12,10 +10,12 @@ final class NonControllerSessionStateMachine { private var publishers = [AnyCancellable]() private let logger: ConsoleLogging - init(networkingInteractor: NetworkInteracting, - kms: KeyManagementServiceProtocol, - sessionStore: WCSessionStorage, - logger: ConsoleLogging) { + init( + networkingInteractor: NetworkInteracting, + kms: KeyManagementServiceProtocol, + sessionStore: WCSessionStorage, + logger: ConsoleLogging + ) { self.networkingInteractor = networkingInteractor self.kms = kms self.sessionStore = sessionStore @@ -28,11 +28,6 @@ final class NonControllerSessionStateMachine { .sink { [unowned self] (payload: RequestSubscriptionPayload) in onSessionUpdateNamespacesRequest(payload: payload, updateParams: payload.request) }.store(in: &publishers) - - networkingInteractor.requestSubscription(on: SessionExtendProtocolMethod()) - .sink { [unowned self] (payload: RequestSubscriptionPayload) in - onSessionUpdateExpiry(payload: payload, updateExpiryParams: payload.request) - }.store(in: &publishers) } private func respondError(payload: SubscriptionPayload, reason: SignReasonCode, protocolMethod: ProtocolMethod) { @@ -72,27 +67,4 @@ final class NonControllerSessionStateMachine { onNamespacesUpdate?(session.topic, updateParams.namespaces) } - - private func onSessionUpdateExpiry(payload: SubscriptionPayload, updateExpiryParams: SessionType.UpdateExpiryParams) { - let protocolMethod = SessionExtendProtocolMethod() - let topic = payload.topic - guard var session = sessionStore.getSession(forTopic: topic) else { - return respondError(payload: payload, reason: .noSessionForTopic, protocolMethod: protocolMethod) - } - guard session.peerIsController else { - return respondError(payload: payload, reason: .unauthorizedExtendRequest, protocolMethod: protocolMethod) - } - do { - try session.updateExpiry(to: updateExpiryParams.expiry) - } catch { - return respondError(payload: payload, reason: .invalidExtendRequest, protocolMethod: protocolMethod) - } - sessionStore.setSession(session) - - Task(priority: .high) { - try await networkingInteractor.respondSuccess(topic: payload.topic, requestId: payload.id, protocolMethod: protocolMethod) - } - - onExtend?(session.topic, session.expiryDate) - } } diff --git a/Sources/WalletConnectSign/Sign/SignClient.swift b/Sources/WalletConnectSign/Sign/SignClient.swift index 5a173e067..1ea172041 100644 --- a/Sources/WalletConnectSign/Sign/SignClient.swift +++ b/Sources/WalletConnectSign/Sign/SignClient.swift @@ -110,6 +110,8 @@ public final class SignClient: SignClientProtocol { private let nonControllerSessionStateMachine: NonControllerSessionStateMachine private let controllerSessionStateMachine: ControllerSessionStateMachine private let sessionExtendRequester: SessionExtendRequester + private let sessionExtendRequestSubscriber: SessionExtendRequestSubscriber + private let sessionExtendResponseSubscriber: SessionExtendResponseSubscriber private let appProposeService: AppProposeService private let historyService: HistoryService private let cleanupService: SignCleanupService @@ -140,6 +142,8 @@ public final class SignClient: SignClientProtocol { nonControllerSessionStateMachine: NonControllerSessionStateMachine, controllerSessionStateMachine: ControllerSessionStateMachine, sessionExtendRequester: SessionExtendRequester, + sessionExtendRequestSubscriber: SessionExtendRequestSubscriber, + sessionExtendResponseSubscriber: SessionExtendResponseSubscriber, appProposeService: AppProposeService, disconnectService: DisconnectService, historyService: HistoryService, @@ -155,6 +159,8 @@ public final class SignClient: SignClientProtocol { self.nonControllerSessionStateMachine = nonControllerSessionStateMachine self.controllerSessionStateMachine = controllerSessionStateMachine self.sessionExtendRequester = sessionExtendRequester + self.sessionExtendRequestSubscriber = sessionExtendRequestSubscriber + self.sessionExtendResponseSubscriber = sessionExtendResponseSubscriber self.appProposeService = appProposeService self.historyService = historyService self.cleanupService = cleanupService @@ -402,13 +408,13 @@ public final class SignClient: SignClientProtocol { controllerSessionStateMachine.onNamespacesUpdate = { [unowned self] topic, namespaces in sessionUpdatePublisherSubject.send((topic, namespaces)) } - controllerSessionStateMachine.onExtend = { [unowned self] topic, date in - sessionExtendPublisherSubject.send((topic, date)) - } nonControllerSessionStateMachine.onNamespacesUpdate = { [unowned self] topic, namespaces in sessionUpdatePublisherSubject.send((topic, namespaces)) } - nonControllerSessionStateMachine.onExtend = { [unowned self] topic, date in + sessionExtendRequestSubscriber.onExtend = { [unowned self] topic, date in + sessionExtendPublisherSubject.send((topic, date)) + } + sessionExtendResponseSubscriber.onExtend = { [unowned self] topic, date in sessionExtendPublisherSubject.send((topic, date)) } sessionEngine.onEventReceived = { [unowned self] topic, event, chainId in diff --git a/Sources/WalletConnectSign/Sign/SignClientFactory.swift b/Sources/WalletConnectSign/Sign/SignClientFactory.swift index 079e5f87a..cfaaf355f 100644 --- a/Sources/WalletConnectSign/Sign/SignClientFactory.swift +++ b/Sources/WalletConnectSign/Sign/SignClientFactory.swift @@ -31,6 +31,8 @@ public struct SignClientFactory { let nonControllerSessionStateMachine = NonControllerSessionStateMachine(networkingInteractor: networkingClient, kms: kms, sessionStore: sessionStore, logger: logger) let controllerSessionStateMachine = ControllerSessionStateMachine(networkingInteractor: networkingClient, kms: kms, sessionStore: sessionStore, logger: logger) let sessionExtendRequester = SessionExtendRequester(sessionStore: sessionStore, networkingInteractor: networkingClient) + let sessionExtendRequestSubscriber = SessionExtendRequestSubscriber(networkingInteractor: networkingClient, sessionStore: sessionStore, logger: logger) + let sessionExtendResponseSubscriber = SessionExtendResponseSubscriber(networkingInteractor: networkingClient, sessionStore: sessionStore, logger: logger) let sessionTopicToProposal = CodableStore(defaults: RuntimeKeyValueStorage(), identifier: SignStorageIdentifiers.sessionTopicToProposal.rawValue) let approveEngine = ApproveEngine( networkingInteractor: networkingClient, @@ -62,6 +64,8 @@ public struct SignClientFactory { nonControllerSessionStateMachine: nonControllerSessionStateMachine, controllerSessionStateMachine: controllerSessionStateMachine, sessionExtendRequester: sessionExtendRequester, + sessionExtendRequestSubscriber: sessionExtendRequestSubscriber, + sessionExtendResponseSubscriber: sessionExtendResponseSubscriber, appProposeService: appProposerService, disconnectService: disconnectService, historyService: historyService, diff --git a/Tests/WalletConnectSignTests/NonControllerSessionStateMachineTests.swift b/Tests/WalletConnectSignTests/NonControllerSessionStateMachineTests.swift index aa4c917ca..7304ea2c8 100644 --- a/Tests/WalletConnectSignTests/NonControllerSessionStateMachineTests.swift +++ b/Tests/WalletConnectSignTests/NonControllerSessionStateMachineTests.swift @@ -67,20 +67,6 @@ class NonControllerSessionStateMachineTests: XCTestCase { } // MARK: - Update Expiry - - func testPeerUpdateExpirySuccess() { - let tomorrow = TimeTraveler.dateByAdding(days: 1) - let session = WCSession.stub(isSelfController: false, expiryDate: tomorrow) - storageMock.setSession(session) - let twoDaysFromNowTimestamp = Int64(TimeTraveler.dateByAdding(days: 2).timeIntervalSince1970) - - networkingInteractor.requestPublisherSubject.send((session.topic, RPCRequest.stubUpdateExpiry(expiry: twoDaysFromNowTimestamp), Data(), Date(), nil)) - let extendedSession = storageMock.getAll().first {$0.topic == session.topic}! - print(extendedSession.expiryDate) - - XCTAssertEqual(extendedSession.expiryDate.timeIntervalSince1970, TimeTraveler.dateByAdding(days: 2).timeIntervalSince1970, accuracy: 1) - } - func testPeerUpdateExpiryUnauthorized() { let tomorrow = TimeTraveler.dateByAdding(days: 1) let session = WCSession.stub(isSelfController: true, expiryDate: tomorrow) From fdf6517342b192a01d0fe5de1cb1ec124caf9400 Mon Sep 17 00:00:00 2001 From: alexander-lsvk Date: Thu, 26 Oct 2023 10:29:04 +0200 Subject: [PATCH 04/12] Set User Agent --- Sources/WalletConnectRelay/PackageConfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/WalletConnectRelay/PackageConfig.json b/Sources/WalletConnectRelay/PackageConfig.json index 7db8bf6cc..78e802ff1 100644 --- a/Sources/WalletConnectRelay/PackageConfig.json +++ b/Sources/WalletConnectRelay/PackageConfig.json @@ -1 +1 @@ -{"version": "1.9.1"} +{"version": "1.9.2"} From 324bd4506abdcf921241112446480b4ac952a426 Mon Sep 17 00:00:00 2001 From: Artur Guseinov Date: Fri, 27 Oct 2023 19:24:23 +0800 Subject: [PATCH 05/12] Timeout removed --- .../Notifications/NotificationsInteractor.swift | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/Example/WalletApp/PresentationLayer/Wallet/Notifications/NotificationsInteractor.swift b/Example/WalletApp/PresentationLayer/Wallet/Notifications/NotificationsInteractor.swift index 3eeeb8ea3..1a1bd5b8f 100644 --- a/Example/WalletApp/PresentationLayer/Wallet/Notifications/NotificationsInteractor.swift +++ b/Example/WalletApp/PresentationLayer/Wallet/Notifications/NotificationsInteractor.swift @@ -36,20 +36,12 @@ final class NotificationsInteractor { return try await withCheckedThrowingContinuation { continuation in var cancellable: AnyCancellable? cancellable = subscriptionsPublisher - .setFailureType(to: Error.self) - .timeout(10, scheduler: RunLoop.main, customError: { Errors.subscribeTimeout }) - .sink(receiveCompletion: { completion in - defer { cancellable?.cancel() } - switch completion { - case .failure(let error): continuation.resume(with: .failure(error)) - case .finished: break - } - }, receiveValue: { subscriptions in + .sink { subscriptions in guard subscriptions.contains(where: { $0.metadata.url == domain }) else { return } cancellable?.cancel() continuation.resume(with: .success(())) - }) - + } + Task { [cancellable] in do { try await Notify.instance.subscribe(appDomain: domain, account: importAccount.account) From 7d865a19162273960cded853d3cb9b0beac1791b Mon Sep 17 00:00:00 2001 From: Artur Guseinov Date: Fri, 27 Oct 2023 19:24:41 +0800 Subject: [PATCH 06/12] Always respond to subscriptionChanged --- ...ubscriptionsChangedRequestSubscriber.swift | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift index 95d92a0a1..a14c8c621 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift @@ -54,30 +54,30 @@ class NotifySubscriptionsChangedRequestSubscriber { logger.debug("Received: \(newSubscriptions.count), changed: \(subscriptions.count)") - guard subscriptions.count > 0 else { return } + if subscriptions.count > 0 { + notifyStorage.replaceAllSubscriptions(newSubscriptions, account: account) - notifyStorage.replaceAllSubscriptions(newSubscriptions, account: account) + for subscription in newSubscriptions { + let symKey = try SymmetricKey(hex: subscription.symKey) + try groupKeychainStorage.add(symKey, forKey: subscription.topic) + try kms.setSymmetricKey(symKey, for: subscription.topic) + } - for subscription in newSubscriptions { - let symKey = try SymmetricKey(hex: subscription.symKey) - try groupKeychainStorage.add(symKey, forKey: subscription.topic) - try kms.setSymmetricKey(symKey, for: subscription.topic) - } + let topics = newSubscriptions.map { $0.topic } - let topics = newSubscriptions.map { $0.topic } + try await networkingInteractor.batchSubscribe(topics: topics) - try await networkingInteractor.batchSubscribe(topics: topics) + try Task.checkCancellation() - try Task.checkCancellation() + var logProperties = ["rpcId": payload.id.string] + for (index, subscription) in newSubscriptions.enumerated() { + let key = "subscription_\(index + 1)" + logProperties[key] = subscription.topic + } - var logProperties = ["rpcId": payload.id.string] - for (index, subscription) in newSubscriptions.enumerated() { - let key = "subscription_\(index + 1)" - logProperties[key] = subscription.topic + logger.debug("Updated Subscriptions by Subscriptions Changed Request", properties: logProperties) } - logger.debug("Updated Subscriptions by Subscriptions Changed Request", properties: logProperties) - try await respond(topic: payload.topic, account: jwtPayload.account, rpcId: payload.id, notifyServerAuthenticationKey: jwtPayload.notifyServerAuthenticationKey) } } From ef69125d3d6ecbec8750f60ce8f3ab84931389e1 Mon Sep 17 00:00:00 2001 From: Artur Guseinov Date: Fri, 27 Oct 2023 19:30:06 +0800 Subject: [PATCH 07/12] appAuthenticationKey added --- Sources/WalletConnectNotify/Client/Wallet/NotifyStorage.swift | 2 +- .../Client/Wallet/NotifySubscriptionsBuilder.swift | 3 ++- .../Types/DataStructures/NotifyServerSubscription.swift | 1 + .../Types/DataStructures/NotifySubscription.swift | 1 + 4 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Sources/WalletConnectNotify/Client/Wallet/NotifyStorage.swift b/Sources/WalletConnectNotify/Client/Wallet/NotifyStorage.swift index a7e2c92b8..ab873dcf1 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/NotifyStorage.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/NotifyStorage.swift @@ -89,7 +89,7 @@ final class NotifyStorage: NotifyStoring { func updateSubscription(_ subscription: NotifySubscription, scope: [String: ScopeValue], expiry: UInt64) { let expiry = Date(timeIntervalSince1970: TimeInterval(expiry)) - let updated = NotifySubscription(topic: subscription.topic, account: subscription.account, relay: subscription.relay, metadata: subscription.metadata, scope: scope, expiry: expiry, symKey: subscription.symKey) + let updated = NotifySubscription(topic: subscription.topic, account: subscription.account, relay: subscription.relay, metadata: subscription.metadata, scope: scope, expiry: expiry, symKey: subscription.symKey, appAuthenticationKey: subscription.appAuthenticationKey) subscriptionStore.set(element: updated, for: updated.account.absoluteString) updateSubscriptionSubject.send(updated) } diff --git a/Sources/WalletConnectNotify/Client/Wallet/NotifySubscriptionsBuilder.swift b/Sources/WalletConnectNotify/Client/Wallet/NotifySubscriptionsBuilder.swift index d2c9cd582..0426ce460 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/NotifySubscriptionsBuilder.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/NotifySubscriptionsBuilder.swift @@ -24,7 +24,8 @@ class NotifySubscriptionsBuilder { metadata: config.metadata, scope: scope, expiry: subscription.expiry, - symKey: subscription.symKey + symKey: subscription.symKey, + appAuthenticationKey: subscription.appAuthenticationKey )) } catch { continue diff --git a/Sources/WalletConnectNotify/Types/DataStructures/NotifyServerSubscription.swift b/Sources/WalletConnectNotify/Types/DataStructures/NotifyServerSubscription.swift index 56ebbd352..bdce74bac 100644 --- a/Sources/WalletConnectNotify/Types/DataStructures/NotifyServerSubscription.swift +++ b/Sources/WalletConnectNotify/Types/DataStructures/NotifyServerSubscription.swift @@ -6,4 +6,5 @@ struct NotifyServerSubscription: Codable, Equatable { let scope: [String] let symKey: String let expiry: Date + let appAuthenticationKey: String } diff --git a/Sources/WalletConnectNotify/Types/DataStructures/NotifySubscription.swift b/Sources/WalletConnectNotify/Types/DataStructures/NotifySubscription.swift index cc47fce34..cb4982555 100644 --- a/Sources/WalletConnectNotify/Types/DataStructures/NotifySubscription.swift +++ b/Sources/WalletConnectNotify/Types/DataStructures/NotifySubscription.swift @@ -8,6 +8,7 @@ public struct NotifySubscription: DatabaseObject { public let scope: [String: ScopeValue] public let expiry: Date public let symKey: String + public let appAuthenticationKey: String public var databaseId: String { return topic From bf4c23f9d20f005e4a142191b472de2027b86089 Mon Sep 17 00:00:00 2001 From: Artur Guseinov Date: Fri, 27 Oct 2023 23:34:58 +0800 Subject: [PATCH 08/12] Cached dappAuthenticationKey used for delete and update methods --- .../Client/Wallet/NotifyClientFactory.swift | 4 ++-- .../DeleteNotifySubscriptionRequester.swift | 7 ++----- .../wc_notifyUpdate/NotifyUpdateRequester.swift | 7 ++----- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/Sources/WalletConnectNotify/Client/Wallet/NotifyClientFactory.swift b/Sources/WalletConnectNotify/Client/Wallet/NotifyClientFactory.swift index f04b62a14..9d0e41f4a 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/NotifyClientFactory.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/NotifyClientFactory.swift @@ -47,7 +47,7 @@ public struct NotifyClientFactory { let identityClient = IdentityClientFactory.create(keyserver: keyserverURL, keychain: keychainStorage, logger: logger) let notifyMessageSubscriber = NotifyMessageSubscriber(keyserver: keyserverURL, networkingInteractor: networkInteractor, identityClient: identityClient, notifyStorage: notifyStorage, crypto: crypto, logger: logger) let webDidResolver = NotifyWebDidResolver() - let deleteNotifySubscriptionRequester = DeleteNotifySubscriptionRequester(keyserver: keyserverURL, networkingInteractor: networkInteractor, identityClient: identityClient, webDidResolver: webDidResolver, kms: kms, logger: logger, notifyStorage: notifyStorage) + let deleteNotifySubscriptionRequester = DeleteNotifySubscriptionRequester(keyserver: keyserverURL, networkingInteractor: networkInteractor, identityClient: identityClient, kms: kms, logger: logger, notifyStorage: notifyStorage) let resubscribeService = NotifyResubscribeService(networkInteractor: networkInteractor, notifyStorage: notifyStorage, logger: logger) let notifyConfigProvider = NotifyConfigProvider(projectId: projectId, explorerHost: explorerHost) @@ -56,7 +56,7 @@ public struct NotifyClientFactory { let notifySubscribeResponseSubscriber = NotifySubscribeResponseSubscriber(networkingInteractor: networkInteractor, kms: kms, logger: logger, groupKeychainStorage: groupKeychainStorage, notifyStorage: notifyStorage, notifyConfigProvider: notifyConfigProvider) - let notifyUpdateRequester = NotifyUpdateRequester(keyserverURL: keyserverURL, webDidResolver: webDidResolver, identityClient: identityClient, networkingInteractor: networkInteractor, notifyConfigProvider: notifyConfigProvider, logger: logger, notifyStorage: notifyStorage) + let notifyUpdateRequester = NotifyUpdateRequester(keyserverURL: keyserverURL, identityClient: identityClient, networkingInteractor: networkInteractor, notifyConfigProvider: notifyConfigProvider, logger: logger, notifyStorage: notifyStorage) let notifyUpdateResponseSubscriber = NotifyUpdateResponseSubscriber(networkingInteractor: networkInteractor, logger: logger, notifyConfigProvider: notifyConfigProvider, notifyStorage: notifyStorage) diff --git a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyDelete/DeleteNotifySubscriptionRequester.swift b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyDelete/DeleteNotifySubscriptionRequester.swift index ea3281849..d0e49ef0f 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyDelete/DeleteNotifySubscriptionRequester.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyDelete/DeleteNotifySubscriptionRequester.swift @@ -7,7 +7,6 @@ class DeleteNotifySubscriptionRequester { private let keyserver: URL private let networkingInteractor: NetworkInteracting private let identityClient: IdentityClient - private let webDidResolver: NotifyWebDidResolver private let kms: KeyManagementServiceProtocol private let logger: ConsoleLogging private let notifyStorage: NotifyStorage @@ -16,7 +15,6 @@ class DeleteNotifySubscriptionRequester { keyserver: URL, networkingInteractor: NetworkInteracting, identityClient: IdentityClient, - webDidResolver: NotifyWebDidResolver, kms: KeyManagementServiceProtocol, logger: ConsoleLogging, notifyStorage: NotifyStorage @@ -24,7 +22,6 @@ class DeleteNotifySubscriptionRequester { self.keyserver = keyserver self.networkingInteractor = networkingInteractor self.identityClient = identityClient - self.webDidResolver = webDidResolver self.kms = kms self.logger = logger self.notifyStorage = notifyStorage @@ -37,10 +34,10 @@ class DeleteNotifySubscriptionRequester { else { throw Errors.notifySubscriptionNotFound} let protocolMethod = NotifyDeleteProtocolMethod() - let dappAuthenticationKey = try await webDidResolver.resolveAuthenticationKey(domain: subscription.metadata.url) + let dappAuthenticationKey = try DIDKey(did: subscription.appAuthenticationKey) let wrapper = try createJWTWrapper( - dappPubKey: DIDKey(rawData: dappAuthenticationKey), + dappPubKey: dappAuthenticationKey, reason: NotifyDeleteParams.userDisconnected.message, app: DIDWeb(host: subscription.metadata.url), account: subscription.account diff --git a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyUpdate/NotifyUpdateRequester.swift b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyUpdate/NotifyUpdateRequester.swift index 7ddb67379..104c5d31a 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyUpdate/NotifyUpdateRequester.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyUpdate/NotifyUpdateRequester.swift @@ -10,7 +10,6 @@ class NotifyUpdateRequester: NotifyUpdateRequesting { } private let keyserverURL: URL - private let webDidResolver: NotifyWebDidResolver private let identityClient: IdentityClient private let networkingInteractor: NetworkInteracting private let notifyConfigProvider: NotifyConfigProvider @@ -19,7 +18,6 @@ class NotifyUpdateRequester: NotifyUpdateRequesting { init( keyserverURL: URL, - webDidResolver: NotifyWebDidResolver, identityClient: IdentityClient, networkingInteractor: NetworkInteracting, notifyConfigProvider: NotifyConfigProvider, @@ -27,7 +25,6 @@ class NotifyUpdateRequester: NotifyUpdateRequesting { notifyStorage: NotifyStorage ) { self.keyserverURL = keyserverURL - self.webDidResolver = webDidResolver self.identityClient = identityClient self.networkingInteractor = networkingInteractor self.notifyConfigProvider = notifyConfigProvider @@ -40,10 +37,10 @@ class NotifyUpdateRequester: NotifyUpdateRequesting { guard let subscription = notifyStorage.getSubscription(topic: topic) else { throw Errors.noSubscriptionForGivenTopic } - let dappAuthenticationKey = try await webDidResolver.resolveAuthenticationKey(domain: subscription.metadata.url) + let dappAuthenticationKey = try DIDKey(did: subscription.appAuthenticationKey) let request = try createJWTRequest( - dappPubKey: DIDKey(rawData: dappAuthenticationKey), + dappPubKey: dappAuthenticationKey, subscriptionAccount: subscription.account, appDomain: subscription.metadata.url, scope: scope ) From 06266b621d6e0afe6062471dbc4ef05c65edf8c6 Mon Sep 17 00:00:00 2001 From: Artur Guseinov Date: Sat, 28 Oct 2023 00:30:05 +0800 Subject: [PATCH 09/12] SubscriptionChanged tests --- .../IntegrationTests/Push/NotifyTests.swift | 2 +- .../Client/Wallet/NotifyClient.swift | 7 ++- ...ubscriptionsChangedRequestSubscriber.swift | 9 ++- .../NotifySubscribeRequester.swift | 2 +- .../Client/Wallet/SubscriptionWatcher.swift | 60 +++++++------------ 5 files changed, 39 insertions(+), 41 deletions(-) diff --git a/Example/IntegrationTests/Push/NotifyTests.swift b/Example/IntegrationTests/Push/NotifyTests.swift index 97edfdd0a..83de217cb 100644 --- a/Example/IntegrationTests/Push/NotifyTests.swift +++ b/Example/IntegrationTests/Push/NotifyTests.swift @@ -137,7 +137,7 @@ final class NotifyTests: XCTestCase { expectation.assertForOverFulfill = false let clientB = makeWalletClient(prefix: "👐🏼 Wallet B: ") - clientB.subscriptionsPublisher.sink { subscriptions in + clientB.subscriptionChangedPublisher.sink { subscriptions in guard let subscription = subscriptions.first else { return } Task(priority: .high) { try await clientB.deleteSubscription(topic: subscription.topic) diff --git a/Sources/WalletConnectNotify/Client/Wallet/NotifyClient.swift b/Sources/WalletConnectNotify/Client/Wallet/NotifyClient.swift index 29a58e77f..b4e04c5be 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/NotifyClient.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/NotifyClient.swift @@ -78,7 +78,7 @@ public class NotifyClient { public func register(account: Account, domain: String, isLimited: Bool = false, onSign: @escaping SigningCallback) async throws { try await identityService.register(account: account, domain: domain, isLimited: isLimited, onSign: onSign) notifyAccountProvider.setAccount(account) - subscriptionWatcher.start() + try await subscriptionWatcher.start() } public func unregister(account: Account) async throws { @@ -132,6 +132,11 @@ public class NotifyClient { #if targetEnvironment(simulator) extension NotifyClient { + + public var subscriptionChangedPublisher: AnyPublisher<[NotifySubscription], Never> { + return notifySubscriptionsChangedRequestSubscriber.subscriptionChangedPublisher + } + public func register(deviceToken: String) async throws { try await pushClient.register(deviceToken: deviceToken) } diff --git a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift index a14c8c621..87825fd58 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift @@ -11,6 +11,12 @@ class NotifySubscriptionsChangedRequestSubscriber { private let notifyStorage: NotifyStorage private let notifySubscriptionsBuilder: NotifySubscriptionsBuilder + private let subscriptionChangedSubject = PassthroughSubject<[NotifySubscription], Never>() + + var subscriptionChangedPublisher: AnyPublisher<[NotifySubscription], Never> { + return subscriptionChangedSubject.eraseToAnyPublisher() + } + init( keyserver: URL, networkingInteractor: NetworkInteracting, @@ -54,7 +60,8 @@ class NotifySubscriptionsChangedRequestSubscriber { logger.debug("Received: \(newSubscriptions.count), changed: \(subscriptions.count)") - if subscriptions.count > 0 { + if subscriptions.count > 0 { + subscriptionChangedSubject.send(newSubscriptions) notifyStorage.replaceAllSubscriptions(newSubscriptions, account: account) for subscription in newSubscriptions { diff --git a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_pushSubscribe/NotifySubscribeRequester.swift b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_pushSubscribe/NotifySubscribeRequester.swift index ad5c0cee0..cc6894e86 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_pushSubscribe/NotifySubscribeRequester.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_pushSubscribe/NotifySubscribeRequester.swift @@ -36,7 +36,7 @@ class NotifySubscribeRequester { logger.debug("Subscribing for Notify, dappUrl: \(appDomain)") - let config = try await notifyConfigProvider.resolveNotifyConfig(appDomain: appDomain) + let config = await notifyConfigProvider.resolveNotifyConfig(appDomain: appDomain) let peerPublicKey = try await webDidResolver.resolveAgreementKey(domain: appDomain) let subscribeTopic = peerPublicKey.rawRepresentation.sha256().toHexString() diff --git a/Sources/WalletConnectNotify/Client/Wallet/SubscriptionWatcher.swift b/Sources/WalletConnectNotify/Client/Wallet/SubscriptionWatcher.swift index 00ae7bebc..5b8a97d36 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/SubscriptionWatcher.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/SubscriptionWatcher.swift @@ -6,16 +6,13 @@ import UIKit class SubscriptionWatcher { - private var timerCancellable: AnyCancellable? + private var timer: Timer? private var appLifecycleCancellable: AnyCancellable? private var notifyWatchSubscriptionsRequester: NotifyWatchSubscriptionsRequesting private let logger: ConsoleLogging - private let backgroundQueue = DispatchQueue(label: "com.walletconnect.subscriptionWatcher", qos: .background) private let notificationCenter: NotificationPublishing - private var watchSubscriptionsWorkItem: DispatchWorkItem? var timerInterval: TimeInterval = 5 * 60 - var debounceInterval: TimeInterval = 0.5 var onSetupTimer: (() -> Void)? init(notifyWatchSubscriptionsRequester: NotifyWatchSubscriptionsRequesting, @@ -28,57 +25,46 @@ class SubscriptionWatcher { deinit { stop() } - func start() { + func start() async throws { + setupAppLifecyclePublisher() setupTimer() - watchAppLifecycle() - watchSubscriptions() + + try await notifyWatchSubscriptionsRequester.watchSubscriptions() } func stop() { - timerCancellable?.cancel() + timer?.invalidate() appLifecycleCancellable?.cancel() - watchSubscriptionsWorkItem?.cancel() } } internal extension SubscriptionWatcher { - func watchSubscriptions() { - watchSubscriptionsWorkItem?.cancel() - - let workItem = DispatchWorkItem { [weak self] in - self?.logger.debug("Will watch subscriptions") - Task(priority: .background) { [weak self] in try await self?.notifyWatchSubscriptionsRequester.watchSubscriptions() } - } - - watchSubscriptionsWorkItem = workItem - DispatchQueue.main.asyncAfter(deadline: .now() + debounceInterval, execute: workItem) - } - - func watchAppLifecycle() { + func setupAppLifecyclePublisher() { #if os(iOS) appLifecycleCancellable = notificationCenter.publisher(for: UIApplication.willEnterForegroundNotification) .receive(on: RunLoop.main) .sink { [weak self] _ in - self?.logger.debug("Will setup Subscription Watcher after app entered foreground") - self?.setupTimer() - self?.backgroundQueue.async { - self?.watchSubscriptions() - } + guard let self else { return } + self.logger.debug("SubscriptionWatcher entered foreground event") + self.watchSubscriptions() } #endif } func setupTimer() { - onSetupTimer?() - logger.debug("Setting up Subscription Watcher timer") - timerCancellable?.cancel() - timerCancellable = Timer.publish(every: timerInterval, on: .main, in: .common) - .autoconnect() - .sink { [weak self] _ in - self?.backgroundQueue.async { - self?.watchSubscriptions() - } - } + timer?.invalidate() + timer = Timer.scheduledTimer(withTimeInterval: timerInterval, repeats: true) { [weak self] _ in + guard let self else { return } + self.logger.debug("SubscriptionWatcher scheduled event") + self.watchSubscriptions() + } + RunLoop.main.add(timer!, forMode: .common) + } + + func watchSubscriptions() { + Task(priority: .high) { + try await self.notifyWatchSubscriptionsRequester.watchSubscriptions() + } } } From e74d77073bcba400657911af31ab62e87916a0a1 Mon Sep 17 00:00:00 2001 From: Artur Guseinov Date: Sat, 28 Oct 2023 00:35:32 +0800 Subject: [PATCH 10/12] NotifyTests updated --- .../Client/Wallet/SubscriptionWatcher.swift | 2 +- .../Stubs/NotifySubscription.swift | 3 ++- .../SubscriptionWatcherTests.swift | 25 ++++++++----------- 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/Sources/WalletConnectNotify/Client/Wallet/SubscriptionWatcher.swift b/Sources/WalletConnectNotify/Client/Wallet/SubscriptionWatcher.swift index 5b8a97d36..a08c95d6b 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/SubscriptionWatcher.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/SubscriptionWatcher.swift @@ -38,7 +38,7 @@ class SubscriptionWatcher { } } -internal extension SubscriptionWatcher { +private extension SubscriptionWatcher { func setupAppLifecyclePublisher() { #if os(iOS) diff --git a/Tests/NotifyTests/Stubs/NotifySubscription.swift b/Tests/NotifyTests/Stubs/NotifySubscription.swift index 3e9a1892e..7fd10597e 100644 --- a/Tests/NotifyTests/Stubs/NotifySubscription.swift +++ b/Tests/NotifyTests/Stubs/NotifySubscription.swift @@ -15,7 +15,8 @@ extension NotifySubscription { metadata: metadata, scope: ["test": ScopeValue(id: "id", name: "name", description: "desc", enabled: true)], expiry: expiry, - symKey: symKey + symKey: symKey, + appAuthenticationKey: "did:key:z6MkpTEGT75mnz8TiguXYYVnS1GbsNCdLo72R7kUCLShTuFV" ) } } diff --git a/Tests/NotifyTests/SubscriptionWatcherTests.swift b/Tests/NotifyTests/SubscriptionWatcherTests.swift index e2d389759..a00bd7362 100644 --- a/Tests/NotifyTests/SubscriptionWatcherTests.swift +++ b/Tests/NotifyTests/SubscriptionWatcherTests.swift @@ -16,8 +16,6 @@ class SubscriptionWatcherTests: XCTestCase { mockLogger = ConsoleLoggerMock() mockNotificationCenter = MockNotificationCenter() sut = SubscriptionWatcher(notifyWatchSubscriptionsRequester: mockRequester, logger: mockLogger, notificationCenter: mockNotificationCenter) - sut.debounceInterval = 0.0001 - sut.start() } override func tearDown() { @@ -28,39 +26,36 @@ class SubscriptionWatcherTests: XCTestCase { super.tearDown() } - func testWatchSubscriptions() { + func testWatchSubscriptions() async throws { let expectation = XCTestExpectation(description: "Expect watchSubscriptions to be called") mockRequester.onWatchSubscriptions = { expectation.fulfill() } - sut.watchSubscriptions() + try await sut.start() wait(for: [expectation], timeout: 0.5) } - func testWatchAppLifecycleReactsToEnterForegroundNotification() { - let setupExpectation = XCTestExpectation(description: "Expect setupTimer to be called on app enter foreground") + func testWatchAppLifecycleReactsToEnterForegroundNotification() async throws { let watchSubscriptionsExpectation = XCTestExpectation(description: "Expect watchSubscriptions to be called on app enter foreground") - - sut.onSetupTimer = { - setupExpectation.fulfill() - } + watchSubscriptionsExpectation.expectedFulfillmentCount = 2 mockRequester.onWatchSubscriptions = { watchSubscriptionsExpectation.fulfill() } - mockNotificationCenter.post(name: UIApplication.willEnterForegroundNotification) + try await sut.start() - wait(for: [setupExpectation, watchSubscriptionsExpectation], timeout: 0.5) + await mockNotificationCenter.post(name: UIApplication.willEnterForegroundNotification) + + wait(for: [watchSubscriptionsExpectation], timeout: 0.5) } - func testTimerTriggeringWatchSubscriptionsMultipleTimes() { + func testTimerTriggeringWatchSubscriptionsMultipleTimes() async throws { sut.timerInterval = 0.0001 - sut.setupTimer() let expectation = XCTestExpectation(description: "Expect watchSubscriptions to be called multiple times") expectation.expectedFulfillmentCount = 3 @@ -69,6 +64,8 @@ class SubscriptionWatcherTests: XCTestCase { expectation.fulfill() } + try await sut.start() + wait(for: [expectation], timeout: 0.5) } } From 7fe66a2040140f0b9d15bb3c69440112c957503c Mon Sep 17 00:00:00 2001 From: Artur Guseinov Date: Sat, 28 Oct 2023 03:33:24 +0800 Subject: [PATCH 11/12] testNotifySubscriptionChanged stability --- .../IntegrationTests/Push/NotifyTests.swift | 14 ++++---- .../Client/Wallet/NotifyWebDidResolver.swift | 34 +++++++++--------- .../DeleteNotifySubscriptionRequester.swift | 6 +--- ...ubscriptionsChangedRequestSubscriber.swift | 5 +-- .../NotifyWatchSubscriptionsRequester.swift | 6 ++-- ...WatchSubscriptionsResponseSubscriber.swift | 35 ++++++++++--------- .../NotifySubscribeRequester.swift | 3 +- 7 files changed, 52 insertions(+), 51 deletions(-) diff --git a/Example/IntegrationTests/Push/NotifyTests.swift b/Example/IntegrationTests/Push/NotifyTests.swift index 83de217cb..9c9fdc96d 100644 --- a/Example/IntegrationTests/Push/NotifyTests.swift +++ b/Example/IntegrationTests/Push/NotifyTests.swift @@ -136,13 +136,13 @@ final class NotifyTests: XCTestCase { let expectation = expectation(description: "expects client B to receive subscription after both clients are registered and client A creates one") expectation.assertForOverFulfill = false + var subscription: NotifySubscription! + let clientB = makeWalletClient(prefix: "👐🏼 Wallet B: ") - clientB.subscriptionChangedPublisher.sink { subscriptions in - guard let subscription = subscriptions.first else { return } - Task(priority: .high) { - try await clientB.deleteSubscription(topic: subscription.topic) - expectation.fulfill() - } + clientB.subscriptionsPublisher.sink { subscriptions in + guard let newSubscription = subscriptions.first else { return } + subscription = newSubscription + expectation.fulfill() }.store(in: &publishers) try! await walletNotifyClientA.register(account: account, domain: gmDappDomain, onSign: sign) @@ -150,6 +150,8 @@ final class NotifyTests: XCTestCase { try! await walletNotifyClientA.subscribe(appDomain: gmDappDomain, account: account) wait(for: [expectation], timeout: InputConfig.defaultTimeout) + + try await clientB.deleteSubscription(topic: subscription.topic) } func testWalletCreatesAndUpdatesSubscription() async { diff --git a/Sources/WalletConnectNotify/Client/Wallet/NotifyWebDidResolver.swift b/Sources/WalletConnectNotify/Client/Wallet/NotifyWebDidResolver.swift index 5312e28bd..33a8449e6 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/NotifyWebDidResolver.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/NotifyWebDidResolver.swift @@ -5,23 +5,21 @@ final class NotifyWebDidResolver { private static var subscribeKey = "wc-notify-subscribe-key" private static var authenticationKey = "wc-notify-authentication-key" - func resolveAgreementKey(domain: String) async throws -> AgreementPublicKey { - let didDoc = try await resolveDidDoc(domainUrl: domain) - let subscribeKeyPath = "\(didDoc.id)#\(Self.subscribeKey)" - guard let verificationMethod = didDoc.verificationMethod.first(where: { verificationMethod in verificationMethod.id == subscribeKeyPath }) else { throw Errors.noVerificationMethodForKey } - guard verificationMethod.publicKeyJwk.crv == .X25519 else { throw Errors.unsupportedCurve} - let pubKeyBase64Url = verificationMethod.publicKeyJwk.x - return try AgreementPublicKey(base64url: pubKeyBase64Url) + func resolveDidDoc(appDomain: String) async throws -> WebDidDoc { + guard let didDocUrl = URL(string: "https://\(appDomain)/.well-known/did.json") else { throw Errors.invalidUrl } + let (data, _) = try await URLSession.shared.data(from: didDocUrl) + return try JSONDecoder().decode(WebDidDoc.self, from: data) } - // TODO - Add cache for diddocs + func resolveAgreementKey(didDoc: WebDidDoc) throws -> AgreementPublicKey { + let keypath = "\(didDoc.id)#\(Self.subscribeKey)" + let pubKeyBase64Url = try resolveKey(didDoc: didDoc, curve: .X25519, keyPath: keypath) + return try AgreementPublicKey(base64url: pubKeyBase64Url) + } - func resolveAuthenticationKey(domain: String) async throws -> Data { - let didDoc = try await resolveDidDoc(domainUrl: domain) - let authenticationKeyPath = "\(didDoc.id)#\(Self.authenticationKey)" - guard let verificationMethod = didDoc.verificationMethod.first(where: { verificationMethod in verificationMethod.id == authenticationKeyPath }) else { throw Errors.noVerificationMethodForKey } - guard verificationMethod.publicKeyJwk.crv == .Ed25519 else { throw Errors.unsupportedCurve} - let pubKeyBase64Url = verificationMethod.publicKeyJwk.x + func resolveAuthenticationKey(didDoc: WebDidDoc) throws -> Data { + let keyPath = "\(didDoc.id)#\(Self.authenticationKey)" + let pubKeyBase64Url = try resolveKey(didDoc: didDoc, curve: .Ed25519, keyPath: keyPath) guard let raw = Data(base64url: pubKeyBase64Url) else { throw Errors.invalidBase64urlString } return raw } @@ -36,9 +34,9 @@ private extension NotifyWebDidResolver { case unsupportedCurve } - func resolveDidDoc(domainUrl: String) async throws -> WebDidDoc { - guard let didDocUrl = URL(string: "https://\(domainUrl)/.well-known/did.json") else { throw Errors.invalidUrl } - let (data, _) = try await URLSession.shared.data(from: didDocUrl) - return try JSONDecoder().decode(WebDidDoc.self, from: data) + func resolveKey(didDoc: WebDidDoc, curve: WebDidDoc.PublicKeyJwk.Curve, keyPath: String) throws -> String { + guard let verificationMethod = didDoc.verificationMethod.first(where: { verificationMethod in verificationMethod.id == keyPath }) else { throw Errors.noVerificationMethodForKey } + guard verificationMethod.publicKeyJwk.crv == curve else { throw Errors.unsupportedCurve } + return verificationMethod.publicKeyJwk.x } } diff --git a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyDelete/DeleteNotifySubscriptionRequester.swift b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyDelete/DeleteNotifySubscriptionRequester.swift index d0e49ef0f..a94e86420 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyDelete/DeleteNotifySubscriptionRequester.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyDelete/DeleteNotifySubscriptionRequester.swift @@ -54,11 +54,7 @@ class DeleteNotifySubscriptionRequester { logger.debug("Subscription removed, topic: \(topic)") kms.deleteSymmetricKey(for: topic) - } - - - - + } } private extension DeleteNotifySubscriptionRequester { diff --git a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift index 87825fd58..18c8bbc31 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifySubscriptionsChanged/NotifySubscriptionsChangedRequestSubscriber.swift @@ -53,7 +53,9 @@ class NotifySubscriptionsChangedRequestSubscriber { let oldSubscriptions = notifyStorage.getSubscriptions(account: account) let newSubscriptions = try await notifySubscriptionsBuilder.buildSubscriptions(jwtPayload.subscriptions) - + + subscriptionChangedSubject.send(newSubscriptions) + try Task.checkCancellation() let subscriptions = oldSubscriptions.difference(from: newSubscriptions) @@ -61,7 +63,6 @@ class NotifySubscriptionsChangedRequestSubscriber { logger.debug("Received: \(newSubscriptions.count), changed: \(subscriptions.count)") if subscriptions.count > 0 { - subscriptionChangedSubject.send(newSubscriptions) notifyStorage.replaceAllSubscriptions(newSubscriptions, account: account) for subscription in newSubscriptions { diff --git a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyWatchSubscriptions/NotifyWatchSubscriptionsRequester.swift b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyWatchSubscriptions/NotifyWatchSubscriptionsRequester.swift index 72702c588..3b38ad939 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyWatchSubscriptions/NotifyWatchSubscriptionsRequester.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyWatchSubscriptions/NotifyWatchSubscriptionsRequester.swift @@ -41,8 +41,10 @@ class NotifyWatchSubscriptionsRequester: NotifyWatchSubscriptionsRequesting { logger.debug("Watching subscriptions") - let notifyServerPublicKey = try await webDidResolver.resolveAgreementKey(domain: notifyHost) - let notifyServerAuthenticationKey = try await webDidResolver.resolveAuthenticationKey(domain: notifyHost) + let didDoc = try await webDidResolver.resolveDidDoc(appDomain: notifyHost) + let notifyServerPublicKey = try webDidResolver.resolveAgreementKey(didDoc: didDoc) + let notifyServerAuthenticationKey = try webDidResolver.resolveAuthenticationKey(didDoc: didDoc) + let notifyServerAuthenticationDidKey = DIDKey(rawData: notifyServerAuthenticationKey) let watchSubscriptionsTopic = notifyServerPublicKey.rawRepresentation.sha256().toHexString() diff --git a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyWatchSubscriptions/NotifyWatchSubscriptionsResponseSubscriber.swift b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyWatchSubscriptions/NotifyWatchSubscriptionsResponseSubscriber.swift index 298932dec..55323843e 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyWatchSubscriptions/NotifyWatchSubscriptionsResponseSubscriber.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_notifyWatchSubscriptions/NotifyWatchSubscriptionsResponseSubscriber.swift @@ -49,27 +49,28 @@ class NotifyWatchSubscriptionsResponseSubscriber { logger.debug("Received: \(newSubscriptions.count), changed: \(subscriptions.count)") - guard subscriptions.count > 0 else { return } - // TODO: unsubscribe for oldSubscriptions topics that are not included in new subscriptions - notifyStorage.replaceAllSubscriptions(newSubscriptions, account: account) - - for subscription in newSubscriptions { - let symKey = try SymmetricKey(hex: subscription.symKey) - try groupKeychainStorage.add(symKey, forKey: subscription.topic) - try kms.setSymmetricKey(symKey, for: subscription.topic) - } + if subscriptions.count > 0 { + // TODO: unsubscribe for oldSubscriptions topics that are not included in new subscriptions + notifyStorage.replaceAllSubscriptions(newSubscriptions, account: account) - try await networkingInteractor.batchSubscribe(topics: newSubscriptions.map { $0.topic }) + for subscription in newSubscriptions { + let symKey = try SymmetricKey(hex: subscription.symKey) + try groupKeychainStorage.add(symKey, forKey: subscription.topic) + try kms.setSymmetricKey(symKey, for: subscription.topic) + } - try Task.checkCancellation() + try await networkingInteractor.batchSubscribe(topics: newSubscriptions.map { $0.topic }) - var logProperties = [String: String]() - for (index, subscription) in newSubscriptions.enumerated() { - let key = "subscription_\(index + 1)" - logProperties[key] = subscription.topic - } + try Task.checkCancellation() - logger.debug("Updated Subscriptions with Watch Subscriptions Update, number of subscriptions: \(newSubscriptions.count)", properties: logProperties) + var logProperties = [String: String]() + for (index, subscription) in newSubscriptions.enumerated() { + let key = "subscription_\(index + 1)" + logProperties[key] = subscription.topic + } + + logger.debug("Updated Subscriptions with Watch Subscriptions Update, number of subscriptions: \(newSubscriptions.count)", properties: logProperties) + } } } diff --git a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_pushSubscribe/NotifySubscribeRequester.swift b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_pushSubscribe/NotifySubscribeRequester.swift index cc6894e86..32a875b43 100644 --- a/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_pushSubscribe/NotifySubscribeRequester.swift +++ b/Sources/WalletConnectNotify/Client/Wallet/ProtocolEngine/wc_pushSubscribe/NotifySubscribeRequester.swift @@ -38,7 +38,8 @@ class NotifySubscribeRequester { let config = await notifyConfigProvider.resolveNotifyConfig(appDomain: appDomain) - let peerPublicKey = try await webDidResolver.resolveAgreementKey(domain: appDomain) + let didDoc = try await webDidResolver.resolveDidDoc(appDomain: appDomain) + let peerPublicKey = try webDidResolver.resolveAgreementKey(didDoc: didDoc) let subscribeTopic = peerPublicKey.rawRepresentation.sha256().toHexString() let keysY = try generateAgreementKeys(peerPublicKey: peerPublicKey) From 7be0a4b037e64c8e37c6fc96281498cec1f045da Mon Sep 17 00:00:00 2001 From: Artur Guseinov Date: Mon, 30 Oct 2023 02:56:39 +0800 Subject: [PATCH 12/12] APNS icon --- Example/PNDecryptionService/Info.plist | 25 +++-- .../NotificationService.swift | 105 +++++++++++++++--- Example/WalletApp/Other/Info.plist | 4 + Example/WalletApp/WalletApp.entitlements | 2 + .../WalletApp/WalletAppRelease.entitlements | 2 + 5 files changed, 113 insertions(+), 25 deletions(-) diff --git a/Example/PNDecryptionService/Info.plist b/Example/PNDecryptionService/Info.plist index 57421ebf9..cb9e830fd 100644 --- a/Example/PNDecryptionService/Info.plist +++ b/Example/PNDecryptionService/Info.plist @@ -1,13 +1,20 @@ - - NSExtension - - NSExtensionPointIdentifier - com.apple.usernotifications.service - NSExtensionPrincipalClass - $(PRODUCT_MODULE_NAME).NotificationService - - + + NSExtension + + NSExtensionAttributes + + IntentsSupported + + INSendMessageIntent + + + NSExtensionPointIdentifier + com.apple.usernotifications.service + NSExtensionPrincipalClass + $(PRODUCT_MODULE_NAME).NotificationService + + diff --git a/Example/PNDecryptionService/NotificationService.swift b/Example/PNDecryptionService/NotificationService.swift index 50023dd13..70232ec62 100644 --- a/Example/PNDecryptionService/NotificationService.swift +++ b/Example/PNDecryptionService/NotificationService.swift @@ -1,42 +1,115 @@ import UserNotifications import WalletConnectNotify -import os +import Intents class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? - var bestAttemptContent: UNMutableNotificationContent? + var bestAttemptContent: UNNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler - bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) - if let bestAttemptContent = bestAttemptContent { - let topic = bestAttemptContent.userInfo["topic"] as! String - let ciphertext = bestAttemptContent.userInfo["blob"] as! String - NSLog("Push decryption, topic=%@", topic) + self.bestAttemptContent = request.content + + if let content = bestAttemptContent, + let topic = content.userInfo["topic"] as? String, + let ciphertext = content.userInfo["blob"] as? String { + do { let service = NotifyDecryptionService(groupIdentifier: "group.com.walletconnect.sdk") let pushMessage = try service.decryptMessage(topic: topic, ciphertext: ciphertext) - bestAttemptContent.title = pushMessage.title - bestAttemptContent.body = pushMessage.body - contentHandler(bestAttemptContent) - return + let updatedContent = try handle(content: content, pushMessage: pushMessage, topic: topic) + + let mutableContent = updatedContent.mutableCopy() as! UNMutableNotificationContent + mutableContent.title = pushMessage.title + mutableContent.body = pushMessage.body + + contentHandler(mutableContent) } catch { - NSLog("Push decryption, error=%@", error.localizedDescription) - bestAttemptContent.title = "" - bestAttemptContent.body = error.localizedDescription + let mutableContent = content.mutableCopy() as! UNMutableNotificationContent + mutableContent.title = "Error" + mutableContent.body = error.localizedDescription + + contentHandler(mutableContent) } - contentHandler(bestAttemptContent) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. - if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { + if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } } +} + +private extension NotificationService { + + func handle(content: UNNotificationContent, pushMessage: NotifyMessage, topic: String) throws -> UNNotificationContent { + let iconUrl = try pushMessage.icon.asURL() + + let senderThumbnailImageData = try Data(contentsOf: iconUrl) + let senderThumbnailImageFileUrl = try downloadAttachment(data: senderThumbnailImageData, fileName: iconUrl.lastPathComponent) + let senderThumbnailImageFileData = try Data(contentsOf: senderThumbnailImageFileUrl) + let senderAvatar = INImage(imageData: senderThumbnailImageFileData) + + var personNameComponents = PersonNameComponents() + personNameComponents.nickname = pushMessage.title + + let senderPerson = INPerson( + personHandle: INPersonHandle(value: topic, type: .unknown), + nameComponents: personNameComponents, + displayName: pushMessage.title, + image: senderAvatar, + contactIdentifier: nil, + customIdentifier: topic, + isMe: false, + suggestionType: .none + ) + + let selfPerson = INPerson( + personHandle: INPersonHandle(value: "0", type: .unknown), + nameComponents: nil, + displayName: nil, + image: nil, + contactIdentifier: nil, + customIdentifier: nil, + isMe: true, + suggestionType: .none + ) + + let incomingMessagingIntent = INSendMessageIntent( + recipients: [selfPerson], + outgoingMessageType: .outgoingMessageText, + content: pushMessage.body, + speakableGroupName: nil, + conversationIdentifier: pushMessage.type, + serviceName: nil, + sender: senderPerson, + attachments: [] + ) + + incomingMessagingIntent.setImage(senderAvatar, forParameterNamed: \.sender) + + let interaction = INInteraction(intent: incomingMessagingIntent, response: nil) + interaction.direction = .incoming + interaction.donate(completion: nil) + + return try content.updating(from: incomingMessagingIntent) + } + + func downloadAttachment(data: Data, fileName: String) throws -> URL { + let fileManager = FileManager.default + let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString + let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true) + + try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil) + let fileURL = tmpSubFolderURL.appendingPathComponent(fileName) + try data.write(to: fileURL) + + return fileURL + } } diff --git a/Example/WalletApp/Other/Info.plist b/Example/WalletApp/Other/Info.plist index 2f0f15d26..25606209f 100644 --- a/Example/WalletApp/Other/Info.plist +++ b/Example/WalletApp/Other/Info.plist @@ -2,6 +2,10 @@ + NSUserActivityTypes + + INSendMessageIntent + CFBundleIconName AppIcon CFBundleURLTypes diff --git a/Example/WalletApp/WalletApp.entitlements b/Example/WalletApp/WalletApp.entitlements index 2dccdcca9..46de0afbc 100644 --- a/Example/WalletApp/WalletApp.entitlements +++ b/Example/WalletApp/WalletApp.entitlements @@ -4,6 +4,8 @@ aps-environment development + com.apple.developer.usernotifications.communication + com.apple.security.application-groups group.com.walletconnect.sdk diff --git a/Example/WalletApp/WalletAppRelease.entitlements b/Example/WalletApp/WalletAppRelease.entitlements index 315a4dbfc..7028e40d9 100644 --- a/Example/WalletApp/WalletAppRelease.entitlements +++ b/Example/WalletApp/WalletAppRelease.entitlements @@ -4,6 +4,8 @@ aps-environment production + com.apple.developer.usernotifications.communication + com.apple.security.application-groups group.com.walletconnect.sdk