Skip to content

Commit

Permalink
Merge pull request #34 from tkey/encapsulate_torusnetwork
Browse files Browse the repository at this point in the history
Encapsulate torusnetwork
  • Loading branch information
himanshuchawla009 authored Nov 22, 2024
2 parents 2df2d0a + 73158e7 commit fb0ba60
Show file tree
Hide file tree
Showing 38 changed files with 86 additions and 122 deletions.
9 changes: 2 additions & 7 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,19 @@ import PackageDescription
let package = Package(
name: "tkey-mpc-swift",
platforms: [
.iOS(.v13), .macOS(.v10_15)
.iOS(.v14), .macOS(.v11)
],
products: [
// Products define the executables and libraries a package produces, and make them visible to other packages.
.library(
name: "tkey",
targets: ["tkey"]),
],
dependencies: [
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
.package(name: "TorusUtils", url: "https://github.com/torusresearch/torus-utils-swift" , from: "8.1.0"),
.package(name: "TorusUtils", url: "https://github.com/torusresearch/torus-utils-swift", from: "10.0.0"),
// dev dependencies only
.package(name:"jwt-kit", url: "https://github.com/vapor/jwt-kit.git", from: "4.0.0"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages this package depends on.
.binaryTarget(name: "libtkey",
path: "Sources/libtkey/libtkey.xcframework"
),
Expand Down
6 changes: 3 additions & 3 deletions Sources/ThresholdKey/Modules/PrivateKeysModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import Foundation
#endif

public struct KeyData: Decodable {
let id: String
let privateKey: String
let type: String
public let id: String
public let privateKey: String
public let type: String
}

public final class PrivateKeysModule {
Expand Down
14 changes: 7 additions & 7 deletions Sources/ThresholdKey/Modules/TssModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public final class TssModule {
/// - tss_tag: The tss tag to be set.
///
/// - Throws: `RuntimeError`, indicates invalid parameters was used or invalid threshold key.
static func set_tss_tag(threshold_key: ThresholdKey, tss_tag: String) async throws {
public static func set_tss_tag(threshold_key: ThresholdKey, tss_tag: String) async throws {
return try await withCheckedThrowingContinuation {
continuation in
set_tss_tag(threshold_key: threshold_key, tss_tag: tss_tag) {
Expand Down Expand Up @@ -540,27 +540,27 @@ public final class TssModule {
public static func find_device_share_index(threshold_key: ThresholdKey, factor_key: String) async throws -> String {
let result = try await threshold_key.storage_layer_get_metadata(private_key: factor_key)
guard let resultData = result.data(using: .utf8) else {
throw "Invalid factor key"
throw RuntimeError("Invalid factor key")
}
guard let resultJson = try JSONSerialization.jsonObject(with: resultData) as? [String: Any] else {
throw "Invalid factor key"
throw RuntimeError("Invalid factor key")
}

var deviceShareJson = resultJson;

// backward competible
if resultJson["deviceShare"] != nil {
guard let deviceShare = resultJson["deviceShare"] as? [String: Any] else {
throw "Invalid factor key"
throw RuntimeError("Invalid factor key")
}
deviceShareJson = deviceShare
}

guard let shareJson = deviceShareJson["share"] as? [String: Any] else {
throw "Invalid factor key"
throw RuntimeError("Invalid factor key")
}
guard let shareIndex = shareJson["shareIndex"] as? String else {
throw "Invalid factor key"
throw RuntimeError("Invalid factor key")
}
return shareIndex
}
Expand All @@ -579,7 +579,7 @@ public final class TssModule {
let extendedVerifierId = try threshold_key.get_extended_verifier_id()
let split = extendedVerifierId.components(separatedBy: "\u{001c}")

let result = try await torusUtils.getPublicAddress(endpoints: nodeDetails.torusNodeEndpoints, torusNodePubs: nodeDetails.torusNodePub, verifier: split[0], verifierId: split[1], extendedVerifierId: "\(split[1])\u{0015}\(tssTag)\u{0016}\(nonce)")
let result = try await torusUtils.getPublicAddress(endpoints: nodeDetails.getTorusNodeEndpoints(), verifier: split[0], verifierId: split[1], extendedVerifierId: "\(split[1])\u{0015}\(tssTag)\u{0016}\(nonce)")

guard let x = result.finalKeyData?.X, let y = result.finalKeyData?.Y, let nodeIndexes = result.nodesData?.nodeIndexes else {
throw RuntimeError("conversion error")
Expand Down
53 changes: 17 additions & 36 deletions Sources/ThresholdKey/RssComm.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,29 @@ import Foundation

public final class RssComm {
private(set) var pointer: OpaquePointer?

// This is a placeholder to satisfy the interface,
// tracking this object is not necessary in swift as it maintains context
// on entry for the callback
private var obj_ref: UnsafeMutableRawPointer?

public static func percentEscapeString( string: String ) -> String {
var characterSet = CharacterSet.alphanumerics
characterSet.insert(charactersIn: "-.* ")
public static func percentEscapeString(string: String) -> String {
var characterSet = CharacterSet.alphanumerics
characterSet.insert(charactersIn: "-.* ")

return string
.addingPercentEncoding(withAllowedCharacters: characterSet)!
.replacingOccurrences(of: " ", with: "+")
.replacingOccurrences(of: " ", with: "+", options: [], range: nil)
return string
.addingPercentEncoding(withAllowedCharacters: characterSet)!
.replacingOccurrences(of: " ", with: "+")
.replacingOccurrences(of: " ", with: "+", options: [], range: nil)
}

public init() throws {
var errorCode: Int32 = -1

let network_interface: (@convention(c) (UnsafeMutablePointer<CChar>?, UnsafeMutablePointer<CChar>?, UnsafeMutableRawPointer?, UnsafeMutablePointer<Int32>?) -> UnsafeMutablePointer<CChar>?)? = {url, data, obj_ref, error_code in
let sem = DispatchSemaphore.init(value: 0)
let urlString = String.init(cString: url!)
let dataString = String.init(cString: data!)
let network_interface: (@convention(c) (UnsafeMutablePointer<CChar>?, UnsafeMutablePointer<CChar>?, UnsafeMutableRawPointer?, UnsafeMutablePointer<Int32>?) -> UnsafeMutablePointer<CChar>?)? = { url, data, _, error_code in
let sem = DispatchSemaphore(value: 0)
let urlString = String(cString: url!)
let dataString = String(cString: data!)
string_free(url)
string_free(data)
let url = URL(string: urlString)!
Expand All @@ -37,27 +37,9 @@ public final class RssComm {
request.addValue("*", forHTTPHeaderField: "Access-Control-Allow-Origin")
request.addValue("GET, POST", forHTTPHeaderField: "Access-Control-Allow-Methods")
request.addValue("Content-Type", forHTTPHeaderField: "Access-Control-Allow-Headers")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

if urlString.split(separator: "/").last == "bulk_set_stream" {
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")

let json = try! JSONSerialization.jsonObject(with: dataString.data(using: String.Encoding.utf8)!, options: .allowFragments) as! [[String: Any]]

var form_data: [String] = []

for (index, element) in json.enumerated() {
let json_elem = try! JSONSerialization.data(withJSONObject: element, options: .withoutEscapingSlashes)
let json_escaped_string = RssComm.percentEscapeString(string: String(data: json_elem, encoding: .utf8)!)
let final_string = String(index) + "=" + json_escaped_string
form_data.append(final_string)
}
let body_data = form_data.joined(separator: "&")

request.httpBody = body_data.data(using: String.Encoding.utf8)
} else {
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = dataString.data(using: String.Encoding.utf8)
}
request.httpBody = dataString.data(using: String.Encoding.utf8)
var resultPointer = UnsafeMutablePointer<CChar>(nil)
var result = NSString()
session.dataTask(with: request) { data, _, error in
Expand All @@ -71,7 +53,6 @@ public final class RssComm {
if let data = data {
let resultString: String = String(decoding: data, as: UTF8.self)
result = NSString(string: resultString)

}
}.resume()

Expand All @@ -81,11 +62,11 @@ public final class RssComm {
}

let result = withUnsafeMutablePointer(to: &errorCode, { error in
rss_comm(network_interface, obj_ref, error)
})
rss_comm(network_interface, obj_ref, error)
})
guard errorCode == 0 else {
throw RuntimeError("Error in RssComm")
}
}
pointer = result
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/ThresholdKey/ServiceProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public final class ServiceProvider {
let rssEndpoints = try JSONSerialization.data(withJSONObject: nodeDetails.getTorusNodeRSSEndpoints())
let tssEndpoints = try JSONSerialization.data(withJSONObject: nodeDetails.getTorusNodeTSSEndpoints())

let pub = nodeDetails.torusNodePub
let pub = nodeDetails.getTorusNodePub()
let pubkey = try JSONEncoder().encode(pub)

sss = try NodeDetails(server_endpoints: String(data: sssEndpoints, encoding: .utf8)!, server_public_keys: String(data: pubkey, encoding: .utf8)!, serverThreshold: 3)
Expand Down
Loading

0 comments on commit fb0ba60

Please sign in to comment.