Skip to content

Commit

Permalink
- Add tests
Browse files Browse the repository at this point in the history
- Support aggregate login
  • Loading branch information
chaitanyapotti committed Nov 24, 2020
1 parent 30d68ac commit ecb855d
Show file tree
Hide file tree
Showing 10 changed files with 223 additions and 39 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,5 @@ nb-configuration.xml
## OS X
##############################
.DS_Store

*.pem
5 changes: 4 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ plugins {
apply plugin: 'maven'

group 'org.torusresearch'
version '1.0.3'
version '1.0.4'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
mavenCentral()
jcenter()
maven { url 'https://jitpack.io' }
}

Expand All @@ -23,6 +24,8 @@ dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.2'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.6.2'
testImplementation 'org.slf4j:slf4j-simple:1.7.30'
testImplementation 'com.auth0:java-jwt:3.11.0'
testImplementation 'net.andreinc.mockneat:mockneat:0.4.1'
}

test {
Expand Down
7 changes: 6 additions & 1 deletion src/main/java/org/torusresearch/torusutils/TorusUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,12 @@ public CompletableFuture<RetrieveSharesResponse> retrieveShares(String[] endpoin
Gson gson = new Gson();
nodeSignatures[l] = gson.fromJson(nodeSigs.get(l), NodeSignature.class);
}
ShareRequestItem[] shareRequestItems = {new ShareRequestItem((String) verifierParams.get("verifier_id"), idToken, nodeSignatures, verifier)};
verifierParams.put("idtoken", idToken);
verifierParams.put("nodesignatures", nodeSignatures);
verifierParams.put("verifieridentifier", verifier);
List<HashMap<String, Object>> shareRequestItems = new ArrayList<HashMap<String, Object>>() {{
add(verifierParams);
}};
for (String endpoint : endpoints) {
String req = APIUtils.generateJsonRPCObject("ShareRequest", new ShareRequestParams(shareRequestItems));
promiseArrRequests.add(APIUtils.post(endpoint, req, false));
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
package org.torusresearch.torusutils.apis;

import java.util.HashMap;
import java.util.List;

public class ShareRequestParams {
private final ShareRequestItem[] item;
private final String encrypted;
private final List<HashMap<String, Object>> item;

public ShareRequestParams(ShareRequestItem[] _item) {
item = _item;
public ShareRequestParams(List<HashMap<String, Object>> _item) {
encrypted = "yes";
item = _item;
}

public ShareRequestItem[] getItem() {
public List<HashMap<String, Object>> getItem() {
return item;
}
}
75 changes: 73 additions & 2 deletions src/test/java/org/torusresearch/torusutilstest/TorusUtilsTest.java
Original file line number Diff line number Diff line change
@@ -1,35 +1,63 @@
package org.torusresearch.torusutilstest;

import com.auth0.jwt.algorithms.Algorithm;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.torusresearch.fetchnodedetails.FetchNodeDetails;
import org.torusresearch.fetchnodedetails.types.EthereumNetwork;
import org.torusresearch.fetchnodedetails.types.NodeDetails;
import org.torusresearch.torusutils.TorusUtils;
import org.torusresearch.torusutils.types.RetrieveSharesResponse;
import org.torusresearch.torusutils.types.TorusException;
import org.torusresearch.torusutils.types.TorusPublicKey;
import org.torusresearch.torusutils.types.VerifierArgs;
import org.torusresearch.torusutilstest.utils.JwtUtils;
import org.torusresearch.torusutilstest.utils.PemUtils;
import org.torusresearch.torusutilstest.utils.VerifyParams;
import org.web3j.crypto.Hash;
import sun.security.rsa.RSAPrivateCrtKeyImpl;

import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class TorusUtilsTest {

static NodeDetails nodeDetails;

static Algorithm algorithmRs;

static String TORUS_TEST_VERIFIER = "torus-test-health";
static String TORUS_TEST_AGGREGATE_VERIFIER = "torus-test-aggregate-health";

static String TORUS_TEST_EMAIL = "[email protected]";

@BeforeAll
static void setup() throws ExecutionException, InterruptedException {
static void setup() throws ExecutionException, InterruptedException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
System.out.println("Setup Starting");
FetchNodeDetails fetchNodeDetails = new FetchNodeDetails(EthereumNetwork.ROPSTEN, "0x4023d2a0D330bF11426B12C6144Cfb96B7fa6183");
nodeDetails = fetchNodeDetails.getNodeDetails().get();
RSAPrivateKey privateKey = (RSAPrivateKey) PemUtils.readPrivateKeyFromFile("src/test/java/org/torusresearch/torusutilstest/keys/key.pem", "RSA");
RSAPrivateCrtKeyImpl rsaPrivateKey = (RSAPrivateCrtKeyImpl) privateKey;
RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent()));
algorithmRs = Algorithm.RSA256(publicKey, privateKey);
}

@DisplayName("Gets Public Address")
@Test
public void shouldGetPublicAddress() throws ExecutionException, InterruptedException {
VerifierArgs args = new VerifierArgs("google-lrc", "[email protected]");
VerifierArgs args = new VerifierArgs("google-lrc", TORUS_TEST_EMAIL);
System.out.println("Starting test");
Arrays.stream(nodeDetails.getTorusNodeEndpoints()).forEach(System.out::println);
Arrays.stream(nodeDetails.getTorusNodePub()).forEach(System.out::println);
Expand All @@ -38,4 +66,47 @@ public void shouldGetPublicAddress() throws ExecutionException, InterruptedExcep
System.out.println(publicAddress.getAddress());
assertEquals("0xFf5aDad69F4e97AF4D4567e7C333C12df6836a70", publicAddress.getAddress());
}

@DisplayName("Key Assign test")
@Test
public void shouldKeyAssign() throws ExecutionException, InterruptedException {
TorusUtils torusUtils = new TorusUtils();
String email = JwtUtils.getRandomEmail();
TorusPublicKey publicAddress = torusUtils.getPublicAddress(nodeDetails.getTorusNodeEndpoints(),
nodeDetails.getTorusNodePub(), new VerifierArgs("google-lrc", email)).get();
System.out.println(email + " -> " + publicAddress.getAddress());
assertNotNull(publicAddress.getAddress());
}

@DisplayName("Login test")
@Test
public void shouldLogin() throws ExecutionException, InterruptedException, TorusException {
TorusUtils torusUtils = new TorusUtils();
RetrieveSharesResponse retrieveSharesResponse = torusUtils.retrieveShares(nodeDetails.getTorusNodeEndpoints(),
nodeDetails.getTorusIndexes(), TORUS_TEST_VERIFIER, new HashMap<String, Object>() {{
put("verifier_id", TORUS_TEST_EMAIL);
}},
JwtUtils.generateIdToken(TORUS_TEST_EMAIL, algorithmRs)).get();
System.out.println(retrieveSharesResponse.getEthAddress());
assertNotNull(retrieveSharesResponse.getEthAddress());
}

@DisplayName("Aggregate Login test")
@Test
public void shouldAggregateLogin() throws ExecutionException, InterruptedException, TorusException {
TorusUtils torusUtils = new TorusUtils();
String idToken = JwtUtils.generateIdToken(TORUS_TEST_EMAIL, algorithmRs);
String hashedIdToken = Hash.sha3String(idToken).substring(2);
RetrieveSharesResponse retrieveSharesResponse = torusUtils.retrieveShares(nodeDetails.getTorusNodeEndpoints(),
nodeDetails.getTorusIndexes(), TORUS_TEST_AGGREGATE_VERIFIER, new HashMap<String, Object>() {{
put("verify_params", new VerifyParams[]{
new VerifyParams(idToken, TORUS_TEST_EMAIL)
});
put("sub_verifier_ids", new String[]{TORUS_TEST_VERIFIER});
put("verifier_id", TORUS_TEST_EMAIL);
}},
hashedIdToken).get();
System.out.println(retrieveSharesResponse.getEthAddress());
assertNotNull(retrieveSharesResponse.getEthAddress());
}
}
12 changes: 12 additions & 0 deletions src/test/java/org/torusresearch/torusutilstest/keys/public.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"keys": [
{
"e": "AQAB",
"n": "0XsoG_YYxQS5jgMINADHZp8vQl18KofHRBdwAGHRE8tiXIJZ0MP63hwmb46BdRQWOj3nQpgZoBFhx7Fy4rXISLJ5-NwI2BL800sj0qB7YRyUpf0hHY22iik-O9m-Ow29EV1NjPjgHDvVRDbAA9-fThp15rQh6sltGIBrZXFoQx-n4yXf6BaXd49j-VyVTPjm7Is-wn7X3wFi4YAoNo3fnPcVG3KE2kjBe6Fkgh1HDkWki9ZHnFkajlicIj855xdfDCbmiaRcfECIOSRsbaheishlI9UH7QyzYU7QW9pKnOBJMDWQQSHdMCgWhaW77GG3T7FoOO86xLrTPC1yQLxajw",
"kty": "RSA",
"kid": "-EHdyh3PZCayljxdS3W7gq79oQUHHSei7E8kv_4dNRU",
"alg": "RS256",
"use": "sig"
}
]
}
29 changes: 29 additions & 0 deletions src/test/java/org/torusresearch/torusutilstest/utils/JwtUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package org.torusresearch.torusutilstest.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import net.andreinc.mockneat.MockNeat;

import java.util.Date;

public class JwtUtils {
public static String generateIdToken(String email, Algorithm alg) {
return JWT.create()
.withSubject("email|" + email.split("@")[0])
.withAudience("torus-key-test")
.withExpiresAt(new Date(System.currentTimeMillis() + 3600 * 1000))
.withIssuedAt(new Date())
.withIssuer("torus-key-test")
.withClaim("email", email)
.withClaim("nickname", email.split("@")[0])
.withClaim("name", email)
.withClaim("picture", "")
.withClaim("email_verified", true)
.sign(alg);
}

public static String getRandomEmail() {
MockNeat mock = MockNeat.threadLocal();
return mock.emails().val();
}
}
71 changes: 71 additions & 0 deletions src/test/java/org/torusresearch/torusutilstest/utils/PemUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package org.torusresearch.torusutilstest.utils;

import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class PemUtils {
private static byte[] parsePEMFile(File pemFile) throws IOException {
if (!pemFile.isFile() || !pemFile.exists()) {
throw new FileNotFoundException(String.format("The file '%s' doesn't exist.", pemFile.getAbsolutePath()));
}
PemReader reader = new PemReader(new FileReader(pemFile));
PemObject pemObject = reader.readPemObject();
byte[] content = pemObject.getContent();
reader.close();
return content;
}

private static PublicKey getPublicKey(byte[] keyBytes, String algorithm) {
PublicKey publicKey = null;
try {
KeyFactory kf = KeyFactory.getInstance(algorithm);
EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
publicKey = kf.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the public key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the public key");
}

return publicKey;
}

private static PrivateKey getPrivateKey(byte[] keyBytes, String algorithm) {
PrivateKey privateKey = null;
try {
KeyFactory kf = KeyFactory.getInstance(algorithm);
EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
privateKey = kf.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
System.out.println("Could not reconstruct the private key, the given algorithm could not be found.");
} catch (InvalidKeySpecException e) {
System.out.println("Could not reconstruct the private key");
}

return privateKey;
}

public static PublicKey readPublicKeyFromFile(String filepath, String algorithm) throws IOException {
byte[] bytes = PemUtils.parsePEMFile(new File(filepath));
return PemUtils.getPublicKey(bytes, algorithm);
}

public static PrivateKey readPrivateKeyFromFile(String filepath, String algorithm) throws IOException {
byte[] bytes = PemUtils.parsePEMFile(new File(filepath));
return PemUtils.getPrivateKey(bytes, algorithm);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package org.torusresearch.torusutilstest.utils;

public class VerifyParams {
private final String idtoken;
private final String verifier_id;

public VerifyParams(String idtoken, String verifier_id) {
this.idtoken = idtoken;
this.verifier_id = verifier_id;
}

public String getVerifier_id() {
return verifier_id;
}

public String getIdtoken() {
return idtoken;
}
}

0 comments on commit ecb855d

Please sign in to comment.