Skip to content

Commit

Permalink
Merge branch 'develop' into native-socket
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-lsvk committed Sep 12, 2023
2 parents 1bc4842 + 7a3afdb commit 2340bb3
Show file tree
Hide file tree
Showing 26 changed files with 241 additions and 190 deletions.
6 changes: 3 additions & 3 deletions Example/IntegrationTests/Push/NotifyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ final class NotifyTests: XCTestCase {
}.store(in: &publishers)

try! await walletNotifyClient.register(account: account, onSign: sign)
try! await walletNotifyClient.subscribe(metadata: metadata, account: account, onSign: sign)
try! await walletNotifyClient.subscribe(metadata: metadata, account: account)

wait(for: [expectation], timeout: InputConfig.defaultTimeout)
}
Expand All @@ -113,7 +113,7 @@ final class NotifyTests: XCTestCase {
let metadata = AppMetadata(name: "GM Dapp", description: "", url: gmDappUrl, icons: [])
let updateScope: Set<String> = ["alerts"]
try! await walletNotifyClient.register(account: account, onSign: sign)
try! await walletNotifyClient.subscribe(metadata: metadata, account: account, onSign: sign)
try! await walletNotifyClient.subscribe(metadata: metadata, account: account)
walletNotifyClient.newSubscriptionPublisher
.sink { [unowned self] subscription in
Task(priority: .high) {
Expand Down Expand Up @@ -142,7 +142,7 @@ final class NotifyTests: XCTestCase {

let metadata = AppMetadata(name: "GM Dapp", description: "", url: gmDappUrl, icons: [])
try! await walletNotifyClient.register(account: account, onSign: sign)
try! await walletNotifyClient.subscribe(metadata: metadata, account: account, onSign: sign)
try! await walletNotifyClient.subscribe(metadata: metadata, account: account)

walletNotifyClient.newSubscriptionPublisher
.sink { subscription in
Expand Down
2 changes: 1 addition & 1 deletion Example/PNDecryptionService/NotificationService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class NotificationService: UNNotificationServiceExtension {
let ciphertext = bestAttemptContent.userInfo["blob"] as! String
NSLog("Push decryption, topic=%@", topic)
do {
let service = NotifyDecryptionService()
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ final class ConfigurationService {
account: importAccount.account,
bip44: DefaultBIP44Provider(),
config: [.chatEnabled: false, .settingsEnabled: false],
groupIdentifier: "group.com.walletconnect.sdk",
environment: BuildConfiguration.shared.apnsEnvironment,
crypto: DefaultCryptoProvider(),
onSign: importAccount.onSign
Expand Down
15 changes: 15 additions & 0 deletions Sources/WalletConnectNetworking/NetworkInteracting.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ public protocol NetworkInteracting {
on request: ProtocolMethod
) -> AnyPublisher<ResponseSubscriptionErrorPayload<Request>, Never>

func subscribeOnRequest<RequestParams: Codable>(
protocolMethod: ProtocolMethod,
requestOfType: RequestParams.Type,
errorHandler: ErrorHandler?,
subscription: @escaping (RequestSubscriptionPayload<RequestParams>) async throws -> Void
)

func subscribeOnResponse<Request: Codable, Response: Codable>(
protocolMethod: ProtocolMethod,
requestOfType: Request.Type,
responseOfType: Response.Type,
errorHandler: ErrorHandler?,
subscription: @escaping (ResponseSubscriptionPayload<Request, Response>) async throws -> Void
)

func getClientId() throws -> String
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/WalletConnectNetworking/NetworkingClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import Combine

public protocol NetworkingClient {
var socketConnectionStatusPublisher: AnyPublisher<SocketConnectionStatus, Never> { get }
var logsPublisher: AnyPublisher<Log, Never> {get}
var logsPublisher: AnyPublisher<Log, Never> { get }
func setLogging(level: LoggingLevel)
func connect() throws
func disconnect(closeCode: URLSessionWebSocketTask.CloseCode) throws
Expand Down
37 changes: 37 additions & 0 deletions Sources/WalletConnectNetworking/NetworkingInteractor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,43 @@ public class NetworkingInteractor: NetworkInteracting {
rpcHistory.deleteAll(forTopics: topics)
}

public func subscribeOnRequest<RequestParams: Codable>(
protocolMethod: ProtocolMethod,
requestOfType: RequestParams.Type,
errorHandler: ErrorHandler?,
subscription: @escaping (RequestSubscriptionPayload<RequestParams>) async throws -> Void
) {
requestSubscription(on: protocolMethod)
.sink { (payload: RequestSubscriptionPayload<RequestParams>) in
Task(priority: .high) {
do {
try await subscription(payload)
} catch {
errorHandler?.handle(error: error)
}
}
}.store(in: &publishers)
}

public func subscribeOnResponse<Request: Codable, Response: Codable>(
protocolMethod: ProtocolMethod,
requestOfType: Request.Type,
responseOfType: Response.Type,
errorHandler: ErrorHandler?,
subscription: @escaping (ResponseSubscriptionPayload<Request, Response>) async throws -> Void
) {
responseSubscription(on: protocolMethod)
.sink { (payload: ResponseSubscriptionPayload<Request, Response>) in
Task(priority: .high) {
do {
try await subscription(payload)
} catch {
errorHandler?.handle(error: error)
}
}
}.store(in: &publishers)
}

public func requestSubscription<RequestParams: Codable>(on request: ProtocolMethod) -> AnyPublisher<RequestSubscriptionPayload<RequestParams>, Never> {
return requestPublisher
.filter { rpcRequest in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ class DeleteNotifySubscriptionSubscriber {
private let networkingInteractor: NetworkInteracting
private let kms: KeyManagementServiceProtocol
private let logger: ConsoleLogging
private var publishers = [AnyCancellable]()
private let notifyStorage: NotifyStorage

init(networkingInteractor: NetworkInteracting,
Expand All @@ -21,14 +20,13 @@ class DeleteNotifySubscriptionSubscriber {
}

private func subscribeForDeleteSubscription() {
let protocolMethod = NotifyDeleteProtocolMethod()
networkingInteractor.requestSubscription(on: protocolMethod)
.sink { [unowned self] (payload: RequestSubscriptionPayload<NotifyDeleteResponsePayload.Wrapper>) in

guard let (_, _) = try? NotifyDeleteResponsePayload.decodeAndVerify(from: payload.request)
else { fatalError() /* TODO: Handle error */ }

logger.debug("Peer deleted subscription")
}.store(in: &publishers)
networkingInteractor.subscribeOnRequest(
protocolMethod: NotifyDeleteProtocolMethod(),
requestOfType: NotifyDeleteResponsePayload.Wrapper.self,
errorHandler: logger
) { [unowned self] payload in
let (_, _) = try NotifyDeleteResponsePayload.decodeAndVerify(from: payload.request)
logger.debug("Peer deleted subscription")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ public class NotifyDecryptionService {
self.serializer = serializer
}

public init() {
let keychainStorage = GroupKeychainStorage(serviceIdentifier: "group.com.walletconnect.sdk")
public init(groupIdentifier: String) {
let keychainStorage = GroupKeychainStorage(serviceIdentifier: groupIdentifier)
let kms = KeyManagementService(keychain: keychainStorage)
self.serializer = Serializer(kms: kms, logger: ConsoleLogger(prefix: "🔐", loggingLevel: .off))
}
Expand Down
8 changes: 2 additions & 6 deletions Sources/WalletConnectNotify/Client/Wallet/NotifyClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@ public class NotifyClient {
return notifyStorage.newSubscriptionPublisher
}

public var subscriptionErrorPublisher: AnyPublisher<Error, Never> {
return notifySubscribeResponseSubscriber.subscriptionErrorPublisher
}

public var deleteSubscriptionPublisher: AnyPublisher<String, Never> {
return notifyStorage.deleteSubscriptionPublisher
}
Expand Down Expand Up @@ -89,8 +85,8 @@ public class NotifyClient {
logger.setLogging(level: level)
}

public func subscribe(metadata: AppMetadata, account: Account, onSign: @escaping SigningCallback) async throws {
try await notifySubscribeRequester.subscribe(metadata: metadata, account: account, onSign: onSign)
public func subscribe(metadata: AppMetadata, account: Account) async throws {
try await notifySubscribeRequester.subscribe(metadata: metadata, account: account)
}

public func update(topic: String, scope: Set<String>) async throws {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import Foundation

public struct NotifyClientFactory {

public static func create(networkInteractor: NetworkInteracting, pairingRegisterer: PairingRegisterer, pushClient: PushClient, crypto: CryptoProvider) -> NotifyClient {
public static func create(groupIdentifier: String, networkInteractor: NetworkInteracting, pairingRegisterer: PairingRegisterer, pushClient: PushClient, crypto: CryptoProvider) -> NotifyClient {
let logger = ConsoleLogger(prefix: "🔔",loggingLevel: .debug)
let keyValueStorage = UserDefaults.standard
let keyserverURL = URL(string: "https://keys.walletconnect.com")!
let keychainStorage = KeychainStorage(serviceIdentifier: "com.walletconnect.sdk")
let groupKeychainService = GroupKeychainStorage(serviceIdentifier: "group.com.walletconnect.sdk")
let groupKeychainService = GroupKeychainStorage(serviceIdentifier: groupIdentifier)

return NotifyClientFactory.create(
keyserverURL: keyserverURL,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ class NotifyMessageSubscriber {
private let notifyStorage: NotifyStorage
private let crypto: CryptoProvider
private let logger: ConsoleLogging
private var publishers = [AnyCancellable]()
private let notifyMessagePublisherSubject = PassthroughSubject<NotifyMessageRecord, Never>()

public var notifyMessagePublisher: AnyPublisher<NotifyMessageRecord, Never> {
Expand All @@ -26,45 +25,42 @@ class NotifyMessageSubscriber {
}

private func subscribeForNotifyMessages() {
let protocolMethod = NotifyMessageProtocolMethod()
networkingInteractor.requestSubscription(on: protocolMethod)
.sink { [unowned self] (payload: RequestSubscriptionPayload<NotifyMessagePayload.Wrapper>) in
networkingInteractor.subscribeOnRequest(
protocolMethod: NotifyMessageProtocolMethod(),
requestOfType: NotifyMessagePayload.Wrapper.self,
errorHandler: logger
) { [unowned self] payload in
logger.debug("Received Notify Message on topic: \(payload.topic)", properties: ["topic": payload.topic])

logger.debug("Received Notify Message on topic: \(payload.topic)", properties: ["topic": payload.topic])
let (messagePayload, claims) = try NotifyMessagePayload.decodeAndVerify(from: payload.request)
logger.debug("Decoded Notify Message: \(payload.topic)", properties: ["topic": payload.topic, "messageBody": messagePayload.message.body, "messageTitle": messagePayload.message.title, "publishedAt": payload.publishedAt.description, "id": payload.id.string])
let dappPubKey = try DIDKey(did: claims.iss)
let messageData = try JSONEncoder().encode(messagePayload.message)

Task(priority: .high) {
let (messagePayload, claims) = try NotifyMessagePayload.decodeAndVerify(from: payload.request)
logger.debug("Decoded Notify Message: \(payload.topic)", properties: ["topic": payload.topic, "messageBody": messagePayload.message.body, "messageTitle": messagePayload.message.title, "publishedAt": payload.publishedAt.description, "id": payload.id.string])
let dappPubKey = try DIDKey(did: claims.iss)
let messageData = try JSONEncoder().encode(messagePayload.message)
let record = NotifyMessageRecord(id: payload.id.string, topic: payload.topic, message: messagePayload.message, publishedAt: payload.publishedAt)
notifyStorage.setMessage(record)
notifyMessagePublisherSubject.send(record)

let record = NotifyMessageRecord(id: payload.id.string, topic: payload.topic, message: messagePayload.message, publishedAt: payload.publishedAt)
notifyStorage.setMessage(record)
notifyMessagePublisherSubject.send(record)
let receiptPayload = NotifyMessageReceiptPayload(
keyserver: keyserver, dappPubKey: dappPubKey,
messageHash: crypto.keccak256(messageData).toHexString(),
app: messagePayload.app
)

let receiptPayload = NotifyMessageReceiptPayload(
keyserver: keyserver, dappPubKey: dappPubKey,
messageHash: crypto.keccak256(messageData).toHexString(),
app: messagePayload.app
)
let wrapper = try identityClient.signAndCreateWrapper(
payload: receiptPayload,
account: messagePayload.account
)

let wrapper = try identityClient.signAndCreateWrapper(
payload: receiptPayload,
account: messagePayload.account
)
let response = RPCResponse(id: payload.id, result: wrapper)

let response = RPCResponse(id: payload.id, result: wrapper)

try await networkingInteractor.respond(
topic: payload.topic,
response: response,
protocolMethod: NotifyMessageProtocolMethod()
)

logger.debug("Sent Notify Message Response on topic: \(payload.topic)", properties: ["topic" : payload.topic, "messageBody": messagePayload.message.body, "messageTitle": messagePayload.message.title, "id": payload.id.string, "result": wrapper.jwtString])
}

}.store(in: &publishers)
try await networkingInteractor.respond(
topic: payload.topic,
response: response,
protocolMethod: NotifyMessageProtocolMethod()
)

logger.debug("Sent Notify Message Response on topic: \(payload.topic)", properties: ["topic" : payload.topic, "messageBody": messagePayload.message.body, "messageTitle": messagePayload.message.title, "id": payload.id.string, "result": wrapper.jwtString])
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,29 +30,30 @@ private extension NotifyUpdateResponseSubscriber {
}

func subscribeForUpdateResponse() {
let protocolMethod = NotifyUpdateProtocolMethod()
networkingInteractor.responseSubscription(on: protocolMethod)
.sink {[unowned self] (payload: ResponseSubscriptionPayload<NotifyUpdatePayload.Wrapper, NotifyUpdateResponsePayload.Wrapper>) in
Task(priority: .high) {
logger.debug("Received Notify Update response")
networkingInteractor.subscribeOnResponse(
protocolMethod: NotifyUpdateProtocolMethod(),
requestOfType: NotifyUpdatePayload.Wrapper.self,
responseOfType: NotifyUpdateResponsePayload.Wrapper.self,
errorHandler: logger
) { [unowned self] payload in
logger.debug("Received Notify Update response")

let subscriptionTopic = payload.topic
let subscriptionTopic = payload.topic

let (requestPayload, requestClaims) = try NotifyUpdatePayload.decodeAndVerify(from: payload.request)
let (_, _) = try NotifyUpdateResponsePayload.decodeAndVerify(from: payload.response)
let (requestPayload, requestClaims) = try NotifyUpdatePayload.decodeAndVerify(from: payload.request)
let (_, _) = try NotifyUpdateResponsePayload.decodeAndVerify(from: payload.response)

let scope = try await buildScope(selected: requestPayload.scope, dappUrl: requestPayload.dappUrl)
let scope = try await buildScope(selected: requestPayload.scope, dappUrl: requestPayload.dappUrl)

guard let oldSubscription = notifyStorage.getSubscription(topic: subscriptionTopic) else {
logger.debug("NotifyUpdateResponseSubscriber Subscription does not exist")
return
}
guard let oldSubscription = notifyStorage.getSubscription(topic: subscriptionTopic) else {
logger.debug("NotifyUpdateResponseSubscriber Subscription does not exist")
return
}

notifyStorage.updateSubscription(oldSubscription, scope: scope, expiry: requestClaims.exp)
notifyStorage.updateSubscription(oldSubscription, scope: scope, expiry: requestClaims.exp)

logger.debug("Updated Subscription")
}
}.store(in: &publishers)
logger.debug("Updated Subscription")
}
}

func buildScope(selected: String, dappUrl: String) async throws -> [String: ScopeValue] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class NotifySubscribeRequester {
self.dappsMetadataStore = dappsMetadataStore
}

@discardableResult func subscribe(metadata: AppMetadata, account: Account, onSign: @escaping SigningCallback) async throws -> NotifySubscriptionPayload.Wrapper {
@discardableResult func subscribe(metadata: AppMetadata, account: Account) async throws -> NotifySubscriptionPayload.Wrapper {

let dappUrl = metadata.url

Expand Down
Loading

0 comments on commit 2340bb3

Please sign in to comment.