From 5375aa0cbe7a8f2cfc3acd6f4bc7b5f33a495a79 Mon Sep 17 00:00:00 2001 From: metalurgical <97008724+metalurgical@users.noreply.github.com> Date: Thu, 25 Apr 2024 07:22:15 +0200 Subject: [PATCH] fix: remove lookupkey variables and unnecessary getPublicAddress() call from handleRetrieveShares --- README.md | 11 ++++- .../Extensions/TorusUtils+extension.swift | 23 ++++------- .../Helpers/LangrangeInterpolatePoly.swift | 2 +- Sources/TorusUtils/Point.swift | 3 -- Sources/TorusUtils/TorusUtils.swift | 40 +++++++------------ Torus-utils.podspec | 2 +- 6 files changed, 32 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index b25be952..614fbe31 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,15 @@ You can install the SingleFactorAuth Swift using Swift Package Manager. ... dependencies: [ ... - .package(url: "https://github.com/torusresearch/torus-utils-swift", from: "8.0.1") + .package(url: "https://github.com/torusresearch/torus-utils-swift", from: "8.1") ], +targets: [ + .target( name: "", + dependencies: [ + .product(name: "TorusUtils", package: "torus-utils-swift") + ] + ) ], +] ... ``` @@ -85,4 +92,4 @@ do { - Have a look at our [Community Portal](https://community.web3auth.io/) to see if anyone has any questions or issues you might be having. Feel free to reate new topics and we'll help you out as soon as possible. - Checkout our [Troubleshooting Documentation Page](https://web3auth.io/docs/troubleshooting) to know the common issues and solutions. -- For Priority Support, please have a look at our [Pricing Page](https://web3auth.io/pricing.html) for the plan that suits your needs. \ No newline at end of file +- For Priority Support, please have a look at our [Pricing Page](https://web3auth.io/pricing.html) for the plan that suits your needs. diff --git a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift index b01e1eda..9474a971 100644 --- a/Sources/TorusUtils/Extensions/TorusUtils+extension.swift +++ b/Sources/TorusUtils/Extensions/TorusUtils+extension.swift @@ -1,16 +1,12 @@ -import Foundation -import curveSecp256k1 import AnyCodable import BigInt import CryptoKit +import curveSecp256k1 import FetchNodeDetails +import Foundation import OSLog - - extension TorusUtils { - - internal func combinations(elements: ArraySlice, k: Int) -> [[T]] { if k == 0 { return [[]] @@ -163,13 +159,9 @@ extension TorusUtils { "params": AnyCodable(params), ] as [String: AnyCodable] - // do { let encoder = JSONEncoder() encoder.outputFormatting = .sortedKeys rpcdata = try encoder.encode(dataForRequest) - // } catch { - // os_log("get share or key assign - error: %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .error), type: .error, error.localizedDescription) - // } // Create Array of URLRequest Promises var requestArray = [URLRequest]() @@ -238,8 +230,7 @@ extension TorusUtils { // Hash the token from OAuth login let timestamp = String(Int(getTimestamp())) let hashedToken = keccak256Data(idToken.data(using: .utf8) ?? Data()).toHexString() - - + let nodeSigs = try await commitmentRequest(endpoints: endpoints, verifier: verifier, pubKeyX: pubKeyX, pubKeyY: pubKeyY, timestamp: timestamp, tokenCommitment: hashedToken) os_log("retrieveShares - data after commitment request: %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .info), type: .info, nodeSigs) var promiseArrRequest = [URLRequest]() @@ -698,10 +689,10 @@ extension TorusUtils { else { throw TorusUtilError.decryptionFailed } - + let ecies: ECIES = .init(iv: el.value.iv, ephemPublicKey: el.value.ephemPublicKey, ciphertext: share, mac: el.value.mac) result[nodeIndex] = try decrypt(privateKey: privateKey, opts: ecies).toHexString() - + if shares.count == result.count { return result } @@ -711,7 +702,7 @@ extension TorusUtils { // MARK: - Lagrange interpolation - internal func thresholdLagrangeInterpolation(data filteredData: [Int: String], endpoints: [String], lookupPubkeyX: String, lookupPubkeyY: String) throws -> (String, String, String) { + internal func thresholdLagrangeInterpolation(data filteredData: [Int: String], endpoints: [String], xCoordinate: String, yCoordinate: String) throws -> (String, String, String) { // all possible combinations of share indexes to interpolate let shareCombinations = combinations(elements: Array(filteredData.keys), k: Int(endpoints.count / 2) + 1) for shareIndexSet in shareCombinations { @@ -727,7 +718,7 @@ extension TorusUtils { os_log("retrieveDecryptAndReconstuct: private key rebuild %@ %@ %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .debug), type: .debug, data, pubKeyX, pubKeyY) // Verify - if pubKeyX == lookupPubkeyX && pubKeyY == lookupPubkeyY { + if pubKeyX == xCoordinate && pubKeyY == yCoordinate { return (pubKeyX, pubKeyY, data) } else { os_log("retrieveDecryptAndReconstuct: verification failed", log: getTorusLogger(log: TorusUtilsLogger.core, type: .error), type: .error) diff --git a/Sources/TorusUtils/Helpers/LangrangeInterpolatePoly.swift b/Sources/TorusUtils/Helpers/LangrangeInterpolatePoly.swift index a284bc23..3e4337d9 100644 --- a/Sources/TorusUtils/Helpers/LangrangeInterpolatePoly.swift +++ b/Sources/TorusUtils/Helpers/LangrangeInterpolatePoly.swift @@ -172,7 +172,7 @@ func generateRandomPolynomial(degree: Int, secret: BigInt? = nil, deterministicS while points[shareIndex.description.padding(toLength: 64, withPad: "0", startingAt: 0)] != nil { shareIndex = try generatePrivateExcludingIndexes(shareIndexes: [BigInt(0)]) } - points[String(shareIndex, radix: 16).addLeading0sForLength64()] = Point(x: shareIndex, y: BigInt(Data(hex:try SecretKey().serialize().addLeading0sForLength64()))) + points[String(shareIndex, radix: 16).addLeading0sForLength64()] = Point(x: shareIndex, y: BigInt(Data(hex: try SecretKey().serialize().addLeading0sForLength64()))) } points["0"] = Point(x: BigInt(0), y: actualS!) diff --git a/Sources/TorusUtils/Point.swift b/Sources/TorusUtils/Point.swift index f4414ce3..e36a4402 100644 --- a/Sources/TorusUtils/Point.swift +++ b/Sources/TorusUtils/Point.swift @@ -37,9 +37,6 @@ public class Point: Decodable { let xData = Data(hex: x.description) let yData = Data(hex: y.description) return prefix + xData + yData -// case "elliptic-compressed": -// let publicKey = try getCompressedPublicKey() -// return publicKey default: throw PointError.encodingNotSupported } diff --git a/Sources/TorusUtils/TorusUtils.swift b/Sources/TorusUtils/TorusUtils.swift index b431e2d7..594a7624 100644 --- a/Sources/TorusUtils/TorusUtils.swift +++ b/Sources/TorusUtils/TorusUtils.swift @@ -1,8 +1,8 @@ +import AnyCodable import BigInt import FetchNodeDetails import Foundation import OSLog -import AnyCodable #if canImport(curveSecp256k1) import curveSecp256k1 #endif @@ -32,8 +32,8 @@ open class TorusUtils: AbstractTorusUtils { self.urlSession = urlSession utilsLogType = loglevel self.enableOneKey = enableOneKey - self.allowHost = network.signerMap + "/api/allow" - self.signerHost = network.signerMap + "/api/sign" + allowHost = network.signerMap + "/api/allow" + signerHost = network.signerMap + "/api/sign" self.network = network self.serverTimeOffset = serverTimeOffset self.clientId = clientId @@ -71,7 +71,7 @@ open class TorusUtils: AbstractTorusUtils { do { let result = try await session.data(for: allowHostRequest) let responseData = try JSONDecoder().decode(AllowSuccess.self, from: result.0) - if (responseData.success == false ) { + if responseData.success == false { let errorData = try JSONDecoder().decode(AllowRejected.self, from: result.0) throw TorusUtilError.gatingError("code: \(errorData.code), error: \(errorData.error)") } @@ -244,26 +244,15 @@ open class TorusUtils: AbstractTorusUtils { let timestamp = String(Int(getTimestamp())) - let hashedToken = keccak256Data(idToken.data(using: .utf8) ?? Data()).toHexString() - var lookupPubkeyX: String = "" - var lookupPubkeyY: String = "" + let hashedToken = keccak256Data(idToken.data(using: .utf8) ?? Data()).toHexString() do { - let getPublicAddressData = try await getPublicAddress(endpoints: endpoints, torusNodePubs: torusNodePubs, verifier: verifier, verifierId: verifierId) - guard (getPublicAddressData.finalKeyData?.evmAddress) != nil - else { - throw TorusUtilError.runtime("Unable to provide evmAddress") - } - let localPubkeyX = getPublicAddressData.finalKeyData!.X.addLeading0sForLength64() - let localPubkeyY = getPublicAddressData.finalKeyData!.Y.addLeading0sForLength64() - lookupPubkeyX = localPubkeyX - lookupPubkeyY = localPubkeyY let commitmentRequestData = try await commitmentRequest(endpoints: endpoints, verifier: verifier, pubKeyX: pubKeyX, pubKeyY: pubKeyY, timestamp: timestamp, tokenCommitment: hashedToken) os_log("retrieveShares - data after commitment request: %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .info), type: .info, commitmentRequestData) let (oAuthKeyX, oAuthKeyY, oAuthKey) = try await retrieveDecryptAndReconstruct( endpoints: endpoints, indexes: indexes, - extraParams: extraParams, verifier: verifier, tokenCommitment: idToken, nodeSignatures: commitmentRequestData, verifierId: verifierId, lookupPubkeyX: lookupPubkeyX, lookupPubkeyY: lookupPubkeyY, privateKey: privateKey.serialize().addLeading0sForLength64()) + extraParams: extraParams, verifier: verifier, tokenCommitment: idToken, nodeSignatures: commitmentRequestData, verifierId: verifierId, xCoordinate: pubKeyX, yCoordinate: pubKeyY, privateKey: privateKey.serialize().addLeading0sForLength64()) var metadataNonce: BigUInt var typeOfUser: UserType = .v1 @@ -285,9 +274,9 @@ open class TorusUtils: AbstractTorusUtils { metadataNonce = try await getMetadata(dictionary: ["pub_key_X": oAuthKeyX, "pub_key_Y": oAuthKeyY]) var privateKeyWithNonce = BigInt(metadataNonce) + BigInt(oAuthKey, radix: 16)! privateKeyWithNonce = privateKeyWithNonce.modulus(modulusValue) - let serializedKey = privateKeyWithNonce.magnitude.serialize().hexString.addLeading0sForLength64() + let serializedKey = privateKeyWithNonce.magnitude.serialize().hexString.addLeading0sForLength64() let finalPrivateKey = try - SecretKey(hex: serializedKey) + SecretKey(hex: serializedKey) finalPubKey = try finalPrivateKey.toPublic().serialize(compressed: false) } } else { @@ -356,7 +345,7 @@ open class TorusUtils: AbstractTorusUtils { private func retrieveDecryptAndReconstruct(endpoints: [String], indexes: [BigUInt], - extraParams: [String: Codable], verifier: String, tokenCommitment: String, nodeSignatures: [CommitmentRequestResponse], verifierId: String, lookupPubkeyX: String, lookupPubkeyY: String, privateKey: String) async throws -> (String, String, String) { + extraParams: [String: Codable], verifier: String, tokenCommitment: String, nodeSignatures: [CommitmentRequestResponse], verifierId: String, xCoordinate: String, yCoordinate: String, privateKey: String) async throws -> (String, String, String) { // Rebuild extraParams let session = createURLSession() let threshold = Int(endpoints.count / 2) + 1 @@ -423,8 +412,8 @@ open class TorusUtils: AbstractTorusUtils { throw TorusUtilError.decodingFailed(decoded.error?.data) } os_log("retrieveDecryptAndReconstuct: %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .info), type: .info, "\(decoded)") - var X = lookupPubkeyX.addLeading0sForLength64() - var Y = lookupPubkeyY.addLeading0sForLength64() + var X = xCoordinate.addLeading0sForLength64() + var Y = yCoordinate.addLeading0sForLength64() if let decodedResult = decoded.result as? LegacyLookupResponse { // case non migration let keyObj = decodedResult.keys @@ -442,8 +431,8 @@ open class TorusUtils: AbstractTorusUtils { let pointHex = PointHex(from: .init(x: first.publicKey.X, y: first.publicKey.Y)) shareResponses.append(pointHex) let metadata = first.metadata - X = pointHex.x - Y = pointHex.y + X = pointHex.x.addLeading0sForLength64() + Y = pointHex.y.addLeading0sForLength64() let model = RetrieveDecryptAndReconstuctResponseModel(iv: metadata.iv, ephemPublicKey: metadata.ephemPublicKey, share: first.share, pubKeyX: pointHex.x, pubKeyY: pointHex.y, mac: metadata.mac) resultArray[i] = model } @@ -452,7 +441,6 @@ open class TorusUtils: AbstractTorusUtils { } // Due to multiple keyAssign - let lookupShares = shareResponses.filter { $0 != nil } // Nonnil elements // Comparing dictionaries, so the order of keys doesn't matter @@ -468,7 +456,7 @@ open class TorusUtils: AbstractTorusUtils { let filteredData = data.filter { $0.value != TorusUtilError.decodingFailed(nil).debugDescription } if filteredData.count < threshold { throw TorusUtilError.thresholdError } - let thresholdLagrangeInterpolationData = try thresholdLagrangeInterpolation(data: filteredData, endpoints: endpoints, lookupPubkeyX: X.addLeading0sForLength64(), lookupPubkeyY: Y.addLeading0sForLength64()) + let thresholdLagrangeInterpolationData = try thresholdLagrangeInterpolation(data: filteredData, endpoints: endpoints, xCoordinate: X.addLeading0sForLength64(), yCoordinate: Y.addLeading0sForLength64()) session.invalidateAndCancel() return thresholdLagrangeInterpolationData case let .failure(error): diff --git a/Torus-utils.podspec b/Torus-utils.podspec index 79de4a86..bfb37321 100644 --- a/Torus-utils.podspec +++ b/Torus-utils.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |spec| spec.name = "Torus-utils" - spec.version = "8.1.0" + spec.version = "8.1.1" spec.ios.deployment_target = "13.0" spec.summary = "Retrieve user shares" spec.homepage = "https://github.com/torusresearch/torus-utils-swift"