Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Auth, Sign] #485 remove pairing #486

Merged
merged 14 commits into from
Sep 5, 2022
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ let package = Package(
targets: ["WalletConnectRouter"]),
.library(
name: "WalletConnectNetworking",
targets: ["WalletConnectNetworking"]),
targets: ["WalletConnectNetworking"])
],
dependencies: [
.package(url: "https://github.com/flypaper0/Web3.swift", .branch("feature/eip-155"))
Expand Down
8 changes: 7 additions & 1 deletion Sources/Auth/AuthClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public class AuthClient {
private var authRequestPublisherSubject = PassthroughSubject<AuthRequest, Never>()
private let appPairService: AppPairService
private let appRequestService: AppRequestService
private let deletePairingService: DeletePairingService
private let appRespondSubscriber: AppRespondSubscriber
private let walletPairService: WalletPairService
private let walletRequestSubscriber: WalletRequestSubscriber
Expand All @@ -61,6 +62,7 @@ public class AuthClient {
walletPairService: WalletPairService,
walletRequestSubscriber: WalletRequestSubscriber,
walletRespondService: WalletRespondService,
deletePairingService: DeletePairingService,
account: Account?,
pendingRequestsProvider: PendingRequestsProvider,
cleanupService: CleanupService,
Expand All @@ -80,7 +82,7 @@ public class AuthClient {
self.logger = logger
self.pairingStorage = pairingStorage
self.socketConnectionStatusPublisher = socketConnectionStatusPublisher

self.deletePairingService = deletePairingService
setUpPublishers()
}

Expand Down Expand Up @@ -135,6 +137,10 @@ public class AuthClient {
try await walletRespondService.respondError(requestId: requestId)
}

public func disconnect(topic: String) async throws {
try await deletePairingService.delete(topic: topic)
}

/// Query pending authentication requests
/// - Returns: Pending authentication requests
public func getPendingRequests() throws -> [AuthRequest] {
Expand Down
3 changes: 2 additions & 1 deletion Sources/Auth/AuthClientFactory.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,14 @@ public struct AuthClientFactory {
let walletRespondService = WalletRespondService(networkingInteractor: networkingInteractor, logger: logger, kms: kms, rpcHistory: history)
let pendingRequestsProvider = PendingRequestsProvider(rpcHistory: history)
let cleanupService = CleanupService(pairingStore: pairingStore, kms: kms)
let deletePairingService = DeletePairingService(networkingInteractor: networkingInteractor, kms: kms, pairingStorage: pairingStore, logger: logger)

return AuthClient(appPairService: appPairService,
appRequestService: appRequestService,
appRespondSubscriber: appRespondSubscriber,
walletPairService: walletPairService,
walletRequestSubscriber: walletRequestSubscriber,
walletRespondService: walletRespondService,
walletRespondService: walletRespondService, deletePairingService: deletePairingService,
account: account,
pendingRequestsProvider: pendingRequestsProvider,
cleanupService: cleanupService,
Expand Down
34 changes: 34 additions & 0 deletions Sources/Auth/AuthProtocolMethod.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import Foundation
import WalletConnectNetworking

enum AuthProtocolMethod: String, ProtocolMethod {
case authRequest = "wc_authRequest"
case pairingDelete = "wc_pairingDelete"
case pairingPing = "wc_pairingPing"

var method: String {
return self.rawValue
}

var requestTag: Int {
switch self {
case .authRequest:
return 3000
case .pairingDelete:
return 1000
case .pairingPing:
return 1002
}
}

var responseTag: Int {
switch self {
case .authRequest:
return 3001
case .pairingDelete:
return 1001
case .pairingPing:
return 1003
}
}
}
2 changes: 1 addition & 1 deletion Sources/Auth/Services/App/AppRequestService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ actor AppRequestService {
let request = RPCRequest(method: "wc_authRequest", params: params)
try kms.setPublicKey(publicKey: pubKey, for: responseTopic)
logger.debug("AppRequestService: Subscribibg for response topic: \(responseTopic)")
try await networkingInteractor.requestNetworkAck(request, topic: topic, tag: AuthProtocolMethod.request.tag)
try await networkingInteractor.requestNetworkAck(request, topic: topic, tag: AuthProtocolMethod.authRequest.responseTag)
try await networkingInteractor.subscribe(topic: responseTopic)
}
}
4 changes: 2 additions & 2 deletions Sources/Auth/Services/App/AppRespondSubscriber.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ class AppRespondSubscriber {
}

private func subscribeForResponse() {
networkingInteractor.responseErrorSubscription(on: AuthProtocolMethod.request)
networkingInteractor.responseErrorSubscription(on: AuthProtocolMethod.authRequest)
.sink { [unowned self] payload in
guard let error = AuthError(code: payload.error.code) else { return }
onResponse?(payload.id, .failure(error))
}.store(in: &publishers)

networkingInteractor.responseSubscription(on: AuthProtocolMethod.request)
networkingInteractor.responseSubscription(on: AuthProtocolMethod.authRequest)
.sink { [unowned self] (payload: ResponseSubscriptionPayload<AuthRequestParams, Cacao>) in

activatePairingIfNeeded(id: payload.id)
Expand Down
37 changes: 37 additions & 0 deletions Sources/Auth/Services/Common/DeletePairingService.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import Foundation
import WalletConnectNetworking
import JSONRPC
import WalletConnectKMS
import WalletConnectUtils
import WalletConnectPairing

class DeletePairingService {
enum Errors: Error {
case pairingNotFound
}
private let networkingInteractor: NetworkInteracting
private let kms: KeyManagementServiceProtocol
private let pairingStorage: WCPairingStorage
private let logger: ConsoleLogging

init(networkingInteractor: NetworkInteracting,
kms: KeyManagementServiceProtocol,
pairingStorage: WCPairingStorage,
logger: ConsoleLogging) {
self.networkingInteractor = networkingInteractor
self.kms = kms
self.pairingStorage = pairingStorage
self.logger = logger
}

func delete(topic: String) async throws {
guard pairingStorage.hasPairing(forTopic: topic) else { throw Errors.pairingNotFound}
let reason = AuthError.userDisconnected
logger.debug("Will delete pairing for reason: message: \(reason.message) code: \(reason.code)")
let request = RPCRequest(method: AuthProtocolMethod.pairingDelete.rawValue, params: reason)
try await networkingInteractor.request(request, topic: topic, tag: AuthProtocolMethod.pairingDelete.requestTag)
pairingStorage.delete(topic: topic)
kms.deleteSymmetricKey(for: topic)
networkingInteractor.unsubscribe(topic: topic)
}
}
4 changes: 2 additions & 2 deletions Sources/Auth/Services/Wallet/WalletRequestSubscriber.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class WalletRequestSubscriber {
private func subscribeForRequest() {
guard let address = address else { return }

networkingInteractor.requestSubscription(on: AuthProtocolMethod.request)
networkingInteractor.requestSubscription(on: AuthProtocolMethod.authRequest)
.sink { [unowned self] (payload: RequestSubscriptionPayload<AuthRequestParams>) in
logger.debug("WalletRequestSubscriber: Received request")
let message = messageFormatter.formatMessage(from: payload.request.payloadParams, address: address)
Expand All @@ -42,7 +42,7 @@ class WalletRequestSubscriber {
guard let pubKey = kms.getAgreementSecret(for: topic)?.publicKey
else { return logger.error("Agreement key for topic \(topic) not found") }

let tag = AuthProtocolMethod.request.tag
let tag = AuthProtocolMethod.authRequest.responseTag
let envelopeType = Envelope.EnvelopeType.type1(pubKey: pubKey.rawRepresentation)

Task(priority: .high) {
Expand Down
4 changes: 2 additions & 2 deletions Sources/Auth/Services/Wallet/WalletRespondService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ actor WalletRespondService {
let didpkh = DIDPKH(account: account)
let cacao = CacaoFormatter().format(authRequestParams, signature, didpkh)
let response = RPCResponse(id: requestId, result: cacao)
try await networkingInteractor.respond(topic: topic, response: response, tag: AuthProtocolMethod.request.tag, envelopeType: .type1(pubKey: keys.publicKey.rawRepresentation))
try await networkingInteractor.respond(topic: topic, response: response, tag: AuthProtocolMethod.authRequest.responseTag, envelopeType: .type1(pubKey: keys.publicKey.rawRepresentation))
}

func respondError(requestId: RPCID) async throws {
Expand All @@ -42,7 +42,7 @@ actor WalletRespondService {

try kms.setAgreementSecret(keys, topic: topic)

let tag = AuthProtocolMethod.request.tag
let tag = AuthProtocolMethod.authRequest.responseTag
let error = AuthError.userRejeted
let envelopeType = Envelope.EnvelopeType.type1(pubKey: keys.publicKey.rawRepresentation)
try await networkingInteractor.respondError(topic: topic, requestId: requestId, tag: tag, reason: error, envelopeType: envelopeType)
Expand Down
14 changes: 0 additions & 14 deletions Sources/Auth/Types/AuthProtocolMethod.swift

This file was deleted.

5 changes: 5 additions & 0 deletions Sources/Auth/Types/Errors/AuthError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import WalletConnectNetworking

/// Authentication error
public enum AuthError: Codable, Equatable, Error {
case userDisconnected
case userRejeted
case malformedResponseParams
case malformedRequestParams
Expand Down Expand Up @@ -31,6 +32,8 @@ extension AuthError: Reason {

public var code: Int {
switch self {
case .userDisconnected:
return 6000
case .userRejeted:
return 14001
case .malformedResponseParams:
Expand All @@ -56,6 +59,8 @@ extension AuthError: Reason {
return "Original message compromised"
case .signatureVerificationFailed:
return "Message verification failed"
case .userDisconnected:
return "User Disconnected"
}
}
}
4 changes: 2 additions & 2 deletions Sources/Chat/ProtocolServices/Common/MessagingService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class MessagingService {
let timestamp = Int64(Date().timeIntervalSince1970 * 1000)
let message = Message(topic: topic, message: messageString, authorAccount: authorAccount, timestamp: timestamp)
let request = RPCRequest(method: ChatProtocolMethod.message.method, params: message)
try await networkingInteractor.request(request, topic: topic, tag: ChatProtocolMethod.message.tag)
try await networkingInteractor.request(request, topic: topic, tag: ChatProtocolMethod.message.requestTag)
Task(priority: .background) {
await messagesStore.add(message)
onMessage?(message)
Expand All @@ -59,7 +59,7 @@ class MessagingService {

private func handleMessage(_ message: Message, topic: String, requestId: RPCID) {
Task(priority: .background) {
try await networkingInteractor.respondSuccess(topic: topic, requestId: requestId, tag: ChatProtocolMethod.message.tag)
try await networkingInteractor.respondSuccess(topic: topic, requestId: requestId, tag: ChatProtocolMethod.message.responseTag)
await messagesStore.add(message)
logger.debug("Received message")
onMessage?(message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ class InvitationHandlingService {

let response = RPCResponse(id: payload.id, result: inviteResponse)
let responseTopic = try getInviteResponseTopic(requestTopic: payload.topic, invite: payload.request)
try await networkingInteractor.respond(topic: responseTopic, response: response, tag: ChatProtocolMethod.invite.tag)
try await networkingInteractor.respond(topic: responseTopic, response: response, tag: ChatProtocolMethod.invite.responseTag)

let threadAgreementKeys = try kms.performKeyAgreement(selfPublicKey: selfThreadPubKey, peerPublicKey: payload.request.publicKey)
let threadTopic = threadAgreementKeys.derivedTopic()
Expand All @@ -71,7 +71,7 @@ class InvitationHandlingService {

let responseTopic = try getInviteResponseTopic(requestTopic: payload.topic, invite: payload.request)

try await networkingInteractor.respondError(topic: responseTopic, requestId: payload.id, tag: ChatProtocolMethod.invite.tag, reason: ChatError.userRejected)
try await networkingInteractor.respondError(topic: responseTopic, requestId: payload.id, tag: ChatProtocolMethod.invite.responseTag, reason: ChatError.userRejected)

invitePayloadStore.delete(forKey: inviteId)
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Chat/ProtocolServices/Inviter/InviteService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class InviteService {
try kms.setSymmetricKey(symKeyI.sharedKey, for: responseTopic)

try await networkingInteractor.subscribe(topic: responseTopic)
try await networkingInteractor.request(request, topic: inviteTopic, tag: ChatProtocolMethod.invite.tag, envelopeType: .type1(pubKey: selfPubKeyY.rawRepresentation))
try await networkingInteractor.request(request, topic: inviteTopic, tag: ChatProtocolMethod.invite.requestTag, envelopeType: .type1(pubKey: selfPubKeyY.rawRepresentation))

logger.debug("invite sent on topic: \(inviteTopic)")
}
Expand Down
13 changes: 11 additions & 2 deletions Sources/Chat/Types/ChatProtocolMethod.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,23 @@ enum ChatProtocolMethod: ProtocolMethod {
case invite
case message

var tag: Int {
var requestTag: Int {
switch self {
case .invite:
return 2002
return 2000
case .message:
return 2002
}
}

var responseTag: Int {
switch self {
case .invite:
return 2001
case .message:
return 2003
}
}

var method: String {
switch self {
Expand Down
8 changes: 8 additions & 0 deletions Sources/Chat/Types/Invite.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,12 @@ public struct Invite: Codable, Equatable {
public let message: String
public let account: Account
public let publicKey: String

static var tag: Int {
return 2000
}

static var method: String {
return "wc_chatInvite"
}
}
2 changes: 1 addition & 1 deletion Sources/WalletConnectKMS/Serialiser/Serializer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public class Serializer: Serializing {
private func handleType1Envelope<T: Codable>(_ topic: String, peerPubKey: Data, sealbox: Data) throws -> T {
guard let selfPubKey = kms.getPublicKey(for: topic)
else { throw Errors.publicKeyForTopicNotFound }

let agreementKeys = try kms.performKeyAgreement(selfPublicKey: selfPubKey, peerPublicKey: peerPubKey.toHexString())
let decodedType: T = try decode(sealbox: sealbox, symmetricKey: agreementKeys.sharedKey.rawRepresentation)
let newTopic = agreementKeys.derivedTopic()
Expand Down
3 changes: 2 additions & 1 deletion Sources/WalletConnectNetworking/ProtocolMethod.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ import Foundation

public protocol ProtocolMethod {
var method: String { get }
var tag: Int { get }
var requestTag: Int { get }
var responseTag: Int { get }
}
31 changes: 31 additions & 0 deletions Sources/WalletConnectSign/Engine/Common/DeletePairingService.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Foundation
import WalletConnectKMS
import WalletConnectUtils
import WalletConnectPairing

class DeletePairingService {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we move it in WalletConnectPairing package?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, I see. Whey using different NetworkInteractors..

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah exactly, even the protocol method is the same

private let networkingInteractor: NetworkInteracting
private let kms: KeyManagementServiceProtocol
private let pairingStorage: WCPairingStorage
private let logger: ConsoleLogging

init(networkingInteractor: NetworkInteracting,
kms: KeyManagementServiceProtocol,
pairingStorage: WCPairingStorage,
logger: ConsoleLogging) {
self.networkingInteractor = networkingInteractor
self.kms = kms
self.pairingStorage = pairingStorage
self.logger = logger
}

func delete(topic: String) async throws {
let reasonCode = ReasonCode.userDisconnected
let reason = SessionType.Reason(code: reasonCode.code, message: reasonCode.message)
logger.debug("Will delete pairing for reason: message: \(reason.message) code: \(reason.code)")
try await networkingInteractor.request(.wcSessionDelete(reason), onTopic: topic)
pairingStorage.delete(topic: topic)
kms.deleteSymmetricKey(for: topic)
networkingInteractor.unsubscribe(topic: topic)
}
}
30 changes: 30 additions & 0 deletions Sources/WalletConnectSign/Engine/Common/DeleteSessionService.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import Foundation
import WalletConnectKMS
import WalletConnectUtils

class DeleteSessionService {
private let networkingInteractor: NetworkInteracting
private let kms: KeyManagementServiceProtocol
private let sessionStore: WCSessionStorage
private let logger: ConsoleLogging

init(networkingInteractor: NetworkInteracting,
kms: KeyManagementServiceProtocol,
sessionStore: WCSessionStorage,
logger: ConsoleLogging) {
self.networkingInteractor = networkingInteractor
self.kms = kms
self.sessionStore = sessionStore
self.logger = logger
}

func delete(topic: String) async throws {
let reasonCode = ReasonCode.userDisconnected
let reason = SessionType.Reason(code: reasonCode.code, message: reasonCode.message)
logger.debug("Will delete session for reason: message: \(reason.message) code: \(reason.code)")
try await networkingInteractor.request(.wcSessionDelete(reason), onTopic: topic)
sessionStore.delete(topic: topic)
kms.deleteSymmetricKey(for: topic)
networkingInteractor.unsubscribe(topic: topic)
}
}
Loading