Skip to content

Commit

Permalink
release 0.0.17
Browse files Browse the repository at this point in the history
  • Loading branch information
metallicalfa2 committed Jun 5, 2020
1 parent 5bf3845 commit 223f1f5
Show file tree
Hide file tree
Showing 6 changed files with 136 additions and 18 deletions.
3 changes: 3 additions & 0 deletions .swiftpm/xcode/xcshareddata/xcschemes/TorusUtils.xcscheme
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@
<Test
Identifier = "torus_utils_swiftTests/testKeyLookup()">
</Test>
<Test
Identifier = "torus_utils_swiftTests/testRetreiveShares()">
</Test>
</SkippedTests>
</TestableReference>
</Testables>
Expand Down
1 change: 0 additions & 1 deletion License.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,3 @@ Redistribution and use in source and binary forms, with or without modification,
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
x
48 changes: 48 additions & 0 deletions Sources/TorusUtils/Extensions/torus+extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import PMKFoundation
import secp256k1
import BigInt
import CryptoSwift
import web3swift

@available(iOS 9.0, *)
extension TorusUtils {
Expand Down Expand Up @@ -58,6 +59,39 @@ extension TorusUtils {
return pubKey2
}

func privateKeyToAddress(key: Data) -> Data{
print(key)
let publicKey = SECP256K1.privateToPublic(privateKey: key)!
let address = Data(publicKey.sha3(.keccak256).suffix(20))
return address
}

// MARK: metadata API
func getMetadata(dictionary: [String:String]) -> Promise<BigInt>{

// Enode data
let encoded = try! JSONSerialization.data(withJSONObject: dictionary, options: [])
let rq = self.makeUrlRequest(url: "https://metadata.tor.us/get");
let request = URLSession.shared.uploadTask(.promise, with: rq, from: encoded)

let (tempPromise, seal) = Promise<BigInt>.pending()

request.compactMap {
try JSONSerialization.jsonObject(with: $0.data) as? [String: Any]
}.done{ data in
print("metdata response", data)
seal.fulfill(BigInt(data["message"] as! String, radix: 16)!)
}.catch{ err in
seal.fulfill(BigInt("0", radix: 16)!)
}

return tempPromise
}
//
// func addMetaData() -> Promise<BigInt>{
//
// }

// MARK:- commitment request
func commitmentRequest(endpoints : Array<String>, verifier: String, pubKeyX: String, pubKeyY: String, timestamp: String, tokenCommitment: String) -> Promise<[[String:String]]>{

Expand Down Expand Up @@ -385,6 +419,7 @@ extension TorusUtils {
return URLSession.shared.uploadTask(.promise, with: request, from: rpcdata)
}.done{ data, response in
let decodedData = try! JSONDecoder().decode(JSONRPCresponse.self, from: data) // User decoder to covert to struct
print(decodedData)
seal.fulfill(decodedData)

semaphore.signal() // Signal to start again
Expand Down Expand Up @@ -457,13 +492,22 @@ extension String {
return self
}

func strip0xPrefix() -> String {
if self.hasPrefix("0x") {
let indexStart = self.index(self.startIndex, offsetBy: 2)
return String(self[indexStart...])
}
return self
}

func addLeading0sForLength64() -> String{
if self.count < 64 {
let toAdd = String(repeating: "0", count: 64 - self.count)
return toAdd + self
}else {
return self
}
// String(format: "%064d", self)
}
}

Expand Down Expand Up @@ -501,5 +545,9 @@ extension Data {
}
self = data
}

func addLeading0sForLength64() -> Data{
Data(hex: self.toHexString().addLeading0sForLength64())
}
}

43 changes: 28 additions & 15 deletions Sources/TorusUtils/TorusUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@ public class TorusUtils{

}

func getMetadata() -> Promise<BigInt>{
return Promise<BigInt>.value(BigInt(0))
}

