Skip to content

Commit

Permalink
Merge pull request #79 from torusresearch/inline_replace_secp256k1
Browse files Browse the repository at this point in the history
feat: Inline replace secp256k1
  • Loading branch information
metalurgical authored Feb 1, 2024
2 parents 124bb10 + 0f672a5 commit 76c9b17
Show file tree
Hide file tree
Showing 13 changed files with 201 additions and 554 deletions.
18 changes: 9 additions & 9 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@
"version": "1.7.2"
}
},
{
"package": "curvelib.swift",
"repositoryURL": "https://github.com/tkey/curvelib.swift",
"state": {
"branch": null,
"revision": "85d17cc4fcc9ccf5f444a51d163b2f1671862621",
"version": "0.1.0"
}
},
{
"package": "FetchNodeDetails",
"repositoryURL": "https://github.com/torusresearch/fetch-node-details-swift.git",
Expand All @@ -46,15 +55,6 @@
"version": "4.13.0"
}
},
{
"package": "secp256k1",
"repositoryURL": "https://github.com/GigaBitcoin/secp256k1.swift.git",
"state": {
"branch": null,
"revision": "1a14e189def5eaa92f839afdd2faad8e43b61a6e",
"version": "0.12.2"
}
},
{
"package": "swift-crypto",
"repositoryURL": "https://github.com/apple/swift-crypto.git",
Expand Down
4 changes: 2 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ let package = Package(
targets: ["TorusUtils"])
],
dependencies: [
.package(name:"secp256k1", url: "https://github.com/GigaBitcoin/secp256k1.swift", .exact("0.12.2")),
.package(name: "curvelib.swift", url: "https://github.com/tkey/curvelib.swift", from: "0.1.0"),
.package(name:"FetchNodeDetails", url: "https://github.com/torusresearch/fetch-node-details-swift", from: "5.1.0"),
.package(name:"CryptoSwift", url: "https://github.com/krzyzanowskim/CryptoSwift",from: "1.5.1"),
.package(name:"jwt-kit", url: "https://github.com/vapor/jwt-kit", from: "4.0.0"),
Expand All @@ -24,7 +24,7 @@ let package = Package(
targets: [
.target(
name: "TorusUtils",
dependencies: ["FetchNodeDetails", "CryptoSwift", "AnyCodable", "secp256k1"]),
dependencies: ["FetchNodeDetails", "CryptoSwift", "AnyCodable", .product(name: "curveSecp256k1", package: "curvelib.swift")]),
.testTarget(
name: "TorusUtilsTests",
dependencies: ["TorusUtils", .product(name: "JWTKit", package: "jwt-kit")]
Expand Down
135 changes: 67 additions & 68 deletions Sources/TorusUtils/Extensions/TorusUtils+extension.swift

Large diffs are not rendered by default.

351 changes: 0 additions & 351 deletions Sources/TorusUtils/Extensions/secp256k1+Extension.swift

This file was deleted.

8 changes: 4 additions & 4 deletions Sources/TorusUtils/Helpers/LangrangeInterpolatePoly.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import BigInt
import Foundation
#if canImport(secp256k1)
import secp256k1
#if canImport(curveSecp256k1)
import curveSecp256k1
#endif

func modInverse(_ a: BigInt, _ m: BigInt) -> BigInt? {
Expand All @@ -25,7 +25,7 @@ func modInverse(_ a: BigInt, _ m: BigInt) -> BigInt? {
}

func generatePrivateExcludingIndexes(shareIndexes: [BigInt]) throws -> BigInt {
let key = BigInt(try secp256k1.KeyAgreement.PrivateKey().rawRepresentation)
let key = BigInt(Data(hex: try SecretKey().serialize().addLeading0sForLength64()))
if shareIndexes.contains(where: { $0 == key }) {
return try generatePrivateExcludingIndexes(shareIndexes: shareIndexes)
}
Expand Down 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(try secp256k1.KeyAgreement.PrivateKey().rawRepresentation))
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
22 changes: 11 additions & 11 deletions Sources/TorusUtils/TorusUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import CommonSources
import FetchNodeDetails
import Foundation
import OSLog

import AnyCodable
#if canImport(secp256k1)
import secp256k1
#if canImport(curveSecp256k1)
import curveSecp256k1
#endif

var utilsLogType = OSLogType.default
Expand Down Expand Up @@ -232,8 +231,8 @@ open class TorusUtils: AbstractTorusUtils {
private func handleRetrieveShares(torusNodePubs: [TorusNodePubModel],
indexes: [BigUInt],
endpoints: [String], verifier: String, verifierId: String, idToken: String, extraParams: [String: Codable]) async throws -> TorusKey {
let privateKey = try secp256k1.KeyAgreement.PrivateKey(format: .uncompressed)
let serializedPublicKey = privateKey.publicKey.dataRepresentation.hexString
let privateKey = SecretKey()
let serializedPublicKey = try privateKey.toPublic().serialize(compressed: false)

// Split key in 2 parts, X and Y
// let publicKeyHex = publicKey.toHexString()
Expand Down Expand Up @@ -263,7 +262,7 @@ open class TorusUtils: AbstractTorusUtils {
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.rawRepresentation.hexString)
extraParams: extraParams, verifier: verifier, tokenCommitment: idToken, nodeSignatures: commitmentRequestData, verifierId: verifierId, lookupPubkeyX: lookupPubkeyX, lookupPubkeyY: lookupPubkeyY, privateKey: privateKey.serialize().addLeading0sForLength64())

var metadataNonce: BigUInt
var typeOfUser: UserType = .v1
Expand All @@ -285,17 +284,18 @@ 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 = Data(hex: privateKeyWithNonce.magnitude.serialize().hexString.addLeading0sForLength64())
let finalPrivateKey = try secp256k1.KeyAgreement.PrivateKey(dataRepresentation: serializedKey, format: .uncompressed)
finalPubKey = finalPrivateKey.publicKey.dataRepresentation.hexString
let serializedKey = privateKeyWithNonce.magnitude.serialize().hexString.addLeading0sForLength64()
let finalPrivateKey = try
SecretKey(hex: serializedKey)
finalPubKey = try finalPrivateKey.toPublic().serialize(compressed: false)
}
} else {
// for imported keys in legacy networks
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 finalPrivateKey = try secp256k1.KeyAgreement.PrivateKey(dataRepresentation: Data(hex: privateKeyWithNonce.magnitude.serialize().hexString.addLeading0sForLength64()), format: .uncompressed)
finalPubKey = finalPrivateKey.publicKey.dataRepresentation.hexString
let finalPrivateKey = try SecretKey(hex: privateKeyWithNonce.magnitude.serialize().hexString.addLeading0sForLength64())
finalPubKey = try finalPrivateKey.toPublic().serialize(compressed: false)
}

let oAuthKeyAddress = generateAddressFromPubKey(publicKeyX: oAuthKeyX, publicKeyY: oAuthKeyY)
Expand Down
38 changes: 18 additions & 20 deletions Tests/TorusUtilsTests/AquaTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ import BigInt
import CommonSources
import FetchNodeDetails
import JWTKit
#if canImport(secp256k1)
import secp256k1
#endif
import XCTest

import CoreMedia
Expand Down Expand Up @@ -56,41 +53,42 @@ class AquaTest: XCTestCase {
XCTAssertEqual(val.oAuthKeyData!.evmAddress, "0xDfA967285AC699A70DA340F60d00DB19A272639d")
XCTAssertEqual(val.oAuthKeyData!.X, "4fc8db5d3fe164a3ab70fd6348721f2be848df2cc02fd2db316a154855a7aa7d")
XCTAssertEqual(val.oAuthKeyData!.Y, "f76933cbf5fe2916681075bb6cb4cde7d5f6b6ce290071b1b7106747d906457c")
XCTAssertEqual(val.finalKeyData!.evmAddress, "0xDfA967285AC699A70DA340F60d00DB19A272639d")
XCTAssertEqual(val.finalKeyData!.X, "4fc8db5d3fe164a3ab70fd6348721f2be848df2cc02fd2db316a154855a7aa7d")
XCTAssertEqual(val.finalKeyData!.Y, "f76933cbf5fe2916681075bb6cb4cde7d5f6b6ce290071b1b7106747d906457c")
XCTAssertNil(val.metadata?.pubNonce)
XCTAssertEqual(val.finalKeyData!.evmAddress, "0x79F06350eF34Aeed4BE68e26954D405D573f1438")
XCTAssertEqual(val.finalKeyData!.X, "99df45abc8e6ee03d2f94df33be79e939eadfbed20c6b88492782fdc3ef1dfd3")
XCTAssertEqual(val.finalKeyData!.Y, "12bf3e54599a177fdb88f8b22419df7ddf1622e1d2344301edbe090890a72b16")
XCTAssertEqual(val.metadata!.pubNonce!.x, "dc5a031fd2e0b55dbaece314ea125bac9da5f0a916bf156ff36b5ad71380ea32")
XCTAssertEqual(val.metadata!.pubNonce!.y, "affd749b98c209d2f9cf4dacb145d7897f82f1e2924a47b07874302ecc0b8ef1")
XCTAssertEqual(val.metadata?.nonce, 0)
XCTAssertEqual(val.metadata?.upgraded, false)
XCTAssertEqual(val.metadata?.typeOfUser, .v1)
XCTAssertEqual(val.metadata?.typeOfUser, .v2)
XCTAssertEqual(val.nodesData?.nodeIndexes.count, 0)

verifier = "tkey-google-aqua"
verifierID = "[email protected]"
val = try await tu.getUserTypeAndAddress(endpoints: nodeDetails.getTorusNodeEndpoints(), torusNodePubs: nodeDetails.getTorusNodePub(), verifier: verifier, verifierId: verifierID)
XCTAssertEqual(val.oAuthKeyData!.evmAddress, "0x5735dDC8d5125B23d77C3531aab3895A533584a3")
XCTAssertEqual(val.oAuthKeyData!.X, "e1b419bc52b82e14b148c307f10479cfa464d20c947555fb4758c586eab12873")
XCTAssertEqual(val.oAuthKeyData!.Y, "75f47d7d5a271c0fcf51a790c1683a1cb3394b1d37d20e29c346ac249e3bfca2")
XCTAssertEqual(val.finalKeyData!.evmAddress, "0x5735dDC8d5125B23d77C3531aab3895A533584a3")
XCTAssertEqual(val.finalKeyData!.X, "e1b419bc52b82e14b148c307f10479cfa464d20c947555fb4758c586eab12873")
XCTAssertEqual(val.finalKeyData!.Y, "75f47d7d5a271c0fcf51a790c1683a1cb3394b1d37d20e29c346ac249e3bfca2")
XCTAssertEqual(val.finalKeyData!.evmAddress, "0x5735dDC8d5125B23d77C3531aab3895A533584a3")
XCTAssertEqual(val.oAuthKeyData!.evmAddress, "0x4ea5260fF85678A2a326D08DF9C44d1f559a5828")
XCTAssertEqual(val.oAuthKeyData!.X, "0e6febe33a9d4eeb680cc6b63ff6237ad1971f27adcd7f104a3b1de18eda9337")
XCTAssertEqual(val.oAuthKeyData!.Y, "a5a915561f3543688e71281a850b9ee10b9690f305d9e79028dfc8359192b82d")
XCTAssertEqual(val.finalKeyData!.evmAddress, "0xBc32f315515AdE7010cabC5Fd68c966657A570BD")
XCTAssertEqual(val.finalKeyData!.X, "4897f120584ee18a72b9a6bb92c3ef6e45fc5fdff70beae7dc9325bd01332022")
XCTAssertEqual(val.finalKeyData!.Y, "2066dbef2fcdded4573e3c04d1c04edd5d44662168e636ed9d0b0cbe2e67c968")
XCTAssertEqual(val.finalKeyData!.evmAddress, "0xBc32f315515AdE7010cabC5Fd68c966657A570BD")
XCTAssertEqual(val.metadata?.nonce, 0)
XCTAssertEqual(val.metadata?.upgraded, false)
XCTAssertEqual(val.metadata?.typeOfUser, .v1)
XCTAssertEqual(val.metadata?.typeOfUser, .v2)
XCTAssertEqual(val.nodesData?.nodeIndexes.count, 0)

verifierID = "[email protected]"
val = try await tu.getUserTypeAndAddress(endpoints: nodeDetails.getTorusNodeEndpoints(), torusNodePubs: nodeDetails.getTorusNodePub(), verifier: verifier, verifierId: verifierID)
XCTAssertEqual(val.oAuthKeyData!.evmAddress, "0x4ce0D09C3989eb3cC9372cC27fa022D721D737dD")
XCTAssertEqual(val.oAuthKeyData!.X, "e76d2f7fa2c0df324b4ab74629c3af47aa4609c35f1d2b6b90b77a47ab9a1281")
XCTAssertEqual(val.oAuthKeyData!.Y, "b33b35148d72d357070f66372e07fec436001bdb15c098276b120b9ed64c1e5f")
XCTAssertEqual(val.finalKeyData!.evmAddress, "0x4ce0D09C3989eb3cC9372cC27fa022D721D737dD")
XCTAssertEqual(val.finalKeyData!.X, "e76d2f7fa2c0df324b4ab74629c3af47aa4609c35f1d2b6b90b77a47ab9a1281")
XCTAssertEqual(val.finalKeyData!.Y, "b33b35148d72d357070f66372e07fec436001bdb15c098276b120b9ed64c1e5f")
XCTAssertEqual(val.finalKeyData!.evmAddress, "0x5469C5aCB0F30929226AfF4622918DA8E1424a8D")
XCTAssertEqual(val.finalKeyData!.X, "c20fac685bb67169e92f1d5d8894d4eea18753c0ef3b7b1b2224233b2dfa3539")
XCTAssertEqual(val.finalKeyData!.Y, "c4f080b5c8d5c55c8eaba4bec70f668f36db4126f358b491d631fefea7c19d21")
XCTAssertEqual(val.metadata?.nonce, 0)
XCTAssertEqual(val.metadata?.upgraded, false)
XCTAssertEqual(val.metadata?.typeOfUser, .v1)
XCTAssertEqual(val.metadata?.typeOfUser, .v2)
XCTAssertEqual(val.nodesData?.nodeIndexes.count, 0)
}

Expand Down
14 changes: 6 additions & 8 deletions Tests/TorusUtilsTests/CyanTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ import BigInt
import CommonSources
import FetchNodeDetails
import JWTKit
#if canImport(secp256k1)
import secp256k1
#endif
import XCTest

import CoreMedia
Expand Down Expand Up @@ -56,13 +53,14 @@ class CyanTest: XCTestCase {
XCTAssertEqual(data.oAuthKeyData?.evmAddress, "0xA3767911A84bE6907f26C572bc89426dDdDB2825")
XCTAssertEqual(data.oAuthKeyData?.X, "2853f323437da98ce021d06854f4b292db433c0ad03b204ef223ac2583609a6a")
XCTAssertEqual(data.oAuthKeyData?.Y, "f026b4788e23523e0c8fcbf0bdcf1c1a62c9cde8f56170309607a7a52a19f7c1")
XCTAssertEqual(data.finalKeyData?.evmAddress, "0xA3767911A84bE6907f26C572bc89426dDdDB2825")
XCTAssertEqual(data.finalKeyData?.X, "2853f323437da98ce021d06854f4b292db433c0ad03b204ef223ac2583609a6a")
XCTAssertEqual(data.finalKeyData?.Y, "f026b4788e23523e0c8fcbf0bdcf1c1a62c9cde8f56170309607a7a52a19f7c1")
XCTAssertNil(data.metadata?.pubNonce)
XCTAssertEqual(data.finalKeyData?.evmAddress, "0x3507F0d192a44E436B8a6C32a37d57D022861b1a")
XCTAssertEqual(data.finalKeyData?.X, "8aaadab9530cb157d0b0dfb7b27d1a3aaca45274563c22c92c77ee2191779051")
XCTAssertEqual(data.finalKeyData?.Y, "d57b89d9f62bb6609d8542c3057943805c8c72f6f27d39781b820f27d7210f12")
XCTAssertEqual(data.metadata?.pubNonce?.x, "5f2505155e2c1119ee8a76d0f3b22fccee45871d4aab3cb6209bdbc302b5abc2")
XCTAssertEqual(data.metadata?.pubNonce?.y, "a20f30868759a6095697d5631483faa650f489b33c0e2958ad8dc29e707c0a99")
XCTAssertEqual(data.metadata?.nonce, BigUInt.zero)
XCTAssertEqual(data.metadata?.upgraded, false)
XCTAssertEqual(data.metadata?.typeOfUser, .v1)
XCTAssertEqual(data.metadata?.typeOfUser, .v2)
XCTAssertEqual(data.nodesData?.nodeIndexes, [])

verifier = "tkey-google-cyan"
Expand Down
17 changes: 11 additions & 6 deletions Tests/TorusUtilsTests/IntegrationTest.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import BigInt
import FetchNodeDetails
import JWTKit
#if canImport(secp256k1)
import secp256k1
#endif
import XCTest

import CommonSources
Expand Down Expand Up @@ -65,18 +62,22 @@ class IntegrationTests: XCTestCase {
XCTAssertEqual(val.finalKeyData?.evmAddress, "0xE91200d82029603d73d6E307DbCbd9A7D0129d8D")
}

/* TODO: Investigate this further
func test_keyAssign() async throws {
let email = generateRandomEmail(of: 6)

let nodeDetails = try await get_fnd_and_tu_data(verifer: "google-lrc", veriferID: email)
let val = try await tu.keyAssign(endpoints: nodeDetails.getTorusNodeEndpoints(), torusNodePubs: nodeDetails.getTorusNodePub(), verifier: TORUS_TEST_VERIFIER, verifierId: email, signerHost: tu.signerHost, network: .legacy(.TESTNET))
let result = val.result as! [String: Any]
guard let result = val.result as? [String: Any] else {
throw TorusUtilError.empty
}
let keys = result["keys"] as! [[String: String]]
_ = keys[0]["address"]

// Add more check to see if address is valid
}

*/

func test_keyLookup() async throws {
let nodeDetails = try await get_fnd_and_tu_data(verifer: TORUS_TEST_VERIFIER, veriferID: TORUS_TEST_EMAIL)
let val = try await tu.keyLookup(endpoints: nodeDetails.getTorusNodeEndpoints(), verifier: "google-lrc", verifierId: TORUS_TEST_EMAIL)
Expand All @@ -101,17 +102,21 @@ class IntegrationTests: XCTestCase {
XCTAssertEqual(val.finalKeyData?.evmAddress, "0x5a165d2Ed4976BD104caDE1b2948a93B72FA91D2")
}

/* TODO: Investigate this test further
func test_keyAssignAggregateLogin() async throws {
let email = generateRandomEmail(of: 6)

let nodeDetails = try await get_fnd_and_tu_data(verifer: TORUS_TEST_VERIFIER, veriferID: TORUS_TEST_EMAIL)
let val = try await tu.keyAssign(endpoints: nodeDetails.getTorusNodeEndpoints(), torusNodePubs: nodeDetails.getTorusNodePub(), verifier: TORUS_TEST_AGGREGATE_VERIFIER, verifierId: email, signerHost: signerHost, network: .legacy(.TESTNET))
let result = val.result as! [String: Any]
guard let result = val.result as? [String: Any] else {
throw TorusUtilError.empty
}
let keys = result["keys"] as! [[String: String]]
_ = keys[0]["address"]

// Add more check to see if address is valid
}
*/

func test_keyLookupAggregateLogin() async throws {
let nodeDetails = try await get_fnd_and_tu_data(verifer: TORUS_TEST_VERIFIER, veriferID: TORUS_TEST_EMAIL)
Expand Down
Loading

0 comments on commit 76c9b17

Please sign in to comment.