Skip to content

Commit

Permalink
cleanup: remove dictionary from getMetadata() parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
metalurgical committed Jul 22, 2024
1 parent 9797680 commit 22d913f
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 22 deletions.
4 changes: 4 additions & 0 deletions Sources/TorusUtils/Extensions/String+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ extension String {
}
return "0x" + self
}

func add04PrefixUnchecked() -> String {
return "04" + self
}

func stripHexPrefix() -> String {
if hasPrefix("0x") {
Expand Down
2 changes: 1 addition & 1 deletion Sources/TorusUtils/Helpers/KeyUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public class KeyUtils {
let X = pubKeyX.addLeading0sForLength64()
let Y = pubKeyY.addLeading0sForLength64()

return prefixed ? "04" + X + Y : X + Y
return prefixed ? (X + Y).add04PrefixUnchecked() : X + Y
}

internal static func combinePublicKeys(keys: [String], compressed: Bool = false) throws -> String {
Expand Down
25 changes: 10 additions & 15 deletions Sources/TorusUtils/Helpers/MetadataUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ internal class MetadataUtils {
let secret = try SecretKey(hex: privateKey)
var publicKey = opts.ephemPublicKey
if opts.ephemPublicKey.count == 128 { // missing 04 prefix
publicKey = "04" + publicKey
publicKey = publicKey.add04PrefixUnchecked()
}
let msg = try EncryptedMessage(cipherText: opts.ciphertext, ephemeralPublicKey: PublicKey(hex: publicKey), iv: opts.iv, mac: opts.mac)
let result = try Encryption.decrypt(sk: secret, encrypted: msg)
Expand Down Expand Up @@ -65,21 +65,16 @@ internal class MetadataUtils {
return .init(pub_key_X: X, pub_key_Y: Y, setData: setData, signature: Data(hex: sigData).base64EncodedString(), keyType: keyType)
}

public static func getMetadata(legacyMetadataHost: String, dictionary: [String: String]) async throws -> BigUInt {
let encoded = try JSONSerialization.data(withJSONObject: dictionary, options: [.sortedKeys])

public static func getMetadata(legacyMetadataHost: String, params: GetMetadataParams) async throws -> BigUInt {
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
var request = try makeUrlRequest(url: "\(legacyMetadataHost)/get")
request.httpBody = encoded
request.httpBody = try encoder.encode(params)
let urlSession = URLSession(configuration: .default)
let val = try await urlSession.data(for: request)
let data = try JSONSerialization.jsonObject(with: val.0) as? [String: Any] ?? [:]
os_log("getMetadata: %@", log: getTorusLogger(log: TorusUtilsLogger.network, type: .info), type: .info, data)
guard
let msg: String = data["message"] as? String,
let ret = BigUInt(msg, radix: 16)
else {
throw TorusUtilError.decodingFailed("Message value not correct or nil in \(data)")
}
let data: GetMetadataResponse = try JSONDecoder().decode(GetMetadataResponse.self, from: val.0)
let msg: String = data.message
let ret = BigUInt(msg, radix: 16)!
return ret
}

Expand All @@ -99,14 +94,14 @@ internal class MetadataUtils {
request.httpBody = data
let urlSession = URLSession(configuration: .default)
let val = try await urlSession.data(for: request)

let decoded = try JSONDecoder().decode(GetOrSetNonceResult.self, from: val.0)
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 {
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)
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
6 changes: 3 additions & 3 deletions Sources/TorusUtils/Helpers/NodeUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ internal class NodeUtils {
}
var collected = [CommitmentRequestResult]()
for try await value in group {
if (value != nil && value?.error == nil) {
if value != nil && value?.error == nil {
collected.append(value!.result!)
received += 1
if !isImportShareReq {
Expand Down Expand Up @@ -506,13 +506,13 @@ internal class NodeUtils {
finalPubKey = try KeyUtils.combinePublicKeys(keys: [oAuthPublicKey, publicNonce])
} else {
typeOfUser = .v1
metadataNonce = BigInt(try await MetadataUtils.getMetadata(legacyMetadataHost: legacyMetadataHost, dictionary: ["pub_key_X": oAuthPublicKeyX, "pub_key_Y": oAuthPublicKeyY]))
metadataNonce = BigInt(try await MetadataUtils.getMetadata(legacyMetadataHost: legacyMetadataHost, params: GetMetadataParams(pub_key_X: oAuthPublicKeyX, pub_key_Y: oAuthPublicKeyY)))
let privateKeyWithNonce = (BigInt(oAuthKey.addLeading0sForLength64(), radix: 16)! + BigInt(metadataNonce)).modulus(KeyUtils.getOrderOfCurve())
finalPubKey = try SecretKey(hex: privateKeyWithNonce.magnitude.serialize().hexString.addLeading0sForLength64()).toPublic().serialize(compressed: false)
}
} else {
typeOfUser = .v1
metadataNonce = BigInt(try await MetadataUtils.getMetadata(legacyMetadataHost: legacyMetadataHost, dictionary: ["pub_key_X": oAuthPublicKeyX, "pub_key_Y": oAuthPublicKeyY]))
metadataNonce = BigInt(try await MetadataUtils.getMetadata(legacyMetadataHost: legacyMetadataHost, params: GetMetadataParams(pub_key_X: oAuthPublicKeyX, pub_key_Y: oAuthPublicKeyY)))
let privateKeyWithNonce = (BigInt(oAuthKey.addLeading0sForLength64(), radix: 16)! + BigInt(metadataNonce)).modulus(KeyUtils.getOrderOfCurve())
finalPubKey = try SecretKey(hex: privateKeyWithNonce.magnitude.serialize().hexString.addLeading0sForLength64()).toPublic().serialize(compressed: false)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import Foundation

internal struct GetMetadataResponse: Codable {
public var message: String

public init(message: String) {
self.message = message
}
}
10 changes: 10 additions & 0 deletions Sources/TorusUtils/Interfaces/MetaData/MetadataParams.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import Foundation

internal struct GetMetadataParams: Codable {
public var pub_key_X: String
public var pub_key_Y: String

public init(pub_key_X: String, pub_key_Y: String) {
self.pub_key_X = pub_key_X
self.pub_key_Y = pub_key_Y
}
}

internal struct MetadataParams: Codable {
public struct SetData: Codable {
public var data: String // "getNonce" || "getOrSetNonce" || String
Expand Down
4 changes: 2 additions & 2 deletions Sources/TorusUtils/TorusUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ public class TorusUtils {

if typeOfUser == .v1 {
finalPubKey = oAuthPubKey
nonce = try await MetadataUtils.getMetadata(legacyMetadataHost: legacyMetadataHost, dictionary: ["pub_key_X": X, "pub_key_Y": Y])
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())
Expand All @@ -328,7 +328,7 @@ public class TorusUtils {
} else {
typeOfUser = .v1
finalPubKey = oAuthPubKey
nonce = try await MetadataUtils.getMetadata(legacyMetadataHost: legacyMetadataHost, dictionary: ["pub_key_X": X, "pub_key_Y": Y])
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())
Expand Down
2 changes: 1 addition & 1 deletion Tests/TorusUtilsTests/BaseTests/HexEncodedString.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class HexEndodedTest: XCTestCase {
let extra_zero_padded = "06576656E".hexEncodedToString()
let double_padded = "00006576656E".hexEncodedToString()
let unpadded = "56E".hexEncodedToString()

XCTAssertEqual(odd, "odd") // 6F 64 64
XCTAssertEqual(even, "even") // 65 76 65 6E
XCTAssertEqual(extra_zero_padded, "even") // 00 65 76 65 6E
Expand Down

0 comments on commit 22d913f

Please sign in to comment.