Skip to content

Commit

Permalink
Merge pull request #3 from torusresearch/feat/lagrangeInterpolation
Browse files Browse the repository at this point in the history
updated lagrage interpolation;
  • Loading branch information
rathishubham7 authored Feb 22, 2021
2 parents 03f4e69 + c88192c commit 920b909
Show file tree
Hide file tree
Showing 445 changed files with 459 additions and 254 deletions.
4 changes: 2 additions & 2 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@
"repositoryURL": "https://github.com/torusresearch/fetch-node-details-swift",
"state": {
"branch": null,
"revision": "172efe5e39c525927142b457b826a250fa0dfe07",
"version": "0.1.1"
"revision": "7d93d8c98d45c723d4836e9406282dda237e48cb",
"version": "0.1.2"
}
},
{
Expand Down
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ let package = Package(
dependencies: [
.package(url: "https://github.com/rathishubham7/web3swift", from:"2.0.0"),
.package(url: "https://github.com/rathishubham7/swift-logger", from:"0.0.1"),
.package(url: "https://github.com/torusresearch/fetch-node-details-swift", from:"0.0.1"),
.package(url: "https://github.com/torusresearch/fetch-node-details-swift", from:"0.1.0"),
.package(url: "https://github.com/PromiseKit/Foundation.git", from: "3.0.0"),
.package(url: "https://github.com/IBM-Swift/BlueECC.git", from: "1.2.4"),
],
Expand Down
Binary file removed Shortcut
Binary file not shown.
243 changes: 216 additions & 27 deletions Sources/TorusUtils/Extensions/TorusUtils+extension.swift

Large diffs are not rendered by default.

50 changes: 39 additions & 11 deletions Sources/TorusUtils/Helpers/Error.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,50 @@ public enum TorusError: Error{
case decodingError
case commitmentRequestFailed
case decryptionFailed
case thresholdError
case promiseFulfilled
case timeout
case unableToDerive
case interpolationFailed
case nodesUnavailable
case empty
}

extension TorusError: CustomDebugStringConvertible{
public var debugDescription: String{
switch self {
case .apiRequestFailed:
return "API request failed or No response from the node"
case .decodingError:
return "JSON Decoding error"
case .errInResponse(let str):
return "API response error \(str)"
case .decryptionFailed:
return "Decryption Failed"
case .commitmentRequestFailed:
return "commitment request failed"
case .apiRequestFailed:
return "API request failed or No response from the node"
case .decodingError:
return "JSON Decoding error"
case .errInResponse(let str):
return "API response error \(str)"
case .decryptionFailed:
return "Decryption Failed"
case .commitmentRequestFailed:
return "commitment request failed"
case .thresholdError:
return "Threshold error"
case .promiseFulfilled:
return "Promise fulfilled"
case .timeout:
return "Timeout"
case .unableToDerive:
return "could not derive private key"
case .interpolationFailed:
return "lagrange interpolation failed"
case .nodesUnavailable:
return "One or more nodes unavailable"
case .empty:
return ""
}

}

static public func == (lhs: TorusError, rhs: TorusError) -> Bool {
guard type(of: lhs) == type(of: rhs) else { return false }
let error1 = lhs as NSError
let error2 = rhs as NSError
return error1.debugDescription == error2.debugDescription && "\(lhs)" == "\(rhs)"
}
}

90 changes: 39 additions & 51 deletions Sources/TorusUtils/TorusUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import CryptoSwift
import BigInt
import BestLogger

@available(iOS 9.0, *)
public class TorusUtils{
static let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN|SECP256K1_CONTEXT_VERIFY))
let nodePubKeys: Array<TorusNodePub>
Expand Down Expand Up @@ -66,7 +65,11 @@ public class TorusUtils{

}.catch{err in
self.logger.error("getPublicAddress: err: ", err)
seal.reject(err)
if let tmpError = err as? TorusError{
if(tmpError == TorusError.nodesUnavailable){
seal.reject(TorusError.nodesUnavailable)
}
}
}

return tempPromise
Expand All @@ -90,63 +93,48 @@ public class TorusUtils{
let hashedOnce = idToken.sha3(.keccak256)
// let tokenCommitment = hashedOnce.sha3(.keccak256)
let timestamp = String(Int(Date().timeIntervalSince1970))

var nodeReturnedPubKeyX:String = ""
var nodeReturnedPubKeyY:String = ""
var publicAddress: String = ""
var lookupPubkeyX: String = ""
var lookupPubkeyY: String = ""

self.logger.debug("RetrieveShares: ", privateKey?.toHexString() as Any, publicKeyHex as Any, pubKeyX as Any, pubKeyY as Any, hashedOnce)

return Promise<[String:String]>{ seal in

getPublicAddress(endpoints: endpoints, torusNodePubs: nodePubKeys, verifier: verifierIdentifier, verifierId: verifierId, isExtended: true).then{ data -> Promise<[[String:String]]> in
publicAddress = data["address"] ?? ""
return self.commitmentRequest(endpoints: endpoints, verifier: verifierIdentifier, pubKeyX: pubKeyX!, pubKeyY: pubKeyY!, timestamp: timestamp, tokenCommitment: hashedOnce)
}.then{ data -> Promise<[Int:[String:String]]> in
self.logger.info("retrieveShares: data after commitment request", data)
return self.retrieveIndividualNodeShare(endpoints: endpoints, extraParams: extraParams, verifier: verifierIdentifier, tokenCommitment: idToken, nodeSignatures: data, verifierId: verifierId)
}.then{ data -> Promise<[Int:String]> in
self.logger.trace("retrieveShares: data after retrieveIndividualNodeShare", data)
if let temp = data.first{
nodeReturnedPubKeyX = temp.value["pubKeyX"]!.addLeading0sForLength64()
nodeReturnedPubKeyY = temp.value["pubKeyY"]!.addLeading0sForLength64()
}
return self.decryptIndividualShares(shares: data, privateKey: privateKey!.toHexString())
}.then{ data -> Promise<String> in
self.logger.trace("retrieveShares: data after decryptIndividualShares", data)
return self.lagrangeInterpolation(shares: data)
}.then{ data -> Promise<(String, String, String)> in

// Split key in 2 parts, X and Y
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()
self.logger.trace("retrieveShares: private key rebuild", data, pubKeyX as Any, pubKeyY as Any)

// Verify
if( pubKeyX == nodeReturnedPubKeyX && pubKeyY == nodeReturnedPubKeyY) {
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 tempNewKey = BigInt(nonce) + BigInt(key, radix: 16)!
let newKey = tempNewKey.modulus(BigInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", radix: 16)!)
self.logger.info(newKey)
seal.fulfill(["privateKey": BigUInt(newKey).serialize().suffix(64).toHexString(), "publicAddress": publicAddress])
}
seal.fulfill(["privateKey":key, "publicAddress": publicAddress])

}.catch{ err in
self.logger.error("retrieveShares: err: ",err)
seal.reject(err)
let (tempPromise, seal) = Promise<[String:String]>.pending()

// Reject if not resolved in 30 seconds
after(.seconds(300)).done {
seal.reject(TorusError.timeout)
}

getPublicAddress(endpoints: endpoints, torusNodePubs: nodePubKeys, verifier: verifierIdentifier, verifierId: verifierId, isExtended: true).then{ data -> Promise<[[String:String]]> in
publicAddress = data["address"] ?? ""
lookupPubkeyX = data["pub_key_X"]!.addLeading0sForLength64()
lookupPubkeyY = data["pub_key_Y"]!.addLeading0sForLength64()
return self.commitmentRequest(endpoints: endpoints, verifier: verifierIdentifier, pubKeyX: pubKeyX!, pubKeyY: pubKeyY!, timestamp: timestamp, tokenCommitment: hashedOnce)
}.then{ data -> Promise<(String, String, String)> in
self.logger.info("retrieveShares: data after commitment request", data)
return self.retrieveDecryptAndReconstruct(endpoints: endpoints, extraParams: extraParams, verifier: verifierIdentifier, tokenCommitment: idToken, nodeSignatures: data, verifierId: verifierId, lookupPubkeyX: lookupPubkeyX, lookupPubkeyY: lookupPubkeyY, privateKey: (privateKey?.toHexString())!)
}.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 tempNewKey = BigInt(nonce) + BigInt(key, radix: 16)!
let newKey = tempNewKey.modulus(BigInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", radix: 16)!)
self.logger.info(newKey)
seal.fulfill(["privateKey": BigUInt(newKey).serialize().suffix(64).toHexString(), "publicAddress": publicAddress])
}
seal.fulfill(["privateKey":key, "publicAddress": publicAddress])

}.catch{ err in
self.logger.error("retrieveShares: err: ",err)
seal.reject(err)
}.finally {
if(tempPromise.isPending){
seal.reject(TorusError.unableToDerive)
}
}

return tempPromise
}

}
2 changes: 1 addition & 1 deletion Example/TestApplication/Podfile → cocoapods/Podfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ target 'TestApplication' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# pod 'Torus-fetchNodeDetails', :git=>'https://github.com/torusresearch/fetch-node-details-swift'
pod "Torus-utils", :path => '../../'
pod "Torus-utils", :path => '../'
# Pods for TestApplication


Expand Down
14 changes: 7 additions & 7 deletions Example/TestApplication/Podfile.lock → cocoapods/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ PODS:
- PromiseKit/CorePromise
- secp256k1.c (0.1.2)
- Starscream (3.1.1)
- Torus-fetchNodeDetails (0.1.0):
- Torus-fetchNodeDetails (0.0.20):
- BestLogger (~> 0.0.1)
- web3swift (~> 2.3.0)
- Torus-utils (0.1.1):
- BestLogger (~> 0.0.1)
- PromiseKit/Foundation (~> 6.0)
- Torus-fetchNodeDetails (~> 0.1.0)
- Torus-fetchNodeDetails (~> 0.0.1)
- web3swift (2.3.0):
- BigInt (~> 4.0)
- CryptoSwift (~> 1.0.0)
Expand All @@ -28,7 +28,7 @@ PODS:
- Starscream (~> 3.1.0)

DEPENDENCIES:
- Torus-utils (from `../../`)
- Torus-utils (from `../`)

SPEC REPOS:
trunk:
Expand All @@ -43,7 +43,7 @@ SPEC REPOS:

EXTERNAL SOURCES:
Torus-utils:
:path: "../../"
:path: "../"

SPEC CHECKSUMS:
BestLogger: 70475db073dfab3ec1ba9b58b0bb78126b068eee
Expand All @@ -52,10 +52,10 @@ SPEC CHECKSUMS:
PromiseKit: 9616b0afef31eae56ab9ce044c8ec2b8612a15cd
secp256k1.c: db47b726585d80f027423682eb369729e61b3b20
Starscream: 4bb2f9942274833f7b4d296a55504dcfc7edb7b0
Torus-fetchNodeDetails: d04806e1befa430d920cd538ad1aef2ca5332622
Torus-utils: c1df3ec0720c7bb9c1666395b588bed603ffd1f8
Torus-fetchNodeDetails: 567d0c73c1b318c8811abcef0b2f31cfdcd5a4a4
Torus-utils: cd8ac44a3397d1dac0132ca414478f9dd55a8825
web3swift: 0f097eafe1d08f478694b882581b85a01afb6633

PODFILE CHECKSUM: 06ce0718f4492f3ce5d67cd4472ed09aacc8b3e0
PODFILE CHECKSUM: de6dc705fbcaee4478a78e83fe706aec34cc08c1

COCOAPODS: 1.10.1
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 920b909

Please sign in to comment.