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

Fix some build warnings and typos #47

Merged
merged 1 commit into from
Jan 24, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/Relayer/WakuNetworkRelay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ public final class WakuNetworkRelay {
private func acknowledgeSubscription(requestId: Int64) {
let response = JSONRPCResponse(id: requestId, result: AnyCodable(true))
let responseJson = try! response.json()
try? jsonRpcSubscriptionsHistory.resolve(response: JsonRpcResponseTypes.response(response))
_ = try? jsonRpcSubscriptionsHistory.resolve(response: JsonRpcResponseTypes.response(response))
dispatcher.send(responseJson) { [weak self] error in
if let error = error {
self?.logger.debug("Failed to Respond for request id: \(requestId), error: \(error)")
Expand Down
8 changes: 4 additions & 4 deletions Sources/WalletConnect/Engine/SessionEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ final class SessionEngine {
restoreSubscriptions()

relayer.onResponse = { [weak self] in
self?.handleReponse($0)
self?.handleResponse($0)
}
}

Expand Down Expand Up @@ -366,7 +366,7 @@ final class SessionEngine {
if let error = error {
logger.error(error)
} else {
try? sequencesStore.setSequence(session)
sequencesStore.setSequence(session)
onSessionUpgrade?(session.topic, newPermissions)
}
}
Expand Down Expand Up @@ -502,12 +502,12 @@ final class SessionEngine {
}.store(in: &publishers)
}

private func handleReponse(_ response: WCResponse) {
private func handleResponse(_ response: WCResponse) {
switch response.requestParams {
case .pairingPayload(let payloadParams):
let proposeParams = payloadParams.request.params
handleProposeResponse(topic: response.topic, proposeParams: proposeParams, result: response.result)
case .sessionApprove(let approveParams):
case .sessionApprove:
handleApproveResponse(topic: response.topic, result: response.result)
default:
break
Expand Down
26 changes: 13 additions & 13 deletions Sources/WalletConnect/Relay/WalletConnectRelay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class WalletConnectRelay: WalletConnectRelaying {
var onResponse: ((WCResponse) -> Void)?

private var networkRelayer: NetworkRelaying
private let jsonRpcSerialiser: JSONRPCSerialising
private let jsonRpcSerializer: JSONRPCSerializing
private let jsonRpcHistory: JsonRpcHistoryRecording

var transportConnectionPublisher: AnyPublisher<Void, Never> {
Expand All @@ -55,11 +55,11 @@ class WalletConnectRelay: WalletConnectRelaying {
let logger: ConsoleLogging

init(networkRelayer: NetworkRelaying,
jsonRpcSerialiser: JSONRPCSerialising,
jsonRpcSerializer: JSONRPCSerializing,
logger: ConsoleLogging,
jsonRpcHistory: JsonRpcHistoryRecording) {
self.networkRelayer = networkRelayer
self.jsonRpcSerialiser = jsonRpcSerialiser
self.jsonRpcSerializer = jsonRpcSerializer
self.logger = logger
self.jsonRpcHistory = jsonRpcHistory
setUpPublishers()
Expand All @@ -72,7 +72,7 @@ class WalletConnectRelay: WalletConnectRelaying {
func request(topic: String, payload: WCRequest, completion: ((Result<JSONRPCResponse<AnyCodable>, JSONRPCErrorResponse>)->())?) {
do {
try jsonRpcHistory.set(topic: topic, request: payload, chainId: getChainId(payload))
let message = try jsonRpcSerialiser.serialise(topic: topic, encodable: payload)
let message = try jsonRpcSerializer.serialize(topic: topic, encodable: payload)
networkRelayer.publish(topic: topic, payload: message) { [weak self] error in
guard let self = self else {return}
if let error = error {
Expand Down Expand Up @@ -103,10 +103,10 @@ class WalletConnectRelay: WalletConnectRelaying {

func respond(topic: String, response: JsonRpcResponseTypes, completion: @escaping ((Error?)->())) {
do {
try jsonRpcHistory.resolve(response: response)
let message = try jsonRpcSerialiser.serialise(topic: topic, encodable: response.value)
_ = try jsonRpcHistory.resolve(response: response)
let message = try jsonRpcSerializer.serialize(topic: topic, encodable: response.value)
logger.debug("Responding....topic: \(topic)")
networkRelayer.publish(topic: topic, payload: message) { [weak self] error in
networkRelayer.publish(topic: topic, payload: message) { error in
completion(error)
}
} catch WalletConnectError.internal(.jsonRpcDuplicateDetected) {
Expand Down Expand Up @@ -145,12 +145,12 @@ class WalletConnectRelay: WalletConnectRelaying {
}

private func manageSubscription(_ topic: String, _ message: String) {
if let deserialisedJsonRpcRequest: WCRequest = jsonRpcSerialiser.tryDeserialise(topic: topic, message: message) {
handleWCRequest(topic: topic, request: deserialisedJsonRpcRequest)
} else if let deserialisedJsonRpcResponse: JSONRPCResponse<AnyCodable> = jsonRpcSerialiser.tryDeserialise(topic: topic, message: message) {
handleJsonRpcResponse(response: deserialisedJsonRpcResponse)
} else if let deserialisedJsonRpcError: JSONRPCErrorResponse = jsonRpcSerialiser.tryDeserialise(topic: topic, message: message) {
handleJsonRpcErrorResponse(response: deserialisedJsonRpcError)
if let deserializedJsonRpcRequest: WCRequest = jsonRpcSerializer.tryDeserialize(topic: topic, message: message) {
handleWCRequest(topic: topic, request: deserializedJsonRpcRequest)
} else if let deserializedJsonRpcResponse: JSONRPCResponse<AnyCodable> = jsonRpcSerializer.tryDeserialize(topic: topic, message: message) {
handleJsonRpcResponse(response: deserializedJsonRpcResponse)
} else if let deserializedJsonRpcError: JSONRPCErrorResponse = jsonRpcSerializer.tryDeserialize(topic: topic, message: message) {
handleJsonRpcErrorResponse(response: deserializedJsonRpcError)
} else {
logger.warn("Warning: WalletConnect Relay - Received unknown object type from networking relay")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@

import Foundation

enum JSONRPCSerialiserError: String, Error {
enum JSONRPCSerializerError: String, Error {
case messageToShort = "Error: message is too short"
}
28 changes: 14 additions & 14 deletions Sources/WalletConnect/Serialiser/JSONRPCSerializing.swift
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import Foundation

protocol JSONRPCSerialising {
func serialise(topic: String, encodable: Encodable) throws -> String
func tryDeserialise<T: Codable>(topic: String, message: String) -> T?
protocol JSONRPCSerializing {
func serialize(topic: String, encodable: Encodable) throws -> String
func tryDeserialize<T: Codable>(topic: String, message: String) -> T?
var codec: Codec {get}
}

class JSONRPCSerialiser: JSONRPCSerialising {
class JSONRPCSerializer: JSONRPCSerializing {

private let crypto: Crypto
let codec: Codec
Expand All @@ -16,7 +16,7 @@ class JSONRPCSerialiser: JSONRPCSerialising {
self.codec = codec
}

func serialise(topic: String, encodable: Encodable) throws -> String {
func serialize(topic: String, encodable: Encodable) throws -> String {
let messageJson = try encodable.json()
var message: String
if let agreementKeys = try? crypto.getAgreementSecret(for: topic) {
Expand All @@ -27,23 +27,23 @@ class JSONRPCSerialiser: JSONRPCSerialising {
return message
}

func tryDeserialise<T: Codable>(topic: String, message: String) -> T? {
func tryDeserialize<T: Codable>(topic: String, message: String) -> T? {
do {
let deserialisedJsonRpcRequest: T
let deserializedJsonRpcRequest: T
if let agreementKeys = try? crypto.getAgreementSecret(for: topic) {
deserialisedJsonRpcRequest = try deserialise(message: message, symmetricKey: agreementKeys.sharedSecret)
deserializedJsonRpcRequest = try deserialize(message: message, symmetricKey: agreementKeys.sharedSecret)
} else {
let jsonData = Data(hex: message)
deserialisedJsonRpcRequest = try JSONDecoder().decode(T.self, from: jsonData)
deserializedJsonRpcRequest = try JSONDecoder().decode(T.self, from: jsonData)
}
return deserialisedJsonRpcRequest
return deserializedJsonRpcRequest
} catch {
// logger.debug("Type \(T.self) does not match the payload")
return nil
}
}

func deserialise<T: Codable>(message: String, symmetricKey: Data) throws -> T {
func deserialize<T: Codable>(message: String, symmetricKey: Data) throws -> T {
let JSONRPCData = try decrypt(message: message, symmetricKey: symmetricKey)
return try JSONDecoder().decode(T.self, from: JSONRPCData)
}
Expand All @@ -58,18 +58,18 @@ class JSONRPCSerialiser: JSONRPCSerialising {
}

private func decrypt(message: String, symmetricKey: Data) throws -> Data {
let encryptionPayload = try deserialiseIntoPayload(message: message)
let encryptionPayload = try deserializeIntoPayload(message: message)
let decryptedJSONRPC = try codec.decode(payload: encryptionPayload, sharedSecret: symmetricKey)
guard let JSONRPCData = decryptedJSONRPC.data(using: .utf8) else {
throw DataConversionError.stringToDataFailed
}
return JSONRPCData
}

private func deserialiseIntoPayload(message: String) throws -> EncryptionPayload {
private func deserializeIntoPayload(message: String) throws -> EncryptionPayload {
let data = Data(hex: message)
guard data.count > EncryptionPayload.ivLength + EncryptionPayload.publicKeyLength + EncryptionPayload.macLength else {
throw JSONRPCSerialiserError.messageToShort
throw JSONRPCSerializerError.messageToShort
}
let pubKeyRangeStartIndex = EncryptionPayload.ivLength
let macStartIndex = pubKeyRangeStartIndex + EncryptionPayload.publicKeyLength
Expand Down
8 changes: 4 additions & 4 deletions Sources/WalletConnect/WalletConnectClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import UIKit

/// An Object that expose public API to provide interactions with WalletConnect SDK
///
/// WalletConnect Client is not a singleton but once you create an instance, you should not deinitialise it. Usually only one instance of a client is required in the application.
/// WalletConnect Client is not a singleton but once you create an instance, you should not deinitialize it. Usually only one instance of a client is required in the application.
///
/// ```swift
/// let metadata = AppMetadata(name: String?, description: String?, url: String?, icons: [String]?)
Expand Down Expand Up @@ -44,7 +44,7 @@ public final class WalletConnectClient {
/// - keyValueStorage: by default WalletConnect SDK will store sequences in UserDefaults but if for some reasons you want to provide your own storage you can inject it here.
/// - clientName: if your app requires more than one client you are required to call them with different names to distinguish logs source and prefix storage keys.
///
/// WalletConnect Client is not a singleton but once you create an instance, you should not deinitialise it. Usually only one instance of a client is required in the application.
/// WalletConnect Client is not a singleton but once you create an instance, you should not deinitialize it. Usually only one instance of a client is required in the application.
public convenience init(metadata: AppMetadata, projectId: String, isController: Bool, relayHost: String, keyValueStorage: KeyValueStorage = UserDefaults.standard, clientName: String? = nil) {
self.init(metadata: metadata, projectId: projectId, isController: isController, relayHost: relayHost, logger: ConsoleLogger(loggingLevel: .off), keychain: KeychainStorage(uniqueIdentifier: clientName), keyValueStorage: keyValueStorage, clientName: clientName)
}
Expand All @@ -58,9 +58,9 @@ public final class WalletConnectClient {
self.secureStorage = SecureStorage(keychain: keychain)
let relayUrl = WakuNetworkRelay.makeRelayUrl(host: relayHost, projectId: projectId)
self.wakuRelay = WakuNetworkRelay(logger: logger, url: relayUrl, keyValueStorage: keyValueStorage, uniqueIdentifier: clientName ?? "")
let serialiser = JSONRPCSerialiser(crypto: crypto)
let serializer = JSONRPCSerializer(crypto: crypto)
self.history = JsonRpcHistory(logger: logger, keyValueStore: KeyValueStore<JsonRpcRecord>(defaults: keyValueStorage, identifier: StorageDomainIdentifiers.jsonRpcHistory(clientName: clientName ?? "_")))
self.relay = WalletConnectRelay(networkRelayer: wakuRelay, jsonRpcSerialiser: serialiser, logger: logger, jsonRpcHistory: history)
self.relay = WalletConnectRelay(networkRelayer: wakuRelay, jsonRpcSerializer: serializer, logger: logger, jsonRpcHistory: history)
let pairingSequencesStore = PairingStorage(storage: SequenceStore<PairingSequence>(storage: keyValueStorage, identifier: StorageDomainIdentifiers.pairings(clientName: clientName ?? "_")))
let sessionSequencesStore = SessionStorage(storage: SequenceStore<SessionSequence>(storage: keyValueStorage, identifier: StorageDomainIdentifiers.sessions(clientName: clientName ?? "_")))
self.pairingEngine = PairingEngine(relay: relay, crypto: crypto, subscriber: WCSubscriber(relay: relay, logger: logger), sequencesStore: pairingSequencesStore, isController: isController, metadata: metadata, logger: logger)
Expand Down
4 changes: 2 additions & 2 deletions Sources/WalletConnectUtils/AnyCodable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,10 @@ extension AnyCodable: Decodable, Encodable {
} else if let stringVal = try? container.decode(String.self) {
value = stringVal
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "the container contains nothing serialisable")
throw DecodingError.dataCorruptedError(in: container, debugDescription: "the container contains nothing serializable")
}
} else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not serialise"))
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Could not serialize"))
}
}

Expand Down
34 changes: 17 additions & 17 deletions Tests/WalletConnectTests/JSONRPCSerialiserTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,33 @@ import Foundation
import XCTest
@testable import WalletConnect

final class JSONRPCSerialiserTests: XCTestCase {
var serialiser: JSONRPCSerialiser!
final class JSONRPCSerializerTests: XCTestCase {
var serializer: JSONRPCSerializer!
var codec: MockedCodec!
override func setUp() {
codec = MockedCodec()
self.serialiser = JSONRPCSerialiser(crypto: Crypto(keychain: KeychainStorageMock()), codec: codec)
self.serializer = JSONRPCSerializer(crypto: Crypto(keychain: KeychainStorageMock()), codec: codec)
}

override func tearDown() {
serialiser = nil
serializer = nil
}

func testSerialise() {
codec.encryptionPayload = EncryptionPayload(iv: SerialiserTestData.iv,
publicKey: SerialiserTestData.publicKey,
mac: SerialiserTestData.mac,
cipherText: SerialiserTestData.cipherText)
let serialisedMessage = try! serialiser.encrypt(json: SerialiserTestData.pairingApproveJSON, agreementKeys: SerialiserTestData.emptyAgreementSecret)
let serialisedMessageSample = SerialiserTestData.serialisedMessage
XCTAssertEqual(serialisedMessage, serialisedMessageSample)
func testSerialize() {
codec.encryptionPayload = EncryptionPayload(iv: SerializerTestData.iv,
publicKey: SerializerTestData.publicKey,
mac: SerializerTestData.mac,
cipherText: SerializerTestData.cipherText)
let serializedMessage = try! serializer.encrypt(json: SerializerTestData.pairingApproveJSON, agreementKeys: SerializerTestData.emptyAgreementSecret)
let serializedMessageSample = SerializerTestData.serializedMessage
XCTAssertEqual(serializedMessage, serializedMessageSample)
}

func testDeserialise() {
let serialisedMessageSample = SerialiserTestData.serialisedMessage
codec.decodedJson = SerialiserTestData.pairingApproveJSON
let deserialisedJSONRPC: WCRequest = try! serialiser.deserialise(message: serialisedMessageSample, symmetricKey: Data(hex: ""))
XCTAssertEqual(deserialisedJSONRPC.params, SerialiserTestData.pairingApproveJSONRPCRequest.params)
func testDeserialize() {
let serializedMessageSample = SerializerTestData.serializedMessage
codec.decodedJson = SerializerTestData.pairingApproveJSON
let deserializedJSONRPC: WCRequest = try! serializer.deserialize(message: serializedMessageSample, symmetricKey: Data(hex: ""))
XCTAssertEqual(deserializedJSONRPC.params, SerializerTestData.pairingApproveJSONRPCRequest.params)
}
}

39 changes: 0 additions & 39 deletions Tests/WalletConnectTests/Mocks/MockedJSONRPCSerialiser.swift

This file was deleted.

39 changes: 39 additions & 0 deletions Tests/WalletConnectTests/Mocks/MockedJSONRPCSerializer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//

import Foundation
import WalletConnectUtils
@testable import WalletConnect

class MockedJSONRPCSerializer: JSONRPCSerializing {

var codec: Codec
var deserialized: Any!
var serialized: String!

init(codec: Codec = MockedCodec()) {
self.codec = codec
}

func serialize(topic: String, encodable: Encodable) throws -> String {
try serialize(json: try encodable.json(), agreementKeys: AgreementSecret(sharedSecret: Data(), publicKey: AgreementPrivateKey().publicKey))
}
func tryDeserialize<T: Codable>(topic: String, message: String) -> T? {
try? deserialize(message: message, symmetricKey: Data())
}
func deserializeJsonRpc(topic: String, message: String) throws -> Result<JSONRPCResponse<AnyCodable>, JSONRPCErrorResponse> {
.success(try deserialize(message: message, symmetricKey: Data()))
}

func deserialize<T>(message: String, symmetricKey: Data) throws -> T where T : Codable {
if let deserializedModel = deserialized as? T {
return deserializedModel
} else {
throw NSError.mock()
}
}

func serialize(json: String, agreementKeys: AgreementSecret) throws -> String {
return serialized
}

}
2 changes: 1 addition & 1 deletion Tests/WalletConnectTests/Mocks/MockedRelay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class MockedWCRelay: WalletConnectRelaying {

func sendSubscriptionPayloadOn(topic: String) {
let payload = WCRequestSubscriptionPayload(topic: topic,
wcRequest: SerialiserTestData.pairingApproveJSONRPCRequest)
wcRequest: SerializerTestData.pairingApproveJSONRPCRequest)
wcRequestPublisherSubject.send(payload)
}
}
Loading