diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/TorusUtils.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/TorusUtils.xcscheme index d7cb3177..cf958597 100644 --- a/.swiftpm/xcode/xcshareddata/xcschemes/TorusUtils.xcscheme +++ b/.swiftpm/xcode/xcshareddata/xcschemes/TorusUtils.xcscheme @@ -61,6 +61,9 @@ + + diff --git a/License.md b/License.md index e081e7c9..5eec43ec 100644 --- a/License.md +++ b/License.md @@ -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 diff --git a/Sources/TorusUtils/Extensions/torus+extension.swift b/Sources/TorusUtils/Extensions/torus+extension.swift index ef0e9a3e..c87ec4ae 100644 --- a/Sources/TorusUtils/Extensions/torus+extension.swift +++ b/Sources/TorusUtils/Extensions/torus+extension.swift @@ -14,6 +14,7 @@ import PMKFoundation import secp256k1 import BigInt import CryptoSwift +import web3swift @available(iOS 9.0, *) extension TorusUtils { @@ -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{ + + // 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.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{ +// +// } + // MARK:- commitment request func commitmentRequest(endpoints : Array, verifier: String, pubKeyX: String, pubKeyY: String, timestamp: String, tokenCommitment: String) -> Promise<[[String:String]]>{ @@ -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 @@ -457,6 +492,14 @@ 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) @@ -464,6 +507,7 @@ extension String { }else { return self } + // String(format: "%064d", self) } } @@ -501,5 +545,9 @@ extension Data { } self = data } + + func addLeading0sForLength64() -> Data{ + Data(hex: self.toHexString().addLeading0sForLength64()) + } } diff --git a/Sources/TorusUtils/TorusUtils.swift b/Sources/TorusUtils/TorusUtils.swift index af2777ff..9c4a8338 100644 --- a/Sources/TorusUtils/TorusUtils.swift +++ b/Sources/TorusUtils/TorusUtils.swift @@ -21,10 +21,6 @@ public class TorusUtils{ } - func getMetadata() -> Promise{ - return Promise.value(BigInt(0)) - } - public func getPublicAddress(endpoints : Array, torusNodePubs : Array, verifier : String, verifierId : String, isExtended: Bool) -> Promise<[String:String]>{ let (tempPromise, seal) = Promise<[String:String]>.pending() @@ -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) @@ -102,24 +109,30 @@ public class TorusUtils{ }.then{ data -> Promise 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) diff --git a/Tests/torus-utils-swiftTests/unit_test.swift b/Tests/torus-utils-swiftTests/unit_test.swift index 38101558..067e9c62 100644 --- a/Tests/torus-utils-swiftTests/unit_test.swift +++ b/Tests/torus-utils-swiftTests/unit_test.swift @@ -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.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), diff --git a/Torus-utils.podspec b/Torus-utils.podspec index 3a2eec9c..90eab743 100644 --- a/Torus-utils.podspec +++ b/Torus-utils.podspec @@ -1,6 +1,6 @@ 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" @@ -8,7 +8,7 @@ Pod::Spec.new do |spec| spec.swift_version = "5.0" spec.author = { "Torus Labs" => "rathishubham017@gmail.com" } 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'