Skip to content

Commit 06ec8f9

Browse files
committed
fix: remove lookupkey variables and unnecessary getPublicAddress() call from handleRetrieveShares
1 parent 608c284 commit 06ec8f9

File tree

5 files changed

+31
-48
lines changed

5 files changed

+31
-48
lines changed

README.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,15 @@ You can install the SingleFactorAuth Swift using Swift Package Manager.
1414
...
1515
dependencies: [
1616
...
17-
.package(url: "https://github.com/torusresearch/torus-utils-swift", from: "8.0.1")
17+
.package(url: "https://github.com/torusresearch/torus-utils-swift", from: "8.1")
1818
],
19+
targets: [
20+
.target( name: "",
21+
dependencies: [
22+
.product(name: "TorusUtils", package: "torus-utils-swift")
23+
]
24+
) ],
25+
]
1926
...
2027
```
2128

@@ -85,4 +92,4 @@ do {
8592

8693
- 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.
8794
- Checkout our [Troubleshooting Documentation Page](https://web3auth.io/docs/troubleshooting) to know the common issues and solutions.
88-
- For Priority Support, please have a look at our [Pricing Page](https://web3auth.io/pricing.html) for the plan that suits your needs.
95+
- For Priority Support, please have a look at our [Pricing Page](https://web3auth.io/pricing.html) for the plan that suits your needs.

Sources/TorusUtils/Extensions/TorusUtils+extension.swift

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,12 @@
1-
import Foundation
2-
import curveSecp256k1
31
import AnyCodable
42
import BigInt
53
import CryptoKit
4+
import curveSecp256k1
65
import FetchNodeDetails
6+
import Foundation
77
import OSLog
88

9-
10-
119
extension TorusUtils {
12-
13-
1410
internal func combinations<T>(elements: ArraySlice<T>, k: Int) -> [[T]] {
1511
if k == 0 {
1612
return [[]]
@@ -163,13 +159,9 @@ extension TorusUtils {
163159
"params": AnyCodable(params),
164160
] as [String: AnyCodable]
165161

166-
// do {
167162
let encoder = JSONEncoder()
168163
encoder.outputFormatting = .sortedKeys
169164
rpcdata = try encoder.encode(dataForRequest)
170-
// } catch {
171-
// os_log("get share or key assign - error: %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .error), type: .error, error.localizedDescription)
172-
// }
173165

174166
// Create Array of URLRequest Promises
175167
var requestArray = [URLRequest]()
@@ -238,8 +230,7 @@ extension TorusUtils {
238230
// Hash the token from OAuth login
239231
let timestamp = String(Int(getTimestamp()))
240232
let hashedToken = keccak256Data(idToken.data(using: .utf8) ?? Data()).toHexString()
241-
242-
233+
243234
let nodeSigs = try await commitmentRequest(endpoints: endpoints, verifier: verifier, pubKeyX: pubKeyX, pubKeyY: pubKeyY, timestamp: timestamp, tokenCommitment: hashedToken)
244235
os_log("retrieveShares - data after commitment request: %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .info), type: .info, nodeSigs)
245236
var promiseArrRequest = [URLRequest]()
@@ -698,10 +689,10 @@ extension TorusUtils {
698689
else {
699690
throw TorusUtilError.decryptionFailed
700691
}
701-
692+
702693
let ecies: ECIES = .init(iv: el.value.iv, ephemPublicKey: el.value.ephemPublicKey, ciphertext: share, mac: el.value.mac)
703694
result[nodeIndex] = try decrypt(privateKey: privateKey, opts: ecies).toHexString()
704-
695+
705696
if shares.count == result.count {
706697
return result
707698
}
@@ -711,7 +702,7 @@ extension TorusUtils {
711702

712703
// MARK: - Lagrange interpolation
713704

714-
internal func thresholdLagrangeInterpolation(data filteredData: [Int: String], endpoints: [String], lookupPubkeyX: String, lookupPubkeyY: String) throws -> (String, String, String) {
705+
internal func thresholdLagrangeInterpolation(data filteredData: [Int: String], endpoints: [String], xCoordinate: String, yCoordinate: String) throws -> (String, String, String) {
715706
// all possible combinations of share indexes to interpolate
716707
let shareCombinations = combinations(elements: Array(filteredData.keys), k: Int(endpoints.count / 2) + 1)
717708
for shareIndexSet in shareCombinations {
@@ -727,7 +718,7 @@ extension TorusUtils {
727718
os_log("retrieveDecryptAndReconstuct: private key rebuild %@ %@ %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .debug), type: .debug, data, pubKeyX, pubKeyY)
728719

729720
// Verify
730-
if pubKeyX == lookupPubkeyX && pubKeyY == lookupPubkeyY {
721+
if pubKeyX == xCoordinate && pubKeyY == yCoordinate {
731722
return (pubKeyX, pubKeyY, data)
732723
} else {
733724
os_log("retrieveDecryptAndReconstuct: verification failed", log: getTorusLogger(log: TorusUtilsLogger.core, type: .error), type: .error)

Sources/TorusUtils/Helpers/LangrangeInterpolatePoly.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ func generateRandomPolynomial(degree: Int, secret: BigInt? = nil, deterministicS
172172
while points[shareIndex.description.padding(toLength: 64, withPad: "0", startingAt: 0)] != nil {
173173
shareIndex = try generatePrivateExcludingIndexes(shareIndexes: [BigInt(0)])
174174
}
175-
points[String(shareIndex, radix: 16).addLeading0sForLength64()] = Point(x: shareIndex, y: BigInt(Data(hex:try SecretKey().serialize().addLeading0sForLength64())))
175+
points[String(shareIndex, radix: 16).addLeading0sForLength64()] = Point(x: shareIndex, y: BigInt(Data(hex: try SecretKey().serialize().addLeading0sForLength64())))
176176
}
177177

178178
points["0"] = Point(x: BigInt(0), y: actualS!)

Sources/TorusUtils/Point.swift

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,6 @@ public class Point: Decodable {
3737
let xData = Data(hex: x.description)
3838
let yData = Data(hex: y.description)
3939
return prefix + xData + yData
40-
// case "elliptic-compressed":
41-
// let publicKey = try getCompressedPublicKey()
42-
// return publicKey
4340
default:
4441
throw PointError.encodingNotSupported
4542
}

Sources/TorusUtils/TorusUtils.swift

Lines changed: 14 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1+
import AnyCodable
12
import BigInt
23
import FetchNodeDetails
34
import Foundation
45
import OSLog
5-
import AnyCodable
66
#if canImport(curveSecp256k1)
77
import curveSecp256k1
88
#endif
@@ -32,8 +32,8 @@ open class TorusUtils: AbstractTorusUtils {
3232
self.urlSession = urlSession
3333
utilsLogType = loglevel
3434
self.enableOneKey = enableOneKey
35-
self.allowHost = network.signerMap + "/api/allow"
36-
self.signerHost = network.signerMap + "/api/sign"
35+
allowHost = network.signerMap + "/api/allow"
36+
signerHost = network.signerMap + "/api/sign"
3737
self.network = network
3838
self.serverTimeOffset = serverTimeOffset
3939
self.clientId = clientId
@@ -71,7 +71,7 @@ open class TorusUtils: AbstractTorusUtils {
7171
do {
7272
let result = try await session.data(for: allowHostRequest)
7373
let responseData = try JSONDecoder().decode(AllowSuccess.self, from: result.0)
74-
if (responseData.success == false ) {
74+
if responseData.success == false {
7575
let errorData = try JSONDecoder().decode(AllowRejected.self, from: result.0)
7676
throw TorusUtilError.gatingError("code: \(errorData.code), error: \(errorData.error)")
7777
}
@@ -244,26 +244,15 @@ open class TorusUtils: AbstractTorusUtils {
244244

245245
let timestamp = String(Int(getTimestamp()))
246246

247-
let hashedToken = keccak256Data(idToken.data(using: .utf8) ?? Data()).toHexString()
248-
var lookupPubkeyX: String = ""
249-
var lookupPubkeyY: String = ""
247+
let hashedToken = keccak256Data(idToken.data(using: .utf8) ?? Data()).toHexString()
250248
do {
251-
let getPublicAddressData = try await getPublicAddress(endpoints: endpoints, torusNodePubs: torusNodePubs, verifier: verifier, verifierId: verifierId)
252-
guard (getPublicAddressData.finalKeyData?.evmAddress) != nil
253-
else {
254-
throw TorusUtilError.runtime("Unable to provide evmAddress")
255-
}
256-
let localPubkeyX = getPublicAddressData.finalKeyData!.X.addLeading0sForLength64()
257-
let localPubkeyY = getPublicAddressData.finalKeyData!.Y.addLeading0sForLength64()
258-
lookupPubkeyX = localPubkeyX
259-
lookupPubkeyY = localPubkeyY
260249
let commitmentRequestData = try await commitmentRequest(endpoints: endpoints, verifier: verifier, pubKeyX: pubKeyX, pubKeyY: pubKeyY, timestamp: timestamp, tokenCommitment: hashedToken)
261250
os_log("retrieveShares - data after commitment request: %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .info), type: .info, commitmentRequestData)
262251

263252
let (oAuthKeyX, oAuthKeyY, oAuthKey) = try await retrieveDecryptAndReconstruct(
264253
endpoints: endpoints,
265254
indexes: indexes,
266-
extraParams: extraParams, verifier: verifier, tokenCommitment: idToken, nodeSignatures: commitmentRequestData, verifierId: verifierId, lookupPubkeyX: lookupPubkeyX, lookupPubkeyY: lookupPubkeyY, privateKey: privateKey.serialize().addLeading0sForLength64())
255+
extraParams: extraParams, verifier: verifier, tokenCommitment: idToken, nodeSignatures: commitmentRequestData, verifierId: verifierId, xCoordinate: pubKeyX, yCoordinate: pubKeyY, privateKey: privateKey.serialize().addLeading0sForLength64())
267256

268257
var metadataNonce: BigUInt
269258
var typeOfUser: UserType = .v1
@@ -285,9 +274,9 @@ open class TorusUtils: AbstractTorusUtils {
285274
metadataNonce = try await getMetadata(dictionary: ["pub_key_X": oAuthKeyX, "pub_key_Y": oAuthKeyY])
286275
var privateKeyWithNonce = BigInt(metadataNonce) + BigInt(oAuthKey, radix: 16)!
287276
privateKeyWithNonce = privateKeyWithNonce.modulus(modulusValue)
288-
let serializedKey = privateKeyWithNonce.magnitude.serialize().hexString.addLeading0sForLength64()
277+
let serializedKey = privateKeyWithNonce.magnitude.serialize().hexString.addLeading0sForLength64()
289278
let finalPrivateKey = try
290-
SecretKey(hex: serializedKey)
279+
SecretKey(hex: serializedKey)
291280
finalPubKey = try finalPrivateKey.toPublic().serialize(compressed: false)
292281
}
293282
} else {
@@ -356,7 +345,7 @@ open class TorusUtils: AbstractTorusUtils {
356345

357346
private func retrieveDecryptAndReconstruct(endpoints: [String],
358347
indexes: [BigUInt],
359-
extraParams: [String: Codable], verifier: String, tokenCommitment: String, nodeSignatures: [CommitmentRequestResponse], verifierId: String, lookupPubkeyX: String, lookupPubkeyY: String, privateKey: String) async throws -> (String, String, String) {
348+
extraParams: [String: Codable], verifier: String, tokenCommitment: String, nodeSignatures: [CommitmentRequestResponse], verifierId: String, xCoordinate: String, yCoordinate: String, privateKey: String) async throws -> (String, String, String) {
360349
// Rebuild extraParams
361350
let session = createURLSession()
362351
let threshold = Int(endpoints.count / 2) + 1
@@ -423,8 +412,8 @@ open class TorusUtils: AbstractTorusUtils {
423412
throw TorusUtilError.decodingFailed(decoded.error?.data)
424413
}
425414
os_log("retrieveDecryptAndReconstuct: %@", log: getTorusLogger(log: TorusUtilsLogger.core, type: .info), type: .info, "\(decoded)")
426-
var X = lookupPubkeyX.addLeading0sForLength64()
427-
var Y = lookupPubkeyY.addLeading0sForLength64()
415+
var X = xCoordinate.addLeading0sForLength64()
416+
var Y = yCoordinate.addLeading0sForLength64()
428417
if let decodedResult = decoded.result as? LegacyLookupResponse {
429418
// case non migration
430419
let keyObj = decodedResult.keys
@@ -442,8 +431,8 @@ open class TorusUtils: AbstractTorusUtils {
442431
let pointHex = PointHex(from: .init(x: first.publicKey.X, y: first.publicKey.Y))
443432
shareResponses.append(pointHex)
444433
let metadata = first.metadata
445-
X = pointHex.x
446-
Y = pointHex.y
434+
X = pointHex.x.addLeading0sForLength64()
435+
Y = pointHex.y.addLeading0sForLength64()
447436
let model = RetrieveDecryptAndReconstuctResponseModel(iv: metadata.iv, ephemPublicKey: metadata.ephemPublicKey, share: first.share, pubKeyX: pointHex.x, pubKeyY: pointHex.y, mac: metadata.mac)
448437
resultArray[i] = model
449438
}
@@ -452,7 +441,6 @@ open class TorusUtils: AbstractTorusUtils {
452441
}
453442

454443
// Due to multiple keyAssign
455-
456444
let lookupShares = shareResponses.filter { $0 != nil } // Nonnil elements
457445

458446
// Comparing dictionaries, so the order of keys doesn't matter
@@ -468,7 +456,7 @@ open class TorusUtils: AbstractTorusUtils {
468456
let filteredData = data.filter { $0.value != TorusUtilError.decodingFailed(nil).debugDescription }
469457

470458
if filteredData.count < threshold { throw TorusUtilError.thresholdError }
471-
let thresholdLagrangeInterpolationData = try thresholdLagrangeInterpolation(data: filteredData, endpoints: endpoints, lookupPubkeyX: X.addLeading0sForLength64(), lookupPubkeyY: Y.addLeading0sForLength64())
459+
let thresholdLagrangeInterpolationData = try thresholdLagrangeInterpolation(data: filteredData, endpoints: endpoints, xCoordinate: X.addLeading0sForLength64(), yCoordinate: Y.addLeading0sForLength64())
472460
session.invalidateAndCancel()
473461
return thresholdLagrangeInterpolationData
474462
case let .failure(error):

0 commit comments

Comments
 (0)