Skip to content

Commit

Permalink
fix: remove lookupkey variables and unnecessary getPublicAddress() ca…
Browse files Browse the repository at this point in the history
…ll from handleRetrieveShares
  • Loading branch information
metalurgical committed Apr 25, 2024
1 parent f20a23b commit 5375aa0
Show file tree
Hide file tree
Showing 6 changed files with 32 additions and 49 deletions.
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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")
]
) ],
]
...
```

Expand Down Expand Up @@ -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.
- For Priority Support, please have a look at our [Pricing Page](https://web3auth.io/pricing.html) for the plan that suits your needs.
23 changes: 7 additions & 16 deletions Sources/TorusUtils/Extensions/TorusUtils+extension.swift
Original file line number Diff line number Diff line change
@@ -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<T>(elements: ArraySlice<T>, k: Int) -> [[T]] {
if k == 0 {
return [[]]
Expand Down Expand Up @@ -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]()
Expand Down Expand Up @@ -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]()
Expand Down Expand Up @@ -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
}
Expand All @@ -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 {
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion Sources/TorusUtils/Helpers/LangrangeInterpolatePoly.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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!)
Expand Down
3 changes: 0 additions & 3 deletions Sources/TorusUtils/Point.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
40 changes: 14 additions & 26 deletions Sources/TorusUtils/TorusUtils.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import AnyCodable
import BigInt
import FetchNodeDetails
import Foundation
import OSLog
import AnyCodable
#if canImport(curveSecp256k1)
import curveSecp256k1
#endif
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)")
}
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand All @@ -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
Expand All @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion Torus-utils.podspec
Original file line number Diff line number Diff line change
@@ -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"
Expand Down

0 comments on commit 5375aa0

Please sign in to comment.