public func getPublicAddress(endpoints : Array<String>, torusNodePubs : Array<TorusNodePub>, verifier : String, verifierId : String, isExtended: Bool) -> Promise<[String:String]>{

let (tempPromise, seal) = Promise<[String:String]>.pending()
Expand All @@ -45,13 +41,24 @@ public class TorusUtils{
}else{
return Promise<[String: String]>.value(lookupData)
}
}.done{ data in
}.then{ data in
return self.getMetadata(dictionary: ["pub_key_X":data["pub_key_X"]!, "pub_key_Y": data["pub_key_Y"]!]).map{ ($0, data) } // Tuple
}.done{ nonce, data in
var newData = data

if(nonce != BigInt(0)) {
let address = self.privateKeyToAddress(key: nonce.serialize().addLeading0sForLength64())
let newAddress = BigInt(address.toHexString(), radix: 16)! + BigInt(data["address"]!.strip0xPrefix(), radix: 16)!
print(newAddress, "newAddress")
newData["address"] = newAddress.serialize().toHexString()
}

if(!isExtended){
seal.fulfill(["address": data["address"]!])
seal.fulfill(["address": newData["address"]!])
}else{
seal.fulfill(data)
seal.fulfill(newData)
}

}.catch{err in
print("err", err)
seal.reject(TorusError.decodingError)
Expand Down Expand Up @@ -102,24 +109,30 @@ public class TorusUtils{
}.then{ data -> Promise<String> in
print("individual shares array", data)
return self.lagrangeInterpolation(shares: data)
}.done{ data in
let publicKey = SECP256K1.privateToPublic(privateKey: Data.init(hex: data) , compressed: false)?.suffix(64) // take last 64
}.then{ data -> Promise<(String, String, String)> in

// Split key in 2 parts, X and Y
// let publicKeyHex = publicKey?.toHexString()
let publicKey = SECP256K1.privateToPublic(privateKey: Data.init(hex: data) , compressed: false)?.suffix(64) // take last 64
let pubKeyX = publicKey?.prefix(publicKey!.count/2).toHexString()
let pubKeyY = publicKey?.suffix(publicKey!.count/2).toHexString()
print("private key rebuild", data, pubKeyX as Any, pubKeyY as Any)

print("private key rebuild", data, pubKeyX, pubKeyY)

// Verify
if( pubKeyX == nodeReturnedPubKeyX && pubKeyY == nodeReturnedPubKeyY) {
self.privateKey = data
seal.fulfill(data)

return Promise<(String, String, String)>.value((pubKeyX!, pubKeyY!, data)) //Tuple
}else{
throw "could not derive private key"
}
}.then{ x, y, key in
return self.getMetadata(dictionary: ["pub_key_X": x, "pub_key_Y": y]).map{ ($0, key) } // Tuple
}.done{ nonce, key in
if(nonce != BigInt(0)) {
let newKey = nonce + BigInt(key, radix: 16)!
print(newKey)
seal.fulfill(newKey.serialize().suffix(64).toHexString())
}
seal.fulfill(key)

}.catch{ err in
// print(err)
seal.reject(err)
Expand Down
55 changes: 55 additions & 0 deletions Tests/torus-utils-swiftTests/unit_test.swift
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,61 @@ final class torus_utils_swiftTests: XCTestCase {
wait(for: [exp1], timeout: 10)
}

// 8b288671081621975c9d4af918a15a5358a793c7bea4c066c37effe2f0c8d1ee unused private key

// generateMetadataParams(message, privateKey) {
// const key = this.ec.keyFromPrivate(privateKey.toString('hex', 64))
// const setData = {
// data: message,
// timestamp: new BN(Date.now()).toString(16),
// }
// const sig = key.sign(keccak256(JSON.stringify(setData)).slice(2))
// return {
// pub_key_X: key.getPublic().getX().toString('hex'),
// pub_key_Y: key.getPublic().getY().toString('hex'),
// set_data: setData,
// signature: Buffer.from(sig.r.toString(16, 64) + sig.s.toString(16, 64) + new BN(sig.v).toString(16, 2), 'hex').toString('base64'),
// }
// }

func testSetMetadata(){

let keystore = try! EthereumKeystoreV3(privateKey: Data(hex: "8b288671081621975c9d4af918a15a5358a793c7bea4c066c37effe2f0c8d1ee"))
let setData = [
"data": "8",
"timestamp": String(Int(Date().timeIntervalSince1970))
]
// print(try! JSONSerialization.data(withJSONObject: setData, options: []))
let setDataString = try! JSONSerialization.data(withJSONObject: setData, options: [])
let hash = setDataString.sha3(.keccak256)
let sign = SECP256K1.signForRecovery(hash: hash, privateKey: Data(hex: "8b288671081621975c9d4af918a15a5358a793c7bea4c066c37effe2f0c8d1ee"))
let unmarshallSig = SECP256K1.unmarshalSignature(signatureData: sign.serializedSignature!)!
print(String(data: unmarshallSig.r, encoding: .utf8))

let newData = [
"pub_key_X": "83ebc5515a6f3ad8d1d83c53b324afb7f88edc499e3bdbbd149492e460018292",
"pub_key_Y": "a0de020d476f558d69e0b54ce83277df5f6305dbe065e337be313a51ad397958",
"set_data": setData,
"signature": "SECP256K1.unmarshalSignature(signatureData: sign)"
]

//
// let encoded = try! JSONSerialization.data(withJSONObject: dictionary, options: [])
// let rq = self.makeUrlRequest(url: "https://metadata.tor.us/set");
// let request = URLSession.shared.uploadTask(.promise, with: rq, from: encoded)
//
// let (tempPromise, seal) = Promise<BigInt>.pending()
//
// request.compactMap {
// try JSONSerialization.jsonObject(with: $0.data) as? [String: Any]
// }.done{ data in
// print("metdata response", data)
// seal.fulfill(BigInt(data["message"] as! String, radix: 16)!)
// }.catch{ err in
// seal.fulfill(BigInt("1", radix: 16)!)
// }
}

var allTests = [
("testKeyLookup", testKeyLookup),
("testKeyAssign", testKeyAssign),
Expand Down
4 changes: 2 additions & 2 deletions Torus-utils.podspec
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
Pod::Spec.new do |spec|
spec.name = "Torus-utils"
spec.version = "0.0.16"
spec.version = "0.0.17"
spec.platform = :ios, "10.0"
spec.summary = "Retrieve user shares"
spec.homepage = "https://github.com/torusresearch/torus-utils-swift"
spec.license = { :type => 'BSD', :file => 'License.md' }
spec.swift_version = "5.0"
spec.author = { "Torus Labs" => "[email protected]" }
spec.module_name = "TorusUtils"
spec.source = { :git => "https://github.com/torusresearch/torus-utils-swift.git", :tag => "0.0.16" }
spec.source = { :git => "https://github.com/torusresearch/torus-utils-swift.git", :tag => "0.0.17" }
spec.source_files = "Sources/TorusUtils/*.{swift,json}","Sources/TorusUtils/**/*.{swift,json}"
spec.dependency 'Torus-fetchNodeDetails', '~> 0.0.1'
spec.dependency 'PromiseKit/Foundation', '~> 6.0'
Expand Down

0 comments on commit 223f1f5

Please sign in to comment.