-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathTorusUtils.swift
363 lines (312 loc) · 16.5 KB
/
TorusUtils.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import BigInt
import FetchNodeDetails
import Foundation
import OSLog
#if canImport(curveSecp256k1)
import curveSecp256k1
#endif
var utilsLogType = OSLogType.default
public class TorusUtils {
private var sessionTime: Int = 86400 // 24 hour
var allowHost: String
var serverTimeOffset: Int?
var network: Web3AuthNetwork
var clientId: String
var enableOneKey: Bool
var signerHost: String
var legacyMetadataHost: String
var apiKey: String = "torus-default"
/// Initializes TorusUtils with the provided options
///
/// - Parameters:
/// - params: `TorusOptions`
/// - logLevel: `OSLogType`, only needs to be provided if the default logging level should be changed
///
/// - Returns: `TorusUtils`
///
/// - Throws: `TorusUtilError.invalidInput`
public init(params: TorusOptions, loglevel: OSLogType = .default) throws {
var defaultHost = ""
if params.legacyMetadataHost == nil {
defaultHost = try params.network.metadataMap
} else {
defaultHost = params.legacyMetadataHost!
}
serverTimeOffset = params.serverTimeOffset
network = params.network
clientId = params.clientId
allowHost = params.network.signerMap + "/api/allow"
utilsLogType = loglevel
enableOneKey = params.enableOneKey
legacyMetadataHost = defaultHost
signerHost = params.network.signerMap + "/api/sign"
}
internal static func isLegacyNetworkRouteMap(network: Web3AuthNetwork) -> Bool {
if network.isLegacy {
return true
}
return false
}
/// Sets the apiKey
///
/// - Parameters:
/// - apiKey: The api key to be assigned
public func setApiKey(apiKey: String) {
self.apiKey = apiKey
}
/// Reverts the apiKey for `TorusUtils` to the default value
public func removeApiKey() {
apiKey = "torus-default"
}
/// Sets the sessionTime
///
/// - Parameters:
/// - sessionTime: The amount of time a session should be valid for in seconds, default is 24 hours.
public func setSessionTime(sessionTime: Int) {
self.sessionTime = sessionTime
}
/// Convenience function to quickly retrieve the postbox key from `TorusKey`
///
/// - Parameters:
/// - torusKey: `TorusKey`
///
/// - Returns: `String`
public static func getPostboxKey(torusKey: TorusKey) -> String {
if torusKey.metadata.typeOfUser == .v1 {
return torusKey.finalKeyData.privKey
}
return torusKey.oAuthKeyData.privKey
}
/// Login for the provided user
///
/// - Parameters:
/// - endpoints: The endpoints to be queried for the relevant network.
/// - verifier: The verifier to query, this can be a single verifier or an aggregate verifier.
/// - verifier_id: The identity of the user to be queried against the verifier, this is usually an emal.
/// - verifierParams: `VerifierParams`
/// - idToken: This is the identity token of the user. For single verifiers this will be a jwt, in the case of an aggregate verifier, this will be a keccak256 hash of the jwt.
///
/// - Returns: `TorusKey`
///
/// - Throws: `TorusUtilError`
public func retrieveShares(
endpoints: [String],
verifier: String,
verifierParams: VerifierParams,
idToken: String,
extraParams: TorusUtilsExtraParams = TorusUtilsExtraParams()
) async throws -> TorusKey {
if extraParams.session_token_exp_second == nil {
extraParams.session_token_exp_second = sessionTime
}
return try await NodeUtils.retrieveOrImportShare(legacyMetadataHost: legacyMetadataHost, serverTimeOffset: serverTimeOffset, enableOneKey: enableOneKey, allowHost: allowHost, network: network, clientId: clientId, endpoints: endpoints, verifier: verifier, verifierParams: verifierParams, idToken: idToken, importedShares: [], apiKey: apiKey, newPrivateKey: nil, extraParams: extraParams)
}
/// Retrieves user information, defaulting the user type to .v2
///
/// - Parameters:
/// - endpoints: The endpoints to be queried for the relevant network.
/// - verifier: The verifier to query, this can be a single verifier or an aggregate verifier.
/// - verifier_id: The identity of the user to be queried against the verifier, this is usually an emal.
/// - extended_verifier_id: This is only used if querying a tss verifier, otherwise it is not supplied. Format is (verifierId + "\u{0015}" + tssTag + "\u{0016}" + randomNonce)
///
/// - Returns: `TorusPublicKey`
///
/// - Throws: `TorusUtilError
public func getPublicAddress(endpoints: [String], verifier: String, verifierId: String, extendedVerifierId: String? = nil) async throws -> TorusPublicKey {
return try await getNewPublicAddress(endpoints: endpoints, verifier: verifier, verifierId: verifierId, extendedVerifierId: extendedVerifierId, enableOneKey: enableOneKey)
}
/// Imports a private key for the provided user
///
/// - Parameters:
/// - endpoints: The endpoints to be queried for the relevant network.
/// - nodeIndexes: The node indexes for the endpoints.
/// - nodePubKeys: The public keys for the endpoints. `TorusNodePubModel`
/// - verifier: The verifier to query, this can be a single verifier or an aggregate verifier.
/// - verifier_id: The identity of the user to be queried against the verifier, this is usually an emal.
/// - verifierParams: `VerifierParams`
/// - idToken: This is the identity token of the user. For single verifiers this will be a jwt, in the case of an aggregate verifier, this will be a keccak256 hash of the jwt.
/// - newPrivateKey: The private key that is being imported.
///
/// - Returns: `TorusKey`
///
/// - Throws: `TorusUtilError`
public func importPrivateKey(
endpoints: [String],
nodeIndexes: [BigUInt],
nodePubKeys: [TorusNodePubModel],
verifier: String,
verifierParams: VerifierParams,
idToken: String,
newPrivateKey: String,
extraParams: TorusUtilsExtraParams = TorusUtilsExtraParams()
) async throws -> TorusKey {
let nodePubs = TorusNodePubModelToINodePub(nodes: nodePubKeys)
if endpoints.count != nodeIndexes.count {
throw TorusUtilError.runtime("Length of endpoints must be the same as length of nodeIndexes")
}
let sharesData = try KeyUtils.generateShares(serverTimeOffset: serverTimeOffset ?? 0, nodeIndexes: nodeIndexes, nodePubKeys: nodePubs, privateKey: newPrivateKey)
if extraParams.session_token_exp_second == nil {
extraParams.session_token_exp_second = sessionTime
}
return try await NodeUtils.retrieveOrImportShare(legacyMetadataHost: legacyMetadataHost, serverTimeOffset: serverTimeOffset ?? 0, enableOneKey: enableOneKey, allowHost: allowHost, network: network, clientId: clientId, endpoints: endpoints, verifier: verifier, verifierParams: verifierParams, idToken: idToken, importedShares: sharesData, newPrivateKey: newPrivateKey, extraParams: extraParams)
}
/// Retrieves user information
///
/// - Parameters:
/// - endpoints: The endpoints to be queried for the relevant network.
/// - verifier: The verifier to query, this can be a single verifier or an aggregate verifier.
/// - verifier_id: The identity of the user to be queried against the verifier, this is usually an emal.
/// - extended_verifier_id: This is only used if querying a tss verifier, otherwise it is not supplied. Format is (verifierId + "\u{0015}" + tssTag + "\u{0016}" + randomNonce)
///
/// - Returns: `TorusPublicKey`
///
/// - Throws: `TorusUtilError`
public func getUserTypeAndAddress(
endpoints: [String],
verifier: String,
verifierId: String,
extendedVerifierId: String? = nil
) async throws -> TorusPublicKey {
return try await getNewPublicAddress(endpoints: endpoints, verifier: verifier, verifierId: verifierId, extendedVerifierId: extendedVerifierId, enableOneKey: true)
}
private func getNewPublicAddress(endpoints: [String], verifier: String, verifierId: String, extendedVerifierId: String? = nil, enableOneKey: Bool) async throws -> TorusPublicKey {
let keyAssignResult = try await NodeUtils.getPubKeyOrKeyAssign(endpoints: endpoints, network: network, verifier: verifier, verifierId: verifierId, legacyMetadataHost: legacyMetadataHost, serverTimeOffset: serverTimeOffset, extendedVerifierId: extendedVerifierId)
if keyAssignResult.errorResult != nil {
let error = keyAssignResult.errorResult!.message
if error.lowercased().contains("verifier not supported") {
throw TorusUtilError.runtime("Verifier not supported. Check if you: 1. Are on the right network (Torus testnet/mainnet) 2. Have setup a verifier on dashboard.web3auth.io?")
} else {
throw TorusUtilError.runtime(error)
}
}
if keyAssignResult.keyResult == nil || keyAssignResult.keyResult?.keys.count == 0 {
throw TorusUtilError.runtime("node results do not match at final lookup")
}
if keyAssignResult.nonceResult == nil && extendedVerifierId == nil && !TorusUtils.isLegacyNetworkRouteMap(network: network) {
throw TorusUtilError.runtime("metadata nonce is missing in share response")
}
let pubKey = KeyUtils.getPublicKeyFromCoords(pubKeyX: keyAssignResult.keyResult!.keys[0].pub_key_X, pubKeyY: keyAssignResult.keyResult!.keys[0].pub_key_Y)
var pubNonce: PubNonce?
let nonce: BigUInt = BigUInt(keyAssignResult.nonceResult?.nonce ?? "0", radix: 16) ?? BigUInt(0)
var oAuthPubKey: String?
var finalPubKey: String?
let finalServerTimeOffset = serverTimeOffset ?? keyAssignResult.serverTimeOffset
if extendedVerifierId != nil {
finalPubKey = pubKey
oAuthPubKey = finalPubKey
} else if TorusUtils.isLegacyNetworkRouteMap(network: network) {
let legacyKeysResult = keyAssignResult.keyResult!.keys.map({
LegacyVerifierLookupResponse.Key(pub_key_X: $0.pub_key_X, pub_key_Y: $0.pub_key_Y, address: $0.address)
})
let legacyResult = LegacyVerifierLookupResponse(keys: legacyKeysResult, serverTimeOffset: String(finalServerTimeOffset))
return try await formatLegacyPublicKeyData(finalKeyResult: legacyResult, enableOneKey: enableOneKey, isNewKey: keyAssignResult.keyResult!.is_new_key, serverTimeOffset: finalServerTimeOffset)
} else {
let (X, Y) = try KeyUtils.getPublicKeyCoords(pubKey: pubKey)
oAuthPubKey = KeyUtils.getPublicKeyFromCoords(pubKeyX: X, pubKeyY: Y)
finalPubKey = oAuthPubKey!
if keyAssignResult.nonceResult!.pubNonce != nil && !(keyAssignResult.nonceResult!.pubNonce!.x.isEmpty || keyAssignResult.nonceResult!.pubNonce!.y.isEmpty) {
let pubNonceResult = keyAssignResult.nonceResult!.pubNonce!
let pubNonceKey = KeyUtils.getPublicKeyFromCoords(pubKeyX: pubNonceResult.x, pubKeyY: pubNonceResult.y)
finalPubKey = try KeyUtils.combinePublicKeys(keys: [oAuthPubKey!, pubNonceKey])
pubNonce = pubNonceResult
} else {
throw TorusUtilError.pubNonceMissing
}
}
if oAuthPubKey == nil || finalPubKey == nil {
throw TorusUtilError.privateKeyDeriveFailed
}
let (oAuthPubKeyX, oAuthPubKeyY) = try KeyUtils.getPublicKeyCoords(pubKey: oAuthPubKey!)
let oAuthAddress = try KeyUtils.generateAddressFromPubKey(publicKeyX: oAuthPubKeyX, publicKeyY: oAuthPubKeyY)
let (finalPubKeyX, finalPubKeyY) = try KeyUtils.getPublicKeyCoords(pubKey: finalPubKey!)
let finalAddress = try KeyUtils.generateAddressFromPubKey(publicKeyX: finalPubKeyX, publicKeyY: finalPubKeyY)
return TorusPublicKey(
oAuthKeyData: TorusPublicKey.OAuthKeyData(
evmAddress: oAuthAddress,
X: oAuthPubKeyX,
Y: oAuthPubKeyY
),
finalKeyData: TorusPublicKey.FinalKeyData(
evmAddress: finalAddress,
X: finalPubKeyX,
Y: finalPubKeyY
),
metadata: TorusPublicKey.Metadata(
pubNonce: pubNonce,
nonce: nonce,
typeOfUser: .v2,
upgraded: keyAssignResult.nonceResult?.upgraded ?? false,
serverTimeOffset: finalServerTimeOffset
),
nodesData: TorusPublicKey.NodesData(
nodeIndexes: keyAssignResult.nodeIndexes
)
)
}
internal func formatLegacyPublicKeyData(finalKeyResult: LegacyVerifierLookupResponse, enableOneKey: Bool, isNewKey: Bool, serverTimeOffset: Int) async throws -> TorusPublicKey {
let firstResult = finalKeyResult.keys[0]
let X = firstResult.pub_key_X
let Y = firstResult.pub_key_Y
var nonceResult: GetOrSetNonceResult?
var finalPubKey: String?
var nonce: BigUInt?
var typeOfUser: UserType
var pubNonce: PubNonce?
let oAuthPubKey = KeyUtils.getPublicKeyFromCoords(pubKeyX: X, pubKeyY: Y)
let finalServertimeOffset = self.serverTimeOffset ?? serverTimeOffset
if enableOneKey {
nonceResult = try await MetadataUtils.getOrSetNonce(legacyMetadataHost: legacyMetadataHost, serverTimeOffset: finalServertimeOffset, X: X, Y: Y, getOnly: !isNewKey)
nonce = BigUInt(nonceResult!.nonce ?? "0", radix: 16)
typeOfUser = UserType(rawValue: nonceResult?.typeOfUser?.lowercased() ?? "v1")!
if typeOfUser == .v1 {
finalPubKey = oAuthPubKey
nonce = try await MetadataUtils.getMetadata(legacyMetadataHost: legacyMetadataHost, params: GetMetadataParams(pub_key_X: X, pub_key_Y: Y))
if nonce! > BigUInt(0) {
let noncePrivateKey = try SecretKey(hex: nonce!.magnitude.serialize().hexString.addLeading0sForLength64())
let noncePublicKey = try noncePrivateKey.toPublic().serialize(compressed: false)
finalPubKey = try KeyUtils.combinePublicKeys(keys: [finalPubKey!, noncePublicKey])
}
} else if typeOfUser == .v2 {
let pubNonceKey = KeyUtils.getPublicKeyFromCoords(pubKeyX: nonceResult!.pubNonce!.x, pubKeyY: nonceResult!.pubNonce!.y)
finalPubKey = try KeyUtils.combinePublicKeys(keys: [oAuthPubKey, pubNonceKey])
pubNonce = nonceResult!.pubNonce!
} else {
throw TorusUtilError.metadataNonceMissing
}
} else {
typeOfUser = .v1
finalPubKey = oAuthPubKey
nonce = try await MetadataUtils.getMetadata(legacyMetadataHost: legacyMetadataHost, params: GetMetadataParams(pub_key_X: X, pub_key_Y: Y))
if nonce! > BigUInt(0) {
let noncePrivateKey = try SecretKey(hex: nonce!.magnitude.serialize().hexString.addLeading0sForLength64())
let noncePublicKey = try noncePrivateKey.toPublic().serialize(compressed: false)
finalPubKey = try KeyUtils.combinePublicKeys(keys: [finalPubKey!, noncePublicKey])
}
}
let oAuthAddress = try KeyUtils.generateAddressFromPubKey(publicKeyX: X, publicKeyY: Y)
if typeOfUser == .v2 && finalPubKey == nil {
throw TorusUtilError.privateKeyDeriveFailed
}
let (finalPubKeyX, finalPubKeyY) = try KeyUtils.getPublicKeyCoords(pubKey: finalPubKey!)
let finalAddress = try KeyUtils.generateAddressFromPubKey(publicKeyX: finalPubKeyX, publicKeyY: finalPubKeyY)
return TorusPublicKey(
oAuthKeyData: TorusPublicKey.OAuthKeyData(
evmAddress: oAuthAddress,
X: X.addLeading0sForLength64(),
Y: Y.addLeading0sForLength64()
),
finalKeyData: TorusPublicKey.FinalKeyData(
evmAddress: finalAddress,
X: finalPubKeyX,
Y: finalPubKeyY
),
metadata: TorusPublicKey.Metadata(
pubNonce: pubNonce,
nonce: nonce,
typeOfUser: typeOfUser,
upgraded: nonceResult?.upgraded ?? false,
serverTimeOffset: finalServertimeOffset),
nodesData: TorusPublicKey.NodesData(nodeIndexes: [])
)
}
}