Skip to content

Commit

Permalink
Merge pull request #110 from torusresearch/encapsulate_torusnetwork
Browse files Browse the repository at this point in the history
refactor: update to latest fetch node details
  • Loading branch information
chaitanyapotti authored Oct 24, 2024
2 parents 0ac2810 + 2278e11 commit baa822f
Show file tree
Hide file tree
Showing 18 changed files with 68 additions and 81 deletions.
18 changes: 9 additions & 9 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{
"identity" : "bigint",
"kind" : "remoteSourceControl",
"location" : "https://github.com/attaswift/BigInt",
"location" : "https://github.com/attaswift/BigInt.git",
"state" : {
"revision" : "0ed110f7555c34ff468e72e1686e59721f2b0da6",
"version" : "5.3.0"
Expand All @@ -14,26 +14,26 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/tkey/curvelib.swift",
"state" : {
"revision" : "9f88bd5e56d1df443a908f7a7e81ae4f4d9170ea",
"version" : "1.0.1"
"revision" : "432bf1abe7ff505fc2ac9fcf697341ff5b2dc6d0",
"version" : "2.0.0"
}
},
{
"identity" : "fetch-node-details-swift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/torusresearch/fetch-node-details-swift.git",
"location" : "https://github.com/torusresearch/fetch-node-details-swift",
"state" : {
"revision" : "4bd96c33ba8d02d9e27190c5c7cedf09cfdfd656",
"version" : "6.0.3"
"revision" : "52fb5efaa94e0fe3775913ab00964bcb51601c2a",
"version" : "8.0.0"
}
},
{
"identity" : "jwt-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/jwt-kit",
"location" : "https://github.com/vapor/jwt-kit.git",
"state" : {
"revision" : "e05513b5aec24f88012b6e3034115b6bc915356a",
"version" : "4.13.2"
"revision" : "c2595b9ad7f512d7f334830b4df1fed6e917946a",
"version" : "4.13.4"
}
},
{
Expand Down
6 changes: 3 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
import PackageDescription
let package = Package(
name: "TorusUtils",
platforms: [.iOS(.v13), .macOS(.v10_15)],
platforms: [.iOS(.v14), .macOS(.v10_15)],
products: [
.library(
name: "TorusUtils",
targets: ["TorusUtils"])
],
dependencies: [
.package(url: "https://github.com/tkey/curvelib.swift", from: "1.0.1"),
.package(url: "https://github.com/torusresearch/fetch-node-details-swift", from: "6.0.3"),
.package(url: "https://github.com/tkey/curvelib.swift", from: "2.0.0"),
.package(url: "https://github.com/torusresearch/fetch-node-details-swift", from: "8.0.0"),
// NB: jwt-kit may only be a dependency in tests or it will break cocoapod support
.package(url: "https://github.com/vapor/jwt-kit.git", from: "4.0.0"),
],
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ You can install the TorusUtils using Swift Package Manager:
...
dependencies: [
...
.package(url: "https://github.com/torusresearch/torus-utils-swift", from: "9.0.0")
.package(url: "https://github.com/torusresearch/torus-utils-swift", from: "10.0.0")
],
targets: [
.target( name: "<INSERT_TARGET_NAME>",
Expand All @@ -30,15 +30,15 @@ Or CocoaPods:

```
...
pod 'Torus-utils', '~> 9.0.0'
pod 'Torus-utils', '~> 10.0.0'
...
```

## Getting Started
Initialize the `TorusUtils` class by passing `TorusOptions` as params. Params includes `TorusNetwork`, `enableOneKey`, and your `clientId`. `enableOneKey` if true, adds the nonce value to the key, to make it compatible with v2 users. The package supports both legacy and sapphire networks.

```swift
let torusUtils = TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .sapphire(.SAPPHIRE_MAINNET), enableOneKey: true))
let torusUtils = TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .SAPPHIRE_MAINNET, enableOneKey: true))
```


Expand Down
6 changes: 3 additions & 3 deletions Sources/TorusUtils/Helpers/Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public enum TorusUtilError: Error, Equatable {
case invalidKeySize
case invalidPubKeySize
case runtime(_ msg: String)
case retrieveOrImportShareError
case retrieveOrImportShareError(_ msg: String)
case metadataNonceMissing
case pubNonceMissing
case gatingError(_ msg: String = "")
Expand Down Expand Up @@ -46,8 +46,8 @@ extension TorusUtilError: CustomDebugStringConvertible {
return "Invalid key size. Expected 64 bytes"
case let .encodingFailed(msg):
return "Could not encode data" + msg
case .retrieveOrImportShareError:
return "retrieve or import share failed"
case let .retrieveOrImportShareError(msg):
return msg
case .metadataNonceMissing:
return "Unable to fetch metadata nonce"
case let .gatingError(msg):
Expand Down
6 changes: 3 additions & 3 deletions Sources/TorusUtils/Helpers/MetadataUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ internal class MetadataUtils {
let val = try await urlSession.data(for: request)
let data: GetMetadataResponse = try JSONDecoder().decode(GetMetadataResponse.self, from: val.0)
let msg: String = data.message
let ret = BigUInt(msg, radix: 16)!
let ret = BigUInt(msg, radix: 16) ?? 0
return ret
}

Expand All @@ -82,8 +82,8 @@ internal class MetadataUtils {
return decoded
}

public static func getOrSetSapphireMetadataNonce(metadataHost: String, network: TorusNetwork, X: String, Y: String, serverTimeOffset: Int? = nil, privateKey: String? = nil, getOnly: Bool = false, keyType: TorusKeyType = .secp256k1) async throws -> GetOrSetNonceResult {
if case .sapphire = network {
public static func getOrSetSapphireMetadataNonce(metadataHost: String, network: Web3AuthNetwork, X: String, Y: String, serverTimeOffset: Int? = nil, privateKey: String? = nil, getOnly: Bool = false, keyType: TorusKeyType = .secp256k1) async throws -> GetOrSetNonceResult {
if network.isSapphire {
return try await getOrSetNonce(legacyMetadataHost: metadataHost, serverTimeOffset: serverTimeOffset ?? Int(trunc(Double(0 + Int(Date().timeIntervalSince1970)))), X: X, Y: Y, privateKey: privateKey, getOnly: getOnly, keyType: keyType)
} else {
throw TorusUtilError.metadataNonceMissing
Expand Down
14 changes: 7 additions & 7 deletions Sources/TorusUtils/Helpers/NodeUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import OSLog
internal class NodeUtils {
public static func getPubKeyOrKeyAssign(
endpoints: [String],
network: TorusNetwork,
network: Web3AuthNetwork,
verifier: String,
verifierId: String,
legacyMetadataHost: String,
Expand Down Expand Up @@ -122,7 +122,7 @@ internal class NodeUtils {
serverTimeOffset: Int?,
enableOneKey: Bool,
allowHost: String,
network: TorusNetwork,
network: Web3AuthNetwork,
clientId: String,
endpoints: [String],
verifier: String,
Expand Down Expand Up @@ -364,7 +364,7 @@ internal class NodeUtils {
}

if thresholdPublicKey == nil {
throw TorusUtilError.retrieveOrImportShareError
throw TorusUtilError.retrieveOrImportShareError("invalid result from nodes, threshold number of public key results are not matching, please check configuration")
}

for item in shareResponses {
Expand Down Expand Up @@ -395,7 +395,7 @@ internal class NodeUtils {

// Invert comparision to return error early
if !(shareResponses.count >= thresholdReqCount && thresholdPublicKey != nil && (thresholdNonceData != nil || verifierParams.extended_verifier_id != nil || TorusUtils.isLegacyNetworkRouteMap(network: network))) {
throw TorusUtilError.retrieveOrImportShareError
throw TorusUtilError.retrieveOrImportShareError("invalid result from nodes, threshold number of public key results are not matching")
}

var shares: [String?] = []
Expand Down Expand Up @@ -450,13 +450,13 @@ internal class NodeUtils {
let validSigs = sessionTokenSigs.filter({ $0 != nil }).map({ $0! })

if verifierParams.extended_verifier_id == nil && validSigs.count < threshold {
throw TorusUtilError.retrieveOrImportShareError
throw TorusUtilError.retrieveOrImportShareError("Insufficient number of signatures from nodes")
}

let validTokens = sessionTokens.filter({ $0 != nil }).map({ $0! })

if verifierParams.extended_verifier_id == nil && validTokens.count < threshold {
throw TorusUtilError.runtime("Insufficient number of signatures from nodes")
throw TorusUtilError.retrieveOrImportShareError("Insufficient number of signatures from nodes")
}

for (i, item) in sessionTokens.enumerated() {
Expand Down Expand Up @@ -560,7 +560,7 @@ internal class NodeUtils {
}

if finalPubKey == nil {
throw TorusUtilError.retrieveOrImportShareError
throw TorusUtilError.retrieveOrImportShareError("Invalid public key, this might be a bug, please report this to web3auth team")
}

let oAuthKeyAddress = try KeyUtils.generateAddressFromPubKey(publicKeyX: oAuthPublicKeyX, publicKeyY: oAuthPublicKeyY)
Expand Down
4 changes: 2 additions & 2 deletions Sources/TorusUtils/Interfaces/TorusOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import Foundation
public class TorusOptions {
public var enableOneKey: Bool
public var clientId: String
public var network: TorusNetwork
public var network: Web3AuthNetwork
public var serverTimeOffset: Int
public var legacyMetadataHost: String?

Expand All @@ -19,7 +19,7 @@ public class TorusOptions {
/// - enableOneKey: Use the oneKey flow.
///
/// - Returns: `TorusOptions`
public init(clientId: String, network: TorusNetwork, legacyMetadataHost: String? = nil, serverTimeOffset: Int = 0, enableOneKey: Bool = false) {
public init(clientId: String, network: Web3AuthNetwork, legacyMetadataHost: String? = nil, serverTimeOffset: Int = 0, enableOneKey: Bool = false) {
self.clientId = clientId
self.enableOneKey = enableOneKey
self.network = network
Expand Down
21 changes: 4 additions & 17 deletions Sources/TorusUtils/TorusUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class TorusUtils {

var serverTimeOffset: Int?

var network: TorusNetwork
var network: Web3AuthNetwork

var clientId: String

Expand All @@ -39,20 +39,7 @@ public class TorusUtils {
public init(params: TorusOptions, loglevel: OSLogType = .default) throws {
var defaultHost = ""
if params.legacyMetadataHost == nil {
if case let .legacy(urlHost) = params.network {
defaultHost = urlHost.metadataMap
} else {
// TODO: Move this into fetchNodeDetails metadataMap
if case let .sapphire(sapphireNetwork) = params.network {
if sapphireNetwork == .SAPPHIRE_MAINNET {
defaultHost = "https://node-1.node.web3auth.io/metadata"
} else {
defaultHost = "https://node-1.dev-node.web3auth.io/metadata"
}
} else {
throw TorusUtilError.invalidInput
}
}
defaultHost = try params.network.metadataMap
} else {
defaultHost = params.legacyMetadataHost!
}
Expand All @@ -67,8 +54,8 @@ public class TorusUtils {
signerHost = params.network.signerMap + "/api/sign"
}

internal static func isLegacyNetworkRouteMap(network: TorusNetwork) -> Bool {
if case .legacy = network {
internal static func isLegacyNetworkRouteMap(network: Web3AuthNetwork) -> Bool {
if network.isLegacy {
return true
}
return false
Expand Down
4 changes: 2 additions & 2 deletions Tests/TorusUtilsTests/AquaTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ class AquaTest: XCTestCase {

override func setUp() {
super.setUp()
fnd = NodeDetailManager(network: .legacy(.AQUA))
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .legacy(.AQUA)))
fnd = NodeDetailManager(network: .AQUA)
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .AQUA))
}

func test_should_fetch_public_address() async throws {
Expand Down
8 changes: 4 additions & 4 deletions Tests/TorusUtilsTests/Celeste.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ class CelesteTest: XCTestCase {

override func setUp() {
super.setUp()
fnd = NodeDetailManager(network: .legacy(.CELESTE))
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .legacy(.CELESTE)))
fnd = NodeDetailManager(network: .CELESTE)
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .CELESTE))
}

func test_should_fetch_public_address() async throws {
let verifier = "tkey-google-celeste"
let verifierID = TORUS_TEST_EMAIL
let nodeDetails = try await fnd.getNodeDetails(verifier: verifier, verifierID: verifierID)
let val = try await torus.getPublicAddress(endpoints: nodeDetails.torusNodeEndpoints, verifier: verifier, verifierId: verifierID)
let val = try await torus.getPublicAddress(endpoints: nodeDetails.getTorusNodeEndpoints(), verifier: verifier, verifierId: verifierID)

XCTAssertEqual(val.finalKeyData!.evmAddress, "0xC3115b9d6FaB99739b23DA9dfcBA47A4Ec4Cd113")
XCTAssertLessThan(val.metadata!.serverTimeOffset, 20)
Expand Down Expand Up @@ -148,7 +148,7 @@ class CelesteTest: XCTestCase {
let nodeDetails = try await fnd.getNodeDetails(verifier: verifier, verifierID: verifierID)

let verifierParams = VerifierParams(verifier_id: verifierID, sub_verifier_ids: [TORUS_TEST_VERIFIER], verify_params: [VerifyParams(verifier_id: verifierID, idtoken: jwt)])
let data = try await torus.retrieveShares(endpoints: nodeDetails.torusNodeEndpoints, verifier: verifier, verifierParams: verifierParams, idToken: hashedIDToken)
let data = try await torus.retrieveShares(endpoints: nodeDetails.getTorusNodeEndpoints(), verifier: verifier, verifierParams: verifierParams, idToken: hashedIDToken)

XCTAssertEqual(data.finalKeyData.evmAddress, "0x535Eb1AefFAc6f699A2a1A5846482d7b5b2BD564")
XCTAssertLessThan(data.metadata.serverTimeOffset, 20)
Expand Down
4 changes: 2 additions & 2 deletions Tests/TorusUtilsTests/CyanTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ class CyanTest: XCTestCase {

override func setUp() {
super.setUp()
fnd = NodeDetailManager(network: .legacy(.CYAN))
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .legacy(.CYAN)))
fnd = NodeDetailManager(network: .CYAN)
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .CYAN))
}

func test_should_fetch_public_address() async throws {
Expand Down
8 changes: 4 additions & 4 deletions Tests/TorusUtilsTests/MainnetTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@ class MainnetTests: XCTestCase {

override func setUp() {
super.setUp()
fnd = NodeDetailManager(network: .legacy(.MAINNET))
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .legacy(.MAINNET)))
fnd = NodeDetailManager(network: .MAINNET)
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .MAINNET))
}

func test_should_fetch_public_address() async throws {
let verifier = "google"
let verifierID = TORUS_TEST_EMAIL
let nodeDetails = try await fnd.getNodeDetails(verifier: verifier, verifierID: verifierID)
let val = try await torus.getPublicAddress(endpoints: nodeDetails.torusNodeEndpoints, verifier: verifier, verifierId: verifierID)
let val = try await torus.getPublicAddress(endpoints: nodeDetails.getTorusNodeEndpoints(), verifier: verifier, verifierId: verifierID)

XCTAssertEqual(val.finalKeyData!.evmAddress, "0x0C44AFBb5395a9e8d28DF18e1326aa0F16b9572A")
XCTAssertLessThan(val.metadata!.serverTimeOffset, 20)
Expand Down Expand Up @@ -156,7 +156,7 @@ class MainnetTests: XCTestCase {
let nodeDetails = try await fnd.getNodeDetails(verifier: verifier, verifierID: verifierID)

let verifierParams = VerifierParams(verifier_id: verifierID, sub_verifier_ids: [TORUS_TEST_VERIFIER], verify_params: [VerifyParams(verifier_id: verifierID, idtoken: jwt)])
let data = try await torus.retrieveShares(endpoints: nodeDetails.torusNodeEndpoints, verifier: verifier, verifierParams: verifierParams, idToken: hashedIDToken)
let data = try await torus.retrieveShares(endpoints: nodeDetails.getTorusNodeEndpoints(), verifier: verifier, verifierParams: verifierParams, idToken: hashedIDToken)

XCTAssertEqual(data.finalKeyData.evmAddress, "0x621a4d458cFd345dAE831D9E756F10cC40A50381")
XCTAssertLessThan(data.metadata.serverTimeOffset, 20)
Expand Down
4 changes: 2 additions & 2 deletions Tests/TorusUtilsTests/SapphireDevnetTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ final class SapphireDevnetTest: XCTestCase {

override func setUp() {
super.setUp()
fnd = NodeDetailManager(network: .sapphire(.SAPPHIRE_DEVNET))
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .sapphire(.SAPPHIRE_DEVNET)))
fnd = NodeDetailManager(network: .SAPPHIRE_DEVNET)
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .SAPPHIRE_DEVNET))
}

func test_should_fetch_public_address() async throws {
Expand Down
4 changes: 2 additions & 2 deletions Tests/TorusUtilsTests/SapphireMainnetTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ class SapphireMainnetTests: XCTestCase {

override func setUp() {
super.setUp()
fnd = NodeDetailManager(network: .sapphire(.SAPPHIRE_MAINNET))
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .sapphire(.SAPPHIRE_MAINNET), enableOneKey: true))
fnd = NodeDetailManager(network: .SAPPHIRE_MAINNET)
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .SAPPHIRE_MAINNET, enableOneKey: true))
}

func test_should_fetch_public_address() async throws {
Expand Down
8 changes: 4 additions & 4 deletions Tests/TorusUtilsTests/TestnetTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ class TestnetTest: XCTestCase {

override func setUp() {
super.setUp()
fnd = NodeDetailManager(network: .legacy(.TESTNET))
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .legacy(.TESTNET)))
fnd = NodeDetailManager(network: .TESTNET)
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .TESTNET))
}

func test_should_fetch_public_address() async throws {
let verifier = "google-lrc"
let verifierID = TORUS_TEST_EMAIL
let nodeDetails = try await fnd.getNodeDetails(verifier: verifier, verifierID: verifierID)
let val = try await torus.getPublicAddress(endpoints: nodeDetails.torusNodeEndpoints, verifier: verifier, verifierId: verifierID)
let val = try await torus.getPublicAddress(endpoints: nodeDetails.getTorusNodeEndpoints(), verifier: verifier, verifierId: verifierID)

XCTAssertEqual(val.finalKeyData!.evmAddress, "0x9bcBAde70546c0796c00323CD1b97fa0a425A506")
XCTAssertLessThan(val.metadata!.serverTimeOffset, 20)
Expand Down Expand Up @@ -149,7 +149,7 @@ class TestnetTest: XCTestCase {
let verifierParams = VerifierParams(verifier_id: verifierID,
sub_verifier_ids: [TORUS_TEST_VERIFIER],
verify_params: [VerifyParams(verifier_id: verifierID, idtoken: jwt)])
let data = try await torus.retrieveShares(endpoints: nodeDetails.torusNodeEndpoints, verifier: verifier, verifierParams: verifierParams, idToken: hashedIDToken)
let data = try await torus.retrieveShares(endpoints: nodeDetails.getTorusNodeEndpoints(), verifier: verifier, verifierParams: verifierParams, idToken: hashedIDToken)

XCTAssertEqual(data.finalKeyData.evmAddress, "0x938a40E155d118BD31E439A9d92D67bd55317965")
XCTAssertLessThan(data.metadata.serverTimeOffset, 20)
Expand Down
4 changes: 2 additions & 2 deletions Tests/TorusUtilsTests/oneKeyTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ class OneKeyTest: XCTestCase {

override func setUp() {
super.setUp()
fnd = NodeDetailManager(network: .legacy(.TESTNET))
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .legacy(.TESTNET), enableOneKey: true))
fnd = NodeDetailManager(network: .TESTNET)
torus = try! TorusUtils(params: TorusOptions(clientId: "YOUR_CLIENT_ID", network: .TESTNET, enableOneKey: true))
}

func test_should_still_fetch_v1_address_correctly() async throws {
Expand Down
Loading

0 comments on commit baa822f

Please sign in to comment.