Skip to content

Commit

Permalink
strip out relevant legacy code
Browse files Browse the repository at this point in the history
  • Loading branch information
metalurgical committed May 14, 2024
1 parent 3efc132 commit 57c7a99
Show file tree
Hide file tree
Showing 6 changed files with 4 additions and 561 deletions.
17 changes: 0 additions & 17 deletions Sources/TorusUtils/Helpers/Common.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,6 @@ internal func normalizeKeysResult(result: VerifierLookupResponse) -> KeyLookupRe
return finalResult
}

internal func normalizeLegacyKeysResult(result: LegacyVerifierLookupResponse) -> LegacyKeyLookupResult.LegacyKeyResult {
var finalResult = LegacyKeyLookupResult.LegacyKeyResult()

if !result.keys.isEmpty {
let finalKey = result.keys[0]
finalResult.keys = [
LegacyVerifierLookupResponse.Key(
pub_key_X: finalKey.pub_key_X,
pub_key_Y: finalKey.pub_key_Y,
address: finalKey.address
),
]
}

return finalResult
}

internal func kCombinations<T>(elements: ArraySlice<T>, k: Int) -> [[T]] {
if k == 0 || k > elements.count {
return []
Expand Down
131 changes: 0 additions & 131 deletions Sources/TorusUtils/Helpers/NodeUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -526,135 +526,4 @@ public class NodeUtils {
)
)
}

public static func legacyKeyLookup(endpoints: [String], verifier: String, verifierId: String, timeout: TimeInterval = TimeInterval(0)) async throws -> LegacyKeyLookupResult {
let session = URLSession(configuration: .default)
if timeout != TimeInterval(0) {
session.configuration.timeoutIntervalForRequest = timeout
}

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let params = VerifierLookupParams(verifier: verifier, verifier_id: verifierId, client_time: String(Int(floor(Double(Date().timeIntervalSince1970 / 1000)))))
let jRPCRequest = JRPCRequest(
method: JRPC_METHODS.VERIFIER_LOOKUP_REQUEST,
params: params)
let rpcdata = try encoder.encode(jRPCRequest)

let lookupResults: [JRPCResponse<LegacyVerifierLookupResponse>?] = try await withThrowingTaskGroup(of: JRPCResponse?.self, returning: [JRPCResponse<LegacyVerifierLookupResponse>?].self) { group -> [JRPCResponse?] in
for endpoint in endpoints {
group.addTask {
do {
var request = try MetadataUtils.makeUrlRequest(url: endpoint)
request.httpBody = rpcdata
let val = try await URLSession(configuration: .default).data(for: request)
let decoded = try JSONDecoder().decode(JRPCResponse<LegacyVerifierLookupResponse>.self, from: val.0)
return decoded
} catch {
return nil
}
}
}
var collected = [JRPCResponse<LegacyVerifierLookupResponse>?]()
for try await value in group {
collected.append(value)
}
return collected
}

let lookupShares = lookupResults.filter({ $0 != nil })

let threshold = Int(trunc(Double(endpoints.count / 2) + 1))

let errorResult = try thresholdSame(arr: lookupShares.map({ $0?.error }), threshold: threshold)

let keyResults = lookupResults.filter({ $0 != nil && $0?.result != nil }).map { normalizeLegacyKeysResult(result: ($0!.result)!) }

let keyResult = try thresholdSame(arr: keyResults, threshold: threshold)

var serverTimeOffsets: [Int] = []

if keyResult != nil {
for item in keyResults {
let timeOffset = item.server_time_offset
serverTimeOffsets.append(Int(timeOffset ?? "0")!)
}
}

if keyResult == nil && errorResult == nil {
throw TorusUtilError.apiRequestFailed
}

let serverTimeOffset = keyResult != nil ? calculateMedian(arr: serverTimeOffsets) : 0

return LegacyKeyLookupResult(keyResult: keyResult, errorResult: errorResult as? ErrorMessage, serverTimeOffset: serverTimeOffset)
}

public static func legacyKeyAssign(keyAssignInput: KeyAssignInput, apiKey: String) async throws {
var nodeNum: Int = 0
var initialPoint: Int?
if keyAssignInput.lastPoint == nil {
nodeNum = Int(floor(Double(Int.random(in: 0 ..< 1) * keyAssignInput.endpoints.count)))
initialPoint = nodeNum
} else {
nodeNum = (keyAssignInput.lastPoint ?? 0) / keyAssignInput.endpoints.count
}

// This check looked like it should appear before the next check
// since the next check could have compared zero to nil
if keyAssignInput.firstPoint != nil {
initialPoint = keyAssignInput.firstPoint!
}

if nodeNum == initialPoint {
throw TorusUtilError.apiRequestFailed
}

let params = SignerParams(verifier: keyAssignInput.verifier, varifier_id: keyAssignInput.verifierId)
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys

let session = URLSession(configuration: .default)
var request = try MetadataUtils.makeUrlRequest(url: keyAssignInput.signerHost)
request.addValue(apiKey, forHTTPHeaderField: "x-api-key")
request.addValue(keyAssignInput.torusNodePubs[nodeNum].X, forHTTPHeaderField: "pubkeyx")
request.addValue(keyAssignInput.torusNodePubs[nodeNum].Y, forHTTPHeaderField: "pubkeyy")
request.addValue(keyAssignInput.network.name, forHTTPHeaderField: "network")
request.addValue(keyAssignInput.clientId, forHTTPHeaderField: "clientId")
let data = try encoder.encode(params)
request.httpBody = data

let response: (Data, URLResponse) = try await session.data(for: request)
let signerResponse = try JSONDecoder().decode(SignerResponse.self, from: response.0)

let keyAssignRequestParams = KeyAssignRequestParams(params: params, signerResponse: signerResponse)
let newData = try encoder.encode(keyAssignRequestParams)

var request2 = try MetadataUtils.makeUrlRequest(url: keyAssignInput.endpoints[nodeNum])
request2.httpBody = newData

let keyAssignRequestData: (Data, URLResponse) = try await session.data(for: request2)

let decodedData = try JSONDecoder().decode(JRPCResponse<NoReply>.self, from: keyAssignRequestData.0)

if decodedData.error != nil && (
[502, 504, 401].contains(decodedData.error!.code) ||
["Timed out",
"Failed to fetch",
"cancelled",
"NetworkError when attempting to fetch resource.",
"TypeError: Failed to fetch",
"TypeError: cancelled",
"TypeError: NetworkError when attempting to fetch resource.",
"reason: getaddrinfo EAI_AGAIN"].contains(decodedData.error!.message)
) {
var retry = keyAssignInput
retry.lastPoint = nodeNum + 1
try await legacyKeyAssign(keyAssignInput: retry, apiKey: apiKey)
}
}

public static func legacyWaitKeyLookup(endpoints: [String], verifier: String, verifierId: String, timeout: TimeInterval) async throws -> LegacyKeyLookupResult {
try await legacyKeyLookup(endpoints: endpoints, verifier: verifier, verifierId: verifierId, timeout: timeout)
}
}

This file was deleted.

This file was deleted.

This file was deleted.

Loading

0 comments on commit 57c7a99

Please sign in to comment.